A platform for community discussion. Free, open, simple.
FEATURE: Data Explorer add to dashboard button (#44126)
David Battersbyaf30595a49a4
diff --git a/app/controllers/admin/dashboard_controller.rb b/app/controllers/admin/dashboard_controller.rbindex 18e5b4a43e8..0cff87eabed 100644--- a/app/controllers/admin/dashboard_controller.rb+++ b/app/controllers/admin/dashboard_controller.rb@@ -6,7 +6,9 @@ class Admin::DashboardController < Admin::StaffControllerbefore_action :ensure_admin,only: %i[available_reports+ mount_reporttraffic+ unmount_reportupdate_reports_sectionupdate_configurationupdate_section_settings@@ -130,6 +132,29 @@ class Admin::DashboardController < Admin::StaffControllerhead :no_contentend+ def mount_report+ report =+ AdminDashboard::Reports::Mounter.mount(+ source: params.require(:source),+ identifier: params.require(:identifier),+ guardian: guardian,+ )+ render json: report.slice(:source, :identifier, :position, :rows, :cols), status: :created+ rescue AdminDashboard::Reports::Mounter::CapReached+ render_json_error(+ I18n.t("dashboard.reports.cap_reached", max: AdminDashboardReport::VISIBLE_CAP),+ status: 422,+ )+ end++ def unmount_report+ AdminDashboard::Reports::Mounter.unmount(+ source: params.require(:source),+ identifier: params.require(:identifier),+ )+ head :no_content+ end+def available_reportssearch = params[:search]cursor = params.permit(cursor: %i[title key])[:cursor]&.to_h&.symbolize_keysdiff --git a/config/locales/server.en.yml b/config/locales/server.en.ymlindex 5204b0727d9..95a16dcf86d 100644--- a/config/locales/server.en.yml+++ b/config/locales/server.en.yml@@ -2024,6 +2024,8 @@ en:description: "Show number of associated accounts grouped by login provider. Applicable only when social login methods are enabled."dashboard:+ reports:+ cap_reached: "The dashboard already shows the maximum of %{max} reports. Remove one before adding another."problem:twitter_login: 'Twitter login appears to not be working at the moment. Check the credentials in <a href="%{base_path}/admin/site_settings/category/login?filter=twitter">the Site Settings</a>.'group_email_credentials: 'There was an issue with the email credentials for the group <a href="%{base_path}/g/%{group_name}/manage/email">%{group_full_name}</a>. No emails will be sent from the group inbox until this problem is addressed. %{error}'diff --git a/config/routes.rb b/config/routes.rbindex f721548e3ca..85e11d7c8c4 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -389,6 +389,10 @@ Discourse::Application.routes.draw do:constraints => AdminConstraint.newput "dashboard/reports/layout" => "dashboard#update_reports_section",:constraints => AdminConstraint.new+ post "dashboard/reports/mount" => "dashboard#mount_report",+ :constraints => AdminConstraint.new+ delete "dashboard/reports/mount" => "dashboard#unmount_report",+ :constraints => AdminConstraint.newget "dashboard/whats-new" => "dashboard#new_features"get "/whats-new" => "dashboard#new_features"post "/toggle-feature" => "dashboard#toggle_feature"diff --git a/lib/admin_dashboard/reports/mounter.rb b/lib/admin_dashboard/reports/mounter.rbnew file mode 100644index 00000000000..8530c78fcf2--- /dev/null+++ b/lib/admin_dashboard/reports/mounter.rb@@ -0,0 +1,31 @@+# frozen_string_literal: true++module AdminDashboard+ module Reports+ # Adds or removes a single report on the dashboard's Reports section,+ # leaving the rest of the layout untouched.+ class Mounter+ class CapReached < StandardError+ end++ def self.mount(source:, identifier:, guardian:)+ provider = Registry.provider_for(source)+ raise Discourse::InvalidParameters.new(:source) if provider.nil?++ accessible = provider.accessible_ids([identifier], guardian: guardian)+ raise Discourse::InvalidAccess if !accessible.include?(identifier)++ existing = AdminDashboardReport.find_by(source: source, identifier: identifier)+ return existing if existing++ raise CapReached if AdminDashboardReport.count >= AdminDashboardReport::VISIBLE_CAP++ AdminDashboardReport.create!(source: source, identifier: identifier)+ end++ def self.unmount(source:, identifier:)+ AdminDashboardReport.where(source: source, identifier: identifier).delete_all+ end+ end+ end+enddiff --git a/plugins/discourse-data-explorer/admin/assets/javascripts/admin/templates/admin-plugins/show/explorer/edit.gjs b/plugins/discourse-data-explorer/admin/assets/javascripts/admin/templates/admin-plugins/show/explorer/edit.gjsindex aa0d64340cb..ef25dedde66 100644--- a/plugins/discourse-data-explorer/admin/assets/javascripts/admin/templates/admin-plugins/show/explorer/edit.gjs+++ b/plugins/discourse-data-explorer/admin/assets/javascripts/admin/templates/admin-plugins/show/explorer/edit.gjs@@ -232,6 +232,17 @@ export default class QueriesEdit extends Component {@value={{@controller.view}}/>{{/if}}+ {{#if @controller.showDashboardToggle}}+ <DButton+ class="btn-default query-action-bar__dashboard-toggle"+ @action={{@controller.toggleDashboard}}+ @disabled={{@controller.dashboardToggleDisabled}}+ @icon={{@controller.dashboardToggleIcon}}+ @isLoading={{@controller.dashboardBusy}}+ @label={{@controller.dashboardToggleLabel}}+ @translatedTitle={{@controller.dashboardToggleTitle}}+ />+ {{/if}}<QueryResultDownloadButtons@content={{@controller.results}}@includeQueryExport={{true}}diff --git a/plugins/discourse-data-explorer/app/serializers/discourse_data_explorer/query_details_serializer.rb b/plugins/discourse-data-explorer/app/serializers/discourse_data_explorer/query_details_serializer.rbindex d2e76970eb2..45aff103c24 100644--- a/plugins/discourse-data-explorer/app/serializers/discourse_data_explorer/query_details_serializer.rb+++ b/plugins/discourse-data-explorer/app/serializers/discourse_data_explorer/query_details_serializer.rb@@ -2,7 +2,7 @@module DiscourseDataExplorerclass QueryDetailsSerializer < QuerySerializer- attributes :sql, :param_info, :created_at, :hidden+ attributes :sql, :param_info, :created_at, :hidden, :dashboard_mountable, :dashboard_mounteddef include_sql?scope&.is_admin?@@ -11,5 +11,21 @@ module DiscourseDataExplorerdef param_infoobject&.params&.uniq { |p| p.identifier }&.map(&:to_hash)end++ def dashboard_mountable+ AdminDashboardReportProvider.mountable?(object)+ end++ def dashboard_mounted+ AdminDashboardReportProvider.mounted?(object)+ end++ def include_dashboard_mountable?+ scope&.is_admin?+ end++ def include_dashboard_mounted?+ scope&.is_admin?+ endendenddiff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins/show/explorer/edit.js b/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins/show/explorer/edit.jsindex c961e7e9c8c..2e38392d627 100644--- a/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins/show/explorer/edit.js+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins/show/explorer/edit.js@@ -22,6 +22,7 @@ import Query from "discourse/plugins/discourse-data-explorer/discourse/models/quconst DEFAULT_QUERY_TAG = "default";const HIDE_SCHEMA_KEY = "hide_schema";+const DASHBOARD_REPORT_SOURCE = "data_explorer_query";export default class PluginsExplorerController extends Controller {@service modal;@@ -43,6 +44,9 @@ export default class PluginsExplorerController extends Controller {@tracked aiPrompt = "";@tracked aiGenerating = false;@tracked lastGeneratedPrompt = null;+ @tracked dashboardBusy = false;+ @tracked dashboardMounted = false;+ @tracked dashboardMountable = false;queryParams = ["params"];order = null;@@ -146,6 +150,35 @@ export default class PluginsExplorerController extends Controller {);}+ get showDashboardToggle() {+ return this.siteSettings.dashboard_improvements && !this.model.destroyed;+ }++ get dashboardToggleIcon() {+ return this.dashboardMounted ? "thumbtack-slash" : "thumbtack";+ }++ get dashboardToggleLabel() {+ return this.dashboardMounted+ ? "explorer.dashboard.remove"+ : "explorer.dashboard.add";+ }++ get dashboardToggleDisabled() {+ return (+ this.actionsBusy ||+ this.dashboardBusy ||+ (!this.dashboardMounted && !this.dashboardMountable)+ );+ }++ get dashboardToggleTitle() {+ if (this.dashboardMounted || this.dashboardMountable) {+ return null;+ }+ return i18n("explorer.dashboard.unmountable");+ }+get viewItems() {const items = [{ value: "chart", icon: "signal" },@@ -374,6 +407,33 @@ export default class PluginsExplorerController extends Controller {}}+ @action+ async toggleDashboard() {+ const mounted = this.dashboardMounted;+ this.dashboardBusy = true;+ try {+ await ajax("/admin/dashboard/reports/mount", {+ type: mounted ? "DELETE" : "POST",+ data: {+ source: DASHBOARD_REPORT_SOURCE,+ identifier: String(this.model.id),+ },+ });+ this.dashboardMounted = !mounted;+ this.toasts.success({+ data: {+ message: i18n(+ mounted ? "explorer.dashboard.removed" : "explorer.dashboard.added"+ ),+ },+ });+ } catch (error) {+ popupAjaxError(error);+ } finally {+ this.dashboardBusy = false;+ }+ }+@actionupdateGroupIds(value) {this.model.set("group_ids", value);diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/routes/admin-plugins/show/explorer/edit.js b/plugins/discourse-data-explorer/assets/javascripts/discourse/routes/admin-plugins/show/explorer/edit.jsindex e0f3f5bbff1..723b9347199 100644--- a/plugins/discourse-data-explorer/assets/javascripts/discourse/routes/admin-plugins/show/explorer/edit.js+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/routes/admin-plugins/show/explorer/edit.js@@ -61,6 +61,8 @@ export default class AdminPluginsExplorerQueriesDetails extends DiscourseRoute {results: showCachedResult ? cachedResult : null,showResults: showCachedResult,isCachedResult: showCachedResult,+ dashboardMounted: !!model.model.dashboard_mounted,+ dashboardMountable: !!model.model.dashboard_mountable,shouldAutoRun,mode: defaultMode,aiPrompt: "",diff --git a/plugins/discourse-data-explorer/config/locales/client.en.yml b/plugins/discourse-data-explorer/config/locales/client.en.ymlindex fbdb2818c58..862a0c87966 100644--- a/plugins/discourse-data-explorer/config/locales/client.en.yml+++ b/plugins/discourse-data-explorer/config/locales/client.en.yml@@ -108,6 +108,12 @@ en:undo: "Discard changes"delete: "Delete"recover: "Undelete query"+ dashboard:+ add: "Add to dashboard"+ remove: "Remove from dashboard"+ added: "Query added to dashboard"+ removed: "Query removed from dashboard"+ unmountable: "Queries with required parameters that have no default value can't be shown on the dashboard"sql_label: "SQL"run_with_explain: "Run with query plan"run_options: "More run options"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.rbindex ad85470c548..64224e24f45 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@@ -114,7 +114,10 @@ module DiscourseDataExplorerDASHBOARD_SUPPLIED_PARAMS.include?(param.identifier)endend- private_class_method :mountable?++ def self.mounted?(query)+ AdminDashboardReport.exists?(source: SOURCE_NAME, identifier: query.id.to_s)+ enddef self.prewarmable?(query, params)QueryRunner.cacheable?(query) &&diff --git a/plugins/discourse-data-explorer/plugin.rb b/plugins/discourse-data-explorer/plugin.rbindex 07aa3edd0ce..620a26760ca 100644--- a/plugins/discourse-data-explorer/plugin.rb+++ b/plugins/discourse-data-explorer/plugin.rb@@ -18,6 +18,7 @@ register_svg_icon "angle-left"register_svg_icon "circle-exclamation"register_svg_icon "info"register_svg_icon "pencil"+register_svg_icon "thumbtack-slash"register_svg_icon "upload"add_admin_route "explorer.title", "discourse-data-explorer", use_new_show_route: truediff --git a/plugins/discourse-data-explorer/spec/requests/query_controller_spec.rb b/plugins/discourse-data-explorer/spec/requests/query_controller_spec.rbindex 22b9168230c..f24bcf26eb3 100644--- a/plugins/discourse-data-explorer/spec/requests/query_controller_spec.rb+++ b/plugins/discourse-data-explorer/spec/requests/query_controller_spec.rb@@ -354,6 +354,33 @@ describe DiscourseDataExplorer::QueryController doendend+ describe "#show" do+ it "reports whether the query can be, and is, on the admin dashboard" do+ query = make_query("SELECT 1 as value")++ get "/admin/plugins/discourse-data-explorer/queries/#{query.id}.json"++ expect(response.status).to eq(200)+ expect(response_json["query"]["dashboard_mountable"]).to eq(true)+ expect(response_json["query"]["dashboard_mounted"]).to eq(false)++ AdminDashboardReport.create!(source: "data_explorer_query", identifier: query.id.to_s)++ get "/admin/plugins/discourse-data-explorer/queries/#{query.id}.json"++ expect(response_json["query"]["dashboard_mounted"]).to eq(true)+ end++ it "flags a query with a required parameter as not mountable" do+ query = make_query("-- [params]\n-- int :num\nSELECT :num")++ get "/admin/plugins/discourse-data-explorer/queries/#{query.id}.json"++ expect(response.status).to eq(200)+ expect(response_json["query"]["dashboard_mountable"]).to eq(false)+ end+ end+describe "#destroy" doit "returns 404 when query does not exist" dodelete "/admin/plugins/discourse-data-explorer/queries/999999.json"@@ -1177,6 +1204,15 @@ describe DiscourseDataExplorer::QueryController doexpect(response.status).to eq(200)end+ it "does not expose admin dashboard state" do+ query = make_query("SELECT 1 as value", {}, [group.id.to_s])++ get "/g/#{group.name}/reports/#{query.id}.json"+ expect(response.status).to eq(200)+ expect(response_json["query"]).not_to have_key("dashboard_mountable")+ expect(response_json["query"]).not_to have_key("dashboard_mounted")+ end+it "return a 404 when the query is hidden" doquery = make_query("SELECT 1 as value", { hidden: true }, [group.id.to_s])diff --git a/plugins/discourse-data-explorer/spec/system/admin_dashboard_toggle_spec.rb b/plugins/discourse-data-explorer/spec/system/admin_dashboard_toggle_spec.rbnew file mode 100644index 00000000000..3e9bd18315c--- /dev/null+++ b/plugins/discourse-data-explorer/spec/system/admin_dashboard_toggle_spec.rb@@ -0,0 +1,73 @@+# frozen_string_literal: true++describe "Data Explorer | Add query to admin dashboard" do+ fab!(:current_user, :admin)+ fab!(:query) { Fabricate(:query, name: "Signups", sql: "SELECT 1 AS value", user: current_user) }++ let(:query_runner) { PageObjects::Pages::DataExplorerQueryRunner.new }+ let(:dashboard) { PageObjects::Pages::AdminDashboardReports.new }+ let(:toasts) { PageObjects::Components::Toasts.new }++ before do+ SiteSetting.dashboard_improvements = true+ SiteSetting.data_explorer_enabled = true+ SiteSetting.data_explorer_ai_queries_enabled = false+ AdminDashboardSectionConfiguration.update(+ [+ { id: "reports", visible: true },+ { id: "highlights", visible: false },+ { id: "traffic", visible: false },+ { id: "engagement", visible: false },+ ],+ actor: current_user,+ )+ AdminDashboardReport.delete_all+ sign_in(current_user)+ end++ it "adds the query to the dashboard and removes it again" do+ query_runner.visit_admin_query(query.id)+ expect(query_runner).to have_dashboard_toggle("Add to dashboard")++ query_runner.click_dashboard_toggle++ expect(toasts).to have_success(I18n.t("js.explorer.dashboard.added"))+ expect(query_runner).to have_dashboard_toggle("Remove from dashboard")+ expect(+ AdminDashboardReport.exists?(source: "data_explorer_query", identifier: query.id.to_s),+ ).to eq(true)++ query_runner.click_dashboard_toggle++ expect(toasts).to have_success(I18n.t("js.explorer.dashboard.removed"))+ expect(query_runner).to have_dashboard_toggle("Add to dashboard")+ expect(AdminDashboardReport.count).to eq(0)+ end++ it "shows the added query on the admin dashboard" do+ query_runner.visit_admin_query(query.id)+ query_runner.click_dashboard_toggle+ expect(query_runner).to have_dashboard_toggle("Remove from dashboard")++ page.visit("/admin")++ expect(dashboard).to have_card("data_explorer_query:#{query.id}")+ end++ it "disables the button for a query with a required parameter" do+ query.update!(sql: "-- [params]\n-- int :num\nSELECT :num")++ query_runner.visit_admin_query(query.id)++ expect(query_runner).to have_disabled_dashboard_toggle+ end++ it "hides the button when the dashboard improvements are disabled" do+ SiteSetting.dashboard_improvements = false++ query_runner.visit_admin_query(query.id)++ expect(page).to have_css(".query-run-split__primary")+ expect(query_runner).to have_no_dashboard_toggle+ end+enddiff --git a/plugins/discourse-data-explorer/spec/system/page_objects/pages/data_explorer_query_runner.rb b/plugins/discourse-data-explorer/spec/system/page_objects/pages/data_explorer_query_runner.rbindex dac91ac2b28..a4f396f1a93 100644--- a/plugins/discourse-data-explorer/spec/system/page_objects/pages/data_explorer_query_runner.rb+++ b/plugins/discourse-data-explorer/spec/system/page_objects/pages/data_explorer_query_runner.rb@@ -84,6 +84,23 @@ module PageObjects)end+ def has_dashboard_toggle?(label)+ page.has_css?(".query-action-bar__dashboard-toggle", text: label)+ end++ def has_no_dashboard_toggle?+ page.has_no_css?(".query-action-bar__dashboard-toggle")+ end++ def has_disabled_dashboard_toggle?+ page.has_css?(".query-action-bar__dashboard-toggle:disabled")+ end++ def click_dashboard_toggle+ page.find(".query-action-bar__dashboard-toggle:not(:disabled)").click+ self+ end+def visit_new_querypage.visit("/admin/plugins/discourse-data-explorer/queries/new")selfdiff --git a/spec/requests/admin/dashboard_controller_spec.rb b/spec/requests/admin/dashboard_controller_spec.rbindex e3bae06dd17..f1db1f46ef0 100644--- a/spec/requests/admin/dashboard_controller_spec.rb+++ b/spec/requests/admin/dashboard_controller_spec.rb@@ -2513,4 +2513,167 @@ RSpec.describe Admin::DashboardController doendendend++ describe "#mount_report and #unmount_report" do+ before { AdminDashboardReport.delete_all }++ 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 }++ before { DiscoursePluginRegistry.register_admin_dashboard_report_source(fake_provider, plugin) }++ after do+ DiscoursePluginRegistry._raw_admin_dashboard_report_sources.reject! do |entry|+ entry[:value] == fake_provider+ end+ end++ context "when not signed in" do+ it "denies access" do+ post "/admin/dashboard/reports/mount.json",+ params: {+ source: "fake_source",+ identifier: "a",+ }+ expect(response.status).to eq(404)++ delete "/admin/dashboard/reports/mount.json",+ params: {+ source: "fake_source",+ identifier: "a",+ }+ expect(response.status).to eq(404)+ end+ end++ context "when signed in as a moderator" do+ before { sign_in(moderator) }++ it "denies access" do+ post "/admin/dashboard/reports/mount.json",+ params: {+ source: "fake_source",+ identifier: "a",+ }+ expect(response.status).to eq(404)++ delete "/admin/dashboard/reports/mount.json",+ params: {+ source: "fake_source",+ identifier: "a",+ }+ expect(response.status).to eq(404)+ end+ end++ context "when signed in as an admin" do+ before { sign_in(admin) }++ it "appends the report after the existing layout" do+ AdminDashboardReport.create!(source: "fake_source", identifier: "old", position: 4)++ post "/admin/dashboard/reports/mount.json",+ params: {+ source: "fake_source",+ identifier: "new",+ }++ expect(response.status).to eq(201)+ expect(response.parsed_body).to include("source" => "fake_source", "identifier" => "new")+ expect(AdminDashboardReport.order(:position).pluck(:identifier)).to eq(%w[old new])+ end++ it "is a no-op when the report is already mounted" do+ AdminDashboardReport.create!(source: "fake_source", identifier: "a", position: 0)++ post "/admin/dashboard/reports/mount.json",+ params: {+ source: "fake_source",+ identifier: "a",+ }++ expect(response.status).to eq(201)+ expect(AdminDashboardReport.count).to eq(1)+ end++ it "rejects a report the guardian cannot access" do+ post "/admin/dashboard/reports/mount.json",+ params: {+ source: "fake_source",+ identifier: "forbidden",+ }++ expect(response.status).to eq(403)+ expect(AdminDashboardReport.count).to eq(0)+ end++ it "rejects a source with no registered provider" do+ post "/admin/dashboard/reports/mount.json",+ params: {+ source: "totally_unregistered",+ identifier: "a",+ }++ expect(response.status).to eq(400)+ end++ it "rejects a missing identifier" do+ post "/admin/dashboard/reports/mount.json", params: { source: "fake_source" }++ expect(response.status).to eq(400)+ end++ it "refuses to exceed VISIBLE_CAP" do+ AdminDashboardReport::VISIBLE_CAP.times do |i|+ AdminDashboardReport.create!(source: "fake_source", identifier: "id#{i}", position: i)+ end++ post "/admin/dashboard/reports/mount.json",+ params: {+ source: "fake_source",+ identifier: "one_too_many",+ }++ expect(response.status).to eq(422)+ expect(response.parsed_body["errors"].first).to eq(+ I18n.t("dashboard.reports.cap_reached", max: AdminDashboardReport::VISIBLE_CAP),+ )+ expect(AdminDashboardReport.count).to eq(AdminDashboardReport::VISIBLE_CAP)+ end++ it "removes only the named report" do+ AdminDashboardReport.create!(source: "fake_source", identifier: "a", position: 0)+ AdminDashboardReport.create!(source: "fake_source", identifier: "b", position: 1)++ delete "/admin/dashboard/reports/mount.json",+ params: {+ source: "fake_source",+ identifier: "a",+ }++ expect(response.status).to eq(204)+ expect(AdminDashboardReport.pluck(:identifier)).to eq(["b"])+ end++ it "succeeds when the report is not mounted" do+ delete "/admin/dashboard/reports/mount.json",+ params: {+ source: "fake_source",+ identifier: "missing",+ }++ expect(response.status).to eq(204)+ end+ end+ endend