Skip to content

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

FEATURE: Let plugins register persistable admin dashboard section settings (#41843)

Osama Sayegh2eb203bb4a0c
diff --git a/app/services/admin_dashboard_section_configuration.rb b/app/services/admin_dashboard_section_configuration.rb
index 51f3897c249..7a6fba372d3 100644
--- a/app/services/admin_dashboard_section_configuration.rb
+++ b/app/services/admin_dashboard_section_configuration.rb
@@ -85,7 +85,21 @@ class AdminDashboardSectionConfiguration
end
def self.setting_definition(section_id, key)
- SUPPORTED_SETTINGS.dig(section_id.to_s, key.to_s)
+ section_id = section_id.to_s
+ key = key.to_s
+
+ SUPPORTED_SETTINGS.dig(section_id, key) || plugin_setting_definition(section_id, key)
+ end
+
+ def self.plugin_setting_definition(section_id, key)
+ entry = DiscoursePluginRegistry.admin_dashboard_sections.find { |s| s[:id] == section_id }
+ return nil if entry.nil?
+ return nil if entry[:enabled].respond_to?(:call) && !entry[:enabled].call
+
+ klass = entry[:settings]&.dig(key)
+ return nil if klass.nil?
+
+ { permit: klass.permit, validate: ->(attrs) { klass.validate(attrs) } }
end
def self.update_setting(section_id:, key:, attrs:)
@@ -97,8 +111,11 @@ class AdminDashboardSectionConfiguration
value = definition[:validate].call(attrs.to_h.with_indifferent_access)
- record = AdminDashboardSection.find_by(section_id:)
- raise Discourse::InvalidParameters.new(:section_id) if record.nil?
+ record =
+ AdminDashboardSection.find_or_create_by!(section_id:) do |r|
+ r.position = (AdminDashboardSection.maximum(:position) || -1) + 1
+ r.visible = true
+ end
record.with_lock { record.update!(settings: record.settings.to_h.deep_merge(key => value)) }
diff --git a/lib/plugin/instance.rb b/lib/plugin/instance.rb
index c5420c6e246..0d430800686 100644
--- a/lib/plugin/instance.rb
+++ b/lib/plugin/instance.rb
@@ -1275,11 +1275,24 @@ class Plugin::Instance
# Return false to omit the section (and hide it from the configure menu)
# without disabling the plugin entirely — e.g. only when relevant data
# exists.
+ # @param settings [Hash<String, Class>] optional map of setting key to a
+ # class responding to `.permit` (a strong-params shape) and `.validate`
+ # (raises `Discourse::InvalidParameters` or returns the sanitized value to
+ # persist). Lets the section's own filter selections be saved via
+ # `PUT /admin/dashboard/sections/:id/settings/:key`, the same mechanism
+ # core sections use. A setting inherits the section's own `enabled` gate
+ # rather than declaring its own.
# @yield [start_date:, end_date:, current_user:] block returning the section's
# data hash, run inside the dashboard's parallel section loader.
- def register_admin_dashboard_section(id:, enabled: nil, &loader)
+ def register_admin_dashboard_section(id:, enabled: nil, settings: nil, &loader)
+ settings&.each_value do |setting|
+ if !setting.respond_to?(:permit) || !setting.respond_to?(:validate)
+ raise ArgumentError, "#{setting} must respond to .permit and .validate"
+ end
+ end
+
DiscoursePluginRegistry.register_admin_dashboard_section(
- { id: id.to_s, enabled: enabled, loader: loader },
+ { id: id.to_s, enabled: enabled, settings: settings&.transform_keys(&:to_s), loader: loader },
self,
)
end
diff --git a/plugins/discourse-solved/admin/assets/javascripts/admin/components/dashboard/support.gjs b/plugins/discourse-solved/admin/assets/javascripts/admin/components/dashboard/support.gjs
index 9fa5841a3db..e11b63baa43 100644
--- a/plugins/discourse-solved/admin/assets/javascripts/admin/components/dashboard/support.gjs
+++ b/plugins/discourse-solved/admin/assets/javascripts/admin/components/dashboard/support.gjs
@@ -1,22 +1,24 @@
import Component from "@glimmer/component";
import { tracked } from "@glimmer/tracking";
-import { concat } from "@ember/helper";
+import { concat, hash } from "@ember/helper";
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 DashboardSection from "discourse/admin/components/dashboard/section";
import DTooltip from "discourse/float-kit/components/d-tooltip";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import { durationTiny } from "discourse/lib/formatter";
-import ComboBox from "discourse/select-kit/components/combo-box";
+import Category from "discourse/models/category";
+import CategorySelector from "discourse/select-kit/components/category-selector";
import { eq } from "discourse/truth-helpers";
import { i18n } from "discourse-i18n";
import SupportResponseTime from "./support/response-time";
import SupportTopicOutcomes from "./support/topic-outcomes";
import SupportWhosAnswering from "./support/whos-answering";
-const ALL_CATEGORIES = "all";
+const MAX_CATEGORIES = 10;
const DeltaPill = <template>
{{#if @delta.hasDelta}}
@@ -31,10 +33,22 @@ const DeltaPill = <template>
</template>;
export default class SupportSection extends Component {
- @tracked categoryId = ALL_CATEGORIES;
+ @service currentUser;
+ @service toasts;
+
+ @tracked selectedCategories = [];
@tracked override = null;
@tracked loading = false;
+ constructor() {
+ super(...arguments);
+
+ this.selectedCategories = (this.args.data?.category_ids ?? [])
+ .map((id) => Category.findById(id))
+ .filter(Boolean);
+ this.appliedCategoryIds = this.selectedCategories.map((c) => c.id);
+ }
+
// The active payload: the category-filtered refetch when present, otherwise
// the data supplied by the main dashboard request.
get data() {
@@ -47,14 +61,11 @@ export default class SupportSection extends Component {
return (this.args.data?.category_options?.length ?? 0) > 1;
}
- get categoryOptions() {
- return [
- {
- id: ALL_CATEGORIES,
- name: i18n("admin.dashboard.sections.support.filter.all_categories"),
- },
- ...(this.args.data?.category_options ?? []),
- ];
+ get blockedCategories() {
+ const allowedIds = new Set(
+ (this.args.data?.category_options ?? []).map((option) => option.id)
+ );
+ return Category.list().filter((category) => !allowedIds.has(category.id));
}
get headline() {
@@ -161,14 +172,50 @@ export default class SupportSection extends Component {
}
@action
- onCategoryChange(categoryId) {
- this.categoryId = categoryId;
+ onCategoriesChange(categories) {
+ this.selectedCategories = categories;
+ }
+
+ @action
+ onClose() {
+ const ids = this.selectedCategories.map((c) => c.id);
+ const unchanged =
+ ids.length === this.appliedCategoryIds.length &&
+ ids.every((id) => this.appliedCategoryIds.includes(id));
+
+ if (unchanged) {
+ return;
+ }
+
+ this.appliedCategoryIds = ids;
this.refetch();
+ this.#persistSelection();
+ }
+
+ #persistSelection() {
+ if (!this.currentUser?.admin) {
+ return;
+ }
+
+ ajax("/admin/dashboard/sections/support/settings/categories.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.support.save_error"),
+ },
+ });
+ });
}
@action
onPeriodChange() {
- if (this.categoryId === ALL_CATEGORIES) {
+ if (this.selectedCategories.length === 0) {
this.override = null;
} else {
this.refetch();
@@ -185,8 +232,9 @@ export default class SupportSection extends Component {
if (this.args.endDate) {
data.end_date = moment(this.args.endDate).format("YYYY-MM-DD");
}
- if (this.categoryId !== ALL_CATEGORIES) {
- data.category_id = this.categoryId;
+ const ids = this.selectedCategories.map((c) => c.id);
+ if (ids.length > 0) {
+ data.category_ids = ids.join(",");
}
try {
@@ -292,12 +340,12 @@ export default class SupportSection extends Component {
{{#if this.showFilter}}
<div class="db-support__filter">
- <ComboBox
- @content={{this.categoryOptions}}
- @value={{this.categoryId}}
- @onChange={{this.onCategoryChange}}
- @valueProperty="id"
- @nameProperty="name"
+ <CategorySelector
+ @categories={{this.selectedCategories}}
+ @blockedCategories={{this.blockedCategories}}
+ @onChange={{this.onCategoriesChange}}
+ @onClose={{this.onClose}}
+ @options={{hash maximum=MAX_CATEGORIES none="category.all"}}
/>
</div>
{{/if}}
diff --git a/plugins/discourse-solved/app/controllers/discourse_solved/admin_dashboard_support_controller.rb b/plugins/discourse-solved/app/controllers/discourse_solved/admin_dashboard_support_controller.rb
index c9fa48e0a09..c67eaa33ea2 100644
--- a/plugins/discourse-solved/app/controllers/discourse_solved/admin_dashboard_support_controller.rb
+++ b/plugins/discourse-solved/app/controllers/discourse_solved/admin_dashboard_support_controller.rb
@@ -9,7 +9,7 @@ class DiscourseSolved::AdminDashboardSupportController < ::Admin::StaffControlle
start_date: params[:start_date],
end_date: params[:end_date],
current_user: current_user,
- category_id: params[:category_id],
+ category_ids: params[:category_ids],
)
end
end
diff --git a/plugins/discourse-solved/assets/stylesheets/admin/dashboard-support.scss b/plugins/discourse-solved/assets/stylesheets/admin/dashboard-support.scss
index 0c9b31c5859..bdabceca599 100644
--- a/plugins/discourse-solved/assets/stylesheets/admin/dashboard-support.scss
+++ b/plugins/discourse-solved/assets/stylesheets/admin/dashboard-support.scss
@@ -5,7 +5,7 @@
$db-bar-height: var(--space-2);
.db-support__filter {
- .select-kit.combo-box {
+ .select-kit.multi-select.category-selector {
max-width: 220px;
}
}
diff --git a/plugins/discourse-solved/config/locales/client.en.yml b/plugins/discourse-solved/config/locales/client.en.yml
index 30acb476fcb..cbde8167289 100644
--- a/plugins/discourse-solved/config/locales/client.en.yml
+++ b/plugins/discourse-solved/config/locales/client.en.yml
@@ -14,8 +14,7 @@ en:
support:
title: "Support"
fetch_error: "Support data couldn't be loaded."
- filter:
- all_categories: "All categories"
+ save_error: "Couldn't save your selection for next time."
headline:
healthy:
title: "The community is solving its own problems."
diff --git a/plugins/discourse-solved/lib/discourse_solved/admin_dashboard_support.rb b/plugins/discourse-solved/lib/discourse_solved/admin_dashboard_support.rb
index a2da225fb19..cad29e6f1e2 100644
--- a/plugins/discourse-solved/lib/discourse_solved/admin_dashboard_support.rb
+++ b/plugins/discourse-solved/lib/discourse_solved/admin_dashboard_support.rb
@@ -4,7 +4,7 @@ module DiscourseSolved
# Builds the data for the "Support" section of the redesigned admin dashboard
# (registered via `register_admin_dashboard_section`). All metrics are scoped
# to "support categories" — categories where accepted answers are enabled — for
- # the selected period, optionally narrowed to a single category.
+ # the selected period, optionally narrowed to one or more categories.
class AdminDashboardSupport
DEFAULT_RANGE_DAYS = 30
AVAILABILITY_CACHE_KEY = "solved_admin_dashboard_support_available"
@@ -29,20 +29,21 @@ module DiscourseSolved
end
end
- def self.build(start_date:, end_date:, current_user: nil, category_id: nil)
+ def self.build(start_date:, end_date:, current_user: nil, category_ids: nil)
new(
start_date: start_date,
end_date: end_date,
current_user: current_user,
- category_id: category_id,
+ category_ids: category_ids,
).build
end
- def initialize(start_date:, end_date:, current_user: nil, category_id: nil)
+ def initialize(start_date:, end_date:, current_user: nil, category_ids: nil)
@start_date = parse_date(start_date) || DEFAULT_RANGE_DAYS.days.ago.beginning_of_day
@end_date = parse_date(end_date)&.end_of_day || Time.zone.now.end_of_day
@current_user = current_user
- @category_id = category_id.presence&.to_i
+ @requested_category_ids =
+ Array(category_ids.is_a?(String) ? category_ids.split(",") : category_ids).map(&:to_i)
end
def build
@@ -51,6 +52,7 @@ module DiscourseSolved
.fetch(cache_key, expires_in: DATA_CACHE_DURATION) do
{
category_options: category_options,
+ category_ids: selected_category_ids,
kpis: build_kpis,
headline: build_headline,
topic_outcomes: topic_outcomes,
@@ -62,7 +64,7 @@ module DiscourseSolved
private
- attr_reader :start_date, :end_date, :current_user, :category_id
+ attr_reader :start_date, :end_date, :current_user, :requested_category_ids
def parse_date(value)
return nil if value.blank?
@@ -98,12 +100,12 @@ module DiscourseSolved
@all_support_category_ids ||= support_categories.pluck(:id)
end
- def selected_category_id
- category_id if category_id && all_support_category_ids.include?(category_id)
+ def selected_category_ids
+ requested_category_ids & all_support_category_ids
end
def effective_category_ids
- selected_category_id ? [selected_category_id] : all_support_category_ids
+ selected_category_ids.presence || all_support_category_ids
end
def category_options
@@ -115,7 +117,7 @@ module DiscourseSolved
Digest::SHA1.hexdigest(
[
all_support_category_ids.sort,
- selected_category_id,
+ selected_category_ids.sort,
start_date.to_i,
end_date.to_i,
].to_json,
@@ -147,7 +149,9 @@ module DiscourseSolved
def resolution_report_query
query = { start_date: start_date.to_date.iso8601, end_date: end_date.to_date.iso8601 }
- query[:filters] = { category: selected_category_id } if selected_category_id
+ if selected_category_ids.present?
+ query[:filters] = { category_ids: selected_category_ids.join(",") }
+ end
query
end
diff --git a/plugins/discourse-solved/lib/discourse_solved/admin_dashboard_support_categories_setting.rb b/plugins/discourse-solved/lib/discourse_solved/admin_dashboard_support_categories_setting.rb
new file mode 100644
index 00000000000..2ba6f3a75fd
--- /dev/null
+++ b/plugins/discourse-solved/lib/discourse_solved/admin_dashboard_support_categories_setting.rb
@@ -0,0 +1,30 @@
+# frozen_string_literal: true
+
+module DiscourseSolved
+ # Persistable setting for the "Support" admin dashboard section's category
+ # filter, registered via `register_admin_dashboard_section`'s `settings:`.
+ class AdminDashboardSupportCategoriesSetting
+ MAX_CATEGORY_IDS = 10
+
+ def self.permit
+ [{ category_ids: [] }]
+ end
+
+ def self.validate(attrs)
+ 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 > MAX_CATEGORY_IDS || 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
+ end
+end
diff --git a/plugins/discourse-solved/plugin.rb b/plugins/discourse-solved/plugin.rb
index 9b02914eba9..a99cf3e0c26 100644
--- a/plugins/discourse-solved/plugin.rb
+++ b/plugins/discourse-solved/plugin.rb
@@ -23,6 +23,7 @@ module ::DiscourseSolved
EMPTY_BOX_ON_UNSOLVED_CUSTOM_FIELD = "empty_box_on_unsolved"
SHARED_ISSUES_ENABLED_CUSTOM_FIELD = "enable_shared_issues"
MAX_AUTO_CLOSE_HOURS = 20.years.to_i / 1.hour.to_i
+ MAX_ACCEPTED_SOLUTIONS_CATEGORY_IDS = 50
def self.accept_answer!(post, acting_user, topic: nil)
DiscourseSolved::AcceptAnswer.call(params: { post_id: post.id }, guardian: acting_user.guardian)
@@ -165,17 +166,17 @@ after_initialize do
.joins(:topic)
.where.not(topics: { archetype: Archetype.private_message })
- category_id, include_subcategories = report.add_category_filter
- if category_id
- if include_subcategories
- accepted_solutions =
- accepted_solutions.where(
- "topics.category_id IN (?)",
- Category.subcategory_ids(category_id),
- )
- else
- accepted_solutions = accepted_solutions.where("topics.category_id = ?", category_id)
- end
+ raw_ids = report.filters[:category_ids]
+ if raw_ids.present?
+ parsed_ids = Array(raw_ids.is_a?(String) ? raw_ids.split(",") : raw_ids).map(&:to_i)
+ requested_ids =
+ Category
+ .where(id: parsed_ids)
+ .limit(DiscourseSolved::MAX_ACCEPTED_SOLUTIONS_CATEGORY_IDS)
+ .pluck(:id)
+ report.add_filter("category_ids", type: "category_list", default: requested_ids)
+
+ accepted_solutions = accepted_solutions.where("topics.category_id" => requested_ids)
end
accepted_solutions
@@ -228,11 +229,19 @@ after_initialize do
register_admin_dashboard_section(
id: "support",
enabled: -> { DiscourseSolved::AdminDashboardSupport.available? },
+ settings: {
+ "categories" => DiscourseSolved::AdminDashboardSupportCategoriesSetting,
+ },
) do |start_date:, end_date:, current_user:|
DiscourseSolved::AdminDashboardSupport.build(
start_date: start_date,
end_date: end_date,
current_user: current_user,
+ category_ids:
+ AdminDashboardSectionConfiguration.settings_for("support").dig(
+ "categories",
+ "category_ids",
+ ),
)
end
diff --git a/plugins/discourse-solved/spec/fabricators/support_category_fabricator.rb b/plugins/discourse-solved/spec/fabricators/support_category_fabricator.rb
new file mode 100644
index 00000000000..d05951d6b65
--- /dev/null
+++ b/plugins/discourse-solved/spec/fabricators/support_category_fabricator.rb
@@ -0,0 +1,7 @@
+# frozen_string_literal: true
+Fabricator(:support_category, from: :category) do
+ after_create do |category|
+ category.custom_fields[DiscourseSolved::ENABLE_ACCEPTED_ANSWERS_CUSTOM_FIELD] = "true"
+ category.save!
+ end
+end
diff --git a/plugins/discourse-solved/spec/lib/discourse_solved/admin_dashboard_support_spec.rb b/plugins/discourse-solved/spec/lib/discourse_solved/admin_dashboard_support_spec.rb
index 734cc3aed47..8f67c7a2a3e 100644
--- a/plugins/discourse-solved/spec/lib/discourse_solved/admin_dashboard_support_spec.rb
+++ b/plugins/discourse-solved/spec/lib/discourse_solved/admin_dashboard_support_spec.rb
@@ -1,17 +1,13 @@
# frozen_string_literal: true
RSpec.describe DiscourseSolved::AdminDashboardSupport do
- fab!(:support_category, :category)
+ fab!(:support_category)
fab!(:admin)
fab!(:author) { Fabricate(:user, trust_level: TrustLevel[1]) }
fab!(:staff_user, :moderator)
fab!(:member_user) { Fabricate(:user, trust_level: TrustLevel[2]) }
- before do
- SiteSetting.solved_enabled = true
- support_category.custom_fields[DiscourseSolved::ENABLE_ACCEPTED_ANSWERS_CUSTOM_FIELD] = "true"
- support_category.save!
- end
+ before { SiteSetting.solved_enabled = true }
def build(**opts)
described_class.build(
@@ -137,12 +133,12 @@ RSpec.describe DiscourseSolved::AdminDashboardSupport do
expect(build[:kpis][:resolution_rate][:value]).to eq(33.3)
end
- it "carries the selected category into the report drill-down query" do
+ it "carries the selected categories into the report drill-down query" do
solved_topic
- query = build(category_id: support_category.id)[:kpis][:resolution_rate][:report_query]
+ query = build(category_ids: [support_category.id])[:kpis][:resolution_rate][:report_query]
- expect(query[:filters]).to eq(category: support_category.id)
+ expect(query[:filters]).to eq(category_ids: support_category.id.to_s)
end
it "omits the category filter when viewing all categories" do
@@ -204,21 +200,32 @@ RSpec.describe DiscourseSolved::AdminDashboardSupport do
end
describe "category scoping" do
- fab!(:second_support_category, :category)
-
- before do
- second_support_category.custom_fields[
- DiscourseSolved::ENABLE_ACCEPTED_ANSWERS_CUSTOM_FIELD
- ] = "true"
- second_support_category.save!
- end
+ fab!(:second_support_category, :support_category)
it "limits metrics to a single category when one is selected" do
solved_topic(category: support_category)
solved_topic(category: second_support_category)
expect(build[:topic_outcomes][:resolved]).to eq(2)
- expect(build(category_id: support_category.id)[:topic_outcomes][:resolved]).to eq(1)
+ expect(build(category_ids: [support_category.id])[:topic_outcomes][:resolved]).to eq(1)
+ end
+
+ it "limits metrics to the union of multiple selected categories" do
+ solved_topic(category: support_category)
+ solved_topic(category: second_support_category)
+
+ result = build(category_ids: [support_category.id, second_support_category.id])
+
+ expect(result[:topic_outcomes][:resolved]).to eq(2)
+ end
+
+ it "strips ids that don't correspond to a support category" do
+ solved_topic(category: support_category)
+ other_category = Fabricate(:category)
+
+ result = build(category_ids: [support_category.id, other_category.id])
+
+ expect(result[:category_ids]).to contain_exactly(support_category.id)
end
it "lists both support categories as filter options" do
diff --git a/plugins/discourse-solved/spec/reports/accepted_solutions_spec.rb b/plugins/discourse-solved/spec/reports/accepted_solutions_spec.rb
new file mode 100644
index 00000000000..987c9b7ab2e
--- /dev/null
+++ b/plugins/discourse-solved/spec/reports/accepted_solutions_spec.rb
@@ -0,0 +1,78 @@
+# frozen_string_literal: true
+
+describe "accepted_solutions report" do # rubocop:disable RSpec/DescribeClass
+ fab!(:author, :user)
+
+ def solved_topic_in(category)
+ topic = Fabricate(:topic, category: category, user: author, created_at: 1.day.ago)
+ answer = Fabricate(:post, topic: topic, user: author, created_at: 1.day.ago)
+ Fabricate(:solved_topic, topic: topic, answer_post: answer, created_at: 1.day.ago)
+ topic
+ end
+
+ def build(filters: {})
+ Report.find("accepted_solutions", start_date: 2.days.ago, end_date: Time.current, filters:)
+ end
+
+ it "counts accepted solutions across all categories when no filter is given" do
+ solved_topic_in(Fabricate(:category))
+ solved_topic_in(Fabricate(:category))
+
+ expect(build.total).to eq(2)
+ end
+
+ it "filters by category when the category_ids filter is provided" do
+ target_category = Fabricate(:category)
+ other_category = Fabricate(:category)
+ solved_topic_in(target_category)
+ solved_topic_in(other_category)
+
+ report = build(filters: { category_ids: [target_category.id] })
+
+ expect(report.total).to eq(1)
+ end
+
+ it "filters by the union of multiple categories" do
+ first_category = Fabricate(:category)
+ second_category = Fabricate(:category)
+ other_category = Fabricate(:category)
+ solved_topic_in(first_category)
+ solved_topic_in(second_category)
+ solved_topic_in(other_category)
+
+ report = build(filters: { category_ids: [first_category.id, second_category.id] })
+
+ expect(report.total).to eq(2)
+ end
+
+ it "accepts a comma-separated string of category ids" do
+ first_category = Fabricate(:category)
+ second_category = Fabricate(:category)
+ other_category = Fabricate(:category)
+ solved_topic_in(first_category)
+ solved_topic_in(second_category)
+ solved_topic_in(other_category)
+
+ report = build(filters: { category_ids: "#{first_category.id},#{second_category.id}" })
+
+ expect(report.total).to eq(2)
+ end
+
+ it "strips category ids that don't correspond to an existing category" do
+ target_category = Fabricate(:category)
+ solved_topic_in(target_category)
+ nonexistent_id = Category.unscoped.maximum(:id).to_i + 1
+
+ report = build(filters: { category_ids: [target_category.id, nonexistent_id] })
+
+ expect(report.total).to eq(1)
+ end
+
+ it "returns zero when a requested filter resolves to no valid ids" do
+ solved_topic_in(Fabricate(:category))
+
+ report = build(filters: { category_ids: "foo,bar" })
+
+ expect(report.total).to eq(0)
+ end
+end
diff --git a/plugins/discourse-solved/spec/requests/discourse_solved/admin_dashboard_support_controller_spec.rb b/plugins/discourse-solved/spec/requests/discourse_solved/admin_dashboard_support_controller_spec.rb
index 0603bccd157..60f0a977eca 100644
--- a/plugins/discourse-solved/spec/requests/discourse_solved/admin_dashboard_support_controller_spec.rb
+++ b/plugins/discourse-solved/spec/requests/discourse_solved/admin_dashboard_support_controller_spec.rb
@@ -25,6 +25,7 @@ RSpec.describe DiscourseSolved::AdminDashboardSupportController do
"whos_answering",
"response_time_distribution",
"category_options",
+ "category_ids",
)
end
@@ -33,10 +34,31 @@ RSpec.describe DiscourseSolved::AdminDashboardSupportController do
get "/admin/plugins/solved/dashboard-support.json",
params: {
- category_id: support_category.id,
+ category_ids: [support_category.id],
}
expect(response.status).to eq(200)
+ expect(response.parsed_body["category_ids"]).to eq([support_category.id])
+ end
+
+ it "accepts multiple categories in a comma-separated string" do
+ sign_in(admin)
+ other_support_category = Fabricate(:category)
+ other_support_category.custom_fields[
+ DiscourseSolved::ENABLE_ACCEPTED_ANSWERS_CUSTOM_FIELD
+ ] = "true"
+ other_support_category.save!
+
+ get "/admin/plugins/solved/dashboard-support.json",
+ params: {
+ category_ids: "#{support_category.id},#{other_support_category.id}",
+ }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["category_ids"]).to contain_exactly(
+ support_category.id,
+ other_support_category.id,
+ )
end
it "is available to moderators" do
diff --git a/plugins/discourse-solved/spec/system/admin_dashboard_support_section_spec.rb b/plugins/discourse-solved/spec/system/admin_dashboard_support_section_spec.rb
index 706a25be001..dd99270b479 100644
--- a/plugins/discourse-solved/spec/system/admin_dashboard_support_section_spec.rb
+++ b/plugins/discourse-solved/spec/system/admin_dashboard_support_section_spec.rb
@@ -2,7 +2,7 @@
describe "Admin dashboard Support section" do
fab!(:admin)
- fab!(:support_category, :category)
+ fab!(:support_category)
fab!(:author) { Fabricate(:user, trust_level: TrustLevel[1]) }
fab!(:staff_replier, :moderator)
fab!(:member_replier) { Fabricate(:user, trust_level: TrustLevel[2]) }
@@ -13,8 +13,6 @@ describe "Admin dashboard Support section" do
before do
SiteSetting.solved_enabled = true
SiteSetting.dashboard_improvements = true
- support_category.custom_fields[DiscourseSolved::ENABLE_ACCEPTED_ANSWERS_CUSTOM_FIELD] = "true"
- support_category.save!
# Resolved: staff makes the first reply, which is accepted as the solution.
resolved = Fabricate(:topic, category: support_category, user: author)
@@ -54,4 +52,39 @@ describe "Admin dashboard Support section" do
# With a single support category there is nothing to filter between.
expect(support).to have_no_category_filter
end
+
+ context "with multiple support categories" do
+ fab!(:other_support_category, :support_category)
+ fab!(:moderator)
+
+ it "saves an admin's category selection when the picker closes, and persists it across a refresh" do
+ dashboard.visit
+ expect(support).to have_category_filter
+ expect(support).to have_no_selected_category(support_category)
+
+ support.select_category(support_category)
+ support.close_category_filter
+
+ support.expand_category_filter
+ expect(support).to have_selected_category(support_category)
+
+ dashboard.visit
+
+ support.expand_category_filter
+ expect(support).to have_selected_category(support_category)
+ end
+
+ it "does not persist a moderator's category selection" do
+ sign_in(moderator)
+
+ dashboard.visit
+ support.select_category(support_category)
+ support.close_category_filter
+
+ dashboard.visit
+ support.expand_category_filter
+
+ expect(support).to have_no_selected_category(support_category)
+ end
+ end
end
diff --git a/plugins/discourse-solved/spec/system/page_objects/components/admin_dashboard_support.rb b/plugins/discourse-solved/spec/system/page_objects/components/admin_dashboard_support.rb
index 20bc48b26ca..d0e30fb6fcd 100644
--- a/plugins/discourse-solved/spec/system/page_objects/components/admin_dashboard_support.rb
+++ b/plugins/discourse-solved/spec/system/page_objects/components/admin_dashboard_support.rb
@@ -42,6 +42,36 @@ module PageObjects
def has_no_category_filter?
has_no_css?("#{SELECTOR} .db-support__filter")
end
+
+ CATEGORY_FILTER = "#{SELECTOR} .db-support__filter .category-selector"
+
+ def category_filter
+ PageObjects::Components::SelectKit.new(CATEGORY_FILTER)
+ end
+
+ def expand_category_filter
+ category_filter.expand
+ self
+ end
+
+ def select_category(category)
+ expand_category_filter
+ category_filter.select_row_by_value(category.id)
+ self
+ end
+
+ def close_category_filter
+ category_filter.collapse
+ self
+ end
+
+ def has_selected_category?(category)
+ has_css?("#{CATEGORY_FILTER} .selected-choice[data-value='#{category.id}']")
+ end
+
+ def has_no_selected_category?(category)
+ has_no_css?("#{CATEGORY_FILTER} .selected-choice[data-value='#{category.id}']")
+ end
end
end
end
diff --git a/plugins/discourse-solved/test/javascripts/integration/support-test.gjs b/plugins/discourse-solved/test/javascripts/integration/support-test.gjs
index 1cb696be016..98e5ee74af6 100644
--- a/plugins/discourse-solved/test/javascripts/integration/support-test.gjs
+++ b/plugins/discourse-solved/test/javascripts/integration/support-test.gjs
@@ -1,6 +1,7 @@
import { render } from "@ember/test-helpers";
import { module, test } from "qunit";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import selectKit from "discourse/tests/helpers/select-kit-helper";
import SupportSection from "discourse/plugins/discourse-solved/admin/components/dashboard/support";
function buildData(overrides = {}) {
@@ -245,5 +246,28 @@ module("Integration | Component | Dashboard | Support", function (hooks) {
);
assert.dom(".db-support__filter").exists("shown with multiple categories");
+ assert.dom(".category-selector").exists();
+ });
+
+ test("prefills the selector with the persisted category selection", async function (assert) {
+ const data = buildData({
+ category_options: [
+ { id: 1, name: "Support" },
+ { id: 2, name: "Help" },
+ ],
+ category_ids: [1, 2],
+ });
+
+ await render(
+ <template>
+ <SupportSection
+ @data={{data}}
+ @startDate={{startDate}}
+ @endDate={{endDate}}
+ />
+ </template>
+ );
+
+ assert.strictEqual(selectKit(".category-selector").header().value(), "1,2");
});
});
diff --git a/spec/lib/plugin/instance_spec.rb b/spec/lib/plugin/instance_spec.rb
index 1aee6d32bc1..e194adcc37d 100644
--- a/spec/lib/plugin/instance_spec.rb
+++ b/spec/lib/plugin/instance_spec.rb
@@ -1176,6 +1176,82 @@ TEXT
end
end
+ describe "#register_admin_dashboard_section" do
+ let(:plugin) { Plugin::Instance.new }
+
+ after do
+ DiscoursePluginRegistry._raw_admin_dashboard_sections.reject! do |entry|
+ entry[:value][:id] == "fake_section"
+ end
+ end
+
+ it "registers a section without settings" do
+ plugin.register_admin_dashboard_section(id: "fake_section") { {} }
+
+ entry = DiscoursePluginRegistry.admin_dashboard_sections.find { |s| s[:id] == "fake_section" }
+ expect(entry[:settings]).to be_nil
+ end
+
+ it "registers a section with settings, normalizing keys to strings" do
+ setting_class =
+ Class.new do
+ def self.permit
+ [:category_id]
+ end
+
+ def self.validate(attrs)
+ attrs
+ end
+ end
+
+ plugin.register_admin_dashboard_section(
+ id: "fake_section",
+ settings: {
+ category_id: setting_class,
+ },
+ ) { {} }
+
+ entry = DiscoursePluginRegistry.admin_dashboard_sections.find { |s| s[:id] == "fake_section" }
+ expect(entry[:settings]).to eq({ "category_id" => setting_class })
+ end
+
+ it "raises when a setting class doesn't respond to .validate" do
+ setting_class =
+ Class.new do
+ def self.permit
+ []
+ end
+ end
+
+ expect {
+ plugin.register_admin_dashboard_section(
+ id: "fake_section",
+ settings: {
+ "x" => setting_class,
+ },
+ ) { {} }
+ }.to raise_error(ArgumentError, /must respond to .permit and .validate/)
+ end
+
+ it "raises when a setting class doesn't respond to .permit" do
+ setting_class =
+ Class.new do
+ def self.validate(attrs)
+ attrs
+ end
+ end
+
+ expect {
+ plugin.register_admin_dashboard_section(
+ id: "fake_section",
+ settings: {
+ "x" => setting_class,
+ },
+ ) { {} }
+ }.to raise_error(ArgumentError, /must respond to .permit and .validate/)
+ end
+ end
+
describe "#register_modifier" do
let(:plugin) { Plugin::Instance.new }
diff --git a/spec/requests/admin/dashboard_controller_spec.rb b/spec/requests/admin/dashboard_controller_spec.rb
index 87d20756ae8..f2008b4e58c 100644
--- a/spec/requests/admin/dashboard_controller_spec.rb
+++ b/spec/requests/admin/dashboard_controller_spec.rb
@@ -760,6 +760,12 @@ RSpec.describe Admin::DashboardController do
before { SiteSetting.dashboard_improvements = true }
+ after do
+ DiscoursePluginRegistry._raw_admin_dashboard_sections.reject! do |entry|
+ entry[:value][:id] == "support"
+ end
+ end
+
it "persists the selected category ids and returns 204 for admins" do
sign_in(admin)
@@ -881,6 +887,38 @@ RSpec.describe Admin::DashboardController do
expect(response.status).to eq(404)
end
+
+ it "resolves a plugin-registered setting's permit shape and persists it" do
+ plugin = Plugin::Instance.new
+ fake_setting =
+ Class.new do
+ def self.permit
+ [:category_id]
+ end
+
+ def self.validate(attrs)
+ { "category_id" => attrs[:category_id].to_i }
+ end
+ end
+ plugin.register_admin_dashboard_section(
+ id: "support",
+ enabled: -> { true },
+ settings: {
+ "category_id" => fake_setting,
+ },
+ ) { {} }
+ sign_in(admin)
+
+ put "/admin/dashboard/sections/support/settings/category_id.json",
+ params: {
+ category_id: category.id,
+ }
+
+ expect(response.status).to eq(204)
+ expect(AdminDashboardSectionConfiguration.settings_for("support")).to eq(
+ { "category_id" => { "category_id" => category.id } },
+ )
+ end
end
describe "#problems" do
diff --git a/spec/services/admin_dashboard_section_configuration_spec.rb b/spec/services/admin_dashboard_section_configuration_spec.rb
index b525d1bb6c4..56009dbad69 100644
--- a/spec/services/admin_dashboard_section_configuration_spec.rb
+++ b/spec/services/admin_dashboard_section_configuration_spec.rb
@@ -214,6 +214,63 @@ describe AdminDashboardSectionConfiguration do
end
end
+ describe ".setting_definition" do
+ let(:plugin) { Plugin::Instance.new }
+
+ let(:fake_setting) do
+ Class.new do
+ def self.permit
+ [:category_id]
+ end
+
+ def self.validate(attrs)
+ id = attrs[:category_id]
+ raise Discourse::InvalidParameters.new(:category_id) if id.blank?
+ { "category_id" => id.to_i }
+ end
+ end
+ end
+
+ def register_support_section(enabled: true)
+ plugin.register_admin_dashboard_section(
+ id: "support",
+ enabled: -> { enabled },
+ settings: {
+ "category_id" => fake_setting,
+ },
+ ) { {} }
+ end
+
+ after do
+ DiscoursePluginRegistry._raw_admin_dashboard_sections.reject! do |entry|
+ entry[:value][:id] == "support"
+ end
+ end
+
+ it "resolves a setting definition registered on an enabled plugin section" do
+ register_support_section
+
+ definition = described_class.setting_definition("support", "category_id")
+
+ expect(definition[:permit]).to eq([:category_id])
+ expect(definition[:validate].call(category_id: category.id)).to eq(
+ { "category_id" => category.id },
+ )
+ end
+
+ it "returns nil for an unregistered setting key on a plugin section" do
+ register_support_section
+
+ expect(described_class.setting_definition("support", "not_a_real_setting")).to be_nil
+ end
+
+ it "returns nil when the section's enabled proc is false" do
+ register_support_section(enabled: false)
+
+ expect(described_class.setting_definition("support", "category_id")).to be_nil
+ end
+ end
+
describe ".update_setting" do
it "persists a valid selection under its key" do
described_class.update_setting(
@@ -373,15 +430,79 @@ describe AdminDashboardSectionConfiguration do
{ "activity_by_category" => { "category_ids" => [category.id, category_2.id] } },
)
end
+
+ let(:plugin) { Plugin::Instance.new }
+
+ let(:fake_setting) do
+ Class.new do
+ def self.permit
+ [:category_id]
+ end
+
+ def self.validate(attrs)
+ id = attrs[:category_id]
+ raise Discourse::InvalidParameters.new(:category_id) if id.blank?
+ { "category_id" => id.to_i }
+ end
+ end
+ end
+
+ def register_support_section(enabled: true)
+ plugin.register_admin_dashboard_section(
+ id: "support",
+ enabled: -> { enabled },
+ settings: {
+ "category_id" => fake_setting,
+ },
+ ) { {} }
+ end
+
+ after do
+ DiscoursePluginRegistry._raw_admin_dashboard_sections.reject! do |entry|
+ entry[:value][:id] == "support"
+ end
+ end
+
+ it "creates a section row on the fly when persisting a plugin section's setting for the first time" do
+ register_support_section
+ expect(AdminDashboardSection.find_by(section_id: "support")).to be_nil
+
+ described_class.update_setting(
+ section_id: "support",
+ key: "category_id",
+ attrs: {
+ category_id: category.id,
+ },
+ )
+
+ record = AdminDashboardSection.find_by(section_id: "support")
+ expect(record.settings).to eq({ "category_id" => { "category_id" => category.id } })
+ end
+
+ it "still raises for an unregistered setting key on a plugin section" do
+ register_support_section
+
+ expect {
+ described_class.update_setting(section_id: "support", key: "not_a_real_setting", attrs: {})
+ }.to raise_error(Discourse::InvalidParameters)
+ end
end
describe "plugin sections" do
- def stub_plugin_sections(sections)
- DiscoursePluginRegistry.stubs(:admin_dashboard_sections).returns(sections)
+ let(:plugin) { Plugin::Instance.new }
+
+ def register_support_section(enabled:)
+ plugin.register_admin_dashboard_section(id: "support", enabled: enabled) { {} }
+ end
+
+ after do
+ DiscoursePluginRegistry._raw_admin_dashboard_sections.reject! do |entry|
+ entry[:value][:id] == "support"
+ end
end
it "includes an enabled plugin section, visible by default" do
- stub_plugin_sections([{ id: "support", enabled: -> { true }, loader: -> {} }])
+ register_support_section(enabled: -> { true })
expect(described_class.all_known_section_ids).to include("support")
expect(described_class.sections).to include({ id: "support", visible: true })
@@ -389,7 +510,7 @@ describe AdminDashboardSectionConfiguration do
end
it "hides a plugin section whose enabled proc returns false" do
- stub_plugin_sections([{ id: "support", enabled: -> { false }, loader: -> {} }])
+ register_support_section(enabled: -> { false })
expect(described_class.all_known_section_ids).not_to include("support")
expect(described_class.sections.map { |s| s[:id] }).not_to include("support")
@@ -397,13 +518,13 @@ describe AdminDashboardSectionConfiguration do
end
it "includes a plugin section that has no enabled proc" do
- stub_plugin_sections([{ id: "support", enabled: nil, loader: -> {} }])
+ register_support_section(enabled: nil)
expect(described_class.all_known_section_ids).to include("support")
end
it "drops a disabled plugin section id passed to update" do
- stub_plugin_sections([{ id: "support", enabled: -> { false }, loader: -> {} }])
+ register_support_section(enabled: -> { false })
described_class.update([{ id: "support", visible: true }], actor: admin)