Skip to content

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

FEATURE: Admin dashboard highlights to real data (#39895)

Natalie Tay728e70f507f3
diff --git a/app/assets/stylesheets/admin/admin_dashboard.scss b/app/assets/stylesheets/admin/admin_dashboard.scss
index 3ec770c4c84..1ec21b736f7 100644
--- a/app/assets/stylesheets/admin/admin_dashboard.scss
+++ b/app/assets/stylesheets/admin/admin_dashboard.scss
@@ -211,8 +211,8 @@ h1 {
.db-link-arrow {
top: 0;
- right: calc(var(--space-6) * -1);
- margin-left: var(--space-4);
+ inset-inline-end: calc(var(--space-6) * -1);
+ margin-inline-start: var(--space-4);
}
&:is(a):hover {
@@ -259,6 +259,25 @@ h1 {
}
}
+.db-highlights {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-2);
+
+ &__comparison {
+ align-self: flex-end;
+ font-size: var(--font-down-1-rem);
+ color: var(--primary-medium);
+ }
+
+ &__error {
+ flex: 1;
+ padding: var(--space-4);
+ color: var(--primary-medium);
+ font-size: var(--font-down-1-rem);
+ }
+}
+
.db-kpi {
position: relative;
display: flex;
@@ -267,7 +286,7 @@ h1 {
.db-link-arrow {
top: var(--space-4);
- right: var(--space-4);
+ inset-inline-end: var(--space-4);
}
&:hover {
diff --git a/app/controllers/admin/dashboard_controller.rb b/app/controllers/admin/dashboard_controller.rb
index 742a518866a..199603b0523 100644
--- a/app/controllers/admin/dashboard_controller.rb
+++ b/app/controllers/admin/dashboard_controller.rb
@@ -2,10 +2,22 @@
class Admin::DashboardController < Admin::StaffController
def index
- data = AdminDashboardIndexData.fetch_cached_stats
-
- if SiteSetting.version_checks?
- data.merge!(version_check: DiscourseUpdates.check_version.as_json)
+ if SiteSetting.dashboard_improvements
+ data = {
+ sections: {
+ highlights:
+ AdminDashboardHighlights.build(
+ start_date: params[:start_date],
+ end_date: params[:end_date],
+ ),
+ },
+ }
+ else
+ data = AdminDashboardIndexData.fetch_cached_stats
+
+ if SiteSetting.version_checks?
+ data.merge!(version_check: DiscourseUpdates.check_version.as_json)
+ end
end
render json: data
diff --git a/app/services/admin_dashboard_highlights.rb b/app/services/admin_dashboard_highlights.rb
new file mode 100644
index 00000000000..ad11f90432e
--- /dev/null
+++ b/app/services/admin_dashboard_highlights.rb
@@ -0,0 +1,108 @@
+# frozen_string_literal: true
+
+class AdminDashboardHighlights
+ DEFAULT_RANGE_DAYS = 30
+
+ KPI_REPORTS = {
+ new_signups: "signups",
+ dau_mau: "dau_by_mau",
+ new_contributors: "new_contributors",
+ }.freeze
+
+ def self.build(start_date:, end_date:)
+ new(start_date: start_date, end_date: end_date).build
+ end
+
+ def initialize(start_date:, end_date:)
+ @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
+ end
+
+ def build
+ { kpis: build_kpis }
+ end
+
+ private
+
+ attr_reader :start_date, :end_date
+
+ def parse_date(value)
+ return nil if value.blank?
+ Time.zone.parse(value.to_s)&.beginning_of_day
+ rescue ArgumentError, TypeError
+ nil
+ end
+
+ def build_kpis
+ core_kpis = KPI_REPORTS.map { |type, report| { type: type, report: report } }
+ all_kpis = core_kpis + DiscoursePluginRegistry.admin_dashboard_highlight_kpis
+
+ all_kpis.filter_map do |kpi|
+ next if kpi[:enabled].respond_to?(:call) && !kpi[:enabled].call
+ build_kpi(kpi[:type], kpi[:report])
+ end
+ end
+
+ def build_kpi(type, report_name)
+ args = { start_date: start_date, end_date: end_date, facets: %i[prev_period] }
+
+ report = Report.find_cached(report_name, args)
+ if report.nil?
+ report = Report.find(report_name, args)
+ Report.cache(report) if report && report.error.blank?
+ end
+
+ return nil if report.nil? || report_error?(report) || report_data(report).nil?
+
+ current = period_value(type, report_data(report))
+ previous = report_prev_period(report)
+
+ {
+ type: type,
+ value: current,
+ previous_value: previous,
+ percent_change: compute_percent_change(current, previous),
+ report_type: report_name,
+ report_query: {
+ start_date: start_date.to_date.iso8601,
+ end_date: end_date.to_date.iso8601,
+ },
+ }
+ end
+
+ # Report.find returns a Report object
+ # Report.find_cached returns the as_json hash (symbol-keyed).
+ # The accessors below cope with either
+ def report_error?(report_or_hash)
+ report_or_hash.is_a?(Hash) ? report_or_hash[:error].present? : report_or_hash.error.present?
+ end
+
+ def report_data(report_or_hash)
+ report_or_hash.is_a?(Hash) ? report_or_hash[:data] : report_or_hash.data
+ end
+
+ def report_prev_period(report_or_hash)
+ if report_or_hash.is_a?(Hash)
+ report_or_hash[:prev_period]
+ else
+ report_or_hash.prev_period
+ end
+ end
+
+ def period_value(type, data)
+ return nil if data.empty?
+
+ ys = data.map { |point| point[:y] }
+
+ if type == :dau_mau
+ (ys.sum(&:to_f) / ys.size).round(1)
+ else
+ ys.sum(&:to_i)
+ end
+ end
+
+ def compute_percent_change(current, previous)
+ return nil if previous.blank? || previous.zero? || current.blank?
+ ((current.to_f - previous) / previous * 100).round(2)
+ end
+end
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index 1e41d5994a5..6ae26f378ff 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -6836,6 +6836,24 @@ en:
engagement:
title: "Engagement"
+ highlights:
+ fetch_error: "Couldn't load highlights. Try refreshing the page."
+ kpi:
+ new_signups:
+ label: "New sign-ups"
+ tooltip: "Accounts created in this period, including unactivated and staged accounts."
+ dau_mau:
+ label: "DAU / MAU stickiness"
+ tooltip: 'The share of monthly active users who returned to the community in the last day. This shows how "sticky" your community is based on how often people come back.'
+ new_contributors:
+ label: "New contributors"
+ tooltip: "The number of members who made their first post in this period."
+ comparison:
+ last_7_days: "vs last 7 days"
+ last_30_days: "vs last 30 days"
+ last_3_months: "vs last 3 months"
+ previous_period: "vs previous period"
+
period:
last_7_days: "Last 7 days"
last_30_days: "Last 30 days"
diff --git a/frontend/discourse/admin/components/dashboard/highlights.gjs b/frontend/discourse/admin/components/dashboard/highlights.gjs
index cf481d167dd..c4488321171 100644
--- a/frontend/discourse/admin/components/dashboard/highlights.gjs
+++ b/frontend/discourse/admin/components/dashboard/highlights.gjs
@@ -1,62 +1,51 @@
+import Component from "@glimmer/component";
+import KpiTile from "discourse/admin/components/dashboard/kpi-tile";
import DashboardSection from "discourse/admin/components/dashboard/section";
-import dIcon from "discourse/ui-kit/helpers/d-icon";
import { i18n } from "discourse-i18n";
-<template>
- <DashboardSection
- @title={{i18n "admin.dashboard.sections.highlights.title"}}
- @description="Your community grew to 1,100 new members this month — and resolved 73% of questions without staff. Most growth came from a Hacker News spike on Mar 8–9."
- @layout="row"
- @startDate={{@startDate}}
- @endDate={{@endDate}}
- >
- <a class="db-kpi db-section__row-block">
- <div class="db-kpi__value">1,100</div>
- <div class="db-kpi__label">New sign-ups</div>
- <div class="db-delta --pos">+12%</div>
- <span class="db-link-arrow">{{dIcon "arrow-right"}}</span>
- </a>
- <a class="db-kpi db-section__row-block">
- <div class="db-kpi__value-row">
- <div class="db-kpi__value">21%</div>
- <span class="db-pill --pos">stable</span>
- </div>
- <div class="db-kpi__label">
- DAU / MAU stickiness
- <span
- class="db-section__info"
- aria-label="Daily active users divided by monthly active users. Higher means members come back more often."
- title="Daily active users divided by monthly active users. Higher means members come back more often."
- >{{dIcon "far-circle-question"}}</span>
- </div>
- <div class="db-delta --pos">+0.4pts</div>
- <span class="db-link-arrow">{{dIcon "arrow-right"}}</span>
- </a>
- <a class="db-kpi db-section__row-block">
- <div class="db-kpi__value">374</div>
- <div class="db-kpi__label">
- New contributors
- <span
- class="db-section__info"
- aria-label="Members who posted, replied, or reacted for the first time this period."
- title="Members who posted, replied, or reacted for the first time this period."
- >{{dIcon "far-circle-question"}}</span>
- </div>
- <div class="db-delta --pos">+6%</div>
- <span class="db-link-arrow">{{dIcon "arrow-right"}}</span>
- </a>
- <a class="db-kpi db-section__row-block">
- <div class="db-kpi__value">73%</div>
- <div class="db-kpi__label">
- Questions resolved
- <span
- class="db-section__info"
- aria-label="Topics in support categories with a marked solution, divided by total topics."
- title="Topics in support categories with a marked solution, divided by total topics."
- >{{dIcon "far-circle-question"}}</span>
- </div>
- <div class="db-delta --pos">+1%</div>
- <span class="db-link-arrow">{{dIcon "arrow-right"}}</span>
- </a>
- </DashboardSection>
-</template>
+const PRESET_PERIODS = ["last_7_days", "last_30_days", "last_3_months"];
+
+export default class Highlights extends Component {
+ get comparisonLabel() {
+ const key = PRESET_PERIODS.includes(this.args.period)
+ ? this.args.period
+ : "previous_period";
+ return i18n(`admin.dashboard.highlights.comparison.${key}`);
+ }
+
+ get hasKpis() {
+ return this.args.highlights?.kpis?.length > 0;
+ }
+
+ <template>
+ <div class="db-highlights">
+ <DashboardSection
+ @title={{i18n "admin.dashboard.sections.highlights.title"}}
+ @layout="row"
+ @startDate={{@startDate}}
+ @endDate={{@endDate}}
+ >
+ {{#if @fetchError}}
+ <div class="db-highlights__error" role="alert">
+ {{i18n "admin.dashboard.highlights.fetch_error"}}
+ </div>
+ {{else}}
+ {{#each @highlights.kpis as |kpi|}}
+ <KpiTile
+ @type={{kpi.type}}
+ @value={{kpi.value}}
+ @previousValue={{kpi.previous_value}}
+ @percentChange={{kpi.percent_change}}
+ @reportType={{kpi.report_type}}
+ @reportQuery={{kpi.report_query}}
+ @comparisonLabel={{this.comparisonLabel}}
+ />
+ {{/each}}
+ {{/if}}
+ </DashboardSection>
+ {{#if this.hasKpis}}
+ <div class="db-highlights__comparison">{{this.comparisonLabel}}</div>
+ {{/if}}
+ </div>
+ </template>
+}
diff --git a/frontend/discourse/admin/components/dashboard/kpi-tile.gjs b/frontend/discourse/admin/components/dashboard/kpi-tile.gjs
new file mode 100644
index 00000000000..a827698802e
--- /dev/null
+++ b/frontend/discourse/admin/components/dashboard/kpi-tile.gjs
@@ -0,0 +1,111 @@
+import Component from "@glimmer/component";
+import { concat, hash } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { LinkTo } from "@ember/routing";
+import DTooltip from "discourse/float-kit/components/d-tooltip";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import I18n, { i18n } from "discourse-i18n";
+
+const PERCENTAGE_KPIS = ["dau_mau"];
+
+export default class KpiTile extends Component {
+ get isPercentage() {
+ return PERCENTAGE_KPIS.includes(this.args.type);
+ }
+
+ get displayValue() {
+ const value = this.args.value;
+ if (value == null) {
+ return "—";
+ }
+ if (this.isPercentage) {
+ return `${I18n.toNumber(value, { precision: 1 })}%`;
+ }
+ return I18n.toNumber(value, { precision: 0 });
+ }
+
+ get label() {
+ return i18n(`admin.dashboard.highlights.kpi.${this.args.type}.label`);
+ }
+
+ get tooltip() {
+ return i18n(`admin.dashboard.highlights.kpi.${this.args.type}.tooltip`);
+ }
+
+ get hasDelta() {
+ return this.args.percentChange != null;
+ }
+
+ get deltaClass() {
+ return this.args.percentChange >= 0 ? "--pos" : "--neg";
+ }
+
+ get deltaText() {
+ const value = this.args.percentChange;
+ const abs = Math.abs(value);
+
+ if (abs > 0 && abs < 1) {
+ const sign = value > 0 ? "+" : "-";
+ return `${sign}${I18n.toNumber(abs, { precision: 1 })}%`;
+ }
+
+ const rounded = Math.round(value);
+ const sign = rounded > 0 ? "+" : "";
+ return `${sign}${I18n.toNumber(rounded, { precision: 0 })}%`;
+ }
+
+ get ariaLabel() {
+ const parts = [this.label, this.displayValue];
+ if (this.hasDelta) {
+ const trend = this.args.comparisonLabel
+ ? `${this.deltaText} ${this.args.comparisonLabel}`
+ : this.deltaText;
+ parts.push(trend);
+ }
+ return parts.join(", ");
+ }
+
+ get reportQuery() {
+ return this.args.reportQuery ?? {};
+ }
+
+ @action
+ stopPropagation(event) {
+ // tooltip lives inside the LinkTo; without this, clicking the trigger
+ // also navigates to the report
+ event.stopPropagation();
+ }
+
+ <template>
+ <LinkTo
+ class="db-kpi db-section__row-block"
+ @route="adminReports.show"
+ @model={{@reportType}}
+ @query={{hash
+ start_date=this.reportQuery.start_date
+ end_date=this.reportQuery.end_date
+ }}
+ aria-label={{this.ariaLabel}}
+ >
+ <div class="db-kpi__value">{{this.displayValue}}</div>
+ <div class="db-kpi__label">
+ {{this.label}}
+ <DTooltip
+ class="db-kpi__tooltip"
+ @icon="circle-question"
+ @content={{this.tooltip}}
+ {{on "click" this.stopPropagation}}
+ />
+ </div>
+ {{#if this.hasDelta}}
+ <div
+ class={{concat "db-delta " this.deltaClass}}
+ >{{this.deltaText}}</div>
+ {{/if}}
+ <span class="db-link-arrow" aria-hidden="true">{{dIcon
+ "arrow-right"
+ }}</span>
+ </LinkTo>
+ </template>
+}
diff --git a/frontend/discourse/admin/components/redesigned-admin-dashboard.gjs b/frontend/discourse/admin/components/redesigned-admin-dashboard.gjs
index 2a5b519a7a6..ba1a78f07e5 100644
--- a/frontend/discourse/admin/components/redesigned-admin-dashboard.gjs
+++ b/frontend/discourse/admin/components/redesigned-admin-dashboard.gjs
@@ -73,7 +73,14 @@ const RedesignedAdminDashboard = <template>
</div>
<div class="db-main">
- <DashboardHighlights @startDate={{@startDate}} @endDate={{@endDate}} />
+ <DashboardHighlights
+ @highlights={{@sections.highlights}}
+ @period={{@period}}
+ @loading={{@loadingSections}}
+ @fetchError={{@sectionsFetchError}}
+ @startDate={{@startDate}}
+ @endDate={{@endDate}}
+ />
<DashboardReports @startDate={{@startDate}} @endDate={{@endDate}} />
<DashboardTraffic @startDate={{@startDate}} @endDate={{@endDate}} />
<DashboardEngagement @startDate={{@startDate}} @endDate={{@endDate}} />
diff --git a/frontend/discourse/admin/controllers/admin/dashboard.js b/frontend/discourse/admin/controllers/admin/dashboard.js
index 16aa634a2ec..477e7ba2fa3 100644
--- a/frontend/discourse/admin/controllers/admin/dashboard.js
+++ b/frontend/discourse/admin/controllers/admin/dashboard.js
@@ -24,12 +24,16 @@ export default class AdminDashboardController extends Controller {
@tracked range = DEFAULT_PERIOD;
@tracked start_date = null;
@tracked end_date = null;
+ @tracked sections = null;
+ @tracked loadingSections = false;
+ @tracked sectionsFetchError = false;
@autoTrackedArray problems;
queryParams = ["range", "start_date", "end_date"];
isLoading = false;
dashboardFetchedAt = null;
+ _sectionsLoadId = 0;
get safePeriod() {
if (!VALID_PERIODS.includes(this.range)) {
@@ -66,6 +70,7 @@ export default class AdminDashboardController extends Controller {
this.range = period;
this.start_date = null;
this.end_date = null;
+ this.fetchSections();
}
@action
@@ -73,6 +78,33 @@ export default class AdminDashboardController extends Controller {
this.range = PERIOD_CUSTOM;
this.start_date = moment(startDate).format("YYYY-MM-DD");
this.end_date = moment(endDate).format("YYYY-MM-DD");
+ this.fetchSections();
+ }
+
+ async fetchSections() {
+ const id = ++this._sectionsLoadId;
+ this.loadingSections = true;
+ this.sectionsFetchError = false;
+
+ try {
+ const model = await AdminDashboard.fetch({
+ startDate: this.startDate,
+ endDate: this.endDate,
+ });
+ if (id !== this._sectionsLoadId) {
+ return;
+ }
+ this.sections = model.sections;
+ } catch {
+ if (id !== this._sectionsLoadId) {
+ return;
+ }
+ this.sectionsFetchError = true;
+ } finally {
+ if (id === this._sectionsLoadId) {
+ this.loadingSections = false;
+ }
+ }
}
@computed("siteSettings.version_checks")
diff --git a/frontend/discourse/admin/models/admin-dashboard.js b/frontend/discourse/admin/models/admin-dashboard.js
index 651ab673d74..e665cfc3f00 100644
--- a/frontend/discourse/admin/models/admin-dashboard.js
+++ b/frontend/discourse/admin/models/admin-dashboard.js
@@ -8,12 +8,21 @@ const GENERAL_ATTRIBUTES = [
];
export default class AdminDashboard extends EmberObject {
- static async fetch() {
- const json = await ajax("/admin/dashboard.json");
+ static async fetch({ startDate, endDate } = {}) {
+ const data = {};
+ if (startDate) {
+ data.start_date = moment(startDate).format("YYYY-MM-DD");
+ }
+ if (endDate) {
+ data.end_date = moment(endDate).format("YYYY-MM-DD");
+ }
+
+ const json = await ajax("/admin/dashboard.json", { data });
const model = AdminDashboard.create();
model.setProperties({
version_check: json.version_check,
+ sections: json.sections,
});
return model;
diff --git a/frontend/discourse/admin/routes/admin/dashboard.js b/frontend/discourse/admin/routes/admin/dashboard.js
index 2ea9a38d308..3287db16430 100644
--- a/frontend/discourse/admin/routes/admin/dashboard.js
+++ b/frontend/discourse/admin/routes/admin/dashboard.js
@@ -1,15 +1,25 @@
+import { service } from "@ember/service";
import { scrollTop } from "discourse/lib/scroll-top";
import DiscourseRoute from "discourse/routes/discourse";
import { i18n } from "discourse-i18n";
export default class AdminDashboardRoute extends DiscourseRoute {
+ @service siteSettings;
+
titleToken() {
return i18n("admin.config.dashboard.title");
}
activate() {
- this.controllerFor("admin.dashboard").fetchProblems();
- this.controllerFor("admin.dashboard").fetchDashboard();
+ const controller = this.controllerFor("admin.dashboard");
+
+ if (this.siteSettings.dashboard_improvements) {
+ controller.fetchSections();
+ } else {
+ controller.fetchProblems();
+ controller.fetchDashboard();
+ }
+
scrollTop();
}
}
diff --git a/frontend/discourse/admin/templates/admin/dashboard.gjs b/frontend/discourse/admin/templates/admin/dashboard.gjs
index 2e02aafb1c4..0b5d876d663 100644
--- a/frontend/discourse/admin/templates/admin/dashboard.gjs
+++ b/frontend/discourse/admin/templates/admin/dashboard.gjs
@@ -15,6 +15,9 @@ export default <template>
@endDate={{@controller.endDate}}
@setPeriod={{@controller.setPeriod}}
@setCustomDateRange={{@controller.setCustomDateRange}}
+ @sections={{@controller.sections}}
+ @loadingSections={{@controller.loadingSections}}
+ @sectionsFetchError={{@controller.sectionsFetchError}}
/>
{{else}}
<PluginOutlet @name="admin-dashboard-top" @connectorTagName="div" />
diff --git a/frontend/discourse/tests/integration/components/dashboard/highlights-test.gjs b/frontend/discourse/tests/integration/components/dashboard/highlights-test.gjs
new file mode 100644
index 00000000000..1639de2977f
--- /dev/null
+++ b/frontend/discourse/tests/integration/components/dashboard/highlights-test.gjs
@@ -0,0 +1,207 @@
+import { render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import DashboardHighlights from "discourse/admin/components/dashboard/highlights";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+
+module("Integration | Component | Dashboard | Highlights", function (hooks) {
+ setupRenderingTest(hooks);
+
+ const start = new Date("2026-04-01");
+ const end = new Date("2026-04-30");
+ const reportQuery = { start_date: "2026-04-01", end_date: "2026-04-30" };
+
+ test("renders one KpiTile per kpi in the response", async function (assert) {
+ const highlights = {
+ kpis: [
+ {
+ type: "new_signups",
+ value: 1100,
+ percent_change: 12,
+ report_type: "signups",
+ report_query: reportQuery,
+ },
+ {
+ type: "dau_mau",
+ value: 21.6,
+ percent_change: 1.9,
+ report_type: "dau_by_mau",
+ report_query: reportQuery,
+ },
+ {
+ type: "new_contributors",
+ value: 374,
+ percent_change: 6,
+ report_type: "new_contributors",
+ report_query: reportQuery,
+ },
+ ],
+ };
+
+ await render(
+ <template>
+ <DashboardHighlights
+ @highlights={{highlights}}
+ @startDate={{start}}
+ @endDate={{end}}
+ />
+ </template>
+ );
+
+ assert.dom(".db-kpi").exists({ count: 3 });
+ assert
+ .dom('a.db-kpi[href*="/admin/reports/signups"] .db-kpi__value')
+ .hasText("1,100");
+ assert
+ .dom('a.db-kpi[href*="/admin/reports/dau_by_mau"] .db-kpi__value')
+ .hasText("21.6%");
+ assert
+ .dom('a.db-kpi[href*="/admin/reports/new_contributors"] .db-kpi__value')
+ .hasText("374");
+ });
+
+ test("omits accepted_solutions when not in the kpis array", async function (assert) {
+ const highlights = {
+ kpis: [
+ {
+ type: "new_signups",
+ value: 1100,
+ percent_change: 12,
+ report_type: "signups",
+ report_query: reportQuery,
+ },
+ {
+ type: "new_contributors",
+ value: 374,
+ percent_change: 6,
+ report_type: "new_contributors",
+ report_query: reportQuery,
+ },
+ ],
+ };
+
+ await render(
+ <template>
+ <DashboardHighlights
+ @highlights={{highlights}}
+ @startDate={{start}}
+ @endDate={{end}}
+ />
+ </template>
+ );
+
+ assert.dom(".db-kpi").exists({ count: 2 });
+ assert
+ .dom('a.db-kpi[href*="/admin/reports/accepted_solutions"]')
+ .doesNotExist();
+ });
+
+ test("renders no tiles when kpis is empty", async function (assert) {
+ const highlights = { kpis: [] };
+
+ await render(
+ <template>
+ <DashboardHighlights
+ @highlights={{highlights}}
+ @startDate={{start}}
+ @endDate={{end}}
+ />
+ </template>
+ );
+
+ assert.dom(".db-kpi").doesNotExist();
+ assert.dom(".db-highlights__comparison").doesNotExist();
+ });
+
+ test("renders the comparison label tied to the active period", async function (assert) {
+ const highlights = {
+ kpis: [
+ {
+ type: "new_signups",
+ value: 1100,
+ percent_change: 12,
+ report_type: "signups",
+ report_query: reportQuery,
+ },
+ ],
+ };
+
+ await render(
+ <template>
+ <DashboardHighlights
+ @highlights={{highlights}}
+ @period="last_30_days"
+ @startDate={{start}}
+ @endDate={{end}}
+ />
+ </template>
+ );
+
+ assert.dom(".db-highlights__comparison").hasText("vs last 30 days");
+ assert
+ .dom("a.db-kpi")
+ .hasAttribute(
+ "aria-label",
+ /vs last 30 days$/,
+ "comparison label flows into the child tile's aria-label"
+ );
+ });
+
+ test("falls back to 'vs previous period' for custom ranges", async function (assert) {
+ const highlights = {
+ kpis: [
+ {
+ type: "new_signups",
+ value: 1100,
+ percent_change: 12,
+ report_type: "signups",
+ report_query: reportQuery,
+ },
+ ],
+ };
+
+ await render(
+ <template>
+ <DashboardHighlights
+ @highlights={{highlights}}
+ @period="custom"
+ @startDate={{start}}
+ @endDate={{end}}
+ />
+ </template>
+ );
+
+ assert.dom(".db-highlights__comparison").hasText("vs previous period");
+ });
+
+ test("does not render a description headline", async function (assert) {
+ const highlights = { kpis: [] };
+
+ await render(
+ <template>
+ <DashboardHighlights
+ @highlights={{highlights}}
+ @startDate={{start}}
+ @endDate={{end}}
+ />
+ </template>
+ );
+
+ assert.dom(".db-section__intro").doesNotExist();
+ });
+
+ test("renders an inline error when the fetch failed", async function (assert) {
+ await render(
+ <template>
+ <DashboardHighlights
+ @highlights={{null}}
+ @fetchError={{true}}
+ @startDate={{start}}
+ @endDate={{end}}
+ />
+ </template>
+ );
+
+ assert.dom(".db-highlights__error").exists();
+ assert.dom(".db-kpi").doesNotExist();
+ });
+});
diff --git a/frontend/discourse/tests/integration/components/dashboard/kpi-tile-test.gjs b/frontend/discourse/tests/integration/components/dashboard/kpi-tile-test.gjs
new file mode 100644
index 00000000000..330e9cdc075
--- /dev/null
+++ b/frontend/discourse/tests/integration/components/dashboard/kpi-tile-test.gjs
@@ -0,0 +1,242 @@
+import { render, triggerEvent } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import KpiTile from "discourse/admin/components/dashboard/kpi-tile";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+
+module("Integration | Component | Dashboard | KpiTile", function (hooks) {
+ setupRenderingTest(hooks);
+
+ const reportQuery = { start_date: "2026-04-01", end_date: "2026-04-30" };
+
+ test("renders the label and formatted value", async function (assert) {
+ await render(
+ <template>
+ <KpiTile
+ @type="new_signups"
+ @value={{1100}}
+ @reportType="signups"
+ @reportQuery={{reportQuery}}
+ />
+ </template>
+ );
+
+ assert.dom(".db-kpi__value").hasText("1,100");
+ assert.dom(".db-kpi__label").includesText("New sign-ups");
+ });
+
+ test("formats percentage KPIs with a percent suffix and 1 decimal", async function (assert) {
+ await render(
+ <template>
+ <KpiTile
+ @type="dau_mau"
+ @value={{21.6}}
+ @reportType="dau_by_mau"
+ @reportQuery={{reportQuery}}
+ />
+ </template>
+ );
+
+ assert.dom(".db-kpi__value").hasText("21.6%");
+ assert.dom(".db-kpi__label").includesText("DAU / MAU stickiness");
+ });
+
+ test("renders an em dash when the value is null", async function (assert) {
+ await render(
+ <template>
+ <KpiTile
+ @type="new_signups"
+ @value={{null}}
+ @reportType="signups"
+ @reportQuery={{reportQuery}}
+ />
+ </template>
+ );
+
+ assert.dom(".db-kpi__value").hasText("—");
+ });
+
+ test("hides the delta when percentChange is null", async function (assert) {
+ await render(
+ <template>
+ <KpiTile
+ @type="new_signups"
+ @value={{1100}}
+ @percentChange={{null}}
+ @reportType="signups"
+ @reportQuery={{reportQuery}}
+ />
+ </template>
+ );
+
+ assert.dom(".db-delta").doesNotExist();
+ });
+
+ test("renders the positive delta with --pos class", async function (assert) {
+ await render(
+ <template>
+ <KpiTile
+ @type="new_signups"
+ @value={{1100}}
+ @percentChange={{12.02}}
+ @reportType="signups"
+ @reportQuery={{reportQuery}}
+ />
+ </template>
+ );
+
+ assert.dom(".db-delta").hasClass("--pos");
+ assert.dom(".db-delta").hasText("+12%");
+ });
+
+ test("renders sub-1% positive deltas with one decimal", async function (assert) {
+ await render(
+ <template>
+ <KpiTile
+ @type="new_signups"
+ @value={{1100}}
+ @percentChange={{0.4}}
+ @reportType="signups"
+ @reportQuery={{reportQuery}}
+ />
+ </template>
+ );
+
+ assert.dom(".db-delta").hasClass("--pos");
+ assert.dom(".db-delta").hasText("+0.4%");
+ });
+
+ test("renders sub-1% negative deltas with one decimal and a minus sign", async function (assert) {
+ await render(
+ <template>
+ <KpiTile
+ @type="new_signups"
+ @value={{1100}}
+ @percentChange={{-0.4}}
+ @reportType="signups"
+ @reportQuery={{reportQuery}}
+ />
+ </template>
+ );
+
+ assert.dom(".db-delta").hasClass("--neg");
+ assert.dom(".db-delta").hasText("-0.4%");
+ });
+
+ test("renders exact zero deltas without a sign", async function (assert) {
+ await render(
+ <template>
+ <KpiTile
+ @type="new_signups"
+ @value={{1100}}
+ @percentChange={{0}}
+ @reportType="signups"
+ @reportQuery={{reportQuery}}
+ />
+ </template>
+ );
+
+ assert.dom(".db-delta").hasText("0%");
+ });
+
+ test("renders the negative delta with --neg class", async function (assert) {
+ await render(
+ <template>
+ <KpiTile
+ @type="new_signups"
+ @value={{142}}
+ @percentChange={{-38.5}}
+ @reportType="signups"
+ @reportQuery={{reportQuery}}
+ />
+ </template>
+ );
+
+ assert.dom(".db-delta").hasClass("--neg");
+ assert.dom(".db-delta").hasText("-38%");
+ });
+
+ test("links to the report route with the report query params", async function (assert) {
+ await render(
+ <template>
+ <KpiTile
+ @type="new_signups"
+ @value={{1100}}
+ @reportType="signups"
+ @reportQuery={{reportQuery}}
+ />
+ </template>
+ );
+
+ const href = document.querySelector("a.db-kpi").getAttribute("href");
+ assert.true(
+ href.includes("/admin/reports/signups"),
+ "links to the report route"
+ );
+ assert.true(
+ href.includes("start_date=2026-04-01"),
+ "carries the start_date query param"
+ );
+ assert.true(
+ href.includes("end_date=2026-04-30"),
+ "carries the end_date query param"
+ );
+ });
+
+ test("includes the trend in the aria-label", async function (assert) {
+ await render(
+ <template>
+ <KpiTile
+ @type="new_signups"
+ @value={{1100}}
+ @percentChange={{12}}
+ @reportType="signups"
+ @reportQuery={{reportQuery}}
+ />
+ </template>
+ );
+
+ assert
+ .dom("a.db-kpi")
+ .hasAttribute("aria-label", "New sign-ups, 1,100, +12%");
+ });
+
+ test("renders an accessible tooltip with the KPI description", async function (assert) {
+ await render(
+ <template>
+ <KpiTile
+ @type="new_signups"
+ @value={{1100}}
+ @reportType="signups"
+ @reportQuery={{reportQuery}}
+ />
+ </template>
+ );
+
+ assert.dom(".db-kpi__tooltip").exists();
+ await triggerEvent(".db-kpi__tooltip", "pointermove");
+ assert
+ .dom(".fk-d-tooltip__content")
+ .includesText(
+ "Accounts created in this period, including unactivated and staged accounts."
+ );
+ });
+
+ test("appends the comparison label to the trend in aria-label", async function (assert) {
+ await render(
+ <template>
+ <KpiTile
+ @type="new_signups"
+ @value={{1100}}
+ @percentChange={{12}}
+ @reportType="signups"
+ @reportQuery={{reportQuery}}
+ @comparisonLabel="vs last 30 days"
+ />
+ </template>
+ );
+
+ assert
+ .dom("a.db-kpi")
+ .hasAttribute("aria-label", "New sign-ups, 1,100, +12% vs last 30 days");
+ });
+});
diff --git a/lib/discourse_plugin_registry.rb b/lib/discourse_plugin_registry.rb
index 6404d3f505a..02fbb55d577 100644
--- a/lib/discourse_plugin_registry.rb
+++ b/lib/discourse_plugin_registry.rb
@@ -119,6 +119,7 @@ class DiscoursePluginRegistry
define_filtered_register :search_handlers
define_filtered_register :stats
+ define_filtered_register :admin_dashboard_highlight_kpis
define_filtered_register :bookmarkables
define_filtered_register :list_suggested_for_providers
diff --git a/lib/plugin/instance.rb b/lib/plugin/instance.rb
index efb54183b98..59e9c85d7ae 100644
--- a/lib/plugin/instance.rb
+++ b/lib/plugin/instance.rb
@@ -1225,6 +1225,23 @@ class Plugin::Instance
DiscoursePluginRegistry.register_stat(stat, self)
end
+ # Registers a KPI tile in the admin dashboard "Highlights" section
+ # (gated by SiteSetting.dashboard_improvements). The KPI is rendered as a
+ # tile linking to /admin/reports/:report.
+ #
+ # @param type [Symbol] unique identifier for the KPI. Used as the i18n key
+ # (admin.dashboard.highlights.kpi.<type>.label / .tooltip) and to
+ # namespace the percentage-formatting client-side.
+ # @param report [String] the underlying Report.find type.
+ # @param enabled [Proc] optional gate evaluated on every dashboard build.
+ # Return false to omit the KPI without disabling the plugin entirely.
+ def register_admin_dashboard_highlight_kpi(type:, report:, enabled: nil)
+ DiscoursePluginRegistry.register_admin_dashboard_highlight_kpi(
+ { type: type, report: report, enabled: enabled },
+ self,
+ )
+ end
+
##
# Used to register data sources for HashtagAutocompleteService to look
# up results based on a #hashtag string.
diff --git a/plugins/discourse-solved/config/locales/client.en.yml b/plugins/discourse-solved/config/locales/client.en.yml
index cafb8176437..168c338783f 100644
--- a/plugins/discourse-solved/config/locales/client.en.yml
+++ b/plugins/discourse-solved/config/locales/client.en.yml
@@ -4,6 +4,12 @@ en:
site_settings:
categories:
discourse_solved: "Discourse Solved"
+ dashboard:
+ highlights:
+ kpi:
+ accepted_solutions:
+ label: "Accepted solutions"
+ tooltip: "The number of topics that had a post marked as the solution in this period."
js:
notifications:
alt:
diff --git a/plugins/discourse-solved/plugin.rb b/plugins/discourse-solved/plugin.rb
index 7aa16608c8e..1c85b95e13a 100644
--- a/plugins/discourse-solved/plugin.rb
+++ b/plugins/discourse-solved/plugin.rb
@@ -166,8 +166,40 @@ after_initialize do
.where("discourse_solved_solved_topics.created_at >= ?", report.start_date - 30.days)
.where("discourse_solved_solved_topics.created_at <= ?", report.start_date)
.count
+
+ if report.facets.include?(:prev_period)
+ report.prev_period =
+ accepted_solutions
+ .where("discourse_solved_solved_topics.created_at >= ?", report.prev_start_date)
+ .where("discourse_solved_solved_topics.created_at < ?", report.prev_end_date)
+ .count
+ end
end
+ register_admin_dashboard_highlight_kpi(
+ type: :accepted_solutions,
+ report: "accepted_solutions",
+ enabled: -> do
+ next true if SiteSetting.allow_solved_on_all_topics
+
+ Discourse
+ .cache
+ .fetch("solved_admin_dashboard_kpi_enabled", expires_in: 5.minutes) do
+ Category
+ .joins(
+ "INNER JOIN category_custom_fields ON category_custom_fields.category_id = categories.id",
+ )
+ .where(
+ category_custom_fields: {
+ name: DiscourseSolved::ENABLE_ACCEPTED_ANSWERS_CUSTOM_FIELD,
+ value: "true",
+ },
+ )
+ .exists?
+ end
+ 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/integration/admin_dashboard_highlight_kpi_spec.rb b/plugins/discourse-solved/spec/integration/admin_dashboard_highlight_kpi_spec.rb
new file mode 100644
index 00000000000..23863b89655
--- /dev/null
+++ b/plugins/discourse-solved/spec/integration/admin_dashboard_highlight_kpi_spec.rb
@@ -0,0 +1,44 @@
+# frozen_string_literal: true
+
+describe "discourse-solved admin dashboard highlight KPI" do
+ def lookup_kpi
+ DiscoursePluginRegistry.admin_dashboard_highlight_kpis.find do |kpi|
+ kpi[:type] == :accepted_solutions
+ end
+ end
+
+ before do
+ SiteSetting.allow_solved_on_all_topics = false
+ Discourse.cache.clear
+ end
+
+ after { Discourse.cache.clear }
+
+ it "is registered with the plugin registry" do
+ expect(lookup_kpi).to be_present
+ expect(lookup_kpi[:report]).to eq("accepted_solutions")
+ end
+
+ describe "enabled lambda" do
+ it "returns false when no category opts in and the global setting is off" do
+ expect(lookup_kpi[:enabled].call).to eq(false)
+ end
+
+ it "returns true when allow_solved_on_all_topics is enabled" do
+ SiteSetting.allow_solved_on_all_topics = true
+
+ expect(lookup_kpi[:enabled].call).to eq(true)
+ end
+
+ it "returns true when at least one category opts in via custom field" do
+ category = Fabricate(:category)
+ CategoryCustomField.create!(
+ category_id: category.id,
+ name: DiscourseSolved::ENABLE_ACCEPTED_ANSWERS_CUSTOM_FIELD,
+ value: "true",
+ )
+
+ expect(lookup_kpi[:enabled].call).to eq(true)
+ end
+ end
+end
diff --git a/plugins/discourse-solved/spec/lib/admin_dashboard_highlights_integration_spec.rb b/plugins/discourse-solved/spec/lib/admin_dashboard_highlights_integration_spec.rb
new file mode 100644
index 00000000000..121ea59f015
--- /dev/null
+++ b/plugins/discourse-solved/spec/lib/admin_dashboard_highlights_integration_spec.rb
@@ -0,0 +1,110 @@
+# frozen_string_literal: true
+
+describe AdminDashboardHighlights do
+ before do
+ freeze_time(Time.zone.local(2026, 4, 28, 12, 0, 0))
+ Discourse.cache.clear
+ end
+
+ context "when solved is enabled" do
+ before { SiteSetting.solved_enabled = true }
+
+ it "omits the KPI when no category enables accepted answers" do
+ Fabricate(:category)
+
+ result = AdminDashboardHighlights.build(start_date: "2026-04-01", end_date: "2026-04-28")
+ expect(result[:kpis].map { |k| k[:type] }).not_to include(:accepted_solutions)
+ end
+
+ it "includes the KPI when at least one category supports accepted answers" do
+ category = Fabricate(:category)
+ category.custom_fields[DiscourseSolved::ENABLE_ACCEPTED_ANSWERS_CUSTOM_FIELD] = "true"
+ category.save!
+
+ result = AdminDashboardHighlights.build(start_date: "2026-04-01", end_date: "2026-04-28")
+ kpi = result[:kpis].find { |k| k[:type] == :accepted_solutions }
+
+ expect(kpi).to be_present
+ expect(kpi[:report_type]).to eq("accepted_solutions")
+ end
+ end
+
+ context "when solved is disabled" do
+ before { SiteSetting.solved_enabled = false }
+
+ it "omits the KPI even if a category enables accepted answers" do
+ category = Fabricate(:category)
+ category.custom_fields[DiscourseSolved::ENABLE_ACCEPTED_ANSWERS_CUSTOM_FIELD] = "true"
+ category.save!
+
+ result = AdminDashboardHighlights.build(start_date: "2026-04-01", end_date: "2026-04-28")
+ expect(result[:kpis].map { |k| k[:type] }).not_to include(:accepted_solutions)
+ end
+ end
+
+ describe "accepted_solutions report prev_period facet" do
+ fab!(:user)
+ fab!(:topic)
+ fab!(:post) { Fabricate(:post, topic: topic) }
+
+ it "populates prev_period when the facet is requested" do
+ DiscourseSolved::SolvedTopic.create!(
+ topic: topic,
+ answer_post: post,
+ accepter: user,
+ created_at: Time.zone.local(2026, 3, 15),
+ )
+
+ report =
+ Report.find(
+ "accepted_solutions",
+ start_date: Time.zone.local(2026, 4, 1),
+ end_date: Time.zone.local(2026, 4, 28),
+ facets: %i[prev_period],
+ )
+
+ expect(report.prev_period).to be >= 1
+ end
+
+ it "excludes deleted topics from prev_period" do
+ DiscourseSolved::SolvedTopic.create!(
+ topic: topic,
+ answer_post: post,
+ accepter: user,
+ created_at: Time.zone.local(2026, 3, 15),
+ )
+ topic.trash!
+
+ report =
+ Report.find(
+ "accepted_solutions",
+ start_date: Time.zone.local(2026, 4, 1),
+ end_date: Time.zone.local(2026, 4, 28),
+ facets: %i[prev_period],
+ )
+
+ expect(report.prev_period.to_i).to eq(0)
+ end
+
+ it "excludes private message topics from prev_period" do
+ pm = Fabricate(:private_message_topic)
+ pm_post = Fabricate(:post, topic: pm)
+ DiscourseSolved::SolvedTopic.create!(
+ topic: pm,
+ answer_post: pm_post,
+ accepter: user,
+ created_at: Time.zone.local(2026, 3, 15),
+ )
+
+ report =
+ Report.find(
+ "accepted_solutions",
+ start_date: Time.zone.local(2026, 4, 1),
+ end_date: Time.zone.local(2026, 4, 28),
+ facets: %i[prev_period],
+ )
+
+ expect(report.prev_period.to_i).to eq(0)
+ end
+ end
+end
diff --git a/spec/requests/admin/dashboard_controller_spec.rb b/spec/requests/admin/dashboard_controller_spec.rb
index 7d0761e939f..b704ad0a241 100644
--- a/spec/requests/admin/dashboard_controller_spec.rb
+++ b/spec/requests/admin/dashboard_controller_spec.rb
@@ -95,6 +95,109 @@ RSpec.describe Admin::DashboardController do
expect(response.parsed_body["errors"]).to include(I18n.t("not_found"))
end
end
+
+ describe "sections.highlights payload" do
+ before do
+ SiteSetting.dashboard_improvements = true
+ AdminDashboardData.unstub(:fetch_cached_stats)
+ AdminDashboardData.stubs(:fetch_cached_stats).returns(reports: [])
+ Discourse.cache.clear
+ sign_in(admin)
+ end
+
+ it "is omitted when dashboard_improvements is disabled" do
+ SiteSetting.dashboard_improvements = false
+ get "/admin/dashboard.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["sections"]).to be_nil
+ end
+
+ it "includes a highlights section with kpis" do
+ get "/admin/dashboard.json"
+
+ expect(response.status).to eq(200)
+ highlights = response.parsed_body["sections"]["highlights"]
+ expect(highlights).to be_present
+ expect(highlights["kpis"]).to be_an(Array)
+ end
+
+ it "returns the documented payload shape for new_signups" do
+ freeze_time(Time.utc(2026, 4, 28, 12, 0, 0)) do
+ Fabricate(:user, created_at: 5.days.ago)
+ get "/admin/dashboard.json", params: { start_date: "2026-03-01", end_date: "2026-04-28" }
+
+ kpis = response.parsed_body["sections"]["highlights"]["kpis"]
+ signups = kpis.find { |k| k["type"] == "new_signups" }
+
+ expect(signups).to include(
+ "type" => "new_signups",
+ "report_type" => "signups",
+ "report_query" => {
+ "start_date" => "2026-03-01",
+ "end_date" => "2026-04-28",
+ },
+ )
+ expect(signups["value"]).to be >= 1
+ expect(signups).to have_key("previous_value")
+ expect(signups).to have_key("percent_change")
+ end
+ end
+
+ it "honours start_date and end_date query params" do
+ Fabricate(:user, created_at: 2.days.ago)
+ get "/admin/dashboard.json",
+ params: {
+ start_date: 7.days.ago.strftime("%Y-%m-%d"),
+ end_date: Date.current.strftime("%Y-%m-%d"),
+ }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["sections"]["highlights"]["kpis"]).to be_an(Array)
+ end
+
+ it "ignores malformed date params and falls back to defaults" do
+ get "/admin/dashboard.json", params: { start_date: "garbage", end_date: "also-garbage" }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["sections"]["highlights"]).to be_present
+ end
+
+ it "denies non-staff users" do
+ sign_in(user)
+ get "/admin/dashboard.json"
+
+ expect(response.status).to eq(404)
+ end
+
+ it "allows moderators and returns the highlights payload" do
+ sign_in(moderator)
+ get "/admin/dashboard.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["sections"]["highlights"]).to be_present
+ end
+
+ it "omits version_check when the flag is on" do
+ SiteSetting.version_checks = true
+ DiscourseUpdates.expects(:check_version).never
+
+ get "/admin/dashboard.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body).not_to have_key("version_check")
+ end
+
+ it "still includes version_check when the flag is off" do
+ SiteSetting.dashboard_improvements = false
+ SiteSetting.version_checks = true
+
+ get "/admin/dashboard.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body).to have_key("version_check")
+ end
+ end
end
describe "#problems" do
diff --git a/spec/services/admin_dashboard_highlights_spec.rb b/spec/services/admin_dashboard_highlights_spec.rb
new file mode 100644
index 00000000000..9f7018da6e0
--- /dev/null
+++ b/spec/services/admin_dashboard_highlights_spec.rb
@@ -0,0 +1,196 @@
+# frozen_string_literal: true
+
+describe AdminDashboardHighlights do
+ describe ".build" do
+ before do
+ freeze_time(Time.zone.local(2026, 4, 28, 12, 0, 0))
+ Discourse.cache.clear
+ end
+
+ it "returns a kpis array keyed by report type" do
+ result = described_class.build(start_date: "2026-04-01", end_date: "2026-04-28")
+
+ expect(result[:kpis]).to be_an(Array)
+ types = result[:kpis].map { |k| k[:type] }
+ expect(types).to include(:new_signups, :dau_mau, :new_contributors)
+ end
+
+ it "computes value, previous_value and percent_change for new_signups" do
+ Fabricate(:user, created_at: Time.zone.local(2026, 4, 10))
+ Fabricate(:user, created_at: Time.zone.local(2026, 4, 15))
+ Fabricate(:user, created_at: Time.zone.local(2026, 3, 10))
+
+ result = described_class.build(start_date: "2026-04-01", end_date: "2026-04-28")
+ signups = result[:kpis].find { |k| k[:type] == :new_signups }
+
+ expect(signups[:value]).to eq(2)
+ expect(signups[:previous_value]).to eq(1)
+ expect(signups[:percent_change]).to eq(100.0)
+ end
+
+ it "emits report_type and report_query instead of a synthesised URL" do
+ result = described_class.build(start_date: "2026-04-01", end_date: "2026-04-28")
+ signups = result[:kpis].find { |k| k[:type] == :new_signups }
+
+ expect(signups[:report_type]).to eq("signups")
+ expect(signups[:report_query]).to eq(start_date: "2026-04-01", end_date: "2026-04-28")
+ expect(signups).not_to have_key(:report_url)
+ end
+
+ it "returns nil percent_change when previous is zero" do
+ Fabricate(:user, created_at: Time.zone.local(2026, 4, 10))
+
+ result = described_class.build(start_date: "2026-04-01", end_date: "2026-04-28")
+ signups = result[:kpis].find { |k| k[:type] == :new_signups }
+
+ expect(signups[:percent_change]).to be_nil
+ end
+
+ it "returns nil value when the report has no data points" do
+ result = described_class.build(start_date: "2026-04-01", end_date: "2026-04-28")
+ dau = result[:kpis].find { |k| k[:type] == :dau_mau }
+
+ expect(dau[:value]).to be_nil
+ end
+
+ it "averages dau_mau values rather than summing them when there is data" do
+ Fabricate(:user_visit, visited_at: Time.zone.local(2026, 4, 10).to_date)
+ Fabricate(:user_visit, visited_at: Time.zone.local(2026, 4, 15).to_date)
+
+ result = described_class.build(start_date: "2026-04-01", end_date: "2026-04-28")
+ dau = result[:kpis].find { |k| k[:type] == :dau_mau }
+
+ expect(dau[:value]).to be_a(Float)
+ end
+
+ describe "plugin-registered KPIs" do
+ let(:kpi_entry) { { type: :extra_kpi, report: "signups", enabled: -> { @kpi_enabled } } }
+
+ before { DiscoursePluginRegistry.stubs(:admin_dashboard_highlight_kpis).returns([kpi_entry]) }
+
+ it "includes a registered KPI when its enabled proc returns true" do
+ @kpi_enabled = true
+ result = described_class.build(start_date: "2026-04-01", end_date: "2026-04-28")
+ expect(result[:kpis].map { |k| k[:type] }).to include(:extra_kpi)
+ end
+
+ it "omits a registered KPI when its enabled proc returns false" do
+ @kpi_enabled = false
+ result = described_class.build(start_date: "2026-04-01", end_date: "2026-04-28")
+ expect(result[:kpis].map { |k| k[:type] }).not_to include(:extra_kpi)
+ end
+ end
+
+ it "skips a KPI when its report errors out" do
+ original = Report.method(:find)
+ Report.define_singleton_method(:find) do |type, *args, **kwargs|
+ if type == "signups"
+ r = original.call(type, *args, **kwargs)
+ r.error = :timeout
+ r
+ else
+ original.call(type, *args, **kwargs)
+ end
+ end
+
+ result = described_class.build(start_date: "2026-04-01", end_date: "2026-04-28")
+ expect(result[:kpis].map { |k| k[:type] }).not_to include(:new_signups)
+ ensure
+ Report.define_singleton_method(:find, &original)
+ end
+
+ it "falls back to a default 30-day window when params are blank" do
+ result = described_class.build(start_date: nil, end_date: nil)
+ expect(result[:kpis]).to be_an(Array)
+ expect(result[:kpis]).not_to be_empty
+ end
+
+ it "falls back to defaults when params are unparseable" do
+ result = described_class.build(start_date: "garbage", end_date: "also-garbage")
+ expect(result[:kpis]).to be_an(Array)
+ expect(result[:kpis]).not_to be_empty
+ end
+
+ it "ignores unicode garbage in date params" do
+ result = described_class.build(start_date: "字字字", end_date: "字字字")
+ expect(result[:kpis]).to be_an(Array)
+ expect(result[:kpis]).not_to be_empty
+ end
+
+ it "does not pass current_user to Report.find so admins share one cache entry" do
+ received_args = []
+ original_find = Report.method(:find)
+ Report.define_singleton_method(:find) do |type, opts = nil|
+ received_args << (opts || {})
+ original_find.call(type, opts)
+ end
+
+ described_class.build(start_date: "2026-04-01", end_date: "2026-04-28")
+
+ expect(received_args).not_to be_empty
+ received_args.each { |args| expect(args).not_to have_key(:current_user) }
+ ensure
+ Report.define_singleton_method(:find, &original_find)
+ end
+
+ it "parses dates in Time.zone, not UTC" do
+ Time.use_zone("America/Los_Angeles") do
+ result = described_class.build(start_date: "2026-04-01", end_date: "2026-04-02")
+ signups = result[:kpis].find { |k| k[:type] == :new_signups }
+ expect(signups[:report_query][:start_date]).to eq("2026-04-01")
+ end
+
+ Time.use_zone("Etc/UTC") do
+ result = described_class.build(start_date: "2026-04-01", end_date: "2026-04-02")
+ signups = result[:kpis].find { |k| k[:type] == :new_signups }
+ expect(signups[:report_query][:start_date]).to eq("2026-04-01")
+ end
+ end
+
+ it "accepts ISO8601 strings with time and drops the time-of-day" do
+ result =
+ described_class.build(start_date: "2026-04-01T18:00:00Z", end_date: "2026-04-28T23:59:59Z")
+ signups = result[:kpis].find { |k| k[:type] == :new_signups }
+
+ expect(signups[:report_query]).to eq(start_date: "2026-04-01", end_date: "2026-04-28")
+ end
+
+ describe "per-report caching" do
+ it "reuses Report.find_cached on subsequent calls with the same date range" do
+ described_class.build(start_date: "2026-04-01", end_date: "2026-04-28")
+
+ # second call should hit the report-level cache for every core KPI
+ Report.expects(:find).never
+
+ result = described_class.build(start_date: "2026-04-01", end_date: "2026-04-28")
+ expect(result[:kpis].map { |k| k[:type] }).to include(:new_signups, :new_contributors)
+ end
+
+ it "recomputes when the date range changes" do
+ described_class.build(start_date: "2026-04-01", end_date: "2026-04-28")
+
+ # different range — cache miss, so Report.find must be called at least once
+ Report
+ .expects(:find)
+ .at_least_once
+ .returns(stub(type: "signups", error: nil, data: [], prev_period: 0))
+ Report.stubs(:cache)
+ described_class.build(start_date: "2026-03-01", end_date: "2026-03-31")
+ end
+
+ it "re-evaluates plugin enabled procs on every build (no outer cache)" do
+ @kpi_enabled = true
+ DiscoursePluginRegistry.stubs(:admin_dashboard_highlight_kpis).returns(
+ [{ type: :toggleable_kpi, report: "signups", enabled: -> { @kpi_enabled } }],
+ )
+
+ first = described_class.build(start_date: "2026-04-01", end_date: "2026-04-28")
+ expect(first[:kpis].map { |k| k[:type] }).to include(:toggleable_kpi)
+
+ @kpi_enabled = false
+ second = described_class.build(start_date: "2026-04-01", end_date: "2026-04-28")
+ expect(second[:kpis].map { |k| k[:type] }).not_to include(:toggleable_kpi)
+ end
+ end
+ end
+end