A platform for community discussion. Free, open, simple.
DEV: Load Rewind reports through one paginated endpoint
Régis Hanolfce26a310f62
diff --git a/plugins/discourse-rewind/app/controllers/discourse_rewind/rewinds_controller.rb b/plugins/discourse-rewind/app/controllers/discourse_rewind/rewinds_controller.rbindex aab6bc9feee..3647c6137ea 100644--- a/plugins/discourse-rewind/app/controllers/discourse_rewind/rewinds_controller.rb+++ b/plugins/discourse-rewind/app/controllers/discourse_rewind/rewinds_controller.rb@@ -14,60 +14,34 @@ module ::DiscourseRewinddef indexDiscourseRewind::FetchReports.call(service_params) do- on_model_not_found(:for_user) do- raise Discourse::NotFound.new(nil, custom_message: "discourse_rewind.user_not_found")- end- on_model_not_found(:year) do- raise Discourse::NotFound.new(nil, custom_message: "discourse_rewind.invalid_year")- end- on_model_not_found(:all_reports) do- raise Discourse::NotFound.new(nil, custom_message: "discourse_rewind.report_failed")- end- on_success do |reports:, total_available:|- render json: { reports:, total_available: }, status: :ok- end- end- end-- def show- DiscourseRewind::FetchReport.call(service_params) do- on_model_not_found(:for_user) do- raise Discourse::NotFound.new(nil, custom_message: "discourse_rewind.user_not_found")- end- on_model_not_found(:year) do- raise Discourse::NotFound.new(nil, custom_message: "discourse_rewind.invalid_year")- end- on_model_not_found(:all_reports) do- raise Discourse::NotFound.new(nil, custom_message: "discourse_rewind.reports_not_cached")- end- on_model_not_found(:report) do- raise Discourse::NotFound.new(nil, custom_message: "discourse_rewind.report_not_found")- end+ on_model_not_found(:for_user) { raise_not_found("user_not_found") }+ on_model_not_found(:year) { raise_not_found("invalid_year") }on_failed_contract do |contract|render json: failed_json.merge(errors: contract.errors.full_messages),status: :bad_requestendon_failure { render(json: failed_json, status: :unprocessable_entity) }- on_success { |report:| render json: { report: }, status: :ok }+ on_success { |reports:, total_available:| render json: { reports:, total_available: } }endenddef toggle_shareDiscourseRewind::ToggleShare.call(service_params) do- on_success do |shared:|- render json: {- shared: guardian.user.reload.user_option.discourse_rewind_share_publicly,- },- status: :ok- end+ on_success { |shared:| render json: { shared: } }on_failure { render(json: failed_json, status: :unprocessable_entity) }on_failed_policy(:user_not_hiding_profile) dorender_json_error(I18n.t("discourse_rewind.cannot_share_when_profile_hidden"),- status: 400,+ status: :bad_request,)endendend++ private++ def raise_not_found(key)+ raise Discourse::NotFound.new(nil, custom_message: "discourse_rewind.#{key}")+ endendenddiff --git a/plugins/discourse-rewind/app/services/discourse_rewind/action/ai_usage.rb b/plugins/discourse-rewind/app/services/discourse_rewind/action/ai_usage.rbindex 1e0cef43d18..9926d4a1b90 100644--- a/plugins/discourse-rewind/app/services/discourse_rewind/action/ai_usage.rb+++ b/plugins/discourse-rewind/app/services/discourse_rewind/action/ai_usage.rb@@ -92,6 +92,12 @@ module DiscourseRewinddef enabled?Discourse.plugins_by_name["discourse-ai"]&.enabled?end++ def self.filter_for_viewer(report, guardian:, for_user:)+ return report if guardian.is_me?(for_user) || guardian.is_admin?++ report.merge(data: report[:data].except(:model_usage))+ endendendenddiff --git a/plugins/discourse-rewind/app/services/discourse_rewind/action/base_report.rb b/plugins/discourse-rewind/app/services/discourse_rewind/action/base_report.rbindex 618afb45030..e62d35fbfc7 100644--- a/plugins/discourse-rewind/app/services/discourse_rewind/action/base_report.rb+++ b/plugins/discourse-rewind/app/services/discourse_rewind/action/base_report.rb@@ -18,6 +18,10 @@ module DiscourseRewindPost.visible.merge(publicly_visible_topics).where.not(post_type: Post.types[:whisper])end+ def self.filter_for_viewer(report, **)+ report+ end+def self.enabled?trueenddiff --git a/plugins/discourse-rewind/app/services/discourse_rewind/action/best_posts.rb b/plugins/discourse-rewind/app/services/discourse_rewind/action/best_posts.rbindex bd2e76b04a9..f719011a234 100644--- a/plugins/discourse-rewind/app/services/discourse_rewind/action/best_posts.rb+++ b/plugins/discourse-rewind/app/services/discourse_rewind/action/best_posts.rb@@ -36,18 +36,14 @@ module DiscourseRewindreturn FakeData if should_use_fake_data?best_posts =- Post- .public_posts- .visible- .joins(topic: :category)- .where(user_id: user.id)- .where(posts: { created_at: date, deleted_at: nil })+ self+ .class+ .publicly_visible_posts+ .where(user_id: user.id, created_at: date).where("post_number > 1")- .where("NOT categories.read_restricted")- .where.not(post_type: Post.types[:whisper])- .order("like_count DESC NULLS LAST, posts.created_at ASC")+ .order("posts.like_count DESC NULLS LAST, posts.created_at ASC").limit(3)- .select(:post_number, :topic_id, :like_count, :reply_count, :raw, :cooked)+ .select(:post_number, :topic_id, :like_count, :reply_count, :cooked).map do |post|{post_number: post.post_number,@@ -61,6 +57,22 @@ module DiscourseRewind{ data: best_posts, identifier: "best-posts" }end++ def self.filter_for_viewer(report, guardian:, **)+ topic_ids = guardian.can_see_topic_ids(topic_ids: report[:data].pluck(:topic_id))+ eligible_post_keys =+ publicly_visible_posts.where(+ topic_id: topic_ids,+ post_number: report[:data].pluck(:post_number),+ ).pluck(:topic_id, :post_number)++ report.merge(+ data:+ report[:data].select do |post|+ [post[:topic_id], post[:post_number]].in?(eligible_post_keys)+ end,+ )+ endendendenddiff --git a/plugins/discourse-rewind/app/services/discourse_rewind/action/best_topics.rb b/plugins/discourse-rewind/app/services/discourse_rewind/action/best_topics.rbindex 85f16cfecbe..d5aa6755383 100644--- a/plugins/discourse-rewind/app/services/discourse_rewind/action/best_topics.rb+++ b/plugins/discourse-rewind/app/services/discourse_rewind/action/best_topics.rb@@ -9,19 +9,16 @@ module DiscourseRewindtopic_id: 1,title: "How to get started with Rails",excerpt: "A comprehensive guide to getting started with Ruby on Rails...",- yearly_score: 42.5,},{topic_id: 2,title: ":file_cabinet: Best practices for database optimization",excerpt: "Learn how to optimize your database queries for better performance...",- yearly_score: 38.2,},{topic_id: 3,title: "Understanding ActiveRecord associations",excerpt: "Deep dive into has_many, belongs_to, and other associations...",- yearly_score: 35.7,},],identifier: "best-topics",@@ -32,21 +29,25 @@ module DiscourseRewindbest_topics =TopTopic- .includes(:topic)- .references(:topic)- .joins(topic: :category)- .where(topic: { deleted_at: nil, created_at: date, user_id: user.id, visible: true })- .where.not(topic: { archetype: Archetype.private_message })- .where("NOT categories.read_restricted")+ .joins(:topic)+ .merge(self.class.publicly_visible_topics)+ .where(topics: { created_at: date, user_id: user.id }).order("yearly_score DESC NULLS LAST, top_topics.topic_id").limit(3)- .pluck(:topic_id, :title, :excerpt, :yearly_score)- .map do |topic_id, title, excerpt, yearly_score|- { topic_id: topic_id, title: title, excerpt: excerpt, yearly_score: yearly_score }- end+ .pluck(:topic_id, :title, :excerpt)+ .map { |topic_id, title, excerpt| { topic_id:, title:, excerpt: } }{ data: best_topics, identifier: "best-topics" }end++ def self.filter_for_viewer(report, guardian:, **)+ topic_ids = guardian.can_see_topic_ids(topic_ids: report[:data].pluck(:topic_id))+ eligible_topic_ids = publicly_visible_topics.where(id: topic_ids).pluck(:id)++ report.merge(+ data: report[:data].select { |topic| topic[:topic_id].in?(eligible_topic_ids) },+ )+ endendendenddiff --git a/plugins/discourse-rewind/app/services/discourse_rewind/action/invites.rb b/plugins/discourse-rewind/app/services/discourse_rewind/action/invites.rbindex 84454a7c2a2..772e6b22317 100644--- a/plugins/discourse-rewind/app/services/discourse_rewind/action/invites.rb+++ b/plugins/discourse-rewind/app/services/discourse_rewind/action/invites.rb@@ -96,6 +96,10 @@ module DiscourseRewindidentifier: "invites",}end++ def self.filter_for_viewer(report, guardian:, for_user:)+ report if guardian.can_see_invite_details?(for_user)+ endendendenddiff --git a/plugins/discourse-rewind/app/services/discourse_rewind/fetch_report.rb b/plugins/discourse-rewind/app/services/discourse_rewind/fetch_report.rbdeleted file mode 100644index 42e5672cf37..00000000000--- a/plugins/discourse-rewind/app/services/discourse_rewind/fetch_report.rb+++ /dev/null@@ -1,120 +0,0 @@-# frozen_string_literal: true--module DiscourseRewind- # Service responsible to fetch a single report by index.- #- # NOTE: When changing any report implementations, please- # also update FetchReportsHelper::REWIND_REPORT_VERSION- # to invalidate caches.- #- # @example- # ::DiscourseRewind::FetchReport.call(- # guardian: guardian,- # params: { index: 3, for_user_username: 'codinghorror' }- # )- #- class FetchReport- include Service::Base- include DiscourseRewind::FetchReportsHelper-- # @!method self.call(guardian:, params:)- # @param [Guardian] guardian- # @param [Hash] params- # @option params [Integer] :index of the report- # @option params [String] :for_user_username (optional) username of the user to see the rewind for, otherwise the guardian user is used- # @return [Service::Base::Context]-- params do- attribute :index, :integer- attribute :for_user_username, :string-- validates :index, presence: true, numericality: { greater_than_or_equal_to: 0 }- end-- model :for_user # see FetchReportsHelper#fetch_for_user- model :year # see FetchReportsHelper#fetch_year- model :date- model :report-- private-- def fetch_date(params:, year:)- Time.zone.local(year).all_year- end-- def fetch_report(params:, for_user:, year:, date:, guardian:)- report_class = FetchReports::REPORTS[params.index]- return if !report_class-- report_name = report_class.name.demodulize- report = load_single_report_from_cache(for_user.id, year, report_name)- if !report- report = report_class.call(date:, user: for_user)- cache_single_report(for_user.id, year, report_name, report.as_json)- end-- return report if !report || !report_class.in?(FetchReports::VISIBILITY_FILTERED_REPORTS)-- filter_report_for_viewer(report, guardian, for_user, report_class)- end-- def filter_report_for_viewer(report, guardian, for_user, report_class)- case report_class.name- when Action::BestTopics.name- filter_best_topics_for_viewer(report, guardian)- when Action::BestPosts.name- filter_best_posts_for_viewer(report, guardian)- when Action::AiUsage.name- filter_ai_usage_for_viewer(report, guardian, for_user)- when Action::Invites.name- report if guardian.can_see_invite_details?(for_user)- end- end-- def filter_ai_usage_for_viewer(report, guardian, for_user)- return report if guardian.is_me?(for_user) || guardian.is_admin?-- report.merge(data: report[:data].except(:model_usage))- end-- def filter_best_topics_for_viewer(report, guardian)- topic_ids = report[:data].pluck(:topic_id)- visible_topic_ids = guardian.can_see_topic_ids(topic_ids:)- eligible_topic_ids =- Topic- .visible- .where(id: visible_topic_ids, deleted_at: nil)- .where.not(archetype: Archetype.private_message)- .joins(:category)- .where("NOT categories.read_restricted")- .pluck(:id)-- report.merge(data: report[:data].select { |topic| topic[:topic_id].in?(eligible_topic_ids) })- end-- def filter_best_posts_for_viewer(report, guardian)- topic_ids = report[:data].pluck(:topic_id)- visible_topic_ids = guardian.can_see_topic_ids(topic_ids:)- eligible_post_keys =- Post- .public_posts- .visible- .joins(topic: :category)- .where(- topic_id: visible_topic_ids,- post_number: report[:data].pluck(:post_number),- deleted_at: nil,- )- .where("NOT categories.read_restricted")- .where.not(post_type: Post.types[:whisper])- .pluck(:topic_id, :post_number)-- report.merge(- data:- report[:data].select do |post|- [post[:topic_id], post[:post_number]].in?(eligible_post_keys)- end,- )- end- end-enddiff --git a/plugins/discourse-rewind/app/services/discourse_rewind/fetch_reports.rb b/plugins/discourse-rewind/app/services/discourse_rewind/fetch_reports.rbindex 21005174f61..8ee17efd248 100644--- a/plugins/discourse-rewind/app/services/discourse_rewind/fetch_reports.rb+++ b/plugins/discourse-rewind/app/services/discourse_rewind/fetch_reports.rb@@ -1,37 +1,33 @@# frozen_string_literal: truemodule DiscourseRewind- # Service responsible to fetch a rewind for a username/year.+ # Service responsible to fetch a page of the reports of a rewind.## @example- # ::DiscourseRewind::Rewind::Fetch.call(+ # ::DiscourseRewind::FetchReports.call(# guardian: guardian,- # params: { for_user_username: 'codinghorror' }+ # params: { for_user_username: 'codinghorror', offset: 3 }# )#class FetchReportsinclude Service::Base- include DiscourseRewind::FetchReportsHelper# @!method self.call(guardian:, params:)# @param [Guardian] guardian# @param [Hash] params# @option params [String] :for_user_username (optional) username of the user to see the rewind for, otherwise the guardian user is used+ # @option params [Integer] :offset (optional) position of the first report of the page, defaults to 0# @return [Service::Base::Context]- INITIAL_REPORT_COUNT = 3- VISIBILITY_FILTERED_REPORTS = [- Action::BestTopics,- Action::BestPosts,- Action::AiUsage,- Action::Invites,- ].freeze+ PAGE_SIZE = 3+ REWIND_REPORT_VERSION = "3"+ CACHE_DURATION = Rails.env.development? ? 10.seconds : 3.days# The order here controls the order of reports in the UI,# so be careful when moving these around.## NOTE: When changing any report implementations, please- # also update FetchReportsHelper::REWIND_REPORT_VERSION+ # also update REWIND_REPORT_VERSION# to invalidate caches.REPORTS = [Action::TopWords,@@ -52,40 +48,66 @@ module DiscourseRewindAction::Invites,]- params { attribute :for_user_username, :string }+ params do+ attribute :for_user_username, :string+ attribute :offset, :integer, default: 0- model :for_user # see FetchReportsHelper#fetch_for_user- model :year # see FetchReportsHelper#fetch_year- model :date+ validates :offset,+ numericality: {+ greater_than_or_equal_to: 0,+ less_than: ->(_) { REPORTS.size },+ }+ end++ model :for_user+ model :yearmodel :reportsmodel :total_availableprivate- def fetch_date(params:, year:)- Time.zone.local(year).all_year- end+ def fetch_for_user(guardian:, params:)+ return guardian.user if params.for_user_username.blank?++ user = User.find_by_username(params.for_user_username)+ return if !user- def fetch_reports(date:, for_user:, year:)- reports = load_reports_from_cache(for_user.id, year)-- if !reports- reports =- REPORTS- .first(INITIAL_REPORT_COUNT)- .filter_map do |report|- report.call(date:, user: for_user)- rescue StandardError- nil- end- cache_reports(for_user.id, year, reports)+ if guardian.is_me?(user) || guardian.is_admin? || user.discourse_rewind_and_profile_public?+ userend+ end++ def fetch_year+ DiscourseRewind.rewind_year if DiscourseRewind.rewind_period?+ end- reports+ def fetch_reports(params:, for_user:, year:, guardian:)+ REPORTS[params.offset, PAGE_SIZE].map do |report_class|+ fetch_report(report_class, for_user:, year:, guardian:)+ endenddef fetch_total_availableREPORTS.sizeend++ def fetch_report(report_class, for_user:, year:, guardian:)+ name = report_class.name.demodulize+ key = "rewind:#{for_user.id}:#{year}:#{name}:v#{REWIND_REPORT_VERSION}"+ report =+ Discourse+ .cache+ .fetch(key, expires_in: CACHE_DURATION) do+ report_class.call(date: Time.zone.local(year).all_year, user: for_user)+ rescue StandardError => e+ Discourse.warn_exception(e, message: "Rewind report #{name} failed")+ return+ end++ return if report&.dig(:data).blank?++ report = report_class.filter_for_viewer(report, guardian:, for_user:)+ report if report&.dig(:data).present?+ endendenddiff --git a/plugins/discourse-rewind/assets/javascripts/discourse/components/rewind.gjs b/plugins/discourse-rewind/assets/javascripts/discourse/components/rewind.gjsindex e97090dc517..725ee9a3aba 100644--- a/plugins/discourse-rewind/assets/javascripts/discourse/components/rewind.gjs+++ b/plugins/discourse-rewind/assets/javascripts/discourse/components/rewind.gjs@@ -1,19 +1,21 @@import Component from "@glimmer/component";import { tracked } from "@glimmer/tracking";+import { get } from "@ember/helper";import { on } from "@ember/modifier";import { action } from "@ember/object";import didInsert from "@ember/render-modifiers/modifiers/did-insert";-import willDestroy from "@ember/render-modifiers/modifiers/will-destroy";import { service } from "@ember/service";import { trustHTML } from "@ember/template";+import { modifier } from "ember-modifier";import { ajax } from "discourse/lib/ajax";import { popupAjaxError } from "discourse/lib/ajax-error";import { getAbsoluteURL } from "discourse/lib/get-url";import { clipboardCopy } from "discourse/lib/utilities";-import { eq } from "discourse/truth-helpers";import DButton from "discourse/ui-kit/d-button";+import DLoadMore from "discourse/ui-kit/d-load-more";import DToggleSwitch from "discourse/ui-kit/d-toggle-switch";import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";+import dLoadingSpinner from "discourse/ui-kit/helpers/d-loading-spinner";import { i18n } from "discourse-i18n";import ActivityCalendar from "discourse/plugins/discourse-rewind/discourse/components/reports/activity-calendar";import AiUsage from "discourse/plugins/discourse-rewind/discourse/components/reports/ai-usage";@@ -21,7 +23,6 @@ import Assignments from "discourse/plugins/discourse-rewind/discourse/componentsimport BestPosts from "discourse/plugins/discourse-rewind/discourse/components/reports/best-posts";import BestTopics from "discourse/plugins/discourse-rewind/discourse/components/reports/best-topics";import ChatUsage from "discourse/plugins/discourse-rewind/discourse/components/reports/chat-usage";-// import FavoriteGifs from "discourse/plugins/discourse-rewind/discourse/components/reports/favorite-gifs";import FBFF from "discourse/plugins/discourse-rewind/discourse/components/reports/fbff";import RewindHeader from "discourse/plugins/discourse-rewind/discourse/components/reports/header";import Invites from "discourse/plugins/discourse-rewind/discourse/components/reports/invites";@@ -34,56 +35,65 @@ import TimeOfDayActivity from "discourse/plugins/discourse-rewind/discourse/compimport TopWords from "discourse/plugins/discourse-rewind/discourse/components/reports/top-words";import WritingAnalysis from "discourse/plugins/discourse-rewind/discourse/components/reports/writing-analysis";-const BUFFER_SIZE = 3;-const SCROLL_THRESHOLD = 0.7;+const REPORT_COMPONENTS = {+ "activity-calendar": ActivityCalendar,+ "ai-usage": AiUsage,+ assignments: Assignments,+ "best-posts": BestPosts,+ "best-topics": BestTopics,+ "chat-usage": ChatUsage,+ fbff: FBFF,+ invites: Invites,+ "most-viewed-categories": MostViewedCategories,+ "most-viewed-tags": MostViewedTags,+ "new-user-interactions": NewUserInteractions,+ reactions: Reactions,+ "reading-time": ReadingTime,+ "time-of-day-activity": TimeOfDayActivity,+ "top-words": TopWords,+ "writing-analysis": WritingAnalysis,+};export default class Rewind extends Component {- @service dialog;@service currentUser;+ @service dialog;@service toasts;- @tracked rewind = [];- @tracked fullScreen = this.currentUser !== null;+ @tracked cannotViewRewind = false;+ @tracked fullScreen = true;+ @tracked isLoadingMore = false;@tracked loadingRewind = false;+ @tracked nextOffset = 0;+ @tracked rewind = [];+ @tracked scrollWrapper = null;@tracked totalAvailable = 0;- @tracked isLoadingMore = false;- @tracked cannotViewRewind = false;- nextReportIndex = 0;- get canShare() {- return this.currentUser.id === this.args.user.id;- }+ registerScrollWrapper = modifier((element) => {+ this.scrollWrapper = element;+ return () => (this.scrollWrapper = null);+ });get isOwnRewind() {- return this.currentUser?.id === this.args.user.id;+ return this.currentUser.id === this.args.user.id;}- @action- registerScrollWrapper(element) {- this.scrollWrapper = element;- this.scrollWrapper.addEventListener("scroll", this.handleScroll);+ get #userParams() {+ return this.isOwnRewind+ ? {}+ : { for_user_username: this.args.user.username };}- @action- cleanup() {- this.scrollWrapper?.removeEventListener("scroll", this.handleScroll);+ get hasMoreReports() {+ return this.nextOffset < this.totalAvailable;}@actionasync loadRewind() {- let url = "/rewinds.json";- if (this.args.user.id !== this.currentUser.id) {- url += `?for_user_username=${this.args.user.username}`;- }-try {this.loadingRewind = true;- const response = await ajax(url);- this.rewind = response.reports;- this.totalAvailable = response.total_available;- this.nextReportIndex = response.reports.length;+ await this.#loadReports();} catch (err) {- if (err.jqXHR.status === 404 || err.jqXHR.status === 403) {+ if (err.jqXHR?.status === 404 || err.jqXHR?.status === 403) {this.cannotViewRewind = true;} else {popupAjaxError(err);@@ -91,73 +101,24 @@ export default class Rewind extends Component {} finally {this.loadingRewind = false;}-- // Load more if content fits on screen without scrolling- this.checkIfMoreContentNeeded();- }-- checkIfMoreContentNeeded() {- if (!this.scrollWrapper || this.nextReportIndex >= this.totalAvailable) {- return;- }-- const { scrollHeight, clientHeight } = this.scrollWrapper;- if (scrollHeight <= clientHeight) {- this.preloadNextReports();- }}@action- handleScroll() {- if (this.isLoadingMore || this.nextReportIndex >= this.totalAvailable) {- return;- }-- const { scrollTop, scrollHeight, clientHeight } = this.scrollWrapper;- const scrollProgress = (scrollTop + clientHeight) / scrollHeight;-- if (scrollProgress > SCROLL_THRESHOLD) {- this.preloadNextReports();- }- }-- async preloadNextReports() {- if (this.nextReportIndex >= this.totalAvailable) {+ async loadMoreReports() {+ if (this.isLoadingMore) {return;}- const targetIndex = Math.min(- this.nextReportIndex + BUFFER_SIZE,- this.totalAvailable- );-this.isLoadingMore = true;try {- while (this.nextReportIndex < targetIndex) {- let url = `/rewinds/${this.nextReportIndex}.json`;- if (this.args.user.id !== this.currentUser.id) {- url += `?for_user_username=${this.args.user.username}`;- }-- try {- const response = await ajax(url, {- ignoreUnsent: false,- });- if (response.report) {- this.rewind = [...this.rewind, response.report];- }- } catch {- // Skip failed reports and continue loading- }- this.nextReportIndex++;- }+ await this.#loadReports();+ } catch (err) {+ this.totalAvailable = this.nextOffset;+ popupAjaxError(err);} finally {this.isLoadingMore = false;}-- // Re-check in case we need more content (failed reports or content fits on screen)- this.checkIfMoreContentNeeded();}@action@@ -181,27 +142,7 @@ export default class Rewind extends Component {@actionasync toggleShareRewind() {if (this.currentUser.user_option.discourse_rewind_share_publicly) {- try {- const response = await ajax("/rewinds/toggle-share", {- type: "PUT",- });-- this.currentUser.set(- "user_option.discourse_rewind_share_publicly",- response.shared- );-- this.toasts.success({- duration: "short",- data: {- message: i18n("discourse_rewind.share.disabled_success"),- },- });- } catch (err) {- popupAjaxError(err);- return;- }-+ await this.#toggleShare("discourse_rewind.share.disabled_success");return;}@@ -209,26 +150,8 @@ export default class Rewind extends Component {message: i18n("discourse_rewind.share.confirm"),confirmButtonLabel: "discourse_rewind.share.confirm_button.enable",cancelButtonLabel: "discourse_rewind.share.confirm_button.disable",- didConfirm: async () => {- try {- const response = await ajax("/rewinds/toggle-share", {- type: "PUT",- });- this.currentUser.set(- "user_option.discourse_rewind_share_publicly",- response.shared- );-- this.toasts.success({- duration: "short",- data: {- message: i18n("discourse_rewind.share.enabled_success"),- },- });- } catch (err) {- popupAjaxError(err);- }- },+ didConfirm: () =>+ this.#toggleShare("discourse_rewind.share.enabled_success"),});}@@ -246,49 +169,28 @@ export default class Rewind extends Component {}}- @action- registerRewindContainer(element) {- this.rewindContainer = element;+ async #loadReports() {+ const response = await ajax("/rewinds.json", {+ data: { ...this.#userParams, offset: this.nextOffset },+ });+ this.rewind = [...this.rewind, ...response.reports.filter(Boolean)];+ this.totalAvailable = response.total_available;+ this.nextOffset += response.reports.length;}- getReportComponent(identifier) {- switch (identifier) {- case "fbff":- return FBFF;- case "reactions":- return Reactions;- case "top-words":- return TopWords;- case "best-posts":- return BestPosts;- case "best-topics":- return BestTopics;- case "activity-calendar":- return ActivityCalendar;- case "most-viewed-tags":- return MostViewedTags;- case "reading-time":- return ReadingTime;- case "most-viewed-categories":- return MostViewedCategories;- case "ai-usage":- return AiUsage;- case "assignments":- return Assignments;- case "chat-usage":- return ChatUsage;- // case "favorite-gifs":- // return FavoriteGifs;- case "invites":- return Invites;- case "new-user-interactions":- return NewUserInteractions;- case "time-of-day-activity":- return TimeOfDayActivity;- case "writing-analysis":- return WritingAnalysis;- default:- return null;+ async #toggleShare(successMessageKey) {+ try {+ const response = await ajax("/rewinds/toggle-share", { type: "PUT" });+ this.currentUser.set(+ "user_option.discourse_rewind_share_publicly",+ response.shared+ );+ this.toasts.success({+ duration: "short",+ data: { message: i18n(successMessageKey) },+ });+ } catch (err) {+ popupAjaxError(err);}}@@ -302,20 +204,19 @@ export default class Rewind extends Component {{{didInsert this.loadRewind}}{{on "keydown" this.handleEscape}}{{on "click" this.handleBackdropClick}}- {{didInsert this.registerRewindContainer}}><div class="rewind"><RewindHeader />{{#if this.loadingRewind}}<div class="rewind-loader">- <div class="spinner small"></div>+ {{dLoadingSpinner size="small"}}<div class="rewind-loader__text">{{i18n "discourse_rewind.loading"}}</div></div>{{else}}<div class="rewind__header-buttons">- {{#if this.canShare}}+ {{#if this.isOwnRewind}}<div class="rewind__share-toggle-wrapper">{{i18n "discourse_rewind.share.toggle_label.private"}}@@ -350,12 +251,8 @@ export default class Rewind extends Component {</div>- <div- class="rewind__scroll-wrapper"- {{didInsert this.registerScrollWrapper}}- {{willDestroy this.cleanup}}- >- {{#unless (eq this.currentUser.id @user.id)}}+ <div class="rewind__scroll-wrapper" {{this.registerScrollWrapper}}>+ {{#unless this.isOwnRewind}}<p class="rewind-other-user">{{trustHTML(i18n"discourse_rewind.viewing_other_user"@@ -386,7 +283,7 @@ export default class Rewind extends Component {{{#each this.rewind as |report|}}{{#let- (this.getReportComponent report.identifier)+ (get REPORT_COMPONENTS report.identifier)as |ReportComponent|}}{{#if ReportComponent}}@@ -401,28 +298,19 @@ export default class Rewind extends Component {{{/let}}{{/each}}+ <DLoadMore+ @action={{this.loadMoreReports}}+ @enabled={{this.hasMoreReports}}+ @isLoading={{this.isLoadingMore}}+ @root={{this.scrollWrapper}}+ />+{{#if this.isLoadingMore}}<div class="rewind-loader --more">- <div class="spinner small"></div>+ {{dLoadingSpinner size="small"}}</div>{{/if}}</div>-- {{#if this.showPrev}}- <DButton- class="rewind__prev-btn"- @action={{this.prev}}- @icon="chevron-left"- />- {{/if}}-- {{#if this.showNext}}- <DButton- class="rewind__next-btn"- @action={{this.next}}- @icon="chevron-right"- />- {{/if}}{{/if}}</div></div>diff --git a/plugins/discourse-rewind/config/locales/server.en.yml b/plugins/discourse-rewind/config/locales/server.en.ymlindex 77f3195af9e..7a4738efbc5 100644--- a/plugins/discourse-rewind/config/locales/server.en.yml+++ b/plugins/discourse-rewind/config/locales/server.en.yml@@ -2,9 +2,6 @@ en:site_settings:discourse_rewind_enabled: "Enable Discourse Rewind for a fun end-of-year summary for members' activity in the community."discourse_rewind:- report_failed: "Failed to generate Discourse Rewind report."invalid_year: "Rewind can only be generated in January or December."user_not_found: "User not found or cannot be viewed."- reports_not_cached: "Reports have not been generated yet. Please refresh the page."- report_not_found: "Report not found."cannot_share_when_profile_hidden: "In order to share Rewind you must allow others to view your public profile."diff --git a/plugins/discourse-rewind/config/routes.rb b/plugins/discourse-rewind/config/routes.rbindex 1acc14fa87b..c300ba02d9a 100644--- a/plugins/discourse-rewind/config/routes.rb+++ b/plugins/discourse-rewind/config/routes.rb@@ -2,7 +2,6 @@DiscourseRewind::Engine.routes.draw doget "/rewinds" => "rewinds#index"- get "/rewinds/:index" => "rewinds#show"put "/rewinds/toggle-share" => "rewinds#toggle_share"post "/rewinds/dismiss" => "rewinds#dismiss"enddiff --git a/plugins/discourse-rewind/lib/discourse_rewind/fetch_reports_helper.rb b/plugins/discourse-rewind/lib/discourse_rewind/fetch_reports_helper.rbdeleted file mode 100644index 2d401c13857..00000000000--- a/plugins/discourse-rewind/lib/discourse_rewind/fetch_reports_helper.rb+++ /dev/null@@ -1,79 +0,0 @@-# frozen_string_literal: true--module DiscourseRewind- module FetchReportsHelper- extend self-- REWIND_REPORT_VERSION = "3"- CACHE_DURATION = Rails.env.development? ? 10.seconds : 3.days-- def cache_key(user_id, year)- "rewind:#{user_id}:#{year}:v#{REWIND_REPORT_VERSION}"- end-- def single_report_cache_key(user_id, year, name)- "rewind:#{user_id}:#{year}:#{name}:v#{REWIND_REPORT_VERSION}"- end-- def load_reports_from_cache(user_id, year)- reports = Discourse.redis.get(cache_key(user_id, year))- return nil if !reports- MultiJson.load(reports, symbolize_keys: true)- end-- def load_single_report_from_cache(user_id, year, name)- report = Discourse.redis.get(single_report_cache_key(user_id, year, name))- return nil if !report- MultiJson.load(report, symbolize_keys: true)- end-- # NOTE: This only caches the first INITIAL_REPORT_COUNT reports.- def cache_reports(user_id, year, reports)- Discourse.redis.setex(cache_key(user_id, year), CACHE_DURATION, MultiJson.dump(reports))- end-- def cache_single_report(user_id, year, name, report)- Discourse.redis.setex(- single_report_cache_key(user_id, year, name),- CACHE_DURATION,- MultiJson.dump(report),- )- end-- def fetch_for_user(guardian:, params:)- return guardian.user if params.for_user_username.blank?-- user = User.find_by(username: params.for_user_username)- return if user.nil?-- if guardian.user.id != user.id- if !user.discourse_rewind_and_profile_public?- return if !guardian.user.admin?- end- end-- user- end-- def fetch_year- current_date = Time.zone.now- current_month = current_date.month- current_year = current_date.year-- case current_month- when 1- current_year - 1- when 12- current_year- else- # Otherwise it's impossible to test in browser locally unless you're- # in December or January- if Rails.env.development?- current_year- else- nil- end- end- end- end-enddiff --git a/plugins/discourse-rewind/plugin.rb b/plugins/discourse-rewind/plugin.rbindex 30bf4be9e7d..b3455f46640 100644--- a/plugins/discourse-rewind/plugin.rb+++ b/plugins/discourse-rewind/plugin.rb@@ -28,6 +28,10 @@ module ::DiscourseRewinddate ||= Time.zone.nowdate.month == 1 ? date.year - 1 : date.yearend++ def self.rewind_period?+ Rails.env.development? || Time.zone.now.month.in?([1, 12])+ endendrequire_relative "lib/discourse_rewind/engine"@@ -58,9 +62,7 @@ after_initialize doendadd_to_serializer(:current_user, :is_rewind_active) do- is_rewind_period = Rails.env.development? || Date.today.month == 1 || Date.today.month == 12- user_old_enough = scope.user.created_at <= 1.month.ago- is_rewind_period && user_old_enough+ DiscourseRewind.rewind_period? && scope.user.created_at <= 1.month.agoendDiscourse::Application.routes.append dodiff --git a/plugins/discourse-rewind/spec/actions/ai_usage_spec.rb b/plugins/discourse-rewind/spec/actions/ai_usage_spec.rbnew file mode 100644index 00000000000..5ee60434f61--- /dev/null+++ b/plugins/discourse-rewind/spec/actions/ai_usage_spec.rb@@ -0,0 +1,32 @@+# frozen_string_literal: true++RSpec.describe DiscourseRewind::Action::AiUsage do+ fab!(:user)++ before { SiteSetting.discourse_ai_enabled = true }++ describe ".filter_for_viewer" do+ let(:report) do+ { data: { total_requests: 1, model_usage: [{ name: "secret-model", count: 1 }] } }+ end++ it "hides the models from other users" do+ filtered =+ described_class.filter_for_viewer(+ report,+ guardian: Fabricate(:user).guardian,+ for_user: user,+ )++ expect(filtered[:data]).to eq(total_requests: 1)+ end++ it "shows the models to the owner and admins" do+ [user, Fabricate(:admin)].each do |viewer|+ expect(+ described_class.filter_for_viewer(report, guardian: viewer.guardian, for_user: user),+ ).to eq(report)+ end+ end+ end+enddiff --git a/plugins/discourse-rewind/spec/actions/best_posts_spec.rb b/plugins/discourse-rewind/spec/actions/best_posts_spec.rbindex 3af81d8eb26..981df9aab2d 100644--- a/plugins/discourse-rewind/spec/actions/best_posts_spec.rb+++ b/plugins/discourse-rewind/spec/actions/best_posts_spec.rb@@ -1,7 +1,6 @@# frozen_string_literal: trueRSpec.describe DiscourseRewind::Action::BestPosts do- fab!(:date) { Date.new(2021).all_year }fab!(:user)fab!(:post_1) { Fabricate(:post, created_at: random_datetime, user: user, post_number: 3) }fab!(:post_2) { Fabricate(:post, created_at: random_datetime, user: user, post_number: 2) }@@ -18,139 +17,52 @@ RSpec.describe DiscourseRewind::Action::BestPosts dopost_5.update!(like_count: 7)expect(call_report[:data]).to eq(- [+ [post_4, post_3, post_1].map do |post|{- post_number: post_4.post_number,- topic_id: post_4.topic_id,- like_count: post_4.like_count,- reply_count: post_4.reply_count,- excerpt:- post_4.excerpt(200, { strip_links: true, remap_emoji: true, keep_images: true }),- },- {- post_number: post_3.post_number,- topic_id: post_3.topic_id,- like_count: post_3.like_count,- reply_count: post_3.reply_count,- excerpt:- post_3.excerpt(200, { strip_links: true, remap_emoji: true, keep_images: true }),- },- {- post_number: post_1.post_number,- topic_id: post_1.topic_id,- like_count: post_1.like_count,- reply_count: post_1.reply_count,- excerpt:- post_1.excerpt(200, { strip_links: true, remap_emoji: true, keep_images: true }),- },- ],+ post_number: post.post_number,+ topic_id: post.topic_id,+ like_count: post.like_count,+ reply_count: post.reply_count,+ excerpt: post.excerpt(200, { strip_links: true, remap_emoji: true, keep_images: true }),+ }+ end,)end- context "when a post is deleted" do- before { post_1.trash!(Discourse.system_user) }-- it "is not included" do- expect(call_report[:data].map { |d| d[:post_number] }).not_to include(post_1.post_number)- end- end-- context "when a post is made by another user" do- before { post_1.update!(user: Fabricate(:user)) }-- it "is not included" do- expect(call_report[:data].map { |d| d[:post_number] }).not_to include(post_1.post_number)- end- end-- context "when a post is in a private message" do- fab!(:pm_topic) { Fabricate(:private_message_topic, user: user) }- fab!(:pm_post) do- Fabricate(- :post,- created_at: random_datetime,- user: user,- post_number: 2,- topic: pm_topic,- like_count: 99,- )- end-- it "is not included" do- expect(call_report[:data].map { |d| d[:topic_id] }).not_to include(pm_topic.id)- end- end-- context "when a post is in a private category" do- fab!(:private_category) { Fabricate(:category, read_restricted: true) }- fab!(:private_topic) { Fabricate(:topic, category: private_category, user: user) }- fab!(:private_category_post) do- Fabricate(- :post,- created_at: random_datetime,- user: user,- post_number: 2,- topic: private_topic,- like_count: 99,- )- end-- it "is not included" do- expect(call_report[:data].map { |d| d[:topic_id] }).not_to include(private_topic.id)- end- end+ it "only includes the user's publicly visible posts" do+ post_1.update!(user: Fabricate(:user))+ post_2.update!(topic: Fabricate(:private_message_topic, user:))- context "when public content is hidden from normal viewers" do- fab!(:public_category, :category)- fab!(:hidden_post_topic) { Fabricate(:topic, user: user, category: public_category) }- fab!(:hidden_post) do- Fabricate(- :post,- created_at: random_datetime,- user: user,- post_number: 2,- topic: hidden_post_topic,- hidden: true,- like_count: 99,- )- end- fab!(:unlisted_topic) do- Fabricate(:topic, user: user, category: public_category, visible: false)- end- fab!(:unlisted_topic_post) do- Fabricate(- :post,- created_at: random_datetime,- user: user,- post_number: 2,- topic: unlisted_topic,- like_count: 98,- )- end-- it "does not include hidden posts or posts in unlisted topics" do- topic_ids = call_report[:data].map { |d| d[:topic_id] }-- expect(topic_ids).not_to include(hidden_post_topic.id)- expect(topic_ids).not_to include(unlisted_topic.id)- end+ expect(call_report[:data].pluck(:topic_id)).to contain_exactly(+ post_3.topic_id,+ post_4.topic_id,+ )end+ end- context "when a post is a whisper" do- fab!(:whisper_post) do- Fabricate(- :post,- created_at: random_datetime,- user: user,- post_number: 2,- post_type: Post.types[:whisper],- like_count: 99,+ describe ".filter_for_viewer" do+ it "only keeps public posts the viewer can see" do+ posts = [+ Fabricate(:post, hidden: true),+ Fabricate(:post, topic: Fabricate(:shared_draft).topic),+ post_1,+ ]+ report = {+ data: posts.map { |post| { topic_id: post.topic_id, post_number: post.post_number } },+ identifier: "best-posts",+ }++ filtered =+ described_class.filter_for_viewer(+ report,+ guardian: Fabricate(:user).guardian,+ for_user: user,)- end- it "is not included" do- expect(call_report[:data].map { |d| d[:topic_id] }).not_to include(whisper_post.topic_id)- end+ expect(filtered[:data]).to contain_exactly(+ topic_id: post_1.topic_id,+ post_number: post_1.post_number,+ )endendenddiff --git a/plugins/discourse-rewind/spec/actions/best_topics_spec.rb b/plugins/discourse-rewind/spec/actions/best_topics_spec.rbindex 9f51a4c2a2d..b3e0715cdb0 100644--- a/plugins/discourse-rewind/spec/actions/best_topics_spec.rb+++ b/plugins/discourse-rewind/spec/actions/best_topics_spec.rb@@ -1,7 +1,6 @@# frozen_string_literal: trueRSpec.describe DiscourseRewind::Action::BestTopics do- fab!(:date) { Date.new(2021).all_year }fab!(:user)fab!(:topic_1) { Fabricate(:topic, user: user, created_at: random_datetime) }fab!(:topic_2) { Fabricate(:topic, user: user, created_at: random_datetime) }@@ -9,100 +8,51 @@ RSpec.describe DiscourseRewind::Action::BestTopics dofab!(:topic_4) { Fabricate(:topic, user: user, created_at: random_datetime) }fab!(:topic_5) { Fabricate(:topic, user: user, created_at: random_datetime) }- before { TopTopic.refresh! }-describe ".call" do- it "returns top 3 topics ordered by yearly_score" do- [topic_1, topic_2, topic_3, topic_4, topic_5].each do |topic|- topic.update!(created_at: random_datetime)- end- TopTopic.refresh!+ before { TopTopic.refresh! }+ it "returns top 3 topics ordered by yearly_score" doTopTopic.find_by(topic_id: topic_1.id).update!(yearly_score: 15)TopTopic.find_by(topic_id: topic_2.id).update!(yearly_score: 10)TopTopic.find_by(topic_id: topic_3.id).update!(yearly_score: 6)TopTopic.find_by(topic_id: topic_4.id).update!(yearly_score: 11)TopTopic.find_by(topic_id: topic_5.id).update!(yearly_score: 13)+expect(call_report[:data]).to eq(- [- {- topic_id: topic_1.id,- title: topic_1.title,- excerpt: topic_1.excerpt,- yearly_score: 15.0,- },- {- topic_id: topic_5.id,- title: topic_5.title,- excerpt: topic_5.excerpt,- yearly_score: 13.0,- },- {- topic_id: topic_4.id,- title: topic_4.title,- excerpt: topic_4.excerpt,- yearly_score: 11.0,- },- ],+ [topic_1, topic_5, topic_4].map do |topic|+ { topic_id: topic.id, title: topic.title, excerpt: topic.excerpt }+ end,)end- context "when a topic is deleted" do- before { topic_1.trash!(Discourse.system_user) }-- it "is not included" do- expect(call_report[:data].map { |d| d[:topic_id] }).not_to include(topic_1.id)- end- end-- context "when a topic is unlisted" do- before do- topic_1.update!(visible: false)- TopTopic.find_by(topic_id: topic_1.id).update!(yearly_score: 99)- end-- it "does not expose the topic title or excerpt" do- topic_ids = call_report[:data].map { |topic| topic[:topic_id] }-- expect(topic_ids).not_to include(topic_1.id)- end- end-- context "when a topic belongs to another user" do- before { topic_1.update!(user: Fabricate(:user)) }+ it "only includes the user's publicly visible topics" do+ topic_1.update!(user: Fabricate(:user))+ topic_2.update!(visible: false)- it "is not included" do- expect(call_report[:data].map { |d| d[:topic_id] }).not_to include(topic_1.id)- end+ expect(call_report[:data].pluck(:topic_id)).to contain_exactly(+ topic_3.id,+ topic_4.id,+ topic_5.id,+ )end+ end- context "when a topic is a private message" do- fab!(:pm_topic) { Fabricate(:private_message_topic, user: user, created_at: random_datetime) }-- before do- TopTopic.refresh!- TopTopic.find_by(topic_id: pm_topic.id)&.update!(yearly_score: 99)- end-- it "is not included" do- expect(call_report[:data].map { |d| d[:topic_id] }).not_to include(pm_topic.id)- end- end+ describe ".filter_for_viewer" do+ fab!(:group)+ fab!(:viewer) { Fabricate(:user).tap { |viewer| group.add(viewer) } }- context "when topic is in a private category" do- fab!(:private_category) { Fabricate(:category, read_restricted: true) }- fab!(:private_topic) do- Fabricate(:topic, category: private_category, user: user, created_at: random_datetime)- end+ it "only keeps public topics the viewer can see" do+ topics = [+ Fabricate(:topic, category: Fabricate(:private_category, group:)),+ Fabricate(:shared_draft).topic,+ topic_1,+ ]+ report = { data: topics.map { |topic| { topic_id: topic.id } }, identifier: "best-topics" }- before do- TopTopic.refresh!- TopTopic.find_by(topic_id: private_topic.id)&.update!(yearly_score: 99)- end+ filtered =+ described_class.filter_for_viewer(report, guardian: viewer.guardian, for_user: user)- it "is not included" do- expect(call_report[:data].map { |d| d[:topic_id] }).not_to include(private_topic.id)- end+ expect(filtered[:data]).to contain_exactly(topic_id: topic_1.id)endendenddiff --git a/plugins/discourse-rewind/spec/actions/invites_spec.rb b/plugins/discourse-rewind/spec/actions/invites_spec.rbnew file mode 100644index 00000000000..de7ff50f1fd--- /dev/null+++ b/plugins/discourse-rewind/spec/actions/invites_spec.rb@@ -0,0 +1,27 @@+# frozen_string_literal: true++RSpec.describe DiscourseRewind::Action::Invites do+ fab!(:user)++ describe ".filter_for_viewer" do+ let(:report) { { data: { total_invites: 1 } } }++ it "hides the invites from other users" do+ expect(+ described_class.filter_for_viewer(+ report,+ guardian: Fabricate(:user).guardian,+ for_user: user,+ ),+ ).to be_nil+ end++ it "shows the invites to the owner and staff" do+ [user, Fabricate(:moderator)].each do |viewer|+ expect(+ described_class.filter_for_viewer(report, guardian: viewer.guardian, for_user: user),+ ).to eq(report)+ end+ end+ end+enddiff --git a/plugins/discourse-rewind/spec/requests/rewinds_controller_spec.rb b/plugins/discourse-rewind/spec/requests/rewinds_controller_spec.rbindex e67ac023666..331c8e79f2a 100644--- a/plugins/discourse-rewind/spec/requests/rewinds_controller_spec.rb+++ b/plugins/discourse-rewind/spec/requests/rewinds_controller_spec.rb@@ -21,17 +21,6 @@ RSpec.describe DiscourseRewind::RewindsController doexpect(response.status).to eq(204)expect(user.user_option.reload.discourse_rewind_dismissed_at).to eq_time(Time.current)end-- it "returns dismissed state via session/current endpoint" do- freeze_time DateTime.parse("2022-12-24")- user.user_option.update!(discourse_rewind_dismissed_at: Time.current)-- get "/session/current.json"-- expect(- response.parsed_body.dig("current_user", "user_option", "discourse_rewind_dismissed"),- ).to eq(true)- endendend@@ -54,271 +43,17 @@ RSpec.describe DiscourseRewind::RewindsController docontext "when in valid month" dobefore { freeze_time DateTime.parse("2022-12-24") }- it "returns 200 with reports and total_available" do+ it "returns a page of reports and the total available" doget "/rewinds.json"expect(response.status).to eq(200)- body = response.parsed_body- expect(body).to have_key("reports")- expect(body).to have_key("total_available")- expect(body["reports"].size).to be <= DiscourseRewind::FetchReports::INITIAL_REPORT_COUNT- expect(body["total_available"]).to be >= body["reports"].size+ expect(response.parsed_body.keys).to contain_exactly("reports", "total_available")end- context "when some reports fail" do- before do- DiscourseRewind::Action::TopWords.stubs(:call).raises(StandardError.new("Some error"))- end-- it "returns reports excluding the failed ones" do- get "/rewinds.json"+ it "returns 400 for an offset past the last report" do+ get "/rewinds.json", params: { offset: DiscourseRewind::FetchReports::REPORTS.size }- expect(response.status).to eq(200)- body = response.parsed_body- expect(body["reports"]).to be_an(Array)- expect(body["reports"].map { |r| r["identifier"] }).not_to include("top-words")- end- end- end- end-- describe "#show" do- fab!(:user)-- before { sign_in(user) }-- context "when out of valid month" do- before { freeze_time DateTime.parse("2022-11-24") }-- it "returns 404" do- get "/rewinds/0.json"-- expect(response.status).to eq(404)- expect(response.parsed_body["errors"].first).to eq(I18n.t("discourse_rewind.invalid_year"))- end- end-- context "when in valid month" do- before { freeze_time DateTime.parse("2022-12-24") }-- it "does not return cached best post excerpts after their category becomes read-restricted" do- report_user = Fabricate(:user)- viewer = Fabricate(:user)- category = Fabricate(:category)- topic = Fabricate(:topic, category:, user: report_user)- post =- Fabricate(- :post,- topic:,- user: report_user,- post_number: 2,- created_at: Time.zone.parse("2022-06-01"),- raw: "classified rewind cache content",- like_count: 1,- )- report_user.user_option.update!(discourse_rewind_share_publicly: true)-- sign_in(report_user)- get "/rewinds/#{DiscourseRewind::FetchReports::REPORTS.index(DiscourseRewind::Action::BestPosts)}.json"-- expect(response.status).to eq(200)- expect(response.body).to include(post.raw)-- category.update!(read_restricted: true)-- sign_in(viewer)- get "/t/#{topic.id}.json"-- expect(response.status).to eq(404)- expect(response.body).not_to include(post.raw)-- get "/rewinds/#{DiscourseRewind::FetchReports::REPORTS.index(DiscourseRewind::Action::BestPosts)}.json",- params: {- for_user_username: report_user.username,- }-- expect(response.status).to eq(200)- expect(response.body).not_to include(post.raw)- end-- context "when reports are cached" do- before { get "/rewinds.json" }-- it "returns 200 with the requested report" do- get "/rewinds/0.json"-- expect(response.status).to eq(200)- body = response.parsed_body- expect(body).to have_key("report")- expect(body["report"]).to have_key("identifier")- end-- it "returns 404 for invalid index" do- get "/rewinds/999.json"-- expect(response.status).to eq(404)- expect(response.parsed_body["errors"].first).to eq(- I18n.t("discourse_rewind.report_not_found"),- )- end- end-- context "when cached topic-backed reports become ineligible" do- fab!(:rewind_owner, :user)- fab!(:viewer, :user)- fab!(:restricted_category) { Fabricate(:category, read_restricted: true) }- fab!(:unlisted_topic) do- Fabricate(- :topic,- user: rewind_owner,- created_at: DateTime.parse("2022-01-01"),- title: "Cached unlisted topic title",- excerpt: "Cached unlisted topic excerpt",- )- end- fab!(:restricted_topic) do- Fabricate(- :topic,- user: rewind_owner,- created_at: DateTime.parse("2022-01-02"),- title: "Cached restricted topic title",- )- end- fab!(:eligible_topic) do- Fabricate(- :topic,- user: rewind_owner,- created_at: DateTime.parse("2022-01-03"),- title: "Cached eligible topic title",- )- end- fab!(:hidden_reply) do- Fabricate(- :post,- topic: eligible_topic,- user: rewind_owner,- post_number: 2,- created_at: DateTime.parse("2022-01-04"),- raw: "Cached hidden post excerpt",- like_count: 100,- )- end- fab!(:deleted_reply) do- Fabricate(- :post,- topic: eligible_topic,- user: rewind_owner,- post_number: 3,- created_at: DateTime.parse("2022-01-05"),- raw: "Cached deleted post excerpt",- like_count: 99,- )- end- fab!(:eligible_reply) do- Fabricate(- :post,- topic: eligible_topic,- user: rewind_owner,- post_number: 4,- created_at: DateTime.parse("2022-01-06"),- raw: "Cached eligible post excerpt",- like_count: 98,- )- end-- before do- rewind_owner.user_option.update!(discourse_rewind_share_publicly: true)- TopTopic.refresh!- TopTopic.find_by!(topic_id: unlisted_topic.id).update!(yearly_score: 100)- TopTopic.find_by!(topic_id: restricted_topic.id).update!(yearly_score: 99)- TopTopic.find_by!(topic_id: eligible_topic.id).update!(yearly_score: 98)- sign_in(rewind_owner)- get "/rewinds/7.json"- get "/rewinds/8.json"- end-- it "omits an unlisted topic from a cached shared Best Topics report" do- cached_report =- DiscourseRewind::FetchReportsHelper.load_single_report_from_cache(- rewind_owner.id,- 2022,- "BestTopics",- )- cached_topic = cached_report[:data].find { |topic| topic[:topic_id] == unlisted_topic.id }- expect(cached_topic).to be_present-- unlisted_topic.update!(visible: false)- sign_in(viewer)-- get "/rewinds/7.json", params: { for_user_username: rewind_owner.username }-- expect(response.status).to eq(200)- expect(- response.parsed_body.dig("report", "data").map { |topic| topic["topic_id"] },- ).to contain_exactly(restricted_topic.id, eligible_topic.id)- expect(response.body).not_to include(cached_topic[:title])- expect(response.body).not_to include(cached_topic[:excerpt])- expect(- DiscourseRewind::FetchReportsHelper.load_single_report_from_cache(- rewind_owner.id,- 2022,- "BestTopics",- ),- ).to include(data: include(cached_topic))- end-- it "omits a deleted topic while retaining eligible cached Best Topics entries" do- restricted_topic.trash!(Discourse.system_user)- sign_in(viewer)-- get "/rewinds/7.json", params: { for_user_username: rewind_owner.username }-- expect(response.status).to eq(200)- expect(- response.parsed_body.dig("report", "data").map { |topic| topic["topic_id"] },- ).to contain_exactly(unlisted_topic.id, eligible_topic.id)- end-- it "omits a topic after the viewer loses category access while retaining eligible cached Best Topics entries" do- restricted_topic.change_category_to_id(restricted_category.id)- expect(viewer.guardian.can_see?(restricted_topic)).to eq(false)- sign_in(viewer)-- get "/rewinds/7.json", params: { for_user_username: rewind_owner.username }-- expect(response.status).to eq(200)- expect(- response.parsed_body.dig("report", "data").map { |topic| topic["topic_id"] },- ).to contain_exactly(unlisted_topic.id, eligible_topic.id)- end-- it "omits hidden and deleted posts from a cached shared Best Posts report" do- cached_report =- DiscourseRewind::FetchReportsHelper.load_single_report_from_cache(- rewind_owner.id,- 2022,- "BestPosts",- )- cached_hidden_post =- cached_report[:data].find { |post| post[:post_number] == hidden_reply.post_number }- cached_deleted_post =- cached_report[:data].find { |post| post[:post_number] == deleted_reply.post_number }- expect(cached_hidden_post).to be_present- expect(cached_deleted_post).to be_present-- hidden_reply.update!(hidden: true)- deleted_reply.trash!(Discourse.system_user)- sign_in(viewer)-- get "/rewinds/8.json", params: { for_user_username: rewind_owner.username }-- expect(response.status).to eq(200)- expect(- response.parsed_body.dig("report", "data").map { |post| post["post_number"] },- ).to contain_exactly(eligible_reply.post_number)- expect(response.body).not_to include(cached_hidden_post[:excerpt])- expect(response.body).not_to include(cached_deleted_post[:excerpt])- end+ expect(response.status).to eq(400)endendend@@ -343,16 +78,6 @@ RSpec.describe DiscourseRewind::RewindsController doexpect(user.user_option.reload.discourse_rewind_share_publicly).to eq(true)end- it "toggles share preference from true to false" do- user.user_option.update!(discourse_rewind_share_publicly: true)-- put "/rewinds/toggle-share.json"-- expect(response.status).to eq(200)- expect(response.parsed_body["shared"]).to eq(false)- expect(user.user_option.reload.discourse_rewind_share_publicly).to eq(false)- end-context "when user has hidden profile" dobefore { user.user_option.update!(hide_profile: true) }@@ -367,16 +92,6 @@ RSpec.describe DiscourseRewind::RewindsController do)expect(user.user_option.reload.discourse_rewind_share_publicly).to eq(false)end-- it "allows disabling share even when profile is hidden" do- user.user_option.update!(discourse_rewind_share_publicly: true)-- put "/rewinds/toggle-share.json"-- expect(response.status).to eq(200)- expect(response.parsed_body["shared"]).to eq(false)- expect(user.user_option.reload.discourse_rewind_share_publicly).to eq(false)- endendendenddiff --git a/plugins/discourse-rewind/spec/services/fetch_report_spec.rb b/plugins/discourse-rewind/spec/services/fetch_report_spec.rbdeleted file mode 100644index d304170cffc..00000000000--- a/plugins/discourse-rewind/spec/services/fetch_report_spec.rb+++ /dev/null@@ -1,394 +0,0 @@-# frozen_string_literal: true--RSpec.describe(DiscourseRewind::FetchReport) do- describe ".call" do- subject(:result) { described_class.call(**dependencies) }-- fab!(:current_user, :user)-- let(:guardian) { Guardian.new(current_user) }- let(:params) { { index: 0 } }- let(:dependencies) { { guardian:, params: } }-- before { SiteSetting.discourse_rewind_enabled = true }-- context "when index is not provided" do- let(:params) { {} }-- it { is_expected.to fail_a_contract }- end-- context "when index is negative" do- let(:params) { { index: -1 } }-- it { is_expected.to fail_a_contract }- end-- context "when index is out of bounds" do- before { freeze_time DateTime.parse("2021-12-22") }-- let(:params) { { index: 999 } }-- it { is_expected.to fail_to_find_a_model(:report) }- end-- context "when in january" do- before { freeze_time DateTime.parse("2021-01-22") }-- let(:params) { { index: 0 } }-- it "fetches reports from the previous year" do- expect(result.year).to eq(2020)- expect(result).to be_success- end- end-- context "when out of valid months" do- before { freeze_time DateTime.parse("2021-02-22") }-- it { is_expected.to fail_to_find_a_model(:year) }- end-- context "in development mode" do- before do- Rails.env.stubs(:development?).returns(true)- freeze_time DateTime.parse("2021-06-22")- end-- let(:params) { { index: 0 } }-- it "finds the year no matter what month" do- expect(result.year).to eq(2021)- expect(result).to be_success- end- end-- context "when a report is cached" do- before { freeze_time DateTime.parse("2021-12-22") }-- context "when index is 0" do- let(:params) { { index: 0 } }-- before do- cached_report = { data: "cached top words", identifier: "top-words" }- DiscourseRewind::FetchReportsHelper.cache_single_report(- current_user.id,- 2021,- "TopWords",- cached_report,- )- end-- it "returns the cached report" do- allow(DiscourseRewind::Action::TopWords).to receive(:call)- expect(result).to be_success- expect(result.report[:identifier]).to eq("top-words")- expect(result.report[:data]).to eq("cached top words")- expect(DiscourseRewind::Action::TopWords).to_not have_received(:call)- end- end-- context "when index is 1" do- let(:params) { { index: 1 } }-- before do- cached_report = { data: "cached reading time", identifier: "reading-time" }- DiscourseRewind::FetchReportsHelper.cache_single_report(- current_user.id,- 2021,- "ReadingTime",- cached_report,- )- end-- it "returns the cached report" do- allow(DiscourseRewind::Action::ReadingTime).to receive(:call)- expect(result).to be_success- expect(result.report[:identifier]).to eq("reading-time")- expect(DiscourseRewind::Action::ReadingTime).to_not have_received(:call)- end- end-- context "when index is beyond INITIAL_REPORT_COUNT" do- let(:params) { { index: 3 } }-- before do- cached_report = { data: "cached reactions", identifier: "reactions" }- DiscourseRewind::FetchReportsHelper.cache_single_report(- current_user.id,- 2021,- "Reactions",- cached_report,- )- end-- it "returns the cached report even though it's beyond INITIAL_REPORT_COUNT" do- allow(DiscourseRewind::Action::Reactions).to receive(:call)- expect(result).to be_success- expect(result.report[:identifier]).to eq("reactions")- expect(DiscourseRewind::Action::Reactions).to_not have_received(:call)- end- end-- context "when a cached best topics report contains content from a now-restricted topic" do- let(:params) { { index: 7 } }-- before do- DiscourseRewind::FetchReportsHelper.cache_single_report(- current_user.id,- 2021,- "BestTopics",- {- data: [{ topic_id: 1, title: "restricted topic", excerpt: "restricted content" }],- identifier: "best-topics",- },- )- end-- it "filters the cached report without regenerating it" do- allow(DiscourseRewind::Action::BestTopics).to receive(:call)-- expect(result).to be_success- expect(result.report[:data]).to eq([])- expect(DiscourseRewind::Action::BestTopics).to_not have_received(:call)- expect(- DiscourseRewind::FetchReportsHelper.load_single_report_from_cache(- current_user.id,- 2021,- "BestTopics",- )[- :data- ],- ).to contain_exactly(- topic_id: 1,- title: "restricted topic",- excerpt: "restricted content",- )- end- end- end-- context "when a report is not cached" do- before { freeze_time DateTime.parse("2021-12-22") }-- context "when index is 0" do- let(:params) { { index: 0 } }-- it "generates and caches the report" do- allow(DiscourseRewind::Action::TopWords).to receive(:call).and_return(- { data: "generated top words", identifier: "top-words" },- )- expect(result).to be_success- expect(result.report[:identifier]).to eq("top-words")- expect(result.report[:data]).to eq("generated top words")- expect(DiscourseRewind::Action::TopWords).to have_received(:call)-- cached =- DiscourseRewind::FetchReportsHelper.load_single_report_from_cache(- current_user.id,- 2021,- "TopWords",- )- expect(cached[:identifier]).to eq("top-words")- end- end-- context "when index is beyond INITIAL_REPORT_COUNT" do- let(:params) { { index: 3 } }-- it "generates and caches the report even though it's beyond INITIAL_REPORT_COUNT" do- allow(DiscourseRewind::Action::Reactions).to receive(:call).and_return(- { data: "generated reactions", identifier: "reactions" },- )- expect(result).to be_success- expect(result.report[:identifier]).to eq("reactions")- expect(DiscourseRewind::Action::Reactions).to have_received(:call)-- cached =- DiscourseRewind::FetchReportsHelper.load_single_report_from_cache(- current_user.id,- 2021,- "Reactions",- )- expect(cached[:identifier]).to eq("reactions")- end- end- end-- context "when viewing someone else's AI usage" do- fab!(:owner, :user)-- let(:params) do- {- index: DiscourseRewind::FetchReports::REPORTS.index(DiscourseRewind::Action::AiUsage),- for_user_username: owner.username,- }- end- let(:report) do- {- data: {- total_requests: 1,- model_usage: [{ name: "secret-model", count: 1 }],- },- identifier: "ai-usage",- }- end-- before do- freeze_time DateTime.parse("2021-12-22")- owner.user_option.update!(discourse_rewind_share_publicly: true)- DiscourseRewind::Action::AiUsage.stubs(:call).returns(report)- end-- it "hides the models" do- expect(result.report[:data]).to eq(total_requests: 1)- end-- context "when the viewer is the owner" do- let(:guardian) { owner.guardian }-- it "shows the models" do- expect(result.report).to eq(report)- end- end-- context "when the viewer is an admin" do- let(:guardian) { Fabricate(:admin).guardian }-- it "shows the models" do- expect(result.report).to eq(report)- end- end- end-- context "when viewing someone else's invites" do- fab!(:owner, :user)-- let(:params) do- {- index: DiscourseRewind::FetchReports::REPORTS.index(DiscourseRewind::Action::Invites),- for_user_username: owner.username,- }- end- let(:report) { { data: { total_invites: 1 }, identifier: "invites" } }-- before do- freeze_time DateTime.parse("2021-12-22")- owner.user_option.update!(discourse_rewind_share_publicly: true)- DiscourseRewind::Action::Invites.stubs(:call).returns(report)- end-- it { is_expected.to fail_to_find_a_model(:report) }-- context "when the viewer is the owner" do- let(:guardian) { owner.guardian }-- it "shows the invites" do- expect(result.report).to eq(report)- end- end-- context "when the viewer is a moderator" do- let(:guardian) { Fabricate(:moderator).guardian }-- it "shows the invites" do- expect(result.report).to eq(report)- end- end- end-- context "with for_user_username parameter" do- fab!(:other_user, :user)- fab!(:admin, :admin)-- before { freeze_time DateTime.parse("2021-12-22") }-- context "when for_user_username is blank" do- let(:params) { { index: 0, for_user_username: "" } }-- it "uses the guardian user" do- expect(result).to be_success- expect(result.for_user).to eq(current_user)- end- end-- context "when for_user_username is provided but user does not exist" do- let(:params) { { index: 0, for_user_username: "nonexistent" } }-- it { is_expected.to fail_to_find_a_model(:for_user) }- end-- context "when viewing own rewind" do- let(:params) { { index: 0, for_user_username: current_user.username } }-- it "returns the user's report" do- expect(result).to be_success- expect(result.for_user).to eq(current_user)- end- end-- context "when viewing another user's rewind" do- context "when the other user has sharing enabled" do- before { other_user.user_option.update!(discourse_rewind_share_publicly: true) }-- let(:params) { { index: 0, for_user_username: other_user.username } }-- before do- cached_report = { data: "other user report", identifier: "top-words" }- DiscourseRewind::FetchReportsHelper.cache_single_report(- other_user.id,- 2021,- "TopWords",- cached_report,- )- end-- it "allows access to the report" do- expect(result).to be_success- expect(result.for_user).to eq(other_user)- expect(result.report[:identifier]).to eq("top-words")- expect(result.report[:data]).to eq("other user report")- end-- context "when the other user has hide_profile enabled" do- before { other_user.user_option.update!(hide_profile: true) }-- it { is_expected.to fail_to_find_a_model(:for_user) }- end- end-- context "when the other user has sharing disabled" do- before { other_user.user_option.update!(discourse_rewind_share_publicly: false) }-- context "when guardian is an admin" do- let(:guardian) { Guardian.new(admin) }- let(:params) { { index: 0, for_user_username: other_user.username } }-- before do- cached_report = { data: "other user report", identifier: "top-words" }- DiscourseRewind::FetchReportsHelper.cache_single_report(- other_user.id,- 2021,- "TopWords",- cached_report,- )- end-- it "allows access to the report" do- expect(result).to be_success- expect(result.for_user).to eq(other_user)- expect(result.report[:identifier]).to eq("top-words")- expect(result.report[:data]).to eq("other user report")- end- end-- context "when guardian is not an admin" do- let(:params) { { index: 0, for_user_username: other_user.username } }-- it { is_expected.to fail_to_find_a_model(:for_user) }- end- end- end- end- end-enddiff --git a/plugins/discourse-rewind/spec/services/fetch_reports_spec.rb b/plugins/discourse-rewind/spec/services/fetch_reports_spec.rbindex 67647ffc8df..4567ef15b17 100644--- a/plugins/discourse-rewind/spec/services/fetch_reports_spec.rb+++ b/plugins/discourse-rewind/spec/services/fetch_reports_spec.rb@@ -2,153 +2,203 @@RSpec.describe(DiscourseRewind::FetchReports) dodescribe ".call" do- subject(:result) { described_class.call(**dependencies) }+ subject(:result) { described_class.call(guardian:, params:) }fab!(:current_user, :user)+ fab!(:other_user, :user)- let(:guardian) { Guardian.new(current_user) }- let(:dependencies) { { guardian: } }+ let(:guardian) { current_user.guardian }+ let(:params) { {} }- before { SiteSetting.discourse_rewind_enabled = true }+ before do+ SiteSetting.discourse_rewind_enabled = true+ freeze_time DateTime.parse("2021-12-22")+ end++ it "returns the initial reports and the total available" do+ expect(result).to have_attributes(+ year: 2021,+ for_user: current_user,+ reports: [+ nil,+ include(identifier: "reading-time"),+ include(identifier: "writing-analysis"),+ ],+ total_available: described_class::REPORTS.size,+ )+ endcontext "when in january" dobefore { freeze_time DateTime.parse("2021-01-22") }- it "computes the correct previous year" do+ it "uses the previous year" doexpect(result.year).to eq(2020)endend- context "when in december" do- before { freeze_time DateTime.parse("2021-12-22") }-- it "computes the correct previous year" do- expect(result.year).to eq(2021)- end- end-- context "when out of valid months december" do+ context "when out of valid months" dobefore { freeze_time DateTime.parse("2021-02-22") }it { is_expected.to fail_to_find_a_model(:year) }end- context "in development mode" do+ context "when out of valid months in development" dobefore doRails.env.stubs(:development?).returns(true)freeze_time DateTime.parse("2021-06-22")end- it "finds the year no matter what month" do+ it "uses the current year" doexpect(result.year).to eq(2021)endend- context "when reports are cached" do- before { freeze_time DateTime.parse("2021-12-22") }+ context "when a report fails" do+ it "keeps the other reports at their position and retries the failed one" do+ DiscourseRewind::Action::ReadingTime.stubs(:call).raises(StandardError)++ expect(+ described_class+ .call(guardian:, params:)+ .reports+ .map { |report| report&.dig(:identifier) },+ ).to eq([nil, nil, "writing-analysis"])- it "returns the cached reports" do- initial_count = result.reports.length- expect(initial_count).to eq(DiscourseRewind::FetchReports::INITIAL_REPORT_COUNT)+ DiscourseRewind::Action::ReadingTime.unstub(:call)- allow(DiscourseRewind::Action::TopWords).to receive(:call)- expect(result.reports.length).to eq(initial_count)- expect(DiscourseRewind::Action::TopWords).to_not have_received(:call)+ expect(result.reports.map { |report| report&.dig(:identifier) }).to eq(+ [nil, "reading-time", "writing-analysis"],+ )endend- context "when reports are not cached" do- before { freeze_time DateTime.parse("2021-01-22") }+ context "when a report was already generated" do+ it "returns the cached report, even when it had no data" do+ DiscourseRewind::Action::TopWords.stubs(:call).returns(data: [1], identifier: "top-words")+ DiscourseRewind::Action::ReadingTime.stubs(:call).returns(nil)+ described_class.call(guardian:, params:)+ DiscourseRewind::Action::TopWords.stubs(:call).returns(data: [1], identifier: "changed")+ DiscourseRewind::Action::ReadingTime.stubs(:call).returns(+ data: [1],+ identifier: "reading-time",+ )++ expect(result.reports.first(2)).to eq([{ data: [1], identifier: "top-words" }, nil])+ end+ end- it "returns the reports" do- expect(result.reports.length).to eq(DiscourseRewind::FetchReports::INITIAL_REPORT_COUNT)+ context "with every report returning data" do+ let(:params) { { offset: 3 } }++ before do+ described_class::REPORTS.each do |report_class|+ report = { data: [1], identifier: report_class.name.demodulize }+ report_class.stubs(:call).returns(report)+ report_class.stubs(:filter_for_viewer).returns(report)+ endend- it "only actually calls the first INITIAL_REPORT_COUNT reports" do- DiscourseRewind::Action::TopWords.expects(:call).once- DiscourseRewind::Action::ReadingTime.expects(:call).once- DiscourseRewind::Action::WritingAnalysis.expects(:call).once- DiscourseRewind::Action::Reactions.expects(:call).never- result+ def reports_named(*names)+ names.map { |name| { data: [1], identifier: name } }+ end++ it "returns the page of reports starting at the offset" do+ expect(result).to have_attributes(+ reports: reports_named("Reactions", "Fbff", "MostViewedTags"),+ total_available: described_class::REPORTS.size,+ )end- end- context "when checking total_available" do- before { freeze_time DateTime.parse("2021-12-22") }+ it "returns null for reports without data" do+ DiscourseRewind::Action::Fbff.stubs(:filter_for_viewer).returns(+ data: [],+ identifier: "Fbff",+ )- it "returns the total number of available reports" do- expect(result.total_available).to eq(DiscourseRewind::FetchReports::REPORTS.size)- expect(result.total_available).to be > result.reports.length+ expect(result.reports).to eq(+ [*reports_named("Reactions"), nil, *reports_named("MostViewedTags")],+ )endend- context "with for_user_username parameter" do- fab!(:other_user, :user)- fab!(:admin, :admin)+ context "when the offset is negative" do+ let(:params) { { offset: -1 } }- before { freeze_time DateTime.parse("2021-12-22") }+ it { is_expected.to fail_a_contract }+ end- context "when for_user_username is blank" do- let(:dependencies) { { guardian:, params: { for_user_username: "" } } }+ context "when the offset is past the last report" do+ let(:params) { { offset: described_class::REPORTS.size } }- it "uses the guardian user" do- expect(result).to be_success- expect(result.for_user).to eq(current_user)- end+ it { is_expected.to fail_a_contract }+ end++ context "when a report contains a topic the viewer cannot see" do+ fab!(:visible_topic, :topic)+ fab!(:shared_draft_topic) { Fabricate(:shared_draft).topic }++ let(:params) do+ { offset: described_class::REPORTS.index(DiscourseRewind::Action::BestTopics) }end- context "when for_user_username is provided but user does not exist" do- let(:dependencies) { { guardian:, params: { for_user_username: "nonexistent" } } }+ it "filters the report for the viewer" do+ DiscourseRewind::Action::BestTopics.stubs(:call).returns(+ data: [{ topic_id: visible_topic.id }, { topic_id: shared_draft_topic.id }],+ identifier: "best-topics",+ )- it { is_expected.to fail_to_find_a_model(:for_user) }+ expect(result.reports.first[:data]).to contain_exactly(topic_id: visible_topic.id)end- context "when viewing own rewind" do- let(:dependencies) { { guardian:, params: { for_user_username: current_user.username } } }+ it "returns null when the viewer can see none of the report" do+ DiscourseRewind::Action::BestTopics.stubs(:call).returns(+ data: [{ topic_id: shared_draft_topic.id }],+ identifier: "best-topics",+ )- it "returns the user's reports" do- expect(result).to be_success- expect(result.for_user).to eq(current_user)- end+ expect(result.reports.first).to be_nilend+ end++ context "when the user does not exist" do+ let(:params) { { for_user_username: "nonexistent" } }++ it { is_expected.to fail_to_find_a_model(:for_user) }+ end- context "when viewing another user's rewind" do- context "when the other user has sharing enabled" do- before { other_user.user_option.update!(discourse_rewind_share_publicly: true) }+ context "when viewing own rewind by username" do+ let(:params) { { for_user_username: current_user.username } }- let(:dependencies) { { guardian:, params: { for_user_username: other_user.username } } }+ it "returns the user's rewind" do+ expect(result.for_user).to eq(current_user)+ end+ end- it "allows access to the reports" do- expect(result).to be_success- expect(result.for_user).to eq(other_user)- end+ context "when the other user shares their rewind" do+ let(:params) { { for_user_username: other_user.username } }- context "when the other user has hide_profile enabled" do- before { other_user.user_option.update!(hide_profile: true) }+ before { other_user.user_option.update!(discourse_rewind_share_publicly: true) }- it { is_expected.to fail_to_find_a_model(:for_user) }- end- end+ it "returns the other user's rewind" do+ expect(result.for_user).to eq(other_user)+ end- context "when the other user has sharing disabled" do- before { other_user.user_option.update!(discourse_rewind_share_publicly: false) }+ it "fails when the other user hides their profile" do+ other_user.user_option.update!(hide_profile: true)- context "when guardian is an admin" do- let(:guardian) { Guardian.new(admin) }- let(:dependencies) { { guardian:, params: { for_user_username: other_user.username } } }+ expect(result).to fail_to_find_a_model(:for_user)+ end+ end- it "allows access to the reports" do- expect(result).to be_success- expect(result.for_user).to eq(other_user)- end- end+ context "when the other user does not share their rewind" do+ let(:params) { { for_user_username: other_user.username } }- context "when guardian is not an admin" do- let(:dependencies) { { guardian:, params: { for_user_username: other_user.username } } }+ it { is_expected.to fail_to_find_a_model(:for_user) }- it { is_expected.to fail_to_find_a_model(:for_user) }- end- end+ it "returns the other user's rewind to an admin" do+ current_user.update!(admin: true)++ expect(result.for_user).to eq(other_user)endendenddiff --git a/plugins/discourse-rewind/test/javascripts/integration/components/rewind-test.gjs b/plugins/discourse-rewind/test/javascripts/integration/components/rewind-test.gjsnew file mode 100644index 00000000000..71119ec0277--- /dev/null+++ b/plugins/discourse-rewind/test/javascripts/integration/components/rewind-test.gjs@@ -0,0 +1,52 @@+import { render } from "@ember/test-helpers";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import pretender, { response } from "discourse/tests/helpers/create-pretender";+import stubIntersectionObserver from "discourse/tests/helpers/stub-intersection-observer";+import {+ disableLoadMoreObserver,+ enableLoadMoreObserver,+} from "discourse/ui-kit/d-load-more";+import Rewind from "discourse/plugins/discourse-rewind/discourse/components/rewind";++module("Integration | Component | Rewind", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ enableLoadMoreObserver();+ this.observations = stubIntersectionObserver();+ });++ hooks.afterEach(function () {+ disableLoadMoreObserver();+ });++ test("pages through the reports, skipping missing ones", async function (assert) {+ const topWords = {+ identifier: "top-words",+ data: [{ word: "pumpkin", score: 7 }],+ };+ const requestedOffsets = [];+ pretender.get("/rewinds.json", (request) => {+ requestedOffsets.push(request.queryParams.offset);+ const reports =+ request.queryParams.offset === "0"+ ? [topWords, null, topWords]+ : [topWords];+ return response({ reports, total_available: 4 });+ });++ await render(<template><Rewind @user={{this.currentUser}} /></template>);+ await this.observations.at(-1).trigger();+ await this.observations.at(-1).trigger();++ assert+ .dom(".rewind-report")+ .exists({ count: 3 }, "the missing report is skipped");+ assert.deepEqual(+ requestedOffsets,+ ["0", "3"],+ "loading continues after the first page and stops after the last"+ );+ });+});