A platform for community discussion. Free, open, simple.
FEATURE: Show related items in admin reports (#42958)
Krzysztof Kotlareke20c10c056d2
diff --git a/app/assets/stylesheets/admin/admin_base.scss b/app/assets/stylesheets/admin/admin_base.scssindex 256cc6b54f4..02f71a837ed 100644--- a/app/assets/stylesheets/admin/admin_base.scss+++ b/app/assets/stylesheets/admin/admin_base.scss@@ -1247,6 +1247,7 @@ a.inline-editable-field {@import "admin/admin_report_radar";@import "admin/admin_report_stacked_line_chart";@import "admin/admin_report_table";+@import "admin/admin_report_related_items";@import "admin/admin_report_inline_table";@import "admin/posters_by_member_type_report";@import "admin/admin_section_landing_page";diff --git a/app/assets/stylesheets/admin/admin_report_related_items.scss b/app/assets/stylesheets/admin/admin_report_related_items.scssnew file mode 100644index 00000000000..bcc10cfa21d--- /dev/null+++ b/app/assets/stylesheets/admin/admin_report_related_items.scss@@ -0,0 +1,153 @@+.admin-report-related-items {+ margin-block-start: var(--space-8);++ h2 {+ margin: 0;+ font-size: var(--font-up-2);+ }++ &__description {+ margin-block: var(--space-1) var(--space-4);+ color: var(--token-color-text-subtle);+ }++ &__limit {+ display: block;+ margin-block-start: var(--space-1);+ }++ &__table {+ width: 100%;+ margin: 0;+ table-layout: fixed;+ }++ &__user-cell {+ width: 70%;+ }++ &__timestamp-cell {+ width: 30%;+ text-align: end;+ white-space: nowrap;+ }++ &__user-link {+ display: inline-flex;+ align-items: center;+ gap: var(--space-2);+ max-width: 100%;+ }++ &__avatar {+ flex: none;+ }++ &__user-identity {+ min-width: 0;+ }++ &__username,+ &__name {+ overflow-wrap: anywhere;+ }++ &__username {+ font-weight: var(--token-font-weight-semibold);+ }++ &__name {+ margin-inline-start: var(--space-2);+ color: var(--token-color-text-subtle);+ }+}++.admin-report-table-summary {+ min-height: 0;+ padding: 0;+ border: 1px solid transparent;+ background: transparent;+ box-shadow: none;+ color: inherit;+ font: inherit;+ line-height: inherit;+ text-align: inherit;+ text-decoration-line: underline;+ text-decoration-style: dotted;+ text-underline-offset: 0.2em;++ &:hover,+ &:focus,+ &:active {+ background-color: transparent;+ border-color: transparent;+ box-shadow: none;+ color: inherit;+ outline: none;+ }++ &:focus-visible {+ text-decoration-style: solid;+ text-decoration-thickness: 2px;+ }++ &__content {+ min-width: min(16rem, calc(100dvw - var(--space-8)));+ }++ &__body {+ padding: var(--space-3);+ }++ &__heading {+ margin: 0 0 var(--space-2);+ font-size: var(--font-up-1);+ }++ &__message {+ margin: 0;+ color: var(--token-color-text-subtle);+ }++ &__limit {+ margin: 0 0 var(--space-2);+ color: var(--token-color-text-subtle);+ }++ &__list {+ display: grid;+ gap: var(--space-2);+ margin: 0;+ padding: 0;+ list-style: none;+ }++ &__item {+ min-width: 0;+ }++ &__user-link {+ display: inline-flex;+ align-items: center;+ gap: var(--space-2);+ max-width: 100%;+ overflow-wrap: anywhere;+ }++ &__avatar {+ flex: none;+ }++ &__user-identity {+ min-width: 0;+ }++ &__username {+ font-weight: var(--token-font-weight-semibold);+ }++ &__name {+ margin-inline-start: var(--space-2);+ color: var(--token-color-text-subtle);+ }+}diff --git a/app/controllers/admin/reports_controller.rb b/app/controllers/admin/reports_controller.rbindex d3a6b86ef58..6352254dcca 100644--- a/app/controllers/admin/reports_controller.rb+++ b/app/controllers/admin/reports_controller.rb@@ -102,6 +102,16 @@ class Admin::ReportsController < Admin::StaffControllerfilters = nilfilters = report_params[:filters] if report_params.has_key?(:filters)- { start_date: start_date, end_date: end_date, filters: filters, facets: facets, limit: limit }+ include_related_items =+ ActiveModel::Type::Boolean.new.cast(report_params[:include_related_items])++ {+ start_date: start_date,+ end_date: end_date,+ filters: filters,+ facets: facets,+ limit: limit,+ include_related_items: include_related_items,+ }endenddiff --git a/app/models/concerns/reports/new_contributors.rb b/app/models/concerns/reports/new_contributors.rbindex 4ea8e5cf65f..fb1d8bf4838 100644--- a/app/models/concerns/reports/new_contributors.rb+++ b/app/models/concerns/reports/new_contributors.rb@@ -24,6 +24,33 @@ module Reports::NewContributorsenddata.each { |key, value| report.data << { x: key, y: value } }++ return if !report.include_related_items++ users =+ User+ .real+ .preload(:user_stat)+ .joins(:user_stat)+ .where(+ "user_stats.first_post_created_at > ? AND user_stats.first_post_created_at < ?",+ report.start_date,+ report.end_date,+ )+ .order("user_stats.first_post_created_at DESC")++ report.related_items_totals = { users: users.count }+ users = users.limit(report.limit || Report::RELATED_ITEMS_LIMIT)++ report.related_items = {+ users:+ users.map do |user|+ {+ user: BasicUserSerializer.new(user, scope: report.guardian, root: false).as_json,+ timestamp: user.user_stat.first_post_created_at.iso8601,+ }+ end,+ }endendenddiff --git a/app/models/concerns/reports/signups.rb b/app/models/concerns/reports/signups.rbindex 200d229dfe0..0acef07125d 100644--- a/app/models/concerns/reports/signups.rb+++ b/app/models/concerns/reports/signups.rb@@ -21,6 +21,26 @@ module Reports::Signupselsereport_about report, User.real, :count_by_signup_dateend++ return if !report.include_related_items++ users = User.real.where(created_at: report.start_date..report.end_date)+ users =+ users.joins(:group_users).where(group_users: { group_id: group_filter }) if group_filter+ users = users.order(created_at: :desc)++ report.related_items_totals = { users: users.count }+ users = users.limit(report.limit || Report::RELATED_ITEMS_LIMIT)++ report.related_items = {+ users:+ users.map do |user|+ {+ user: BasicUserSerializer.new(user, scope: report.guardian, root: false).as_json,+ timestamp: user.created_at.iso8601,+ }+ end,+ }endendenddiff --git a/app/models/report.rb b/app/models/report.rbindex 3b154260b05..ce6ba8a90fe 100644--- a/app/models/report.rb+++ b/app/models/report.rb@@ -5,6 +5,8 @@ class Report# and you want to ensure cache is resetSCHEMA_VERSION = 5+ RELATED_ITEMS_LIMIT = 50+FILTERS = %i[namestart_date@@ -44,6 +46,7 @@ class Reporttop_referrers_by_browser_pageviewstop_countries_by_browser_pageviews]+ ADMIN_ONLY_RELATED_ITEMS_REPORTS = %w[new_contributors signups]IP_ADDRESS_REPORTS = %w[suspicious_logins]BROWSER_PAGEVIEW_REPORTS = %w[top_countries_by_browser_pageviews@@ -179,7 +182,10 @@ class Report:default_group_by,:y_axis_title,:current_user,- :guardian+ :guardian,+ :include_related_items,+ :related_items,+ :related_items_totalsdef self.default_days30@@ -315,6 +321,8 @@ class Reportjson[:limit] = limit if limitjson[:default_group_by] = default_group_by if default_group_byjson[:y_axis_title] = y_axis_title if y_axis_title+ json[:related_items] = related_items if related_items+ json[:related_items_totals] = related_items_totals if related_items_totalsif type == "page_view_crawler_reqs"json[:related_report] = Report.find(@@ -326,15 +334,22 @@ class Reportendend- def Report.add_report(name, exclude_from_dashboard: false, &block)+ def Report.add_report(+ name,+ exclude_from_dashboard: false,+ admin_only_related_items: false,+ &block+ )singleton_class.instance_eval { define_method("report_#{name}", &block) }dashboard_excluded_report_types << name.to_s if exclude_from_dashboard+ registered_admin_only_related_items_report_types << name.to_s if admin_only_related_itemsend# Only used for testing.def Report.remove_report(name)singleton_class.instance_eval { remove_method("report_#{name}") }dashboard_excluded_report_types.delete(name.to_s)+ registered_admin_only_related_items_report_types.delete(name.to_s)end# Report types a plugin has marked as not mountable on the customisable@@ -343,8 +358,17 @@ class Report@dashboard_excluded_report_types ||= Set.newend+ def Report.admin_only_related_items_report_types+ ADMIN_ONLY_RELATED_ITEMS_REPORTS.to_set | registered_admin_only_related_items_report_types+ end++ def Report.registered_admin_only_related_items_report_types+ @registered_admin_only_related_items_report_types ||= Set.new+ end+def self._get(type, opts = nil)opts ||= {}+ type = type.to_s# Load the reportreport = Report.new(type)@@ -359,6 +383,9 @@ class Reportreport.current_user = opts[:current_user] if opts[:current_user]report.current_user ||= report.guardian&.userreport.guardian ||= report.current_user&.guardian+ report.include_related_items =+ opts[:include_related_items] &&+ (report.guardian&.is_admin? || !admin_only_related_items_report_types.include?(report.type))report.labels = Report.default_labelsreport.legacy = LEGACY_REPORTS.include?(type)@@ -368,10 +395,14 @@ class Reportdef self.find_cached(type, opts = nil)report = _get(type, opts)+ return if report.include_related_items+Discourse.cache.read(cache_key(report))enddef self.cache(report)+ return if report.include_related_items+duration = report.error == :exception ? 1.minute : 60.minutesDiscourse.cache.write(cache_key(report), report.as_json, expires_in: duration)enddiff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex 56654fb75f1..4f2d9df2ff8 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -6737,6 +6737,24 @@ en:legacy_warning: "This is a legacy report. It will be retired soon. If you need help finding the replacement, contact support."chart:total: "Total: %{count}"+ related_items:+ showing: "Showing the newest %{shown} of %{total}."+ users:+ title: "Users"+ signups:+ description: "New accounts created between %{startDate} and %{endDate}, newest first."+ new_contributors:+ description: "Users who made their first post between %{startDate} and %{endDate}, newest first."+ labels:+ user: "User"+ created_at: "Created at"+ first_post: "First post created at"+ table_summary:+ trigger: "%{count}, show summary for %{date}"+ users_title: "Users on %{date}"+ loading: "Loading summary…"+ empty: "No details are available."+ error: "Couldn't load the summary."config_sections:account:diff --git a/frontend/discourse/admin/components/admin-report-body.gjs b/frontend/discourse/admin/components/admin-report-body.gjsindex d43fd9d12ec..b231db080f6 100644--- a/frontend/discourse/admin/components/admin-report-body.gjs+++ b/frontend/discourse/admin/components/admin-report-body.gjs@@ -1,6 +1,7 @@import { concat, fn } from "@ember/helper";import didUpdate from "@ember/render-modifiers/modifiers/did-update";import AdminReport from "discourse/admin/components/admin-report";+import AdminReportRelatedItems from "discourse/admin/components/admin-report-related-items";import DSegmentedControl from "discourse/components/d-segmented-control";import DTooltip from "discourse/float-kit/components/d-tooltip";import { and } from "discourse/truth-helpers";@@ -171,7 +172,10 @@ export default <template>{{component@report.modeComponent}}{{#if @report.model.relatedReport}}@@ -247,6 +251,15 @@ export default <template></div>{{/if}}</div>+ {{#if (and @report.isChartMode @report.hasRelatedItems)}}+ <AdminReportRelatedItems+ @relatedItems={{@report.model.related_items}}+ @relatedItemsTotals={{@report.model.related_items_totals}}+ @startDate={{@report.startDate}}+ @endDate={{@report.endDate}}+ @type={{@report.model.type}}+ />+ {{/if}}</DConditionalLoadingSection>{{/unless}}</div>diff --git a/frontend/discourse/admin/components/admin-report-related-items.gjs b/frontend/discourse/admin/components/admin-report-related-items.gjsnew file mode 100644index 00000000000..c0edb4b9a5a--- /dev/null+++ b/frontend/discourse/admin/components/admin-report-related-items.gjs@@ -0,0 +1,136 @@+import Component from "@glimmer/component";+import { adminReportRelatedItemsRenderer } from "discourse/admin/lib/admin-report-related-items";+import { userPath } from "discourse/lib/url";+import { formatUsername } from "discourse/lib/utilities";+import dAvatar from "discourse/ui-kit/helpers/d-avatar";+import dFormatDate from "discourse/ui-kit/helpers/d-format-date";+import { i18n } from "discourse-i18n";++export default class AdminReportRelatedItems extends Component {+ get users() {+ return this.args.relatedItems?.users || [];+ }++ get usersTotal() {+ return this.args.relatedItemsTotals?.users || this.users.length;+ }++ get usersAreTruncated() {+ return this.users.length < this.usersTotal;+ }++ get userDescriptionKey() {+ return `admin.reports.related_items.users.${this.args.type}.description`;+ }++ get userTimestampLabelKey() {+ return this.args.type === "new_contributors"+ ? "admin.reports.related_items.labels.first_post"+ : "admin.reports.related_items.labels.created_at";+ }++ get relatedItemsComponent() {+ return adminReportRelatedItemsRenderer(this.args.type)+ ?.relatedItemsComponent;+ }++ get startDate() {+ return moment(this.args.startDate).format(+ i18n("dates.long_with_year_no_time")+ );+ }++ get endDate() {+ return moment(this.args.endDate).format(+ i18n("dates.long_with_year_no_time")+ );+ }++ userProfilePath(user) {+ return userPath(user.username);+ }++ <template>+ {{#if this.users.length}}+ <section class="admin-report-related-items">+ <h2>{{i18n "admin.reports.related_items.users.title"}}</h2>+ <p class="admin-report-related-items__description">+ {{i18n+ this.userDescriptionKey+ startDate=this.startDate+ endDate=this.endDate+ }}+ {{#if this.usersAreTruncated}}+ <span class="admin-report-related-items__limit">+ {{i18n+ "admin.reports.related_items.showing"+ shown=this.users.length+ total=this.usersTotal+ }}+ </span>+ {{/if}}+ </p>++ <table class="table admin-report-related-items__table">+ <thead>+ <tr>+ <th class="admin-report-related-items__user-cell">+ {{i18n "admin.reports.related_items.labels.user"}}+ </th>+ <th class="admin-report-related-items__timestamp-cell">+ {{i18n this.userTimestampLabelKey}}+ </th>+ </tr>+ </thead>+ <tbody>+ {{#each this.users as |item|}}+ <tr>+ <td class="admin-report-related-items__user-cell">+ <a+ class="admin-report-related-items__user-link"+ href={{this.userProfilePath item.user}}+ >+ {{dAvatar+ item.user+ imageSize="small"+ extraClasses="admin-report-related-items__avatar"+ }}+ <span class="admin-report-related-items__user-identity">+ <span class="admin-report-related-items__username">+ {{formatUsername item.user.username}}+ </span>+ {{#if item.user.name}}+ <span class="admin-report-related-items__name">+ {{item.user.name}}+ </span>+ {{/if}}+ </span>+ </a>+ </td>+ <td class="admin-report-related-items__timestamp-cell">+ <time datetime={{item.timestamp}}>+ {{dFormatDate+ item.timestamp+ format="medium"+ leaveAgo="true"+ }}+ </time>+ </td>+ </tr>+ {{/each}}+ </tbody>+ </table>+ </section>+ {{/if}}++ {{#if this.relatedItemsComponent}}+ {{component+ this.relatedItemsComponent+ relatedItems=@relatedItems+ relatedItemsTotals=@relatedItemsTotals+ startDate=@startDate+ endDate=@endDate+ }}+ {{/if}}+ </template>+}diff --git a/frontend/discourse/admin/components/admin-report-table-cell.gjs b/frontend/discourse/admin/components/admin-report-table-cell.gjsindex c18f0e87559..da721057554 100644--- a/frontend/discourse/admin/components/admin-report-table-cell.gjs+++ b/frontend/discourse/admin/components/admin-report-table-cell.gjs@@ -3,6 +3,8 @@ import Component from "@ember/component";import { computed, set } from "@ember/object";import { trustHTML } from "@ember/template";import { tagName } from "@ember-decorators/component";+import AdminReportTableSummary from "discourse/admin/components/admin-report-table-summary";+import { adminReportRelatedItemsRenderer } from "discourse/admin/lib/admin-report-related-items";import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";@tagName("")@@ -50,13 +52,59 @@ export default class AdminReportTableCell extends Component {return this.label.compute(this.data, this.options || {});}+ @computed("hasRelatedItems", "type", "property", "value")+ get hasRelatedItemsSummary() {+ return (+ this.hasRelatedItems &&+ this.type === "number" &&+ this.property === "y" &&+ this.value > 0+ );+ }++ @computed("reportType")+ get relatedItemsRenderer() {+ return adminReportRelatedItemsRenderer(this.reportType);+ }++ @computed("reportType")+ get relatedItemsSummary() {+ return this.relatedItemsRenderer?.tableSummary;+ }+<template><td- title={{this.value}}+ title={{if this.hasRelatedItemsSummary null this.value}}class={{dConcatClass "admin-report-table-cell" this.type this.property}}...attributes>- {{trustHTML this.formattedValue}}+ {{#if this.hasRelatedItemsSummary}}+ {{#if this.relatedItemsRenderer}}+ {{#if this.relatedItemsSummary}}+ <AdminReportTableSummary+ @date={{this.data.x}}+ @formattedValue={{this.formattedValue}}+ @itemComponent={{this.relatedItemsSummary.itemComponent}}+ @itemsKey={{this.relatedItemsSummary.itemsKey}}+ @listClass={{this.relatedItemsSummary.listClass}}+ @reportType={{this.reportType}}+ @reportFilters={{this.reportFilters}}+ @titleKey={{this.relatedItemsSummary.titleKey}}+ />+ {{else}}+ {{trustHTML this.formattedValue}}+ {{/if}}+ {{else}}+ <AdminReportTableSummary+ @date={{this.data.x}}+ @formattedValue={{this.formattedValue}}+ @reportType={{this.reportType}}+ @reportFilters={{this.reportFilters}}+ />+ {{/if}}+ {{else}}+ {{trustHTML this.formattedValue}}+ {{/if}}</td></template>}diff --git a/frontend/discourse/admin/components/admin-report-table-row.gjs b/frontend/discourse/admin/components/admin-report-table-row.gjsindex a914bbd15a4..c5b76df80c3 100644--- a/frontend/discourse/admin/components/admin-report-table-row.gjs+++ b/frontend/discourse/admin/components/admin-report-table-row.gjs@@ -13,7 +13,10 @@ export default class AdminReportTableRow extends Component {<AdminReportTableCell@label={{label}}@data={{this.data}}+ @hasRelatedItems={{@hasRelatedItems}}@options={{this.options}}+ @reportType={{@reportType}}+ @reportFilters={{@reportFilters}}/>{{/each}}</tr>diff --git a/frontend/discourse/admin/components/admin-report-table-summary.gjs b/frontend/discourse/admin/components/admin-report-table-summary.gjsnew file mode 100644index 00000000000..e4a1108b00a--- /dev/null+++ b/frontend/discourse/admin/components/admin-report-table-summary.gjs@@ -0,0 +1,187 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { array } from "@ember/helper";+import { action } from "@ember/object";+import { trustHTML } from "@ember/template";+import DMenu from "discourse/float-kit/components/d-menu";+import { ajax } from "discourse/lib/ajax";+import { userPath } from "discourse/lib/url";+import { formatUsername } from "discourse/lib/utilities";+import dAvatar from "discourse/ui-kit/helpers/d-avatar";+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";+import dElement from "discourse/ui-kit/helpers/d-element";+import { i18n } from "discourse-i18n";++const SUMMARY_LIMIT = 5;++export default class AdminReportTableSummary extends Component {+ @tracked items = null;+ @tracked total = null;+ @tracked isLoading = false;+ @tracked hasError = false;++ get date() {+ return moment.utc(this.args.date).format("YYYY-MM-DD");+ }++ get dateLabel() {+ return moment+ .utc(this.args.date)+ .format(i18n("dates.long_with_year_no_time"));+ }++ get triggerLabel() {+ return i18n("admin.reports.related_items.table_summary.trigger", {+ count: this.args.formattedValue,+ date: this.dateLabel,+ });+ }++ get title() {+ return i18n(+ this.args.titleKey ||+ "admin.reports.related_items.table_summary.users_title",+ { date: this.dateLabel }+ );+ }++ get hasItems() {+ return this.items?.length > 0;+ }++ get itemsAreTruncated() {+ return this.items.length < this.total;+ }++ get itemsKey() {+ return this.args.itemsKey || "users";+ }++ userProfilePath(user) {+ return userPath(user.username);+ }++ @action+ async load() {+ if (this.items || this.isLoading) {+ return;+ }++ this.isLoading = true;+ this.hasError = false;++ const data = {+ start_date: this.date,+ end_date: this.date,+ limit: SUMMARY_LIMIT,+ facets: ["related_items"],+ include_related_items: true,+ };++ if (this.args.reportFilters) {+ data.filters = this.args.reportFilters;+ }++ try {+ const response = await ajax(`/admin/reports/${this.args.reportType}`, {+ data,+ });+ this.items = response.report.related_items?.[this.itemsKey] || [];+ this.total =+ response.report.related_items_totals?.[this.itemsKey] ??+ this.items.length;+ } catch {+ this.hasError = true;+ this.items = null;+ this.total = null;+ } finally {+ this.isLoading = false;+ }+ }++ <template>+ <DMenu+ @ariaLabel={{this.triggerLabel}}+ @contentClass="admin-report-table-summary__content"+ @fallbackPlacements={{array "top-start"}}+ @hoverGracePeriod={{200}}+ @identifier="admin-report-table-summary"+ @interactive={{true}}+ @maxWidth={{360}}+ @modalForMobile={{true}}+ @onShow={{this.load}}+ @placement="bottom-start"+ @triggerComponent={{dElement "button"}}+ @triggerClass="admin-report-table-summary"+ @triggers={{array "delayed-hover" "click"}}+ @untriggers={{array "hover" "click"}}+ aria-label={{this.triggerLabel}}+ >+ <:trigger>{{trustHTML @formattedValue}}</:trigger>+ <:content>+ <div class="admin-report-table-summary__body">+ <h3 class="admin-report-table-summary__heading">{{this.title}}</h3>++ {{#if this.isLoading}}+ <p class="admin-report-table-summary__message">+ {{i18n "admin.reports.related_items.table_summary.loading"}}+ </p>+ {{else if this.hasItems}}+ {{#if this.itemsAreTruncated}}+ <p class="admin-report-table-summary__limit">+ {{i18n+ "admin.reports.related_items.showing"+ shown=this.items.length+ total=this.total+ }}+ </p>+ {{/if}}+ <ul+ class={{dConcatClass+ "admin-report-table-summary__list"+ @listClass+ }}+ >+ {{#each this.items as |item|}}+ <li class="admin-report-table-summary__item">+ {{#if @itemComponent}}+ {{component @itemComponent item=item}}+ {{else}}+ <a+ class="admin-report-table-summary__user-link"+ href={{this.userProfilePath item.user}}+ >+ {{dAvatar+ item.user+ imageSize="small"+ extraClasses="admin-report-table-summary__avatar"+ }}+ <span class="admin-report-table-summary__user-identity">+ <span class="admin-report-table-summary__username">+ {{formatUsername item.user.username}}+ </span>+ {{#if item.user.name}}+ <span class="admin-report-table-summary__name">+ {{item.user.name}}+ </span>+ {{/if}}+ </span>+ </a>+ {{/if}}+ </li>+ {{/each}}+ </ul>+ {{else if this.hasError}}+ <p class="admin-report-table-summary__message">+ {{i18n "admin.reports.related_items.table_summary.error"}}+ </p>+ {{else}}+ <p class="admin-report-table-summary__message">+ {{i18n "admin.reports.related_items.table_summary.empty"}}+ </p>+ {{/if}}+ </div>+ </:content>+ </DMenu>+ </template>+}diff --git a/frontend/discourse/admin/components/admin-report-table.gjs b/frontend/discourse/admin/components/admin-report-table.gjsindex 862207d57ae..709237737ed 100644--- a/frontend/discourse/admin/components/admin-report-table.gjs+++ b/frontend/discourse/admin/components/admin-report-table.gjs@@ -227,8 +227,11 @@ export default class AdminReportTable extends Component {{{#each this.paginatedData as |data|}}<AdminReportTableRow@data={{data}}+ @hasRelatedItems={{@hasRelatedItems}}@labels={{this.model.computedLabels}}@options={{this.options}}+ @reportType={{@reportType}}+ @reportFilters={{@reportFilters}}/>{{/each}}diff --git a/frontend/discourse/admin/components/admin-report.gjs b/frontend/discourse/admin/components/admin-report.gjsindex 8591757d2ce..885b06ea53b 100644--- a/frontend/discourse/admin/components/admin-report.gjs+++ b/frontend/discourse/admin/components/admin-report.gjs@@ -164,6 +164,19 @@ export default class AdminReport extends Component {return isPresent(this.model?.data);}+ get hasRelatedItems() {+ return (+ this.args.showRelatedItems &&+ Object.values(this.model?.related_items || {}).some(+ (items) => items.length > 0+ )+ );+ }++ get reportFilters() {+ return this.args.filters?.customFilters;+ }+get disabledLabel() {return this.args.disabledLabel || i18n("admin.dashboard.disabled");}@@ -544,6 +557,10 @@ export default class AdminReport extends Component {payload.data.filters = this.args.filters?.customFilters;}+ if (this.args.showRelatedItems) {+ payload.data.include_related_items = true;+ }+return payload;}diff --git a/frontend/discourse/admin/lib/admin-report-related-items.js b/frontend/discourse/admin/lib/admin-report-related-items.jsnew file mode 100644index 00000000000..1a46df32c21--- /dev/null+++ b/frontend/discourse/admin/lib/admin-report-related-items.js@@ -0,0 +1,13 @@+const renderers = new Map();++export function registerAdminReportRelatedItemsRenderer(reportType, renderer) {+ renderers.set(reportType, renderer);+}++export function adminReportRelatedItemsRenderer(reportType) {+ return renderers.get(reportType);+}++export function resetAdminReportRelatedItemsRenderers() {+ renderers.clear();+}diff --git a/frontend/discourse/admin/templates/admin-reports/show.gjs b/frontend/discourse/admin/templates/admin-reports/show.gjsindex 4d662a6d5d6..d8f1557c84d 100644--- a/frontend/discourse/admin/templates/admin-reports/show.gjs+++ b/frontend/discourse/admin/templates/admin-reports/show.gjs@@ -16,6 +16,7 @@ export default <template>@reportOptions={{@controller.reportOptions}}@showFilteringUI={{true}}@showDescriptionInTooltip={{false}}+ @showRelatedItems={{@controller.currentUser.admin}}@onRefresh={{routeAction "onParamsChange"}}/></div>diff --git a/frontend/discourse/app/lib/plugin-api.gjs b/frontend/discourse/app/lib/plugin-api.gjsindex 17341d175a0..5e97746f27f 100644--- a/frontend/discourse/app/lib/plugin-api.gjs+++ b/frontend/discourse/app/lib/plugin-api.gjs@@ -2,6 +2,7 @@import $ from "jquery";import { registerAdminDashboardReportRenderer } from "discourse/admin/lib/admin-dashboard-report-renderers";import { registerAdminDashboardSection } from "discourse/admin/lib/admin-dashboard-sections";+import { registerAdminReportRelatedItemsRenderer } from "discourse/admin/lib/admin-report-related-items";import { _renderBlocks } from "discourse/blocks/block-outlet";import { addAboutPageActivity } from "discourse/components/about-page";import { addBulkDropdownButton } from "discourse/components/bulk-select-topics-dropdown";@@ -3664,6 +3665,22 @@ class _PluginApi {registerReportModeComponent(mode, componentClass);}+ /**+ * Registers components that render related items for an admin report.+ *+ * @param {String} reportType - The report's identifier+ * @param {Object} renderer - The related-item renderer configuration+ * @param {Class} [renderer.relatedItemsComponent] - Component for the report detail view+ * @param {Object} [renderer.tableSummary] - Configuration for table cell summaries+ * @param {Class} renderer.tableSummary.itemComponent - Component for each summary item+ * @param {String} renderer.tableSummary.itemsKey - Related-items response key+ * @param {String} [renderer.tableSummary.listClass] - Class for the summary list+ * @param {String} renderer.tableSummary.titleKey - Summary title translation key+ */+ registerAdminReportRelatedItemsRenderer(reportType, renderer) {+ registerAdminReportRelatedItemsRenderer(reportType, renderer);+ }+/*** Registers an extension for the rich editor*diff --git a/frontend/discourse/tests/acceptance/reports-test.js b/frontend/discourse/tests/acceptance/reports-test.jsindex 2a57b988ef7..68497b62b88 100644--- a/frontend/discourse/tests/acceptance/reports-test.js+++ b/frontend/discourse/tests/acceptance/reports-test.js@@ -1,5 +1,6 @@import { click, currentURL, fillIn, select, visit } from "@ember/test-helpers";import { test } from "qunit";+import reportsBulkFixtures from "discourse/tests/fixtures/reports-bulk";import { acceptance } from "discourse/tests/helpers/qunit-helpers";acceptance("Reports", function (needs) {@@ -32,6 +33,37 @@ acceptance("Reports", function (needs) {});});+acceptance("Reports | Moderator related items", function (needs) {+ needs.user({ admin: false, moderator: true });++ let requestParams;+ needs.hooks.beforeEach(() => (requestParams = undefined));++ needs.pretender((server, helper) => {+ server.get("/admin/reports/bulk", (request) => {+ if (+ Object.keys(request.queryParams).some((key) =>+ key.startsWith("reports[signups]")+ )+ ) {+ requestParams = request.queryParams;+ }+ return helper.response(reportsBulkFixtures["/admin/reports/bulk"]);+ });+ });++ test("moderators request only report aggregates", async function (assert) {+ await visit("/admin/reports/signups");++ assert.strictEqual(+ requestParams["reports[signups][include_related_items]"],+ undefined,+ "omits the identity-level payload"+ );+ assert.dom(".admin-report.signups").exists("shows the aggregate report");+ });+});+acceptance("Reports | Plugin groups sorted by display name", function (needs) {needs.user();needs.pretender((server, helper) => {diff --git a/frontend/discourse/tests/fixtures/reports-bulk.js b/frontend/discourse/tests/fixtures/reports-bulk.jsindex 062e33afbe8..0437c288147 100644--- a/frontend/discourse/tests/fixtures/reports-bulk.js+++ b/frontend/discourse/tests/fixtures/reports-bulk.js@@ -78,6 +78,22 @@ let signups = {higher_is_better: true,modes: ["table", "chart"],prev_period: 961,+ related_items: {+ users: [+ {+ user: {+ id: 1,+ username: "dana_whitfield",+ name: "Dana Whitfield",+ avatar_template: "/letter_avatar_proxy/v4/letter/d/3be4f0/{size}.png",+ },+ timestamp: "2018-06-25T15:30:00Z",+ },+ ],+ },+ related_items_totals: {+ users: 3,+ },};let signups_fixture = JSON.parse(JSON.stringify(signups));diff --git a/frontend/discourse/tests/helpers/qunit-helpers.js b/frontend/discourse/tests/helpers/qunit-helpers.jsindex 956342943cb..386a5085c5b 100644--- a/frontend/discourse/tests/helpers/qunit-helpers.js+++ b/frontend/discourse/tests/helpers/qunit-helpers.js@@ -16,6 +16,7 @@ import QUnit, { module, test } from "qunit";import sinon from "sinon";import { resetAdminDashboardReportRenderers } from "discourse/admin/lib/admin-dashboard-report-renderers";import { resetAdminDashboardSections } from "discourse/admin/lib/admin-dashboard-sections";+import { resetAdminReportRelatedItemsRenderers } from "discourse/admin/lib/admin-report-related-items";import { _resetOutletLayoutsForTesting } from "discourse/blocks/block-outlet";import { clearAboutPageActivities } from "discourse/components/about-page";import { resetCardClickListenerSelector } from "discourse/components/card-contents-base";@@ -221,6 +222,7 @@ export function testCleanup(container, app) {noteKeyboardEvidence();resetAdditionalReportModes();resetAdminDashboardReportRenderers();+ resetAdminReportRelatedItemsRenderers();resetAdminDashboardSections();resetExtraClasses();clearOutletCache();diff --git a/frontend/discourse/tests/integration/components/admin-report-related-items-test.gjs b/frontend/discourse/tests/integration/components/admin-report-related-items-test.gjsnew file mode 100644index 00000000000..c80cff61940--- /dev/null+++ b/frontend/discourse/tests/integration/components/admin-report-related-items-test.gjs@@ -0,0 +1,106 @@+import { render } from "@ember/test-helpers";+import { module, test } from "qunit";+import AdminReportRelatedItems from "discourse/admin/components/admin-report-related-items";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import { fakeTime } from "discourse/tests/helpers/qunit-helpers";++module("Integration | Component | AdminReportRelatedItems", function (hooks) {+ setupRenderingTest(hooks);++ test("renders users with profile links", async function (assert) {+ const clock = fakeTime("2026-08-20T12:00:00", null, true);++ this.set("relatedItems", {+ users: [+ {+ user: {+ id: 1,+ username: "dana_whitfield",+ name: "Dana Whitfield",+ avatar_template:+ "/letter_avatar_proxy/v4/letter/d/3be4f0/{size}.png",+ },+ timestamp: "2026-08-18T08:42:00Z",+ },+ ],+ });+ this.set("relatedItemsTotals", { users: 3 });++ try {+ await render(+ <template>+ <AdminReportRelatedItems+ @relatedItems={{this.relatedItems}}+ @relatedItemsTotals={{this.relatedItemsTotals}}+ @startDate="2026-07-17"+ @endDate="2026-08-18"+ @type="new_contributors"+ />+ </template>+ );++ assert+ .dom(".admin-report-related-items h2")+ .hasText("Users", "labels the user list");+ assert+ .dom(".admin-report-related-items__user-link")+ .hasAttribute("href", "/u/dana_whitfield", "links to the user profile");+ assert+ .dom(".admin-report-related-items__user-link")+ .doesNotHaveAttribute("data-user-card", "does not open a user card");+ assert+ .dom(".admin-report-related-items__name")+ .hasText("Dana Whitfield", "shows the user's name");+ assert+ .dom("thead .admin-report-related-items__timestamp-cell")+ .hasText("First post created at", "labels the first-post timestamp");+ assert+ .dom(".admin-report-related-items__timestamp-cell time")+ .hasText("2 days ago", "shows a relative timestamp with ago");+ assert+ .dom(".admin-report-related-items__limit")+ .hasText(+ "Showing the newest 1 of 3.",+ "discloses that the list is limited"+ );+ } finally {+ clock.restore();+ }+ });++ test("preserves report dates in positive UTC offsets", async function (assert) {+ this.set("relatedItems", {+ users: [+ {+ user: {+ id: 1,+ username: "dana_whitfield",+ avatar_template:+ "/letter_avatar_proxy/v4/letter/d/3be4f0/{size}.png",+ },+ timestamp: "2026-08-18T08:42:00Z",+ },+ ],+ });+ this.set("startDate", moment.parseZone("2026-07-26T00:00:00+08:00"));+ this.set("endDate", moment.parseZone("2026-08-27T00:00:00+08:00"));++ await render(+ <template>+ <AdminReportRelatedItems+ @relatedItems={{this.relatedItems}}+ @startDate={{this.startDate}}+ @endDate={{this.endDate}}+ @type="signups"+ />+ </template>+ );++ assert+ .dom(".admin-report-related-items__description")+ .hasText(+ "New accounts created between Jul 26, 2026 and Aug 27, 2026, newest first.",+ "keeps the selected calendar dates"+ );+ });+});diff --git a/frontend/discourse/tests/integration/components/admin-report-table-summary-test.gjs b/frontend/discourse/tests/integration/components/admin-report-table-summary-test.gjsnew file mode 100644index 00000000000..3d42d3cd474--- /dev/null+++ b/frontend/discourse/tests/integration/components/admin-report-table-summary-test.gjs@@ -0,0 +1,144 @@+import { click, render, settled, triggerEvent } from "@ember/test-helpers";+import { module, test } from "qunit";+import AdminReportTableSummary from "discourse/admin/components/admin-report-table-summary";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import pretender, { response } from "discourse/tests/helpers/create-pretender";++module("Integration | Component | AdminReportTableSummary", function (hooks) {+ setupRenderingTest(hooks);++ test("loads and displays users for the selected day", async function (assert) {+ let requestParams;++ pretender.get("/admin/reports/signups", (request) => {+ requestParams = request.queryParams;++ return response({+ report: {+ related_items: {+ users: [+ {+ user: {+ id: 1,+ username: "dana_whitfield",+ name: "Dana Whitfield",+ avatar_template:+ "/letter_avatar_proxy/v4/letter/d/3be4f0/{size}.png",+ },+ },+ ],+ },+ related_items_totals: { users: 3 },+ },+ });+ });++ await render(+ <template>+ <AdminReportTableSummary+ @date="2026-08-18"+ @formattedValue="3"+ @reportType="signups"+ />+ </template>+ );++ assert+ .dom(".admin-report-table-summary")+ .doesNotHaveClass("btn", "does not use generic button styling");+ assert+ .dom(".admin-report-table-summary")+ .hasAttribute(+ "aria-label",+ "3, show summary for Aug 18, 2026",+ "starts the accessible label with the visible count"+ );++ triggerEvent(".admin-report-table-summary", "pointerenter");+ await settled();++ assert+ .dom(".admin-report-table-summary__heading")+ .hasText("Users on Aug 18, 2026", "labels the selected day");+ assert+ .dom(".admin-report-table-summary__user-link")+ .hasAttribute("href", "/u/dana_whitfield", "links to the user profile");+ assert+ .dom(".admin-report-table-summary__user-link")+ .doesNotHaveAttribute("data-user-card", "does not open a user card");+ assert+ .dom(".admin-report-table-summary__limit")+ .hasText(+ "Showing the newest 1 of 3.",+ "discloses that the list is limited"+ );+ assert.strictEqual(+ requestParams.cache,+ undefined,+ "does not request caching for the related-item payload"+ );+ assert.strictEqual(+ requestParams.include_related_items,+ "true",+ "requests the related-item payload"+ );+ assert.deepEqual(+ requestParams.facets,+ ["related_items"],+ "requests only the related-items facet"+ );+ });++ test("retries loading after an error", async function (assert) {+ let requestCount = 0;++ pretender.get("/admin/reports/signups", () => {+ requestCount++;++ if (requestCount === 1) {+ return response(500, {});+ }++ return response({+ report: {+ related_items: {+ users: [+ {+ user: {+ id: 1,+ username: "dana_whitfield",+ avatar_template:+ "/letter_avatar_proxy/v4/letter/d/3be4f0/{size}.png",+ },+ },+ ],+ },+ },+ });+ });++ await render(+ <template>+ <AdminReportTableSummary+ @date="2026-08-18"+ @formattedValue="3"+ @reportType="signups"+ />+ </template>+ );++ await click(".admin-report-table-summary");++ assert+ .dom(".admin-report-table-summary__message")+ .hasText("Couldn't load the summary.", "shows the failed request state");++ await click(".admin-report-table-summary");+ await click(".admin-report-table-summary");++ assert.strictEqual(requestCount, 2, "retries when the menu reopens");+ assert+ .dom(".admin-report-table-summary__user-link")+ .hasAttribute("href", "/u/dana_whitfield", "shows the retried response");+ });+});diff --git a/frontend/discourse/tests/integration/components/admin-report-test.gjs b/frontend/discourse/tests/integration/components/admin-report-test.gjsindex 63e580bc888..70ab1146b7c 100644--- a/frontend/discourse/tests/integration/components/admin-report-test.gjs+++ b/frontend/discourse/tests/integration/components/admin-report-test.gjs@@ -3,6 +3,8 @@ import { module, test } from "qunit";import AdminReport, {updateReportFilters,} from "discourse/admin/components/admin-report";+import { registerAdminReportRelatedItemsRenderer } from "discourse/admin/lib/admin-report-related-items";+import reportsBulkFixtures from "discourse/tests/fixtures/reports-bulk";import { setupRenderingTest } from "discourse/tests/helpers/component-test";import pretender, { response } from "discourse/tests/helpers/create-pretender";@@ -104,9 +106,20 @@ module("Integration | Component | AdminReport", function (hooks) {});test("switch modes", async function (assert) {+ let requestParams;++ pretender.get("/admin/reports/bulk", (request) => {+ requestParams = request.queryParams;+ return response(reportsBulkFixtures["/admin/reports/bulk"]);+ });+await render(<template>- <AdminReport @dataSourceName="signups" @showFilteringUI={{true}} />+ <AdminReport+ @dataSourceName="signups"+ @showFilteringUI={{true}}+ @showRelatedItems={{true}}+ /></template>);@@ -114,6 +127,54 @@ module("Integration | Component | AdminReport", function (hooks) {assert.dom(".admin-report-table").doesNotExist("removes the table");assert.dom(".admin-report-chart").exists("shows the chart");+ assert.dom(".admin-report-related-items").exists("shows the related users");+ assert+ .dom(".admin-report-related-items__user-link")+ .hasAttribute("href", "/u/dana_whitfield", "links to the user profile");+ assert+ .dom(".admin-report-related-items__limit")+ .hasText(+ "Showing the newest 1 of 3.",+ "discloses that the list is limited"+ );+ assert.strictEqual(+ requestParams["reports[signups][include_related_items]"],+ "true",+ "requests the related-item payload"+ );+ });++ test("does not render related items unless requested", async function (assert) {+ await render(+ <template>+ <AdminReport @dataSourceName="signups" @showFilteringUI={{true}} />+ </template>+ );++ await click(".mode-btn.chart");++ assert+ .dom(".admin-report-related-items")+ .doesNotExist("keeps dashboard-style reports compact");+ });++ test("keeps table values plain when a renderer omits its optional summary component", async function (assert) {+ registerAdminReportRelatedItemsRenderer("signups", {+ relatedItemsComponent: Object,+ });++ await render(+ <template>+ <AdminReport @dataSourceName="signups" @showRelatedItems={{true}} />+ </template>+ );++ assert+ .dom(".admin-report-table-summary")+ .doesNotExist("does not use the core user-summary fallback");+ assert+ .dom(".admin-report-table tbody tr:first-child td:nth-child(2)")+ .hasText("12", "retains the report value");});test("timeout", async function (assert) {diff --git a/lib/plugin/instance.rb b/lib/plugin/instance.rbindex 963fa9fae69..308884e2a1c 100644--- a/lib/plugin/instance.rb+++ b/lib/plugin/instance.rb@@ -250,8 +250,10 @@ class Plugin::Instanceend# Applies to all sites in a multisite environment. Ignores plugin.enabled?- def add_report(name, exclude_from_dashboard: false, &block)- reloadable_patch { |plugin| Report.add_report(name, exclude_from_dashboard:, &block) }+ def add_report(name, exclude_from_dashboard: false, admin_only_related_items: false, &block)+ reloadable_patch do |plugin|+ Report.add_report(name, exclude_from_dashboard:, admin_only_related_items:, &block)+ endend# Applies to all sites in a multisite environment. Ignores plugin.enabled?diff --git a/plugins/discourse-solved/assets/javascripts/discourse/components/solved-admin-report-related-items.gjs b/plugins/discourse-solved/assets/javascripts/discourse/components/solved-admin-report-related-items.gjsnew file mode 100644index 00000000000..4b1aa4a6f48--- /dev/null+++ b/plugins/discourse-solved/assets/javascripts/discourse/components/solved-admin-report-related-items.gjs@@ -0,0 +1,128 @@+import Component from "@glimmer/component";+import { userPath } from "discourse/lib/url";+import { formatUsername } from "discourse/lib/utilities";+import dAvatar from "discourse/ui-kit/helpers/d-avatar";+import dCategoryBadge from "discourse/ui-kit/helpers/d-category-badge";+import { i18n } from "discourse-i18n";++export default class SolvedAdminReportRelatedItems extends Component {+ get solvedTopics() {+ return this.args.relatedItems?.solved_topics || [];+ }++ get solvedTopicsTotal() {+ return (+ this.args.relatedItemsTotals?.solved_topics || this.solvedTopics.length+ );+ }++ get solvedTopicsAreTruncated() {+ return this.solvedTopics.length < this.solvedTopicsTotal;+ }++ get startDate() {+ return moment(this.args.startDate).format(+ i18n("dates.long_with_year_no_time")+ );+ }++ get endDate() {+ return moment(this.args.endDate).format(+ i18n("dates.long_with_year_no_time")+ );+ }++ userProfilePath(user) {+ return userPath(user.username);+ }++ <template>+ {{#if this.solvedTopics.length}}+ <section+ class="admin-report-related-items solved-admin-report-related-items"+ >+ <h2>{{i18n "admin.reports.related_items.solved_topics.title"}}</h2>+ <p class="admin-report-related-items__description">+ {{i18n+ "admin.reports.related_items.solved_topics.description"+ startDate=this.startDate+ endDate=this.endDate+ }}+ {{#if this.solvedTopicsAreTruncated}}+ <span class="admin-report-related-items__limit">+ {{i18n+ "admin.reports.related_items.showing"+ shown=this.solvedTopics.length+ total=this.solvedTopicsTotal+ }}+ </span>+ {{/if}}+ </p>++ <table+ class="table admin-report-related-items__table solved-admin-report-related-items__table"+ >+ <thead>+ <tr>+ <th class="solved-admin-report-related-items__topic-cell">+ {{i18n "admin.reports.related_items.labels.topic"}}+ </th>+ <th class="solved-admin-report-related-items__solved-by-cell">+ {{i18n "admin.reports.related_items.labels.solved_by"}}+ </th>+ <th class="solved-admin-report-related-items__category-cell">+ {{i18n "admin.reports.related_items.labels.category"}}+ </th>+ </tr>+ </thead>+ <tbody>+ {{#each this.solvedTopics as |item|}}+ <tr>+ <td class="solved-admin-report-related-items__topic-cell">+ <a+ class="solved-admin-report-related-items__topic-link"+ href={{item.topic.url}}+ >+ {{item.topic.title}}+ </a>+ </td>+ <td class="solved-admin-report-related-items__solved-by-cell">+ {{#let item.solved_by_users as |users|}}+ {{#if users.length}}+ <div+ class="solved-admin-report-related-items__solved-by-users"+ >+ {{#each users as |user|}}+ <a+ class="admin-report-related-items__user-link"+ href={{this.userProfilePath user}}+ >+ {{dAvatar+ user+ imageSize="small"+ extraClasses="admin-report-related-items__avatar"+ }}+ <span class="admin-report-related-items__username">+ {{formatUsername user.username}}+ </span>+ </a>+ {{/each}}+ </div>+ {{/if}}+ {{/let}}+ </td>+ <td class="solved-admin-report-related-items__category-cell">+ {{#if item.category}}+ {{dCategoryBadge item.category}}+ {{else}}+ {{i18n "category.none"}}+ {{/if}}+ </td>+ </tr>+ {{/each}}+ </tbody>+ </table>+ </section>+ {{/if}}+ </template>+}diff --git a/plugins/discourse-solved/assets/javascripts/discourse/components/solved-admin-report-table-summary-item.gjs b/plugins/discourse-solved/assets/javascripts/discourse/components/solved-admin-report-table-summary-item.gjsnew file mode 100644index 00000000000..d0a1f98b295--- /dev/null+++ b/plugins/discourse-solved/assets/javascripts/discourse/components/solved-admin-report-table-summary-item.gjs@@ -0,0 +1,40 @@+import Component from "@glimmer/component";+import { userPath } from "discourse/lib/url";+import { formatUsername } from "discourse/lib/utilities";+import dAvatar from "discourse/ui-kit/helpers/d-avatar";+import dCategoryBadge from "discourse/ui-kit/helpers/d-category-badge";++export default class SolvedAdminReportTableSummaryItem extends Component {+ userProfilePath(user) {+ return userPath(user.username);+ }++ <template>+ <a+ class="solved-admin-report-table-summary__topic-link"+ href={{@item.topic.url}}+ >+ {{@item.topic.title}}+ </a>+ <div class="solved-admin-report-table-summary__topic-meta">+ {{#each @item.solved_by_users as |user|}}+ <a+ class="admin-report-table-summary__user-link"+ href={{this.userProfilePath user}}+ >+ {{dAvatar+ user+ imageSize="small"+ extraClasses="admin-report-table-summary__avatar"+ }}+ <span class="admin-report-table-summary__username">+ {{formatUsername user.username}}+ </span>+ </a>+ {{/each}}+ {{#if @item.category}}+ {{dCategoryBadge @item.category}}+ {{/if}}+ </div>+ </template>+}diff --git a/plugins/discourse-solved/assets/javascripts/discourse/initializers/solved-admin-report-related-items.gjs b/plugins/discourse-solved/assets/javascripts/discourse/initializers/solved-admin-report-related-items.gjsnew file mode 100644index 00000000000..1c63441f88c--- /dev/null+++ b/plugins/discourse-solved/assets/javascripts/discourse/initializers/solved-admin-report-related-items.gjs@@ -0,0 +1,22 @@+import { withPluginApi } from "discourse/lib/plugin-api";+import SolvedAdminReportRelatedItems from "discourse/plugins/discourse-solved/discourse/components/solved-admin-report-related-items";+import SolvedAdminReportTableSummaryItem from "discourse/plugins/discourse-solved/discourse/components/solved-admin-report-table-summary-item";++export default {+ name: "solved-admin-report-related-items",++ initialize() {+ withPluginApi((api) => {+ api.registerAdminReportRelatedItemsRenderer("accepted_solutions", {+ relatedItemsComponent: SolvedAdminReportRelatedItems,+ tableSummary: {+ itemComponent: SolvedAdminReportTableSummaryItem,+ itemsKey: "solved_topics",+ listClass: "solved-admin-report-table-summary__list",+ titleKey:+ "admin.reports.related_items.table_summary.solved_topics_title",+ },+ });+ });+ },+};diff --git a/plugins/discourse-solved/assets/stylesheets/admin/report-related-items.scss b/plugins/discourse-solved/assets/stylesheets/admin/report-related-items.scssnew file mode 100644index 00000000000..b0833802e74--- /dev/null+++ b/plugins/discourse-solved/assets/stylesheets/admin/report-related-items.scss@@ -0,0 +1,72 @@+@use "lib/viewport";++.solved-admin-report-related-items {+ &__table tr {+ @include viewport.until(sm) {+ display: grid;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ }+ }++ &__topic-cell {+ width: 40%;++ @include viewport.until(sm) {+ grid-column: 1 / -1;+ width: auto;+ }+ }++ &__solved-by-cell {+ width: 25%;++ @include viewport.until(sm) {+ width: auto;+ }+ }++ &__category-cell {+ width: 35%;++ @include viewport.until(sm) {+ width: auto;+ }+ }++ &__category-cell > .badge-category__wrapper {+ max-width: 100%;+ }++ &__solved-by-users {+ display: grid;+ gap: var(--space-1);+ }++ &__topic-link {+ overflow-wrap: anywhere;+ }+}++.solved-admin-report-table-summary {+ &__list {+ gap: var(--space-4);+ }++ &__topic-link {+ overflow-wrap: anywhere;+ }++ &__topic-meta {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: var(--space-2);+ margin-block-start: var(--space-1);+ }++ &__topic-meta > .badge-category__wrapper {+ flex: 1 1 0;+ min-width: 0;+ max-width: 100%;+ }+}diff --git a/plugins/discourse-solved/config/locales/client.en.yml b/plugins/discourse-solved/config/locales/client.en.ymlindex 65b47d01545..e06b811a422 100644--- a/plugins/discourse-solved/config/locales/client.en.yml+++ b/plugins/discourse-solved/config/locales/client.en.yml@@ -169,6 +169,17 @@ en:unsolved: "are unsolved"admin:+ reports:+ related_items:+ solved_topics:+ title: "Solved topics"+ description: "Topics marked as solved between %{startDate} and %{endDate}, newest first."+ labels:+ topic: "Topic"+ solved_by: "Solved by"+ category: "Category"+ table_summary:+ solved_topics_title: "Solved topics on %{date}"web_hooks:solved_event:group_name: "Solved Event"diff --git a/plugins/discourse-solved/plugin.rb b/plugins/discourse-solved/plugin.rbindex 4f561cc0dab..e2a927b4148 100644--- a/plugins/discourse-solved/plugin.rb+++ b/plugins/discourse-solved/plugin.rb@@ -15,6 +15,7 @@ register_svg_icon "far-square"register_asset "stylesheets/solutions.scss"register_asset "stylesheets/admin/dashboard-support.scss", :admin+register_asset "stylesheets/admin/report-related-items.scss", :adminmodule ::DiscourseSolvedPLUGIN_NAME = "discourse-solved"@@ -158,7 +159,7 @@ after_initialize doresult[:html] if result.success?end- Report.add_report("accepted_solutions") do |report|+ Report.add_report("accepted_solutions", admin_only_related_items: true) do |report|report.data = []accepted_solutions =@@ -181,19 +182,26 @@ after_initialize doaccepted_solutions =accepted_solutions.where("topics.category_id" => requested_ids) if filter_requested- accepted_solutions- .where("discourse_solved_solved_topics.created_at >= ?", report.start_date)- .where("discourse_solved_solved_topics.created_at <= ?", report.end_date)+ current_accepted_solutions =+ accepted_solutions.where(+ "discourse_solved_solved_topics.created_at >= ?",+ report.start_date,+ ).where("discourse_solved_solved_topics.created_at <= ?", report.end_date)++ current_accepted_solutions.group("DATE(discourse_solved_solved_topics.created_at)").order("DATE(discourse_solved_solved_topics.created_at)").count.each { |date, count| report.data << { x: date, y: count } }- report.total = accepted_solutions.count- report.prev30Days =- accepted_solutions- .where("discourse_solved_solved_topics.created_at >= ?", report.start_date - 30.days)- .where("discourse_solved_solved_topics.created_at <= ?", report.start_date)- .count+ report.total = accepted_solutions.count if report.facets.include?(:total)++ if report.facets.include?(:prev30Days)+ report.prev30Days =+ accepted_solutions+ .where("discourse_solved_solved_topics.created_at >= ?", report.start_date - 30.days)+ .where("discourse_solved_solved_topics.created_at <= ?", report.start_date)+ .count+ endif report.facets.include?(:prev_period)report.prev_period =@@ -202,6 +210,58 @@ after_initialize do.where("discourse_solved_solved_topics.created_at < ?", report.prev_end_date).countend++ next if !report.include_related_items++ guardian = report.guardian+ solved_topics = current_accepted_solutions.merge(Topic.listable_topics.secured(guardian))+ if !guardian.can_see_shared_draft?+ solved_topics = solved_topics.where.not(topic_id: SharedDraft.select(:topic_id))+ end++ report.related_items_totals = { solved_topics: solved_topics.count }++ solved_topics =+ solved_topics+ .includes({ topic: :category }, answer_posts: :user)+ .order(created_at: :desc)+ .limit(report.limit || Report::RELATED_ITEMS_LIMIT)+ .to_a++ report.related_items = {+ solved_topics:+ solved_topics.map do |solved_topic|+ topic = solved_topic.topic+ category = topic.category+ solved_by_users =+ solved_topic+ .answer_posts+ .sort_by { |answer_post| [answer_post.created_at, answer_post.id] }+ .filter_map(&:user)+ .uniq(&:id)+ .map do |user|+ BasicUserSerializer.new(user, scope: report.guardian, root: false).as_json+ end++ {+ topic: {+ title: topic.title,+ url: topic.relative_url,+ },+ solved_by_users:,+ category:+ if category+ {+ id: category.id,+ name: category.name,+ slug: category.slug,+ color: category.color,+ textColor: category.text_color,+ }+ end,+ }+ end,+ }endregister_admin_dashboard_highlight_kpi(diff --git a/plugins/discourse-solved/spec/reports/accepted_solutions_spec.rb b/plugins/discourse-solved/spec/reports/accepted_solutions_spec.rbindex f20d2ad0e43..af0e600bdfd 100644--- a/plugins/discourse-solved/spec/reports/accepted_solutions_spec.rb+++ b/plugins/discourse-solved/spec/reports/accepted_solutions_spec.rb@@ -3,15 +3,33 @@describe "accepted_solutions report" do # rubocop:disable RSpec/DescribeClassfab!(:author, :user)- def solved_topic_in(category)- topic = Fabricate(:topic, category: category, user: author, created_at: 1.day.ago)- answer = Fabricate(:post, topic: topic, user: author, created_at: 1.day.ago)- Fabricate(:solved_topic, topic: topic, answer_post: answer, created_at: 1.day.ago)+ def solved_topic_in(category, created_at: 1.day.ago)+ topic = Fabricate(:topic, category: category, user: author, created_at:)+ answer = Fabricate(:post, topic: topic, user: author, created_at:)+ Fabricate(:solved_topic, topic: topic, answer_post: answer, created_at:)topicend- def build(filters: {})- Report.find("accepted_solutions", start_date: 2.days.ago, end_date: Time.current, filters:)+ def build(filters: {}, guardian: Discourse.system_user.guardian, facets: nil)+ Report.find(+ "accepted_solutions",+ start_date: 2.days.ago,+ end_date: Time.current,+ filters:,+ guardian:,+ facets:,+ include_related_items: true,+ )+ end++ it "restricts related items to admins while retaining moderator access to aggregates" do+ solved_topic_in(Fabricate(:category))+ moderator_guardian = Fabricate(:moderator).guardian+ report = build(guardian: moderator_guardian)++ expect(report.data.sum { |point| point[:y] }).to eq(1)+ expect(report.related_items).to be_nil+ expect(report.related_items_totals).to be_nilendit "counts accepted solutions across all categories when no filter is given" do@@ -21,6 +39,117 @@ describe "accepted_solutions report" do # rubocop:disable RSpec/DescribeClassexpect(build.total).to eq(2)end+ it "counts accepted solutions outside the selected date range in the total" do+ category = Fabricate(:category)+ solved_topic_in(category)+ solved_topic_in(category, created_at: 3.days.ago)++ expect(build.total).to eq(2)+ end++ it "only calculates requested facets" do+ solved_topic_in(Fabricate(:category))++ report = build(facets: [:related_items])++ expect(report.total).to be_nil+ expect(report.prev30Days).to be_nil+ expect(report.related_items_totals).to eq(solved_topics: 1)+ end++ it "includes the solved topic, answer author, and category" do+ category = Fabricate(:category)+ topic = solved_topic_in(category)++ report = build+ item = report.related_items[:solved_topics].first++ expect(report.related_items_totals).to eq(solved_topics: 1)+ expect(item[:topic]).to eq(title: topic.title, url: topic.relative_url)+ expect(item.dig(:solved_by_users, 0, :username)).to eq(author.username)+ expect(item[:category]).to include(+ id: category.id,+ name: category.name,+ slug: category.slug,+ color: category.color,+ )+ end++ it "includes every accepted answer author when multiple solutions are enabled" do+ SiteSetting.solved_allow_multiple_solutions = true+ category = Fabricate(:category)+ topic = solved_topic_in(category)+ second_author = Fabricate(:user)+ second_answer = Fabricate(:post, topic:, user: second_author, created_at: 23.hours.ago)+ Fabricate(:topic_answer, solved_topic: topic.solved, post: second_answer, accepter: author)++ item = build.related_items[:solved_topics].first++ expect(item[:solved_by_users].map { |user| user[:username] }).to eq(+ [author.username, second_author.username],+ )+ end++ it "only includes solved topics from the selected date range" do+ category = Fabricate(:category)+ in_range_topic = solved_topic_in(category)+ solved_topic_in(category, created_at: 3.days.ago)++ report = build++ expect(report.related_items[:solved_topics].map { |item| item.dig(:topic, :title) }).to eq(+ [in_range_topic.title],+ )+ end++ it "skips related items when the report has no guardian" do+ solved_topic_in(Fabricate(:category))++ report = build(guardian: nil)++ expect(report.total).to eq(1)+ expect(report.related_items).to be_nil+ expect(report.related_items_totals).to be_nil+ end++ it "only includes solved topic details visible to the report guardian" do+ SiteSetting.suppress_secured_categories_from_admin = true+ private_topic = solved_topic_in(Fabricate(:private_category, group: Fabricate(:group)))+ visible_topic = solved_topic_in(Fabricate(:category))+ admin = Fabricate(:admin)++ expect(admin.guardian.can_see_topic?(private_topic)).to be(false)++ report = build(guardian: admin.guardian)++ expect(report.total).to eq(2)+ expect(report.related_items_totals).to eq(solved_topics: 1)+ expect(report.related_items[:solved_topics].map { |item| item.dig(:topic, :title) }).to eq(+ [visible_topic.title],+ )+ end++ it "excludes shared drafts from details when the report guardian cannot see them" do+ shared_drafts_category = Fabricate(:category)+ SiteSetting.suppress_secured_categories_from_admin = true+ SiteSetting.shared_drafts_category = shared_drafts_category.id+ SiteSetting.shared_drafts_allowed_groups = Fabricate(:group).id+ shared_draft_topic = solved_topic_in(shared_drafts_category)+ Fabricate(:shared_draft, topic: shared_draft_topic, category: Fabricate(:category))+ visible_topic = solved_topic_in(Fabricate(:category))+ admin = Fabricate(:admin)++ expect(admin.guardian.can_see_topic?(shared_draft_topic)).to be(false)++ report = build(guardian: admin.guardian)++ expect(report.total).to eq(2)+ expect(report.related_items_totals).to eq(solved_topics: 1)+ expect(report.related_items[:solved_topics].map { |item| item.dig(:topic, :title) }).to eq(+ [visible_topic.title],+ )+ end+it "registers the category_ids filter even when no filter is given" doreport = builddiff --git a/plugins/discourse-solved/test/javascripts/integration/admin-report-related-items-test.gjs b/plugins/discourse-solved/test/javascripts/integration/admin-report-related-items-test.gjsnew file mode 100644index 00000000000..bf387212fb6--- /dev/null+++ b/plugins/discourse-solved/test/javascripts/integration/admin-report-related-items-test.gjs@@ -0,0 +1,228 @@+import { click, render } from "@ember/test-helpers";+import { module, test } from "qunit";+import AdminReportRelatedItems from "discourse/admin/components/admin-report-related-items";+import AdminReportTableSummary from "discourse/admin/components/admin-report-table-summary";+import { adminReportRelatedItemsRenderer } from "discourse/admin/lib/admin-report-related-items";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import pretender, { response } from "discourse/tests/helpers/create-pretender";+import SolvedAdminReportTableSummaryItem from "discourse/plugins/discourse-solved/discourse/components/solved-admin-report-table-summary-item";++module(+ "Integration | Component | Solved admin report related items",+ function (hooks) {+ setupRenderingTest(hooks);++ test("renders the solved-topic detail component registered for the report", async function (assert) {+ this.set("relatedItems", {+ solved_topics: [+ {+ topic: {+ title: "Composer loses draft when switching categories",+ url: "/t/composer-loses-draft-when-switching-categories/1",+ },+ solved_by_users: [+ {+ id: 2,+ username: "priya.n",+ avatar_template:+ "/letter_avatar_proxy/v4/letter/p/3be4f0/{size}.png",+ },+ {+ id: 3,+ username: "laurenb",+ avatar_template:+ "/letter_avatar_proxy/v4/letter/l/3be4f0/{size}.png",+ },+ ],+ category: {+ id: 1,+ name: "Support",+ slug: "support",+ color: "0088CC",+ },+ },+ ],+ });+ this.set("relatedItemsTotals", { solved_topics: 3 });++ await render(+ <template>+ <AdminReportRelatedItems+ @relatedItems={{this.relatedItems}}+ @relatedItemsTotals={{this.relatedItemsTotals}}+ @startDate="2026-07-17"+ @endDate="2026-08-18"+ @type="accepted_solutions"+ />+ </template>+ );++ assert+ .dom(".admin-report-related-items h2")+ .hasText("Solved topics", "labels the solved topic list");+ assert+ .dom(".solved-admin-report-related-items__topic-link")+ .hasAttribute(+ "href",+ "/t/composer-loses-draft-when-switching-categories/1",+ "links to the topic"+ );+ assert+ .dom(".solved-admin-report-related-items__solved-by-cell a")+ .exists({ count: 2 }, "shows every answer author");+ assert+ .dom(".solved-admin-report-related-items__solved-by-cell a:first-child")+ .hasAttribute("href", "/u/priya.n", "links to the first answer author");+ assert+ .dom(".solved-admin-report-related-items__solved-by-cell a:last-child")+ .hasAttribute(+ "href",+ "/u/laurenb",+ "links to the second answer author"+ );+ assert+ .dom(".badge-category")+ .includesText("Support", "shows the category");+ assert+ .dom(".admin-report-related-items__limit")+ .hasText(+ "Showing the newest 1 of 3.",+ "discloses that the list is limited"+ );+ });++ test("preserves report dates in positive UTC offsets", async function (assert) {+ this.set("relatedItems", {+ solved_topics: [+ {+ topic: {+ title: "Composer loses draft when switching categories",+ url: "/t/composer-loses-draft-when-switching-categories/1",+ },+ solved_by_users: [],+ },+ ],+ });+ this.set("startDate", moment.parseZone("2026-07-26T00:00:00+08:00"));+ this.set("endDate", moment.parseZone("2026-08-27T00:00:00+08:00"));++ await render(+ <template>+ <AdminReportRelatedItems+ @relatedItems={{this.relatedItems}}+ @startDate={{this.startDate}}+ @endDate={{this.endDate}}+ @type="accepted_solutions"+ />+ </template>+ );++ assert+ .dom(".admin-report-related-items__description")+ .hasText(+ "Topics marked as solved between Jul 26, 2026 and Aug 27, 2026, newest first.",+ "keeps the selected calendar dates"+ );+ });++ test("uses the table summary item registered for the report", async function (assert) {+ let requestParams;++ pretender.get("/admin/reports/accepted_solutions", (request) => {+ requestParams = request.queryParams;++ return response({+ report: {+ related_items: {+ solved_topics: [+ {+ topic: {+ title: "Composer loses draft when switching categories",+ url: "/t/composer-loses-draft-when-switching-categories/1",+ },+ solved_by_users: [+ {+ id: 2,+ username: "priya.n",+ avatar_template:+ "/letter_avatar_proxy/v4/letter/p/3be4f0/{size}.png",+ },+ {+ id: 3,+ username: "laurenb",+ avatar_template:+ "/letter_avatar_proxy/v4/letter/l/3be4f0/{size}.png",+ },+ ],+ },+ ],+ },+ related_items_totals: { solved_topics: 3 },+ },+ });+ });++ const renderer = adminReportRelatedItemsRenderer("accepted_solutions");+ this.set("tableSummary", renderer.tableSummary);++ await render(+ <template>+ <AdminReportTableSummary+ @date="2026-08-18"+ @formattedValue="1"+ @itemComponent={{this.tableSummary.itemComponent}}+ @itemsKey={{this.tableSummary.itemsKey}}+ @listClass={{this.tableSummary.listClass}}+ @reportType="accepted_solutions"+ @titleKey={{this.tableSummary.titleKey}}+ />+ </template>+ );++ await click(".admin-report-table-summary");++ assert.strictEqual(+ renderer.tableSummary.itemComponent,+ SolvedAdminReportTableSummaryItem,+ "uses the registered Solved item component"+ );+ assert+ .dom(".admin-report-table-summary")+ .hasAttribute(+ "aria-label",+ "1, show summary for Aug 18, 2026",+ "starts the accessible label with the visible count"+ );+ assert+ .dom(".admin-report-table-summary__heading")+ .hasText("Solved topics on Aug 18, 2026", "labels the selected day");+ assert+ .dom(".admin-report-table-summary__list")+ .hasClass(+ "solved-admin-report-table-summary__list",+ "preserves the Solved summary spacing hook"+ );+ assert+ .dom(".solved-admin-report-table-summary__topic-link")+ .hasAttribute(+ "href",+ "/t/composer-loses-draft-when-switching-categories/1",+ "links to the solved topic"+ );+ assert+ .dom(".admin-report-table-summary__user-link")+ .exists({ count: 2 }, "shows every answer author");+ assert+ .dom(".admin-report-table-summary__limit")+ .hasText(+ "Showing the newest 1 of 3.",+ "discloses that the list is limited"+ );+ assert.strictEqual(+ requestParams.include_related_items,+ "true",+ "requests the related-item payload"+ );+ });+ }+);diff --git a/spec/lib/plugin/instance_spec.rb b/spec/lib/plugin/instance_spec.rbindex ba36ac3ec8b..5942f46d29f 100644--- a/spec/lib/plugin/instance_spec.rb+++ b/spec/lib/plugin/instance_spec.rb@@ -391,11 +391,12 @@ TEXTdescribe "#add_report" doafter { Report.remove_report("readers") }- it "adds a report" do+ it "adds a report with admin-only related items" doplugin = Plugin::Instance.new nil, "/tmp/test.rb"- plugin.add_report("readers") {}+ plugin.add_report("readers", admin_only_related_items: true) {}expect(Report.respond_to?(:report_readers)).to eq(true)+ expect(Report.admin_only_related_items_report_types).to include("readers")endenddiff --git a/spec/models/report_spec.rb b/spec/models/report_spec.rbindex 4483b95b040..71fe1060e7a 100644--- a/spec/models/report_spec.rb+++ b/spec/models/report_spec.rb@@ -9,9 +9,17 @@ RSpec.describe Report doexpect(Report.dashboard_excluded_report_types).to include("my_custom_report")end- it "does not record report types by default" do+ it "records report types with admin-only related items" do+ Report.add_report("my_custom_report", admin_only_related_items: true) { |report| }+ Report.add_report("my_custom_report") { |report| }++ expect(Report.admin_only_related_items_report_types).to include("my_custom_report")+ end++ it "does not record report options by default" doReport.add_report("my_custom_report") { |report| }expect(Report.dashboard_excluded_report_types).not_to include("my_custom_report")+ expect(Report.admin_only_related_items_report_types).not_to include("my_custom_report")endend@@ -572,8 +580,8 @@ RSpec.describe Report dodescribe "signups report" doit "returns the current data and previous period count" do- Fabricate(:user, created_at: Time.zone.local(2026, 4, 1, 12))- Fabricate(:user, created_at: Time.zone.local(2026, 4, 2, 12))+ first_signup = Fabricate(:user, created_at: Time.zone.local(2026, 4, 1, 12))+ second_signup = Fabricate(:user, created_at: Time.zone.local(2026, 4, 2, 12))Fabricate(:user, created_at: Time.zone.local(2026, 3, 31, 12))report =@@ -582,10 +590,82 @@ RSpec.describe Report dostart_date: Time.zone.local(2026, 4, 1).beginning_of_day,end_date: Time.zone.local(2026, 4, 2).end_of_day,facets: [:prev_period],+ limit: 2,+ guardian: Discourse.system_user.guardian,+ include_related_items: true,)expect(report.data.sum { |point| point[:y] }).to eq(2)expect(report.prev_period).to eq(1)+ expect(report.related_items[:users].map { |item| item[:user][:username] }).to eq(+ [second_signup.username, first_signup.username],+ )+ expect(report.related_items_totals).to eq(users: 2)++ summary_report =+ Report.find(+ "signups",+ start_date: Time.zone.local(2026, 4, 1).beginning_of_day,+ end_date: Time.zone.local(2026, 4, 2).end_of_day,+ limit: 1,+ guardian: Discourse.system_user.guardian,+ include_related_items: true,+ )++ expect(summary_report.related_items[:users].map { |item| item[:user][:username] }).to eq(+ [second_signup.username],+ )+ expect(summary_report.related_items_totals).to eq(users: 2)+ end++ it "skips related items when the report has no guardian" do+ Fabricate(:user, created_at: Time.zone.local(2026, 4, 1, 12))++ report =+ Report.find(+ "signups",+ start_date: Time.zone.local(2026, 4, 1).beginning_of_day,+ end_date: Time.zone.local(2026, 4, 2).end_of_day,+ include_related_items: true,+ )++ expect(report.data.sum { |point| point[:y] }).to eq(1)+ expect(report.related_items).to be_nil+ expect(report.related_items_totals).to be_nil+ end++ it "skips related items when the guardian is not an admin" do+ Fabricate(:user, created_at: Time.zone.local(2026, 4, 1, 12))++ report =+ Report.find(+ :signups,+ start_date: Time.zone.local(2026, 4, 1).beginning_of_day,+ end_date: Time.zone.local(2026, 4, 2).end_of_day,+ guardian: Fabricate(:moderator).guardian,+ include_related_items: true,+ )++ expect(report.data.sum { |point| point[:y] }).to eq(1)+ expect(report.type).to eq("signups")+ expect(report.related_items).to be_nil+ expect(report.related_items_totals).to be_nil+ end++ it "skips related items unless they are requested" do+ Fabricate(:user, created_at: Time.zone.local(2026, 4, 1, 12))++ report =+ Report.find(+ "signups",+ start_date: Time.zone.local(2026, 4, 1).beginning_of_day,+ end_date: Time.zone.local(2026, 4, 2).end_of_day,+ guardian: Discourse.system_user.guardian,+ )++ expect(report.data.sum { |point| point[:y] }).to eq(1)+ expect(report.related_items).to be_nil+ expect(report.related_items_totals).to be_nilendend@@ -637,10 +717,37 @@ RSpec.describe Report dostart_date: Time.zone.local(2026, 4, 1).beginning_of_day,end_date: Time.zone.local(2026, 4, 2).end_of_day,facets: [:prev_period],+ limit: 2,+ guardian: Discourse.system_user.guardian,+ include_related_items: true,)expect(report.data.sum { |point| point[:y] }).to eq(2)expect(report.prev_period).to eq(1)+ expect(report.related_items[:users].map { |item| item[:user][:username] }).to eq(+ [another_current_contributor.username, current_contributor.username],+ )+ expect(report.related_items_totals).to eq(users: 2)+ end++ it "skips related items when the report has no guardian" do+ contributor = Fabricate(:user)+ contributor.user_stat.update!(+ new_since: Time.zone.local(2026, 4, 1, 12),+ first_post_created_at: Time.zone.local(2026, 4, 1, 12),+ )++ report =+ Report.find(+ "new_contributors",+ start_date: Time.zone.local(2026, 4, 1).beginning_of_day,+ end_date: Time.zone.local(2026, 4, 2).end_of_day,+ include_related_items: true,+ )++ expect(report.data.sum { |point| point[:y] }).to eq(1)+ expect(report.related_items).to be_nil+ expect(report.related_items_totals).to be_nilendend@@ -1972,6 +2079,18 @@ RSpec.describe Report do.with(Report.cache_key(valid_report), valid_report.as_json, expires_in: 60.minutes)Report.cache(valid_report)end++ it "does not read or write cached related-item reports" do+ guardian = Discourse.system_user.guardian+ related_report = Report._get("signups", guardian:, include_related_items: true)+ Report.cache(related_report)++ expect(Report.find_cached("signups", guardian:)).to be_nil++ Report.cache(Report._get("signups", guardian:))++ expect(Report.find_cached("signups", guardian:, include_related_items: true)).to be_nil+ endenddescribe ".cache_key" dodiff --git a/spec/requests/admin/reports_controller_spec.rb b/spec/requests/admin/reports_controller_spec.rbindex b9f4c0bd2ac..053219fc9d1 100644--- a/spec/requests/admin/reports_controller_spec.rb+++ b/spec/requests/admin/reports_controller_spec.rb@@ -241,6 +241,27 @@ RSpec.describe Admin::ReportsController doexpect(response.parsed_body["reports"][3]).to include("error" => "not_found", "data" => nil)end+ it "returns aggregates but not related items for identity-level reports" do+ get "/admin/reports/bulk.json",+ params: {+ reports: {+ signups: {+ include_related_items: false,+ },+ new_contributors: {+ include_related_items: true,+ },+ },+ }++ expect(response.status).to eq(200)+ expect(response.parsed_body["reports"][0]["type"]).to eq("signups")+ expect(response.parsed_body["reports"][1]["type"]).to eq("new_contributors")+ expect(+ response.parsed_body["reports"].filter_map { |report| report["related_items"] },+ ).to be_empty+ end+it "redacts suspicious login IP addresses when IP viewing is disabled" doSiteSetting.moderators_view_ips = falseDiscourseIpInfo.stubs(:get).returns(location: "Earth")@@ -394,6 +415,19 @@ RSpec.describe Admin::ReportsController doexpect(response.status).to eq(200)expect(response.parsed_body["report"]["total"]).to eq(1)end++ it "only includes related items when requested" do+ Fabricate(:user, created_at: 1.hour.ago)++ get "/admin/reports/signups.json", params: { cache: true }+ expect(response.parsed_body["report"]).not_to have_key("related_items")++ get "/admin/reports/signups.json", params: { cache: true, include_related_items: true }+ expect(response.parsed_body["report"]["related_items"]["users"]).to be_present++ get "/admin/reports/signups.json", params: { cache: true }+ expect(response.parsed_body["report"]).not_to have_key("related_items")+ endendcontext "when limit param is invalid" do@@ -483,6 +517,18 @@ RSpec.describe Admin::ReportsController doexpect(response.parsed_body["report"]["total"]).to eq(1)end+ it "returns report aggregates without identity-level data" do+ get "/admin/reports/signups.json"++ expect(response.status).to eq(200)+ expect(response.parsed_body["report"]["type"]).to eq("signups")++ get "/admin/reports/signups.json", params: { include_related_items: true }++ expect(response.status).to eq(200)+ expect(response.parsed_body["report"]).not_to have_key("related_items")+ end+context "when moderators cannot view IPs" dobefore doSiteSetting.moderators_view_ips = false