A platform for community discussion. Free, open, simple.
FEATURE: Add nested replies category conversion (#41236)
Mark VanLandingham2409dc314ad4
diff --git a/app/controllers/categories_controller.rb b/app/controllers/categories_controller.rbindex 036ff1d8171..88950a7b65a 100644--- a/app/controllers/categories_controller.rb+++ b/app/controllers/categories_controller.rb@@ -16,7 +16,7 @@ class CategoriesController < ApplicationControllersearch]- before_action :fetch_category, only: %i[show update destroy visible_groups]+ before_action :fetch_category, only: %i[show update destroy visible_groups convert_nested_replies]before_action :initialize_staff_action_logger, only: %i[create update destroy]skip_before_action :check_xhr,@@ -316,6 +316,27 @@ class CategoriesController < ApplicationControllerendend+ def convert_nested_replies+ NestedTopic::ConvertCategory.call(+ service_params.deep_merge(params: { category_id: @category.id }),+ ) do+ on_success do |category:, converted_topic_count:|+ render json:+ success_json.merge(+ converted_topic_count: converted_topic_count,+ nested_replies_conversion_completed:+ category.nested_replies_conversion_completed?,+ )+ end+ on_failed_contract { raise Discourse::InvalidParameters }+ on_model_not_found(:category) { raise Discourse::NotFound }+ on_failed_policy(:nested_replies_enabled) { raise Discourse::InvalidAccess }+ on_failed_policy(:can_edit_category) { raise Discourse::InvalidAccess }+ on_failed_policy(:category_nested_replies_enabled) { raise Discourse::InvalidAccess }+ on_failure { render json: failed_json, status: :unprocessable_entity }+ end+ end+def update_slug@category = Category.find(params[:category_id].to_i)guardian.ensure_can_edit!(@category)diff --git a/app/jobs/scheduled/backfill_nested_reply_stats.rb b/app/jobs/scheduled/backfill_nested_reply_stats.rbindex 7890ccc5775..a3e133774d1 100644--- a/app/jobs/scheduled/backfill_nested_reply_stats.rb+++ b/app/jobs/scheduled/backfill_nested_reply_stats.rb@@ -6,62 +6,56 @@ module Jobscluster_concurrency 1- def execute(_ = nil)+ def execute(args = {})return unless SiteSetting.nested_replies_enabled- topic_ids =- DB.query_single(<<~SQL, batch_size: SiteSetting.nested_replies_backfill_batch_size)- SELECT t.id FROM topics t- INNER JOIN nested_topics nt ON nt.topic_id = t.id- LEFT JOIN nested_view_post_stats s ON s.post_id = (- SELECT p.id FROM posts p- WHERE p.topic_id = t.id AND p.post_number = 1- LIMIT 1- )- WHERE t.deleted_at IS NULL- AND t.archetype = 'regular'- AND s.post_id IS NULL- ORDER BY t.id DESC- LIMIT :batch_size- SQL-+ args ||= {}+ topic_ids = topic_ids_missing_stats(category_id: args[:category_id])return if topic_ids.empty?- topic_ids.each do |topic_id|- backfill_topic(topic_id)- ensure_op_stat_row(topic_id)- end+ topic_ids.each { |topic_id| backfill_topic(topic_id) }endprivate- # Guarantees the OP has a stats row so the selector (which keys on- # s.post_id IS NULL for post_number = 1) will not re-pick this topic- # on the next run when it has no qualifying replies. When a reply later- # arrives, nested_replies_increment_stats upserts into the same row.- def ensure_op_stat_row(topic_id)- DB.exec(<<~SQL, topic_id: topic_id)- INSERT INTO nested_view_post_stats- (post_id, direct_reply_count, whisper_direct_reply_count,- total_descendant_count, whisper_total_descendant_count,- created_at, updated_at)- SELECT p.id, 0, 0, 0, 0, NOW(), NOW()- FROM posts p- WHERE p.topic_id = :topic_id AND p.post_number = 1- ON CONFLICT (post_id) DO NOTHING- SQL+ def topic_ids_missing_stats(category_id: nil)+ category_id = category_id.to_i+ category_filter = category_id.positive? ? "AND t.category_id = :category_id" : ""++ DB.query_single(+ <<~SQL,+ SELECT t.id+ FROM topics t+ INNER JOIN nested_topics nt ON nt.topic_id = t.id+ INNER JOIN posts op ON op.topic_id = t.id AND op.post_number = 1+ LEFT JOIN nested_view_post_stats s ON s.post_id = op.id+ WHERE t.deleted_at IS NULL+ AND t.archetype = :archetype+ #{category_filter}+ AND s.post_id IS NULL+ ORDER BY t.id DESC+ LIMIT :batch_size+ SQL+ archetype: Archetype.default,+ batch_size: SiteSetting.nested_replies_backfill_batch_size,+ category_id: category_id,+ )enddef backfill_topic(topic_id)DB.exec(<<~SQL, topic_id: topic_id, whisper_type: Post.types[:whisper])WITH RECURSIVE- direct_counts AS (- SELECT reply_to_post_number AS parent_number, post_type,- COUNT(*) AS cnt+ edges AS (+ SELECT post_number, reply_to_post_number, post_typeFROM postsWHERE topic_id = :topic_idAND reply_to_post_number IS NOT NULLAND post_number > 1+ ),+ direct_counts AS (+ SELECT reply_to_post_number AS parent_number, post_type,+ COUNT(*) AS cnt+ FROM edgesGROUP BY reply_to_post_number, post_type),direct_agg AS (@@ -71,13 +65,6 @@ module JobsFROM direct_countsGROUP BY parent_number),- edges AS (- SELECT id, post_number, reply_to_post_number, post_type- FROM posts- WHERE topic_id = :topic_id- AND reply_to_post_number IS NOT NULL- AND post_number > 1- ),ancestor_walk AS (SELECT e.reply_to_post_number AS ancestor_number,1 AS descendant_count,@@ -110,7 +97,7 @@ module JobsLEFT JOIN direct_agg d ON d.parent_number = p.post_numberLEFT JOIN descendant_agg t ON t.ancestor_number = p.post_numberWHERE p.topic_id = :topic_id- AND (d.parent_number IS NOT NULL OR t.ancestor_number IS NOT NULL)+ AND (p.post_number = 1 OR d.parent_number IS NOT NULL OR t.ancestor_number IS NOT NULL))INSERT INTO nested_view_post_stats(post_id, direct_reply_count, whisper_direct_reply_count,diff --git a/app/models/category.rb b/app/models/category.rbindex c3964611181..f40a50ec461 100644--- a/app/models/category.rb+++ b/app/models/category.rb@@ -76,6 +76,22 @@ class Category < ActiveRecord::Baseaccepts_nested_attributes_for :category_setting, update_only: trueaccepts_nested_attributes_for :category_localizations, allow_destroy: true+ def nested_replies_conversion_completed?+ !!ActiveModel::Type::Boolean.new.cast(+ custom_fields[NestedReplies::CONVERSION_COMPLETED_CUSTOM_FIELD],+ )+ end++ def mark_nested_replies_conversion_completed!+ custom_fields[NestedReplies::CONVERSION_COMPLETED_CUSTOM_FIELD] = true+ save_custom_fields(true, run_validations: false)+ end++ def clear_nested_replies_conversion_completed!+ custom_fields.delete(NestedReplies::CONVERSION_COMPLETED_CUSTOM_FIELD)+ save_custom_fields(true, run_validations: false)+ end+validates :user_id, presence: truevalidates :name,diff --git a/app/models/category_setting.rb b/app/models/category_setting.rbindex 378841ca6d5..429edee31b2 100644--- a/app/models/category_setting.rb+++ b/app/models/category_setting.rb@@ -13,6 +13,9 @@ class CategorySetting < ActiveRecord::Base{ no_one: 0, everyone: 1, everyone_except: 2, no_one_except: 3 },prefix: true+ after_save :clear_nested_replies_conversion_completed,+ if: :saved_change_to_nested_replies_default?+def require_topic_approval=(value)self.topic_posting_review_mode =ActiveModel::Type::Boolean.new.cast(value) ? :everyone : :no_one@@ -43,6 +46,12 @@ class CategorySetting < ActiveRecord::Basegreater_than_or_equal_to: 0,allow_nil: true,}++ private++ def clear_nested_replies_conversion_completed+ category.clear_nested_replies_conversion_completed! unless nested_replies_default?+ endend# == Schema Informationdiff --git a/app/services/nested_topic/convert_category.rb b/app/services/nested_topic/convert_category.rbnew file mode 100644index 00000000000..522a3a12b1a--- /dev/null+++ b/app/services/nested_topic/convert_category.rb@@ -0,0 +1,94 @@+# frozen_string_literal: true++class NestedTopic::ConvertCategory+ include Service::Base++ BATCH_SIZE = 1000++ params do+ attribute :category_id, :integer++ validates :category_id, presence: true+ end++ model :category+ policy :nested_replies_enabled+ policy :can_edit_category+ policy :category_nested_replies_enabled+ step :enable_nested_view_for_existing_topics+ step :mark_conversion_completed+ only_if(:converted_topics?) { step :enqueue_nested_reply_stats_backfill }++ private++ def fetch_category(params:)+ Category.find_by(id: params.category_id)+ end++ def nested_replies_enabled+ SiteSetting.nested_replies_enabled+ end++ def can_edit_category(guardian:, category:)+ guardian.can_edit?(category)+ end++ def category_nested_replies_enabled(category:)+ category.nested_replies_default+ end++ def enable_nested_view_for_existing_topics(category:)+ converted_topic_count = 0++ loop do+ converted_batch_count = convert_topic_batch(category.id)+ break if converted_batch_count.zero?++ converted_topic_count += converted_batch_count+ end++ context[:converted_topic_count] = converted_topic_count+ end++ def convert_topic_batch(category_id)+ DB+ .query_single(<<~SQL, category_id:, archetype: Archetype.default, batch_size: BATCH_SIZE)+ WITH topics_to_convert AS (+ SELECT t.id+ FROM topics t+ WHERE t.category_id = :category_id+ AND t.archetype = :archetype+ AND t.deleted_at IS NULL+ AND NOT EXISTS (+ SELECT 1+ FROM nested_topics nt+ WHERE nt.topic_id = t.id+ )+ ORDER BY t.id+ LIMIT :batch_size+ ), inserted AS (+ INSERT INTO nested_topics (topic_id, created_at, updated_at)+ SELECT id, NOW(), NOW()+ FROM topics_to_convert+ ON CONFLICT (topic_id) DO NOTHING+ RETURNING 1+ )+ SELECT COUNT(*)+ FROM inserted+ SQL+ .first+ .to_i+ end++ def mark_conversion_completed(category:)+ category.mark_nested_replies_conversion_completed!+ end++ def converted_topics?(converted_topic_count:)+ converted_topic_count.positive?+ end++ def enqueue_nested_reply_stats_backfill(category:)+ Jobs.enqueue(:backfill_nested_reply_stats, category_id: category.id)+ end+enddiff --git a/config/initializers/300-nested-replies.rb b/config/initializers/300-nested-replies.rbindex 8e298559a6e..71ebf2a73a5 100644--- a/config/initializers/300-nested-replies.rb+++ b/config/initializers/300-nested-replies.rb@@ -1,6 +1,10 @@# frozen_string_literal: true-Rails.application.config.to_prepare { require "nested_replies" }+Rails.application.config.to_prepare do+ require "nested_replies"++ Category.register_custom_field_type(NestedReplies::CONVERSION_COMPLETED_CUSTOM_FIELD, :boolean)+endDiscourseEvent.on(:topic_created) do |topic, _opts, _user|next unless SiteSetting.nested_replies_enableddiff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex 3f6a803c6c6..0601ee1d093 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -4206,6 +4206,11 @@ en:all_replies: "All replies"category_settings:default_nested_view: "Use nested view as default for topics in this category"+ convert_existing: "Convert existing topics"+ convert_existing_description: "Existing topics in this category will not use nested replies until you convert them. Run this once to switch them to nested view."+ convert_existing_confirm: "Convert all existing topics in this category to nested replies?"+ convert_existing_complete: "Existing topics have been converted to nested replies."+ save_first: "Save this category setting before converting existing topics."no_replies: "No replies yet."deleted_post_placeholder: "[deleted]"ignored_post_placeholder: "[ignored]"diff --git a/config/routes.rb b/config/routes.rbindex ed57e43aa51..29fc8dc1da9 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -1347,6 +1347,7 @@ Discourse::Application.routes.draw doget "/c", to: redirect(relative_url_root + "categories")resources :categories, only: %i[index create update destroy]+ post "categories/:id/convert_nested_replies" => "categories#convert_nested_replies"post "categories/reorder" => "categories#reorder"get "categories/types" => "categories#types"get "categories/find" => "categories#find"diff --git a/frontend/discourse/app/connectors/category-custom-settings/nested-replies-settings-upsert.gjs b/frontend/discourse/app/connectors/category-custom-settings/nested-replies-settings-upsert.gjsindex b9dcabca755..aa94074ab3c 100644--- a/frontend/discourse/app/connectors/category-custom-settings/nested-replies-settings-upsert.gjs+++ b/frontend/discourse/app/connectors/category-custom-settings/nested-replies-settings-upsert.gjs@@ -1,12 +1,29 @@import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";import { action } from "@ember/object";+import { service } from "@ember/service";+import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";+import DButton from "discourse/ui-kit/d-button";import { i18n } from "discourse-i18n";+const CONVERSION_COMPLETED_CUSTOM_FIELD = "nested_replies_conversion_completed";+export default class NestedRepliesSettingsUpsert extends Component {static shouldRender(args, context) {return context.siteSettings.nested_replies_enabled;}+ @service a11y;+ @service dialog;++ @tracked completed = false;+ @tracked converting = false;++ get category() {+ return this.args.outletArgs.category;+ }+get enabled() {const value =this.args.outletArgs.transientData?.category_setting@@ -14,14 +31,82 @@ export default class NestedRepliesSettingsUpsert extends Component {return !!value;}+ get persistedEnabled() {+ return !!this.category?.category_setting?.nested_replies_default;+ }++ get persistedCompleted() {+ const value =+ this.category?.custom_fields?.[CONVERSION_COMPLETED_CUSTOM_FIELD];+ return value === true || value === "true" || value === "t" || value === "1";+ }++ get conversionCompleted() {+ return (+ this.enabled &&+ this.persistedEnabled &&+ (this.completed || this.persistedCompleted)+ );+ }++ get showSaveFirstMessage() {+ return this.category?.id && this.enabled && !this.persistedEnabled;+ }++ get canConvertExistingTopics() {+ return (+ this.enabled &&+ this.category?.id &&+ this.persistedEnabled &&+ !this.conversionCompleted+ );+ }+@actionasync onToggle(_, { set, name }) {await set(name, !this.enabled);}+ @action+ async convertExistingTopics() {+ const confirmed = await this.dialog.yesNoConfirm({+ message: i18n(+ "nested_replies.category_settings.convert_existing_confirm"+ ),+ });++ if (!confirmed) {+ return;+ }++ this.converting = true;++ try {+ const result = await ajax(+ `/categories/${this.category.id}/convert_nested_replies`,+ { type: "POST" }+ );++ this.completed = result.nested_replies_conversion_completed;+ this.category.custom_fields ??= {};+ this.category.custom_fields[CONVERSION_COMPLETED_CUSTOM_FIELD] = true;+ this.a11y.announce(+ i18n("nested_replies.category_settings.convert_existing_complete"),+ "polite"+ );+ } catch (error) {+ popupAjaxError(error);+ } finally {+ this.converting = false;+ }+ }+<template>{{#let @outletArgs.form as |form|}}- <form.Section @title={{i18n "nested_replies.nested_view"}}>+ <form.Section+ @title={{i18n "nested_replies.nested_view"}}+ class="category-custom-settings-outlet nested-replies-category-settings"+ ><form.Object @name="category_setting" as |categorySetting|><categorySetting.Field@type="checkbox"@@ -35,6 +120,41 @@ export default class NestedRepliesSettingsUpsert extends Component {<field.Control /></categorySetting.Field></form.Object>++ {{#if this.showSaveFirstMessage}}+ <form.Alert+ @type="info"+ class="nested-replies-category-settings__notice"+ >+ {{i18n "nested_replies.category_settings.save_first"}}+ </form.Alert>+ {{else if this.conversionCompleted}}+ <form.Alert+ @type="success"+ class="nested-replies-category-settings__notice"+ >+ {{i18n+ "nested_replies.category_settings.convert_existing_complete"+ }}+ </form.Alert>+ {{else if this.canConvertExistingTopics}}+ <form.Alert+ @type="info"+ class="nested-replies-category-settings__notice"+ >+ {{i18n+ "nested_replies.category_settings.convert_existing_description"+ }}+ </form.Alert>++ <DButton+ @action={{this.convertExistingTopics}}+ @disabled={{this.converting}}+ @isLoading={{this.converting}}+ @label="nested_replies.category_settings.convert_existing"+ class="btn-default nested-replies-category-settings__convert-button"+ />+ {{/if}}</form.Section>{{/let}}</template>diff --git a/frontend/discourse/tests/integration/components/nested-replies-settings-upsert-test.gjs b/frontend/discourse/tests/integration/components/nested-replies-settings-upsert-test.gjsnew file mode 100644index 00000000000..c3cd8808a6d--- /dev/null+++ b/frontend/discourse/tests/integration/components/nested-replies-settings-upsert-test.gjs@@ -0,0 +1,150 @@+import { hash } from "@ember/helper";+import Service from "@ember/service";+import { click, render } from "@ember/test-helpers";+import { module, test } from "qunit";+import Form from "discourse/components/form";+import NestedRepliesSettingsUpsert from "discourse/connectors/category-custom-settings/nested-replies-settings-upsert";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import pretender, { response } from "discourse/tests/helpers/create-pretender";+import { i18n } from "discourse-i18n";++class DialogStub extends Service {+ message = null;++ yesNoConfirm(options) {+ this.message = options.message;+ return Promise.resolve(true);+ }+}++module(+ "Integration | Component | NestedRepliesSettingsUpsert",+ function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.siteSettings.nested_replies_enabled = true;+ this.owner.register("service:dialog", DialogStub);+ this.dialog = this.owner.lookup("service:dialog");+ });++ test("prompts admins to save before converting existing topics", async function (assert) {+ this.data = { category_setting: { nested_replies_default: true } };+ this.category = {+ id: 11,+ category_setting: { nested_replies_default: false },+ custom_fields: {},+ };++ await render(+ <template>+ <Form @data={{this.data}} as |form transientData|>+ <NestedRepliesSettingsUpsert+ @outletArgs={{hash+ category=this.category+ form=form+ transientData=transientData+ }}+ />+ </Form>+ </template>+ );++ assert+ .dom(".nested-replies-category-settings__notice")+ .hasText(+ i18n("nested_replies.category_settings.save_first"),+ "the save-first message is shown"+ );+ assert+ .dom(".nested-replies-category-settings__convert-button")+ .doesNotExist(+ "the conversion button is hidden until the setting is saved"+ );+ });++ test("does not show the conversion button after conversion completed", async function (assert) {+ this.data = { category_setting: { nested_replies_default: true } };+ this.category = {+ id: 11,+ category_setting: { nested_replies_default: true },+ custom_fields: { nested_replies_conversion_completed: true },+ };++ await render(+ <template>+ <Form @data={{this.data}} as |form transientData|>+ <NestedRepliesSettingsUpsert+ @outletArgs={{hash+ category=this.category+ form=form+ transientData=transientData+ }}+ />+ </Form>+ </template>+ );++ assert+ .dom(".nested-replies-category-settings__notice")+ .hasText(+ i18n("nested_replies.category_settings.convert_existing_complete"),+ "the completed message is shown"+ );+ assert+ .dom(".nested-replies-category-settings__convert-button")+ .doesNotExist("the conversion button is hidden after completion");+ });++ test("converts existing topics after confirmation", async function (assert) {+ let requestCount = 0;+ pretender.post("/categories/11/convert_nested_replies", () => {+ requestCount++;+ return response({+ success: "OK",+ converted_topic_count: 1,+ nested_replies_conversion_completed: true,+ });+ });++ this.data = { category_setting: { nested_replies_default: true } };+ this.category = {+ id: 11,+ category_setting: { nested_replies_default: true },+ custom_fields: {},+ };++ await render(+ <template>+ <Form @data={{this.data}} as |form transientData|>+ <NestedRepliesSettingsUpsert+ @outletArgs={{hash+ category=this.category+ form=form+ transientData=transientData+ }}+ />+ </Form>+ </template>+ );++ await click(".nested-replies-category-settings__convert-button");++ assert.strictEqual(+ this.dialog.message,+ i18n("nested_replies.category_settings.convert_existing_confirm"),+ "the confirmation message is shown"+ );+ assert.strictEqual(requestCount, 1, "the conversion endpoint is called");+ assert+ .dom(".nested-replies-category-settings__notice")+ .hasText(+ i18n("nested_replies.category_settings.convert_existing_complete"),+ "the completed message is shown after conversion"+ );+ assert+ .dom(".nested-replies-category-settings__convert-button")+ .doesNotExist("the conversion button is hidden after conversion");+ });+ }+);diff --git a/lib/nested_replies.rb b/lib/nested_replies.rbindex 79412d9d03f..de55d1fcddc 100644--- a/lib/nested_replies.rb+++ b/lib/nested_replies.rb@@ -1,6 +1,7 @@# frozen_string_literal: truemodule NestedReplies+ CONVERSION_COMPLETED_CUSTOM_FIELD = "nested_replies_conversion_completed"endrequire_relative "nested_replies/ancestor_walker"diff --git a/spec/jobs/scheduled/backfill_nested_reply_stats_spec.rb b/spec/jobs/scheduled/backfill_nested_reply_stats_spec.rbindex 96d116a5bad..831c3d576e9 100644--- a/spec/jobs/scheduled/backfill_nested_reply_stats_spec.rb+++ b/spec/jobs/scheduled/backfill_nested_reply_stats_spec.rb@@ -7,8 +7,8 @@ RSpec.describe Jobs::BackfillNestedReplyStats dobefore { SiteSetting.nested_replies_enabled = true }- def execute- described_class.new.execute(nil)+ def execute(args = nil)+ described_class.new.execute(args)endit "does nothing when feature is disabled" do@@ -189,4 +189,38 @@ RSpec.describe Jobs::BackfillNestedReplyStats doexecuteexpect(NestedViewPostStat.find_by(post_id: op.id).updated_at).to eq_time(initial_updated_at)end++ it "limits backfill to the requested category" do+ category = Fabricate(:category)+ other_category = Fabricate(:category)+ category_topic = Fabricate(:topic, category: category)+ other_topic = Fabricate(:topic, category: other_category)+ Fabricate(:nested_topic, topic: category_topic)+ Fabricate(:nested_topic, topic: other_topic)+ category_op = Fabricate(:post, topic: category_topic, post_number: 1)+ other_op = Fabricate(:post, topic: other_topic, post_number: 1)+ Fabricate(:post, topic: category_topic, reply_to_post_number: 1)+ Fabricate(:post, topic: other_topic, reply_to_post_number: 1)++ NestedViewPostStat.delete_all+ execute(category_id: category.id)++ expect(NestedViewPostStat.exists?(post_id: category_op.id)).to eq(true)+ expect(NestedViewPostStat.exists?(post_id: other_op.id)).to eq(false)+ end++ it "respects the configured batch size" do+ other_topic = Fabricate(:topic)+ Fabricate(:nested_topic, topic: other_topic)+ other_op = Fabricate(:post, topic: other_topic, post_number: 1)+ Fabricate(:post, topic: other_topic, reply_to_post_number: 1)+ Fabricate(:post, topic: topic, reply_to_post_number: 1)+ SiteSetting.nested_replies_backfill_batch_size = 1++ NestedViewPostStat.delete_all+ execute++ expect(NestedViewPostStat.exists?(post_id: other_op.id)).to eq(true)+ expect(NestedViewPostStat.exists?(post_id: op.id)).to eq(false)+ endenddiff --git a/spec/models/category_setting_spec.rb b/spec/models/category_setting_spec.rbindex c9bf1160a7d..1a7f4266eb8 100644--- a/spec/models/category_setting_spec.rb+++ b/spec/models/category_setting_spec.rb@@ -16,4 +16,33 @@ RSpec.describe CategorySetting do.is_greater_than_or_equal_to(0).allow_nilend++ describe "nested replies conversion state" do+ fab!(:category)++ it "clears the conversion custom field when nested replies are disabled" do+ category.category_setting.update!(nested_replies_default: true)+ category.mark_nested_replies_conversion_completed!++ expect { category.category_setting.update!(nested_replies_default: false) }.to change {+ category.reload.nested_replies_conversion_completed?+ }.from(true).to(false)++ expect(+ CategoryCustomField.exists?(+ category_id: category.id,+ name: NestedReplies::CONVERSION_COMPLETED_CUSTOM_FIELD,+ ),+ ).to eq(false)+ end++ it "keeps the conversion custom field when nested replies stay enabled" do+ category.category_setting.update!(nested_replies_default: true)+ category.mark_nested_replies_conversion_completed!++ expect { category.category_setting.update!(auto_bump_cooldown_days: 2) }.not_to change {+ category.reload.nested_replies_conversion_completed?+ }+ end+ endenddiff --git a/spec/requests/categories_controller_spec.rb b/spec/requests/categories_controller_spec.rbindex 94e4198a150..e3cbf4dd946 100644--- a/spec/requests/categories_controller_spec.rb+++ b/spec/requests/categories_controller_spec.rb@@ -1691,6 +1691,51 @@ RSpec.describe CategoriesController doendend+ describe "#convert_nested_replies" do+ let!(:topic) { Fabricate(:topic, category: category) }++ let(:url) { "/categories/#{category.id}/convert_nested_replies.json" }++ before do+ SiteSetting.nested_replies_enabled = true+ category.category_setting.update!(nested_replies_default: true)+ end++ it "requires the user to be logged in" do+ post url++ expect(response.status).to eq(403)+ end++ it "converts topics in the category to nested replies" do+ sign_in(admin)++ expect { post url }.to change { NestedTopic.where(topic: topic).count }.from(0).to(1)++ expect(response.status).to eq(200)+ expect(response.parsed_body["converted_topic_count"]).to eq(1)+ expect(response.parsed_body["nested_replies_conversion_completed"]).to eq(true)+ expect(category.reload.nested_replies_conversion_completed?).to eq(true)+ end++ it "does not allow users who cannot edit the category" do+ sign_in(user)++ post url++ expect(response.status).to eq(403)+ expect(NestedTopic.where(topic: topic).exists?).to eq(false)+ end++ it "returns not found for a missing category" do+ sign_in(admin)++ post "/categories/0/convert_nested_replies.json"++ expect(response.status).to eq(404)+ end+ end+describe "#visible_groups" dofab!(:public_group) doFabricate(:group, visibility_level: Group.visibility_levels[:public], name: "aaa")diff --git a/spec/serializers/nested_replies_basic_category_serializer_spec.rb b/spec/serializers/nested_replies_basic_category_serializer_spec.rbindex e6ea4e3c9f7..9c502a9914a 100644--- a/spec/serializers/nested_replies_basic_category_serializer_spec.rb+++ b/spec/serializers/nested_replies_basic_category_serializer_spec.rb@@ -22,4 +22,13 @@ RSpec.describe CategorySerializer doexpect(json[:category_setting][:nested_replies_default]).to eq(false)end++ it "serializes the category conversion custom field" do+ category.mark_nested_replies_conversion_completed!+ cat = Category.includes(:category_setting).find(category.id)++ json = CategorySerializer.new(cat, scope: Guardian.new(admin), root: false).as_json++ expect(json[:custom_fields][NestedReplies::CONVERSION_COMPLETED_CUSTOM_FIELD]).to eq(true)+ endenddiff --git a/spec/services/nested_topic/convert_category_spec.rb b/spec/services/nested_topic/convert_category_spec.rbnew file mode 100644index 00000000000..20225ce1bb4--- /dev/null+++ b/spec/services/nested_topic/convert_category_spec.rb@@ -0,0 +1,97 @@+# frozen_string_literal: true++RSpec.describe NestedTopic::ConvertCategory do+ describe described_class::Contract, type: :model do+ it { is_expected.to validate_presence_of(:category_id) }+ end++ describe ".call" do+ subject(:result) { described_class.call(params:, **dependencies) }++ fab!(:acting_user, :admin)+ fab!(:category)+ fab!(:topic) { Fabricate(:topic, category: category) }+ fab!(:already_nested_topic) { Fabricate(:topic, category: category) }+ fab!(:other_category_topic, :topic)++ let(:params) { { category_id: category.id } }+ let(:dependencies) { { guardian: acting_user.guardian } }++ before do+ SiteSetting.nested_replies_enabled = true+ category.category_setting.update!(nested_replies_default: true)+ Fabricate(:nested_topic, topic: already_nested_topic)+ end++ context "when the contract is invalid" do+ let(:params) { { category_id: nil } }++ it { is_expected.to fail_a_contract }+ end++ context "when the category is not found" do+ let(:params) { { category_id: 0 } }++ it { is_expected.to fail_to_find_a_model(:category) }+ end++ context "when nested replies are disabled" do+ before { SiteSetting.nested_replies_enabled = false }++ it { is_expected.to fail_a_policy(:nested_replies_enabled) }+ end++ context "when the user cannot edit the category" do+ fab!(:acting_user, :user)++ it { is_expected.to fail_a_policy(:can_edit_category) }+ end++ context "when the category does not use nested replies by default" do+ before { category.category_setting.update!(nested_replies_default: false) }++ it { is_expected.to fail_a_policy(:category_nested_replies_enabled) }+ end++ context "when converting existing topics" do+ it { is_expected.to run_successfully }++ it "creates nested topic records for topics in the category" do+ expect { result }.to change { NestedTopic.where(topic: topic).count }.from(0).to(1)++ expect(NestedTopic.where(topic: already_nested_topic).count).to eq(1)+ expect(NestedTopic.where(topic: other_category_topic).exists?).to eq(false)+ expect(result[:converted_topic_count]).to eq(1)+ end++ it "marks the category conversion as completed" do+ expect { result }.to change { category.reload.nested_replies_conversion_completed? }.from(+ false,+ ).to(true)+ end++ it "enqueues one stats backfill job" do+ expect_enqueued_with(+ job: :backfill_nested_reply_stats,+ args: {+ category_id: category.id,+ },+ ) { result }+ end++ it "does not enqueue one stats backfill job per converted batch" do+ SiteSetting.nested_replies_backfill_batch_size = 1+ Fabricate(:topic, category: category)+ Fabricate(:topic, category: category)++ expect { result }.to change { Jobs::BackfillNestedReplyStats.jobs.size }.by(1)+ end++ it "skips stats backfill when no topics are converted" do+ Fabricate(:nested_topic, topic: topic)++ expect_not_enqueued_with(job: :backfill_nested_reply_stats) { result }+ end+ end+ end+end