A platform for community discussion. Free, open, simple.
FEATURE: Add Search section to the redesigned admin dashboard (#40779)
Alan Guo Xiang Tand01a79a0dae3
diff --git a/app/controllers/admin/dashboard_controller.rb b/app/controllers/admin/dashboard_controller.rbindex 1ea541dc6e2..bac67a10310 100644--- a/app/controllers/admin/dashboard_controller.rb+++ b/app/controllers/admin/dashboard_controller.rb@@ -154,6 +154,8 @@ class Admin::DashboardController < Admin::StaffController)when "reports"AdminDashboard::Reports::Section.build(guardian: guardian)+ when "search"+ AdminDashboardSearch.build(start_date: params[:start_date], end_date: params[:end_date])endenddiff --git a/app/services/admin_dashboard_search.rb b/app/services/admin_dashboard_search.rbnew file mode 100644index 00000000000..379f9cc10c5--- /dev/null+++ b/app/services/admin_dashboard_search.rb@@ -0,0 +1,200 @@+# frozen_string_literal: true++class AdminDashboardSearch+ DEFAULT_RANGE_DAYS = 30+ TOP_TERMS_LIMIT = 10+ ALARM_THRESHOLD_PERCENT = 10+ POOR_MATCH_MAX_CTR_PERCENT = 20+ TRENDING_PERIODS_BY_MAX_DAYS = {+ 7 => "weekly",+ 31 => "monthly",+ 92 => "quarterly",+ 366 => "yearly",+ }.freeze+ private_constant :DEFAULT_RANGE_DAYS,+ :TOP_TERMS_LIMIT,+ :ALARM_THRESHOLD_PERCENT,+ :POOR_MATCH_MAX_CTR_PERCENT,+ :TRENDING_PERIODS_BY_MAX_DAYS++ def self.build(start_date:, end_date:)+ new(start_date: start_date, end_date: end_date).build+ end++ def initialize(start_date:, end_date:)+ @start_date = parse_date(start_date) || default_start_date+ @end_date = parse_date(end_date)&.end_of_day || Time.zone.now.end_of_day++ if @start_date.to_date > @end_date.to_date+ @start_date = default_start_date+ @end_date = Time.zone.now.end_of_day+ end+ end++ def build+ return { logging_enabled: false } if !SiteSetting.log_search_queries++ current = window_stats(window_start: start_date, window_end: end_date)+ prior = window_stats(window_start: prior_start_date, window_end: prior_end_date)+ kpis = build_kpis(current: current, prior: prior)++ {+ logging_enabled: true,+ headline_state: headline_state(current: current, kpis: kpis),+ kpis: kpis,+ trending: trending,+ trending_period: trending_period,+ content_gaps: content_gaps,+ }+ end++ private++ attr_reader :start_date, :end_date++ def build_kpis(current:, prior:)+ {+ total_searches: total_searches_kpi(current: current, prior: prior),+ no_result_rate: no_result_rate_kpi(current: current, prior: prior),+ }+ end++ def total_searches_kpi(current:, prior:)+ kpi = { value: current[:total] }++ if current[:total].positive? && prior[:total].positive?+ change = formatted_change((current[:total] - prior[:total]) * 100.0 / prior[:total])+ kpi[:percent_change] = change if change+ end++ kpi+ end++ def no_result_rate_kpi(current:, prior:)+ return { value: nil, exceeds_threshold: false } if current[:total].zero?++ kpi = {+ value: no_result_rate(current).round,+ exceeds_threshold: current[:no_match] * 100 > current[:total] * ALARM_THRESHOLD_PERCENT,+ }++ if prior[:total].positive?+ change = formatted_change(no_result_rate(current) - no_result_rate(prior))+ kpi[:point_change] = change if change+ end++ kpi+ end++ def no_result_rate(stats)+ stats[:no_match] * 100.0 / stats[:total]+ end++ def formatted_change(value)+ rounded = value.abs < 1 ? value.round(1) : value.round+ rounded.zero? ? nil : rounded+ end++ def headline_state(current:, kpis:)+ return "no_signal" if current[:total].zero?+ return "content_gaps" if kpis[:no_result_rate][:exceeds_threshold]+ return "rate_climbing" if kpis[:no_result_rate][:point_change].to_f.positive?+ return "shrinking" if kpis[:total_searches][:percent_change].to_f.negative?++ "healthy"+ end++ def trending+ rows = DB.query(<<~SQL, window_start: start_date, window_end: end_date, limit: TOP_TERMS_LIMIT)+ SELECT lower(term) AS term,+ COUNT(*) AS searches,+ SUM(CASE WHEN search_result_id IS NOT NULL THEN 1 ELSE 0 END) AS clicks+ FROM search_logs+ WHERE created_at >= :window_start AND created_at <= :window_end+ GROUP BY lower(term)+ ORDER BY searches DESC, clicks DESC, term ASC+ LIMIT :limit+ SQL++ rows.map { |row| { term: row.term, searches: row.searches } }+ end++ def trending_period+ TRENDING_PERIODS_BY_MAX_DAYS.each do |max_days, period|+ return period if selected_day_count <= max_days+ end++ "all"+ end++ def content_gaps+ rows =+ DB.query(+ <<~SQL,+ SELECT lower(term) AS term,+ COUNT(*) AS searches,+ SUM(CASE WHEN search_result_id IS NOT NULL THEN 1 ELSE 0 END) AS clicks+ FROM search_logs+ WHERE created_at >= :window_start AND created_at <= :window_end+ GROUP BY lower(term)+ HAVING SUM(CASE WHEN search_result_id IS NOT NULL THEN 1 ELSE 0 END) * 100 <=+ COUNT(*) * :max_ctr_percent+ ORDER BY searches DESC, term ASC+ LIMIT :limit+ SQL+ window_start: start_date,+ window_end: end_date,+ max_ctr_percent: POOR_MATCH_MAX_CTR_PERCENT,+ limit: TOP_TERMS_LIMIT,+ )++ rows.map do |row|+ {+ term: row.term,+ searches: row.searches,+ status: row.clicks.zero? ? "no_match" : "poor_match",+ }+ end+ end++ def window_stats(window_start:, window_end:)+ row = DB.query(<<~SQL, window_start: window_start, window_end: window_end).first+ WITH term_stats AS (+ SELECT COUNT(*) AS searches,+ SUM(CASE WHEN search_result_id IS NOT NULL THEN 1 ELSE 0 END) AS clicks+ FROM search_logs+ WHERE created_at >= :window_start AND created_at <= :window_end+ GROUP BY lower(term)+ )+ SELECT COALESCE(SUM(searches), 0)::bigint AS total,+ COALESCE(SUM(CASE WHEN clicks = 0 THEN searches ELSE 0 END), 0)::bigint AS no_match+ FROM term_stats+ SQL++ { total: row.total, no_match: row.no_match }+ end++ def parse_date(value)+ return nil if value.blank?++ Time.zone.parse(value.to_s)&.beginning_of_day+ rescue ArgumentError, TypeError+ nil+ end++ def default_start_date+ (DEFAULT_RANGE_DAYS - 1).days.ago.beginning_of_day+ end++ def prior_start_date+ (start_date.to_date - selected_day_count).beginning_of_day+ end++ def prior_end_date+ (start_date.to_date - 1).end_of_day+ end++ def selected_day_count+ (end_date.to_date - start_date.to_date).to_i + 1+ end+enddiff --git a/app/services/admin_dashboard_section_configuration.rb b/app/services/admin_dashboard_section_configuration.rbindex 8bb0ded5d7e..1118057fc7e 100644--- a/app/services/admin_dashboard_section_configuration.rb+++ b/app/services/admin_dashboard_section_configuration.rb@@ -1,16 +1,22 @@# frozen_string_literal: trueclass AdminDashboardSectionConfiguration- KNOWN_SECTIONS = %w[highlights reports traffic engagement].freeze+ KNOWN_SECTIONS = %w[highlights reports traffic engagement search].freezedef self.sectionsAdminDashboardSection- .where(section_id: KNOWN_SECTIONS)+ .where(section_id: enabled_sections).order(:position).pluck(:section_id, :visible).map { |id, visible| { id:, visible: } }end+ def self.enabled_sections+ return KNOWN_SECTIONS if SiteSetting.admin_dashboard_search_section_enabled+ KNOWN_SECTIONS - %w[search]+ end+ private_class_method :enabled_sections+def self.visible_section_idssections.select { |s| s[:visible] }.map { |s| s[:id] }enddiff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex a1d2aba0a88..30ab7828456 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -7028,6 +7028,54 @@ en:new_signups: "New sign-ups"dau_mau: "DAU / MAU stickiness"daily_engaged_users: "Daily engaged"+ search:+ title: "Search"+ fetch_error: "Couldn't load search data. Try refreshing the page."+ logging_disabled: 'Search logging is disabled, so no search data is being collected. Enable <a href="%{basePath}/admin/site_settings/category/all_results?filter=log%20search%20queries">log search queries</a> to start collecting it.'+ logging_disabled_moderator: "Search logging is disabled, so no search data is being collected. Ask an admin to enable log search queries to start collecting it."+ count_headline:+ last_7_days:+ one: "Members ran %{formatted_count} on-site search in the last 7 days"+ other: "Members ran %{formatted_count} on-site searches in the last 7 days"+ last_30_days:+ one: "Members ran %{formatted_count} on-site search in the last 30 days"+ other: "Members ran %{formatted_count} on-site searches in the last 30 days"+ last_3_months:+ one: "Members ran %{formatted_count} on-site search in the last 3 months"+ other: "Members ran %{formatted_count} on-site searches in the last 3 months"+ selected_period:+ one: "Members ran %{formatted_count} on-site search in the selected period"+ other: "Members ran %{formatted_count} on-site searches in the selected period"+ headline:+ no_signal_title: "Not enough search activity to summarise yet."+ no_signal: "Pick a longer date range or come back once members have searched more."+ content_gaps: "More than 10% of searches ended without a click this period. Review the content gaps below to see what's missing."+ rate_climbing: "The no-result rate is climbing compared with the previous period. Keep an eye on the content gaps below."+ shrinking: "Search volume is down compared with the previous period, while most searches still lead to content."+ healthy: "Members keep finding what they search for, and search volume is steady or growing."+ kpi:+ total_searches:+ label: "Total searches"+ tooltip: "The number of searches performed in your community."+ no_result_rate:+ label: "No-result rate"+ tooltip: "The percentage of searches where members didn't click any result (0% CTR). This indicates that members may be searching for content your community doesn't have."+ table:+ term: "Search term"+ searches: "Searches"+ status: "Status"+ trending:+ title: "Trending searches"+ tooltip: "The most popular search terms."+ empty: "No searches in this period."+ content_gaps:+ title: "Content gaps"+ empty: "No content gaps in this period."+ badge:+ no_match: "No match"+ no_match_tooltip: "Search terms with a 0% click-through rate (CTR)."+ poor_match: "Poor match"+ poor_match_tooltip: "Search terms with a click-through rate (CTR) between 1-20%."reports_section:description: "Pin standard reports or Data Explorer queries to track what matters to your community."add: "Add report"diff --git a/config/locales/server.en.yml b/config/locales/server.en.ymlindex c669a4a0af0..5bd5d3f5407 100644--- a/config/locales/server.en.yml+++ b/config/locales/server.en.yml@@ -2906,6 +2906,7 @@ en:reporting_improvements: "Improvements to navigation, design, and usability for Discourse's admin reports."granular_anonymous_and_logged_in_groups_permissions: "Makes group-based site setting permissions treat 'everyone' as 'all logged-in users', and enables the new 'anonymous_users' and 'logged_in_users' pseudogroups so admins can explicitly target anonymous visitors and authenticated users."dashboard_improvements: "Enables the redesigned admin dashboard that lets you pin custom reports and includes improved site traffic, engagement, and other analytics tied to community success and value."+ admin_dashboard_search_section_enabled: "Show the Search section on the redesigned admin dashboard while it is in testing."errors:invalid_css_color: "Invalid color. Enter a color name or hex value."diff --git a/config/site_settings.yml b/config/site_settings.ymlindex ae7a34339c7..98cc0144c09 100644--- a/config/site_settings.yml+++ b/config/site_settings.yml@@ -4590,3 +4590,6 @@ experimental:admin_dashboard_reports_seeded:default: falsehidden: true+ admin_dashboard_search_section_enabled:+ default: false+ hidden: truediff --git a/frontend/discourse/admin/components/dashboard/search.gjs b/frontend/discourse/admin/components/dashboard/search.gjsnew file mode 100644index 00000000000..b989704ef32--- /dev/null+++ b/frontend/discourse/admin/components/dashboard/search.gjs@@ -0,0 +1,345 @@+import Component from "@glimmer/component";+import { hash } from "@ember/helper";+import { LinkTo } from "@ember/routing";+import { service } from "@ember/service";+import { trustHTML } from "@ember/template";+import DashboardSection from "discourse/admin/components/dashboard/section";+import DTooltip from "discourse/float-kit/components/d-tooltip";+import dBasePath from "discourse/ui-kit/helpers/d-base-path";+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";+import I18n, { i18n } from "discourse-i18n";++const COUNT_HEADLINE_KEYS = {+ last_7_days: "admin.dashboard.sections.search.count_headline.last_7_days",+ last_30_days: "admin.dashboard.sections.search.count_headline.last_30_days",+ last_3_months: "admin.dashboard.sections.search.count_headline.last_3_months",+};++function formatCount(value) {+ return I18n.toNumber(value, { precision: 0 });+}++function formatDelta(value) {+ const abs = Math.abs(value);++ if (abs > 0 && abs < 1) {+ const sign = value > 0 ? "+" : "-";+ return `${sign}${I18n.toNumber(abs, { precision: 1 })}%`;+ }++ const rounded = Math.round(value);+ const sign = rounded > 0 ? "+" : "";+ return `${sign}${I18n.toNumber(rounded, { precision: 0 })}%`;+}++function badgeLabel(status) {+ return i18n(`admin.dashboard.sections.search.content_gaps.badge.${status}`);+}++function badgeTooltip(status) {+ return i18n(+ `admin.dashboard.sections.search.content_gaps.badge.${status}_tooltip`+ );+}++export default class DashboardSearch extends Component {+ @service currentUser;++ get loggingDisabled() {+ return this.args.search?.logging_enabled === false;+ }++ get isNoSignal() {+ return this.args.search.headline_state === "no_signal";+ }++ get headlineTitle() {+ if (this.isNoSignal) {+ return i18n("admin.dashboard.sections.search.headline.no_signal_title");+ }++ const count = this.args.search.kpis.total_searches.value;+ const key =+ COUNT_HEADLINE_KEYS[this.args.period] ??+ "admin.dashboard.sections.search.count_headline.selected_period";++ return i18n(key, { count, formatted_count: formatCount(count) });+ }++ get headlineSummary() {+ return i18n(+ `admin.dashboard.sections.search.headline.${this.args.search.headline_state}`+ );+ }++ get totalSearchesValue() {+ return formatCount(this.args.search.kpis.total_searches.value);+ }++ get totalSearchesDelta() {+ const change = this.args.search.kpis.total_searches.percent_change;++ if (change == null) {+ return null;+ }++ return {+ text: formatDelta(change),+ className: change > 0 ? "--pos" : "--neg",+ };+ }++ get noResultRateValue() {+ const value = this.args.search.kpis.no_result_rate.value;+ return value == null ? "—" : `${formatCount(value)}%`;+ }++ get noResultRateDelta() {+ const change = this.args.search.kpis.no_result_rate.point_change;++ if (change == null) {+ return null;+ }++ return {+ text: formatDelta(change),+ className: change > 0 ? "--neg" : "--pos",+ };+ }++ get rateExceedsThreshold() {+ return this.args.search.kpis.no_result_rate.exceeds_threshold;+ }++ get trendingTermPeriod() {+ if (this.args.period === "custom") {+ return "all";+ }++ return this.args.search.trending_period;+ }++ <template>+ <DashboardSection+ @title={{i18n "admin.dashboard.sections.search.title"}}+ @startDate={{@startDate}}+ @endDate={{@endDate}}+ ...attributes+ >+ {{#if @fetchError}}+ <div class="db-section__error" role="alert">+ {{i18n "admin.dashboard.sections.search.fetch_error"}}+ </div>+ {{else if this.loggingDisabled}}+ <p class="db-section__callout">+ {{#if this.currentUser.admin}}+ {{trustHTML+ (i18n+ "admin.dashboard.sections.search.logging_disabled"+ basePath=(dBasePath)+ )+ }}+ {{else}}+ {{i18n+ "admin.dashboard.sections.search.logging_disabled_moderator"+ }}+ {{/if}}+ </p>+ {{else if @search}}+ <div class="db-section__subheader">+ <div class="db-section__subintro">+ <h3>{{this.headlineTitle}}</h3>+ <p>{{this.headlineSummary}}</p>+ </div>++ <div class="db-section__metrics">+ <div+ class="db-section__metric"+ data-test-search-kpi="total_searches"+ >+ <div class="db-section__metric-number">+ {{this.totalSearchesValue}}+ </div>+ <div class="db-section__metric-label">+ {{i18n+ "admin.dashboard.sections.search.kpi.total_searches.label"+ }}+ <DTooltip+ class="db-section__info"+ @identifier="search-total-searches-tooltip"+ @icon="far-circle-question"+ >+ <:content>+ {{i18n+ "admin.dashboard.sections.search.kpi.total_searches.tooltip"+ }}+ </:content>+ </DTooltip>+ </div>+ {{#if this.totalSearchesDelta}}+ <div+ class="db-delta {{this.totalSearchesDelta.className}}"+ >{{this.totalSearchesDelta.text}}</div>+ {{/if}}+ </div>++ <div+ class="db-section__metric"+ data-test-search-kpi="no_result_rate"+ >+ <div+ class={{dConcatClass+ "db-section__metric-number"+ (if this.rateExceedsThreshold "--neg")+ }}+ >+ {{this.noResultRateValue}}+ </div>+ <div class="db-section__metric-label">+ {{i18n+ "admin.dashboard.sections.search.kpi.no_result_rate.label"+ }}+ <DTooltip+ class="db-section__info"+ @identifier="search-no-result-rate-tooltip"+ @icon="far-circle-question"+ >+ <:content>+ {{i18n+ "admin.dashboard.sections.search.kpi.no_result_rate.tooltip"+ }}+ </:content>+ </DTooltip>+ </div>+ {{#if this.noResultRateDelta}}+ <div+ class="db-delta {{this.noResultRateDelta.className}}"+ >{{this.noResultRateDelta.text}}</div>+ {{/if}}+ </div>+ </div>+ </div>++ <div class="db-section__row">+ <div class="db-section__row-block">+ <h3 class="db-section__row-block-title">+ {{i18n "admin.dashboard.sections.search.trending.title"}}+ <DTooltip+ class="db-section__info"+ @identifier="search-trending-tooltip"+ @icon="far-circle-question"+ >+ <:content>+ {{i18n "admin.dashboard.sections.search.trending.tooltip"}}+ </:content>+ </DTooltip>+ </h3>+ <div class="db-activity">+ {{#if @search.trending.length}}+ <div class="db-activity__table-scroll-container">+ <table class="db-activity-table">+ <thead>+ <tr>+ <th>{{i18n+ "admin.dashboard.sections.search.table.term"+ }}</th>+ <th class="db-activity-table__col-number">+ {{i18n+ "admin.dashboard.sections.search.table.searches"+ }}+ </th>+ </tr>+ </thead>+ <tbody>+ {{#each @search.trending as |row|}}+ <tr data-test-search-term-row>+ <td>+ <LinkTo+ @route="adminSearchLogs.term"+ @query={{hash+ term=row.term+ period=this.trendingTermPeriod+ }}+ >+ {{row.term}}+ </LinkTo>+ </td>+ <td class="db-activity-table__cell-number">+ {{formatCount row.searches}}+ </td>+ </tr>+ {{/each}}+ </tbody>+ </table>+ </div>+ {{else}}+ <p class="db-activity__empty">+ {{i18n "admin.dashboard.sections.search.trending.empty"}}+ </p>+ {{/if}}+ </div>+ </div>++ <div class="db-section__row-block">+ <h3 class="db-section__row-block-title">+ {{i18n "admin.dashboard.sections.search.content_gaps.title"}}+ </h3>+ <div class="db-activity">+ {{#if @search.content_gaps.length}}+ <div class="db-activity__table-scroll-container">+ <table class="db-activity-table">+ <thead>+ <tr>+ <th>{{i18n+ "admin.dashboard.sections.search.table.term"+ }}</th>+ <th>{{i18n+ "admin.dashboard.sections.search.table.status"+ }}</th>+ <th class="db-activity-table__col-number">+ {{i18n+ "admin.dashboard.sections.search.table.searches"+ }}+ </th>+ </tr>+ </thead>+ <tbody>+ {{#each @search.content_gaps as |row|}}+ <tr data-test-search-term-row>+ <td>+ <LinkTo+ @route="full-page-search"+ @query={{hash q=row.term}}+ >+ {{row.term}}+ </LinkTo>+ </td>+ <td>+ <DTooltip+ class="db-pill --neg"+ @identifier="search-gap-badge-tooltip"+ >+ <:trigger>{{badgeLabel row.status}}</:trigger>+ <:content>{{badgeTooltip row.status}}</:content>+ </DTooltip>+ </td>+ <td class="db-activity-table__cell-number">+ {{formatCount row.searches}}+ </td>+ </tr>+ {{/each}}+ </tbody>+ </table>+ </div>+ {{else}}+ <p class="db-activity__empty">+ {{i18n "admin.dashboard.sections.search.content_gaps.empty"}}+ </p>+ {{/if}}+ </div>+ </div>+ </div>+ {{/if}}+ </DashboardSection>+ </template>+}diff --git a/frontend/discourse/admin/components/redesigned-admin-dashboard.gjs b/frontend/discourse/admin/components/redesigned-admin-dashboard.gjsindex 0636a429077..f51d42694fa 100644--- a/frontend/discourse/admin/components/redesigned-admin-dashboard.gjs+++ b/frontend/discourse/admin/components/redesigned-admin-dashboard.gjs@@ -6,6 +6,7 @@ import DashboardDateRange from "discourse/admin/components/dashboard/date-range"import DashboardEngagement from "discourse/admin/components/dashboard/engagement";import DashboardHighlights from "discourse/admin/components/dashboard/highlights";import DashboardReports from "discourse/admin/components/dashboard/reports";+import DashboardSearch from "discourse/admin/components/dashboard/search";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";@@ -97,6 +98,17 @@ export default class RedesignedAdminDashboard extends Component {@startDate={{@loadedSections.startDate}}@endDate={{@loadedSections.endDate}}/>+ {{else if (eq section.id "search")}}+ <DashboardSearch+ class={{concat "--" section.id}}+ data-section-id={{section.id}}+ @search={{section.data}}+ @period={{@loadedSections.period}}+ @loading={{@loadingSections}}+ @fetchError={{@sectionsFetchError}}+ @startDate={{@loadedSections.startDate}}+ @endDate={{@loadedSections.endDate}}+ />{{/if}}{{/each}}diff --git a/lib/svg_sprite.rb b/lib/svg_sprite.rbindex 4756f74ddda..b218e412a8d 100644--- a/lib/svg_sprite.rb+++ b/lib/svg_sprite.rb@@ -145,6 +145,7 @@ module SvgSpritefar-chart-barfar-circlefar-circle-dot+ far-circle-questionfar-clipboardfar-clockfar-commentdiff --git a/spec/fabricators/search_log_fabricator.rb b/spec/fabricators/search_log_fabricator.rbindex d9d8aa701f1..a7a5b12e36c 100644--- a/spec/fabricators/search_log_fabricator.rb+++ b/spec/fabricators/search_log_fabricator.rb@@ -5,3 +5,8 @@ Fabricator(:search_log) dosearch_type SearchLog.search_types[:header]ip_address "127.0.0.1"end++Fabricator(:clicked_search_log, from: :search_log) do+ search_result_id 1+ search_result_type SearchLog.search_result_types[:topic]+enddiff --git a/spec/lib/seed_data/admin_dashboard_sections_spec.rb b/spec/lib/seed_data/admin_dashboard_sections_spec.rbindex 9fde371f7ad..032d24f6180 100644--- a/spec/lib/seed_data/admin_dashboard_sections_spec.rb+++ b/spec/lib/seed_data/admin_dashboard_sections_spec.rb@@ -15,6 +15,7 @@ describe SeedData::AdminDashboardSections do["reports", 1, true],["traffic", 2, true],["engagement", 3, true],+ ["search", 4, true],],)enddiff --git a/spec/requests/admin/dashboard_controller_spec.rb b/spec/requests/admin/dashboard_controller_spec.rbindex e9f0b2d599a..fede6e70587 100644--- a/spec/requests/admin/dashboard_controller_spec.rb+++ b/spec/requests/admin/dashboard_controller_spec.rb@@ -8,6 +8,7 @@ RSpec.describe Admin::DashboardController dobefore doAdminDashboardData.stubs(:fetch_cached_stats).returns(reports: [])Jobs::CallDiscourseHub.any_instance.stubs(:execute).returns(true)+ SiteSetting.admin_dashboard_search_section_enabled = trueenddef configure_dashboard_sections(visible_ids)@@ -256,6 +257,49 @@ RSpec.describe Admin::DashboardController doendend+ context "with search_data" do+ let(:search_data) { section_payloads["search"]&.dig("data") }++ it "omits the search section while admin_dashboard_search_section_enabled is disabled" do+ SiteSetting.admin_dashboard_search_section_enabled = false+ configure_dashboard_sections(%w[search highlights])++ get "/admin/dashboard.json"++ expect(response.status).to eq(200)+ expect(section_payloads.keys).not_to include("search")+ configuration_ids =+ response.parsed_body["configuration"]["sections"].map { |section| section["id"] }+ expect(configuration_ids).not_to include("search")+ end++ it "returns the search payload for the selected dates" do+ configure_dashboard_sections(%w[search])+ Fabricate(:clicked_search_log, term: "ruby", created_at: "2026-05-02 10:00")+ Fabricate(:search_log, term: "ruby", created_at: "2026-05-02 11:00")++ get "/admin/dashboard.json", params: { start_date: "2026-05-01", end_date: "2026-05-07" }++ expect(response.status).to eq(200)+ expect(search_data).to eq(+ "logging_enabled" => true,+ "headline_state" => "healthy",+ "kpis" => {+ "total_searches" => {+ "value" => 2,+ },+ "no_result_rate" => {+ "value" => 0,+ "exceeds_threshold" => false,+ },+ },+ "trending" => [{ "term" => "ruby", "searches" => 2 }],+ "trending_period" => "weekly",+ "content_gaps" => [],+ )+ end+ end+it "is omitted when enabled for no one" doSiteSetting.dashboard_improvements = false@@ -317,6 +361,7 @@ RSpec.describe Admin::DashboardController do"reports","traffic","engagement",+ "search",)expect(section_payloads.dig("highlights", "data")).to be_presentexpect(section_payloads.dig("traffic", "data")).to be_present@@ -433,7 +478,7 @@ RSpec.describe Admin::DashboardController doexpect(configuration).to be_presentids = configuration["sections"].map { |s| s["id"] }- expect(ids).to match_array(%w[highlights reports traffic engagement])+ expect(ids).to match_array(%w[highlights reports traffic engagement search])visible = configuration["sections"].select { |s| s["visible"] }.map { |s| s["id"] }expect(visible).to eq(%w[highlights reports])@@ -473,6 +518,7 @@ RSpec.describe Admin::DashboardController do{ id: "highlights", visible: true },{ id: "traffic", visible: false },{ id: "engagement", visible: false },+ { id: "search", visible: false },],}@@ -509,7 +555,7 @@ RSpec.describe Admin::DashboardController doexpect(response.status).to eq(204)expect(AdminDashboardSectionConfiguration.sections.map { |s| s[:id] }).to match_array(- %w[highlights reports traffic engagement],+ %w[highlights reports traffic engagement search],)end@@ -523,6 +569,7 @@ RSpec.describe Admin::DashboardController do{ id: "reports", visible: "false" },{ id: "engagement", visible: "1" },{ id: "traffic", visible: "0" },+ { id: "search", visible: "false" },],}@@ -561,6 +608,7 @@ RSpec.describe Admin::DashboardController do{ id: "reports", visible: false },{ id: "traffic", visible: false },{ id: "engagement", visible: false },+ { id: "search", visible: false },],}diff --git a/spec/services/admin_dashboard_search_spec.rb b/spec/services/admin_dashboard_search_spec.rbnew file mode 100644index 00000000000..33eda046983--- /dev/null+++ b/spec/services/admin_dashboard_search_spec.rb@@ -0,0 +1,310 @@+# frozen_string_literal: true++RSpec.describe AdminDashboardSearch do+ before { freeze_time(Time.zone.local(2026, 5, 14, 12, 0, 0)) }++ describe ".build" do+ it "returns KPIs, trending terms, and content gaps for the selected dates" do+ Fabricate.times(3, :clicked_search_log, term: "ruby", created_at: "2026-05-02 10:00")+ Fabricate.times(3, :search_log, term: "ruby", created_at: "2026-05-02 11:00")++ Fabricate(:clicked_search_log, term: "markdown tables", created_at: "2026-05-03 10:00")++ Fabricate.times(+ 4,+ :search_log,+ term: "markdown tables",+ search_type: SearchLog.search_types[:full_page],+ created_at: "2026-05-03 11:00",+ )++ Fabricate.times(4, :search_log, term: "discobot", created_at: "2026-05-04 10:00")++ Fabricate.times(2, :clicked_search_log, term: "zeta", created_at: "2026-05-04 11:00")+ Fabricate.times(2, :search_log, term: "zeta", created_at: "2026-05-04 12:00")++ Fabricate.times(5, :clicked_search_log, term: "ruby", created_at: "2026-04-26 10:00")+ Fabricate.times(5, :search_log, term: "ghost", created_at: "2026-04-26 11:00")++ expect(described_class.build(start_date: "2026-05-01", end_date: "2026-05-07")).to eq(+ logging_enabled: true,+ headline_state: "content_gaps",+ kpis: {+ total_searches: {+ value: 19,+ percent_change: 90,+ },+ no_result_rate: {+ value: 21,+ point_change: -29,+ exceeds_threshold: true,+ },+ },+ trending: [+ { term: "ruby", searches: 6 },+ { term: "markdown tables", searches: 5 },+ { term: "zeta", searches: 4 },+ { term: "discobot", searches: 4 },+ ],+ trending_period: "weekly",+ content_gaps: [+ { term: "markdown tables", searches: 5, status: "poor_match" },+ { term: "discobot", searches: 4, status: "no_match" },+ ],+ )+ end++ it "buckets terms by exact CTR boundaries" do+ Fabricate(:clicked_search_log, term: "tiny-ctr", created_at: "2026-05-02 10:00")+ Fabricate.times(100, :search_log, term: "tiny-ctr", created_at: "2026-05-02 11:00")++ Fabricate.times(5, :clicked_search_log, term: "just-over", created_at: "2026-05-03 10:00")+ Fabricate.times(19, :search_log, term: "just-over", created_at: "2026-05-03 11:00")++ Fabricate(:clicked_search_log, term: "exact-twenty", created_at: "2026-05-04 10:00")+ Fabricate.times(4, :search_log, term: "exact-twenty", created_at: "2026-05-04 11:00")++ Fabricate.times(3, :search_log, term: "zero-clicks", created_at: "2026-05-05 10:00")+ Fabricate.times(3, :search_log, term: "alpha-zero", created_at: "2026-05-05 11:00")++ expect(described_class.build(start_date: "2026-05-01", end_date: "2026-05-07")).to eq(+ logging_enabled: true,+ headline_state: "healthy",+ kpis: {+ total_searches: {+ value: 136,+ },+ no_result_rate: {+ value: 4,+ exceeds_threshold: false,+ },+ },+ trending: [+ { term: "tiny-ctr", searches: 101 },+ { term: "just-over", searches: 24 },+ { term: "exact-twenty", searches: 5 },+ { term: "alpha-zero", searches: 3 },+ { term: "zero-clicks", searches: 3 },+ ],+ trending_period: "weekly",+ content_gaps: [+ { term: "tiny-ctr", searches: 101, status: "poor_match" },+ { term: "exact-twenty", searches: 5, status: "poor_match" },+ { term: "alpha-zero", searches: 3, status: "no_match" },+ { term: "zero-clicks", searches: 3, status: "no_match" },+ ],+ )+ end++ it "caps trending and content gaps at the top 10 terms" do+ (1..11).each do |index|+ Fabricate(:search_log, term: format("gap-%02d", index), created_at: "2026-05-02 10:00")+ end++ expect(described_class.build(start_date: "2026-05-01", end_date: "2026-05-07")).to eq(+ logging_enabled: true,+ headline_state: "content_gaps",+ kpis: {+ total_searches: {+ value: 11,+ },+ no_result_rate: {+ value: 100,+ exceeds_threshold: true,+ },+ },+ trending: (1..10).map { |index| { term: format("gap-%02d", index), searches: 1 } },+ trending_period: "weekly",+ content_gaps:+ (1..10).map do |index|+ { term: format("gap-%02d", index), searches: 1, status: "no_match" }+ end,+ )+ end++ it "picks the headline state from the rate and volume signals" do+ Fabricate(:search_log, term: "ghost", created_at: "2026-05-02 10:00")+ Fabricate.times(11, :clicked_search_log, term: "ruby", created_at: "2026-05-02 11:00")+ Fabricate.times(12, :clicked_search_log, term: "ruby", created_at: "2026-04-26 10:00")++ Fabricate.times(4, :clicked_search_log, term: "ruby", created_at: "2026-04-02 10:00")+ Fabricate.times(10, :clicked_search_log, term: "ruby", created_at: "2026-03-27 10:00")++ Fabricate.times(12, :clicked_search_log, term: "ruby", created_at: "2026-03-02 10:00")+ Fabricate.times(10, :clicked_search_log, term: "ruby", created_at: "2026-02-24 10:00")++ expect(+ described_class.build(start_date: "2026-05-01", end_date: "2026-05-07")[:headline_state],+ ).to eq("rate_climbing")++ expect(+ described_class.build(start_date: "2026-04-01", end_date: "2026-04-07")[:headline_state],+ ).to eq("shrinking")++ expect(+ described_class.build(start_date: "2026-03-01", end_date: "2026-03-07")[:headline_state],+ ).to eq("healthy")+ end++ it "resolves overlapping headline states by priority" do+ Fabricate.times(3, :search_log, term: "ghost", created_at: "2026-02-02 10:00")+ Fabricate.times(7, :clicked_search_log, term: "ruby", created_at: "2026-02-02 11:00")+ Fabricate.times(10, :clicked_search_log, term: "ruby", created_at: "2026-01-27 10:00")++ Fabricate(:search_log, term: "ghost", created_at: "2026-01-02 10:00")+ Fabricate.times(9, :clicked_search_log, term: "ruby", created_at: "2026-01-02 11:00")+ Fabricate.times(20, :clicked_search_log, term: "ruby", created_at: "2025-12-27 10:00")++ expect(+ described_class.build(start_date: "2026-02-01", end_date: "2026-02-07")[:headline_state],+ ).to eq("content_gaps")++ expect(+ described_class.build(start_date: "2026-01-01", end_date: "2026-01-07")[:headline_state],+ ).to eq("rate_climbing")+ end++ it "omits deltas when the prior window has no searches" do+ Fabricate.times(2, :clicked_search_log, term: "ruby", created_at: "2026-05-02 10:00")++ expect(described_class.build(start_date: "2026-05-01", end_date: "2026-05-07")[:kpis]).to eq(+ total_searches: {+ value: 2,+ },+ no_result_rate: {+ value: 0,+ exceeds_threshold: false,+ },+ )+ end++ it "omits deltas and rates when the current window has no searches" do+ Fabricate.times(2, :search_log, term: "ruby", created_at: "2026-04-26 10:00")++ expect(described_class.build(start_date: "2026-05-01", end_date: "2026-05-07")).to eq(+ logging_enabled: true,+ headline_state: "no_signal",+ kpis: {+ total_searches: {+ value: 0,+ },+ no_result_rate: {+ value: nil,+ exceeds_threshold: false,+ },+ },+ trending: [],+ trending_period: "weekly",+ content_gaps: [],+ )+ end++ it "omits deltas when nothing changed between the windows" do+ Fabricate.times(5, :clicked_search_log, term: "ruby", created_at: "2026-05-02 10:00")+ Fabricate.times(5, :clicked_search_log, term: "ruby", created_at: "2026-04-26 10:00")++ expect(described_class.build(start_date: "2026-05-01", end_date: "2026-05-07")[:kpis]).to eq(+ total_searches: {+ value: 5,+ },+ no_result_rate: {+ value: 0,+ exceeds_threshold: false,+ },+ )+ end++ it "reports the rate delta in percentage points, not relative change" do+ Fabricate(:search_log, term: "ghost", created_at: "2026-05-02 10:00")+ Fabricate.times(3, :clicked_search_log, term: "ruby", created_at: "2026-05-02 11:00")++ Fabricate(:search_log, term: "ghost", created_at: "2026-04-26 10:00")+ Fabricate.times(9, :clicked_search_log, term: "ruby", created_at: "2026-04-26 11:00")++ expect(described_class.build(start_date: "2026-05-01", end_date: "2026-05-07")[:kpis]).to eq(+ total_searches: {+ value: 4,+ percent_change: -60,+ },+ no_result_rate: {+ value: 25,+ point_change: 15,+ exceeds_threshold: true,+ },+ )+ end++ it "treats a rate of exactly 10% as within the threshold" do+ Fabricate(:search_log, term: "ghost", created_at: "2026-05-02 10:00")+ Fabricate.times(9, :clicked_search_log, term: "ruby", created_at: "2026-05-02 11:00")++ expect(+ described_class.build(start_date: "2026-05-01", end_date: "2026-05-07")[:kpis][+ :no_result_rate+ ],+ ).to eq(value: 10, exceeds_threshold: false)+ end++ it "flags a rate just above 10% even when the display rounds to 10%" do+ Fabricate.times(5, :search_log, term: "ghost", created_at: "2026-05-02 10:00")+ Fabricate.times(44, :clicked_search_log, term: "ruby", created_at: "2026-05-02 11:00")++ expect(+ described_class.build(start_date: "2026-05-01", end_date: "2026-05-07")[:kpis][+ :no_result_rate+ ],+ ).to eq(value: 10, exceeds_threshold: true)+ end++ it "maps the window length to the per-term report period" do+ {+ %w[2026-05-08 2026-05-14] => "weekly",+ %w[2026-05-07 2026-05-14] => "monthly",+ %w[2026-04-14 2026-05-14] => "monthly",+ %w[2026-04-13 2026-05-14] => "quarterly",+ %w[2026-02-12 2026-05-14] => "quarterly",+ %w[2026-02-11 2026-05-14] => "yearly",+ %w[2025-05-14 2026-05-14] => "yearly",+ %w[2025-05-13 2026-05-14] => "all",+ }.each do |(start_date, end_date), period|+ expect(+ described_class.build(start_date: start_date, end_date: end_date)[:trending_period],+ ).to eq(period)+ end+ end++ it "falls back to the default 30-day window for missing, malformed, or inverted dates" do+ Fabricate(:search_log, term: "inside-window", created_at: "2026-04-16 10:00")+ Fabricate(:search_log, term: "outside-window", created_at: "2026-04-13 10:00")++ [+ described_class.build(start_date: nil, end_date: nil),+ described_class.build(start_date: "not-a-date", end_date: "also-not-a-date"),+ described_class.build(start_date: "2026-05-10", end_date: "2026-05-01"),+ ].each do |response|+ expect(response[:kpis][:total_searches][:value]).to eq(1)+ expect(response[:trending]).to eq([{ term: "inside-window", searches: 1 }])+ end+ end++ it "includes searches at the window start boundary in every list" do+ Fabricate(:search_log, term: "boundary", created_at: "2026-05-01 00:00:00")++ response = described_class.build(start_date: "2026-05-01", end_date: "2026-05-07")++ expect(response[:kpis][:total_searches][:value]).to eq(1)+ expect(response[:trending]).to eq([{ term: "boundary", searches: 1 }])+ expect(response[:content_gaps]).to eq([{ term: "boundary", searches: 1, status: "no_match" }])+ end++ it "returns only the logging flag when search logging is disabled" do+ SiteSetting.log_search_queries = false++ Fabricate(:search_log, term: "ruby", created_at: "2026-05-02 10:00")++ expect(described_class.build(start_date: "2026-05-01", end_date: "2026-05-07")).to eq(+ logging_enabled: false,+ )+ end+ end+enddiff --git a/spec/services/admin_dashboard_section_configuration_spec.rb b/spec/services/admin_dashboard_section_configuration_spec.rbindex 29716dcade7..871b99aff4e 100644--- a/spec/services/admin_dashboard_section_configuration_spec.rb+++ b/spec/services/admin_dashboard_section_configuration_spec.rb@@ -3,7 +3,22 @@describe AdminDashboardSectionConfiguration dofab!(:admin)+ before { SiteSetting.admin_dashboard_search_section_enabled = true }+describe ".sections" do+ it "omits the search section while admin_dashboard_search_section_enabled is disabled" do+ SiteSetting.admin_dashboard_search_section_enabled = false++ expect(described_class.sections).to eq(+ [+ { id: "highlights", visible: true },+ { id: "reports", visible: true },+ { id: "traffic", visible: true },+ { id: "engagement", visible: true },+ ],+ )+ end+it "returns every seeded section, all visible, in canonical order by default" doexpect(described_class.sections).to eq([@@ -11,6 +26,7 @@ describe AdminDashboardSectionConfiguration do{ id: "reports", visible: true },{ id: "traffic", visible: true },{ id: "engagement", visible: true },+ { id: "search", visible: true },],)end@@ -32,6 +48,7 @@ describe AdminDashboardSectionConfiguration do{ id: "reports", visible: true },{ id: "traffic", visible: true },{ id: "engagement", visible: true },+ { id: "search", visible: true },],)end@@ -45,6 +62,7 @@ describe AdminDashboardSectionConfiguration do{ id: "highlights", visible: false },{ id: "engagement", visible: true },{ id: "traffic", visible: false },+ { id: "search", visible: false },],actor: admin,)@@ -71,6 +89,7 @@ describe AdminDashboardSectionConfiguration do{ id: "highlights", visible: false },{ id: "reports", visible: true },{ id: "traffic", visible: true },+ { id: "search", visible: true },],)end@@ -88,6 +107,7 @@ describe AdminDashboardSectionConfiguration do{ id: "reports", visible: true },{ id: "traffic", visible: true },{ id: "engagement", visible: true },+ { id: "search", visible: true },],)end@@ -99,6 +119,7 @@ describe AdminDashboardSectionConfiguration do{ id: "reports", visible: "false" },{ id: "engagement", visible: 1 },{ id: "traffic", visible: 0 },+ { id: "search", visible: "f" },],actor: admin,)diff --git a/spec/system/admin_dashboard_configure_spec.rb b/spec/system/admin_dashboard_configure_spec.rbindex a8226cdc212..1e98defcbb9 100644--- a/spec/system/admin_dashboard_configure_spec.rb+++ b/spec/system/admin_dashboard_configure_spec.rb@@ -6,7 +6,10 @@ describe "Admin Dashboard Configure menu" dolet(:dashboard) { PageObjects::Pages::AdminDashboard.new }- before { SiteSetting.dashboard_improvements = true }+ before do+ SiteSetting.dashboard_improvements = true+ SiteSetting.admin_dashboard_search_section_enabled = true+ endcontext "as an admin" dobefore { sign_in(admin) }@@ -14,13 +17,16 @@ describe "Admin Dashboard Configure menu" doit "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) }+ %w[highlights reports traffic engagement search].each do |id|+ expect(dashboard).to have_section(id)+ enddashboard.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_section("search")expect(dashboard).to have_no_section("traffic")expect(dashboard).to have_no_section("engagement")@@ -29,17 +35,22 @@ describe "Admin Dashboard Configure menu" doexpect(dashboard).to have_section("highlights")expect(dashboard).to have_section("reports")+ expect(dashboard).to have_section("search")expect(dashboard).to have_no_section("traffic")expect(dashboard).to have_no_section("engagement")- dashboard.open_configure_menu.toggle_section("highlights").toggle_section("reports")+ dashboard+ .open_configure_menu+ .toggle_section("highlights")+ .toggle_section("reports")+ .toggle_section("search")expect(dashboard).to have_empty_stateendit "keeps a section's position when it is toggled off and back on" dodashboard.visit- expect(dashboard.section_ids_in_order).to eq(%w[highlights reports traffic engagement])+ expect(dashboard.section_ids_in_order).to eq(%w[highlights reports traffic engagement search])dashboard.open_configure_menu.toggle_section("highlights")expect(dashboard).to have_no_section("highlights")@@ -48,7 +59,7 @@ describe "Admin Dashboard Configure menu" do# it reappears in its original slot, not pushed to the bottomexpect(dashboard).to have_first_section("highlights")- expect(dashboard.section_ids_in_order).to eq(%w[highlights reports traffic engagement])+ expect(dashboard.section_ids_in_order).to eq(%w[highlights reports traffic engagement search])endit "reorders sections via the arrow buttons on mobile", mobile: true dodiff --git a/spec/system/admin_dashboard_redesign/search_section_spec.rb b/spec/system/admin_dashboard_redesign/search_section_spec.rbnew file mode 100644index 00000000000..928acde06e7--- /dev/null+++ b/spec/system/admin_dashboard_redesign/search_section_spec.rb@@ -0,0 +1,214 @@+# frozen_string_literal: true++describe "Admin Dashboard Redesign | Search section" do+ fab!(:current_user, :admin)+ fab!(:moderator)++ let(:dashboard) { PageObjects::Pages::AdminDashboard.new }++ before do+ SiteSetting.dashboard_improvements = true+ SiteSetting.admin_dashboard_search_section_enabled = true+ AdminDashboardSectionConfiguration.update(+ [+ { id: "search", visible: true },+ { id: "highlights", visible: false },+ { id: "reports", visible: false },+ { id: "traffic", visible: false },+ { id: "engagement", visible: false },+ ],+ actor: current_user,+ )+ sign_in(current_user)+ end++ it "lets staff review search health, inspect tooltips, and drill into terms",+ time: Time.zone.local(2026, 5, 14, 12, 0, 0) do+ Fabricate.times(15, :clicked_search_log, term: "ruby", created_at: "2026-05-10 10:00")+ Fabricate.times(10, :search_log, term: "ruby", created_at: "2026-05-10 11:00")+ Fabricate.times(5, :search_log, term: "ruby", created_at: "2026-04-20 10:00")++ Fabricate.times(2, :clicked_search_log, term: "markdown tables", created_at: "2026-04-20 11:00")++ Fabricate.times(13, :search_log, term: "markdown tables", created_at: "2026-04-20 12:00")+ Fabricate.times(3, :search_log, term: "markdown tables", created_at: "2026-05-03 10:00")++ Fabricate.times(2, :search_log, term: "discobot", created_at: "2026-05-10 12:00")++ Fabricate.times(20, :clicked_search_log, term: "ruby", created_at: "2026-03-20 10:00")+ Fabricate.times(20, :search_log, term: "ruby", created_at: "2026-03-20 11:00")++ dashboard.visit+ expect(dashboard).to have_section("search")++ search = dashboard.search++ expect(search).to have_headline(+ "Members ran 50 on-site searches in the last 30 days",+ "The no-result rate is climbing compared with the previous period. " \+ "Keep an eye on the content gaps below.",+ )++ expect(search).to have_total_searches_kpi("50", improving_delta: "+25%")+ expect(search).to have_no_result_rate_kpi("4%", worsening_delta: "+4%")++ search.hover_total_searches_tooltip+ expect(search).to have_total_searches_tooltip(+ "The number of searches performed in your community.",+ )++ search.hover_no_result_rate_tooltip+ expect(search).to have_no_result_rate_tooltip(+ "The percentage of searches where members didn't click any result (0% CTR). " \+ "This indicates that members may be searching for content your community doesn't have.",+ )++ search.hover_trending_tooltip+ expect(search).to have_trending_tooltip("The most popular search terms.")++ expect(search).to have_trending_rows(+ [+ { term: "ruby", searches: 30 },+ { term: "markdown tables", searches: 18 },+ { term: "discobot", searches: 2 },+ ],+ )++ expect(search).to have_content_gap_rows(+ [+ { term: "markdown tables", searches: 18, badge: "Poor match" },+ { term: "discobot", searches: 2, badge: "No match" },+ ],+ )++ search.hover_content_gap_badge("markdown tables")+ expect(search).to have_content_gap_badge_tooltip(+ "Search terms with a click-through rate (CTR) between 1-20%.",+ )++ search.hover_content_gap_badge("discobot")+ expect(search).to have_content_gap_badge_tooltip(+ "Search terms with a 0% click-through rate (CTR).",+ )++ dashboard.select_preset("last_7_days")++ expect(search).to have_headline(+ "Members ran 27 on-site searches in the last 7 days",+ "Members keep finding what they search for, and search volume is steady or growing.",+ )++ expect(search).to have_total_searches_kpi("27", improving_delta: "+800%")+ expect(search).to have_no_result_rate_kpi("7%", improving_delta: "-93%")++ search.click_trending_term("ruby")++ expect(page).to have_current_path("/admin/logs/search_logs/term?period=weekly&term=ruby")++ dashboard.visit+ dashboard.select_preset("last_3_months")++ expect(dashboard.search).to have_headline(+ "Members ran 90 on-site searches in the last 3 months",+ "Members keep finding what they search for, and search volume is steady or growing.",+ )++ dashboard.search.click_content_gap_term("discobot")++ expect(page).to have_current_path("/search?q=discobot")+ end++ it "alerts staff when the no-result rate crosses the threshold",+ time: Time.zone.local(2026, 5, 14, 12, 0, 0) do+ Fabricate.times(5, :search_log, term: "ghost", created_at: "2026-05-10 10:00")+ Fabricate.times(5, :clicked_search_log, term: "ruby", created_at: "2026-05-10 11:00")++ dashboard.visit+ search = dashboard.search++ expect(search).to have_headline(+ "Members ran 10 on-site searches in the last 30 days",+ "More than 10% of searches ended without a click this period. " \+ "Review the content gaps below to see what's missing.",+ )+ expect(search).to have_total_searches_kpi("10")+ expect(search).to have_alert_no_result_rate_kpi("50%")+ end++ it "shows staff a graceful empty state when no searches were logged",+ time: Time.zone.local(2026, 5, 14, 12, 0, 0) do+ dashboard.visit+ search = dashboard.search++ expect(search).to have_headline(+ "Not enough search activity to summarise yet.",+ "Pick a longer date range or come back once members have searched more.",+ )+ expect(search).to have_total_searches_kpi("0")+ expect(search).to have_no_result_rate_kpi("—")+ expect(search).to have_no_kpi_deltas+ expect(search).to have_trending_empty_state("No searches in this period.")+ expect(search).to have_content_gaps_empty_state("No content gaps in this period.")+ end++ it "tells staff when search logging is disabled instead of showing zeros",+ time: Time.zone.local(2026, 5, 14, 12, 0, 0) do+ SiteSetting.log_search_queries = false++ dashboard.visit+ search = dashboard.search++ expect(search).to have_logging_disabled_notice(+ "Search logging is disabled, so no search data is being collected. " \+ "Enable log search queries to start collecting it.",+ )+ expect(search).to have_no_kpis+ end++ it "asks moderators to contact an admin when search logging is disabled",+ time: Time.zone.local(2026, 5, 14, 12, 0, 0) do+ SiteSetting.log_search_queries = false+ sign_in(moderator)++ dashboard.visit++ expect(dashboard.search).to have_moderator_logging_disabled_notice(+ "Search logging is disabled, so no search data is being collected. " \+ "Ask an admin to enable log search queries to start collecting it.",+ )+ end++ it "shows staff search activity for a selected custom date range",+ time: Time.zone.local(2026, 5, 14, 12, 0, 0) do+ Fabricate(:clicked_search_log, term: "ruby", created_at: "2026-05-02 10:00")+ Fabricate.times(2, :search_log, term: "ruby", created_at: "2026-05-02 11:00")++ Fabricate.times(5, :search_log, term: "ruby", created_at: "2026-04-30 10:00")++ Fabricate(:search_log, term: "solo", created_at: "2026-04-25 10:00")++ dashboard.visit_with_query(range: "custom", start_date: "2026-05-01", end_date: "2026-05-03")+ search = dashboard.search++ expect(search).to have_headline(+ "Members ran 3 on-site searches in the selected period",+ "Search volume is down compared with the previous period, " \+ "while most searches still lead to content.",+ )+ expect(search).to have_total_searches_kpi("3", worsening_delta: "-40%")+ expect(search).to have_no_result_rate_kpi("0%", improving_delta: "-100%")+ expect(search).to have_trending_rows([{ term: "ruby", searches: 3 }])++ search.click_trending_term("ruby")++ expect(page).to have_current_path("/admin/logs/search_logs/term?period=all&term=ruby")++ dashboard.visit_with_query(range: "custom", start_date: "2026-04-25", end_date: "2026-04-25")++ expect(search).to have_headline(+ "Members ran 1 on-site search in the selected period",+ "More than 10% of searches ended without a click this period. " \+ "Review the content gaps below to see what's missing.",+ )+ end+enddiff --git a/spec/system/page_objects/components/admin_dashboard_search.rb b/spec/system/page_objects/components/admin_dashboard_search.rbnew file mode 100644index 00000000000..b8f7f1eb289--- /dev/null+++ b/spec/system/page_objects/components/admin_dashboard_search.rb@@ -0,0 +1,162 @@+# frozen_string_literal: true++module PageObjects+ module Components+ class AdminDashboardSearch < PageObjects::Components::Base+ SECTION = "[data-section-id='search']"++ BADGE_SELECTORS = { "No match" => ".db-pill.--neg", "Poor match" => ".db-pill.--neg" }.freeze++ def has_headline?(title, summary)+ has_css?("#{SECTION} .db-section__subintro h3", exact_text: title) &&+ has_css?("#{SECTION} .db-section__subintro p", exact_text: summary)+ end++ def has_total_searches_kpi?(value, improving_delta: nil, worsening_delta: nil)+ has_kpi?(+ "total_searches",+ value,+ improving_delta: improving_delta,+ worsening_delta: worsening_delta,+ )+ end++ def has_no_result_rate_kpi?(value, improving_delta: nil, worsening_delta: nil)+ has_kpi?(+ "no_result_rate",+ value,+ improving_delta: improving_delta,+ worsening_delta: worsening_delta,+ ) && has_no_css?("#{kpi_selector("no_result_rate")} .db-section__metric-number.--neg")+ end++ def has_alert_no_result_rate_kpi?(value)+ has_css?(+ "#{kpi_selector("no_result_rate")} .db-section__metric-number.--neg",+ exact_text: value,+ )+ end++ def has_no_kpi_deltas?+ has_no_css?("#{SECTION} .db-delta")+ end++ def has_no_kpis?+ has_no_css?("#{SECTION} .db-section__metric")+ end++ def hover_total_searches_tooltip+ find("#{SECTION} [data-trigger][data-identifier='search-total-searches-tooltip']").hover+ self+ end++ def has_total_searches_tooltip?(text)+ Tooltips.new("search-total-searches-tooltip").present?(text: text)+ end++ def hover_no_result_rate_tooltip+ find("#{SECTION} [data-trigger][data-identifier='search-no-result-rate-tooltip']").hover+ self+ end++ def has_no_result_rate_tooltip?(text)+ Tooltips.new("search-no-result-rate-tooltip").present?(text: text)+ end++ def hover_trending_tooltip+ find("#{SECTION} [data-trigger][data-identifier='search-trending-tooltip']").hover+ self+ end++ def has_trending_tooltip?(text)+ Tooltips.new("search-trending-tooltip").present?(text: text)+ end++ def has_trending_rows?(rows)+ within_block("Trending searches") do+ next false unless has_css?("[data-test-search-term-row]", count: rows.size)++ rows.each_with_index.all? do |row, index|+ nth = "[data-test-search-term-row]:nth-child(#{index + 1})"+ has_css?("#{nth} a", text: row[:term]) && has_css?(nth, text: row[:searches].to_s)+ end+ end+ end++ def click_trending_term(term)+ within_block("Trending searches") do+ find("[data-test-search-term-row] a", text: term).click+ end+ end++ def has_trending_empty_state?(message)+ within_block("Trending searches") { has_text?(message) }+ end++ def has_content_gap_rows?(rows)+ within_block("Content gaps") do+ next false unless has_css?("[data-test-search-term-row]", count: rows.size)++ rows.each_with_index.all? do |row, index|+ nth = "[data-test-search-term-row]:nth-child(#{index + 1})"+ has_css?("#{nth} a", text: row[:term]) && has_css?(nth, text: row[:searches].to_s) &&+ has_css?("#{nth} #{BADGE_SELECTORS.fetch(row[:badge])}", text: row[:badge])+ end+ end+ end++ def click_content_gap_term(term)+ within_block("Content gaps") { find("[data-test-search-term-row] a", text: term).click }+ end++ def hover_content_gap_badge(term)+ within_block("Content gaps") do+ find("[data-test-search-term-row]", text: term).find(".db-pill").hover+ end+ self+ end++ def has_content_gap_badge_tooltip?(text)+ Tooltips.new("search-gap-badge-tooltip").present?(text: text)+ end++ def has_content_gaps_empty_state?(message)+ within_block("Content gaps") { has_text?(message) }+ end++ def has_logging_disabled_notice?(message)+ has_css?(SECTION, text: message) &&+ has_css?(+ "#{SECTION} a[href='/admin/site_settings/category/all_results?filter=log%20search%20queries']",+ text: "log search queries",+ )+ end++ def has_moderator_logging_disabled_notice?(message)+ has_css?(SECTION, text: message) && has_no_css?("#{SECTION} .db-section__callout a")+ end++ private++ def has_kpi?(type, value, improving_delta:, worsening_delta:)+ unless has_css?("#{kpi_selector(type)} .db-section__metric-number", exact_text: value)+ return false+ end+ if improving_delta.nil? && worsening_delta.nil?+ return has_no_css?("#{kpi_selector(type)} .db-delta")+ end++ modifier, text = improving_delta ? ["--pos", improving_delta] : ["--neg", worsening_delta]+ has_css?("#{kpi_selector(type)} .db-delta.#{modifier}", exact_text: text)+ end++ def kpi_selector(type)+ "#{SECTION} [data-test-search-kpi='#{type}']"+ end++ def within_block(title, &block)+ within(find("#{SECTION} .db-section__row-block", text: title), &block)+ end+ end+ end+enddiff --git a/spec/system/page_objects/pages/admin_dashboard.rb b/spec/system/page_objects/pages/admin_dashboard.rbindex 4974a90d837..52f89d54cf5 100644--- a/spec/system/page_objects/pages/admin_dashboard.rb+++ b/spec/system/page_objects/pages/admin_dashboard.rb@@ -97,6 +97,10 @@ module PageObjectsPageObjects::Components::AdminDashboardSiteTraffic.newend+ def search+ PageObjects::Components::AdminDashboardSearch.new+ end+def section_ids_in_orderall(".db-main [data-section-id]").map { |el| el["data-section-id"] }end