A platform for community discussion. Free, open, simple.
DEV: Persist dashboard configuration in table and *not* on closure of the dialog (#40546)
Natalie Tay8d43a7c5d7c2
diff --git a/app/controllers/admin/dashboard_controller.rb b/app/controllers/admin/dashboard_controller.rbindex 0c8f79bb588..543891cd03b 100644--- a/app/controllers/admin/dashboard_controller.rb+++ b/app/controllers/admin/dashboard_controller.rb@@ -8,11 +8,7 @@ class Admin::DashboardController < Admin::StaffControllerdef indexif dashboard_improvements?- visible_ids = AdminDashboardSectionConfiguration.visible_section_ids- data = { sections: visible_ids.map { |id| { id: id, data: section_data(id) } } }- if current_user.admin?- data[:configuration] = { sections: AdminDashboardSectionConfiguration.sections }- end+ data = dashboard_sections_payloadelsedata = AdminDashboardIndexData.fetch_cached_stats@@ -135,6 +131,15 @@ class Admin::DashboardController < Admin::StaffControllerprivate+ def dashboard_sections_payload+ visible_ids = AdminDashboardSectionConfiguration.visible_section_ids+ data = { sections: visible_ids.map { |id| { id: id, data: section_data(id) } } }+ if current_user.admin?+ data[:configuration] = { sections: AdminDashboardSectionConfiguration.sections }+ end+ data+ end+def section_data(id)case idwhen "highlights"diff --git a/app/models/admin_dashboard_section.rb b/app/models/admin_dashboard_section.rbnew file mode 100644index 00000000000..10f950371f9--- /dev/null+++ b/app/models/admin_dashboard_section.rb@@ -0,0 +1,23 @@+# frozen_string_literal: true++class AdminDashboardSection < ActiveRecord::Base+ validates :section_id, presence: true, uniqueness: true+ validates :position, presence: true+ validates :visible, inclusion: { in: [true, false] }+end++# == Schema Information+#+# Table name: admin_dashboard_sections+#+# id :bigint not null, primary key+# position :integer not null+# visible :boolean default(TRUE), not null+# created_at :datetime not null+# updated_at :datetime not null+# section_id :string not null+#+# Indexes+#+# index_admin_dashboard_sections_on_section_id (section_id) UNIQUE+#diff --git a/app/services/admin_dashboard_section_configuration.rb b/app/services/admin_dashboard_section_configuration.rbindex c4ee407e1b3..8bb0ded5d7e 100644--- a/app/services/admin_dashboard_section_configuration.rb+++ b/app/services/admin_dashboard_section_configuration.rb@@ -3,29 +3,51 @@class AdminDashboardSectionConfigurationKNOWN_SECTIONS = %w[highlights reports traffic engagement].freeze- def self.visible_section_ids- raw = SiteSetting.admin_dashboard_sections.to_s- return [] if raw.empty?-- ids = raw.split("|").map(&:strip).uniq.select { |id| KNOWN_SECTIONS.include?(id) }- ids.empty? ? KNOWN_SECTIONS.dup : ids+ def self.sections+ AdminDashboardSection+ .where(section_id: KNOWN_SECTIONS)+ .order(:position)+ .pluck(:section_id, :visible)+ .map { |id, visible| { id:, visible: } }end- def self.sections- visible = visible_section_ids- hidden = KNOWN_SECTIONS - visible- visible.map { |id| { id: id, visible: true } } + hidden.map { |id| { id: id, visible: false } }+ def self.visible_section_ids+ sections.select { |s| s[:visible] }.map { |s| s[:id] }enddef self.update(input_sections, actor:)- visible_ids =+ sanitized =Array(input_sections)- .select { |s| ActiveModel::Type::Boolean.new.cast(s[:visible] || s["visible"]) }- .map { |s| (s[:id] || s["id"]).to_s }- .uniq- .select { |id| KNOWN_SECTIONS.include?(id) }+ .filter_map do |s|+ attrs = (s.respond_to?(:to_unsafe_h) ? s.to_unsafe_h : s.to_h).symbolize_keys+ id = attrs[:id].to_s+ next if KNOWN_SECTIONS.exclude?(id)+ { id:, visible: ActiveModel::Type::Boolean.new.cast(attrs[:visible]) }+ end+ .uniq { |s| s[:id] }++ present_ids = sanitized.map { |s| s[:id] }+ missing = sections.reject { |s| present_ids.include?(s[:id]) }+ ordered = sanitized + missing++ now = Time.zone.now+ rows =+ ordered.each_with_index.map do |section, index|+ {+ section_id: section[:id],+ position: index,+ visible: section[:visible],+ created_at: now,+ updated_at: now,+ }+ end+ AdminDashboardSection.upsert_all(rows, unique_by: :section_id)++ StaffActionLogger.new(actor).log_custom(+ "update_dashboard_sections",+ layout: ordered.map { |s| "#{s[:id]}:#{s[:visible] ? "visible" : "hidden"}" }.join(", "),+ )- SiteSetting.set_and_log("admin_dashboard_sections", visible_ids.join("|"), actor)sectionsendenddiff --git a/config/locales/server.en.yml b/config/locales/server.en.ymlindex e03142842e9..b76d73fa7ea 100644--- a/config/locales/server.en.yml+++ b/config/locales/server.en.yml@@ -2806,7 +2806,6 @@ en:dashboard_hidden_reports: "Allow to hide the specified reports from the dashboard."dashboard_visible_tabs: "Choose which dashboard tabs are visible."dashboard_general_tab_activity_metrics: "Choose reports to be displayed as activity metrics on the general tab."- admin_dashboard_sections: "Sections shown on the redesigned admin dashboard, in display order. Managed via the Configure menu on the dashboard."gravatar_enabled: "Use the <a href='https://gravatar.com/'>Gravatar</a> service for user avatars. Disabling this will prevent users from switching to Gravatar for their avatars, but will not impact users who already use it."gravatar_name: "Specify the name of the Gravatar service provider. This name is typically used to identify the source providing Gravatar avatars to the site."diff --git a/config/site_settings.yml b/config/site_settings.ymlindex 40e056c9562..c5d43571bdc 100644--- a/config/site_settings.yml+++ b/config/site_settings.yml@@ -4355,18 +4355,6 @@ dashboard:- reports- featuresarea: "reports"- admin_dashboard_sections:- type: list- list_type: compact- default: "highlights|reports|traffic|engagement"- allow_any: false- choices:- - highlights- - reports- - traffic- - engagement- area: "reports"- hidden: truedashboard_general_tab_activity_metrics:client: truetype: listdiff --git a/db/fixtures/601_admin_dashboard_sections.rb b/db/fixtures/601_admin_dashboard_sections.rbnew file mode 100644index 00000000000..7e1758b669c--- /dev/null+++ b/db/fixtures/601_admin_dashboard_sections.rb@@ -0,0 +1,5 @@+# frozen_string_literal: true++require "seed_data/admin_dashboard_sections"++SeedData::AdminDashboardSections.creatediff --git a/db/migrate/20260603115200_create_admin_dashboard_sections.rb b/db/migrate/20260603115200_create_admin_dashboard_sections.rbnew file mode 100644index 00000000000..1e7faa96aaa--- /dev/null+++ b/db/migrate/20260603115200_create_admin_dashboard_sections.rb@@ -0,0 +1,13 @@+# frozen_string_literal: true+class CreateAdminDashboardSections < ActiveRecord::Migration[8.0]+ def change+ create_table :admin_dashboard_sections do |t|+ t.string :section_id, null: false+ t.integer :position, null: false+ t.boolean :visible, null: false, default: true+ t.timestamps+ end++ add_index :admin_dashboard_sections, :section_id, unique: true+ end+enddiff --git a/db/post_migrate/20260603115312_remove_admin_dashboard_sections_setting.rb b/db/post_migrate/20260603115312_remove_admin_dashboard_sections_setting.rbnew file mode 100644index 00000000000..9b5b31d14c7--- /dev/null+++ b/db/post_migrate/20260603115312_remove_admin_dashboard_sections_setting.rb@@ -0,0 +1,10 @@+# frozen_string_literal: true+class RemoveAdminDashboardSectionsSetting < ActiveRecord::Migration[8.0]+ def up+ execute "DELETE FROM site_settings WHERE name = 'admin_dashboard_sections'"+ end++ def down+ raise ActiveRecord::IrreversibleMigration+ end+enddiff --git a/db/structure.sql b/db/structure.sqlindex 32d7a57f44b..98ea4cc7565 100644--- a/db/structure.sql+++ b/db/structure.sql@@ -294,6 +294,39 @@ CREATE SEQUENCE public.admin_dashboard_reports_id_seqALTER SEQUENCE public.admin_dashboard_reports_id_seq OWNED BY public.admin_dashboard_reports.id;+--+-- Name: admin_dashboard_sections; Type: TABLE; Schema: public; Owner: -+--++CREATE TABLE public.admin_dashboard_sections (+ id bigint NOT NULL,+ section_id character varying NOT NULL,+ "position" integer NOT NULL,+ visible boolean DEFAULT true NOT NULL,+ created_at timestamp(6) without time zone NOT NULL,+ updated_at timestamp(6) without time zone NOT NULL+);+++--+-- Name: admin_dashboard_sections_id_seq; Type: SEQUENCE; Schema: public; Owner: -+--++CREATE SEQUENCE public.admin_dashboard_sections_id_seq+ START WITH 1+ INCREMENT BY 1+ NO MINVALUE+ NO MAXVALUE+ CACHE 1;+++--+-- Name: admin_dashboard_sections_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -+--++ALTER SEQUENCE public.admin_dashboard_sections_id_seq OWNED BY public.admin_dashboard_sections.id;++---- Name: admin_notices; Type: TABLE; Schema: public; Owner: ---@@ -11800,6 +11833,13 @@ ALTER TABLE ONLY public.ad_plugin_impressions ALTER COLUMN id SET DEFAULT nextvaALTER TABLE ONLY public.admin_dashboard_reports ALTER COLUMN id SET DEFAULT nextval('public.admin_dashboard_reports_id_seq'::regclass);+--+-- Name: admin_dashboard_sections id; Type: DEFAULT; Schema: public; Owner: -+--++ALTER TABLE ONLY public.admin_dashboard_sections ALTER COLUMN id SET DEFAULT nextval('public.admin_dashboard_sections_id_seq'::regclass);++---- Name: admin_notices id; Type: DEFAULT; Schema: public; Owner: ---@@ -13917,6 +13957,14 @@ ALTER TABLE ONLY public.admin_dashboard_reportsADD CONSTRAINT admin_dashboard_reports_pkey PRIMARY KEY (id);+--+-- Name: admin_dashboard_sections admin_dashboard_sections_pkey; Type: CONSTRAINT; Schema: public; Owner: -+--++ALTER TABLE ONLY public.admin_dashboard_sections+ ADD CONSTRAINT admin_dashboard_sections_pkey PRIMARY KEY (id);++---- Name: admin_notices admin_notices_pkey; Type: CONSTRAINT; Schema: public; Owner: ---@@ -17257,6 +17305,13 @@ CREATE INDEX index_admin_dashboard_reports_on_position ON public.admin_dashboardCREATE UNIQUE INDEX index_admin_dashboard_reports_on_source_and_identifier ON public.admin_dashboard_reports USING btree (source, identifier);+--+-- Name: index_admin_dashboard_sections_on_section_id; Type: INDEX; Schema: public; Owner: -+--++CREATE UNIQUE INDEX index_admin_dashboard_sections_on_section_id ON public.admin_dashboard_sections USING btree (section_id);++---- Name: index_admin_notices_on_identifier; Type: INDEX; Schema: public; Owner: ---@@ -21795,6 +21850,8 @@ ALTER TABLE ONLY public.ad_plugin_house_ads_groupsSET search_path TO "$user", public;INSERT INTO "schema_migrations" (version) VALUES+('20260603115312'),+('20260603115200'),('20260601043020'),('20260525105009'),('20260525105006'),diff --git a/frontend/discourse/admin/components/redesigned-admin-dashboard.gjs b/frontend/discourse/admin/components/redesigned-admin-dashboard.gjsindex 21d4ff8c531..0636a429077 100644--- a/frontend/discourse/admin/components/redesigned-admin-dashboard.gjs+++ b/frontend/discourse/admin/components/redesigned-admin-dashboard.gjs@@ -1,7 +1,5 @@import Component from "@glimmer/component";-import { tracked } from "@glimmer/tracking";import { concat } from "@ember/helper";-import { action } from "@ember/object";import { service } from "@ember/service";import ConfigureMenu from "discourse/admin/components/dashboard/configure-menu";import DashboardDateRange from "discourse/admin/components/dashboard/date-range";@@ -11,78 +9,14 @@ import DashboardReports from "discourse/admin/components/dashboard/reports";import DashboardSkeleton from "discourse/admin/components/dashboard/skeleton";import DashboardTraffic from "discourse/admin/components/dashboard/traffic";import DMenu from "discourse/float-kit/components/d-menu";-import { popupAjaxError } from "discourse/lib/ajax-error";-import { deepEqual } from "discourse/lib/object";import { eq } from "discourse/truth-helpers";import { i18n } from "discourse-i18n";export default class RedesignedAdminDashboard extends Component {@service currentUser;- @tracked pendingSections;-- _saving = false;- _opened = false;-- constructor() {- super(...arguments);- this.pendingSections = this.#buildPendingSections(- this.args.loadedSections?.configuration?.sections- );- }-- @action- onMenuOpen() {- this._opened = true;- this.pendingSections = this.#buildPendingSections(- this.args.loadedSections?.configuration?.sections- );- }-- @action- toggleVisibility(id) {- this.pendingSections = this.pendingSections.map((s) =>- s.id === id ? { ...s, visible: !s.visible } : s- );- }-- @action- reorder(fromIndex, toIndex) {- const next = [...this.pendingSections];- const [moved] = next.splice(fromIndex, 1);- next.splice(toIndex, 0, moved);- this.pendingSections = next;- }-- @action- onMenuClose() {- if (this._saving || !this._opened) {- return;- }-- const committedSections =- this.args.loadedSections?.configuration?.sections ?? [];-- if (deepEqual(this.pendingSections, committedSections)) {- return;- }-- this._saving = true;- this.args- .updateConfiguration(this.pendingSections)- .catch((e) => {- popupAjaxError(e);- this.pendingSections = this.#buildPendingSections(- this.args.loadedSections?.configuration?.sections- );- })- .finally(() => {- this._saving = false;- });- }-- #buildPendingSections(sections) {- return sections?.map((section) => ({ ...section })) ?? [];+ get configurationSections() {+ return this.args.loadedSections?.configuration?.sections ?? [];}<template>@@ -105,14 +39,12 @@ export default class RedesignedAdminDashboard extends Component {@title={{i18n "admin.dashboard.configure.tooltip"}}@triggerClass="btn-default"@modalForMobile={{true}}- @onClose={{this.onMenuClose}}- @onShow={{this.onMenuOpen}}><:content><ConfigureMenu- @sections={{this.pendingSections}}- @onReorder={{this.reorder}}- @onToggleVisibility={{this.toggleVisibility}}+ @sections={{this.configurationSections}}+ @onReorder={{@reorderSections}}+ @onToggleVisibility={{@toggleSection}}/></:content></DMenu>diff --git a/frontend/discourse/admin/controllers/admin/dashboard.js b/frontend/discourse/admin/controllers/admin/dashboard.jsindex 6c9682739cd..8cb9c0b7e39 100644--- a/frontend/discourse/admin/controllers/admin/dashboard.js+++ b/frontend/discourse/admin/controllers/admin/dashboard.js@@ -11,6 +11,7 @@ import {import AdminDashboard from "discourse/admin/models/admin-dashboard";import VersionCheck from "discourse/admin/models/version-check";import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";import { autoTrackedArray } from "discourse/lib/tracked-tools";const PROBLEMS_CHECK_MINUTES = 1;@@ -38,6 +39,8 @@ export default class AdminDashboardController extends Controller {dashboardFetchedAt = null;_sectionsLoadId = 0;_sectionsLoadingCount = 0;+ _configSaveId = 0;+ _sectionDataCache = new Map();get safePeriod() {if (!VALID_PERIODS.includes(this.range)) {@@ -86,13 +89,64 @@ export default class AdminDashboardController extends Controller {}@action- async updateConfiguration(sections) {- await ajax("/admin/dashboard/configuration.json", {- type: "PUT",- contentType: "application/json",- data: JSON.stringify({ sections }),- });- await this.fetchSections();+ toggleSection(id) {+ const previous = this.loadedSections;+ const current = previous?.configuration?.sections ?? [];+ const wasVisible = current.find((s) => s.id === id)?.visible;+ const nextConfig = current.map((s) =>+ s.id === id ? { ...s, visible: !s.visible } : s+ );++ this.#applyConfigOptimistically(nextConfig);++ const needsRefetch = !wasVisible && !this._sectionDataCache.has(id);+ this.#persistConfiguration(nextConfig, previous, { needsRefetch });+ }++ @action+ reorderSections(fromIndex, toIndex) {+ const previous = this.loadedSections;+ const nextConfig = [...(previous?.configuration?.sections ?? [])];+ const [moved] = nextConfig.splice(fromIndex, 1);+ nextConfig.splice(toIndex, 0, moved);++ this.#applyConfigOptimistically(nextConfig);+ this.#persistConfiguration(nextConfig, previous, { needsRefetch: false });+ }++ #applyConfigOptimistically(nextConfig) {+ for (const section of this.loadedSections?.sections ?? []) {+ this._sectionDataCache.set(section.id, section.data);+ }++ this.loadedSections = {+ ...this.loadedSections,+ sections: nextConfig+ .filter((s) => s.visible && this._sectionDataCache.has(s.id))+ .map((s) => ({ id: s.id, data: this._sectionDataCache.get(s.id) })),+ configuration: { sections: nextConfig },+ };+ }++ async #persistConfiguration(sections, revertTo, { needsRefetch } = {}) {+ const saveId = ++this._configSaveId;++ try {+ await ajax("/admin/dashboard/configuration.json", {+ type: "PUT",+ contentType: "application/json",+ data: JSON.stringify({ sections }),+ });++ if (needsRefetch && saveId === this._configSaveId) {+ await this.fetchSections();+ }+ } catch (e) {+ if (saveId === this._configSaveId) {+ this.loadedSections = revertTo;+ }+ popupAjaxError(e);+ }}@actiondiff --git a/frontend/discourse/admin/templates/admin/dashboard.gjs b/frontend/discourse/admin/templates/admin/dashboard.gjsindex eadfe10a769..229b35e27c5 100644--- a/frontend/discourse/admin/templates/admin/dashboard.gjs+++ b/frontend/discourse/admin/templates/admin/dashboard.gjs@@ -16,7 +16,8 @@ export default <template>@setPeriod={{@controller.setPeriod}}@setCustomDateRange={{@controller.setCustomDateRange}}@loadedSections={{@controller.loadedSections}}- @updateConfiguration={{@controller.updateConfiguration}}+ @toggleSection={{@controller.toggleSection}}+ @reorderSections={{@controller.reorderSections}}@refreshSections={{@controller.fetchSections}}@loadingSections={{@controller.loadingSections}}@sectionsFetchError={{@controller.sectionsFetchError}}diff --git a/lib/seed_data/admin_dashboard_sections.rb b/lib/seed_data/admin_dashboard_sections.rbnew file mode 100644index 00000000000..05c6fde510e--- /dev/null+++ b/lib/seed_data/admin_dashboard_sections.rb@@ -0,0 +1,14 @@+# frozen_string_literal: true++module SeedData+ class AdminDashboardSections+ def self.create+ AdminDashboardSectionConfiguration::KNOWN_SECTIONS.each do |section_id|+ next if AdminDashboardSection.exists?(section_id:)++ next_position = (AdminDashboardSection.maximum(:position) || -1) + 1+ AdminDashboardSection.create!(section_id:, position: next_position, visible: true)+ end+ end+ end+enddiff --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.rbindex 60eb76690a6..881fec27b97 100644--- 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@@ -10,7 +10,15 @@ describe "Data Explorer | Manage Reports footer hint" dobefore doSiteSetting.dashboard_improvements = trueSiteSetting.data_explorer_enabled = true- SiteSetting.admin_dashboard_sections = "reports"+ AdminDashboardSectionConfiguration.update(+ [+ { id: "reports", visible: true },+ { id: "highlights", visible: false },+ { id: "traffic", visible: false },+ { id: "engagement", visible: false },+ ],+ actor: current_user,+ )AdminDashboardReport.delete_allsign_in(current_user)enddiff --git a/spec/lib/seed_data/admin_dashboard_sections_spec.rb b/spec/lib/seed_data/admin_dashboard_sections_spec.rbnew file mode 100644index 00000000000..9fde371f7ad--- /dev/null+++ b/spec/lib/seed_data/admin_dashboard_sections_spec.rb@@ -0,0 +1,51 @@+# frozen_string_literal: true++require "seed_data/admin_dashboard_sections"++describe SeedData::AdminDashboardSections do+ before { AdminDashboardSection.delete_all }++ it "seeds every known section, visible, in canonical order" do+ described_class.create++ rows = AdminDashboardSection.order(:position).pluck(:section_id, :position, :visible)+ expect(rows).to eq(+ [+ ["highlights", 0, true],+ ["reports", 1, true],+ ["traffic", 2, true],+ ["engagement", 3, true],+ ],+ )+ end++ it "is idempotent and does not duplicate rows" do+ described_class.create+ described_class.create++ expect(AdminDashboardSection.count).to eq(+ AdminDashboardSectionConfiguration::KNOWN_SECTIONS.size,+ )+ end++ it "preserves existing visibility and position" do+ AdminDashboardSection.create!(section_id: "reports", position: 0, visible: false)++ described_class.create++ reports = AdminDashboardSection.find_by(section_id: "reports")+ expect(reports).to have_attributes(position: 0, visible: false)+ end++ it "re-adds a missing known section at the end" do+ described_class.create+ AdminDashboardSection.where(section_id: "engagement").delete_all++ described_class.create++ expect(AdminDashboardSection.order(:position).last).to have_attributes(+ section_id: "engagement",+ visible: true,+ )+ end+enddiff --git a/spec/models/admin_dashboard_section_spec.rb b/spec/models/admin_dashboard_section_spec.rbnew file mode 100644index 00000000000..24ba92c2e80--- /dev/null+++ b/spec/models/admin_dashboard_section_spec.rb@@ -0,0 +1,25 @@+# frozen_string_literal: true++describe AdminDashboardSection do+ before { described_class.delete_all }++ it "requires a section_id" do+ expect(described_class.new(position: 0, visible: true)).not_to be_valid+ end++ it "requires a position" do+ expect(described_class.new(section_id: "highlights", visible: true)).not_to be_valid+ end++ it "enforces a unique section_id" do+ described_class.create!(section_id: "highlights", position: 0, visible: true)++ expect {+ described_class.create!(section_id: "highlights", position: 1, visible: true)+ }.to raise_error(ActiveRecord::RecordInvalid)+ end++ it "is valid with all attributes" do+ expect(described_class.new(section_id: "highlights", position: 0, visible: false)).to be_valid+ end+enddiff --git a/spec/requests/admin/dashboard_controller_spec.rb b/spec/requests/admin/dashboard_controller_spec.rbindex 69679d3feef..da64858a50e 100644--- a/spec/requests/admin/dashboard_controller_spec.rb+++ b/spec/requests/admin/dashboard_controller_spec.rb@@ -10,6 +10,14 @@ RSpec.describe Admin::DashboardController doJobs::CallDiscourseHub.any_instance.stubs(:execute).returns(true)end+ def configure_dashboard_sections(visible_ids)+ hidden = AdminDashboardSectionConfiguration::KNOWN_SECTIONS - visible_ids+ ordered =+ visible_ids.map { |id| { id: id, visible: true } } ++ hidden.map { |id| { id: id, visible: false } }+ AdminDashboardSectionConfiguration.update(ordered, actor: Discourse.system_user)+ end+def populate_new_features(date1 = nil, date2 = nil)sample_features = [{@@ -108,7 +116,6 @@ RSpec.describe Admin::DashboardController dodescribe "sections payload" dobefore doSiteSetting.dashboard_improvements = true- SiteSetting.admin_dashboard_sections = "highlights|reports|traffic|engagement"Discourse.cache.clearsign_in(admin)end@@ -292,7 +299,7 @@ RSpec.describe Admin::DashboardController doendit "returns the sections as an ordered array of {id, data}" do- SiteSetting.admin_dashboard_sections = "reports|highlights"+ configure_dashboard_sections(%w[reports highlights])get "/admin/dashboard.json"@@ -301,7 +308,7 @@ RSpec.describe Admin::DashboardController doendit "omits hidden sections from the data payload" do- SiteSetting.admin_dashboard_sections = "highlights|reports"+ configure_dashboard_sections(%w[highlights reports])get "/admin/dashboard.json"@@ -310,7 +317,7 @@ RSpec.describe Admin::DashboardController doendit "includes built engagement data when the section is enabled" do- SiteSetting.admin_dashboard_sections = "highlights|engagement"+ configure_dashboard_sections(%w[highlights engagement])get "/admin/dashboard.json"engagement = response.parsed_body["sections"].find { |s| s["id"] == "engagement" }@@ -392,7 +399,7 @@ RSpec.describe Admin::DashboardController doendit "is included for admins and lists every known section with a visibility flag" do- SiteSetting.admin_dashboard_sections = "highlights|reports"+ configure_dashboard_sections(%w[highlights reports])sign_in(admin)get "/admin/dashboard.json"@@ -428,12 +435,9 @@ RSpec.describe Admin::DashboardController doenddescribe "#update_configuration" do- before do- SiteSetting.dashboard_improvements = true- SiteSetting.admin_dashboard_sections = "highlights|reports|traffic|engagement"- end+ before { SiteSetting.dashboard_improvements = true }- it "returns 204 and writes the site setting for admins" do+ it "persists the configuration and returns 204 for admins" dosign_in(admin)put "/admin/dashboard/configuration.json",@@ -442,11 +446,31 @@ RSpec.describe Admin::DashboardController do{ id: "reports", visible: true },{ id: "highlights", visible: true },{ id: "traffic", visible: false },+ { id: "engagement", visible: false },+ ],+ }++ expect(response.status).to eq(204)+ expect(AdminDashboardSectionConfiguration.visible_section_ids).to eq(%w[reports highlights])+ end++ it "keeps a section's position when it is toggled off" do+ sign_in(admin)++ put "/admin/dashboard/configuration.json",+ params: {+ sections: [+ { id: "highlights", visible: false },+ { id: "reports", visible: true },+ { id: "traffic", visible: true },+ { id: "engagement", visible: true },],}expect(response.status).to eq(204)- expect(SiteSetting.admin_dashboard_sections).to eq("reports|highlights")+ expect(AdminDashboardSectionConfiguration.sections.first).to eq(+ { id: "highlights", visible: false },+ )endit "drops unknown section ids silently" do@@ -458,7 +482,9 @@ RSpec.describe Admin::DashboardController do}expect(response.status).to eq(204)- expect(SiteSetting.admin_dashboard_sections).to eq("highlights")+ expect(AdminDashboardSectionConfiguration.sections.map { |s| s[:id] }).to match_array(+ %w[highlights reports traffic engagement],+ )endit "coerces non-boolean visible values" do@@ -470,28 +496,13 @@ RSpec.describe Admin::DashboardController do{ id: "highlights", visible: "true" },{ id: "reports", visible: "false" },{ id: "engagement", visible: "1" },+ { id: "traffic", visible: "0" },],}- expect(SiteSetting.admin_dashboard_sections).to eq("highlights|engagement")- end-- it "treats an empty sections array as hide-everything" do- sign_in(admin)-- put "/admin/dashboard/configuration.json", params: { sections: [] }-- expect(response.status).to eq(204)- expect(SiteSetting.admin_dashboard_sections).to eq("")- end-- it "treats a missing sections key the same as an empty array" do- sign_in(admin)-- put "/admin/dashboard/configuration.json"-- expect(response.status).to eq(204)- expect(SiteSetting.admin_dashboard_sections).to eq("")+ expect(AdminDashboardSectionConfiguration.visible_section_ids).to eq(+ %w[highlights engagement],+ )endit "returns 404 for moderators" do@@ -519,7 +530,12 @@ RSpec.describe Admin::DashboardController doput "/admin/dashboard/configuration.json",params: {- sections: [{ id: "highlights", visible: true }],+ sections: [+ { id: "highlights", visible: true },+ { id: "reports", visible: false },+ { id: "traffic", visible: false },+ { id: "engagement", visible: false },+ ],}sign_in(moderator)diff --git a/spec/services/admin_dashboard_section_configuration_spec.rb b/spec/services/admin_dashboard_section_configuration_spec.rbindex 330cf3649fd..29716dcade7 100644--- a/spec/services/admin_dashboard_section_configuration_spec.rb+++ b/spec/services/admin_dashboard_section_configuration_spec.rb@@ -3,88 +3,93 @@describe AdminDashboardSectionConfiguration dofab!(:admin)- before { SiteSetting.admin_dashboard_sections = "highlights|reports|traffic|engagement" }-- describe "the site setting" do- it "rejects unknown ids at the validator level" do- expect { SiteSetting.admin_dashboard_sections = "frobnitz|highlights" }.to raise_error(- Discourse::InvalidParameters,+ describe ".sections" do+ it "returns every seeded section, all visible, in canonical order by default" do+ expect(described_class.sections).to eq(+ [+ { id: "highlights", visible: true },+ { id: "reports", visible: true },+ { id: "traffic", visible: true },+ { id: "engagement", visible: true },+ ],)end- end-- describe ".visible_section_ids" do- it "returns ids in stored order" do- SiteSetting.admin_dashboard_sections = "reports|highlights|engagement"- expect(described_class.visible_section_ids).to eq(%w[reports highlights engagement])- end-- it "dedupes repeated ids, keeping the first occurrence" do- SiteSetting.admin_dashboard_sections = "highlights|highlights|reports"- expect(described_class.visible_section_ids).to eq(%w[highlights reports])- end-- it "returns an empty array when the setting is empty" do- SiteSetting.admin_dashboard_sections = ""- expect(described_class.visible_section_ids).to eq([])- end- it "falls back to canonical defaults when the raw value is non-empty but unusable" do- SiteSetting.stubs(:admin_dashboard_sections).returns("|||")- expect(described_class.visible_section_ids).to eq(described_class::KNOWN_SECTIONS)- end+ it "keeps each section's stored position, independent of visibility" do+ described_class.update(+ [+ { id: "highlights", visible: false },+ { id: "reports", visible: true },+ { id: "traffic", visible: true },+ { id: "engagement", visible: true },+ ],+ actor: admin,+ )- it "falls back to canonical defaults when every id is unknown" do- SiteSetting.stubs(:admin_dashboard_sections).returns("frobnitz|wibble")- expect(described_class.visible_section_ids).to eq(described_class::KNOWN_SECTIONS)+ expect(described_class.sections).to eq(+ [+ { id: "highlights", visible: false },+ { id: "reports", visible: true },+ { id: "traffic", visible: true },+ { id: "engagement", visible: true },+ ],+ )endend- describe ".sections" do- it "returns visible sections first, then hidden in canonical order" do- SiteSetting.admin_dashboard_sections = "reports|engagement"-- expect(described_class.sections).to eq(+ describe ".visible_section_ids" do+ it "returns only visible sections, in stored order" do+ described_class.update([{ id: "reports", visible: true },- { id: "engagement", visible: true },{ id: "highlights", visible: false },+ { id: "engagement", visible: true },{ id: "traffic", visible: false },],+ actor: admin,)- end-- it "marks every known section visible: false when the setting is empty" do- SiteSetting.admin_dashboard_sections = ""- expect(described_class.sections.map { |s| s[:visible] }.uniq).to eq([false])- expect(described_class.sections.map { |s| s[:id] }).to match_array(- described_class::KNOWN_SECTIONS,- )+ expect(described_class.visible_section_ids).to eq(%w[reports engagement])endenddescribe ".update" do- it "persists the visible ids as a pipe-delimited string" do+ it "round-trips order and visibility" dodescribed_class.update(- [{ id: "reports", visible: true }, { id: "highlights", visible: true }],+ [+ { id: "engagement", visible: true },+ { id: "highlights", visible: false },+ { id: "reports", visible: true },+ { id: "traffic", visible: true },+ ],actor: admin,)- expect(SiteSetting.admin_dashboard_sections).to eq("reports|highlights")+ expect(described_class.sections).to eq(+ [+ { id: "engagement", visible: true },+ { id: "highlights", visible: false },+ { id: "reports", visible: true },+ { id: "traffic", visible: true },+ ],+ )end- it "drops sections with visible: false" do- described_class.update(+ it "toggling a section off then on leaves its position unchanged" do+ off = described_class.sections.map { |s| s[:id] == "reports" ? s.merge(visible: false) : s }+ described_class.update(off, actor: admin)++ on = described_class.sections.map { |s| s[:id] == "reports" ? s.merge(visible: true) : s }+ described_class.update(on, actor: admin)++ expect(described_class.sections).to eq([{ id: "highlights", visible: true },- { id: "traffic", visible: false },{ id: "reports", visible: true },+ { id: "traffic", visible: true },+ { id: "engagement", visible: true },],- actor: admin,)-- expect(SiteSetting.admin_dashboard_sections).to eq("highlights|reports")endit "coerces non-boolean visible values" do@@ -93,11 +98,12 @@ describe AdminDashboardSectionConfiguration do{ id: "highlights", visible: "true" },{ id: "reports", visible: "false" },{ id: "engagement", visible: 1 },+ { id: "traffic", visible: 0 },],actor: admin,)- expect(SiteSetting.admin_dashboard_sections).to eq("highlights|engagement")+ expect(described_class.visible_section_ids).to eq(%w[highlights engagement])endit "drops unknown section ids" do@@ -106,37 +112,49 @@ describe AdminDashboardSectionConfiguration doactor: admin,)- expect(SiteSetting.admin_dashboard_sections).to eq("highlights")+ expect(described_class.sections.map { |s| s[:id] }).to match_array(+ described_class::KNOWN_SECTIONS,+ )end- it "accepts string keys as well as symbols" do- described_class.update(- [{ "id" => "highlights", "visible" => true }, { "id" => "reports", "visible" => true }],- actor: admin,- )+ it "appends known sections missing from the input, preserving their visibility" do+ described_class.update([{ id: "reports", visible: false }], actor: admin)- expect(SiteSetting.admin_dashboard_sections).to eq("highlights|reports")+ sections = described_class.sections+ expect(sections.first).to eq({ id: "reports", visible: false })+ expect(sections.map { |s| s[:id] }).to match_array(described_class::KNOWN_SECTIONS)end- it "writes empty string when all sections are hidden" do+ it "accepts string keys as well as symbols" dodescribed_class.update(- [{ id: "highlights", visible: false }, { id: "reports", visible: false }],+ [{ "id" => "reports", "visible" => true }, { "id" => "highlights", "visible" => false }],actor: admin,)- expect(SiteSetting.admin_dashboard_sections).to eq("")+ expect(described_class.sections.first(2)).to eq(+ [{ id: "reports", visible: true }, { id: "highlights", visible: false }],+ )+ end++ it "logs a custom staff action" do+ expect {+ described_class.update([{ id: "highlights", visible: false }], actor: admin)+ }.to change { UserHistory.where(custom_type: "update_dashboard_sections").count }.by(1)endit "returns the new sections snapshot" doresult =described_class.update(- [{ id: "engagement", visible: true }, { id: "highlights", visible: true }],+ [+ { id: "engagement", visible: true },+ { id: "highlights", visible: true },+ { id: "reports", visible: true },+ { id: "traffic", visible: true },+ ],actor: admin,)- expect(result.first(2)).to eq(- [{ id: "engagement", visible: true }, { id: "highlights", visible: true }],- )+ expect(result.first).to eq({ id: "engagement", visible: true })endendenddiff --git a/spec/system/admin_dashboard_configure_spec.rb b/spec/system/admin_dashboard_configure_spec.rbindex 980ff32016c..a8226cdc212 100644--- a/spec/system/admin_dashboard_configure_spec.rb+++ b/spec/system/admin_dashboard_configure_spec.rb@@ -6,30 +6,25 @@ describe "Admin Dashboard Configure menu" dolet(:dashboard) { PageObjects::Pages::AdminDashboard.new }- before do- SiteSetting.dashboard_improvements = true- SiteSetting.admin_dashboard_sections = "highlights|reports|traffic|engagement"- end+ before { SiteSetting.dashboard_improvements = true }context "as an admin" dobefore { sign_in(admin) }- it "toggles section visibility from the Configure menu, persists across reload, and shows an empty state when everything is hidden" do+ it "applies toggles immediately, persists across reload, and shows an empty state when everything is hidden" dodashboard.visitexpect(dashboard).to have_configure_button%w[highlights reports traffic engagement].each { |id| expect(dashboard).to have_section(id) }- dashboard- .open_configure_menu- .toggle_section("traffic")- .toggle_section("engagement")- .close_configure_menu+ dashboard.open_configure_menu.toggle_section("traffic").toggle_section("engagement")+ # changes apply right away, while the menu is still openexpect(dashboard).to have_section("highlights")expect(dashboard).to have_section("reports")expect(dashboard).to have_no_section("traffic")expect(dashboard).to have_no_section("engagement")+ dashboard.close_configure_menupage.refreshexpect(dashboard).to have_section("highlights")@@ -37,20 +32,31 @@ describe "Admin Dashboard Configure menu" doexpect(dashboard).to have_no_section("traffic")expect(dashboard).to have_no_section("engagement")- dashboard- .open_configure_menu- .toggle_section("highlights")- .toggle_section("reports")- .close_configure_menu+ dashboard.open_configure_menu.toggle_section("highlights").toggle_section("reports")expect(dashboard).to have_empty_stateend+ it "keeps a section's position when it is toggled off and back on" do+ dashboard.visit+ expect(dashboard.section_ids_in_order).to eq(%w[highlights reports traffic engagement])++ dashboard.open_configure_menu.toggle_section("highlights")+ expect(dashboard).to have_no_section("highlights")++ dashboard.toggle_section("highlights")++ # it reappears in its original slot, not pushed to the bottom+ expect(dashboard).to have_first_section("highlights")+ expect(dashboard.section_ids_in_order).to eq(%w[highlights reports traffic engagement])+ end+it "reorders sections via the arrow buttons on mobile", mobile: true dodashboard.visit- dashboard.open_configure_menu.move_section_up("reports").close_configure_menu+ dashboard.open_configure_menu.move_section_up("reports")+ # reorder applies immediately, without closing the menuexpect(dashboard).to have_first_section("reports")expect(dashboard.section_ids_in_order.first(2)).to eq(%w[reports highlights])end@@ -65,7 +71,15 @@ describe "Admin Dashboard Configure menu" doendit "sees the same configured layout an admin set up" do- SiteSetting.admin_dashboard_sections = "highlights|reports"+ AdminDashboardSectionConfiguration.update(+ [+ { id: "highlights", visible: true },+ { id: "reports", visible: true },+ { id: "traffic", visible: false },+ { id: "engagement", visible: false },+ ],+ actor: admin,+ )dashboard.visitexpect(dashboard).to have_section("highlights")diff --git a/spec/system/admin_dashboard_redesign/reports_section_spec.rb b/spec/system/admin_dashboard_redesign/reports_section_spec.rbindex 2ce3e49fa4f..ac1381875fe 100644--- a/spec/system/admin_dashboard_redesign/reports_section_spec.rb+++ b/spec/system/admin_dashboard_redesign/reports_section_spec.rb@@ -8,7 +8,15 @@ describe "Admin Dashboard Redesign | Reports section" dobefore doSiteSetting.dashboard_improvements = true- SiteSetting.admin_dashboard_sections = "reports"+ AdminDashboardSectionConfiguration.update(+ [+ { id: "reports", visible: true },+ { id: "highlights", visible: false },+ { id: "traffic", visible: false },+ { id: "engagement", visible: false },+ ],+ actor: current_user,+ )AdminDashboardReport.delete_allsign_in(current_user)enddiff --git a/spec/system/admin_dashboard_redesign/site_traffic_section_spec.rb b/spec/system/admin_dashboard_redesign/site_traffic_section_spec.rbindex 4bbc0c505cd..3ef3c83151c 100644--- a/spec/system/admin_dashboard_redesign/site_traffic_section_spec.rb+++ b/spec/system/admin_dashboard_redesign/site_traffic_section_spec.rb@@ -7,7 +7,15 @@ describe "Admin Dashboard Redesign | Site Traffic section" dobefore doSiteSetting.dashboard_improvements = true- SiteSetting.admin_dashboard_sections = "traffic"+ AdminDashboardSectionConfiguration.update(+ [+ { id: "traffic", visible: true },+ { id: "highlights", visible: false },+ { id: "reports", visible: false },+ { id: "engagement", visible: false },+ ],+ actor: current_user,+ )SiteSetting.use_legacy_pageviews = falseSiteSetting.embed_topics_list = truesign_in(current_user)