Skip to content

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

FEATURE: Add a Support section to the admin dashboard0 (#41359)

Krzysztof Kotlarek1101080b10db
diff --git a/app/assets/stylesheets/admin/admin_dashboard.scss b/app/assets/stylesheets/admin/admin_dashboard.scss
index 7bfae57fb74..d52b50f51d9 100644
--- a/app/assets/stylesheets/admin/admin_dashboard.scss
+++ b/app/assets/stylesheets/admin/admin_dashboard.scss
@@ -1,4 +1,7 @@
@use "lib/viewport";
+
+$db-bar-height: var(--space-2);
+
@import "admin/dashboard/engagement";
@import "admin/dashboard/highlights";
@import "admin/dashboard/reports";
@@ -380,7 +383,10 @@
}
@include viewport.until(sm) {
- border-bottom: 1px solid var(--content-border-color);
+ &:not(:last-child) {
+ border-right: 0;
+ border-bottom: 1px solid var(--content-border-color);
+ }
}
}
diff --git a/app/assets/stylesheets/admin/dashboard/engagement.scss b/app/assets/stylesheets/admin/dashboard/engagement.scss
index 08e13a18abb..8a9d500ddfd 100644
--- a/app/assets/stylesheets/admin/dashboard/engagement.scss
+++ b/app/assets/stylesheets/admin/dashboard/engagement.scss
@@ -158,8 +158,8 @@
}
&__bar-track {
- height: 10px;
- border-radius: 4px;
+ height: $db-bar-height;
+ border-radius: 1em;
background: var(--primary-low);
}
@@ -264,8 +264,8 @@
}
&__bar {
- height: 10px;
- border-radius: 4px;
+ height: $db-bar-height;
+ border-radius: 5px;
flex: 0 0 auto;
background: var(--success);
diff --git a/app/services/admin_dashboard_section_configuration.rb b/app/services/admin_dashboard_section_configuration.rb
index 70b902cc34d..dda46e99571 100644
--- a/app/services/admin_dashboard_section_configuration.rb
+++ b/app/services/admin_dashboard_section_configuration.rb
@@ -3,12 +3,29 @@
class AdminDashboardSectionConfiguration
KNOWN_SECTIONS = %w[highlights reports traffic engagement search].freeze
+ def self.available_plugin_section_ids
+ DiscoursePluginRegistry
+ .admin_dashboard_sections
+ .select { |s| !s[:enabled].respond_to?(:call) || s[:enabled].call }
+ .map { |s| s[:id] }
+ end
+
+ def self.all_known_section_ids
+ KNOWN_SECTIONS + available_plugin_section_ids
+ end
+
def self.sections
- AdminDashboardSection
- .where(section_id: KNOWN_SECTIONS)
- .order(:position)
- .pluck(:section_id, :visible)
- .map { |id, visible| { id:, visible: } }
+ known = all_known_section_ids
+
+ persisted =
+ AdminDashboardSection
+ .where(section_id: known)
+ .order(:position)
+ .pluck(:section_id, :visible)
+ .map { |id, visible| { id:, visible: } }
+ not_persisted = (known - persisted.map { |s| s[:id] }).map { |id| { id:, visible: true } }
+
+ persisted + not_persisted
end
def self.visible_section_ids
@@ -21,7 +38,7 @@ class AdminDashboardSectionConfiguration
.filter_map do |s|
attrs = (s.respond_to?(:to_unsafe_h) ? s.to_unsafe_h : s.to_h).symbolize_keys
id = attrs[:id].to_s
- next if KNOWN_SECTIONS.exclude?(id)
+ next if all_known_section_ids.exclude?(id)
{ id:, visible: ActiveModel::Type::Boolean.new.cast(attrs[:visible]) }
end
.uniq { |s| s[:id] }
diff --git a/app/services/admin_dashboard_section_loader.rb b/app/services/admin_dashboard_section_loader.rb
index f407bb7c385..91f7aca1a0c 100644
--- a/app/services/admin_dashboard_section_loader.rb
+++ b/app/services/admin_dashboard_section_loader.rb
@@ -1,8 +1,6 @@
# frozen_string_literal: true
class AdminDashboardSectionLoader
- POOL_SIZE = AdminDashboardSectionConfiguration::KNOWN_SECTIONS.size
-
def self.build(section_ids:, current_user:, start_date:, end_date:)
new(
section_ids: section_ids,
@@ -12,9 +10,18 @@ class AdminDashboardSectionLoader
).build
end
+ def self.pool_size
+ desired =
+ AdminDashboardSectionConfiguration::KNOWN_SECTIONS.size +
+ DiscoursePluginRegistry.admin_dashboard_sections.size
+
+ available = [ActiveRecord::Base.connection_pool.size - 1, 1].max
+ [desired, available].min
+ end
+
def self.thread_pool
@thread_pool ||=
- Scheduler::ThreadPool.new(min_threads: 0, max_threads: POOL_SIZE, idle_time: 30)
+ Scheduler::ThreadPool.new(min_threads: 0, max_threads: pool_size, idle_time: 30)
end
def initialize(section_ids:, current_user:, start_date:, end_date:)
@@ -67,6 +74,9 @@ class AdminDashboardSectionLoader
AdminDashboard::Reports::Section.build(guardian: user.guardian)
when "search"
AdminDashboardSearch.build(start_date: start_date, end_date: end_date)
+ else
+ section = DiscoursePluginRegistry.admin_dashboard_sections.find { |s| s[:id] == id }
+ section&.dig(:loader)&.call(start_date: start_date, end_date: end_date, current_user: user)
end
end
end
diff --git a/frontend/discourse/admin/components/redesigned-admin-dashboard.gjs b/frontend/discourse/admin/components/redesigned-admin-dashboard.gjs
index 473dd045a5f..06e4cb6cbaa 100644
--- a/frontend/discourse/admin/components/redesigned-admin-dashboard.gjs
+++ b/frontend/discourse/admin/components/redesigned-admin-dashboard.gjs
@@ -10,6 +10,7 @@ import DashboardSearch from "discourse/admin/components/dashboard/search";
import DashboardSiteAdvice from "discourse/admin/components/dashboard/site-advice";
import DashboardSkeleton from "discourse/admin/components/dashboard/skeleton";
import DashboardTraffic from "discourse/admin/components/dashboard/traffic";
+import { lookupAdminDashboardSection } from "discourse/admin/lib/admin-dashboard-sections";
import PluginOutlet from "discourse/components/plugin-outlet";
import DMenu from "discourse/float-kit/components/d-menu";
import { eq } from "discourse/truth-helpers";
@@ -17,6 +18,8 @@ import DBreadcrumbsItem from "discourse/ui-kit/d-breadcrumbs-item";
import DPageHeader from "discourse/ui-kit/d-page-header";
import { i18n } from "discourse-i18n";
+const sectionComponentFor = (id) => lookupAdminDashboardSection(id);
+
export default class RedesignedAdminDashboard extends Component {
@service currentUser;
@@ -134,6 +137,21 @@ export default class RedesignedAdminDashboard extends Component {
@startDate={{@loadedSections.startDate}}
@endDate={{@loadedSections.endDate}}
/>
+ {{else}}
+ {{#let (sectionComponentFor section.id) as |PluginSection|}}
+ {{#if PluginSection}}
+ <PluginSection
+ class={{concat "--" section.id}}
+ data-section-id={{section.id}}
+ @data={{section.data}}
+ @period={{@loadedSections.period}}
+ @loading={{@loadingSections}}
+ @fetchError={{@sectionsFetchError}}
+ @startDate={{@loadedSections.startDate}}
+ @endDate={{@loadedSections.endDate}}
+ />
+ {{/if}}
+ {{/let}}
{{/if}}
{{/each}}
diff --git a/frontend/discourse/admin/lib/admin-dashboard-sections.js b/frontend/discourse/admin/lib/admin-dashboard-sections.js
new file mode 100644
index 00000000000..9537f15fa0c
--- /dev/null
+++ b/frontend/discourse/admin/lib/admin-dashboard-sections.js
@@ -0,0 +1,18 @@
+// Registry for plugin-provided sections in the redesigned admin dashboard.
+// Plugins register a component for a section id via
+// `api.registerAdminDashboardSection`; the section id must match the one
+// registered server-side with `register_admin_dashboard_section`.
+
+const sections = new Map();
+
+export function registerAdminDashboardSection(id, ComponentClass) {
+ sections.set(id, ComponentClass);
+}
+
+export function lookupAdminDashboardSection(id) {
+ return sections.get(id);
+}
+
+export function resetAdminDashboardSections() {
+ sections.clear();
+}
diff --git a/frontend/discourse/app/lib/plugin-api.gjs b/frontend/discourse/app/lib/plugin-api.gjs
index 4c6c047dbce..8c05006c389 100644
--- a/frontend/discourse/app/lib/plugin-api.gjs
+++ b/frontend/discourse/app/lib/plugin-api.gjs
@@ -1,6 +1,7 @@
/* eslint-disable ember/no-jquery */
import $ from "jquery";
import { registerAdminDashboardReportRenderer } from "discourse/admin/lib/admin-dashboard-report-renderers";
+import { registerAdminDashboardSection } from "discourse/admin/lib/admin-dashboard-sections";
import { _renderBlocks } from "discourse/blocks/block-outlet";
import { addAboutPageActivity } from "discourse/components/about-page";
import { addBulkDropdownButton } from "discourse/components/bulk-select-topics-dropdown";
@@ -2995,6 +2996,43 @@ class _PluginApi {
registerAdminDashboardReportRenderer(source, componentClass);
}
+ /**
+ * Registers a component to render a whole section in the redesigned admin
+ * dashboard (gated by the `dashboard_improvements` upcoming change). Pair it
+ * with the server-side `register_admin_dashboard_section`: the `id` here must
+ * match the one registered there, and the loader block registered there
+ * produces the `@data` this component receives.
+ *
+ * The component is rendered once for each visible section with a matching id.
+ * The render site also stamps a `--<id>` class and a `data-section-id="<id>"`
+ * attribute on it, so forward `...attributes` onto your root element (wrapping
+ * the shared `<DashboardSection>` component does this for you).
+ *
+ * The component receives these args:
+ * - `@data` {Object} — the section payload: the hash returned by the
+ * server-side loader block passed to `register_admin_dashboard_section`.
+ * - `@startDate` {Date} — start of the selected dashboard period.
+ * - `@endDate` {Date} — end of the selected dashboard period.
+ * - `@fetchError` {boolean} — true when the dashboard sections request failed.
+ * - `@period` {string} — the selected period preset (e.g. "monthly"), or
+ * "custom" for a custom range.
+ * - `@loading` {boolean} — true while the dashboard is (re)loading sections.
+ * Provided for convenience; a section that refetches on its own (as Solved's
+ * "support" section does) may track its own loading state instead.
+ *
+ * ```
+ * import MySection from "discourse/plugins/my-plugin/admin/components/dashboard/my-section";
+ *
+ * api.registerAdminDashboardSection("my_section", MySection);
+ * ```
+ *
+ * @param {string} id - The section id, matching the server-side registration.
+ * @param {Component} componentClass - A Glimmer component for the section.
+ */
+ registerAdminDashboardSection(id, componentClass) {
+ registerAdminDashboardSection(id, componentClass);
+ }
+
/**
* Registers a new tab in the user menu. This API method expects a callback
* that should return a class inheriting from the class (UserMenuTab) that's
diff --git a/frontend/discourse/tests/helpers/qunit-helpers.js b/frontend/discourse/tests/helpers/qunit-helpers.js
index 837b82453c1..d6a5552f972 100644
--- a/frontend/discourse/tests/helpers/qunit-helpers.js
+++ b/frontend/discourse/tests/helpers/qunit-helpers.js
@@ -15,6 +15,7 @@ import { resetCache as resetOneboxCache } from "pretty-text/oneboxer";
import QUnit, { module, test } from "qunit";
import sinon from "sinon";
import { resetAdminDashboardReportRenderers } from "discourse/admin/lib/admin-dashboard-report-renderers";
+import { resetAdminDashboardSections } from "discourse/admin/lib/admin-dashboard-sections";
import { _resetOutletLayoutsForTesting } from "discourse/blocks/block-outlet";
import { clearAboutPageActivities } from "discourse/components/about-page";
import { resetCardClickListenerSelector } from "discourse/components/card-contents-base";
@@ -212,6 +213,7 @@ export function testCleanup(container, app) {
resetMobile();
resetAdditionalReportModes();
resetAdminDashboardReportRenderers();
+ resetAdminDashboardSections();
resetExtraClasses();
clearOutletCache();
clearHTMLCache();
diff --git a/frontend/discourse/tests/unit/lib/admin-dashboard-sections-test.js b/frontend/discourse/tests/unit/lib/admin-dashboard-sections-test.js
new file mode 100644
index 00000000000..e832e2ae9db
--- /dev/null
+++ b/frontend/discourse/tests/unit/lib/admin-dashboard-sections-test.js
@@ -0,0 +1,33 @@
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import {
+ lookupAdminDashboardSection,
+ registerAdminDashboardSection,
+ resetAdminDashboardSections,
+} from "discourse/admin/lib/admin-dashboard-sections";
+
+module("Unit | Lib | admin-dashboard-sections", function (hooks) {
+ setupTest(hooks);
+
+ hooks.afterEach(function () {
+ resetAdminDashboardSections();
+ });
+
+ test("looks up a component registered for a section id", function (assert) {
+ class SupportSection {}
+ registerAdminDashboardSection("support", SupportSection);
+
+ assert.strictEqual(lookupAdminDashboardSection("support"), SupportSection);
+ });
+
+ test("returns undefined for an unregistered id", function (assert) {
+ assert.strictEqual(lookupAdminDashboardSection("missing"), undefined);
+ });
+
+ test("reset clears registrations", function (assert) {
+ registerAdminDashboardSection("support", class {});
+ resetAdminDashboardSections();
+
+ assert.strictEqual(lookupAdminDashboardSection("support"), undefined);
+ });
+});
diff --git a/lib/discourse_plugin_registry.rb b/lib/discourse_plugin_registry.rb
index 84e1f5c3c70..74148dcf2a1 100644
--- a/lib/discourse_plugin_registry.rb
+++ b/lib/discourse_plugin_registry.rb
@@ -124,6 +124,7 @@ class DiscoursePluginRegistry
define_filtered_register :stats
define_filtered_register :admin_dashboard_highlight_kpis
+ define_filtered_register :admin_dashboard_sections
define_filtered_register :bookmarkables
define_filtered_register :admin_dashboard_report_sources
diff --git a/lib/plugin/instance.rb b/lib/plugin/instance.rb
index 856f17fbcd5..20a402777ca 100644
--- a/lib/plugin/instance.rb
+++ b/lib/plugin/instance.rb
@@ -1250,6 +1250,25 @@ class Plugin::Instance
)
end
+ # Registers a whole section in the redesigned admin dashboard (gated by the
+ # dashboard_improvements upcoming change). The matching client-side section
+ # component must be registered via the JS `api.registerAdminDashboardSection`.
+ #
+ # @param id [String] unique section id. Matched against the persisted
+ # configuration and the client-side component registry.
+ # @param enabled [Proc] optional gate evaluated when assembling the dashboard.
+ # 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.
+ # @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)
+ DiscoursePluginRegistry.register_admin_dashboard_section(
+ { id: id.to_s, enabled: enabled, loader: loader },
+ self,
+ )
+ end
+
##
# Used to register data sources for HashtagAutocompleteService to look
# up results based on a #hashtag string.
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
new file mode 100644
index 00000000000..9fa5841a3db
--- /dev/null
+++ b/plugins/discourse-solved/admin/assets/javascripts/admin/components/dashboard/support.gjs
@@ -0,0 +1,328 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { concat } from "@ember/helper";
+import { action } from "@ember/object";
+import didUpdate from "@ember/render-modifiers/modifiers/did-update";
+import { LinkTo } from "@ember/routing";
+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 { 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 DeltaPill = <template>
+ {{#if @delta.hasDelta}}
+ {{#if (eq @delta.deltaClass "--neutral")}}
+ <span class="db-pill">{{i18n "admin.dashboard.stable"}}</span>
+ {{else}}
+ <div class={{concat "db-delta " @delta.deltaClass}}>
+ {{@delta.deltaText}}
+ </div>
+ {{/if}}
+ {{/if}}
+</template>;
+
+export default class SupportSection extends Component {
+ @tracked categoryId = ALL_CATEGORIES;
+ @tracked override = null;
+ @tracked loading = false;
+
+ // The active payload: the category-filtered refetch when present, otherwise
+ // the data supplied by the main dashboard request.
+ get data() {
+ return this.override ?? this.args.data;
+ }
+
+ // The filter is driven by the unfiltered payload so it stays put while a
+ // category is selected; it's hidden when there's at most one support category.
+ get showFilter() {
+ 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 headline() {
+ const headline = this.data?.headline;
+ if (!headline) {
+ return null;
+ }
+
+ const prefix = "admin.dashboard.sections.support.headline";
+ const titleKey = `${prefix}.${headline.key}.title`;
+
+ if (headline.key === "no_data") {
+ return { titleKey, summary: i18n(`${prefix}.no_data.summary`) };
+ }
+
+ const parts = [
+ i18n(`${prefix}.resolution.${headline.resolution_direction}`, {
+ rate: headline.resolution_rate,
+ }),
+ ];
+
+ if (headline.answerers_focus) {
+ parts.push(
+ i18n(`${prefix}.answerers.${headline.answerers_focus}`, {
+ share: headline.answerers_share,
+ })
+ );
+ }
+
+ if (headline.first_reply_seconds != null) {
+ const dir = headline.first_reply_direction;
+ if (
+ (dir === "faster" || dir === "slower") &&
+ headline.first_reply_delta_seconds != null
+ ) {
+ parts.push(
+ i18n(`${prefix}.reply.${dir}`, {
+ time: durationTiny(headline.first_reply_seconds),
+ delta: durationTiny(headline.first_reply_delta_seconds),
+ })
+ );
+ } else {
+ parts.push(
+ i18n(`${prefix}.reply.flat`, {
+ time: durationTiny(headline.first_reply_seconds),
+ })
+ );
+ }
+ }
+
+ if (headline.key === "struggling" && headline.unanswered_count > 0) {
+ parts.push(
+ i18n(`${prefix}.unanswered`, { count: headline.unanswered_count })
+ );
+ }
+
+ return { titleKey, summary: parts.join(" ") };
+ }
+
+ get resolutionRate() {
+ const kpi = this.data?.kpis?.resolution_rate ?? {};
+ const value = kpi.value ?? 0;
+ const previous = kpi.previous_value;
+ const diff = previous == null ? null : Math.round(value - previous);
+ return {
+ value: `${Math.round(value)}%`,
+ reportType: kpi.report_type,
+ reportQuery: kpi.report_query ?? {},
+ hasDelta: diff != null,
+ deltaText: diff == null ? null : `${diff > 0 ? "+" : ""}${diff}%`,
+ deltaClass: diff === 0 ? "--neutral" : diff > 0 ? "--pos" : "--neg",
+ };
+ }
+
+ get staffInvolvement() {
+ const kpi = this.data?.kpis?.staff_involvement ?? {};
+ const value = kpi.value ?? 0;
+ const previous = kpi.previous_value;
+ const diff = previous == null ? null : Math.round(value - previous);
+ return {
+ value: `${Math.round(value)}%`,
+ hasDelta: diff != null,
+ deltaText: diff == null ? null : `${diff > 0 ? "+" : ""}${diff}%`,
+ deltaClass: diff === 0 ? "--neutral" : diff < 0 ? "--pos" : "--neg",
+ };
+ }
+
+ get avgFirstReply() {
+ const kpi = this.data?.kpis?.avg_first_reply ?? {};
+ const value = kpi.value;
+ const previous = kpi.previous_value;
+ const hasDelta = value != null && previous != null;
+ const diff = hasDelta ? value - previous : null;
+ const slower = value > previous;
+ return {
+ value: value == null ? "—" : durationTiny(value),
+ hasDelta,
+ deltaText:
+ !hasDelta || diff === 0
+ ? null
+ : `${slower ? "+" : "-"}${durationTiny(Math.abs(diff))}`,
+ deltaClass: diff === 0 ? "--neutral" : slower ? "--neg" : "--pos",
+ };
+ }
+
+ @action
+ onCategoryChange(categoryId) {
+ this.categoryId = categoryId;
+ this.refetch();
+ }
+
+ @action
+ onPeriodChange() {
+ if (this.categoryId === ALL_CATEGORIES) {
+ this.override = null;
+ } else {
+ this.refetch();
+ }
+ }
+
+ async refetch() {
+ this.loading = true;
+
+ const data = {};
+ if (this.args.startDate) {
+ data.start_date = moment(this.args.startDate).format("YYYY-MM-DD");
+ }
+ 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;
+ }
+
+ try {
+ this.override = await ajax(
+ "/admin/plugins/solved/dashboard-support.json",
+ {
+ data,
+ }
+ );
+ } catch (error) {
+ popupAjaxError(error);
+ } finally {
+ this.loading = false;
+ }
+ }
+
+ <template>
+ <DashboardSection
+ @title={{i18n "admin.dashboard.sections.support.title"}}
+ @startDate={{@startDate}}
+ @endDate={{@endDate}}
+ ...attributes
+ {{didUpdate this.onPeriodChange @startDate @endDate}}
+ >
+ {{#if @fetchError}}
+ <div class="db-section__error" role="alert">
+ {{i18n "admin.dashboard.sections.support.fetch_error"}}
+ </div>
+ {{else}}
+ {{#if this.headline}}
+ <div class="db-section__subheader">
+ <div class="db-section__subintro">
+ <h3>{{i18n this.headline.titleKey}}</h3>
+ <p>{{this.headline.summary}}</p>
+ </div>
+
+ <div class="db-section__metrics">
+ <div class="db-section__metric">
+ <div class="db-section__metric-number">
+ {{this.resolutionRate.value}}
+ </div>
+ <div class="db-section__metric-label">
+ <LinkTo
+ @route="adminReports.show"
+ @model={{this.resolutionRate.reportType}}
+ @query={{this.resolutionRate.reportQuery}}
+ >
+ {{i18n
+ "admin.dashboard.sections.support.kpi.resolution_rate.label"
+ }}
+ </LinkTo>
+ <DTooltip
+ class="db-section__info"
+ @icon="far-circle-question"
+ @content={{i18n
+ "admin.dashboard.sections.support.kpi.resolution_rate.tooltip"
+ }}
+ />
+ </div>
+ <DeltaPill @delta={{this.resolutionRate}} />
+ </div>
+
+ <div class="db-section__metric">
+ <div class="db-section__metric-number">
+ {{this.staffInvolvement.value}}
+ </div>
+ <div class="db-section__metric-label">
+ {{i18n
+ "admin.dashboard.sections.support.kpi.staff_involvement.label"
+ }}
+ <DTooltip
+ class="db-section__info"
+ @icon="far-circle-question"
+ @content={{i18n
+ "admin.dashboard.sections.support.kpi.staff_involvement.tooltip"
+ }}
+ />
+ </div>
+ <DeltaPill @delta={{this.staffInvolvement}} />
+ </div>
+
+ <div class="db-section__metric">
+ <div class="db-section__metric-number">
+ {{this.avgFirstReply.value}}
+ </div>
+ <div class="db-section__metric-label">
+ {{i18n
+ "admin.dashboard.sections.support.kpi.avg_first_reply.label"
+ }}
+ <DTooltip
+ class="db-section__info"
+ @icon="far-circle-question"
+ @content={{i18n
+ "admin.dashboard.sections.support.kpi.avg_first_reply.tooltip"
+ }}
+ />
+ </div>
+ <DeltaPill @delta={{this.avgFirstReply}} />
+ </div>
+ </div>
+ </div>
+ {{/if}}
+
+ {{#if this.showFilter}}
+ <div class="db-support__filter">
+ <ComboBox
+ @content={{this.categoryOptions}}
+ @value={{this.categoryId}}
+ @onChange={{this.onCategoryChange}}
+ @valueProperty="id"
+ @nameProperty="name"
+ />
+ </div>
+ {{/if}}
+
+ <div class="db-section__row-group">
+ <div class="db-section__row">
+ <div class="db-section__row-block db-support-outcomes">
+ <SupportTopicOutcomes @outcomes={{this.data.topic_outcomes}} />
+
+ </div>
+ <div class="db-section__row-block db-support-response">
+ <SupportResponseTime
+ @data={{this.data.response_time_distribution}}
+ />
+ </div>
+ </div>
+
+ <div class="db-section__row">
+ <div class="db-section__row-block db-support-answerers">
+ <SupportWhosAnswering @data={{this.data.whos_answering}} />
+ </div>
+ <div class="db-section__row-block"></div>
+ </div>
+ </div>
+ {{/if}}
+ </DashboardSection>
+ </template>
+}
diff --git a/plugins/discourse-solved/admin/assets/javascripts/admin/components/dashboard/support/response-time.gjs b/plugins/discourse-solved/admin/assets/javascripts/admin/components/dashboard/support/response-time.gjs
new file mode 100644
index 00000000000..aa5de33eddc
--- /dev/null
+++ b/plugins/discourse-solved/admin/assets/javascripts/admin/components/dashboard/support/response-time.gjs
@@ -0,0 +1,81 @@
+import Component from "@glimmer/component";
+import { concat } from "@ember/helper";
+import { trustHTML } from "@ember/template";
+import { durationTiny } from "discourse/lib/formatter";
+import { i18n } from "discourse-i18n";
+
+const BUCKETS = ["lt_1h", "1_4h", "4_24h", "gt_24h"];
+
+export default class SupportResponseTime extends Component {
+ get rows() {
+ const byKey = Object.fromEntries(
+ (this.args.data?.buckets ?? []).map((bucket) => [bucket.key, bucket])
+ );
+
+ return BUCKETS.map((key) => {
+ const share = byKey[key]?.share ?? 0;
+ return {
+ key,
+ share,
+ shareFormatted: `${Math.round(share)}%`,
+ label: i18n(
+ `admin.dashboard.sections.support.response_time.buckets.${key}`
+ ),
+ fillStyle: trustHTML(`width: ${share}%`),
+ fillClass: `--bucket-${key}`,
+ };
+ });
+ }
+
+ get ariaLabel() {
+ return this.rows
+ .map((row) => `${row.label} ${row.shareFormatted}`)
+ .join(", ");
+ }
+
+ get trend() {
+ const trend = this.args.data?.trend;
+ if (!trend || trend.direction === "flat" || !trend.seconds) {
+ return null;
+ }
+ return {
+ modifier: trend.direction === "faster" ? "--pos" : "--neg",
+ label: i18n(
+ `admin.dashboard.sections.support.response_time.trend.${trend.direction}`,
+ { duration: durationTiny(trend.seconds) }
+ ),
+ };
+ }
+
+ <template>
+ <div class="db-section__row-block-header">
+ <h3 class="db-section__row-block-title">
+ {{i18n "admin.dashboard.sections.support.response_time.title"}}
+ </h3>
+ {{#if this.trend}}
+ <span class={{concat "db-pill " this.trend.modifier}}>
+ {{this.trend.label}}
+ </span>
+ {{/if}}
+ </div>
+
+ <div
+ class="db-support-response__bars"
+ role="img"
+ aria-label={{this.ariaLabel}}
+ >
+ {{#each this.rows as |row|}}
+ <div class="db-support-response__row">
+ <span class="db-support-response__label">{{row.label}}</span>
+ <span class="db-support-response__track">
+ <span
+ class={{concat "db-support-response__fill " row.fillClass}}
+ style={{row.fillStyle}}
+ ></span>
+ </span>
+ <span class="db-support-response__share">{{row.shareFormatted}}</span>
+ </div>
+ {{/each}}
+ </div>
+ </template>
+}
diff --git a/plugins/discourse-solved/admin/assets/javascripts/admin/components/dashboard/support/topic-outcomes.gjs b/plugins/discourse-solved/admin/assets/javascripts/admin/components/dashboard/support/topic-outcomes.gjs
new file mode 100644
index 00000000000..5cba21ac1db
--- /dev/null
+++ b/plugins/discourse-solved/admin/assets/javascripts/admin/components/dashboard/support/topic-outcomes.gjs
@@ -0,0 +1,60 @@
+import Component from "@glimmer/component";
+import { concat } from "@ember/helper";
+import { trustHTML } from "@ember/template";
+import { i18n } from "discourse-i18n";
+
+const ROWS = ["resolved", "in_progress", "unanswered"];
+
+export default class SupportTopicOutcomes extends Component {
+ get rows() {
+ const outcomes = this.args.outcomes ?? {};
+ const max = Math.max(1, ...ROWS.map((key) => outcomes[key] ?? 0));
+
+ return ROWS.map((key) => {
+ const count = outcomes[key] ?? 0;
+ return {
+ key,
+ count,
+ label: i18n(`admin.dashboard.sections.support.outcomes.${key}.label`),
+ tooltip: i18n(
+ `admin.dashboard.sections.support.outcomes.${key}.tooltip`
+ ),
+ fillStyle: trustHTML(`width: ${(count / max) * 100}%`),
+ fillClass: `--${key.replace("_", "-")}`,
+ };
+ });
+ }
+
+ get ariaLabel() {
+ return this.rows.map((row) => `${row.label} ${row.count}`).join(", ");
+ }
+
+ <template>
+ <div class="db-section__row-block-header">
+ <h3 class="db-section__row-block-title">
+ {{i18n "admin.dashboard.sections.support.outcomes.title"}}
+ </h3>
+ </div>
+
+ <div
+ class="db-support-outcomes__bars"
+ role="img"
+ aria-label={{this.ariaLabel}}
+ >
+ {{#each this.rows as |row|}}
+ <div class="db-support-outcomes__row">
+ <span class="db-support-outcomes__label" title={{row.tooltip}}>
+ {{row.label}}
+ </span>
+ <span class="db-support-outcomes__track">
+ <span
+ class={{concat "db-support-outcomes__fill " row.fillClass}}
+ style={{row.fillStyle}}
+ ></span>
+ </span>
+ <span class="db-support-outcomes__share">{{row.count}}</span>
+ </div>
+ {{/each}}
+ </div>
+ </template>
+}
diff --git a/plugins/discourse-solved/admin/assets/javascripts/admin/components/dashboard/support/whos-answering.gjs b/plugins/discourse-solved/admin/assets/javascripts/admin/components/dashboard/support/whos-answering.gjs
new file mode 100644
index 00000000000..e909e5c6bea
--- /dev/null
+++ b/plugins/discourse-solved/admin/assets/javascripts/admin/components/dashboard/support/whos-answering.gjs
@@ -0,0 +1,66 @@
+import Component from "@glimmer/component";
+import { concat } from "@ember/helper";
+import { trustHTML } from "@ember/template";
+import { i18n } from "discourse-i18n";
+
+// Rendered in descending share order, matching the design; buckets with no
+// activity are omitted.
+export default class SupportWhosAnswering extends Component {
+ get rows() {
+ const data = this.args.data ?? {};
+ return (data.rows ?? [])
+ .filter((row) => row.count > 0)
+ .sort((a, b) => b.share - a.share)
+ .map((row) => ({
+ type: row.type,
+ share: row.share,
+ shareFormatted: `${Math.round(row.share)}%`,
+ label: i18n(`admin.dashboard.sections.support.answerers.${row.type}`),
+ fillStyle: trustHTML(`width: ${row.share}%`),
+ fillClass: `--${row.type}`,
+ }));
+ }
+
+ get hasData() {
+ return (this.args.data?.total ?? 0) > 0;
+ }
+
+ get ariaLabel() {
+ return this.rows.map((r) => `${r.label} ${r.shareFormatted}`).join(", ");
+ }
+
+ <template>
+ <div class="db-section__row-block-header">
+ <h3 class="db-section__row-block-title">
+ {{i18n "admin.dashboard.sections.support.answerers.title"}}
+ </h3>
+ </div>
+
+ {{#if this.hasData}}
+ <div
+ class="db-whos-posting__bars"
+ role="img"
+ aria-label={{this.ariaLabel}}
+ >
+ {{#each this.rows as |row|}}
+ <div class="db-whos-posting__bar-row">
+ <span class="db-whos-posting__bar-label">{{row.label}}</span>
+ <span class="db-whos-posting__bar-track">
+ <span
+ class={{concat "db-whos-posting__bar-fill " row.fillClass}}
+ style={{row.fillStyle}}
+ ></span>
+ </span>
+ <span
+ class="db-whos-posting__bar-share"
+ >{{row.shareFormatted}}</span>
+ </div>
+ {{/each}}
+ </div>
+ {{else}}
+ <p class="db-whos-posting__empty">
+ {{i18n "admin.dashboard.sections.support.answerers.empty"}}
+ </p>
+ {{/if}}
+ </template>
+}
diff --git a/plugins/discourse-solved/admin/assets/javascripts/discourse/initializers/solved-admin-dashboard-section.js b/plugins/discourse-solved/admin/assets/javascripts/discourse/initializers/solved-admin-dashboard-section.js
new file mode 100644
index 00000000000..eb65f884a93
--- /dev/null
+++ b/plugins/discourse-solved/admin/assets/javascripts/discourse/initializers/solved-admin-dashboard-section.js
@@ -0,0 +1,17 @@
+import { withPluginApi } from "discourse/lib/plugin-api";
+import SupportSection from "discourse/plugins/discourse-solved/admin/components/dashboard/support";
+
+export default {
+ name: "solved-admin-dashboard-section",
+
+ initialize(container) {
+ const siteSettings = container.lookup("service:site-settings");
+ if (!siteSettings.solved_enabled) {
+ return;
+ }
+
+ withPluginApi((api) => {
+ api.registerAdminDashboardSection("support", SupportSection);
+ });
+ },
+};
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
new file mode 100644
index 00000000000..c9fa48e0a09
--- /dev/null
+++ b/plugins/discourse-solved/app/controllers/discourse_solved/admin_dashboard_support_controller.rb
@@ -0,0 +1,15 @@
+# frozen_string_literal: true
+
+class DiscourseSolved::AdminDashboardSupportController < ::Admin::StaffController
+ requires_plugin DiscourseSolved::PLUGIN_NAME
+
+ def index
+ render json:
+ DiscourseSolved::AdminDashboardSupport.build(
+ start_date: params[:start_date],
+ end_date: params[:end_date],
+ current_user: current_user,
+ category_id: params[:category_id],
+ )
+ end
+end
diff --git a/plugins/discourse-solved/assets/stylesheets/admin/dashboard-support.scss b/plugins/discourse-solved/assets/stylesheets/admin/dashboard-support.scss
new file mode 100644
index 00000000000..0c9b31c5859
--- /dev/null
+++ b/plugins/discourse-solved/assets/stylesheets/admin/dashboard-support.scss
@@ -0,0 +1,176 @@
+// Styles for the Support section of the redesigned admin dashboard. Layout
+// primitives (.db-section__*, .db-delta, .db-pill, .db-whos-posting__*) are
+// owned by core; only Support-specific rules live here.
+
+$db-bar-height: var(--space-2);
+
+.db-support__filter {
+ .select-kit.combo-box {
+ max-width: 220px;
+ }
+}
+
+.db-support-outcomes {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-3);
+ container-type: inline-size;
+ container-name: db-support-outcomes;
+
+ &__bars {
+ display: grid;
+ grid-template-columns: minmax(0, auto) minmax(120px, 1fr) 2.5rem;
+ gap: var(--space-2);
+
+ @container db-support-outcomes (width < 22rem) {
+ grid-template-columns: 1fr;
+ gap: var(--space-3);
+ }
+ }
+
+ &__row {
+ display: grid;
+ grid-column: 1 / -1;
+ grid-template-columns: subgrid;
+ align-items: center;
+
+ @container db-support-outcomes (width < 22rem) {
+ grid-template-columns: 1fr auto;
+ gap: 0 var(--space-2);
+ }
+ }
+
+ &__label {
+ display: flex;
+ align-items: center;
+ gap: var(--space-1);
+ min-width: 0;
+ color: var(--primary);
+ cursor: help;
+
+ @container db-support-outcomes (width < 22rem) {
+ grid-column: 1 / -1;
+ }
+ }
+
+ &__track {
+ height: $db-bar-height;
+ border-radius: var(--d-border-radius-fixed);
+ background: var(--primary-low);
+ }
+
+ &__fill {
+ display: block;
+ height: 100%;
+ border-radius: var(--d-border-radius-fixed);
+
+ &.--resolved {
+ background: var(--success);
+ }
+
+ &.--in-progress {
+ background: var(--tertiary-medium);
+ }
+
+ &.--unanswered {
+ background: var(--danger);
+ }
+ }
+
+ &__share {
+ color: var(--primary-medium);
+ font-variant-numeric: tabular-nums;
+ text-align: end;
+ line-height: 1;
+ }
+}
+
+// Reuse the who's-posting bar layout, recolouring fills per answerer group.
+.db-support-answerers {
+ &.db-section__row-block {
+ // overrule since there is no block next to this one
+ border-right: 0;
+ }
+
+ .db-whos-posting__bar-fill {
+ background: var(--tertiary-medium);
+
+ &.--staff {
+ background: var(--primary-medium);
+ }
+ }
+}
+
+.db-support-response {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-3);
+ container-type: inline-size;
+ container-name: db-support-response;
+
+ &__bars {
+ display: grid;
+ grid-template-columns: minmax(0, auto) minmax(120px, 1fr) 2.5rem;
+ gap: var(--space-2);
+
+ @container db-support-response (width < 22rem) {
+ grid-template-columns: 1fr;
+ gap: var(--space-3);
+ }
+ }
+
+ &__row {
+ display: grid;
+ grid-column: 1 / -1;
+ grid-template-columns: subgrid;
+ align-items: center;
+
+ @container db-support-response (width < 22rem) {
+ grid-template-columns: 1fr auto;
+ gap: 0 var(--space-2);
+ }
+ }
+
+ &__label {
+ @include ellipsis;
+
+ @container db-support-response (width < 22rem) {
+ grid-column: 1 / -1;
+ }
+ }
+
+ &__track {
+ height: $db-bar-height;
+ border-radius: var(--d-border-radius-fixed);
+ background: var(--primary-low);
+ }
+
+ &__fill {
+ display: block;
+ height: 100%;
+ border-radius: var(--d-border-radius-fixed);
+
+ &.--bucket-lt_1h {
+ background: var(--success);
+ }
+
+ &.--bucket-1_4h {
+ background: var(--success-medium, var(--success));
+ }
+
+ &.--bucket-4_24h {
+ background: var(--primary-medium);
+ }
+
+ &.--bucket-gt_24h {
+ background: var(--danger);
+ }
+ }
+
+ &__share {
+ color: var(--primary-medium);
+ font-variant-numeric: tabular-nums;
+ text-align: end;
+ line-height: 1;
+ }
+}
diff --git a/plugins/discourse-solved/config/locales/client.en.yml b/plugins/discourse-solved/config/locales/client.en.yml
index 14c872226a0..30acb476fcb 100644
--- a/plugins/discourse-solved/config/locales/client.en.yml
+++ b/plugins/discourse-solved/config/locales/client.en.yml
@@ -10,6 +10,76 @@ en:
accepted_solutions:
label: "Accepted solutions"
tooltip: "The number of topics that had a post marked as the solution."
+ sections:
+ support:
+ title: "Support"
+ fetch_error: "Support data couldn't be loaded."
+ filter:
+ all_categories: "All categories"
+ headline:
+ healthy:
+ title: "The community is solving its own problems."
+ struggling:
+ title: "Most questions aren't getting answered."
+ mixed:
+ title: "Support is a mixed bag."
+ no_data:
+ title: "Not enough support activity yet"
+ summary: "There's no support activity in this period yet. Once topics come in, you'll see how your community is handling them."
+ resolution:
+ up: "Resolution rate climbed to %{rate}%."
+ down: "Resolution rate dropped to %{rate}%."
+ flat: "Resolution rate held at %{rate}%."
+ answerers:
+ members: "Members are handling %{share}% of replies."
+ staff: "Staff are answering %{share}% of replies."
+ reply:
+ faster: "First-reply time improved to %{time}, %{delta} faster than the previous period."
+ slower: "First-reply time slipped to %{time}, %{delta} slower than the previous period."
+ flat: "First-reply time held at %{time}."
+ unanswered:
+ one: "%{count} topic from this period still has zero replies."
+ other: "%{count} topics from this period still have zero replies."
+ kpi:
+ resolution_rate:
+ label: "Resolution rate"
+ tooltip: "The percentage of open support topics that were solved."
+ staff_involvement:
+ label: "Staff involvement"
+ tooltip: "The percentage of open support topics where a staff member made the first reply."
+ avg_first_reply:
+ label: "Avg. first reply"
+ tooltip: "The average time between when a support topic was posted and when it received its first reply."
+ outcomes:
+ title: "Topic outcomes"
+ resolved:
+ label: "Resolved"
+ tooltip: "The number of topics that were marked solved."
+ in_progress:
+ label: "In progress"
+ tooltip: "The number of topics with at least one reply."
+ unanswered:
+ label: "Unanswered"
+ tooltip: "The number of topics with no replies."
+ answerers:
+ title: "Who's answering?"
+ empty: "No replies in this period."
+ staff: "Staff"
+ leader: "Leaders"
+ regular: "Regulars"
+ member: "Members"
+ basic: "Basic"
+ response_time:
+ title: "Response time distribution"
+ buckets:
+ lt_1h: "< 1 hour"
+ "1_4h": "1–4 hours"
+ "4_24h": "4–24 hours"
+ gt_24h: "> 24 hours"
+ trend:
+ faster: "%{duration} faster"
+ slower: "%{duration} slower"
+ tooltip: "The average response time trend."
js:
notifications:
alt:
diff --git a/plugins/discourse-solved/config/routes.rb b/plugins/discourse-solved/config/routes.rb
index 45f79939fd6..33ad3f1d0f4 100644
--- a/plugins/discourse-solved/config/routes.rb
+++ b/plugins/discourse-solved/config/routes.rb
@@ -9,4 +9,9 @@ DiscourseSolved::Engine.routes.draw do
get "/by_user" => "solved_topics#by_user"
end
-Discourse::Application.routes.draw { mount DiscourseSolved::Engine, at: "solution" }
+Discourse::Application.routes.draw do
+ mount DiscourseSolved::Engine, at: "solution"
+
+ get "/admin/plugins/solved/dashboard-support" => "discourse_solved/admin_dashboard_support#index",
+ :constraints => StaffConstraint.new
+end
diff --git a/plugins/discourse-solved/lib/discourse_solved/admin_dashboard_support.rb b/plugins/discourse-solved/lib/discourse_solved/admin_dashboard_support.rb
new file mode 100644
index 00000000000..a2da225fb19
--- /dev/null
+++ b/plugins/discourse-solved/lib/discourse_solved/admin_dashboard_support.rb
@@ -0,0 +1,414 @@
+# frozen_string_literal: true
+
+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.
+ class AdminDashboardSupport
+ DEFAULT_RANGE_DAYS = 30
+ AVAILABILITY_CACHE_KEY = "solved_admin_dashboard_support_available"
+ DATA_CACHE_DURATION = 30.minutes
+
+ # Response-time buckets, in seconds. Open-ended final bucket uses nil.
+ RESPONSE_TIME_BUCKETS = [
+ { key: "lt_1h", max: 1.hour.to_i },
+ { key: "1_4h", max: 4.hours.to_i },
+ { key: "4_24h", max: 24.hours.to_i },
+ { key: "gt_24h", max: nil },
+ ].freeze
+
+ def self.available?
+ return false if !SiteSetting.solved_enabled
+ return true if SiteSetting.allow_solved_on_all_topics
+
+ Discourse
+ .cache
+ .fetch(AVAILABILITY_CACHE_KEY, expires_in: 5.minutes) do
+ DiscourseSolved::Categories::Types::Support.find_matches.exists?
+ end
+ end
+
+ def self.build(start_date:, end_date:, current_user: nil, category_id: nil)
+ new(
+ start_date: start_date,
+ end_date: end_date,
+ current_user: current_user,
+ category_id: category_id,
+ ).build
+ end
+
+ def initialize(start_date:, end_date:, current_user: nil, category_id: 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
+ end
+
+ def build
+ Discourse
+ .cache
+ .fetch(cache_key, expires_in: DATA_CACHE_DURATION) do
+ {
+ category_options: category_options,
+ kpis: build_kpis,
+ headline: build_headline,
+ topic_outcomes: topic_outcomes,
+ whos_answering: whos_answering,
+ response_time_distribution: response_time_distribution,
+ }
+ end
+ end
+
+ private
+
+ attr_reader :start_date, :end_date, :current_user, :category_id
+
+ def parse_date(value)
+ return nil if value.blank?
+ Time.zone.parse(value.to_s)&.beginning_of_day
+ rescue ArgumentError, TypeError
+ nil
+ end
+
+ # Length-matched window immediately preceding the selected period.
+ def prev_start_date
+ start_date - (end_date - start_date)
+ end
+
+ def prev_end_date
+ start_date
+ end
+
+ def guardian
+ @guardian ||= current_user&.guardian || Guardian.new
+ end
+
+ def support_categories
+ scope =
+ if SiteSetting.allow_solved_on_all_topics
+ Category.all
+ else
+ DiscourseSolved::Categories::Types::Support.find_matches
+ end
+ scope.secured(guardian)
+ end
+
+ def all_support_category_ids
+ @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)
+ end
+
+ def effective_category_ids
+ selected_category_id ? [selected_category_id] : all_support_category_ids
+ end
+
+ def category_options
+ support_categories.order(:name).pluck(:id, :name).map { |id, name| { id: id, name: name } }
+ end
+
+ def cache_key
+ digest =
+ Digest::SHA1.hexdigest(
+ [
+ all_support_category_ids.sort,
+ selected_category_id,
+ start_date.to_i,
+ end_date.to_i,
+ ].to_json,
+ )
+ "solved_admin_dashboard_support_data:#{digest}"
+ end
+
+ def build_kpis
+ current = outcomes_for(start_date, end_date)
+ previous = outcomes_for(prev_start_date, prev_end_date)
+
+ {
+ resolution_rate: {
+ value: resolution_rate(current),
+ previous_value: resolution_rate(previous),
+ report_type: "accepted_solutions",
+ report_query: resolution_report_query,
+ },
+ staff_involvement: {
+ value: staff_involvement(start_date, end_date),
+ previous_value: staff_involvement(prev_start_date, prev_end_date),
+ },
+ avg_first_reply: {
+ value: avg_first_reply_seconds(start_date, end_date),
+ previous_value: avg_first_reply_seconds(prev_start_date, prev_end_date),
+ },
+ }
+ end
+
+ 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
+ query
+ end
+
+ def build_headline
+ outcomes = topic_outcomes
+ total = outcomes.values.sum
+ rate = resolution_rate(outcomes)
+ prev_rate = resolution_rate(outcomes_for(prev_start_date, prev_end_date))
+
+ key =
+ if total.zero?
+ "no_data"
+ elsif rate >= 60
+ "healthy"
+ elsif rate < 40
+ "struggling"
+ else
+ "mixed"
+ end
+
+ reply_now = avg_first_reply_seconds(start_date, end_date)
+ reply_prev = avg_first_reply_seconds(prev_start_date, prev_end_date)
+
+ answerers = whos_answering
+ staff_share =
+ if answerers[:total].to_i.zero?
+ nil
+ else
+ (answerers[:rows].find { |r| r[:type] == "staff" }&.dig(:share) || 0).round
+ end
+ focus = staff_share.nil? ? nil : (staff_share >= 50 ? "staff" : "members")
+
+ {
+ key: key,
+ resolution_rate: rate&.round,
+ resolution_direction: direction(rate, prev_rate),
+ answerers_focus: focus,
+ answerers_share: (focus == "staff" ? staff_share : (staff_share && 100 - staff_share)),
+ first_reply_seconds: reply_now,
+ first_reply_direction: time_direction(reply_now, reply_prev),
+ first_reply_delta_seconds: (reply_now && reply_prev ? (reply_now - reply_prev).abs : nil),
+ unanswered_count: outcomes[:unanswered],
+ }
+ end
+
+ # Mutually-exclusive status counts for topics created in the window:
+ # resolved (has an accepted answer), else in_progress (has at least one
+ # reply), else unanswered.
+ def topic_outcomes
+ outcomes_for(start_date, end_date)
+ end
+
+ def outcomes_for(from, to)
+ (@outcomes_cache ||= {})[[from, to]] ||= compute_outcomes(from, to)
+ end
+
+ def compute_outcomes(from, to)
+ return { resolved: 0, in_progress: 0, unanswered: 0 } if effective_category_ids.empty?
+
+ row = DB.query(<<~SQL, params_for(from, to)).first
+ SELECT
+ COUNT(*) FILTER (WHERE solved) AS resolved,
+ COUNT(*) FILTER (WHERE NOT solved AND has_reply) AS in_progress,
+ COUNT(*) FILTER (WHERE NOT solved AND NOT has_reply) AS unanswered
+ FROM (
+ SELECT
+ (st.topic_id IS NOT NULL) AS solved,
+ EXISTS (
+ SELECT 1
+ FROM posts p
+ WHERE p.topic_id = t.id
+ AND p.post_number > 1
+ AND p.post_type = :post_type
+ AND p.deleted_at IS NULL
+ AND p.user_id <> t.user_id
+ ) AS has_reply
+ FROM topics t
+ LEFT JOIN discourse_solved_solved_topics st ON st.topic_id = t.id
+ WHERE t.category_id IN (:category_ids)
+ AND t.archetype = :archetype
+ AND t.deleted_at IS NULL
+ AND t.created_at >= :from
+ AND t.created_at <= :to
+ ) topics_with_state
+ SQL
+
+ {
+ resolved: row.resolved.to_i,
+ in_progress: row.in_progress.to_i,
+ unanswered: row.unanswered.to_i,
+ }
+ end
+
+ def resolution_rate(outcomes)
+ total = outcomes.values.sum
+ return nil if total.zero?
+ (outcomes[:resolved].to_f / total * 100).round(1)
+ end
+
+ # Percentage of topics in the window whose first reply was authored by staff.
+ def staff_involvement(from, to)
+ return nil if effective_category_ids.empty?
+
+ total = outcomes_for(from, to).values.sum
+ return nil if total.zero?
+
+ staff_first = DB.query_single(<<~SQL, params_for(from, to)).first.to_i
+ SELECT COUNT(*)
+ FROM (
+ SELECT DISTINCT ON (p.topic_id) p.user_id
+ FROM posts p
+ JOIN topics t ON t.id = p.topic_id
+ WHERE t.category_id IN (:category_ids)
+ AND t.archetype = :archetype
+ AND t.deleted_at IS NULL
+ AND t.created_at >= :from
+ AND t.created_at <= :to
+ AND p.post_number > 1
+ AND p.post_type = :post_type
+ AND p.deleted_at IS NULL
+ AND p.user_id <> t.user_id
+ ORDER BY p.topic_id, p.created_at ASC
+ ) first_replies
+ JOIN users u ON u.id = first_replies.user_id
+ WHERE u.admin OR u.moderator
+ SQL
+
+ (staff_first.to_f / total * 100).round(1)
+ end
+
+ def first_reply_seconds(from, to)
+ (@first_reply_cache ||= {})[[from, to]] ||= compute_first_reply_seconds(from, to)
+ end
+
+ def compute_first_reply_seconds(from, to)
+ return [] if effective_category_ids.empty?
+
+ DB.query_single(<<~SQL, params_for(from, to))
+ SELECT EXTRACT(EPOCH FROM MIN(p.created_at) - t.created_at)::int AS seconds
+ FROM topics t
+ JOIN posts p ON p.topic_id = t.id
+ WHERE t.category_id IN (:category_ids)
+ AND t.archetype = :archetype
+ AND t.deleted_at IS NULL
+ AND t.created_at >= :from
+ AND t.created_at <= :to
+ AND p.post_number > 1
+ AND p.post_type = :post_type
+ AND p.deleted_at IS NULL
+ AND p.user_id <> t.user_id
+ GROUP BY t.id
+ HAVING EXTRACT(EPOCH FROM MIN(p.created_at) - t.created_at) > 0
+ SQL
+ end
+
+ def avg_first_reply_seconds(from, to)
+ seconds = first_reply_seconds(from, to)
+ return nil if seconds.empty?
+ (seconds.sum.to_f / seconds.size).round
+ end
+
+ def response_time_distribution
+ seconds = first_reply_seconds(start_date, end_date)
+ total = seconds.size
+
+ buckets =
+ RESPONSE_TIME_BUCKETS.map do |bucket|
+ min = previous_bucket_max(bucket)
+ count = seconds.count { |s| s >= min && (bucket[:max].nil? || s < bucket[:max]) }
+ {
+ key: bucket[:key],
+ count: count,
+ share: total.zero? ? 0.0 : (count.to_f / total * 100).round,
+ }
+ end
+
+ avg_now = avg_first_reply_seconds(start_date, end_date)
+ avg_prev = avg_first_reply_seconds(prev_start_date, prev_end_date)
+
+ trend =
+ if avg_now && avg_prev
+ { direction: time_direction(avg_now, avg_prev), seconds: (avg_now - avg_prev).abs }
+ else
+ { direction: "flat", seconds: 0 }
+ end
+
+ { buckets: buckets, trend: trend }
+ end
+
+ def previous_bucket_max(bucket)
+ index = RESPONSE_TIME_BUCKETS.index(bucket)
+ index.zero? ? 0 : RESPONSE_TIME_BUCKETS[index - 1][:max]
+ end
+
+ def whos_answering
+ @whos_answering ||= compute_whos_answering
+ end
+
+ # Share of replies in the window by author group (staff, then trust level).
+ def compute_whos_answering
+ return { rows: [], total: 0 } if effective_category_ids.empty?
+
+ rows = DB.query(<<~SQL, params_for(start_date, end_date))
+ SELECT
+ CASE
+ WHEN u.admin OR u.moderator THEN 'staff'
+ WHEN u.trust_level >= 4 THEN 'leader'
+ WHEN u.trust_level = 3 THEN 'regular'
+ WHEN u.trust_level = 2 THEN 'member'
+ ELSE 'basic'
+ END AS bucket,
+ COUNT(*) AS count
+ FROM posts p
+ JOIN topics t ON t.id = p.topic_id
+ JOIN users u ON u.id = p.user_id
+ WHERE t.category_id IN (:category_ids)
+ AND t.archetype = :archetype
+ AND t.deleted_at IS NULL
+ AND p.created_at >= :from
+ AND p.created_at <= :to
+ AND p.post_number > 1
+ AND p.post_type = :post_type
+ AND p.deleted_at IS NULL
+ AND p.user_id <> t.user_id
+ AND u.id > 0
+ GROUP BY bucket
+ SQL
+
+ total = rows.sum(&:count)
+ {
+ rows:
+ rows.map do |row|
+ {
+ type: row.bucket,
+ count: row.count,
+ share: total.zero? ? 0.0 : (row.count.to_f / total * 100).round,
+ }
+ end,
+ total: total,
+ }
+ end
+
+ def params_for(from, to)
+ {
+ category_ids: effective_category_ids,
+ archetype: Archetype.default,
+ post_type: Post.types[:regular],
+ from: from,
+ to: to,
+ }
+ end
+
+ def direction(current, previous)
+ return "flat" if current.nil? || previous.nil? || current == previous
+ current > previous ? "up" : "down"
+ end
+
+ # For durations, lower is better, so "faster"/"slower" rather than up/down.
+ def time_direction(current, previous)
+ return "flat" if current.nil? || previous.nil? || current == previous
+ current < previous ? "faster" : "slower"
+ end
+ end
+end
diff --git a/plugins/discourse-solved/plugin.rb b/plugins/discourse-solved/plugin.rb
index 449e0897c5b..1ec67d0d79d 100644
--- a/plugins/discourse-solved/plugin.rb
+++ b/plugins/discourse-solved/plugin.rb
@@ -14,6 +14,7 @@ register_svg_icon "square-check"
register_svg_icon "far-square"
register_asset "stylesheets/solutions.scss"
+register_asset "stylesheets/admin/dashboard-support.scss", :admin
module ::DiscourseSolved
PLUGIN_NAME = "discourse-solved"
@@ -224,6 +225,17 @@ after_initialize do
end,
)
+ register_admin_dashboard_section(
+ id: "support",
+ enabled: -> { DiscourseSolved::AdminDashboardSupport.available? },
+ ) do |start_date:, end_date:, current_user:|
+ DiscourseSolved::AdminDashboardSupport.build(
+ start_date: start_date,
+ end_date: end_date,
+ current_user: current_user,
+ )
+ end
+
register_modifier(:search_rank_sort_priorities) do |priorities, _search|
if SiteSetting.prioritize_solved_topics_in_search
condition = <<~SQL
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
new file mode 100644
index 00000000000..734cc3aed47
--- /dev/null
+++ b/plugins/discourse-solved/spec/lib/discourse_solved/admin_dashboard_support_spec.rb
@@ -0,0 +1,274 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseSolved::AdminDashboardSupport do
+ fab!(:support_category, :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
+
+ def build(**opts)
+ described_class.build(
+ start_date: 30.days.ago.to_s,
+ end_date: Time.zone.now.to_s,
+ current_user: admin,
+ **opts,
+ )
+ end
+
+ def solved_topic(category: support_category, answerer: staff_user)
+ topic = Fabricate(:topic, category: category, user: author)
+ Fabricate(:post, topic: topic, user: author)
+ answer = Fabricate(:post, topic: topic, user: answerer)
+ Fabricate(:solved_topic, topic: topic, answer_post: answer)
+ topic
+ end
+
+ def answered_topic(category: support_category, answerer: member_user)
+ topic = Fabricate(:topic, category: category, user: author)
+ Fabricate(:post, topic: topic, user: author)
+ Fabricate(:post, topic: topic, user: answerer)
+ topic
+ end
+
+ def unanswered_topic(category: support_category)
+ topic = Fabricate(:topic, category: category, user: author)
+ Fabricate(:post, topic: topic, user: author)
+ topic
+ end
+
+ describe ".available?" do
+ it "is true when a support category exists" do
+ expect(described_class.available?).to eq(true)
+ end
+
+ it "is false when the plugin is disabled" do
+ SiteSetting.solved_enabled = false
+ expect(described_class.available?).to eq(false)
+ end
+
+ it "is false when no category enables accepted answers" do
+ support_category.custom_fields[
+ DiscourseSolved::ENABLE_ACCEPTED_ANSWERS_CUSTOM_FIELD
+ ] = "false"
+ support_category.save!
+ Discourse.cache.delete(DiscourseSolved::AdminDashboardSupport::AVAILABILITY_CACHE_KEY)
+
+ expect(described_class.available?).to eq(false)
+ end
+ end
+
+ describe "topic outcomes" do
+ it "counts resolved, in progress, and unanswered as mutually exclusive states" do
+ solved_topic
+ answered_topic
+ unanswered_topic
+
+ expect(build[:topic_outcomes]).to eq(resolved: 1, in_progress: 1, unanswered: 1)
+ end
+
+ it "treats a topic where only the author replied as unanswered, not in progress" do
+ topic = Fabricate(:topic, category: support_category, user: author)
+ Fabricate(:post, topic: topic, user: author)
+ Fabricate(:post, topic: topic, user: author)
+
+ expect(build[:topic_outcomes]).to eq(resolved: 0, in_progress: 0, unanswered: 1)
+ end
+
+ it "serves cached data for the same scope and window within the TTL" do
+ solved_topic
+
+ expect(build[:topic_outcomes]).to eq(resolved: 1, in_progress: 0, unanswered: 0)
+
+ solved_topic
+
+ expect(build[:topic_outcomes]).to eq(resolved: 1, in_progress: 0, unanswered: 0)
+ end
+ end
+
+ describe "headline" do
+ it "chooses the key from the absolute resolution rate, not the trend" do
+ solved_topic
+ unanswered_topic
+ unanswered_topic
+
+ expect(build[:headline][:key]).to eq("struggling")
+ end
+
+ it "reports the resolution direction against the previous period, independent of the level" do
+ previous =
+ Fabricate(:topic, category: support_category, user: author, created_at: 45.days.ago)
+ Fabricate(:post, topic: previous, user: author, created_at: 45.days.ago)
+
+ solved_topic
+ unanswered_topic
+ unanswered_topic
+
+ headline = build[:headline]
+ expect(headline[:key]).to eq("struggling")
+ expect(headline[:resolution_direction]).to eq("up")
+ end
+
+ it "focuses the answerers clause on staff when staff dominate replies" do
+ solved_topic(answerer: staff_user)
+
+ expect(build[:headline][:answerers_focus]).to eq("staff")
+ end
+
+ it "focuses the answerers clause on members when non-staff dominate replies" do
+ answered_topic(answerer: member_user)
+
+ expect(build[:headline][:answerers_focus]).to eq("members")
+ end
+ end
+
+ describe "resolution rate KPI" do
+ it "is the share of period topics that were solved" do
+ solved_topic
+ answered_topic
+ unanswered_topic
+
+ expect(build[:kpis][:resolution_rate][:value]).to eq(33.3)
+ end
+
+ it "carries the selected category into the report drill-down query" do
+ solved_topic
+
+ query = build(category_id: support_category.id)[:kpis][:resolution_rate][:report_query]
+
+ expect(query[:filters]).to eq(category: support_category.id)
+ end
+
+ it "omits the category filter when viewing all categories" do
+ solved_topic
+
+ expect(build[:kpis][:resolution_rate][:report_query]).not_to have_key(:filters)
+ end
+
+ it "reports a nil previous value when the previous period had no topics" do
+ solved_topic
+ answered_topic
+
+ kpis = build[:kpis]
+ expect(kpis[:resolution_rate][:value]).to eq(50.0)
+ expect(kpis[:resolution_rate][:previous_value]).to be_nil
+ expect(kpis[:staff_involvement][:previous_value]).to be_nil
+ end
+ end
+
+ describe "staff involvement KPI" do
+ it "is the share of topics whose first reply came from staff" do
+ solved_topic(answerer: staff_user)
+ answered_topic(answerer: member_user)
+
+ expect(build[:kpis][:staff_involvement][:value]).to eq(50.0)
+ end
+ end
+
+ describe "who's answering" do
+ it "groups repliers by staff and trust level, sharing out the totals" do
+ solved_topic(answerer: staff_user)
+ answered_topic(answerer: member_user)
+
+ rows = build[:whos_answering][:rows]
+
+ expect(build[:whos_answering][:total]).to eq(2)
+ expect(rows.find { |row| row[:type] == "staff" }[:count]).to eq(1)
+ expect(rows.find { |row| row[:type] == "member" }[:count]).to eq(1)
+ end
+
+ it "does not count the topic author replying to their own topic" do
+ topic = Fabricate(:topic, category: support_category, user: author)
+ Fabricate(:post, topic: topic, user: author)
+ Fabricate(:post, topic: topic, user: author)
+
+ expect(build[:whos_answering][:total]).to eq(0)
+ end
+ end
+
+ describe "response time distribution" do
+ it "buckets first-reply times and reports the average" do
+ answered_topic
+
+ distribution = build[:response_time_distribution]
+
+ expect(distribution[:buckets].sum { |bucket| bucket[:count] }).to eq(1)
+ expect(build[:kpis][:avg_first_reply][:value]).not_to be_nil
+ end
+ 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
+
+ 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)
+ end
+
+ it "lists both support categories as filter options" do
+ expect(build[:category_options].map { |option| option[:id] }).to contain_exactly(
+ support_category.id,
+ second_support_category.id,
+ )
+ end
+ end
+
+ describe "when solved is enabled on all topics" do
+ fab!(:plain_category, :category)
+
+ before { SiteSetting.allow_solved_on_all_topics = true }
+
+ it "offers every visible category as a filter option, not just flagged ones" do
+ ids = build[:category_options].map { |option| option[:id] }
+
+ expect(ids).to include(support_category.id, plain_category.id)
+ end
+ end
+
+ describe "guardian scoping" do
+ fab!(:group)
+ fab!(:restricted_category) { Fabricate(:private_category, group: group) }
+ fab!(:outsider, :moderator)
+
+ before do
+ restricted_category.custom_fields[
+ DiscourseSolved::ENABLE_ACCEPTED_ANSWERS_CUSTOM_FIELD
+ ] = "true"
+ restricted_category.save!
+ solved_topic(category: restricted_category)
+ end
+
+ it "excludes categories the viewer cannot see" do
+ as_admin = build[:topic_outcomes][:resolved]
+ as_outsider =
+ described_class.build(
+ start_date: 30.days.ago.to_s,
+ end_date: Time.zone.now.to_s,
+ current_user: outsider,
+ )[
+ :topic_outcomes
+ ][
+ :resolved
+ ]
+
+ expect(as_admin).to eq(1)
+ expect(as_outsider).to eq(0)
+ end
+ 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
new file mode 100644
index 00000000000..0603bccd157
--- /dev/null
+++ b/plugins/discourse-solved/spec/requests/discourse_solved/admin_dashboard_support_controller_spec.rb
@@ -0,0 +1,64 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseSolved::AdminDashboardSupportController do
+ fab!(:admin)
+ fab!(:moderator)
+ fab!(:user)
+ fab!(:support_category, :category)
+
+ before do
+ SiteSetting.solved_enabled = true
+ support_category.custom_fields[DiscourseSolved::ENABLE_ACCEPTED_ANSWERS_CUSTOM_FIELD] = "true"
+ support_category.save!
+ end
+
+ describe "#index" do
+ it "returns the support section payload for an admin" do
+ sign_in(admin)
+
+ get "/admin/plugins/solved/dashboard-support.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body.keys).to include(
+ "kpis",
+ "topic_outcomes",
+ "whos_answering",
+ "response_time_distribution",
+ "category_options",
+ )
+ end
+
+ it "accepts a category filter" do
+ sign_in(admin)
+
+ get "/admin/plugins/solved/dashboard-support.json",
+ params: {
+ category_id: support_category.id,
+ }
+
+ expect(response.status).to eq(200)
+ end
+
+ it "is available to moderators" do
+ sign_in(moderator)
+
+ get "/admin/plugins/solved/dashboard-support.json"
+
+ expect(response.status).to eq(200)
+ end
+
+ it "is not routable for a regular user" do
+ sign_in(user)
+
+ get "/admin/plugins/solved/dashboard-support.json"
+
+ expect(response.status).to eq(404)
+ end
+
+ it "is not routable for anonymous users" do
+ get "/admin/plugins/solved/dashboard-support.json"
+
+ expect(response.status).to eq(404)
+ end
+ end
+end
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
new file mode 100644
index 00000000000..706a25be001
--- /dev/null
+++ b/plugins/discourse-solved/spec/system/admin_dashboard_support_section_spec.rb
@@ -0,0 +1,57 @@
+# frozen_string_literal: true
+
+describe "Admin dashboard Support section" do
+ fab!(:admin)
+ fab!(:support_category, :category)
+ fab!(:author) { Fabricate(:user, trust_level: TrustLevel[1]) }
+ fab!(:staff_replier, :moderator)
+ fab!(:member_replier) { Fabricate(:user, trust_level: TrustLevel[2]) }
+
+ let(:dashboard) { PageObjects::Pages::AdminDashboard.new }
+ let(:support) { PageObjects::Components::AdminDashboardSupport.new }
+
+ 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)
+ Fabricate(:post, topic: resolved, user: author)
+ staff_answer = Fabricate(:post, topic: resolved, user: staff_replier)
+ Fabricate(:solved_topic, topic: resolved, answer_post: staff_answer)
+
+ # In progress: a member has replied but nothing is accepted.
+ in_progress = Fabricate(:topic, category: support_category, user: author)
+ Fabricate(:post, topic: in_progress, user: author)
+ Fabricate(:post, topic: in_progress, user: member_replier)
+
+ # Unanswered: only the opening post.
+ unanswered = Fabricate(:topic, category: support_category, user: author)
+ Fabricate(:post, topic: unanswered, user: author)
+
+ sign_in(admin)
+ end
+
+ it "shows support analytics for the community's support topics" do
+ dashboard.visit
+
+ expect(support).to have_section
+ expect(support).to have_kpi("Resolution rate")
+ expect(support).to have_kpi("Staff involvement")
+ expect(support).to have_kpi("Avg. first reply")
+
+ expect(support).to have_topic_outcome("Resolved", count: 1)
+ expect(support).to have_topic_outcome("In progress", count: 1)
+ expect(support).to have_topic_outcome("Unanswered", count: 1)
+
+ expect(support).to have_answerer("Staff")
+ expect(support).to have_answerer("Members")
+
+ expect(support).to have_response_time_bucket("< 1 hour")
+
+ # With a single support category there is nothing to filter between.
+ expect(support).to have_no_category_filter
+ 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
new file mode 100644
index 00000000000..20bc48b26ca
--- /dev/null
+++ b/plugins/discourse-solved/spec/system/page_objects/components/admin_dashboard_support.rb
@@ -0,0 +1,47 @@
+# frozen_string_literal: true
+
+module PageObjects
+ module Components
+ class AdminDashboardSupport < PageObjects::Components::Base
+ SELECTOR = ".db-main [data-section-id='support']"
+
+ def has_section?
+ has_css?(SELECTOR)
+ end
+
+ def has_no_section?
+ has_no_css?(SELECTOR)
+ end
+
+ def has_headline?(text)
+ has_css?("#{SELECTOR} .db-section__subintro h3", text: text)
+ end
+
+ def has_kpi?(label)
+ has_css?("#{SELECTOR} .db-section__metric-label", text: label)
+ end
+
+ def has_topic_outcome?(label, count:)
+ within("#{SELECTOR} .db-support-outcomes__row", text: label) do
+ has_css?(".db-support-outcomes__share", exact_text: count.to_s)
+ end
+ end
+
+ def has_answerer?(label)
+ has_css?("#{SELECTOR} .db-support-answerers .db-whos-posting__bar-label", text: label)
+ end
+
+ def has_response_time_bucket?(label)
+ has_css?("#{SELECTOR} .db-support-response__label", text: label)
+ end
+
+ def has_category_filter?
+ has_css?("#{SELECTOR} .db-support__filter")
+ end
+
+ def has_no_category_filter?
+ has_no_css?("#{SELECTOR} .db-support__filter")
+ 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
new file mode 100644
index 00000000000..1cb696be016
--- /dev/null
+++ b/plugins/discourse-solved/test/javascripts/integration/support-test.gjs
@@ -0,0 +1,249 @@
+import { render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import SupportSection from "discourse/plugins/discourse-solved/admin/components/dashboard/support";
+
+function buildData(overrides = {}) {
+ return {
+ category_options: [],
+ kpis: {
+ resolution_rate: {
+ value: 72,
+ previous_value: 69,
+ report_type: "accepted_solutions",
+ report_query: { start_date: "2026-04-01", end_date: "2026-04-30" },
+ },
+ staff_involvement: { value: 19, previous_value: 25 },
+ avg_first_reply: { value: 11100, previous_value: 10620 },
+ },
+ headline: {
+ key: "healthy",
+ resolution_rate: 72,
+ resolution_direction: "up",
+ answerers_focus: "members",
+ answerers_share: 82,
+ first_reply_seconds: 11100,
+ first_reply_direction: "slower",
+ first_reply_delta_seconds: 480,
+ unanswered_count: 3,
+ },
+ topic_outcomes: { resolved: 1, in_progress: 0, unanswered: 3 },
+ whos_answering: {
+ rows: [{ type: "staff", count: 1, share: 100 }],
+ total: 1,
+ },
+ response_time_distribution: {
+ buckets: [
+ { key: "lt_1h", count: 1, share: 100 },
+ { key: "1_4h", count: 0, share: 0 },
+ { key: "4_24h", count: 0, share: 0 },
+ { key: "gt_24h", count: 0, share: 0 },
+ ],
+ trend: { direction: "flat", seconds: 0 },
+ },
+ ...overrides,
+ };
+}
+
+const startDate = new Date("2026-04-01");
+const endDate = new Date("2026-04-30");
+
+module("Integration | Component | Dashboard | Support", function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("renders a positive resolution-rate delta", async function (assert) {
+ const data = buildData();
+
+ await render(
+ <template>
+ <SupportSection
+ @data={{data}}
+ @startDate={{startDate}}
+ @endDate={{endDate}}
+ />
+ </template>
+ );
+
+ assert
+ .dom(".db-section__metric:first-child .db-delta.--pos")
+ .hasText("+3%");
+ });
+
+ test("renders a negative resolution-rate delta", async function (assert) {
+ const data = buildData({
+ kpis: {
+ resolution_rate: { value: 34, previous_value: 43, report_query: {} },
+ staff_involvement: { value: 81, previous_value: 62 },
+ avg_first_reply: { value: 51720, previous_value: 20520 },
+ },
+ });
+
+ await render(
+ <template>
+ <SupportSection
+ @data={{data}}
+ @startDate={{startDate}}
+ @endDate={{endDate}}
+ />
+ </template>
+ );
+
+ assert
+ .dom(".db-section__metric:first-child .db-delta.--neg")
+ .hasText("-9%");
+ });
+
+ test("renders a stable tag for metrics that did not change", async function (assert) {
+ const data = buildData({
+ kpis: {
+ resolution_rate: { value: 50, previous_value: 50, report_query: {} },
+ staff_involvement: { value: 20, previous_value: 20 },
+ avg_first_reply: { value: 11100, previous_value: 11100 },
+ },
+ });
+
+ await render(
+ <template>
+ <SupportSection
+ @data={{data}}
+ @startDate={{startDate}}
+ @endDate={{endDate}}
+ />
+ </template>
+ );
+
+ assert.dom(".db-section__metrics .db-pill").exists({ count: 3 });
+ assert.dom(".db-section__metrics .db-delta").doesNotExist();
+ });
+
+ test("shows no delta or stable tag when the previous period has no data", async function (assert) {
+ const data = buildData({
+ kpis: {
+ resolution_rate: { value: 40, previous_value: null, report_query: {} },
+ staff_involvement: { value: 30, previous_value: null },
+ avg_first_reply: { value: 11100, previous_value: null },
+ },
+ });
+
+ await render(
+ <template>
+ <SupportSection
+ @data={{data}}
+ @startDate={{startDate}}
+ @endDate={{endDate}}
+ />
+ </template>
+ );
+
+ assert.dom(".db-section__metrics .db-delta").doesNotExist();
+ assert.dom(".db-section__metrics .db-pill").doesNotExist();
+ });
+
+ test("composes a trend-aware headline summary from each metric's direction", async function (assert) {
+ const positive = buildData();
+
+ await render(
+ <template>
+ <SupportSection
+ @data={{positive}}
+ @startDate={{startDate}}
+ @endDate={{endDate}}
+ />
+ </template>
+ );
+
+ assert.dom(".db-section__subintro p").includesText("climbed to 72%");
+ assert
+ .dom(".db-section__subintro p")
+ .includesText("Members are handling 82%");
+
+ const negative = buildData({
+ headline: {
+ key: "struggling",
+ resolution_rate: 34,
+ resolution_direction: "down",
+ answerers_focus: "staff",
+ answerers_share: 81,
+ first_reply_seconds: 51720,
+ first_reply_direction: "slower",
+ first_reply_delta_seconds: 31200,
+ unanswered_count: 47,
+ },
+ });
+
+ await render(
+ <template>
+ <SupportSection
+ @data={{negative}}
+ @startDate={{startDate}}
+ @endDate={{endDate}}
+ />
+ </template>
+ );
+
+ assert.dom(".db-section__subintro p").includesText("dropped to 34%");
+ assert
+ .dom(".db-section__subintro p")
+ .includesText("47 topics from this period still have zero replies");
+ });
+
+ test("shows a placeholder when the average first reply is unknown", async function (assert) {
+ const data = buildData({
+ kpis: {
+ resolution_rate: { value: 0, previous_value: 0, report_query: {} },
+ staff_involvement: { value: 0, previous_value: 0 },
+ avg_first_reply: { value: null, previous_value: null },
+ },
+ });
+
+ await render(
+ <template>
+ <SupportSection
+ @data={{data}}
+ @startDate={{startDate}}
+ @endDate={{endDate}}
+ />
+ </template>
+ );
+
+ assert.dom(".db-section__metrics").exists();
+ assert.dom(".db-section__metrics").includesText("—");
+ });
+
+ test("shows the category filter only when more than one support category exists", async function (assert) {
+ const single = buildData({
+ category_options: [{ id: 1, name: "Support" }],
+ });
+
+ await render(
+ <template>
+ <SupportSection
+ @data={{single}}
+ @startDate={{startDate}}
+ @endDate={{endDate}}
+ />
+ </template>
+ );
+
+ assert.dom(".db-support__filter").doesNotExist("hidden with one category");
+
+ const multiple = buildData({
+ category_options: [
+ { id: 1, name: "Support" },
+ { id: 2, name: "Help" },
+ ],
+ });
+
+ await render(
+ <template>
+ <SupportSection
+ @data={{multiple}}
+ @startDate={{startDate}}
+ @endDate={{endDate}}
+ />
+ </template>
+ );
+
+ assert.dom(".db-support__filter").exists("shown with multiple categories");
+ });
+});
diff --git a/spec/services/admin_dashboard_section_configuration_spec.rb b/spec/services/admin_dashboard_section_configuration_spec.rb
index 2b6e51764a6..ac826edb380 100644
--- a/spec/services/admin_dashboard_section_configuration_spec.rb
+++ b/spec/services/admin_dashboard_section_configuration_spec.rb
@@ -163,4 +163,40 @@ describe AdminDashboardSectionConfiguration do
expect(result.first).to eq({ id: "engagement", visible: true })
end
end
+
+ describe "plugin sections" do
+ def stub_plugin_sections(sections)
+ DiscoursePluginRegistry.stubs(:admin_dashboard_sections).returns(sections)
+ end
+
+ it "includes an enabled plugin section, visible by default" do
+ stub_plugin_sections([{ id: "support", enabled: -> { true }, loader: -> {} }])
+
+ expect(described_class.all_known_section_ids).to include("support")
+ expect(described_class.sections).to include({ id: "support", visible: true })
+ expect(described_class.visible_section_ids).to include("support")
+ end
+
+ it "hides a plugin section whose enabled proc returns false" do
+ stub_plugin_sections([{ id: "support", enabled: -> { false }, loader: -> {} }])
+
+ expect(described_class.all_known_section_ids).not_to include("support")
+ expect(described_class.sections.map { |s| s[:id] }).not_to include("support")
+ expect(described_class.visible_section_ids).not_to include("support")
+ end
+
+ it "includes a plugin section that has no enabled proc" do
+ stub_plugin_sections([{ id: "support", enabled: nil, loader: -> {} }])
+
+ 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: -> {} }])
+
+ described_class.update([{ id: "support", visible: true }], actor: admin)
+
+ expect(described_class.sections.map { |s| s[:id] }).not_to include("support")
+ end
+ end
end
diff --git a/spec/services/admin_dashboard_section_loader_spec.rb b/spec/services/admin_dashboard_section_loader_spec.rb
index 9997b82ebe6..f1b5cb2ce1a 100644
--- a/spec/services/admin_dashboard_section_loader_spec.rb
+++ b/spec/services/admin_dashboard_section_loader_spec.rb
@@ -45,4 +45,57 @@ describe AdminDashboardSectionLoader do
)
end
end
+
+ describe "plugin sections" do
+ it "routes a registered plugin section id to its loader block" do
+ loader = ->(start_date:, end_date:, current_user:) do
+ { value: "support", user: current_user.id }
+ end
+ DiscoursePluginRegistry.stubs(:admin_dashboard_sections).returns(
+ [{ id: "support", enabled: -> { true }, loader: loader }],
+ )
+
+ expect(
+ described_class.build(
+ section_ids: ["support"],
+ current_user: admin,
+ start_date: "2026-05-01",
+ end_date: "2026-05-07",
+ ),
+ ).to eq([{ id: "support", data: { value: "support", user: admin.id } }])
+ end
+
+ it "returns nil data for an unknown section id" do
+ DiscoursePluginRegistry.stubs(:admin_dashboard_sections).returns([])
+
+ expect(
+ described_class.build(
+ section_ids: ["frobnitz"],
+ current_user: admin,
+ start_date: "2026-05-01",
+ end_date: "2026-05-07",
+ ),
+ ).to eq([{ id: "frobnitz", data: nil }])
+ end
+ end
+
+ describe ".pool_size" do
+ it "caps at the DB connection pool, reserving one for the request thread" do
+ ActiveRecord::Base.connection_pool.stubs(:size).returns(3)
+ expect(described_class.pool_size).to eq(2)
+ end
+
+ it "uses the desired count when the pool has room to spare" do
+ ActiveRecord::Base.connection_pool.stubs(:size).returns(100)
+ desired =
+ AdminDashboardSectionConfiguration::KNOWN_SECTIONS.size +
+ DiscoursePluginRegistry.admin_dashboard_sections.size
+ expect(described_class.pool_size).to eq(desired)
+ end
+
+ it "never drops below one" do
+ ActiveRecord::Base.connection_pool.stubs(:size).returns(1)
+ expect(described_class.pool_size).to eq(1)
+ end
+ end
end