Skip to content

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

FEATURE: Customisable Reports section on the new admin dashboard (#40264)

Osama Sayeghbe54920a1294
diff --git a/app/assets/stylesheets/admin/admin_dashboard.scss b/app/assets/stylesheets/admin/admin_dashboard.scss
index fd0b9f1fe9f..5442a61cae9 100644
--- a/app/assets/stylesheets/admin/admin_dashboard.scss
+++ b/app/assets/stylesheets/admin/admin_dashboard.scss
@@ -730,13 +730,16 @@ h1 {
padding: var(--space-4);
box-sizing: border-box;
background: var(--secondary);
- height: 250px; // to be removed when cards come in with aspect-ratio;
+ height: 320px;
+ display: flex;
+ flex-direction: column;
}
&__header {
display: flex;
align-items: center;
gap: var(--space-2);
+ flex: 0 0 auto;
}
&__name {
@@ -753,17 +756,38 @@ h1 {
font-size: var(--font-down-3);
padding: var(--space-half) var(--space-2);
font-weight: 400;
-
- &.--data-explorer {
- background: var(--tertiary-low);
- color: var(--tertiary);
- }
}
&__remove {
margin-left: auto;
}
+ &__chart {
+ margin-top: var(--space-2);
+ overflow: hidden;
+ flex: 1 1 auto;
+ min-height: 0;
+
+ .chart-canvas {
+ width: 100%;
+ height: 100%;
+ }
+ }
+
+ &__empty {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: var(--space-2);
+ height: 100%;
+ color: var(--primary-medium);
+
+ .d-icon {
+ font-size: var(--font-up-3);
+ }
+ }
+
&__add-report {
border: 1px dashed var(--primary-low-mid);
border-radius: var(--d-border-radius-large);
@@ -907,16 +931,124 @@ h1 {
}
}
-.db-upgrade-banner {
+.db-reports {
+ display: contents;
+}
+
+.manage-reports__search-wrapper {
+ padding: var(--space-2) 1.5rem;
+ border-bottom: 1px solid var(--primary-low);
+ background: var(--secondary);
+}
+
+.manage-reports-modal .d-modal__footer .manage-reports__apply {
+ margin-inline-start: auto;
+}
+
+.manage-reports-modal .d-modal__body {
+ padding-inline: 0;
+ padding-block: var(--space-3);
+}
+
+.manage-reports {
display: flex;
- justify-content: space-between;
- background: var(--tertiary-very-low);
- color: var(--tertiary);
- padding: var(--space-3) var(--space-4);
- border-radius: var(--d-border-radius-large);
- font-size: var(--font-down-1-rem);
+ flex-direction: column;
+ gap: var(--space-3);
+
+ &__section-header {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: var(--space-2);
+ padding-inline: 1.5rem;
+ }
+
+ &__counter {
+ color: var(--primary-medium);
+ font-size: var(--font-down-1-rem);
+ }
+
+ &__group-title {
+ margin: 0;
+ padding-inline: 1.5rem;
+ font-size: var(--font-down-1-rem);
+ color: var(--primary-medium);
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ }
+
+ &__section-header &__group-title {
+ padding-inline: 0;
+ }
- p {
+ &__list {
+ display: flex;
+ flex-direction: column;
+ list-style: none;
margin: 0;
+ padding: 0;
+ border-top: 1px solid var(--primary-low);
+ }
+
+ &__row {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ padding: var(--space-3) 1.5rem;
+ border-bottom: 1px solid var(--primary-low);
+ background: var(--secondary);
+
+ &[draggable="true"] {
+ cursor: grab;
+ }
+ }
+
+ &__grip {
+ color: var(--primary-medium);
+ display: inline-flex;
+ }
+
+ &__row-text {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-half);
+ flex: 1 1 auto;
+ min-width: 0;
+ }
+
+ &__row-heading {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ min-width: 0;
+ }
+
+ &__title {
+ font-weight: 600;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ min-width: 0;
+ }
+
+ &__label {
+ color: var(--primary-high);
+ background: var(--primary-low);
+ border-radius: 4px;
+ font-size: var(--font-down-3);
+ padding: var(--space-half) var(--space-2);
+ flex: 0 0 auto;
+ white-space: nowrap;
+ }
+
+ &__description {
+ margin: 0;
+ color: var(--primary-medium);
+ font-size: var(--font-down-1);
+ }
+
+ &__arrow,
+ &__toggle {
+ flex: 0 0 auto;
}
}
diff --git a/app/controllers/admin/dashboard_controller.rb b/app/controllers/admin/dashboard_controller.rb
index 23caabc1403..7152ba0910b 100644
--- a/app/controllers/admin/dashboard_controller.rb
+++ b/app/controllers/admin/dashboard_controller.rb
@@ -3,7 +3,10 @@
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]
+ before_action :ensure_dashboard_improvements_enabled,
+ only: %i[bulk_reports available_reports update_reports_section]
+ before_action :ensure_admin,
+ only: %i[available_reports update_reports_section update_configuration]
def index
if dashboard_improvements?
@@ -94,29 +97,39 @@ 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
+ def update_reports_section
+ AdminDashboard::Reports::LayoutUpdater.call(
+ items: parse_reports_items_payload,
+ guardian: guardian,
+ )
+ head :no_content
+ 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
+ def available_reports
+ search = params[:search]
+ enabled = AdminDashboard::Reports::Section.build(guardian: guardian, search: search)[:items]
+ listing = AdminDashboard::Reports::Listing.call(cursor: params[:cursor], search: search)
+
+ render json: {
+ providers: listing[:providers],
+ enabled: enabled,
+ available: listing[:items],
+ has_more: listing[:has_more],
+ cursor: listing[:cursor],
+ }
+ end
+ def bulk_reports
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),
+ AdminDashboard::Reports::BulkFetch.call(
+ items: parse_reports_items_payload,
+ filters: filters,
+ guardian: guardian,
+ ),
)
end
end
@@ -155,4 +168,21 @@ class Admin::DashboardController < Admin::StaffController
SiteSetting.dashboard_improvements
end
end
+
+ def parse_reports_items_payload
+ raise Discourse::InvalidParameters.new(:items) if !params[:items].is_a?(Array)
+ if params[:items].size > AdminDashboardReport::VISIBLE_CAP
+ raise Discourse::InvalidParameters.new(:items)
+ end
+
+ 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
+ end
end
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index 8d976b7da16..1484cb97744 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -6946,6 +6946,21 @@ en:
title: "Not enough activity yet to summarise engagement."
summary: "Pick a longer date range or come back once your community has more activity."
+ reports_section:
+ add: "Add report"
+ remove: "Remove report"
+ no_data: "No data to display"
+ modal:
+ title: "Manage reports"
+ search_placeholder: "Search reports"
+ counter: "%{count} / %{max} reports"
+ enabled_heading: "Enabled"
+ all_heading: "All reports"
+ apply: "Apply"
+ toggle: "Toggle report"
+ move_up: "Move up"
+ move_down: "Move down"
+
configure:
button: "Configure"
tooltip: "Configure how this dashboard appears for everyone on this site."
diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml
index 73d8e1ed65c..c57b5b90d0a 100644
--- a/config/locales/server.en.yml
+++ b/config/locales/server.en.yml
@@ -1821,6 +1821,9 @@ en:
admin_sidebar_deprecation: "The old admin layout is deprecated in favour of the new <a href='https://meta.discourse.org/t/-/289281'>sidebar layout</a> and will be removed in the next release. You can <a href='%{base_path}/admin/config/navigation?filter=admin%20sidebar'>configure</a> the new sidebar layout now to opt in before that."
starttls_disabled: "The outgoing email configuration has STARTTLS disabled. This is almost never necessary. Consider removing <pre>DISCOURSE_SMTP_ENABLE_START_TLS=false</pre> from your environment. Please refer to <a href='https://meta.discourse.org/t/387286'>this topic</a> for more details."
back_from_logster_text: "Back to site"
+ reports_section:
+ providers:
+ core_report: "Standard"
site_settings:
allow_bulk_invite: "Allow bulk invites by uploading a CSV file"
diff --git a/config/routes.rb b/config/routes.rb
index 2de7e26e048..5a6f7dc5778 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -337,6 +337,10 @@ Discourse::Application.routes.draw do
get "dashboard/security" => "dashboard#security"
get "dashboard/reports" => "dashboard#reports"
post "dashboard/reports/bulk" => "dashboard#bulk_reports"
+ get "dashboard/reports/available" => "dashboard#available_reports",
+ :constraints => AdminConstraint.new
+ put "dashboard/reports/layout" => "dashboard#update_reports_section",
+ :constraints => AdminConstraint.new
get "dashboard/whats-new" => "dashboard#new_features"
get "/whats-new" => "dashboard#new_features"
post "/toggle-feature" => "dashboard#toggle_feature"
diff --git a/frontend/discourse/admin/components/admin-report-legacy.gjs b/frontend/discourse/admin/components/admin-report-legacy.gjs
index 4a35bc24014..34f2e1f8ce4 100644
--- a/frontend/discourse/admin/components/admin-report-legacy.gjs
+++ b/frontend/discourse/admin/components/admin-report-legacy.gjs
@@ -15,7 +15,12 @@ import { i18n } from "discourse-i18n";
<template>
<div
class={{dConcatClass "admin-report" @report.reportClasses}}
- {{didUpdate @report.fetchOrRender @filters.startDate @filters.endDate}}
+ {{didUpdate
+ @report.fetchOrRender
+ @filters.startDate
+ @filters.endDate
+ @report.preloadedData
+ }}
>
{{#unless @report.isHidden}}
<DConditionalLoadingSection @isLoading={{@report.isLoading}}>
diff --git a/frontend/discourse/admin/components/admin-report-new.gjs b/frontend/discourse/admin/components/admin-report-new.gjs
index 3f9d4fb497c..488070729d3 100644
--- a/frontend/discourse/admin/components/admin-report-new.gjs
+++ b/frontend/discourse/admin/components/admin-report-new.gjs
@@ -16,7 +16,12 @@ import { i18n } from "discourse-i18n";
<template>
<div
class={{dConcatClass "admin-report" @report.reportClasses}}
- {{didUpdate @report.fetchOrRender @filters.startDate @filters.endDate}}
+ {{didUpdate
+ @report.fetchOrRender
+ @filters.startDate
+ @filters.endDate
+ @report.preloadedData
+ }}
>
{{#unless @report.isHidden}}
<DConditionalLoadingSection @isLoading={{@report.isLoading}}>
diff --git a/frontend/discourse/admin/components/admin-report.gjs b/frontend/discourse/admin/components/admin-report.gjs
index 52a4982d940..0136d5eb0b4 100644
--- a/frontend/discourse/admin/components/admin-report.gjs
+++ b/frontend/discourse/admin/components/admin-report.gjs
@@ -171,6 +171,10 @@ export default class AdminReport extends Component {
return `/admin/reports/${dataSourceName}`;
}
+ get preloadedData() {
+ return this.args.preloadedData;
+ }
+
get showModes() {
return this.displayedModes.length > 1;
}
@@ -403,7 +407,14 @@ export default class AdminReport extends Component {
@bind
fetchOrRender() {
- if (this.args.dataSourceName) {
+ if (this.args.preloadedData) {
+ next(() => {
+ if (this.isDestroying || this.isDestroyed) {
+ return;
+ }
+ this._renderReport(this._loadReport(this.args.preloadedData));
+ });
+ } else if (this.args.dataSourceName) {
this._fetchReport();
}
}
diff --git a/frontend/discourse/admin/components/dashboard/report-cards/core-report.gjs b/frontend/discourse/admin/components/dashboard/report-cards/core-report.gjs
new file mode 100644
index 00000000000..ac24409ab0b
--- /dev/null
+++ b/frontend/discourse/admin/components/dashboard/report-cards/core-report.gjs
@@ -0,0 +1,11 @@
+import { hash } from "@ember/helper";
+import AdminReport from "discourse/admin/components/admin-report";
+
+<template>
+ <AdminReport
+ @dataSourceName={{@item.identifier}}
+ @preloadedData={{@payload}}
+ @showHeader={{false}}
+ />
+</template>
diff --git a/frontend/discourse/admin/components/dashboard/report-empty-state.gjs b/frontend/discourse/admin/components/dashboard/report-empty-state.gjs
new file mode 100644
index 00000000000..78362095dc2
--- /dev/null
+++ b/frontend/discourse/admin/components/dashboard/report-empty-state.gjs
@@ -0,0 +1,9 @@
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+
+<template>
+ <div class="db-report__empty">
+ {{dIcon "chart-pie"}}
+ <span>{{i18n "admin.dashboard.reports_section.no_data"}}</span>
+ </div>
+</template>
diff --git a/frontend/discourse/admin/components/dashboard/reports.gjs b/frontend/discourse/admin/components/dashboard/reports.gjs
index a0c2944df06..aec312aac98 100644
--- a/frontend/discourse/admin/components/dashboard/reports.gjs
+++ b/frontend/discourse/admin/components/dashboard/reports.gjs
@@ -1,91 +1,201 @@
import Component from "@glimmer/component";
+import { cached, tracked } from "@glimmer/tracking";
+import { fn, hash } from "@ember/helper";
+import { on } from "@ember/modifier";
import { action } from "@ember/object";
+import didUpdate from "@ember/render-modifiers/modifiers/did-update";
+import { service } from "@ember/service";
+import DashboardReportEmptyState from "discourse/admin/components/dashboard/report-empty-state";
import DashboardSection from "discourse/admin/components/dashboard/section";
+import ManageReports from "discourse/admin/components/modal/manage-reports";
+import { lookupAdminDashboardReportRenderer } from "discourse/admin/lib/admin-dashboard-report-renderers";
+import { loadDashboardReports } from "discourse/admin/lib/dashboard-reports-loader";
+import PluginOutlet from "discourse/components/plugin-outlet";
+import lazyHash from "discourse/helpers/lazy-hash";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
import DButton from "discourse/ui-kit/d-button";
import dIcon from "discourse/ui-kit/helpers/d-icon";
import { i18n } from "discourse-i18n";
+const VISIBLE_CAP = 10;
+
+const rendererFor = (source) => lookupAdminDashboardReportRenderer(source);
+
export default class DashboardReports extends Component {
+ @service currentUser;
+ @service modal;
+
+ @tracked cards = [];
+ @tracked loading = false;
+
+ constructor() {
+ super(...arguments);
+ this.cards = this.items.map((item) => ({ ...item, payload: null }));
+ this.loadPayloads();
+ }
+
+ get items() {
+ return this.args.data?.items ?? [];
+ }
+
+ get showLabels() {
+ return this.args.data?.show_labels ?? false;
+ }
+
+ get canEdit() {
+ return this.currentUser?.admin;
+ }
+
+ get addTileVisible() {
+ return this.canEdit && this.items.length < VISIBLE_CAP;
+ }
+
+ @cached
+ get filters() {
+ const filters = {};
+ if (this.args.startDate) {
+ filters.start_date = moment(this.args.startDate).format("YYYY-MM-DD");
+ }
+ if (this.args.endDate) {
+ filters.end_date = moment(this.args.endDate).format("YYYY-MM-DD");
+ }
+ return filters;
+ }
+
+ @action
+ async loadPayloads() {
+ if (!this.items.length) {
+ this.cards = [];
+ return;
+ }
+
+ this.loading = true;
+ try {
+ const payloads = await loadDashboardReports({
+ items: this.items.map(({ source, identifier }) => ({
+ source,
+ identifier,
+ })),
+ filters: this.filters,
+ });
+ this.cards = this.items.map((item) => ({
+ ...item,
+ payload: payloads.get(item.key),
+ }));
+ } catch (e) {
+ popupAjaxError(e);
+ } finally {
+ this.loading = false;
+ }
+ }
+
@action
openReportsConfig() {
- // eslint-disable-next-line no-console
- console.log("Reports header action clicked", {
- startDate: this.args.startDate,
- endDate: this.args.endDate,
+ this.modal.show(ManageReports, {
+ model: { onApplied: this.onLayoutChanged },
});
}
+ @action
+ async removeReport(item) {
+ const nextItems = this.items
+ .filter(
+ (i) => !(i.source === item.source && i.identifier === item.identifier)
+ )
+ .map(({ source, identifier }) => ({ source, identifier }));
+
+ try {
+ await ajax("/admin/dashboard/reports/layout", {
+ type: "PUT",
+ contentType: "application/json",
+ data: JSON.stringify({ items: nextItems }),
+ });
+ await this.onLayoutChanged();
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ }
+
+ @action
+ async onLayoutChanged() {
+ if (this.args.refreshSections) {
+ await this.args.refreshSections();
+ }
+ }
+
<template>
<DashboardSection
@title={{i18n "admin.dashboard.sections.reports.title"}}
@bordered={{false}}
@layout="grid"
- @headerActionIcon="gear"
- @headerAction={{this.openReportsConfig}}
+ @headerActionIcon={{if this.canEdit "gear"}}
+ @headerAction={{if this.canEdit this.openReportsConfig}}
@startDate={{@startDate}}
@endDate={{@endDate}}
>
- <div class="db-report__card">
- <div class="db-report__header">
- <a class="db-report__name">Pageviews by type</a>
- <div class="db-report__label">Standard</div>
- <DButton
- @icon="xmark"
- @translatedAriaLabel="Remove"
- class="db-report__remove btn-transparent btn-small"
- />
- </div>
- <div class="db-report__chart">PLACEHOLDER</div>
- </div>
-
- <div class="db-report__card">
- <div class="db-report__header">
- <a class="db-report__name">New signups</a>
- <div class="db-report__label --data-explorer">Data Explorer</div>
- <DButton
- @icon="xmark"
- @translatedAriaLabel="Remove"
- class="db-report__remove btn-transparent btn-small"
- />
- </div>
- <div class="db-report__chart">PLACEHOLDER</div>
- </div>
-
- <div class="db-report__card">
- <div class="db-report__header">
- <a class="db-report__name">Active users</a>
- <div class="db-report__label">Standard</div>
- <DButton
- @icon="xmark"
- @translatedAriaLabel="Remove"
- class="db-report__remove btn-transparent btn-small"
- />
- </div>
- <div class="db-report__chart">PLACEHOLDER</div>
- </div>
+ <div
+ class="db-reports"
+ {{didUpdate this.loadPayloads @data @startDate @endDate}}
+ >
+ {{#each this.cards key="key" as |card|}}
+ <div class="db-report__card" data-identifier={{card.key}}>
+ <div class="db-report__header">
+ <span class="db-report__name">{{card.title}}</span>
+ {{#if this.showLabels}}
+ <div
+ class="db-report__label"
+ data-source={{card.source}}
+ >{{card.label}}</div>
+ {{/if}}
+ {{#if this.canEdit}}
+ <DButton
+ @icon="xmark"
+ @translatedAriaLabel={{i18n
+ "admin.dashboard.reports_section.remove"
+ }}
+ @action={{fn this.removeReport card}}
+ class="db-report__remove btn-transparent btn-small"
+ />
+ {{/if}}
+ </div>
+ <div class="db-report__chart">
+ {{#if card.payload}}
+ {{#if card.payload.empty}}
+ <DashboardReportEmptyState />
+ {{else}}
+ {{#let (rendererFor card.source) as |Renderer|}}
+ {{#if Renderer}}
+ <Renderer
+ @item={{card}}
+ @payload={{card.payload}}
+ @filters={{hash startDate=@startDate endDate=@endDate}}
+ />
+ {{/if}}
+ {{/let}}
+ {{/if}}
+ {{/if}}
+ </div>
+ </div>
+ {{/each}}
- <div class="db-report__card">
- <div class="db-report__header">
- <a class="db-report__name">Active users</a>
- <div class="db-report__label">Standard</div>
- <DButton
- @icon="xmark"
- @translatedAriaLabel="Remove"
- class="db-report__remove btn-transparent btn-small"
- />
- </div>
- <div class="db-report__chart">PLACEHOLDER</div>
+ {{#if this.addTileVisible}}
+ <button
+ type="button"
+ class="db-report__add-report"
+ aria-label={{i18n "admin.dashboard.reports_section.add"}}
+ {{on "click" this.openReportsConfig}}
+ >
+ <span>{{dIcon "plus"}}
+ {{i18n "admin.dashboard.reports_section.add"}}</span>
+ </button>
+ {{/if}}
</div>
- <button class="db-report__add-report" aria-label="Add report"><span
- >{{dIcon "plus"}}
- Add report</span></button>
+ <PluginOutlet
+ @name="admin-dashboard-reports-section-after"
+ @outletArgs={{lazyHash startDate=@startDate endDate=@endDate}}
+ />
</DashboardSection>
-
- <aside class="db-upgrade-banner">
- <p>Upgrade to pin Data Explorer queries as charts to track anything
- specific to your community.</p>
- <DButton @display="link" @suffixIcon="arrow-right">Upgrade</DButton>
- </aside>
</template>
}
diff --git a/frontend/discourse/admin/components/modal/manage-reports.gjs b/frontend/discourse/admin/components/modal/manage-reports.gjs
new file mode 100644
index 00000000000..8503cc11a88
--- /dev/null
+++ b/frontend/discourse/admin/components/modal/manage-reports.gjs
@@ -0,0 +1,410 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn, hash } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import PluginOutlet from "discourse/components/plugin-outlet";
+import lazyHash from "discourse/helpers/lazy-hash";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import discourseDebounce from "discourse/lib/debounce";
+import { eq } from "discourse/truth-helpers";
+import DButton from "discourse/ui-kit/d-button";
+import DFilterInput from "discourse/ui-kit/d-filter-input";
+import DLoadMore from "discourse/ui-kit/d-load-more";
+import DModal from "discourse/ui-kit/d-modal";
+import DToggleSwitch from "discourse/ui-kit/d-toggle-switch";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+
+const VISIBLE_CAP = 10;
+const SEARCH_DEBOUNCE_MS = 200;
+
+export default class ManageReports extends Component {
+ @service site;
+
+ @tracked allKeys = [];
+ @tracked enabledOrder = [];
+ @tracked providers = [];
+ @tracked search = "";
+ @tracked nextCursor = null;
+ @tracked hasMore = false;
+ @tracked loading = true;
+ @tracked loadingMore = false;
+ @tracked applying = false;
+ @tracked draggedId = null;
+ itemsByKey = new Map();
+
+ isEnabled = (row) => this.enabledKeys.has(row.key);
+ toggleDisabled = (row) => this.atCap && !this.isEnabled(row);
+
+ constructor() {
+ super(...arguments);
+ this.load();
+ }
+
+ get showLabels() {
+ return this.providers.length > 1;
+ }
+
+ get enabledKeys() {
+ return new Set(this.enabledOrder);
+ }
+
+ get enabledRows() {
+ return this.enabledOrder
+ .map((key) => this.itemsByKey.get(key))
+ .filter(Boolean);
+ }
+
+ get allRows() {
+ return this.allKeys.map((key) => this.itemsByKey.get(key)).filter(Boolean);
+ }
+
+ get visibleEnabled() {
+ return this.enabledRows;
+ }
+
+ get visibleAll() {
+ return this.allRows;
+ }
+
+ get atCap() {
+ return this.enabledOrder.length >= VISIBLE_CAP;
+ }
+
+ cacheItems(items) {
+ for (const item of items) {
+ this.itemsByKey.set(item.key, item);
+ }
+ }
+
+ @action
+ async load() {
+ this.loading = true;
+ try {
+ const response = await this.fetchAll(null);
+ const enabled = response.enabled ?? [];
+ const page = response.available ?? [];
+
+ this.providers = response.providers ?? [];
+ this.cacheItems(enabled);
+ this.cacheItems(page);
+ this.enabledOrder = enabled.map((item) => item.key);
+ this.allKeys = page.map((item) => item.key);
+ this.nextCursor = response.cursor ?? null;
+ this.hasMore = !!response.has_more;
+ } catch (e) {
+ popupAjaxError(e);
+ } finally {
+ this.loading = false;
+ }
+ }
+
+ @action
+ async loadMore() {
+ if (this.loadingMore || !this.hasMore || !this.nextCursor) {
+ return;
+ }
+ this.loadingMore = true;
+ try {
+ const response = await this.fetchAll(this.nextCursor);
+ const page = response.available ?? [];
+ this.cacheItems(page);
+ this.allKeys = [...this.allKeys, ...page.map((item) => item.key)];
+ this.nextCursor = response.cursor ?? null;
+ this.hasMore = !!response.has_more;
+ } catch (e) {
+ popupAjaxError(e);
+ } finally {
+ this.loadingMore = false;
+ }
+ }
+
+ async fetchAll(cursor) {
+ const data = {};
+ if (cursor) {
+ data.cursor = cursor;
+ }
+ if (this.search.trim()) {
+ data.search = this.search.trim();
+ }
+ return await ajax("/admin/dashboard/reports/available.json", { data });
+ }
+
+ @action
+ updateSearch(event) {
+ this.search = event.target.value;
+ discourseDebounce(this, this.refetchForSearch, SEARCH_DEBOUNCE_MS);
+ }
+
+ @action
+ async refetchForSearch() {
+ try {
+ const response = await this.fetchAll(null);
+ const enabled = response.enabled ?? [];
+ const page = response.available ?? [];
+ this.cacheItems(enabled);
+ this.cacheItems(page);
+ this.enabledOrder = enabled.map((item) => item.key);
+ this.allKeys = page.map((item) => item.key);
+ this.nextCursor = response.cursor ?? null;
+ this.hasMore = !!response.has_more;
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ }
+
+ @action
+ toggle(row) {
+ this.itemsByKey.set(row.key, row);
+ if (this.enabledKeys.has(row.key)) {
+ this.enabledOrder = this.enabledOrder.filter((k) => k !== row.key);
+ } else if (!this.atCap) {
+ this.enabledOrder = [...this.enabledOrder, row.key];
+ }
+ }
+
+ @action
+ moveUp(row) {
+ const index = this.enabledOrder.indexOf(row.key);
+ if (index <= 0) {
+ return;
+ }
+ const next = [...this.enabledOrder];
+ [next[index - 1], next[index]] = [next[index], next[index - 1]];
+ this.enabledOrder = next;
+ }
+
+ @action
+ moveDown(row) {
+ const index = this.enabledOrder.indexOf(row.key);
+ if (index < 0 || index === this.enabledOrder.length - 1) {
+ return;
+ }
+ const next = [...this.enabledOrder];
+ [next[index], next[index + 1]] = [next[index + 1], next[index]];
+ this.enabledOrder = next;
+ }
+
+ @action
+ onDragStart(row, event) {
+ this.draggedId = row.key;
+ event.dataTransfer.effectAllowed = "move";
+ }
+
+ @action
+ onDragOver(event) {
+ event.preventDefault();
+ event.dataTransfer.dropEffect = "move";
+ }
+
+ @action
+ onDrop(target) {
+ if (!this.draggedId) {
+ return;
+ }
+ const fromIndex = this.enabledOrder.indexOf(this.draggedId);
+ const toIndex = this.enabledOrder.indexOf(target.key);
+ if (fromIndex < 0 || toIndex < 0 || fromIndex === toIndex) {
+ this.draggedId = null;
+ return;
+ }
+ const next = [...this.enabledOrder];
+ const [moved] = next.splice(fromIndex, 1);
+ next.splice(toIndex, 0, moved);
+ this.enabledOrder = next;
+ this.draggedId = null;
+ }
+
+ @action
+ onDragEnd() {
+ this.draggedId = null;
+ }
+
+ @action
+ async apply() {
+ this.applying = true;
+ try {
+ await ajax("/admin/dashboard/reports/layout", {
+ type: "PUT",
+ contentType: "application/json",
+ data: JSON.stringify({
+ items: this.enabledRows.map(({ source, identifier }) => ({
+ source,
+ identifier,
+ })),
+ }),
+ });
+ this.args.closeModal?.();
+ this.args.model?.onApplied?.();
+ } catch (e) {
+ popupAjaxError(e);
+ } finally {
+ this.applying = false;
+ }
+ }
+
+ <template>
+ <DModal
+ @title={{i18n "admin.dashboard.reports_section.modal.title"}}
+ @closeModal={{@closeModal}}
+ class="manage-reports-modal"
+ >
+ <:belowHeader>
+ <div class="manage-reports__search-wrapper">
+ <DFilterInput
+ @icons={{hash left="magnifying-glass"}}
+ @value={{this.search}}
+ @filterAction={{this.updateSearch}}
+ placeholder={{i18n
+ "admin.dashboard.reports_section.modal.search_placeholder"
+ }}
+ />
+ </div>
+ </:belowHeader>
+
+ <:body>
+ <div class="manage-reports">
+ {{#if this.visibleEnabled.length}}
+ <div class="manage-reports__section-header">
+ <h3 class="manage-reports__group-title">
+ {{i18n "admin.dashboard.reports_section.modal.enabled_heading"}}
+ </h3>
+ <span class="manage-reports__counter">
+ {{i18n
+ "admin.dashboard.reports_section.modal.counter"
+ count=this.enabledOrder.length
+ max=VISIBLE_CAP
+ }}
+ </span>
+ </div>
+ <ul class="manage-reports__list manage-reports__list--enabled">
+ {{#each this.visibleEnabled key="key" as |row index|}}
+ <li
+ class="manage-reports__row"
+ draggable="true"
+ data-identifier={{row.key}}
+ {{on "dragstart" (fn this.onDragStart row)}}
+ {{on "dragover" this.onDragOver}}
+ {{on "drop" (fn this.onDrop row)}}
+ {{on "dragend" this.onDragEnd}}
+ >
+ {{#unless this.site.mobileView}}
+ <span class="manage-reports__grip">
+ {{dIcon "grip-lines"}}
+ </span>
+ {{/unless}}
+ <div class="manage-reports__row-text">
+ <div class="manage-reports__row-heading">
+ <span class="manage-reports__title">{{row.title}}</span>
+ {{#if this.showLabels}}
+ <span
+ class="manage-reports__label"
+ data-source={{row.source}}
+ >{{row.label}}</span>
+ {{/if}}
+ </div>
+ {{#if row.description}}
+ <p
+ class="manage-reports__description"
+ >{{row.description}}</p>
+ {{/if}}
+ </div>
+ {{#if this.site.mobileView}}
+ <DButton
+ @icon="arrow-up"
+ @action={{fn this.moveUp row}}
+ @disabled={{eq index 0}}
+ @translatedAriaLabel={{i18n
+ "admin.dashboard.reports_section.modal.move_up"
+ }}
+ class="manage-reports__arrow btn-transparent btn-small"
+ />
+ <DButton
+ @icon="arrow-down"
+ @action={{fn this.moveDown row}}
+ @translatedAriaLabel={{i18n
+ "admin.dashboard.reports_section.modal.move_down"
+ }}
+ class="manage-reports__arrow btn-transparent btn-small"
+ />
+ {{/if}}
+ <DToggleSwitch
+ @state={{this.isEnabled row}}
+ aria-label={{i18n
+ "admin.dashboard.reports_section.modal.toggle"
+ }}
+ {{on "click" (fn this.toggle row)}}
+ />
+ </li>
+ {{/each}}
+ </ul>
+ {{/if}}
+
+ {{#if this.visibleAll.length}}
+ <h3 class="manage-reports__group-title">
+ {{i18n "admin.dashboard.reports_section.modal.all_heading"}}
+ </h3>
+ <ul class="manage-reports__list manage-reports__list--all">
+ {{#each this.visibleAll key="key" as |row|}}
+ <li class="manage-reports__row" data-identifier={{row.key}}>
+ <div class="manage-reports__row-text">
+ <div class="manage-reports__row-heading">
+ <span class="manage-reports__title">{{row.title}}</span>
+ {{#if this.showLabels}}
+ <span
+ class="manage-reports__label"
+ data-source={{row.source}}
+ >{{row.label}}</span>
+ {{/if}}
+ </div>
+ {{#if row.description}}
+ <p
+ class="manage-reports__description"
+ >{{row.description}}</p>
+ {{/if}}
+ </div>
+ <DToggleSwitch
+ @state={{this.isEnabled row}}
+ disabled={{this.toggleDisabled row}}
+ aria-label={{i18n
+ "admin.dashboard.reports_section.modal.toggle"
+ }}
+ {{on "click" (fn this.toggle row)}}
+ />
+ </li>
+ {{/each}}
+ </ul>
+ <DLoadMore
+ @action={{this.loadMore}}
+ @enabled={{this.hasMore}}
+ @isLoading={{this.loading}}
+ />
+ {{/if}}
+ </div>
+ </:body>
+
+ <:aboveFooter>
+ <PluginOutlet
+ @name="admin-dashboard-manage-reports-footer"
+ @outletArgs={{lazyHash
+ providers=this.providers
+ enabled=this.enabledRows
+ }}
+ />
+ </:aboveFooter>
+
+ <:footer>
+ <DButton
+ @label="admin.dashboard.reports_section.modal.apply"
+ @action={{this.apply}}
+ @disabled={{this.applying}}
+ @isLoading={{this.applying}}
+ class="btn-primary manage-reports__apply"
+ />
+ </:footer>
+ </DModal>
+ </template>
+}
diff --git a/frontend/discourse/admin/components/redesigned-admin-dashboard.gjs b/frontend/discourse/admin/components/redesigned-admin-dashboard.gjs
index 13f44eeb3de..21bfc767557 100644
--- a/frontend/discourse/admin/components/redesigned-admin-dashboard.gjs
+++ b/frontend/discourse/admin/components/redesigned-admin-dashboard.gjs
@@ -135,8 +135,10 @@ export default class RedesignedAdminDashboard extends Component {
/>
{{else if (eq section.id "reports")}}
<DashboardReports
+ @data={{section.data}}
@startDate={{@loadedSections.startDate}}
@endDate={{@loadedSections.endDate}}
+ @refreshSections={{@refreshSections}}
/>
{{else if (eq section.id "traffic")}}
<DashboardTraffic
diff --git a/frontend/discourse/admin/controllers/admin/dashboard.js b/frontend/discourse/admin/controllers/admin/dashboard.js
index 64b4b09f6d2..69cdf749b84 100644
--- a/frontend/discourse/admin/controllers/admin/dashboard.js
+++ b/frontend/discourse/admin/controllers/admin/dashboard.js
@@ -95,6 +95,7 @@ export default class AdminDashboardController extends Controller {
await this.fetchSections();
}
+ @action
async fetchSections() {
const id = ++this._sectionsLoadId;
const period = this.safePeriod;
diff --git a/frontend/discourse/admin/lib/admin-dashboard-report-renderers.js b/frontend/discourse/admin/lib/admin-dashboard-report-renderers.js
new file mode 100644
index 00000000000..6076a4cb1ae
--- /dev/null
+++ b/frontend/discourse/admin/lib/admin-dashboard-report-renderers.js
@@ -0,0 +1,18 @@
+import CoreReportCard from "discourse/admin/components/dashboard/report-cards/core-report";
+
+const renderers = new Map();
+
+export function registerAdminDashboardReportRenderer(source, ComponentClass) {
+ renderers.set(source, ComponentClass);
+}
+
+export function lookupAdminDashboardReportRenderer(source) {
+ if (source === "core_report") {
+ return CoreReportCard;
+ }
+ return renderers.get(source);
+}
+
+export function resetAdminDashboardReportRenderers() {
+ renderers.clear();
+}
diff --git a/frontend/discourse/admin/lib/dashboard-reports-loader.js b/frontend/discourse/admin/lib/dashboard-reports-loader.js
new file mode 100644
index 00000000000..77e7973a609
--- /dev/null
+++ b/frontend/discourse/admin/lib/dashboard-reports-loader.js
@@ -0,0 +1,19 @@
+import { ajax } from "discourse/lib/ajax";
+
+export async function loadDashboardReports({ items, filters }) {
+ if (!items?.length) {
+ return new Map();
+ }
+
+ const response = await ajax("/admin/dashboard/reports/bulk", {
+ type: "POST",
+ contentType: "application/json",
+ data: JSON.stringify({ items, filters }),
+ });
+
+ const map = new Map();
+ for (const entry of response.items) {
+ map.set(entry.key, entry.data);
+ }
+ return map;
+}
diff --git a/frontend/discourse/admin/templates/admin/dashboard.gjs b/frontend/discourse/admin/templates/admin/dashboard.gjs
index 366a2032388..eadfe10a769 100644
--- a/frontend/discourse/admin/templates/admin/dashboard.gjs
+++ b/frontend/discourse/admin/templates/admin/dashboard.gjs
@@ -17,6 +17,7 @@ export default <template>
@setCustomDateRange={{@controller.setCustomDateRange}}
@loadedSections={{@controller.loadedSections}}
@updateConfiguration={{@controller.updateConfiguration}}
+ @refreshSections={{@controller.fetchSections}}
@loadingSections={{@controller.loadingSections}}
@sectionsFetchError={{@controller.sectionsFetchError}}
/>
diff --git a/frontend/discourse/app/lib/plugin-api.gjs b/frontend/discourse/app/lib/plugin-api.gjs
index 665353a659f..887a52b265e 100644
--- a/frontend/discourse/app/lib/plugin-api.gjs
+++ b/frontend/discourse/app/lib/plugin-api.gjs
@@ -1,5 +1,6 @@
/* eslint-disable ember/no-jquery */
import $ from "jquery";
+import { registerAdminDashboardReportRenderer } from "discourse/admin/lib/admin-dashboard-report-renderers";
import { _renderBlocks } from "discourse/blocks/block-outlet";
import { addAboutPageActivity } from "discourse/components/about-page";
import { addBulkDropdownButton } from "discourse/components/bulk-select-topics-dropdown";
@@ -2927,6 +2928,28 @@ class _PluginApi {
registerNotificationTypeRenderer(notificationType, func);
}
+ /**
+ * Registers a component used to render a report on the customisable
+ * Reports section of the new admin dashboard. Pair with the server-side
+ * `register_admin_dashboard_report_source` registration: the source name
+ * passed here matches the provider's `source_name`. The component
+ * receives `@item`, `@payload`, and `@filters` and is mounted inside the
+ * card's chart area; the card frame (title, label pill, X-to-remove) is
+ * owned by core.
+ *
+ * ```
+ * import MyReportCard from "discourse/plugins/my-plugin/discourse/components/my-report-card";
+ *
+ * api.registerAdminDashboardReportRenderer("my_source", MyReportCard);
+ * ```
+ *
+ * @param {string} source - The provider's source_name.
+ * @param {Component} componentClass - A Glimmer component that accepts @item, @payload, @filters.
+ */
+ registerAdminDashboardReportRenderer(source, componentClass) {
+ registerAdminDashboardReportRenderer(source, componentClass);
+ }
+
/**
* Registers a new tab in the user menu. This API method expects a callback
* that should return a class inheriting from the class (UserMenuTab) that's
diff --git a/frontend/discourse/app/ui-kit/d-modal.gjs b/frontend/discourse/app/ui-kit/d-modal.gjs
index f988d5c20ba..42f1d603a87 100644
--- a/frontend/discourse/app/ui-kit/d-modal.gjs
+++ b/frontend/discourse/app/ui-kit/d-modal.gjs
@@ -449,6 +449,10 @@ export default class DModal extends Component {
{{/if}}
</div>
+ {{#if (and (has-block "aboveFooter") (not @hideFooter))}}
+ {{yield to="aboveFooter"}}
+ {{/if}}
+
{{#if (and (has-block "footer") (not @hideFooter))}}
<div class="d-modal__footer">
{{yield to="footer"}}
diff --git a/frontend/discourse/tests/helpers/qunit-helpers.js b/frontend/discourse/tests/helpers/qunit-helpers.js
index aff03b98992..cbd2cbef5ab 100644
--- a/frontend/discourse/tests/helpers/qunit-helpers.js
+++ b/frontend/discourse/tests/helpers/qunit-helpers.js
@@ -14,6 +14,7 @@ import MessageBus from "message-bus-client";
import { resetCache as resetOneboxCache } from "pretty-text/oneboxer";
import QUnit, { module, test } from "qunit";
import sinon from "sinon";
+import { resetAdminDashboardReportRenderers } from "discourse/admin/lib/admin-dashboard-report-renderers";
import { _resetOutletLayoutsForTesting } from "discourse/blocks/block-outlet";
import { clearAboutPageActivities } from "discourse/components/about-page";
import { resetCardClickListenerSelector } from "discourse/components/card-contents-base";
@@ -213,6 +214,7 @@ export function testCleanup(container, app) {
User.resetCurrent();
resetMobile();
resetAdditionalReportModes();
+ resetAdminDashboardReportRenderers();
resetExtraClasses();
clearOutletCache();
clearHTMLCache();
diff --git a/lib/admin_dashboard/reports/bulk_fetch.rb b/lib/admin_dashboard/reports/bulk_fetch.rb
index 7f58232ea23..0f5eb2d7f82 100644
--- a/lib/admin_dashboard/reports/bulk_fetch.rb
+++ b/lib/admin_dashboard/reports/bulk_fetch.rb
@@ -4,37 +4,23 @@ 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
+ results =
+ items.map do |item|
+ {
+ source: item[:source],
+ identifier: item[:identifier],
+ key: "#{item[:source]}:#{item[:identifier]}",
+ data: per_source.dig(item[:source], item[:identifier]),
+ }
+ end
+
+ { items: results }
end
end
end
diff --git a/lib/admin_dashboard/reports/core_report_provider.rb b/lib/admin_dashboard/reports/core_report_provider.rb
index 7563b3eeb0d..f8310a780a8 100644
--- a/lib/admin_dashboard/reports/core_report_provider.rb
+++ b/lib/admin_dashboard/reports/core_report_provider.rb
@@ -9,8 +9,18 @@ module AdminDashboard
SOURCE_NAME
end
+ def self.label
+ I18n.t("dashboard.reports_section.providers.core_report")
+ end
+
def self.resolve_many(identifiers, guardian:)
- index = available_for(guardian).index_by(&:identifier)
+ return {} if guardian.nil?
+
+ index =
+ ::Reports::ListQuery
+ .call(guardian: guardian)
+ .map { |entry| build_resolved(entry) }
+ .index_by(&:identifier)
identifiers.each_with_object({}) do |identifier, hash|
key = identifier.to_s
resolved = index[key]
@@ -28,7 +38,7 @@ module AdminDashboard
cached = ::Report.find_cached(key, opts)
if cached
- hash[key] = cached
+ hash[key] = with_empty_flag(cached)
next
end
@@ -36,16 +46,20 @@ module AdminDashboard
next if report.blank?
::Report.cache(report)
- hash[key] = report.as_json
+ hash[key] = with_empty_flag(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)
+ def self.with_empty_flag(payload)
+ payload.merge(empty: payload[:data].blank?)
+ end
+ private_class_method :with_empty_flag
+
+ def self.list_all(search: nil, offset: 0, limit: nil)
+ entries = ::Reports::ListQuery.call(guardian: Guardian.new(Discourse.system_user))
entries = filter_by_search(entries, search) if search.present?
- entries.map { |entry| build_resolved(entry) }
+ sliced = limit ? entries[offset, limit] : entries[offset..]
+ Array(sliced).map { |entry| build_resolved(entry) }
end
def self.build_resolved(entry)
@@ -54,6 +68,8 @@ module AdminDashboard
identifier: entry[:type],
title: entry[:title],
description: entry[:description],
+ label: label,
+ url: "/admin/reports/#{entry[:type]}",
)
end
private_class_method :build_resolved
diff --git a/lib/admin_dashboard/reports/layout_updater.rb b/lib/admin_dashboard/reports/layout_updater.rb
new file mode 100644
index 00000000000..198b84bf34e
--- /dev/null
+++ b/lib/admin_dashboard/reports/layout_updater.rb
@@ -0,0 +1,36 @@
+# frozen_string_literal: true
+
+module AdminDashboard
+ module Reports
+ class LayoutUpdater
+ def self.call(items:, guardian:)
+ items
+ .group_by { |item| item[:source] }
+ .each do |source, group|
+ provider = Registry.provider_for(source)
+ raise Discourse::InvalidParameters.new(:items) if provider.nil?
+
+ requested = group.map { |item| item[:identifier] }.to_set
+ accessible = provider.accessible_ids(requested.to_a, guardian: guardian)
+ raise Discourse::InvalidAccess unless requested.subset?(accessible)
+ end
+
+ AdminDashboardReport.transaction do
+ AdminDashboardReport.delete_all
+ now = Time.current
+ rows =
+ items.each_with_index.map do |item, index|
+ {
+ source: item[:source],
+ identifier: item[:identifier],
+ position: index,
+ created_at: now,
+ updated_at: now,
+ }
+ end
+ AdminDashboardReport.insert_all(rows) if rows.any?
+ end
+ end
+ end
+ end
+end
diff --git a/lib/admin_dashboard/reports/listing.rb b/lib/admin_dashboard/reports/listing.rb
new file mode 100644
index 00000000000..d7fd5ba101c
--- /dev/null
+++ b/lib/admin_dashboard/reports/listing.rb
@@ -0,0 +1,74 @@
+# frozen_string_literal: true
+
+module AdminDashboard
+ module Reports
+ class Listing
+ PAGE_SIZE = 30
+
+ def self.call(cursor:, search:)
+ new(cursor: cursor, search: search).call
+ end
+
+ def initialize(cursor:, search:)
+ @cursor = parse_cursor(cursor)
+ @search = search.presence
+ end
+
+ def call
+ collected = walk_providers
+ has_more = collected.size > PAGE_SIZE
+
+ {
+ providers: provider_summaries,
+ items: collected.first(PAGE_SIZE).map { |entry| entry[:item].to_h },
+ has_more: has_more,
+ cursor: has_more ? format_cursor(collected[PAGE_SIZE]) : nil,
+ }
+ end
+
+ private
+
+ def walk_providers
+ providers = Registry.providers
+ start_index = @cursor ? providers.find_index { |p| p.source_name == @cursor[:source] } : 0
+ walk = start_index ? providers[start_index..] : []
+ current_offset = @cursor ? @cursor[:offset] : 0
+
+ collected = []
+ to_take = PAGE_SIZE + 1
+ walk.each do |provider|
+ break if to_take <= 0
+
+ items = provider.list_all(search: @search, offset: current_offset, limit: to_take)
+ items.each_with_index do |item, i|
+ collected << { source: provider.source_name, item: item, offset: current_offset + i }
+ end
+ to_take -= items.size
+ current_offset = 0
+ end
+
+ collected
+ end
+
+ def provider_summaries
+ Registry.providers.map { |p| { source: p.source_name, label: p.label } }
+ end
+
+ def parse_cursor(raw)
+ return nil if raw.blank?
+
+ source, offset = raw.to_s.split(":", 2)
+ return nil if source.blank? || offset.blank?
+
+ offset_int = Integer(offset, 10, exception: false)
+ return nil if offset_int.nil? || offset_int < 0
+
+ { source: source, offset: offset_int }
+ end
+
+ def format_cursor(entry)
+ "#{entry[:source]}:#{entry[:offset]}"
+ end
+ end
+ end
+end
diff --git a/lib/admin_dashboard/reports/resolved_report.rb b/lib/admin_dashboard/reports/resolved_report.rb
index e6ba7eb0078..5a988c6195a 100644
--- a/lib/admin_dashboard/reports/resolved_report.rb
+++ b/lib/admin_dashboard/reports/resolved_report.rb
@@ -2,6 +2,15 @@
module AdminDashboard
module Reports
- ResolvedReport = Data.define(:source, :identifier, :title, :description)
+ ResolvedReport =
+ Data.define(:source, :identifier, :title, :description, :label, :url) do
+ def key
+ "#{source}:#{identifier}"
+ end
+
+ def to_h
+ super.merge(key: key)
+ end
+ end
end
end
diff --git a/lib/admin_dashboard/reports/section.rb b/lib/admin_dashboard/reports/section.rb
index f06c2d880bd..6d9b1044a30 100644
--- a/lib/admin_dashboard/reports/section.rb
+++ b/lib/admin_dashboard/reports/section.rb
@@ -3,16 +3,20 @@
module AdminDashboard
module Reports
class Section
- def self.build(guardian:)
- new(guardian: guardian).build
+ def self.build(guardian:, search: nil)
+ new(guardian: guardian, search: search).build
end
- def initialize(guardian:)
+ def initialize(guardian:, search: nil)
@guardian = guardian
+ @search = search.presence
end
def build
- { items: visible_items.map { |_row, resolved| serialize(resolved) } }
+ items = visible_items.map { |_row, resolved| serialize(resolved) }
+ items = filter_by_search(items) if @search
+
+ { items: items, show_labels: AdminDashboard::Reports::Registry.providers.length > 1 }
end
private
@@ -44,12 +48,15 @@ module AdminDashboard
end
def serialize(resolved)
- {
- source: resolved.source,
- identifier: resolved.identifier,
- title: resolved.title,
- description: resolved.description,
- }
+ resolved.to_h
+ end
+
+ def filter_by_search(items)
+ query = @search.downcase
+ items.select do |item|
+ item[:title].to_s.downcase.include?(query) ||
+ item[:description].to_s.downcase.include?(query)
+ end
end
end
end
diff --git a/lib/admin_dashboard/reports/source_provider.rb b/lib/admin_dashboard/reports/source_provider.rb
index 3a613876f59..99bed8ef8d5 100644
--- a/lib/admin_dashboard/reports/source_provider.rb
+++ b/lib/admin_dashboard/reports/source_provider.rb
@@ -18,6 +18,13 @@ module AdminDashboard
raise NotImplementedError
end
+ # @return [String] a short, translated label rendered as a tag pill in
+ # the UI to distinguish this provider from others.
+ # Only shown when more than one provider is registered.
+ def self.label
+ raise NotImplementedError
+ end
+
# Cheap metadata resolution. Called server-side on dashboard render and
# by the Manage Reports modal to populate its enabled list.
#
@@ -41,13 +48,17 @@ module AdminDashboard
raise NotImplementedError
end
- # Universe of items of this source visible to the guardian. Powers the
- # Manage Reports modal's available list and search filter.
+ # Universe of items of this source. Powers the Manage Reports modal's
+ # available list and search filter. Only invoked in admin-only contexts,
+ # so implementations should not perform per-user access filtering here.
+ # Providers paginate themselves via `offset` and `limit` arguments; the
+ # controller orchestrates cross-provider pagination.
#
- # @param guardian [Guardian]
# @param search [String, nil] optional name/description filter.
+ # @param offset [Integer] starting position within this provider's set.
+ # @param limit [Integer, nil] maximum number of items to return.
# @return [Array<AdminDashboard::Reports::ResolvedReport>]
- def self.available_for(guardian, search: nil)
+ def self.list_all(search: nil, offset: 0, limit: nil)
raise NotImplementedError
end
diff --git a/plugins/discourse-data-explorer/app/controllers/discourse_data_explorer/query_controller.rb b/plugins/discourse-data-explorer/app/controllers/discourse_data_explorer/query_controller.rb
index b09d8a95496..f43436b571f 100644
--- a/plugins/discourse-data-explorer/app/controllers/discourse_data_explorer/query_controller.rb
+++ b/plugins/discourse-data-explorer/app/controllers/discourse_data_explorer/query_controller.rb
@@ -46,23 +46,7 @@ module DiscourseDataExplorer
persisted_count = base_scope.count
- # Default queries are only persisted once run. Build in-memory records
- # for any that haven't been run yet so they still appear in the list.
- persisted_default_ids =
- DiscourseDataExplorer::Query.where(hidden: false).where("id < 0").pluck(:id).to_set
- unpersisted_defaults =
- DiscourseDataExplorer::Queries.default.filter_map do |_, attributes|
- next if persisted_default_ids.include?(attributes["id"])
- if filter.present?
- name_match = attributes["name"]&.downcase&.include?(filter.downcase)
- desc_match = attributes["description"]&.downcase&.include?(filter.downcase)
- next unless name_match || desc_match
- end
- query =
- DiscourseDataExplorer::Query.new(attributes.slice("id", "sql", "name", "description"))
- query.user_id = Discourse::SYSTEM_USER_ID.to_s
- query
- end
+ unpersisted_defaults = DiscourseDataExplorer::Query.unpersisted_defaults(search: filter)
total_rows = persisted_count + unpersisted_defaults.size
diff --git a/plugins/discourse-data-explorer/app/models/discourse_data_explorer/query.rb b/plugins/discourse-data-explorer/app/models/discourse_data_explorer/query.rb
index dc2a6348289..02a9a84c65c 100644
--- a/plugins/discourse-data-explorer/app/models/discourse_data_explorer/query.rb
+++ b/plugins/discourse-data-explorer/app/models/discourse_data_explorer/query.rb
@@ -51,6 +51,25 @@ module DiscourseDataExplorer
QueryFinder.find(id)
end
+ def self.unpersisted_defaults(search: nil)
+ persisted_ids = where(hidden: false).where("id < 0").pluck(:id).to_set
+ query_text = search&.downcase
+
+ Queries.default.filter_map do |_, attributes|
+ next if persisted_ids.include?(attributes["id"])
+
+ if query_text
+ name_match = attributes["name"]&.downcase&.include?(query_text)
+ desc_match = attributes["description"]&.downcase&.include?(query_text)
+ next unless name_match || desc_match
+ end
+
+ record = new(attributes.slice("id", "sql", "name", "description"))
+ record.user_id = Discourse::SYSTEM_USER_ID.to_s
+ record
+ end
+ end
+
private
# for `Query.unscoped.find`
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/admin-dashboard-card.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/admin-dashboard-card.gjs
new file mode 100644
index 00000000000..e22f51091f0
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/admin-dashboard-card.gjs
@@ -0,0 +1,86 @@
+import Component from "@glimmer/component";
+import { i18n } from "discourse-i18n";
+import { chartability, looksLikeDate } from "../lib/chart-helpers";
+import DataExplorerChart from "./data-explorer-chart";
+
+export default class DataExplorerAdminDashboardCard extends Component {
+ get rows() {
+ return this.args.payload?.rows ?? [];
+ }
+
+ get columns() {
+ return this.args.payload?.columns ?? [];
+ }
+
+ get chartability() {
+ return chartability(this.args.payload);
+ }
+
+ get isChartable() {
+ return this.columns.length === 2 && this.chartability.chartable;
+ }
+
+ get hasDates() {
+ return this.rows.length > 0 && looksLikeDate(String(this.rows[0][0]));
+ }
+
+ get chartType() {
+ if (this.chartability.numericIndices.length > 1) {
+ return "bar";
+ }
+ return this.hasDates ? "line" : "bar";
+ }
+
+ get isStacked() {
+ return this.chartability.numericIndices.length > 1 && this.hasDates;
+ }
+
+ get chartLabels() {
+ return this.rows.map((row) => row[0]);
+ }
+
+ get chartDatasets() {
+ return this.chartability.numericIndices.map((colIdx) => ({
+ label: this.columns[colIdx],
+ values: this.rows.map((row) => Number(row[colIdx])),
+ }));
+ }
+
+ <template>
+ <div class="de-dashboard-card">
+ {{#if this.rows.length}}
+ {{#if this.isChartable}}
+ <DataExplorerChart
+ @labels={{this.chartLabels}}
+ @datasets={{this.chartDatasets}}
+ @chartType={{this.chartType}}
+ @stacked={{this.isStacked}}
+ />
+ {{else}}
+ <table class="de-dashboard-card__table">
+ <thead>
+ <tr>
+ {{#each this.columns as |col|}}
+ <th>{{col}}</th>
+ {{/each}}
+ </tr>
+ </thead>
+ <tbody>
+ {{#each this.rows as |row|}}
+ <tr>
+ {{#each row as |cell|}}
+ <td>{{cell}}</td>
+ {{/each}}
+ </tr>
+ {{/each}}
+ </tbody>
+ </table>
+ {{/if}}
+ {{else}}
+ <div class="de-dashboard-card__empty">
+ {{i18n "data_explorer.admin_dashboard_card.no_results"}}
+ </div>
+ {{/if}}
+ </div>
+ </template>
+}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/data-explorer-chart.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/data-explorer-chart.gjs
index 630e4682729..7de701c4e0e 100644
--- a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/data-explorer-chart.gjs
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/data-explorer-chart.gjs
@@ -1,6 +1,7 @@
import Component from "@glimmer/component";
import { action } from "@ember/object";
import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import didUpdate from "@ember/render-modifiers/modifiers/did-update";
import { bind } from "discourse/lib/decorators";
import loadChartJS from "discourse/lib/load-chart-js";
import { SERIES_COLORS } from "../lib/chart-helpers";
@@ -148,14 +149,17 @@ export default class DataExplorerChart extends Component {
}
@action
- updateChartData() {
+ updateChartData(canvas) {
if (this.chart) {
this.chart.destroy();
}
- this.initChart(this.chart?.canvas);
+ this.initChart(canvas);
}
<template>
- <canvas {{didInsert this.initChart}}></canvas>
+ <canvas
+ {{didInsert this.initChart}}
+ {{didUpdate this.updateChartData @labels @datasets @chartType @stacked}}
+ ></canvas>
</template>
}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/connectors/admin-dashboard-manage-reports-footer/data-explorer-hint.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/connectors/admin-dashboard-manage-reports-footer/data-explorer-hint.gjs
new file mode 100644
index 00000000000..3c6b156d457
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/connectors/admin-dashboard-manage-reports-footer/data-explorer-hint.gjs
@@ -0,0 +1,21 @@
+import { LinkTo } from "@ember/routing";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+
+<template>
+ <LinkTo
+ @route="adminPlugins.show.explorer.new"
+ @model="discourse-data-explorer"
+ class="de-manage-reports-hint"
+ >
+ <div class="de-manage-reports-hint__text">
+ <span class="de-manage-reports-hint__title">
+ {{i18n "data_explorer.manage_reports_hint.title"}}
+ </span>
+ <span class="de-manage-reports-hint__description">
+ {{i18n "data_explorer.manage_reports_hint.description"}}
+ </span>
+ </div>
+ {{dIcon "chevron-right" class="de-manage-reports-hint__chevron"}}
+ </LinkTo>
+</template>
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/initializers/register-admin-dashboard-renderer.js b/plugins/discourse-data-explorer/assets/javascripts/discourse/initializers/register-admin-dashboard-renderer.js
new file mode 100644
index 00000000000..b520f71b66b
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/initializers/register-admin-dashboard-renderer.js
@@ -0,0 +1,14 @@
+import { withPluginApi } from "discourse/lib/plugin-api";
+import DataExplorerAdminDashboardCard from "../components/admin-dashboard-card";
+
+export default {
+ name: "data-explorer-register-admin-dashboard-renderer",
+ initialize() {
+ withPluginApi((api) => {
+ api.registerAdminDashboardReportRenderer(
+ "data_explorer_query",
+ DataExplorerAdminDashboardCard
+ );
+ });
+ },
+};
diff --git a/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss b/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss
index 6323c775d7a..dc80193606c 100644
--- a/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss
+++ b/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss
@@ -1,5 +1,61 @@
@use "lib/viewport";
+.de-dashboard-card {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-2);
+ height: 100%;
+ min-height: 0;
+
+ canvas {
+ width: 100% !important;
+ height: 100% !important;
+ }
+
+ &__table {
+ overflow: auto;
+ font-size: var(--font-down-2);
+ }
+
+ &__empty {
+ color: var(--primary-medium);
+ font-size: var(--font-down-1);
+ }
+}
+
+.de-manage-reports-hint {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ padding: var(--space-3) 1.5rem;
+ border-top: 1px solid var(--primary-low);
+ text-decoration: none;
+ color: inherit;
+
+ &__text {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-half);
+ flex: 1 1 auto;
+ min-width: 0;
+ }
+
+ &__title {
+ color: var(--tertiary);
+ font-weight: bold;
+ }
+
+ &__description {
+ color: var(--primary-medium);
+ font-size: var(--font-down-1);
+ }
+
+ &__chevron {
+ color: var(--tertiary);
+ font-size: var(--font-down-1);
+ }
+}
+
table.group-reports {
width: 100%;
table-layout: fixed;
diff --git a/plugins/discourse-data-explorer/config/locales/client.en.yml b/plugins/discourse-data-explorer/config/locales/client.en.yml
index 1578c7d0536..eda51b303be 100644
--- a/plugins/discourse-data-explorer/config/locales/client.en.yml
+++ b/plugins/discourse-data-explorer/config/locales/client.en.yml
@@ -15,6 +15,12 @@ en:
explorer:
no_semicolons: "Remove the semicolons from the query."
dirty: "You must save the query before running."
+ data_explorer:
+ admin_dashboard_card:
+ no_results: "No results"
+ manage_reports_hint:
+ title: "Create a Data Explorer query"
+ description: "Write a custom SQL query to surface anything specific to your community."
explorer:
default_query: "Default"
default_query_notice: "This is a default query, the SQL cannot be edited. To edit the SQL, create a new query."
diff --git a/plugins/discourse-data-explorer/config/locales/server.en.yml b/plugins/discourse-data-explorer/config/locales/server.en.yml
index 592420ee34d..7591f452563 100644
--- a/plugins/discourse-data-explorer/config/locales/server.en.yml
+++ b/plugins/discourse-data-explorer/config/locales/server.en.yml
@@ -30,6 +30,7 @@ en:
title: Schedule a post in a topic with Data Explorer results
description: Get scheduled reports posted to a specific topic
data_explorer:
+ admin_dashboard_label: "Data Explorer"
report_generator:
private_message:
title: "Scheduled report for %{query_name}"
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
index 6a4a3513884..e4874d06a93 100644
--- 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
@@ -8,6 +8,10 @@ module DiscourseDataExplorer
SOURCE_NAME
end
+ def self.label
+ I18n.t("data_explorer.admin_dashboard_label")
+ end
+
def self.resolve_many(identifiers, guardian:)
return {} if guardian.nil?
@@ -17,27 +21,48 @@ module DiscourseDataExplorer
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?
+ def self.list_all(search: nil, offset: 0, limit: nil)
+ persisted_total = persisted_scope(search: search).count
+ unpersisted = Query.unpersisted_defaults(search: search).sort_by { |q| q.name.to_s.downcase }
- 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)
+ results = []
+ remaining = limit
+
+ if offset < persisted_total
+ take =
+ if remaining
+ [remaining, persisted_total - offset].min
+ else
+ persisted_total - offset
+ end
+ results.concat(persisted_scope(search: search).offset(offset).limit(take).to_a)
+ remaining -= results.size if remaining
end
- scope.select { |q| guardian.user_can_access_query?(q) }.map { |q| build_resolved(q) }
+ if remaining.nil? || remaining > 0
+ unpersisted_offset = [offset - persisted_total, 0].max
+ slice =
+ if remaining
+ unpersisted[unpersisted_offset, remaining]
+ else
+ unpersisted[unpersisted_offset..]
+ end
+ results.concat(Array(slice))
+ end
+
+ results.map { |q| build_resolved(q) }
end
def self.fetch_many(identifiers, guardian:, filters: {})
return {} if guardian&.user.nil?
+ params = filters.with_indifferent_access
+
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)
+ result = QueryRunner.run(query, params, current_user: guardian.user)
+ result = result.merge(empty: Array(result[:rows]).empty?) if result.is_a?(Hash)
+ hash[query.id.to_s] = result
end
end
@@ -47,15 +72,45 @@ module DiscourseDataExplorer
identifier: query.id.to_s,
title: query.name,
description: query.description,
+ label: label,
+ url: "/admin/plugins/discourse-data-explorer/queries/#{query.id}",
)
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)
+ ids = identifiers.map(&:to_i).reject(&:zero?)
+ return [] if ids.empty?
+
+ positive_ids, negative_ids = ids.partition(&:positive?)
+ queries = []
+
+ if positive_ids.any?
+ queries.concat(Query.where(id: positive_ids, hidden: false).includes(:groups))
+ end
+
+ if negative_ids.any?
+ valid_default_ids = negative_ids.select { |id| Queries.default.key?(id.to_s) }
+ persisted_by_id = Query.where(id: valid_default_ids).index_by(&:id)
+ valid_default_ids.each do |id|
+ query = persisted_by_id[id] || Query.new
+ query.attributes = Queries.default[id.to_s]
+ query.user_id = Discourse::SYSTEM_USER_ID.to_s
+ queries << query if !query.hidden
+ end
+ end
+
+ queries
end
private_class_method :load_queries
+
+ def self.persisted_scope(search:)
+ scope = Query.where(hidden: false).includes(:groups).order(:name)
+ scope = scope.where(<<~SQL, s: "%#{Query.sanitize_sql_like(search)}%") if search.present?
+ name ILIKE :s OR description ILIKE :s
+ SQL
+ scope
+ end
+ private_class_method :persisted_scope
end
end
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
index 3a27cb9b7fc..de10652d4cd 100644
--- 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
@@ -5,10 +5,7 @@ RSpec.describe DiscourseDataExplorer::AdminDashboardReportProvider do
fab!(:user)
fab!(:group)
- let(:admin_guardian) { Guardian.new(admin) }
- let(:user_guardian) { Guardian.new(user) }
-
- let!(:visible_query) do
+ fab!(:visible_query) do
Fabricate(
:query,
name: "Visible query",
@@ -19,7 +16,7 @@ RSpec.describe DiscourseDataExplorer::AdminDashboardReportProvider do
)
end
- let!(:hidden_query) do
+ fab!(:hidden_query) do
Fabricate(
:query,
name: "Hidden query",
@@ -30,6 +27,9 @@ RSpec.describe DiscourseDataExplorer::AdminDashboardReportProvider do
)
end
+ let(:admin_guardian) { admin.guardian }
+ let(:user_guardian) { user.guardian }
+
before { SiteSetting.data_explorer_enabled = true }
after { DiscourseDataExplorer::QueryRunner.invalidate(visible_query.id) }
@@ -39,6 +39,12 @@ RSpec.describe DiscourseDataExplorer::AdminDashboardReportProvider do
end
end
+ describe ".label" do
+ it "returns the localized 'Data Explorer' label" do
+ expect(described_class.label).to eq(I18n.t("data_explorer.admin_dashboard_label"))
+ 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)
@@ -48,6 +54,7 @@ RSpec.describe DiscourseDataExplorer::AdminDashboardReportProvider do
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.label).to eq(described_class.label)
expect(resolved.source).to eq("data_explorer_query")
end
@@ -81,24 +88,33 @@ RSpec.describe DiscourseDataExplorer::AdminDashboardReportProvider do
end
end
- describe ".available_for" do
+ describe ".list_all" do
it "lists visible queries" do
- reports = described_class.available_for(admin_guardian)
+ reports = described_class.list_all
expect(reports.map(&:identifier)).to include(visible_query.id.to_s)
end
it "omits hidden queries" do
- reports = described_class.available_for(admin_guardian)
+ reports = described_class.list_all
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")
+ reports = described_class.list_all(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
+ expect(described_class.list_all(search: "zz_no_match_zz")).to be_empty
+ end
+
+ it "respects offset and limit, paginating across persisted + defaults" do
+ first = described_class.list_all(offset: 0, limit: 1)
+ second = described_class.list_all(offset: 1, limit: 1)
+
+ expect(first.size).to eq(1)
+ expect(second.size).to eq(1)
+ expect(first.first.identifier).not_to eq(second.first.identifier)
end
end
@@ -117,10 +133,16 @@ RSpec.describe DiscourseDataExplorer::AdminDashboardReportProvider do
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)
+ it "skips zero and non-numeric identifiers" do
+ result = described_class.fetch_many(%w[0 abc], guardian: admin_guardian)
expect(result).to be_empty
end
+
+ it "runs unpersisted default queries by negative id" do
+ result = described_class.fetch_many(%w[-1], guardian: admin_guardian)
+ expect(result["-1"]).to be_present
+ expect(result["-1"][:success]).to eq(true)
+ end
end
describe "registration" do
diff --git a/plugins/discourse-data-explorer/spec/system/admin_dashboard_manage_reports_hint_spec.rb b/plugins/discourse-data-explorer/spec/system/admin_dashboard_manage_reports_hint_spec.rb
new file mode 100644
index 00000000000..60eb76690a6
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/system/admin_dashboard_manage_reports_hint_spec.rb
@@ -0,0 +1,42 @@
+# frozen_string_literal: true
+
+describe "Data Explorer | Manage Reports footer hint" do
+ fab!(:current_user, :admin)
+
+ let(:dashboard) { PageObjects::Pages::AdminDashboardReports.new }
+ let(:modal) { PageObjects::Components::ManageReportsModal.new }
+ let(:hint) { PageObjects::Components::AdminDashboardManageReportsHint.new }
+
+ before do
+ SiteSetting.dashboard_improvements = true
+ SiteSetting.data_explorer_enabled = true
+ SiteSetting.admin_dashboard_sections = "reports"
+ AdminDashboardReport.delete_all
+ sign_in(current_user)
+ end
+
+ it "renders the Create a Data Explorer query hint inside the Manage Reports modal" do
+ page.visit("/admin")
+ dashboard.open_manage_reports_via_cog
+
+ expect(hint).to have_hint
+ end
+
+ it "links the hint to the Data Explorer new-query page" do
+ page.visit("/admin")
+ dashboard.open_manage_reports_via_cog
+
+ hint.click_hint
+
+ expect(page).to have_current_path("/admin/plugins/discourse-data-explorer/queries/new")
+ end
+
+ it "does not render the hint when the Data Explorer plugin is disabled" do
+ SiteSetting.data_explorer_enabled = false
+
+ page.visit("/admin")
+ dashboard.open_manage_reports_via_cog
+
+ expect(hint).to have_no_hint
+ end
+end
diff --git a/plugins/discourse-data-explorer/spec/system/page_objects/components/admin_dashboard_manage_reports_hint.rb b/plugins/discourse-data-explorer/spec/system/page_objects/components/admin_dashboard_manage_reports_hint.rb
new file mode 100644
index 00000000000..6fc4a6c0a77
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/system/page_objects/components/admin_dashboard_manage_reports_hint.rb
@@ -0,0 +1,22 @@
+# frozen_string_literal: true
+
+module PageObjects
+ module Components
+ class AdminDashboardManageReportsHint < PageObjects::Components::Base
+ SELECTOR = ".manage-reports-modal .de-manage-reports-hint"
+
+ def has_hint?
+ has_css?(SELECTOR)
+ end
+
+ def has_no_hint?
+ has_no_css?(SELECTOR)
+ end
+
+ def click_hint
+ find(SELECTOR).click
+ self
+ end
+ 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
index b3752b85eae..e2923306f19 100644
--- a/spec/lib/admin_dashboard/reports/core_report_provider_spec.rb
+++ b/spec/lib/admin_dashboard/reports/core_report_provider_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe AdminDashboard::Reports::CoreReportProvider do
fab!(:admin)
- let(:guardian) { Guardian.new(admin) }
+ let(:guardian) { admin.guardian }
describe ".source_name" do
it "returns 'core_report'" do
@@ -10,6 +10,12 @@ RSpec.describe AdminDashboard::Reports::CoreReportProvider do
end
end
+ describe ".label" do
+ it "returns the localized provider label" do
+ expect(described_class.label).to eq(I18n.t("dashboard.reports_section.providers.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)
@@ -20,6 +26,7 @@ RSpec.describe AdminDashboard::Reports::CoreReportProvider do
expect(resolved.source).to eq("core_report")
expect(resolved.identifier).to eq("signups")
expect(resolved.title).to be_present
+ expect(resolved.label).to eq(described_class.label)
end
it "omits identifiers that don't correspond to a built-in report" do
@@ -38,24 +45,32 @@ RSpec.describe AdminDashboard::Reports::CoreReportProvider do
end
end
- describe ".available_for" do
+ describe ".list_all" do
it "includes built-in reports" do
- reports = described_class.available_for(guardian)
- identifiers = reports.map(&:identifier)
+ reports = described_class.list_all
- expect(identifiers).to include("signups")
- reports.each { |r| expect(r).to be_a(AdminDashboard::Reports::ResolvedReport) }
+ expect(reports.map(&:identifier)).to include("signups")
+ expect(reports).to all(be_a(AdminDashboard::Reports::ResolvedReport))
end
it "filters by name/description when search is given" do
- filtered = described_class.available_for(guardian, search: "signup")
+ filtered = described_class.list_all(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
+ expect(described_class.list_all(search: "zzzz_no_match_zzzz")).to be_empty
+ end
+
+ it "respects offset and limit" do
+ first_two = described_class.list_all(offset: 0, limit: 2)
+ next_two = described_class.list_all(offset: 2, limit: 2)
+
+ expect(first_two.size).to eq(2)
+ expect(next_two.size).to eq(2)
+ expect(first_two.map(&:identifier)).not_to include(*next_two.map(&:identifier))
end
end
diff --git a/spec/lib/admin_dashboard/reports/section_spec.rb b/spec/lib/admin_dashboard/reports/section_spec.rb
index 14088bc7117..868c6959438 100644
--- a/spec/lib/admin_dashboard/reports/section_spec.rb
+++ b/spec/lib/admin_dashboard/reports/section_spec.rb
@@ -2,21 +2,25 @@
RSpec.describe AdminDashboard::Reports::Section do
fab!(:admin)
- let(:guardian) { Guardian.new(admin) }
+ let(:guardian) { admin.guardian }
let(:fake_provider) do
Class.new(AdminDashboard::Reports::SourceProvider) do
def self.source_name = "fake"
+ def self.label = "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(
+ .each_with_object({}) do |id, hash|
+ hash[id.to_s] = AdminDashboard::Reports::ResolvedReport.new(
source: "fake",
identifier: id.to_s,
title: "Title for #{id}",
description: "Desc for #{id}",
+ label: label,
+ url: "/fake/#{id}",
)
end
end
@@ -37,7 +41,19 @@ RSpec.describe AdminDashboard::Reports::Section do
end
it "returns an empty items list when there are no rows" do
- expect(described_class.build(guardian: guardian)).to eq(items: [])
+ result = described_class.build(guardian: guardian)
+ expect(result[:items]).to eq([])
+ end
+
+ it "sets show_labels to true when more than one provider is registered" do
+ expect(described_class.build(guardian: guardian)[:show_labels]).to eq(true)
+ end
+
+ it "sets show_labels to false when only one provider is registered" do
+ DiscoursePluginRegistry._raw_admin_dashboard_report_sources.reject! do |entry|
+ entry[:value] == fake_provider
+ end
+ expect(described_class.build(guardian: guardian)[:show_labels]).to eq(false)
end
it "returns items in position order, ignoring insertion order" do
@@ -46,10 +62,10 @@ RSpec.describe AdminDashboard::Reports::Section do
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])
+ expect(result[:items].map { |item| item[:identifier] }).to eq(%w[b a c])
end
- it "serializes source / identifier / title / description from the resolved metadata" do
+ it "serializes the resolved metadata along with a composite key" do
AdminDashboardReport.create!(source: "fake", identifier: "x", position: 0)
item = described_class.build(guardian: guardian)[:items].first
@@ -58,6 +74,9 @@ RSpec.describe AdminDashboard::Reports::Section do
identifier: "x",
title: "Title for x",
description: "Desc for x",
+ label: "Fake",
+ url: "/fake/x",
+ key: "fake:x",
)
end
@@ -67,7 +86,7 @@ RSpec.describe AdminDashboard::Reports::Section do
orphan.update_column(:source, "unregistered_source")
result = described_class.build(guardian: guardian)
- expect(result[:items].map { |i| i[:identifier] }).to eq(%w[good])
+ expect(result[:items].map { |item| item[:identifier] }).to eq(%w[good])
end
it "drops rows the provider declines to resolve" do
@@ -75,22 +94,22 @@ RSpec.describe AdminDashboard::Reports::Section do
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])
+ expect(result[:items].map { |item| item[: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|
+ 5.times do |index|
AdminDashboardReport.create!(
source: "fake",
- identifier: "r_#{i}",
- position: i,
- created_at: i.minutes.ago,
+ identifier: "r_#{index}",
+ position: index,
+ created_at: index.minutes.ago,
)
end
result = described_class.build(guardian: guardian)
- identifiers = result[:items].map { |i| i[:identifier] }
+ identifiers = result[:items].map { |item| item[:identifier] }
expect(identifiers).to eq(%w[r_0 r_1 r_2])
end
diff --git a/spec/lib/admin_dashboard/reports/source_provider_spec.rb b/spec/lib/admin_dashboard/reports/source_provider_spec.rb
index fa826eeb7c3..4728b060291 100644
--- a/spec/lib/admin_dashboard/reports/source_provider_spec.rb
+++ b/spec/lib/admin_dashboard/reports/source_provider_spec.rb
@@ -1,20 +1,24 @@
# frozen_string_literal: true
RSpec.describe AdminDashboard::Reports::SourceProvider do
- describe ".accessible_ids (default implementation)" do
+ describe ".accessible_ids" do
let(:provider) do
Class.new(described_class) do
def self.source_name = "test"
+ def self.label = "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(
+ .each_with_object({}) do |id, hash|
+ hash[id] = AdminDashboard::Reports::ResolvedReport.new(
source: source_name,
identifier: id,
title: id,
description: nil,
+ label: label,
+ url: nil,
)
end
end
diff --git a/spec/requests/admin/dashboard_controller_spec.rb b/spec/requests/admin/dashboard_controller_spec.rb
index c1d1df0cb03..29ea880e552 100644
--- a/spec/requests/admin/dashboard_controller_spec.rb
+++ b/spec/requests/admin/dashboard_controller_spec.rb
@@ -326,7 +326,8 @@ RSpec.describe Admin::DashboardController do
get "/admin/dashboard.json"
expect(response.status).to eq(200)
- expect(reports_data).to eq("items" => [])
+ expect(reports_data["items"]).to eq([])
+ expect(reports_data).to have_key("show_labels")
end
it "serializes configured rows resolved via the registered providers" do
@@ -804,7 +805,7 @@ RSpec.describe Admin::DashboardController do
end
end
- describe "POST /admin/dashboard/reports/bulk" do
+ describe "#bulk_reports" do
before { SiteSetting.dashboard_improvements = true }
let(:fake_provider) do
@@ -935,4 +936,326 @@ RSpec.describe Admin::DashboardController do
end
end
end
+
+ describe "#available_reports" do
+ before do
+ SiteSetting.dashboard_improvements = true
+ AdminDashboardReport.delete_all
+ end
+
+ let(:fake_provider) do
+ Class.new(AdminDashboard::Reports::SourceProvider) do
+ def self.source_name = "a_fake_source"
+ def self.label = "Fake"
+
+ def self.universe
+ %w[a b c].map do |id|
+ AdminDashboard::Reports::ResolvedReport.new(
+ source: source_name,
+ identifier: id,
+ title: "Fakey #{id}",
+ description: "Desc #{id}",
+ label: label,
+ url: "/fake/#{id}",
+ )
+ end
+ end
+
+ def self.list_all(search: nil, offset: 0, limit: nil)
+ items = universe
+ if search.present?
+ items = items.select { |item| item.title.downcase.include?(search.downcase) }
+ end
+ sliced = limit ? items[offset, limit] : items[offset..]
+ Array(sliced)
+ end
+
+ def self.resolve_many(identifiers, guardian:)
+ universe
+ .select { |item| identifiers.map(&:to_s).include?(item.identifier) }
+ .index_by(&:identifier)
+ end
+ end
+ end
+
+ let(:wide_provider) do
+ Class.new(AdminDashboard::Reports::SourceProvider) do
+ def self.source_name = "a_wide_source"
+ def self.label = "Wide"
+
+ def self.list_all(search: nil, offset: 0, limit: nil)
+ items =
+ (1..40).map do |index|
+ AdminDashboard::Reports::ResolvedReport.new(
+ source: source_name,
+ identifier: "row_#{index}",
+ title: "Wideprefix Row #{index}",
+ description: nil,
+ label: label,
+ url: nil,
+ )
+ end
+ if search.present?
+ items = items.select { |item| item.title.downcase.include?(search.downcase) }
+ end
+ sliced = limit ? items[offset, limit] : items[offset..]
+ Array(sliced)
+ end
+
+ def self.resolve_many(_identifiers, guardian:)
+ {}
+ end
+ end
+ end
+
+ let(:plugin) { Plugin::Instance.new }
+
+ after do
+ DiscoursePluginRegistry._raw_admin_dashboard_report_sources.reject! do |entry|
+ [fake_provider, wide_provider].include?(entry[:value])
+ end
+ end
+
+ context "when not signed in" do
+ it "denies access" do
+ get "/admin/dashboard/reports/available.json"
+ expect(response.status).to eq(404)
+ end
+ end
+
+ context "when signed in as a moderator" do
+ before do
+ SiteSetting.dashboard_improvements = true
+ sign_in(Fabricate(:moderator))
+ end
+
+ it "denies access" do
+ get "/admin/dashboard/reports/available.json"
+ expect(response.status).to eq(404)
+ end
+ end
+
+ context "when signed in as an admin" do
+ before { sign_in(admin) }
+
+ it "returns 404 when dashboard_improvements is off" do
+ SiteSetting.dashboard_improvements = false
+ get "/admin/dashboard/reports/available.json"
+ expect(response.status).to eq(404)
+ end
+
+ it "returns enabled, available, and providers" do
+ DiscoursePluginRegistry.register_admin_dashboard_report_source(fake_provider, plugin)
+ AdminDashboardReport.create!(source: "a_fake_source", identifier: "b", position: 0)
+
+ get "/admin/dashboard/reports/available.json", params: { search: "Fakey" }
+ expect(response.status).to eq(200)
+
+ body = response.parsed_body
+ expect(body["providers"].map { |provider| provider["source"] }).to include("a_fake_source")
+ fake_summary = body["providers"].find { |provider| provider["source"] == "a_fake_source" }
+ expect(fake_summary["label"]).to eq("Fake")
+
+ expect(body["enabled"].map { |item| item["identifier"] }).to eq(["b"])
+ expect(body["enabled"].first["label"]).to eq("Fake")
+
+ fake_available = body["available"].select { |item| item["source"] == "a_fake_source" }
+ expect(fake_available.map { |item| item["identifier"] }).to contain_exactly("a", "b", "c")
+ end
+
+ it "includes already-enabled identifiers in the all list" do
+ DiscoursePluginRegistry.register_admin_dashboard_report_source(fake_provider, plugin)
+ AdminDashboardReport.create!(source: "a_fake_source", identifier: "a", position: 0)
+ AdminDashboardReport.create!(source: "a_fake_source", identifier: "b", position: 1)
+
+ get "/admin/dashboard/reports/available.json", params: { search: "Fakey" }
+ body = response.parsed_body
+ fake_available = body["available"].select { |item| item["source"] == "a_fake_source" }
+ expect(fake_available.map { |item| item["identifier"] }).to contain_exactly("a", "b", "c")
+ end
+
+ it "paginates 30 items per response and emits a cursor when more exist" do
+ DiscoursePluginRegistry.register_admin_dashboard_report_source(wide_provider, plugin)
+
+ get "/admin/dashboard/reports/available.json", params: { search: "Wideprefix" }
+ expect(response.status).to eq(200)
+
+ body = response.parsed_body
+ wide = body["available"].select { |item| item["source"] == "a_wide_source" }
+ expect(wide.size).to eq(AdminDashboard::Reports::Listing::PAGE_SIZE)
+ expect(wide.first["identifier"]).to eq("row_1")
+ expect(body["has_more"]).to eq(true)
+ expect(body["cursor"]).to eq("a_wide_source:30")
+ end
+
+ it "returns the next batch when the cursor from a previous response is sent back" do
+ DiscoursePluginRegistry.register_admin_dashboard_report_source(wide_provider, plugin)
+
+ get "/admin/dashboard/reports/available.json",
+ params: {
+ search: "Wideprefix",
+ cursor: "a_wide_source:30",
+ }
+ body = response.parsed_body
+ wide = body["available"].select { |item| item["source"] == "a_wide_source" }
+
+ expect(wide.map { |item| item["identifier"] }).to eq((31..40).map { |n| "row_#{n}" })
+ expect(body["has_more"]).to eq(false)
+ expect(body["cursor"]).to be_nil
+ end
+
+ it "ignores a cursor whose source is not registered" do
+ DiscoursePluginRegistry.register_admin_dashboard_report_source(wide_provider, plugin)
+
+ get "/admin/dashboard/reports/available.json", params: { cursor: "ghost_source:0" }
+
+ expect(response.parsed_body["available"]).to be_empty
+ expect(response.parsed_body["has_more"]).to eq(false)
+ expect(response.parsed_body["cursor"]).to be_nil
+ end
+
+ it "crosses provider boundaries via cursor instead of asking each provider at the same offset" do
+ DiscoursePluginRegistry.register_admin_dashboard_report_source(fake_provider, plugin)
+ DiscoursePluginRegistry.register_admin_dashboard_report_source(wide_provider, plugin)
+
+ get "/admin/dashboard/reports/available.json", params: { cursor: "a_fake_source:0" }
+ body = response.parsed_body
+ sources = body["available"].map { |item| item["source"] }
+
+ expect(sources.first(3)).to eq(%w[a_fake_source a_fake_source a_fake_source])
+ expect(sources.last).to eq("a_wide_source")
+ expect(body["has_more"]).to eq(true)
+ expect(body["cursor"]).to start_with("a_wide_source:")
+ end
+
+ it "filters by the search param" do
+ DiscoursePluginRegistry.register_admin_dashboard_report_source(fake_provider, plugin)
+
+ get "/admin/dashboard/reports/available.json", params: { search: "Fakey a" }
+ body = response.parsed_body
+ fake_available = body["available"].select { |item| item["source"] == "a_fake_source" }
+ expect(fake_available.map { |item| item["identifier"] }).to eq(["a"])
+ end
+ end
+ end
+
+ describe "#update_reports_section" do
+ before do
+ SiteSetting.dashboard_improvements = true
+ AdminDashboardReport.delete_all
+ end
+
+ let(:fake_provider) do
+ Class.new(AdminDashboard::Reports::SourceProvider) do
+ def self.source_name = "fake_source"
+ def self.label = "Fake"
+ def self.accessible_ids(identifiers, guardian:)
+ identifiers.map(&:to_s).reject { |id| id == "forbidden" }.to_set
+ 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
+ put "/admin/dashboard/reports/layout.json", params: { items: [] }
+ expect(response.status).to eq(404)
+ end
+ end
+
+ context "when signed in as a moderator" do
+ before do
+ SiteSetting.dashboard_improvements = true
+ sign_in(Fabricate(:moderator))
+ end
+
+ it "denies access" do
+ put "/admin/dashboard/reports/layout.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 dashboard_improvements is off" do
+ SiteSetting.dashboard_improvements = false
+ put "/admin/dashboard/reports/layout.json", params: { items: [] }
+ expect(response.status).to eq(404)
+ end
+
+ it "replaces the current layout with the supplied items in order" do
+ DiscoursePluginRegistry.register_admin_dashboard_report_source(fake_provider, plugin)
+ AdminDashboardReport.create!(source: "fake_source", identifier: "old", position: 0)
+
+ put "/admin/dashboard/reports/layout.json",
+ params: {
+ items: [
+ { source: "fake_source", identifier: "new_a" },
+ { source: "fake_source", identifier: "new_b" },
+ ],
+ }
+
+ expect(response.status).to eq(204)
+ rows = AdminDashboardReport.order(:position).pluck(:identifier, :position)
+ expect(rows).to eq([["new_a", 0], ["new_b", 1]])
+ end
+
+ it "accepts an empty layout (removes everything)" do
+ DiscoursePluginRegistry.register_admin_dashboard_report_source(fake_provider, plugin)
+ AdminDashboardReport.create!(source: "fake_source", identifier: "y", position: 0)
+
+ put "/admin/dashboard/reports/layout.json", params: { items: [] }
+ expect(response.status).to eq(204)
+ expect(AdminDashboardReport.count).to eq(0)
+ end
+
+ it "rejects more than VISIBLE_CAP items" do
+ DiscoursePluginRegistry.register_admin_dashboard_report_source(fake_provider, plugin)
+ items =
+ (AdminDashboardReport::VISIBLE_CAP + 1).times.map do |i|
+ { source: "fake_source", identifier: "id#{i}" }
+ end
+ put "/admin/dashboard/reports/layout.json", params: { items: items }
+ expect(response.status).to eq(400)
+ end
+
+ it "rejects items missing source or identifier" do
+ put "/admin/dashboard/reports/layout.json", params: { items: [{ source: "fake_source" }] }
+ expect(response.status).to eq(400)
+ end
+
+ it "rejects a non-array items field" do
+ put "/admin/dashboard/reports/layout.json", params: { items: "not_an_array" }
+ expect(response.status).to eq(400)
+ end
+
+ it "rejects items whose source has no registered provider" do
+ put "/admin/dashboard/reports/layout.json",
+ params: {
+ items: [{ source: "totally_unregistered", identifier: "x" }],
+ }
+ expect(response.status).to eq(400)
+ end
+
+ it "rejects items the guardian cannot access" do
+ DiscoursePluginRegistry.register_admin_dashboard_report_source(fake_provider, plugin)
+
+ put "/admin/dashboard/reports/layout.json",
+ params: {
+ items: [{ source: "fake_source", identifier: "forbidden" }],
+ }
+
+ expect(response.status).to eq(403)
+ expect(AdminDashboardReport.count).to eq(0)
+ end
+ end
+ end
end
diff --git a/spec/system/admin_dashboard_redesign/reports_section_spec.rb b/spec/system/admin_dashboard_redesign/reports_section_spec.rb
new file mode 100644
index 00000000000..7d4e779e4a5
--- /dev/null
+++ b/spec/system/admin_dashboard_redesign/reports_section_spec.rb
@@ -0,0 +1,121 @@
+# frozen_string_literal: true
+
+describe "Admin Dashboard Redesign | Reports section" do
+ fab!(:current_user, :admin)
+
+ let(:dashboard) { PageObjects::Pages::AdminDashboardReports.new }
+ let(:modal) { PageObjects::Components::ManageReportsModal.new }
+
+ before do
+ SiteSetting.dashboard_improvements = true
+ SiteSetting.admin_dashboard_sections = "reports"
+ AdminDashboardReport.delete_all
+ sign_in(current_user)
+ end
+
+ it "lets admins customize the reports section via the manage-reports modal" do
+ AdminDashboardReport.create!(source: "core_report", identifier: "signups", position: 0)
+ AdminDashboardReport.create!(source: "core_report", identifier: "topics", position: 1)
+
+ page.visit("/admin")
+ expect(dashboard).to have_section
+ expect(dashboard.card_identifiers).to eq(%w[core_report:signups core_report:topics])
+
+ dashboard.open_manage_reports_via_cog
+ expect(modal).to have_open
+ expect(modal.enabled_identifiers).to eq(%w[core_report:signups core_report:topics])
+ expect(modal).to have_toggle_on("core_report:signups")
+ expect(modal).to have_toggle_off("core_report:admin_logins")
+
+ modal.search("admin_logins")
+ expect(modal).to have_all_row("core_report:admin_logins")
+ expect(modal).to have_no_all_row("core_report:dau_by_mau")
+ modal.search("")
+
+ modal.toggle("core_report:admin_logins")
+ expect(modal).to have_toggle_on("core_report:admin_logins")
+ modal.apply
+ expect(modal).to have_closed
+ expect(dashboard.card_identifiers).to contain_exactly(
+ "core_report:signups",
+ "core_report:topics",
+ "core_report:admin_logins",
+ )
+
+ page.refresh
+ expect(dashboard.card_identifiers).to contain_exactly(
+ "core_report:signups",
+ "core_report:topics",
+ "core_report:admin_logins",
+ )
+
+ dashboard.open_manage_reports_via_tile
+ expect(modal).to have_open
+ modal.toggle("core_report:posts")
+ modal.close
+ expect(modal).to have_closed
+ expect(dashboard.card_identifiers).to contain_exactly(
+ "core_report:signups",
+ "core_report:topics",
+ "core_report:admin_logins",
+ )
+ end
+
+ it "removes a card directly via the X-to-remove button" do
+ AdminDashboardReport.create!(source: "core_report", identifier: "signups", position: 0)
+ AdminDashboardReport.create!(source: "core_report", identifier: "topics", position: 1)
+
+ page.visit("/admin")
+ expect(dashboard).to have_card("core_report:signups")
+
+ dashboard.remove_card("core_report:signups")
+ expect(dashboard).to have_no_card("core_report:signups")
+
+ page.refresh
+ expect(dashboard).to have_no_card("core_report:signups")
+ expect(dashboard).to have_card("core_report:topics")
+ end
+
+ it "hides the Add Report tile when the cap is reached" do
+ identifiers =
+ Reports::ListQuery
+ .call(guardian: current_user.guardian)
+ .first(AdminDashboardReport::VISIBLE_CAP)
+ .map { |entry| entry[:type] }
+ now = Time.current
+ AdminDashboardReport.insert_all(
+ identifiers.each_with_index.map do |identifier, i|
+ {
+ source: "core_report",
+ identifier: identifier,
+ position: i,
+ created_at: now,
+ updated_at: now,
+ }
+ end,
+ )
+
+ page.visit("/admin")
+ expect(dashboard.card_identifiers.size).to eq(AdminDashboardReport::VISIBLE_CAP)
+ expect(dashboard).to have_no_add_tile
+ end
+
+ it "hides provider label pills when only one provider is registered" do
+ AdminDashboardReport.create!(source: "core_report", identifier: "signups", position: 0)
+
+ page.visit("/admin")
+ expect(dashboard).to have_no_label_for("core_report:signups")
+ end
+
+ it "lets moderators view the section but hides all edit affordances" do
+ AdminDashboardReport.create!(source: "core_report", identifier: "signups", position: 0)
+
+ sign_in(Fabricate(:moderator))
+ page.visit("/admin")
+
+ expect(dashboard).to have_card("core_report:signups")
+ expect(dashboard).to have_no_cog
+ expect(dashboard).to have_no_add_tile
+ expect(dashboard).to have_no_remove_button("core_report:signups")
+ end
+end
diff --git a/spec/system/page_objects/components/manage_reports_modal.rb b/spec/system/page_objects/components/manage_reports_modal.rb
new file mode 100644
index 00000000000..dc0f9ae83a7
--- /dev/null
+++ b/spec/system/page_objects/components/manage_reports_modal.rb
@@ -0,0 +1,103 @@
+# frozen_string_literal: true
+
+module PageObjects
+ module Components
+ class ManageReportsModal < PageObjects::Components::Base
+ MODAL = ".manage-reports-modal"
+
+ def has_open?
+ has_css?(MODAL)
+ end
+
+ def has_closed?
+ has_no_css?(MODAL)
+ end
+
+ def search(query)
+ find("#{MODAL} .manage-reports__search-wrapper .filter-input").set(query)
+ self
+ end
+
+ def enabled_identifiers
+ within("#{MODAL} .manage-reports__list--enabled") do
+ all(".manage-reports__row").map { |el| el["data-identifier"] }
+ end
+ end
+
+ def all_identifiers
+ within("#{MODAL} .manage-reports__list--all") do
+ all(".manage-reports__row").map { |el| el["data-identifier"] }
+ end
+ end
+
+ def has_all_row?(identifier)
+ has_css?(
+ "#{MODAL} .manage-reports__list--all " \
+ ".manage-reports__row[data-identifier='#{identifier}']",
+ )
+ end
+
+ def has_no_all_row?(identifier)
+ has_no_css?(
+ "#{MODAL} .manage-reports__list--all " \
+ ".manage-reports__row[data-identifier='#{identifier}']",
+ )
+ end
+
+ def toggle(identifier)
+ toggle_for(identifier).toggle
+ self
+ end
+
+ def has_toggle_on?(identifier)
+ has_css?(
+ "#{MODAL} .manage-reports__list--enabled " \
+ ".manage-reports__row[data-identifier='#{identifier}']",
+ )
+ end
+
+ def has_toggle_off?(identifier)
+ has_no_css?(
+ "#{MODAL} .manage-reports__list--enabled " \
+ ".manage-reports__row[data-identifier='#{identifier}']",
+ ) &&
+ has_css?(
+ "#{MODAL} .manage-reports__list--all " \
+ ".manage-reports__row[data-identifier='#{identifier}']",
+ )
+ end
+
+ def toggle_for(identifier)
+ enabled_row =
+ "#{MODAL} .manage-reports__list--enabled " \
+ ".manage-reports__row[data-identifier='#{identifier}']"
+ toggle_selector =
+ if has_css?(enabled_row, wait: 0)
+ "#{enabled_row} .d-toggle-switch__checkbox"
+ else
+ "#{MODAL} .manage-reports__list--all " \
+ ".manage-reports__row[data-identifier='#{identifier}'] " \
+ ".d-toggle-switch__checkbox"
+ end
+ PageObjects::Components::DToggleSwitch.new(toggle_selector)
+ end
+
+ def apply
+ within(MODAL) { find(".manage-reports__apply").click }
+ self
+ end
+
+ def close
+ find("#{MODAL} .d-modal__header .modal-close").click
+ self
+ end
+
+ def has_counter?(count, max)
+ has_css?(
+ "#{MODAL} .manage-reports__counter",
+ text: I18n.t("admin_js.admin.dashboard.reports_section.modal.counter", count:, max:),
+ )
+ end
+ end
+ end
+end
diff --git a/spec/system/page_objects/pages/admin_dashboard_reports.rb b/spec/system/page_objects/pages/admin_dashboard_reports.rb
new file mode 100644
index 00000000000..bdb2d1f9e8c
--- /dev/null
+++ b/spec/system/page_objects/pages/admin_dashboard_reports.rb
@@ -0,0 +1,87 @@
+# frozen_string_literal: true
+
+module PageObjects
+ module Pages
+ class AdminDashboardReports < PageObjects::Pages::Base
+ SECTION_SELECTOR = ".db-main__section[data-section-id='reports']"
+
+ def has_section?
+ has_css?(SECTION_SELECTOR)
+ end
+
+ def card_identifiers
+ within(SECTION_SELECTOR) { all(".db-report__card").map { |el| el["data-identifier"] } }
+ end
+
+ def has_card?(identifier)
+ has_css?("#{SECTION_SELECTOR} .db-report__card[data-identifier='#{identifier}']")
+ end
+
+ def has_no_card?(identifier)
+ has_no_css?("#{SECTION_SELECTOR} .db-report__card[data-identifier='#{identifier}']")
+ end
+
+ def remove_card(identifier)
+ within("#{SECTION_SELECTOR} .db-report__card[data-identifier='#{identifier}']") do
+ find(".db-report__remove").click
+ end
+ self
+ end
+
+ def has_add_tile?
+ has_css?("#{SECTION_SELECTOR} .db-report__add-report")
+ end
+
+ def has_no_add_tile?
+ has_no_css?("#{SECTION_SELECTOR} .db-report__add-report")
+ end
+
+ def has_cog?
+ has_css?("#{SECTION_SELECTOR} .db-section__header-action .btn")
+ end
+
+ def has_no_cog?
+ has_no_css?("#{SECTION_SELECTOR} .db-section__header-action .btn")
+ end
+
+ def has_no_remove_button?(identifier)
+ has_no_css?(
+ "#{SECTION_SELECTOR} .db-report__card[data-identifier='#{identifier}'] .db-report__remove",
+ )
+ end
+
+ def open_manage_reports_via_tile
+ find("#{SECTION_SELECTOR} .db-report__add-report").click
+ self
+ end
+
+ def open_manage_reports_via_cog
+ within(SECTION_SELECTOR) { find(".db-section__header-action .btn").click }
+ self
+ end
+
+ def manage_reports_modal
+ PageObjects::Components::ManageReportsModal.new
+ end
+
+ def has_label_for?(identifier, label)
+ has_css?(
+ "#{SECTION_SELECTOR} .db-report__card[data-identifier='#{identifier}'] .db-report__label",
+ text: label,
+ )
+ end
+
+ def has_no_label_for?(identifier)
+ has_no_css?(
+ "#{SECTION_SELECTOR} .db-report__card[data-identifier='#{identifier}'] .db-report__label",
+ )
+ end
+
+ def has_empty_state_for?(identifier)
+ has_css?(
+ "#{SECTION_SELECTOR} .db-report__card[data-identifier='#{identifier}'] .db-report__empty",
+ )
+ end
+ end
+ end
+end