Skip to content

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

DEV: Scaffold backend for the new admin dashboard Reports section (#40017)

Osama Sayegh08fdf23a075a
diff --git a/app/controllers/admin/dashboard_controller.rb b/app/controllers/admin/dashboard_controller.rb
index a8e8dec4e2f..4fcbe85cd1b 100644
--- a/app/controllers/admin/dashboard_controller.rb
+++ b/app/controllers/admin/dashboard_controller.rb
@@ -1,6 +1,10 @@
# frozen_string_literal: true
class Admin::DashboardController < Admin::StaffController
+ BULK_REPORTS_FILTER_KEYS = %i[start_date end_date].freeze
+
+ before_action :ensure_dashboard_improvements_enabled, only: %i[bulk_reports]
+
def index
if SiteSetting.dashboard_improvements
visible_ids = AdminDashboardSectionConfiguration.visible_section_ids
@@ -90,6 +94,33 @@ class Admin::DashboardController < Admin::StaffController
end
end
+ def bulk_reports
+ raise Discourse::InvalidParameters.new(:items) if !params[:items].is_a?(Array)
+ if params[:items].size > AdminDashboardReport::VISIBLE_CAP
+ raise Discourse::InvalidParameters.new(:items)
+ end
+
+ items =
+ params
+ .permit(items: %i[source identifier])
+ .fetch(:items, [])
+ .map do |entry|
+ source = entry[:source]
+ identifier = entry[:identifier]
+ raise Discourse::InvalidParameters.new(:items) if source.blank? || identifier.blank?
+ { source: source.to_s, identifier: identifier.to_s }
+ end
+
+ permitted_filters = params.permit(filters: BULK_REPORTS_FILTER_KEYS).fetch(:filters, nil)
+ filters = permitted_filters.present? ? permitted_filters.to_h.symbolize_keys : {}
+
+ hijack do
+ render_json_dump(
+ AdminDashboard::Reports::BulkFetch.call(items: items, filters: filters, guardian: guardian),
+ )
+ end
+ end
+
private
def section_data(id)
@@ -98,10 +129,16 @@ class Admin::DashboardController < Admin::StaffController
AdminDashboardHighlights.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 "reports"
+ AdminDashboard::Reports::Section.build(guardian: guardian)
end
end
def mark_new_features_as_seen
DiscourseUpdates.mark_new_features_as_seen(current_user.id)
end
+
+ def ensure_dashboard_improvements_enabled
+ raise Discourse::NotFound if !SiteSetting.dashboard_improvements
+ end
end
diff --git a/app/models/admin_dashboard_report.rb b/app/models/admin_dashboard_report.rb
new file mode 100644
index 00000000000..b86b7fcb17e
--- /dev/null
+++ b/app/models/admin_dashboard_report.rb
@@ -0,0 +1,41 @@
+# frozen_string_literal: true
+
+class AdminDashboardReport < ActiveRecord::Base
+ VISIBLE_CAP = 10
+
+ validates :source, presence: true
+ validates :identifier, presence: true
+ validates :identifier, uniqueness: { scope: :source }
+ validate :source_must_be_registered
+
+ before_validation :assign_default_position, on: :create
+
+ private
+
+ def assign_default_position
+ self.position ||= self.class.maximum(:position).to_i + 1
+ end
+
+ def source_must_be_registered
+ return if source.blank?
+ return if AdminDashboard::Reports::Registry.provider_for(source)
+ errors.add(:source, :invalid)
+ end
+end
+
+# == Schema Information
+#
+# Table name: admin_dashboard_reports
+#
+# id :bigint not null, primary key
+# identifier :string not null
+# position :integer not null
+# source :string not null
+# created_at :datetime not null
+# updated_at :datetime not null
+#
+# Indexes
+#
+# index_admin_dashboard_reports_on_position (position)
+# index_admin_dashboard_reports_on_source_and_identifier (source,identifier) UNIQUE
+#
diff --git a/config/routes.rb b/config/routes.rb
index 94bf9621dcc..2de7e26e048 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -336,6 +336,7 @@ Discourse::Application.routes.draw do
get "dashboard/moderation" => "dashboard#moderation"
get "dashboard/security" => "dashboard#security"
get "dashboard/reports" => "dashboard#reports"
+ post "dashboard/reports/bulk" => "dashboard#bulk_reports"
get "dashboard/whats-new" => "dashboard#new_features"
get "/whats-new" => "dashboard#new_features"
post "/toggle-feature" => "dashboard#toggle_feature"
diff --git a/config/site_settings.yml b/config/site_settings.yml
index e5e821b34e0..376f661d5bc 100644
--- a/config/site_settings.yml
+++ b/config/site_settings.yml
@@ -4541,3 +4541,6 @@ experimental:
upcoming_change:
status: "conceptual"
impact: "feature,admins"
+ admin_dashboard_reports_seeded:
+ default: false
+ hidden: true
diff --git a/db/fixtures/600_admin_dashboard_reports.rb b/db/fixtures/600_admin_dashboard_reports.rb
new file mode 100644
index 00000000000..3e877e7d8a0
--- /dev/null
+++ b/db/fixtures/600_admin_dashboard_reports.rb
@@ -0,0 +1,5 @@
+# frozen_string_literal: true
+
+require "seed_data/admin_dashboard_reports"
+
+SeedData::AdminDashboardReports.create
diff --git a/db/migrate/20260511080033_create_admin_dashboard_reports.rb b/db/migrate/20260511080033_create_admin_dashboard_reports.rb
new file mode 100644
index 00000000000..002ba671938
--- /dev/null
+++ b/db/migrate/20260511080033_create_admin_dashboard_reports.rb
@@ -0,0 +1,15 @@
+# frozen_string_literal: true
+
+class CreateAdminDashboardReports < ActiveRecord::Migration[8.0]
+ def change
+ create_table :admin_dashboard_reports do |t|
+ t.integer :position, null: false
+ t.string :source, null: false
+ t.string :identifier, null: false
+ t.timestamps
+ end
+
+ add_index :admin_dashboard_reports, %i[source identifier], unique: true
+ add_index :admin_dashboard_reports, :position
+ end
+end
diff --git a/db/structure.sql b/db/structure.sql
index bb268b075fe..ee05030ba85 100644
--- a/db/structure.sql
+++ b/db/structure.sql
@@ -261,6 +261,39 @@ CREATE SEQUENCE public.ad_plugin_impressions_id_seq
ALTER SEQUENCE public.ad_plugin_impressions_id_seq OWNED BY public.ad_plugin_impressions.id;
+--
+-- Name: admin_dashboard_reports; Type: TABLE; Schema: public; Owner: -
+--
+
+CREATE TABLE public.admin_dashboard_reports (
+ id bigint NOT NULL,
+ "position" integer NOT NULL,
+ source character varying NOT NULL,
+ identifier character varying NOT NULL,
+ created_at timestamp(6) without time zone NOT NULL,
+ updated_at timestamp(6) without time zone NOT NULL
+);
+
+
+--
+-- Name: admin_dashboard_reports_id_seq; Type: SEQUENCE; Schema: public; Owner: -
+--
+
+CREATE SEQUENCE public.admin_dashboard_reports_id_seq
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+
+
+--
+-- Name: admin_dashboard_reports_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
+--
+
+ALTER SEQUENCE public.admin_dashboard_reports_id_seq OWNED BY public.admin_dashboard_reports.id;
+
+
--
-- Name: admin_notices; Type: TABLE; Schema: public; Owner: -
--
@@ -11334,6 +11367,13 @@ ALTER TABLE ONLY public.ad_plugin_house_ads ALTER COLUMN id SET DEFAULT nextval(
ALTER TABLE ONLY public.ad_plugin_impressions ALTER COLUMN id SET DEFAULT nextval('public.ad_plugin_impressions_id_seq'::regclass);
+--
+-- Name: admin_dashboard_reports id; Type: DEFAULT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.admin_dashboard_reports ALTER COLUMN id SET DEFAULT nextval('public.admin_dashboard_reports_id_seq'::regclass);
+
+
--
-- Name: admin_notices id; Type: DEFAULT; Schema: public; Owner: -
--
@@ -13366,6 +13406,14 @@ ALTER TABLE ONLY public.ad_plugin_impressions
ADD CONSTRAINT ad_plugin_impressions_pkey PRIMARY KEY (id);
+--
+-- Name: admin_dashboard_reports admin_dashboard_reports_pkey; Type: CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.admin_dashboard_reports
+ ADD CONSTRAINT admin_dashboard_reports_pkey PRIMARY KEY (id);
+
+
--
-- Name: admin_notices admin_notices_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
@@ -16337,6 +16385,20 @@ CREATE INDEX index_ad_plugin_impressions_on_created_at ON public.ad_plugin_impre
CREATE INDEX index_ad_plugin_impressions_on_user_id ON public.ad_plugin_impressions USING btree (user_id);
+--
+-- Name: index_admin_dashboard_reports_on_position; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX index_admin_dashboard_reports_on_position ON public.admin_dashboard_reports USING btree ("position");
+
+
+--
+-- Name: index_admin_dashboard_reports_on_source_and_identifier; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE UNIQUE INDEX index_admin_dashboard_reports_on_source_and_identifier ON public.admin_dashboard_reports USING btree (source, identifier);
+
+
--
-- Name: index_admin_notices_on_identifier; Type: INDEX; Schema: public; Owner: -
--
@@ -20871,6 +20933,7 @@ INSERT INTO "schema_migrations" (version) VALUES
('20260513024004'),
('20260512061336'),
('20260511145109'),
+('20260511080033'),
('20260511044542'),
('20260510232238'),
('20260507083943'),
diff --git a/lib/admin_dashboard/reports/bulk_fetch.rb b/lib/admin_dashboard/reports/bulk_fetch.rb
new file mode 100644
index 00000000000..7f58232ea23
--- /dev/null
+++ b/lib/admin_dashboard/reports/bulk_fetch.rb
@@ -0,0 +1,41 @@
+# frozen_string_literal: true
+
+module AdminDashboard
+ module Reports
+ class BulkFetch
+ def self.call(items:, filters:, guardian:)
+ new(items: items, filters: filters, guardian: guardian).call
+ end
+
+ def initialize(items:, filters:, guardian:)
+ @items = items
+ @filters = filters
+ @guardian = guardian
+ end
+
+ def call
+ { items: collect_results }
+ end
+
+ private
+
+ attr_reader :items, :filters, :guardian
+
+ def collect_results
+ per_source =
+ AdminDashboard::Reports::Registry.dispatch_per_source(items) do |provider, group|
+ identifiers = group.map { |i| i[:identifier] }
+ provider.fetch_many(identifiers, guardian:, filters:)
+ end
+
+ items.map do |item|
+ {
+ source: item[:source],
+ identifier: item[:identifier],
+ data: per_source.dig(item[:source], item[:identifier]),
+ }
+ end
+ end
+ end
+ end
+end
diff --git a/lib/admin_dashboard/reports/core_report_provider.rb b/lib/admin_dashboard/reports/core_report_provider.rb
new file mode 100644
index 00000000000..7563b3eeb0d
--- /dev/null
+++ b/lib/admin_dashboard/reports/core_report_provider.rb
@@ -0,0 +1,90 @@
+# frozen_string_literal: true
+
+module AdminDashboard
+ module Reports
+ class CoreReportProvider < SourceProvider
+ SOURCE_NAME = "core_report"
+
+ def self.source_name
+ SOURCE_NAME
+ end
+
+ def self.resolve_many(identifiers, guardian:)
+ index = available_for(guardian).index_by(&:identifier)
+ identifiers.each_with_object({}) do |identifier, hash|
+ key = identifier.to_s
+ resolved = index[key]
+ hash[key] = resolved if resolved
+ end
+ end
+
+ def self.fetch_many(identifiers, guardian:, filters: {})
+ accessible = accessible_ids(identifiers, guardian: guardian)
+ opts = build_opts(filters, guardian)
+
+ identifiers.each_with_object({}) do |identifier, hash|
+ key = identifier.to_s
+ next if accessible.exclude?(key)
+
+ cached = ::Report.find_cached(key, opts)
+ if cached
+ hash[key] = cached
+ next
+ end
+
+ report = ::Report.find(key, opts)
+ next if report.blank?
+
+ ::Report.cache(report)
+ hash[key] = report.as_json
+ end
+ end
+
+ # TODO: paginate once the Manage Reports modal's list-available endpoint
+ # exists; today this returns every registered built-in report unbounded.
+ def self.available_for(guardian, search: nil)
+ entries = ::Reports::ListQuery.call(guardian: guardian)
+ entries = filter_by_search(entries, search) if search.present?
+ entries.map { |entry| build_resolved(entry) }
+ end
+
+ def self.build_resolved(entry)
+ AdminDashboard::Reports::ResolvedReport.new(
+ source: SOURCE_NAME,
+ identifier: entry[:type],
+ title: entry[:title],
+ description: entry[:description],
+ )
+ end
+ private_class_method :build_resolved
+
+ def self.build_opts(filters, guardian)
+ filters = filters.symbolize_keys if filters.respond_to?(:symbolize_keys)
+ opts = { current_user: guardian&.user }
+ opts[:start_date] = parse_date(filters[:start_date])&.beginning_of_day if filters[
+ :start_date
+ ]
+ opts[:end_date] = parse_date(filters[:end_date])&.end_of_day if filters[:end_date]
+ opts[:filters] = filters[:filters] if filters[:filters]
+ opts
+ end
+ private_class_method :build_opts
+
+ def self.parse_date(value)
+ Time.zone.parse(value.to_s)
+ rescue ArgumentError, TypeError
+ nil
+ end
+ private_class_method :parse_date
+
+ def self.filter_by_search(entries, search)
+ query = search.to_s.downcase
+ entries.select do |entry|
+ entry[:title].to_s.downcase.include?(query) ||
+ entry[:description].to_s.downcase.include?(query)
+ end
+ end
+ private_class_method :filter_by_search
+ end
+ end
+end
diff --git a/lib/admin_dashboard/reports/registry.rb b/lib/admin_dashboard/reports/registry.rb
new file mode 100644
index 00000000000..eb5d9a66203
--- /dev/null
+++ b/lib/admin_dashboard/reports/registry.rb
@@ -0,0 +1,28 @@
+# frozen_string_literal: true
+
+module AdminDashboard
+ module Reports
+ class Registry
+ CORE_PROVIDERS = [CoreReportProvider].freeze
+
+ def self.providers
+ CORE_PROVIDERS + DiscoursePluginRegistry.admin_dashboard_report_sources
+ end
+
+ def self.provider_for(source_name)
+ providers.find { |klass| klass.source_name.to_s == source_name.to_s }
+ end
+
+ def self.dispatch_per_source(items)
+ items
+ .group_by { |item| item[:source] }
+ .each_with_object({}) do |(source, group), result|
+ provider = provider_for(source)
+ next if provider.nil?
+
+ result[source] = yield(provider, group)
+ end
+ end
+ end
+ end
+end
diff --git a/lib/admin_dashboard/reports/resolved_report.rb b/lib/admin_dashboard/reports/resolved_report.rb
new file mode 100644
index 00000000000..e6ba7eb0078
--- /dev/null
+++ b/lib/admin_dashboard/reports/resolved_report.rb
@@ -0,0 +1,7 @@
+# frozen_string_literal: true
+
+module AdminDashboard
+ module Reports
+ ResolvedReport = Data.define(:source, :identifier, :title, :description)
+ end
+end
diff --git a/lib/admin_dashboard/reports/section.rb b/lib/admin_dashboard/reports/section.rb
new file mode 100644
index 00000000000..f06c2d880bd
--- /dev/null
+++ b/lib/admin_dashboard/reports/section.rb
@@ -0,0 +1,56 @@
+# frozen_string_literal: true
+
+module AdminDashboard
+ module Reports
+ class Section
+ def self.build(guardian:)
+ new(guardian: guardian).build
+ end
+
+ def initialize(guardian:)
+ @guardian = guardian
+ end
+
+ def build
+ { items: visible_items.map { |_row, resolved| serialize(resolved) } }
+ end
+
+ private
+
+ attr_reader :guardian
+
+ def visible_items
+ rows = AdminDashboardReport.order(created_at: :desc).to_a
+ resolved_by_row_id = resolve_rows(rows)
+
+ # When more rows resolve than VISIBLE_CAP allows, the older overflow
+ # is hidden — clip by created_at recency first, then re-sort the
+ # survivors by the admin's chosen position.
+ rows
+ .filter_map { |row| (obj = resolved_by_row_id[row.id]) && [row, obj] }
+ .first(AdminDashboardReport::VISIBLE_CAP)
+ .sort_by { |row, _obj| row.position }
+ end
+
+ def resolve_rows(rows)
+ per_source =
+ AdminDashboard::Reports::Registry.dispatch_per_source(rows) do |provider, group|
+ provider.resolve_many(group.map(&:identifier), guardian: guardian)
+ end
+
+ rows.each_with_object({}) do |row, resolved|
+ resolved[row.id] = per_source.dig(row.source, row.identifier)
+ end
+ end
+
+ def serialize(resolved)
+ {
+ source: resolved.source,
+ identifier: resolved.identifier,
+ title: resolved.title,
+ description: resolved.description,
+ }
+ end
+ end
+ end
+end
diff --git a/lib/admin_dashboard/reports/source_provider.rb b/lib/admin_dashboard/reports/source_provider.rb
new file mode 100644
index 00000000000..3a613876f59
--- /dev/null
+++ b/lib/admin_dashboard/reports/source_provider.rb
@@ -0,0 +1,67 @@
+# frozen_string_literal: true
+
+module AdminDashboard
+ module Reports
+ # Base class for anything that contributes mountable reports to the
+ # customisable Reports section on the new admin dashboard. Subclasses are
+ # registered with DiscoursePluginRegistry (or, for built-ins, listed in
+ # AdminDashboard::Reports::Registry::CORE_PROVIDERS) and dispatched to by
+ # source_name.
+ #
+ # Every method on the provider is batch-shaped to keep the dashboard
+ # render path bounded — never one-by-one resolution.
+ class SourceProvider
+ # @return [String] the value stored in admin_dashboard_reports.source for
+ # rows this provider owns. Examples: "core_report",
+ # "data_explorer_query".
+ def self.source_name
+ raise NotImplementedError
+ end
+
+ # Cheap metadata resolution. Called server-side on dashboard render and
+ # by the Manage Reports modal to populate its enabled list.
+ #
+ # @param identifiers [Array<String>]
+ # @param guardian [Guardian]
+ # @return [Hash{String => AdminDashboard::Reports::ResolvedReport}]
+ # identifiers that cannot be resolved (deleted, hidden, no
+ # permission) are simply absent from the hash.
+ def self.resolve_many(identifiers, guardian:)
+ raise NotImplementedError
+ end
+
+ # Expensive data fetch. Called by the bulk endpoint to load chart/table
+ # content. Providers own their own caching.
+ #
+ # @param identifiers [Array<String>]
+ # @param guardian [Guardian]
+ # @param filters [Hash] dashboard-level filter values (date range, etc).
+ # @return [Hash{String => Object}] identifier -> report data payload.
+ def self.fetch_many(identifiers, guardian:, filters: {})
+ raise NotImplementedError
+ end
+
+ # Universe of items of this source visible to the guardian. Powers the
+ # Manage Reports modal's available list and search filter.
+ #
+ # @param guardian [Guardian]
+ # @param search [String, nil] optional name/description filter.
+ # @return [Array<AdminDashboard::Reports::ResolvedReport>]
+ def self.available_for(guardian, search: nil)
+ raise NotImplementedError
+ end
+
+ # Identifiers from the input that the guardian is allowed to mount /
+ # interact with. Default implementation is a subset of `resolve_many`
+ # keys, which works for any provider whose access check is identical
+ # to its resolution check.
+ #
+ # @param identifiers [Array<String>]
+ # @param guardian [Guardian]
+ # @return [Set<String>]
+ def self.accessible_ids(identifiers, guardian:)
+ resolve_many(identifiers, guardian: guardian).keys.to_set
+ end
+ end
+ end
+end
diff --git a/lib/discourse_plugin_registry.rb b/lib/discourse_plugin_registry.rb
index 967048ad612..8542d9e56be 100644
--- a/lib/discourse_plugin_registry.rb
+++ b/lib/discourse_plugin_registry.rb
@@ -121,6 +121,7 @@ class DiscoursePluginRegistry
define_filtered_register :stats
define_filtered_register :admin_dashboard_highlight_kpis
define_filtered_register :bookmarkables
+ define_filtered_register :admin_dashboard_report_sources
define_filtered_register :list_suggested_for_providers
diff --git a/lib/plugin/instance.rb b/lib/plugin/instance.rb
index 72fbf55af39..f83c1d30c03 100644
--- a/lib/plugin/instance.rb
+++ b/lib/plugin/instance.rb
@@ -1333,6 +1333,34 @@ class Plugin::Instance
DiscoursePluginRegistry.register_bookmarkable(RegisteredBookmarkable.new(klass), self)
end
+ ##
+ # Register a class that implements [AdminDashboard::Reports::SourceProvider],
+ # exposing a kind of report (built-in, Data Explorer query, etc.) for the
+ # customisable Reports section on the new admin dashboard. The class must
+ # inherit from AdminDashboard::Reports::SourceProvider and declare a unique
+ # `.source_name`; see the base class for the full contract.
+ def register_admin_dashboard_report_source(provider_class)
+ if !provider_class.is_a?(Class) || !(provider_class < ::AdminDashboard::Reports::SourceProvider)
+ raise ArgumentError,
+ "register_admin_dashboard_report_source expects a subclass of " \
+ "AdminDashboard::Reports::SourceProvider, got #{provider_class.inspect}"
+ end
+
+ existing =
+ ::AdminDashboard::Reports::Registry.providers.find do |klass|
+ klass.source_name.to_s == provider_class.source_name.to_s
+ end
+
+ return if existing == provider_class
+
+ if existing
+ raise ArgumentError,
+ "Source #{provider_class.source_name.inspect} is already registered by #{existing}"
+ end
+
+ DiscoursePluginRegistry.register_admin_dashboard_report_source(provider_class, self)
+ end
+
##
# Register an object that inherits from [Summarization::Base], which provides a way
# to summarize content. Staff can select which strategy to use
diff --git a/lib/seed_data/admin_dashboard_reports.rb b/lib/seed_data/admin_dashboard_reports.rb
new file mode 100644
index 00000000000..7e28eae629d
--- /dev/null
+++ b/lib/seed_data/admin_dashboard_reports.rb
@@ -0,0 +1,20 @@
+# frozen_string_literal: true
+
+module SeedData
+ class AdminDashboardReports
+ DEFAULT_BUILTIN_REPORTS = %w[daily_engaged_users time_to_first_response].freeze
+
+ def self.create
+ return if SiteSetting.admin_dashboard_reports_seeded
+
+ DEFAULT_BUILTIN_REPORTS.each do |identifier|
+ AdminDashboardReport.find_or_create_by!(
+ source: AdminDashboard::Reports::CoreReportProvider::SOURCE_NAME,
+ identifier: identifier,
+ )
+ end
+
+ SiteSetting.set(:admin_dashboard_reports_seeded, true)
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/lib/discourse_data_explorer/admin_dashboard_report_provider.rb b/plugins/discourse-data-explorer/lib/discourse_data_explorer/admin_dashboard_report_provider.rb
new file mode 100644
index 00000000000..6a4a3513884
--- /dev/null
+++ b/plugins/discourse-data-explorer/lib/discourse_data_explorer/admin_dashboard_report_provider.rb
@@ -0,0 +1,61 @@
+# frozen_string_literal: true
+
+module DiscourseDataExplorer
+ class AdminDashboardReportProvider < ::AdminDashboard::Reports::SourceProvider
+ SOURCE_NAME = "data_explorer_query"
+
+ def self.source_name
+ SOURCE_NAME
+ end
+
+ def self.resolve_many(identifiers, guardian:)
+ return {} if guardian.nil?
+
+ load_queries(identifiers).each_with_object({}) do |query, hash|
+ next if !guardian.user_can_access_query?(query)
+ hash[query.id.to_s] = build_resolved(query)
+ end
+ end
+
+ # TODO: paginate once the Manage Reports modal's list-available endpoint
+ # exists; today this loads every non-hidden Data Explorer query (sites
+ # with hundreds of queries will pay the cost).
+ def self.available_for(guardian, search: nil)
+ return [] if guardian.nil?
+
+ scope = Query.where(hidden: false).includes(:groups)
+ if search.present?
+ sanitized = "%#{Query.sanitize_sql_like(search)}%"
+ scope = scope.where("name ILIKE :s OR description ILIKE :s", s: sanitized)
+ end
+
+ scope.select { |q| guardian.user_can_access_query?(q) }.map { |q| build_resolved(q) }
+ end
+
+ def self.fetch_many(identifiers, guardian:, filters: {})
+ return {} if guardian&.user.nil?
+
+ load_queries(identifiers).each_with_object({}) do |query, hash|
+ next if !guardian.user_can_access_query?(query)
+ hash[query.id.to_s] = QueryRunner.run(query, filters, current_user: guardian.user)
+ end
+ end
+
+ def self.build_resolved(query)
+ ::AdminDashboard::Reports::ResolvedReport.new(
+ source: SOURCE_NAME,
+ identifier: query.id.to_s,
+ title: query.name,
+ description: query.description,
+ )
+ end
+ private_class_method :build_resolved
+
+ def self.load_queries(identifiers)
+ ids = identifiers.map(&:to_i).select(&:positive?)
+ return Query.none if ids.empty?
+ Query.where(id: ids, hidden: false).includes(:groups)
+ end
+ private_class_method :load_queries
+ end
+end
diff --git a/plugins/discourse-data-explorer/plugin.rb b/plugins/discourse-data-explorer/plugin.rb
index ca94e9fb228..2256272351c 100644
--- a/plugins/discourse-data-explorer/plugin.rb
+++ b/plugins/discourse-data-explorer/plugin.rb
@@ -67,6 +67,8 @@ after_initialize do
register_bookmarkable(DiscourseDataExplorer::QueryGroupBookmarkable)
+ register_admin_dashboard_report_source(DiscourseDataExplorer::AdminDashboardReportProvider)
+
add_api_key_scope(
:data_explorer,
{
diff --git a/plugins/discourse-data-explorer/spec/lib/discourse_data_explorer/admin_dashboard_report_provider_spec.rb b/plugins/discourse-data-explorer/spec/lib/discourse_data_explorer/admin_dashboard_report_provider_spec.rb
new file mode 100644
index 00000000000..3a27cb9b7fc
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/lib/discourse_data_explorer/admin_dashboard_report_provider_spec.rb
@@ -0,0 +1,133 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseDataExplorer::AdminDashboardReportProvider do
+ fab!(:admin)
+ fab!(:user)
+ fab!(:group)
+
+ let(:admin_guardian) { Guardian.new(admin) }
+ let(:user_guardian) { Guardian.new(user) }
+
+ let!(:visible_query) do
+ Fabricate(
+ :query,
+ name: "Visible query",
+ description: "Anyone can see this one",
+ sql: "SELECT 1 AS value",
+ hidden: false,
+ user: admin,
+ )
+ end
+
+ let!(:hidden_query) do
+ Fabricate(
+ :query,
+ name: "Hidden query",
+ description: "Tucked away",
+ sql: "SELECT 1 AS value",
+ hidden: true,
+ user: admin,
+ )
+ end
+
+ before { SiteSetting.data_explorer_enabled = true }
+ after { DiscourseDataExplorer::QueryRunner.invalidate(visible_query.id) }
+
+ describe ".source_name" do
+ it "is 'data_explorer_query'" do
+ expect(described_class.source_name).to eq("data_explorer_query")
+ end
+ end
+
+ describe ".resolve_many" do
+ it "resolves visible queries by id" do
+ result = described_class.resolve_many([visible_query.id.to_s], guardian: admin_guardian)
+
+ expect(result.keys).to eq([visible_query.id.to_s])
+ resolved = result[visible_query.id.to_s]
+ expect(resolved).to be_a(AdminDashboard::Reports::ResolvedReport)
+ expect(resolved.title).to eq("Visible query")
+ expect(resolved.description).to eq("Anyone can see this one")
+ expect(resolved.source).to eq("data_explorer_query")
+ end
+
+ it "omits hidden queries" do
+ result = described_class.resolve_many([hidden_query.id.to_s], guardian: admin_guardian)
+ expect(result).to be_empty
+ end
+
+ it "omits unknown ids" do
+ result = described_class.resolve_many(["999999"], guardian: admin_guardian)
+ expect(result).to be_empty
+ end
+
+ it "returns an empty hash when guardian is nil" do
+ expect(described_class.resolve_many([visible_query.id.to_s], guardian: nil)).to be_empty
+ end
+
+ context "for a non-admin user" do
+ it "omits queries the user has no access to" do
+ result = described_class.resolve_many([visible_query.id.to_s], guardian: user_guardian)
+ expect(result).to be_empty
+ end
+
+ it "resolves queries the user can access via group membership" do
+ DiscourseDataExplorer::QueryGroup.create!(query: visible_query, group: group)
+ group.add(user)
+
+ result = described_class.resolve_many([visible_query.id.to_s], guardian: user_guardian)
+ expect(result.keys).to eq([visible_query.id.to_s])
+ end
+ end
+ end
+
+ describe ".available_for" do
+ it "lists visible queries" do
+ reports = described_class.available_for(admin_guardian)
+ expect(reports.map(&:identifier)).to include(visible_query.id.to_s)
+ end
+
+ it "omits hidden queries" do
+ reports = described_class.available_for(admin_guardian)
+ expect(reports.map(&:identifier)).not_to include(hidden_query.id.to_s)
+ end
+
+ it "filters by name/description when search is given" do
+ reports = described_class.available_for(admin_guardian, search: "Visible")
+ expect(reports.map(&:identifier)).to eq([visible_query.id.to_s])
+ end
+
+ it "returns nothing when search matches no query" do
+ expect(described_class.available_for(admin_guardian, search: "zz_no_match_zz")).to be_empty
+ end
+ end
+
+ describe ".fetch_many" do
+ it "returns nothing for queries the user can't access" do
+ result = described_class.fetch_many([visible_query.id.to_s], guardian: user_guardian)
+ expect(result).to be_empty
+ end
+
+ it "runs the query and returns the result for an admin" do
+ result = described_class.fetch_many([visible_query.id.to_s], guardian: admin_guardian)
+
+ payload = result[visible_query.id.to_s]
+ expect(payload).to be_present
+ expect(payload[:success]).to eq(true)
+ expect(payload[:columns]).to include("value")
+ end
+
+ it "returns nothing for non-positive identifiers" do
+ result = described_class.fetch_many(%w[0 -1 abc], guardian: admin_guardian)
+ expect(result).to be_empty
+ end
+ end
+
+ describe "registration" do
+ it "is registered as a provider on boot" do
+ expect(AdminDashboard::Reports::Registry.provider_for("data_explorer_query")).to eq(
+ described_class,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-solved/config/settings.yml b/plugins/discourse-solved/config/settings.yml
index d8b3d468db2..ce61ee64863 100644
--- a/plugins/discourse-solved/config/settings.yml
+++ b/plugins/discourse-solved/config/settings.yml
@@ -74,4 +74,7 @@ discourse_solved:
status: "experimental"
impact: "feature,all_members"
learn_more_url: "https://meta.discourse.org/t/-/402498"
+ discourse_solved_admin_dashboard_seeded:
+ default: false
+ hidden: true
diff --git a/plugins/discourse-solved/db/fixtures/700_admin_dashboard_reports.rb b/plugins/discourse-solved/db/fixtures/700_admin_dashboard_reports.rb
new file mode 100644
index 00000000000..0d13b8a2c81
--- /dev/null
+++ b/plugins/discourse-solved/db/fixtures/700_admin_dashboard_reports.rb
@@ -0,0 +1,5 @@
+# frozen_string_literal: true
+
+require "discourse_solved/seed_admin_dashboard_reports"
+
+DiscourseSolved::SeedAdminDashboardReports.create
diff --git a/plugins/discourse-solved/lib/discourse_solved/seed_admin_dashboard_reports.rb b/plugins/discourse-solved/lib/discourse_solved/seed_admin_dashboard_reports.rb
new file mode 100644
index 00000000000..d9afc97a215
--- /dev/null
+++ b/plugins/discourse-solved/lib/discourse_solved/seed_admin_dashboard_reports.rb
@@ -0,0 +1,25 @@
+# frozen_string_literal: true
+
+module DiscourseSolved
+ class SeedAdminDashboardReports
+ REPORT_IDENTIFIER = "accepted_solutions"
+
+ def self.create
+ return if SiteSetting.discourse_solved_admin_dashboard_seeded
+ return if !solved_in_use?
+
+ ::AdminDashboardReport.find_or_create_by!(
+ source: ::AdminDashboard::Reports::CoreReportProvider::SOURCE_NAME,
+ identifier: REPORT_IDENTIFIER,
+ )
+
+ SiteSetting.set(:discourse_solved_admin_dashboard_seeded, true)
+ end
+
+ def self.solved_in_use?
+ SiteSetting.allow_solved_on_all_topics ||
+ ::CategoryCustomField.where(name: "enable_accepted_answers", value: "true").exists?
+ end
+ private_class_method :solved_in_use?
+ end
+end
diff --git a/plugins/discourse-solved/spec/lib/discourse_solved/seed_admin_dashboard_reports_spec.rb b/plugins/discourse-solved/spec/lib/discourse_solved/seed_admin_dashboard_reports_spec.rb
new file mode 100644
index 00000000000..b7289acde73
--- /dev/null
+++ b/plugins/discourse-solved/spec/lib/discourse_solved/seed_admin_dashboard_reports_spec.rb
@@ -0,0 +1,79 @@
+# frozen_string_literal: true
+
+require "discourse_solved/seed_admin_dashboard_reports"
+
+RSpec.describe DiscourseSolved::SeedAdminDashboardReports do
+ before do
+ SiteSetting.discourse_solved_admin_dashboard_seeded = false
+ AdminDashboardReport.delete_all
+ CategoryCustomField.where(name: "enable_accepted_answers").destroy_all
+ SiteSetting.allow_solved_on_all_topics = false
+ end
+
+ describe "when solved is not in use anywhere" do
+ it "does not seed and does not flip the marker" do
+ expect { described_class.create }.not_to change { AdminDashboardReport.count }
+ expect(SiteSetting.discourse_solved_admin_dashboard_seeded).to eq(false)
+ end
+ end
+
+ describe "when allow_solved_on_all_topics is enabled" do
+ before { SiteSetting.allow_solved_on_all_topics = true }
+
+ it "seeds accepted_solutions and flips the marker" do
+ described_class.create
+
+ row = AdminDashboardReport.find_by(source: "core_report", identifier: "accepted_solutions")
+ expect(row).to be_present
+ expect(SiteSetting.discourse_solved_admin_dashboard_seeded).to eq(true)
+ end
+
+ it "places accepted_solutions at the end of the existing position range" do
+ AdminDashboardReport.create!(source: "core_report", identifier: "signups", position: 0)
+ AdminDashboardReport.create!(
+ source: "core_report",
+ identifier: "time_to_first_response",
+ position: 1,
+ )
+
+ described_class.create
+
+ row = AdminDashboardReport.find_by(identifier: "accepted_solutions")
+ expect(row.position).to eq(2)
+ end
+ end
+
+ describe "when at least one category has enable_accepted_answers set" do
+ fab!(:category)
+
+ before do
+ CategoryCustomField.create!(
+ category_id: category.id,
+ name: "enable_accepted_answers",
+ value: "true",
+ )
+ end
+
+ it "seeds accepted_solutions" do
+ described_class.create
+ expect(AdminDashboardReport.exists?(identifier: "accepted_solutions")).to eq(true)
+ end
+ end
+
+ describe "re-seed protection" do
+ before { SiteSetting.allow_solved_on_all_topics = true }
+
+ it "does nothing when the marker is already set" do
+ SiteSetting.discourse_solved_admin_dashboard_seeded = true
+ expect { described_class.create }.not_to change { AdminDashboardReport.count }
+ end
+
+ it "does not resurrect the row after the admin removes it" do
+ described_class.create
+ AdminDashboardReport.where(identifier: "accepted_solutions").destroy_all
+
+ expect { described_class.create }.not_to change { AdminDashboardReport.count }
+ expect(AdminDashboardReport.exists?(identifier: "accepted_solutions")).to eq(false)
+ end
+ end
+end
diff --git a/spec/lib/admin_dashboard/reports/core_report_provider_spec.rb b/spec/lib/admin_dashboard/reports/core_report_provider_spec.rb
new file mode 100644
index 00000000000..b3752b85eae
--- /dev/null
+++ b/spec/lib/admin_dashboard/reports/core_report_provider_spec.rb
@@ -0,0 +1,125 @@
+# frozen_string_literal: true
+
+RSpec.describe AdminDashboard::Reports::CoreReportProvider do
+ fab!(:admin)
+ let(:guardian) { Guardian.new(admin) }
+
+ describe ".source_name" do
+ it "returns 'core_report'" do
+ expect(described_class.source_name).to eq("core_report")
+ end
+ end
+
+ describe ".resolve_many" do
+ it "returns ResolvedReports for known built-in report identifiers" do
+ result = described_class.resolve_many(%w[signups], guardian: guardian)
+
+ expect(result.keys).to eq(%w[signups])
+ resolved = result["signups"]
+ expect(resolved).to be_a(AdminDashboard::Reports::ResolvedReport)
+ expect(resolved.source).to eq("core_report")
+ expect(resolved.identifier).to eq("signups")
+ expect(resolved.title).to be_present
+ end
+
+ it "omits identifiers that don't correspond to a built-in report" do
+ result = described_class.resolve_many(%w[totally_made_up], guardian: guardian)
+ expect(result).to be_empty
+ end
+
+ it "handles mixed valid and invalid identifiers" do
+ result = described_class.resolve_many(%w[signups fake_one], guardian: guardian)
+ expect(result.keys).to eq(%w[signups])
+ end
+
+ it "accepts symbol identifiers" do
+ result = described_class.resolve_many([:signups], guardian: guardian)
+ expect(result.keys).to eq(%w[signups])
+ end
+ end
+
+ describe ".available_for" do
+ it "includes built-in reports" do
+ reports = described_class.available_for(guardian)
+ identifiers = reports.map(&:identifier)
+
+ expect(identifiers).to include("signups")
+ reports.each { |r| expect(r).to be_a(AdminDashboard::Reports::ResolvedReport) }
+ end
+
+ it "filters by name/description when search is given" do
+ filtered = described_class.available_for(guardian, search: "signup")
+ identifiers = filtered.map(&:identifier)
+
+ expect(identifiers).to include("signups")
+ end
+
+ it "returns no results when search matches nothing" do
+ expect(described_class.available_for(guardian, search: "zzzz_no_match_zzzz")).to be_empty
+ end
+ end
+
+ describe ".fetch_many" do
+ it "returns report payloads keyed by identifier" do
+ result = described_class.fetch_many(%w[signups], guardian: guardian, filters: {})
+
+ expect(result.keys).to eq(%w[signups])
+ payload = result["signups"]
+ expect(payload).to be_present
+ expect(payload[:type]).to eq("signups")
+ end
+
+ it "skips identifiers that don't correspond to a built-in report" do
+ result = described_class.fetch_many(%w[fake_one], guardian: guardian)
+ expect(result).to be_empty
+ end
+
+ it "scopes report data to the provided date range" do
+ Discourse.cache.clear
+ freeze_time(Time.utc(2026, 2, 15)) do
+ Fabricate(:user, created_at: Time.utc(2026, 1, 5))
+ Fabricate(:user, created_at: Time.utc(2026, 1, 5))
+ Fabricate(:user, created_at: Time.utc(2026, 1, 25))
+ Fabricate(:user, created_at: Time.utc(2026, 2, 10))
+
+ in_range =
+ described_class.fetch_many(
+ %w[signups],
+ guardian: guardian,
+ filters: {
+ start_date: "2026-01-01",
+ end_date: "2026-01-31",
+ },
+ )
+
+ out_of_range =
+ described_class.fetch_many(
+ %w[signups],
+ guardian: guardian,
+ filters: {
+ start_date: "2026-03-01",
+ end_date: "2026-03-31",
+ },
+ )
+
+ in_range_points = in_range["signups"][:data].map { |point| [point[:x].to_date, point[:y]] }
+ expect(in_range_points).to contain_exactly(
+ [Date.new(2026, 1, 5), 2],
+ [Date.new(2026, 1, 25), 1],
+ )
+
+ expect(out_of_range["signups"][:data]).to be_empty
+ end
+ end
+ end
+
+ describe "registration" do
+ it "is registered as a core provider on boot" do
+ expect(AdminDashboard::Reports::Registry::CORE_PROVIDERS).to include(described_class)
+ end
+
+ it "is discoverable via Registry.provider_for" do
+ expect(AdminDashboard::Reports::Registry.provider_for("core_report")).to eq(described_class)
+ end
+ end
+end
diff --git a/spec/lib/admin_dashboard/reports/registry_spec.rb b/spec/lib/admin_dashboard/reports/registry_spec.rb
new file mode 100644
index 00000000000..eb160cb2d1a
--- /dev/null
+++ b/spec/lib/admin_dashboard/reports/registry_spec.rb
@@ -0,0 +1,53 @@
+# frozen_string_literal: true
+
+RSpec.describe AdminDashboard::Reports::Registry do
+ let(:fake_provider) do
+ Class.new(AdminDashboard::Reports::SourceProvider) { def self.source_name = "fake_source" }
+ end
+
+ let(:plugin) { Plugin::Instance.new }
+
+ after do
+ DiscoursePluginRegistry._raw_admin_dashboard_report_sources.reject! do |entry|
+ entry[:value] == fake_provider
+ end
+ end
+
+ describe ".provider_for" do
+ it "returns nil for an unknown source name" do
+ expect(described_class.provider_for("nonexistent_source")).to be_nil
+ end
+
+ context "with a plugin-registered provider" do
+ before do
+ DiscoursePluginRegistry.register_admin_dashboard_report_source(fake_provider, plugin)
+ end
+
+ it "finds it by source_name" do
+ expect(described_class.provider_for("fake_source")).to eq(fake_provider)
+ end
+
+ it "accepts symbol source names" do
+ expect(described_class.provider_for(:fake_source)).to eq(fake_provider)
+ end
+ end
+
+ it "ignores providers from disabled plugins" do
+ DiscoursePluginRegistry.register_admin_dashboard_report_source(
+ fake_provider,
+ stub(enabled?: false),
+ )
+
+ expect(described_class.provider_for("fake_source")).to be_nil
+ end
+ end
+
+ describe ".providers" do
+ before { DiscoursePluginRegistry.register_admin_dashboard_report_source(fake_provider, plugin) }
+
+ it "combines core providers and plugin-registered providers" do
+ expect(described_class.providers).to include(fake_provider)
+ described_class::CORE_PROVIDERS.each { |p| expect(described_class.providers).to include(p) }
+ end
+ end
+end
diff --git a/spec/lib/admin_dashboard/reports/section_spec.rb b/spec/lib/admin_dashboard/reports/section_spec.rb
new file mode 100644
index 00000000000..14088bc7117
--- /dev/null
+++ b/spec/lib/admin_dashboard/reports/section_spec.rb
@@ -0,0 +1,98 @@
+# frozen_string_literal: true
+
+RSpec.describe AdminDashboard::Reports::Section do
+ fab!(:admin)
+ let(:guardian) { Guardian.new(admin) }
+
+ let(:fake_provider) do
+ Class.new(AdminDashboard::Reports::SourceProvider) do
+ def self.source_name = "fake"
+
+ def self.resolve_many(identifiers, guardian:)
+ identifiers
+ .reject { |id| id.to_s.start_with?("missing_") }
+ .each_with_object({}) do |id, h|
+ h[id.to_s] = AdminDashboard::Reports::ResolvedReport.new(
+ source: "fake",
+ identifier: id.to_s,
+ title: "Title for #{id}",
+ description: "Desc for #{id}",
+ )
+ end
+ end
+ end
+ end
+
+ let(:plugin) { Plugin::Instance.new }
+
+ before do
+ AdminDashboardReport.delete_all
+ DiscoursePluginRegistry.register_admin_dashboard_report_source(fake_provider, plugin)
+ end
+
+ after do
+ DiscoursePluginRegistry._raw_admin_dashboard_report_sources.reject! do |entry|
+ entry[:value] == fake_provider
+ end
+ end
+
+ it "returns an empty items list when there are no rows" do
+ expect(described_class.build(guardian: guardian)).to eq(items: [])
+ end
+
+ it "returns items in position order, ignoring insertion order" do
+ AdminDashboardReport.create!(source: "fake", identifier: "a", position: 1)
+ AdminDashboardReport.create!(source: "fake", identifier: "b", position: 0)
+ AdminDashboardReport.create!(source: "fake", identifier: "c", position: 2)
+
+ result = described_class.build(guardian: guardian)
+ expect(result[:items].map { |i| i[:identifier] }).to eq(%w[b a c])
+ end
+
+ it "serializes source / identifier / title / description from the resolved metadata" do
+ AdminDashboardReport.create!(source: "fake", identifier: "x", position: 0)
+
+ item = described_class.build(guardian: guardian)[:items].first
+ expect(item).to eq(
+ source: "fake",
+ identifier: "x",
+ title: "Title for x",
+ description: "Desc for x",
+ )
+ end
+
+ it "drops rows whose source has no registered provider" do
+ AdminDashboardReport.create!(source: "fake", identifier: "good", position: 0)
+ orphan = AdminDashboardReport.create!(source: "fake", identifier: "becomes_orphan", position: 1)
+ orphan.update_column(:source, "unregistered_source")
+
+ result = described_class.build(guardian: guardian)
+ expect(result[:items].map { |i| i[:identifier] }).to eq(%w[good])
+ end
+
+ it "drops rows the provider declines to resolve" do
+ AdminDashboardReport.create!(source: "fake", identifier: "good", position: 0)
+ AdminDashboardReport.create!(source: "fake", identifier: "missing_one", position: 1)
+
+ result = described_class.build(guardian: guardian)
+ expect(result[:items].map { |i| i[:identifier] }).to eq(%w[good])
+ end
+
+ it "caps at VISIBLE_CAP, dropping the oldest rows by created_at" do
+ stub_const(AdminDashboardReport, :VISIBLE_CAP, 3) do
+ 5.times do |i|
+ AdminDashboardReport.create!(
+ source: "fake",
+ identifier: "r_#{i}",
+ position: i,
+ created_at: i.minutes.ago,
+ )
+ end
+
+ result = described_class.build(guardian: guardian)
+ identifiers = result[:items].map { |i| i[:identifier] }
+
+ expect(identifiers).to eq(%w[r_0 r_1 r_2])
+ end
+ end
+end
diff --git a/spec/lib/admin_dashboard/reports/source_provider_spec.rb b/spec/lib/admin_dashboard/reports/source_provider_spec.rb
new file mode 100644
index 00000000000..fa826eeb7c3
--- /dev/null
+++ b/spec/lib/admin_dashboard/reports/source_provider_spec.rb
@@ -0,0 +1,34 @@
+# frozen_string_literal: true
+
+RSpec.describe AdminDashboard::Reports::SourceProvider do
+ describe ".accessible_ids (default implementation)" do
+ let(:provider) do
+ Class.new(described_class) do
+ def self.source_name = "test"
+
+ def self.resolve_many(identifiers, guardian:)
+ identifiers
+ .select { |id| %w[a b].include?(id) }
+ .each_with_object({}) do |id, h|
+ h[id] = AdminDashboard::Reports::ResolvedReport.new(
+ source: source_name,
+ identifier: id,
+ title: id,
+ description: nil,
+ )
+ end
+ end
+ end
+ end
+
+ it "returns the set of identifiers that resolve_many returned" do
+ result = provider.accessible_ids(%w[a b c], guardian: nil)
+ expect(result).to eq(Set.new(%w[a b]))
+ end
+
+ it "returns an empty set when nothing resolves" do
+ result = provider.accessible_ids(%w[x y z], guardian: nil)
+ expect(result).to be_empty
+ end
+ end
+end
diff --git a/spec/lib/plugin/instance_spec.rb b/spec/lib/plugin/instance_spec.rb
index 5570320ae3c..2a6a9c760d9 100644
--- a/spec/lib/plugin/instance_spec.rb
+++ b/spec/lib/plugin/instance_spec.rb
@@ -1072,6 +1072,65 @@ TEXT
end
end
+ describe "#register_admin_dashboard_report_source" do
+ let(:plugin) { Plugin::Instance.new }
+ let(:fake_provider) do
+ Class.new(AdminDashboard::Reports::SourceProvider) { def self.source_name = "fake_source" }
+ end
+
+ after do
+ DiscoursePluginRegistry._raw_admin_dashboard_report_sources.reject! do |entry|
+ entry[:value] == fake_provider
+ end
+ end
+
+ it "raises when the argument isn't a SourceProvider subclass" do
+ expect { plugin.register_admin_dashboard_report_source(Object) }.to raise_error(
+ ArgumentError,
+ /AdminDashboard::Reports::SourceProvider/,
+ )
+ end
+
+ it "raises when the argument isn't a class at all" do
+ expect { plugin.register_admin_dashboard_report_source("nope") }.to raise_error(
+ ArgumentError,
+ /AdminDashboard::Reports::SourceProvider/,
+ )
+ end
+
+ it "raises when a different provider already claims the source_name" do
+ plugin.register_admin_dashboard_report_source(fake_provider)
+
+ conflicting =
+ Class.new(AdminDashboard::Reports::SourceProvider) { def self.source_name = "fake_source" }
+
+ expect { plugin.register_admin_dashboard_report_source(conflicting) }.to raise_error(
+ ArgumentError,
+ /already registered/,
+ )
+ end
+
+ it "is idempotent when the same class is registered twice (e.g. plugin reload)" do
+ plugin.register_admin_dashboard_report_source(fake_provider)
+
+ expect do plugin.register_admin_dashboard_report_source(fake_provider) end.not_to change {
+ DiscoursePluginRegistry._raw_admin_dashboard_report_sources.count do |entry|
+ entry[:value] == fake_provider
+ end
+ }
+ end
+
+ it "raises against core source_name collisions too" do
+ core_clash =
+ Class.new(AdminDashboard::Reports::SourceProvider) { def self.source_name = "core_report" }
+
+ expect { plugin.register_admin_dashboard_report_source(core_clash) }.to raise_error(
+ ArgumentError,
+ /already registered/,
+ )
+ end
+ end
+
describe "#register_modifier" do
let(:plugin) { Plugin::Instance.new }
diff --git a/spec/lib/seed_data/admin_dashboard_reports_spec.rb b/spec/lib/seed_data/admin_dashboard_reports_spec.rb
new file mode 100644
index 00000000000..b6628e9432f
--- /dev/null
+++ b/spec/lib/seed_data/admin_dashboard_reports_spec.rb
@@ -0,0 +1,41 @@
+# frozen_string_literal: true
+
+require "seed_data/admin_dashboard_reports"
+
+RSpec.describe SeedData::AdminDashboardReports do
+ before do
+ SiteSetting.admin_dashboard_reports_seeded = false
+ AdminDashboardReport.delete_all
+ end
+
+ describe "first-time seed" do
+ it "seeds daily_engaged_users and time_to_first_response in order" do
+ described_class.create
+
+ rows = AdminDashboardReport.order(:position).pluck(:source, :identifier, :position)
+ expect(rows).to eq(
+ [["core_report", "daily_engaged_users", 1], ["core_report", "time_to_first_response", 2]],
+ )
+ end
+
+ it "flips the marker site setting after seeding" do
+ described_class.create
+ expect(SiteSetting.admin_dashboard_reports_seeded).to eq(true)
+ end
+ end
+
+ describe "re-seed protection" do
+ it "does nothing when the marker is already set" do
+ SiteSetting.admin_dashboard_reports_seeded = true
+ expect { described_class.create }.not_to change { AdminDashboardReport.count }
+ end
+
+ it "does not resurrect removed defaults on subsequent calls" do
+ described_class.create
+ AdminDashboardReport.where(identifier: "daily_engaged_users").destroy_all
+
+ expect { described_class.create }.not_to change { AdminDashboardReport.count }
+ expect(AdminDashboardReport.exists?(identifier: "daily_engaged_users")).to eq(false)
+ end
+ end
+end
diff --git a/spec/models/admin_dashboard_report_spec.rb b/spec/models/admin_dashboard_report_spec.rb
new file mode 100644
index 00000000000..fa8c8318211
--- /dev/null
+++ b/spec/models/admin_dashboard_report_spec.rb
@@ -0,0 +1,71 @@
+# frozen_string_literal: true
+
+RSpec.describe AdminDashboardReport do
+ let(:another_provider) do
+ Class.new(AdminDashboard::Reports::SourceProvider) { def self.source_name = "another_source" }
+ end
+
+ before do
+ DiscoursePluginRegistry.register_admin_dashboard_report_source(
+ another_provider,
+ Plugin::Instance.new,
+ )
+ end
+
+ after do
+ DiscoursePluginRegistry._raw_admin_dashboard_report_sources.reject! do |entry|
+ entry[:value] == another_provider
+ end
+ end
+
+ describe "validations" do
+ it "requires source and identifier" do
+ record = described_class.new
+ expect(record).not_to be_valid
+ expect(record.errors.attribute_names).to include(:source, :identifier)
+ end
+
+ it "enforces uniqueness on (source, identifier)" do
+ described_class.create!(source: "core_report", identifier: "signups")
+
+ duplicate = described_class.new(source: "core_report", identifier: "signups")
+ expect(duplicate).not_to be_valid
+ expect(duplicate.errors.attribute_names).to include(:identifier)
+ end
+
+ it "allows the same identifier under a different source" do
+ described_class.create!(source: "core_report", identifier: "signups")
+
+ other_source = described_class.new(source: "another_source", identifier: "signups")
+ expect(other_source).to be_valid
+ end
+
+ it "rejects sources without a registered provider" do
+ record = described_class.new(source: "totally_unregistered", identifier: "x")
+ expect(record).not_to be_valid
+ expect(record.errors.attribute_names).to include(:source)
+ end
+ end
+
+ describe "default position" do
+ before { described_class.delete_all }
+
+ it "assigns position 1 when there are no existing rows" do
+ record = described_class.create!(source: "core_report", identifier: "signups")
+ expect(record.position).to eq(1)
+ end
+
+ it "assigns the next position when rows already exist" do
+ described_class.create!(source: "core_report", identifier: "signups", position: 4)
+ described_class.create!(source: "core_report", identifier: "topics", position: 9)
+
+ latest = described_class.create!(source: "core_report", identifier: "page_view_total_reqs")
+ expect(latest.position).to eq(10)
+ end
+
+ it "honours an explicitly-provided position" do
+ record = described_class.create!(source: "core_report", identifier: "signups", position: 42)
+ expect(record.position).to eq(42)
+ end
+ end
+end
diff --git a/spec/requests/admin/dashboard_controller_spec.rb b/spec/requests/admin/dashboard_controller_spec.rb
index 74e96a2b00c..85b3374424a 100644
--- a/spec/requests/admin/dashboard_controller_spec.rb
+++ b/spec/requests/admin/dashboard_controller_spec.rb
@@ -290,12 +290,37 @@ RSpec.describe Admin::DashboardController do
end
it "leaves data null for sections without a builder yet" do
- SiteSetting.admin_dashboard_sections = "highlights|reports"
-
+ SiteSetting.admin_dashboard_sections = "highlights|engagement"
get "/admin/dashboard.json"
- reports = response.parsed_body["sections"].find { |s| s["id"] == "reports" }
- expect(reports["data"]).to be_nil
+ engagement = response.parsed_body["sections"].find { |s| s["id"] == "engagement" }
+ expect(engagement["data"]).to be_nil
+ end
+
+ describe "reports section data" do
+ before { AdminDashboardReport.delete_all }
+
+ def reports_data
+ response.parsed_body["sections"].find { |s| s["id"] == "reports" }&.dig("data")
+ end
+
+ it "returns an empty items list when no rows exist" do
+ get "/admin/dashboard.json"
+
+ expect(response.status).to eq(200)
+ expect(reports_data).to eq("items" => [])
+ end
+
+ it "serializes configured rows resolved via the registered providers" do
+ AdminDashboardReport.create!(source: "core_report", identifier: "signups", position: 0)
+
+ get "/admin/dashboard.json"
+
+ items = reports_data["items"]
+ expect(items.size).to eq(1)
+ expect(items.first).to include("source" => "core_report", "identifier" => "signups")
+ expect(items.first["title"]).to be_present
+ end
end
it "denies non-staff users" do
@@ -760,4 +785,136 @@ RSpec.describe Admin::DashboardController do
end
end
end
+
+ describe "POST /admin/dashboard/reports/bulk" do
+ before { SiteSetting.dashboard_improvements = true }
+
+ let(:fake_provider) do
+ Class.new(AdminDashboard::Reports::SourceProvider) do
+ def self.source_name = "fake_source"
+ def self.fetch_many(identifiers, guardian:, filters: {})
+ identifiers.each_with_object({}) do |id, h|
+ h[id.to_s] = { id: id.to_s, filters: filters }
+ end
+ end
+ end
+ end
+
+ let(:plugin) { Plugin::Instance.new }
+
+ after do
+ DiscoursePluginRegistry._raw_admin_dashboard_report_sources.reject! do |entry|
+ entry[:value] == fake_provider
+ end
+ end
+
+ context "when not signed in" do
+ it "denies access" do
+ post "/admin/dashboard/reports/bulk.json", params: { items: [] }
+ expect(response.status).to eq(404)
+ end
+ end
+
+ context "when signed in as a non-admin" do
+ before { sign_in(user) }
+
+ it "denies access" do
+ post "/admin/dashboard/reports/bulk.json", params: { items: [] }
+ expect(response.status).to eq(404)
+ end
+ end
+
+ context "when signed in as an admin" do
+ before { sign_in(admin) }
+
+ it "returns 404 when the dashboard_improvements feature flag is off" do
+ SiteSetting.dashboard_improvements = false
+ post "/admin/dashboard/reports/bulk.json", params: { items: [] }
+ expect(response.status).to eq(404)
+ end
+
+ it "returns items in the order they were requested" do
+ DiscoursePluginRegistry.register_admin_dashboard_report_source(fake_provider, plugin)
+
+ post "/admin/dashboard/reports/bulk.json",
+ params: {
+ items: [
+ { source: "fake_source", identifier: "a" },
+ { source: "fake_source", identifier: "b" },
+ { source: "fake_source", identifier: "c" },
+ ],
+ }
+
+ expect(response.status).to eq(200)
+ items = response.parsed_body["items"]
+ expect(items.map { |i| i["identifier"] }).to eq(%w[a b c])
+ expect(items.map { |i| i["source"] }).to eq(%w[fake_source fake_source fake_source])
+ end
+
+ it "returns each requested item's data, keyed by identifier" do
+ DiscoursePluginRegistry.register_admin_dashboard_report_source(fake_provider, plugin)
+
+ post "/admin/dashboard/reports/bulk.json",
+ params: {
+ items: [
+ { source: "fake_source", identifier: "a" },
+ { source: "fake_source", identifier: "b" },
+ ],
+ }
+
+ expect(response.status).to eq(200)
+ items = response.parsed_body["items"]
+ expect(items.map { |i| [i["identifier"], i["data"]["id"]] }).to eq([%w[a a], %w[b b]])
+ end
+
+ it "returns data: nil for items whose source has no registered provider" do
+ post "/admin/dashboard/reports/bulk.json",
+ params: {
+ items: [{ source: "totally_unregistered", identifier: "x" }],
+ }
+
+ expect(response.status).to eq(200)
+ items = response.parsed_body["items"]
+ expect(items.size).to eq(1)
+ expect(items.first["data"]).to be_nil
+ expect(items.first["source"]).to eq("totally_unregistered")
+ end
+
+ it "returns data shaped by the dashboard filters" do
+ DiscoursePluginRegistry.register_admin_dashboard_report_source(fake_provider, plugin)
+
+ post "/admin/dashboard/reports/bulk.json",
+ params: {
+ items: [{ source: "fake_source", identifier: "x" }],
+ filters: {
+ start_date: "2026-01-01",
+ end_date: "2026-01-31",
+ },
+ }
+
+ expect(response.status).to eq(200)
+ data = response.parsed_body["items"].first["data"]
+ expect(data["filters"]).to include("start_date" => "2026-01-01", "end_date" => "2026-01-31")
+ end
+
+ it "rejects requests with more than AdminDashboardReport::VISIBLE_CAP items" do
+ items =
+ (AdminDashboardReport::VISIBLE_CAP + 1).times.map do |i|
+ { source: "x", identifier: i.to_s }
+ end
+ post "/admin/dashboard/reports/bulk.json", params: { items: items }
+ expect(response.status).to eq(400)
+ end
+
+ it "rejects items missing source or identifier" do
+ post "/admin/dashboard/reports/bulk.json", params: { items: [{ source: "fake_source" }] }
+ expect(response.status).to eq(400)
+ end
+
+ it "rejects requests with a non-array items field" do
+ post "/admin/dashboard/reports/bulk.json", params: { items: "not_an_array" }
+ expect(response.status).to eq(400)
+ end
+ end
+ end
end