A platform for community discussion. Free, open, simple.
FEATURE: Engagement section in the updated dashboard (#40220)
Natalie Tay943371efcc18
diff --git a/app/assets/stylesheets/admin/admin_dashboard.scss b/app/assets/stylesheets/admin/admin_dashboard.scssindex 569224d85cb..f81d76887bd 100644--- a/app/assets/stylesheets/admin/admin_dashboard.scss+++ b/app/assets/stylesheets/admin/admin_dashboard.scss@@ -351,6 +351,19 @@ h1 {}}+.db-engagement {+ .db-engagement-headline {+ .db-section__metrics {+ gap: 0;++ .db-kpi {+ border: none;+ padding-top: 0;+ }+ }+ }+}+.db-kpi {position: relative;display: flex;diff --git a/app/controllers/admin/dashboard_controller.rb b/app/controllers/admin/dashboard_controller.rbindex 4fcbe85cd1b..d17978d9805 100644--- a/app/controllers/admin/dashboard_controller.rb+++ b/app/controllers/admin/dashboard_controller.rb@@ -129,6 +129,8 @@ class Admin::DashboardController < Admin::StaffControllerAdminDashboardHighlights.build(start_date: params[:start_date], end_date: params[:end_date])when "traffic"AdminDashboardSiteTraffic.build(start_date: params[:start_date], end_date: params[:end_date])+ when "engagement"+ AdminDashboardEngagement.build(start_date: params[:start_date], end_date: params[:end_date])when "reports"AdminDashboard::Reports::Section.build(guardian: guardian)enddiff --git a/app/services/admin_dashboard_engagement.rb b/app/services/admin_dashboard_engagement.rbnew file mode 100644index 00000000000..ca019ef920f--- /dev/null+++ b/app/services/admin_dashboard_engagement.rb@@ -0,0 +1,141 @@+# frozen_string_literal: true++class AdminDashboardEngagement+ DEFAULT_RANGE_DAYS = 30++ KPI_REPORTS = {+ dau_mau: "dau_by_mau",+ daily_engaged_users: "daily_engaged_users",+ new_signups: "signups",+ }.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+ { kpis: kpis, headline: build_headline(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+ KPI_REPORTS.filter_map { |type, report| build_kpi(type, report) }+ 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++ 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++ HEADLINE_KEYS = {+ healthy_growth: "admin.dashboard.sections.engagement.headline.healthy_growth",+ declining: "admin.dashboard.sections.engagement.headline.declining",+ engaged_but_shrinking: "admin.dashboard.sections.engagement.headline.engaged_but_shrinking",+ growing_but_distracted: "admin.dashboard.sections.engagement.headline.growing_but_distracted",+ mixed: "admin.dashboard.sections.engagement.headline.mixed",+ no_signal: "admin.dashboard.sections.engagement.headline.no_signal",+ }.freeze++ def build_headline(kpis)+ stickiness = sign_of(kpi_change(kpis, :dau_mau))+ signups = sign_of(kpi_change(kpis, :new_signups))+ engaged = sign_of(kpi_change(kpis, :daily_engaged_users))++ key =+ if [stickiness, signups, engaged].all?(&:zero?)+ :no_signal+ elsif stickiness >= 0 && signups >= 0 && engaged >= 0+ :healthy_growth+ elsif stickiness <= 0 && signups <= 0 && engaged <= 0+ :declining+ elsif stickiness >= 0 && (signups < 0 || engaged < 0)+ :engaged_but_shrinking+ elsif stickiness < 0 && signups > 0+ :growing_but_distracted+ else+ :mixed+ end++ { key: HEADLINE_KEYS[key] }+ end++ def kpi_change(kpis, type)+ kpis.find { |k| k[:type] == type }&.dig(:percent_change)+ end++ def sign_of(value)+ return 0 if value.nil? || value.zero?+ value.positive? ? 1 : -1+ end+enddiff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex 4caff6d11fb..85a8716230a 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -6883,6 +6883,26 @@ en:title: "Site traffic"engagement:title: "Engagement"+ fetch_error: "Couldn't load engagement. Try refreshing the page."+ headline:+ healthy_growth:+ title: "Members are forming a habit of coming back."+ summary: "Stickiness, daily engagement, and new sign-ups are all up this period."+ declining:+ title: "Members are coming back less often."+ summary: "Stickiness, daily engagement, and new sign-ups are all down this period."+ engaged_but_shrinking:+ title: "Members are engaged, but the community is shrinking."+ summary: "Stickiness is holding up, but daily engagement or new sign-ups have slipped."+ growing_but_distracted:+ title: "New members are signing up, but they're not sticking around."+ summary: "Sign-ups are up, but stickiness has dropped this period."+ mixed:+ title: "Engagement trends are mixed this period."+ summary: "Some metrics are up while others are down — open the tiles below for detail."+ no_signal:+ title: "Not enough activity yet to summarise engagement."+ summary: "Pick a longer date range or come back once your community has more activity."configure:button: "Configure"@@ -6907,6 +6927,9 @@ en:new_contributors:label: "New contributors"tooltip: "The number of members who made their first post in this period."+ daily_engaged_users:+ label: "Daily engaged"+ tooltip: "The number of members who liked or posted in the community in the last day."comparison:last_7_days: "vs last 7 days"last_30_days: "vs last 30 days"diff --git a/frontend/discourse/admin/components/dashboard/engagement.gjs b/frontend/discourse/admin/components/dashboard/engagement.gjsindex 38577531a5d..243f8f2f8b2 100644--- a/frontend/discourse/admin/components/dashboard/engagement.gjs+++ b/frontend/discourse/admin/components/dashboard/engagement.gjs@@ -1,69 +1,25 @@+import EngagementHeadline from "discourse/admin/components/dashboard/engagement/headline";import DashboardSection from "discourse/admin/components/dashboard/section";-import CategorySelector from "discourse/select-kit/components/category-selector";import { i18n } from "discourse-i18n";<template>- <DashboardSection- @title={{i18n "admin.dashboard.sections.engagement.title"}}- @startDate={{@startDate}}- @endDate={{@endDate}}- >- <div class="db-section__subheader">- <div class="db-section__subintro">- <h3>Members are forming a habit of coming back.</h3>- <p>Stickiness is steady at 21% and new sign-ups are up 9%, but- daily-engaged members slipped 5% — most active members are- participating less often than last month.</p>- </div>- <div class="db-section__metrics">- <div class="db-section__metric">- <div class="db-section__metric-number">38%</div>- <div class="db-section__metric-label">- DAU / MAU- </div>- <span class="db-pill --pos">stable</span>+ <div class="db-engagement">+ <DashboardSection+ @title={{i18n "admin.dashboard.sections.engagement.title"}}+ @startDate={{@startDate}}+ @endDate={{@endDate}}+ >+ {{#if @fetchError}}+ <div class="db-section__error" role="alert">+ {{i18n "admin.dashboard.sections.engagement.fetch_error"}}</div>- <div class="db-section__metric">- <div class="db-section__metric-number">150</div>- <div class="db-section__metric-label">Daily visitors- </div>- <span class="db-delta --neg">-2%</span>- </div>- <div class="db-section__metric">- <div class="db-section__metric-number">248</div>- <div class="db-section__metric-label">New sign ups- </div>- <span class="db-delta --pos">+12%</span>- </div>- </div>- </div>- {{! only needed when adding multiple rows }}- <div class="db-section__row-group">- <div class="db-section__row">- <div class="db-section__row-block">- <div class="db-section__row-block-header">- <h3 class="db-section__row-block-title">Trust Level Pipeline</h3>- <span class="db-pill --pos">+72 climbing</span>- </div>- </div>- <div class="db-section__row-block">- <div class="db-section__row-block-header">- <h3 class="db-section__row-block-title">Who's contributing?</h3>- </div>- </div>- </div>- <div class="db-section__row">- <div class="db-section__row-block"><div- class="db-section__row-block-header"- >- <h3 class="db-section__row-block-title">Activity by category</h3>- <CategorySelector />- </div>- <div class="db-activity">- //table- </div>- </div>- </div>- </div>- </DashboardSection>+ {{else if @engagement.headline}}+ <EngagementHeadline+ @headline={{@engagement.headline}}+ @kpis={{@engagement.kpis}}+ @period={{@period}}+ />+ {{/if}}+ </DashboardSection>+ </div></template>diff --git a/frontend/discourse/admin/components/dashboard/engagement/headline.gjs b/frontend/discourse/admin/components/dashboard/engagement/headline.gjsnew file mode 100644index 00000000000..da6682eecee--- /dev/null+++ b/frontend/discourse/admin/components/dashboard/engagement/headline.gjs@@ -0,0 +1,44 @@+import Component from "@glimmer/component";+import KpiTile from "discourse/admin/components/dashboard/kpi-tile";+import { i18n } from "discourse-i18n";++const PRESET_PERIODS = ["last_7_days", "last_30_days", "last_3_months"];++export default class EngagementHeadline extends Component {+ get titleKey() {+ return `${this.args.headline.key}.title`;+ }++ get summaryKey() {+ return `${this.args.headline.key}.summary`;+ }++ get comparisonLabel() {+ const key = PRESET_PERIODS.includes(this.args.period)+ ? this.args.period+ : "previous_period";+ return i18n(`admin.dashboard.highlights.comparison.${key}`);+ }++ <template>+ <div class="db-section__subheader db-engagement-headline">+ <div class="db-section__subintro">+ <h3>{{i18n this.titleKey}}</h3>+ <p>{{i18n this.summaryKey}}</p>+ </div>+ <div class="db-section__metrics">+ {{#each @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}}+ </div>+ </div>+ </template>+}diff --git a/frontend/discourse/admin/components/redesigned-admin-dashboard.gjs b/frontend/discourse/admin/components/redesigned-admin-dashboard.gjsindex 2042eb72c8d..13f44eeb3de 100644--- a/frontend/discourse/admin/components/redesigned-admin-dashboard.gjs+++ b/frontend/discourse/admin/components/redesigned-admin-dashboard.gjs@@ -149,6 +149,10 @@ export default class RedesignedAdminDashboard extends Component {/>{{else if (eq section.id "engagement")}}<DashboardEngagement+ @engagement={{section.data}}+ @period={{@loadedSections.period}}+ @loading={{@loadingSections}}+ @fetchError={{@sectionsFetchError}}@startDate={{@loadedSections.startDate}}@endDate={{@loadedSections.endDate}}/>diff --git a/frontend/discourse/tests/integration/components/dashboard/engagement-test.gjs b/frontend/discourse/tests/integration/components/dashboard/engagement-test.gjsnew file mode 100644index 00000000000..a07d8abb44e--- /dev/null+++ b/frontend/discourse/tests/integration/components/dashboard/engagement-test.gjs@@ -0,0 +1,101 @@+import { render } from "@ember/test-helpers";+import { module, test } from "qunit";+import DashboardEngagement from "discourse/admin/components/dashboard/engagement";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";++module("Integration | Component | Dashboard | Engagement", 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" };++ const engagement = {+ headline: {+ key: "admin.dashboard.sections.engagement.headline.healthy_growth",+ },+ kpis: [+ {+ type: "dau_mau",+ value: 21.6,+ percent_change: 1.9,+ report_type: "dau_by_mau",+ report_query: reportQuery,+ },+ {+ type: "daily_engaged_users",+ value: 150,+ percent_change: -5,+ report_type: "daily_engaged_users",+ report_query: reportQuery,+ },+ {+ type: "new_signups",+ value: 248,+ percent_change: 9,+ report_type: "signups",+ report_query: reportQuery,+ },+ ],+ };++ test("renders the headline title, summary and one KpiTile per kpi", async function (assert) {+ await render(+ <template>+ <DashboardEngagement+ @engagement={{engagement}}+ @period="last_30_days"+ @startDate={{start}}+ @endDate={{end}}+ />+ </template>+ );++ assert+ .dom(".db-section__subintro h3")+ .hasText("Members are forming a habit of coming back.");+ assert.dom(".db-section__subintro p").exists();+ assert.dom(".db-kpi").exists({ count: 3 });+ 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/daily_engaged_users"] .db-kpi__value'+ )+ .hasText("150");+ assert+ .dom('a.db-kpi[href*="/admin/reports/signups"] .db-kpi__value')+ .hasText("248");+ });++ test("renders an inline error when the section fetch failed", async function (assert) {+ await render(+ <template>+ <DashboardEngagement+ @engagement={{null}}+ @fetchError={{true}}+ @startDate={{start}}+ @endDate={{end}}+ />+ </template>+ );++ assert.dom(".db-section__error").exists();+ assert.dom(".db-kpi").doesNotExist();+ });++ test("omits the headline block when the engagement payload is missing", async function (assert) {+ await render(+ <template>+ <DashboardEngagement+ @engagement={{null}}+ @startDate={{start}}+ @endDate={{end}}+ />+ </template>+ );++ assert.dom(".db-section__subintro").doesNotExist();+ });+});diff --git a/spec/requests/admin/dashboard_controller_spec.rb b/spec/requests/admin/dashboard_controller_spec.rbindex 85b3374424a..294cc3d8953 100644--- a/spec/requests/admin/dashboard_controller_spec.rb+++ b/spec/requests/admin/dashboard_controller_spec.rb@@ -289,12 +289,12 @@ RSpec.describe Admin::DashboardController doexpect(ids).not_to include("traffic", "engagement")end- it "leaves data null for sections without a builder yet" do+ it "includes built engagement data when the section is enabled" doSiteSetting.admin_dashboard_sections = "highlights|engagement"get "/admin/dashboard.json"engagement = response.parsed_body["sections"].find { |s| s["id"] == "engagement" }- expect(engagement["data"]).to be_nil+ expect(engagement["data"]).to include("kpis", "headline")enddescribe "reports section data" dodiff --git a/spec/services/admin_dashboard_engagement_spec.rb b/spec/services/admin_dashboard_engagement_spec.rbnew file mode 100644index 00000000000..5b249f42020--- /dev/null+++ b/spec/services/admin_dashboard_engagement_spec.rb@@ -0,0 +1,126 @@+# frozen_string_literal: true++describe AdminDashboardEngagement 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(:dau_mau, :daily_engaged_users, :new_signups)+ 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 for drill-down" do+ result = described_class.build(start_date: "2026-04-01", end_date: "2026-04-28")+ engaged = result[:kpis].find { |k| k[:type] == :daily_engaged_users }++ expect(engaged[:report_type]).to eq("daily_engaged_users")+ expect(engaged[:report_query]).to eq(start_date: "2026-04-01", end_date: "2026-04-28")+ 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 "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++ describe "headline" do+ def stub_kpis(signups:, dau: 0, engaged: 0)+ described_class+ .any_instance+ .stubs(:build_kpis)+ .returns(+ [+ { type: :dau_mau, percent_change: dau },+ { type: :new_signups, percent_change: signups },+ { type: :daily_engaged_users, percent_change: engaged },+ ],+ )+ end++ it "returns healthy_growth when every metric is non-negative and at least one is positive" do+ stub_kpis(signups: 12, dau: 3, engaged: 5)+ result = described_class.build(start_date: "2026-04-01", end_date: "2026-04-28")+ expect(result[:headline][:key]).to end_with("healthy_growth")+ end++ it "returns declining when every metric is non-positive and at least one is negative" do+ stub_kpis(signups: -8, dau: -2, engaged: -5)+ result = described_class.build(start_date: "2026-04-01", end_date: "2026-04-28")+ expect(result[:headline][:key]).to end_with("declining")+ end++ it "returns engaged_but_shrinking when stickiness is up but engagement or signups fell" do+ stub_kpis(signups: -5, dau: 2, engaged: -3)+ result = described_class.build(start_date: "2026-04-01", end_date: "2026-04-28")+ expect(result[:headline][:key]).to end_with("engaged_but_shrinking")+ end++ it "returns growing_but_distracted when sign-ups rose but stickiness slipped" do+ stub_kpis(signups: 10, dau: -4, engaged: 0)+ result = described_class.build(start_date: "2026-04-01", end_date: "2026-04-28")+ expect(result[:headline][:key]).to end_with("growing_but_distracted")+ end++ it "returns no_signal when every metric has no change" do+ stub_kpis(signups: 0, dau: 0, engaged: 0)+ result = described_class.build(start_date: "2026-04-01", end_date: "2026-04-28")+ expect(result[:headline][:key]).to end_with("no_signal")+ end++ it "returns mixed when stickiness fell, sign-ups flat, but engagement rose" do+ stub_kpis(signups: 0, dau: -3, engaged: 4)+ result = described_class.build(start_date: "2026-04-01", end_date: "2026-04-28")+ expect(result[:headline][:key]).to end_with("mixed")+ end+ end+ end+end