A platform for community discussion. Free, open, simple.
DEV: add service objects for accept_answer and unaccept_answer (#37878)
David Battersbyce377f6949d0
diff --git a/plugins/discourse-assign/spec/integration/solved_integration_spec.rb b/plugins/discourse-assign/spec/integration/solved_integration_spec.rbindex fec9c9e9478..f35c39d3a67 100644--- a/plugins/discourse-assign/spec/integration/solved_integration_spec.rb+++ b/plugins/discourse-assign/spec/integration/solved_integration_spec.rb@@ -1,13 +1,14 @@# frozen_string_literal: trueRSpec.describe "Solved integration", if: defined?(DiscourseSolved) do- fab!(:topic)- fab!(:post) { Fabricate(:post, topic: topic) }fab!(:user)fab!(:group)+ fab!(:topic) { Fabricate(:topic_with_op, user: user) }+ fab!(:post) { Fabricate(:post, topic: topic) }before doSiteSetting.solved_enabled = true+ SiteSetting.allow_solved_on_all_topics = trueSiteSetting.assign_enabled = trueSiteSetting.enable_assign_status = trueSiteSetting.assign_allowed_on_groups = "#{group.id}"@@ -26,7 +27,7 @@ RSpec.describe "Solved integration", if: defined?(DiscourseSolved) doexpect(result[:success]).to eq(true)expect(topic.assignment.status).to eq("New")- DiscourseSolved.accept_answer!(post, user)+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: post.id }, guardian: user.guardian)topic.reloadexpect(topic.solved.answer_post_id).to eq(post.id)@@ -38,11 +39,11 @@ RSpec.describe "Solved integration", if: defined?(DiscourseSolved) doresult = assigner.assign(user)expect(result[:success]).to eq(true)- DiscourseSolved.accept_answer!(post, user)+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: post.id }, guardian: user.guardian)expect(topic.assignment.reload.status).to eq("Done")- DiscourseSolved.unaccept_answer!(post)+ DiscourseSolved::UnacceptAnswer.call!(params: { post_id: post.id }, guardian: user.guardian)expect(topic.assignment.reload.status).to eq("New")end@@ -65,11 +66,21 @@ RSpec.describe "Solved integration", if: defined?(DiscourseSolved) dopost_response = Fabricate(:post, topic: topic_question, user: user_3)Assigner.new(post_response, user_3).assign(user_3)- DiscourseSolved.accept_answer!(post_response, user)+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: post_response.id,+ },+ guardian: user.guardian,+ )expect(topic_question.assignment.assigned_to_id).to eq(user_2.id)expect(post_response.assignment.assigned_to_id).to eq(user_3.id)- DiscourseSolved.unaccept_answer!(post_response)+ DiscourseSolved::UnacceptAnswer.call!(+ params: {+ post_id: post_response.id,+ },+ guardian: user.guardian,+ )expect(topic_question.assignment.assigned_to_id).to eq(user_2.id)expect(post_response.assignment.assigned_to_id).to eq(user_3.id)@@ -77,10 +88,10 @@ RSpec.describe "Solved integration", if: defined?(DiscourseSolved) dodescribe "assigned topic reminder" doit "excludes solved topics when ignore_solved_topics_in_assigned_reminder is true" do- other_topic = Fabricate(:topic, title: "Topic that should be there")+ other_topic = Fabricate(:topic_with_op, title: "Topic that should be there")other_post = Fabricate(:post, topic: other_topic, user: user)- other_topic2 = Fabricate(:topic, title: "Topic that should be there2")+ other_topic2 = Fabricate(:topic_with_op, title: "Topic that should be there2")other_post2 = Fabricate(:post, topic: other_topic2, user: user)Assigner.new(other_topic, user).assign(user)@@ -90,7 +101,12 @@ RSpec.describe "Solved integration", if: defined?(DiscourseSolved) dotopics = reminder.send(:assigned_topics, user, order: :asc)expect(topics.to_a.length).to eq(2)- DiscourseSolved.accept_answer!(other_post2, Discourse.system_user)+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: other_post2.id,+ },+ guardian: Discourse.system_user.guardian,+ )topics = reminder.send(:assigned_topics, user, order: :asc)expect(topics.to_a.length).to eq(2)expect(topics).to include(other_topic2)@@ -107,10 +123,10 @@ RSpec.describe "Solved integration", if: defined?(DiscourseSolved) doit "does not count solved topics using assignment_status_on_solve status" doSiteSetting.ignore_solved_topics_in_assigned_reminder = true- other_topic = Fabricate(:topic, title: "Topic that should be there")+ other_topic = Fabricate(:topic_with_op, title: "Topic that should be there")other_post = Fabricate(:post, topic: other_topic, user: user)- other_topic2 = Fabricate(:topic, title: "Topic that should be there2")+ other_topic2 = Fabricate(:topic_with_op, title: "Topic that should be there2")other_post2 = Fabricate(:post, topic: other_topic2, user: user)Assigner.new(other_topic, user).assign(user)@@ -119,7 +135,12 @@ RSpec.describe "Solved integration", if: defined?(DiscourseSolved) doreminder = PendingAssignsReminder.newexpect(reminder.send(:assigned_count_for, user)).to eq(2)- DiscourseSolved.accept_answer!(other_post2, Discourse.system_user)+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: other_post2.id,+ },+ guardian: Discourse.system_user.guardian,+ )expect(reminder.send(:assigned_count_for, user)).to eq(1)endenddiff --git a/plugins/discourse-gamification/spec/lib/scorables/solutions_spec.rb b/plugins/discourse-gamification/spec/lib/scorables/solutions_spec.rbindex 1f406dfe5f5..0f5b7b58627 100644--- a/plugins/discourse-gamification/spec/lib/scorables/solutions_spec.rb+++ b/plugins/discourse-gamification/spec/lib/scorables/solutions_spec.rb@@ -2,12 +2,15 @@RSpec.describe DiscourseGamification::Solutions dofab!(:category)- fab!(:topic) { Fabricate(:topic, category: category) }+ fab!(:topic) { Fabricate(:topic_with_op, category: category) }fab!(:question_user, :user)fab!(:answer_user, :user)fab!(:answer_post) { Fabricate(:post, topic: topic, user: answer_user) }- before { SiteSetting.solution_score_value = 5 }+ before do+ SiteSetting.allow_solved_on_all_topics = true+ SiteSetting.solution_score_value = 5+ endit "is enabled when score value is positive" doexpect(described_class).to be_enabled@@ -24,19 +27,34 @@ RSpec.describe DiscourseGamification::Solutions doit "scores accepted answers correctly" dofreeze_time DateTime.parse("2024-01-01 12:00")- DiscourseSolved.accept_answer!(answer_post, Discourse.system_user)+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: answer_post.id,+ },+ guardian: Discourse.system_user.guardian,+ )expect(query_results).to contain_exactly(have_attributes(user_id: answer_user.id, date: Time.current.beginning_of_day, points: 5.0),)- DiscourseSolved.unaccept_answer!(answer_post, topic:)+ DiscourseSolved::UnacceptAnswer.call!(+ params: {+ post_id: answer_post.id,+ },+ guardian: Discourse.system_user.guardian,+ )expect(query_results).to be_emptyendit "doesn't score self-accepted answers" dotopic.update!(user: answer_user)- DiscourseSolved.accept_answer!(answer_post, Discourse.system_user)+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: answer_post.id,+ },+ guardian: Discourse.system_user.guardian,+ )expect(query_results).to be_emptyenddiff --git a/plugins/discourse-solved/app/controllers/discourse_solved/answer_controller.rb b/plugins/discourse-solved/app/controllers/discourse_solved/answer_controller.rbindex 67ac86d29c6..63fd387f31a 100644--- a/plugins/discourse-solved/app/controllers/discourse_solved/answer_controller.rb+++ b/plugins/discourse-solved/app/controllers/discourse_solved/answer_controller.rb@@ -3,36 +3,39 @@class DiscourseSolved::AnswerController < ::ApplicationControllerrequires_plugin DiscourseSolved::PLUGIN_NAME- def accept- limit_accepts-- post = Post.find(params[:id].to_i)-- topic = post.topic- topic ||= Topic.with_deleted.find(post.topic_id) if guardian.is_staff?+ before_action :limit_accepts- guardian.ensure_can_accept_answer!(topic, post)-- accepted_answer = DiscourseSolved.accept_answer!(post, current_user, topic: topic)-- render_json_dump(accepted_answer)+ def accept+ DiscourseSolved::AcceptAnswer.call(params: { post_id: params[:id] }, guardian:) do+ on_success { |topic:| render_json_dump(topic.accepted_answer_post_info) }+ on_model_not_found(:post) { raise Discourse::NotFound }+ on_model_not_found(:topic) { raise Discourse::NotFound }+ on_failed_policy(:can_accept_answer) { raise Discourse::InvalidAccess }+ on_model_errors(:solved) do |model|+ render_json_error(model, type: :record_invalid, status: 422)+ end+ on_failed_contract do |contract|+ render json: failed_json.merge(errors: contract.errors.full_messages), status: :bad_request+ end+ on_failure { render json: failed_json, status: :unprocessable_entity }+ endenddef unaccept- limit_accepts-- post = Post.find(params[:id].to_i)-- topic = post.topic- topic ||= Topic.with_deleted.find(post.topic_id) if guardian.is_staff?-- guardian.ensure_can_accept_answer!(topic, post)-- DiscourseSolved.unaccept_answer!(post, topic: topic)-- render json: success_json+ DiscourseSolved::UnacceptAnswer.call(params: { post_id: params[:id] }, guardian:) do+ on_success { render json: success_json }+ on_model_not_found(:post) { raise Discourse::NotFound }+ on_model_not_found(:topic) { raise Discourse::NotFound }+ on_failed_policy(:can_unaccept_answer) { raise Discourse::InvalidAccess }+ on_failed_contract do |contract|+ render json: failed_json.merge(errors: contract.errors.full_messages), status: :bad_request+ end+ on_failure { render json: failed_json, status: :unprocessable_entity }+ endend+ private+def limit_acceptsreturn if current_user.staff?run_rate_limiter =diff --git a/plugins/discourse-solved/app/models/discourse_solved/solved_topic.rb b/plugins/discourse-solved/app/models/discourse_solved/solved_topic.rbindex 1b9dd352b6e..38f6eddd095 100644--- a/plugins/discourse-solved/app/models/discourse_solved/solved_topic.rb+++ b/plugins/discourse-solved/app/models/discourse_solved/solved_topic.rb@@ -5,13 +5,30 @@ module DiscourseSolvedself.table_name = "discourse_solved_solved_topics"belongs_to :topic, class_name: "Topic"- belongs_to :answer_post, class_name: "Post", foreign_key: "answer_post_id"+ belongs_to :answer_post, -> { with_deleted }, class_name: "Post", foreign_key: "answer_post_id"belongs_to :accepter, class_name: "User", foreign_key: "accepter_user_id"belongs_to :topic_timer, dependent: :destroyvalidates :topic_id, presence: truevalidates :answer_post_id, presence: truevalidates :accepter_user_id, presence: true++ before_create :auto_close_topic_timer++ private++ def auto_close_topic_timer+ hours = topic.solved_auto_close_hours+ return if hours.zero? || topic.closed?++ self.topic_timer =+ topic.set_or_create_timer(+ TopicTimer.types[:silent_close],+ nil,+ based_on_last_post: true,+ duration_minutes: hours * 60,+ )+ endendenddiff --git a/plugins/discourse-solved/app/services/discourse_solved/accept_answer.rb b/plugins/discourse-solved/app/services/discourse_solved/accept_answer.rbnew file mode 100644index 00000000000..c6ec5500db2--- /dev/null+++ b/plugins/discourse-solved/app/services/discourse_solved/accept_answer.rb@@ -0,0 +1,143 @@+# frozen_string_literal: true++class DiscourseSolved::AcceptAnswer+ include Service::Base++ params do+ attribute :post_id, :integer++ validates :post_id, presence: true+ end++ model :post+ model :topic+ policy :can_accept_answer++ lock(:topic) do+ transaction do+ only_if(:previous_answer_exists) { step :revoke_previous_accepted_answer }+ step :credit_post_author+ model :solved, :mark_as_solved+ only_if(:should_notify_post_author) { step :notify_post_author }+ only_if(:should_notify_topic_owner) { step :notify_topic_owner }+ end+ end++ only_if(:accepted_solution_webhooks_active) { step :enqueue_web_hooks }+ only_if(:topic_will_auto_close) { step :publish_topic_reload }+ step :publish_solution++ private++ def fetch_post(params:)+ Post.find_by(id: params.post_id)+ end++ def fetch_topic(post:, guardian:)+ return Topic.with_deleted.find_by(id: post.topic_id) if guardian.is_staff?+ post.topic+ end++ def can_accept_answer(guardian:, topic:, post:)+ guardian.can_accept_answer?(topic, post)+ end++ def previous_answer_exists(topic:)+ topic.solved&.answer_post_id.present?+ end++ def revoke_previous_accepted_answer(topic:)+ UserAction.where(+ action_type: UserAction::SOLVED,+ target_post: topic.solved.answer_post,+ ).destroy_all+ topic.solved.destroy!+ end++ def credit_post_author(post:, guardian:)+ UserAction.log_action!(+ action_type: UserAction::SOLVED,+ user_id: post.user_id,+ acting_user_id: guardian.user.id,+ target_post_id: post.id,+ target_topic_id: post.topic_id,+ )+ end++ def mark_as_solved(post:, topic:, guardian:)+ DiscourseSolved::SolvedTopic.create(topic:, answer_post: post, accepter: guardian.user)+ end++ def should_notify_post_author(post:, guardian:)+ return if guardian.user.id == post.user_id+ screener = UserCommScreener.new(acting_user_id: guardian.user.id, target_user_ids: post.user_id)+ !screener.ignoring_or_muting_actor?(post.user_id)+ end++ def notify_post_author(post:, topic:, guardian:)+ Notification.create!(+ notification_type: Notification.types[:custom],+ user_id: post.user_id,+ topic_id: post.topic_id,+ post_number: post.post_number,+ data: {+ message: "solved.accepted_notification",+ display_username: guardian.user.username,+ topic_title: topic.title,+ title: "solved.notification.title",+ }.to_json,+ )+ end++ def should_notify_topic_owner(topic:, guardian:)+ return unless SiteSetting.notify_on_staff_accept_solved+ return if guardian.user.id == topic.user_id+ screener =+ UserCommScreener.new(acting_user_id: guardian.user.id, target_user_ids: topic.user_id)+ !screener.ignoring_or_muting_actor?(topic.user_id)+ end++ def notify_topic_owner(post:, topic:, guardian:)+ Notification.create!(+ notification_type: Notification.types[:custom],+ user_id: topic.user_id,+ topic_id: post.topic_id,+ post_number: post.post_number,+ data: {+ message: "solved.accepted_notification",+ display_username: guardian.user.username,+ topic_title: topic.title,+ title: "solved.notification.title",+ }.to_json,+ )+ end++ def topic_will_auto_close(solved:)+ solved.topic_timer.present?+ end++ def publish_topic_reload(topic:)+ MessageBus.publish(+ "/topic/#{topic.id}",+ { reload_topic: true },+ topic.secure_audience_publish_messages,+ )+ end++ def accepted_solution_webhooks_active+ WebHook.active_web_hooks(:accepted_solution).exists?+ end++ def enqueue_web_hooks(post:)+ WebHook.enqueue_solved_hooks(:accepted_solution, post, WebHook.generate_payload(:post, post))+ end++ def publish_solution(post:, topic:)+ DiscourseEvent.trigger(:accepted_solution, post)+ MessageBus.publish(+ "/topic/#{topic.id}",+ { type: :accepted_solution, accepted_answer: topic.reload.accepted_answer_post_info },+ topic.secure_audience_publish_messages,+ )+ end+enddiff --git a/plugins/discourse-solved/app/services/discourse_solved/unaccept_answer.rb b/plugins/discourse-solved/app/services/discourse_solved/unaccept_answer.rbnew file mode 100644index 00000000000..7c0c607bb42--- /dev/null+++ b/plugins/discourse-solved/app/services/discourse_solved/unaccept_answer.rb@@ -0,0 +1,82 @@+# frozen_string_literal: true++class DiscourseSolved::UnacceptAnswer+ include Service::Base++ params do+ attribute :post_id, :integer++ validates :post_id, presence: true+ end++ model :post+ model :topic+ policy :can_unaccept_answer++ only_if(:post_is_accepted_answer) do+ lock(:topic) do+ transaction do+ step :revoke_solved_credit+ step :remove_accepted_answer_notification+ step :unmark_as_solved+ end+ end++ only_if(:unaccepted_solution_webhooks_active) { step :enqueue_web_hooks }+ step :publish_unaccepted+ end++ private++ def fetch_post(params:, guardian:)+ return Post.with_deleted.find_by(id: params.post_id) if guardian.is_staff?+ Post.find_by(id: params.post_id)+ end++ def fetch_topic(post:, guardian:)+ return Topic.with_deleted.find_by(id: post.topic_id) if guardian.is_staff?+ post.topic+ end++ def can_unaccept_answer(guardian:, topic:, post:)+ guardian.can_unaccept_answer?(topic, post)+ end++ def post_is_accepted_answer(topic:, post:)+ topic.solved&.answer_post == post+ end++ def revoke_solved_credit(post:)+ UserAction.where(action_type: UserAction::SOLVED, target_post: post).destroy_all+ end++ def remove_accepted_answer_notification(post:, topic:)+ Notification.find_by(+ topic:,+ notification_type: Notification.types[:custom],+ user: post.user,+ post_number: post.post_number,+ )&.destroy!+ end++ def unmark_as_solved(topic:)+ topic.solved.destroy!+ end++ def unaccepted_solution_webhooks_active+ WebHook.active_web_hooks(:unaccepted_solution).exists?+ end++ def enqueue_web_hooks(post:)+ WebHook.enqueue_solved_hooks(:unaccepted_solution, post, WebHook.generate_payload(:post, post))+ end++ def publish_unaccepted(post:, topic:)+ DiscourseEvent.trigger(:unaccepted_solution, post)+ MessageBus.publish(+ "/topic/#{topic.id}",+ { type: :unaccepted_solution },+ topic.secure_audience_publish_messages,+ )+ end+enddiff --git a/plugins/discourse-solved/lib/discourse_dev/discourse_solved.rb b/plugins/discourse-solved/lib/discourse_dev/discourse_solved.rbindex 3d72e7e2ab9..07d5e7fcb77 100644--- a/plugins/discourse-solved/lib/discourse_dev/discourse_solved.rb+++ b/plugins/discourse-solved/lib/discourse_dev/discourse_solved.rb@@ -49,7 +49,12 @@ module DiscourseDevpost = DiscourseDev::Post.new(solved_topic, 1).create!end- ::DiscourseSolved.accept_answer!(post, post.topic.user, topic: post.topic)+ ::DiscourseSolved::AcceptAnswer.call(+ params: {+ post_id: post.id,+ },+ guardian: Guardian.new(post.topic.user),+ )endendenddiff --git a/plugins/discourse-solved/lib/discourse_solved/category_extension.rb b/plugins/discourse-solved/lib/discourse_solved/category_extension.rbindex 57772cb52a8..1921d5196e1 100644--- a/plugins/discourse-solved/lib/discourse_solved/category_extension.rb+++ b/plugins/discourse-solved/lib/discourse_solved/category_extension.rb@@ -5,6 +5,11 @@ module DiscourseSolved::CategoryExtensionprepended { after_save :reset_accepted_cache, if: -> { SiteSetting.solved_enabled? } }+ def solved_auto_close_hours+ hours = custom_fields["solved_topics_auto_close_hours"].to_i+ [hours, DiscourseSolved::MAX_AUTO_CLOSE_HOURS].min+ end+privatedef reset_accepted_cachediff --git a/plugins/discourse-solved/lib/discourse_solved/guardian_extensions.rb b/plugins/discourse-solved/lib/discourse_solved/guardian_extensions.rbindex 375bb39a641..49d7d508b8e 100644--- a/plugins/discourse-solved/lib/discourse_solved/guardian_extensions.rb+++ b/plugins/discourse-solved/lib/discourse_solved/guardian_extensions.rb@@ -46,5 +46,9 @@ module DiscourseSolvedtopic.user_id == current_user.id && !topic.closed && SiteSetting.accept_solutions_topic_authorend++ def can_unaccept_answer?(topic, post)+ can_accept_answer?(topic, post) || (is_staff? && topic.solved.present?)+ endendenddiff --git a/plugins/discourse-solved/lib/discourse_solved/topic_extension.rb b/plugins/discourse-solved/lib/discourse_solved/topic_extension.rbindex c3494dda11e..f98762aaef2 100644--- a/plugins/discourse-solved/lib/discourse_solved/topic_extension.rb+++ b/plugins/discourse-solved/lib/discourse_solved/topic_extension.rb@@ -5,6 +5,11 @@ module DiscourseSolved::TopicExtensionprepended { has_one :solved, class_name: "DiscourseSolved::SolvedTopic", dependent: :destroy }+ def solved_auto_close_hours+ hours = category&.solved_auto_close_hours || 0+ hours.zero? ? SiteSetting.solved_topics_auto_close_hours : hours+ end+def accepted_answer_post_inforeturn unless solvedreturn unless answer_post = solved.answer_postdiff --git a/plugins/discourse-solved/lib/discourse_solved/topics_controller_extension.rb b/plugins/discourse-solved/lib/discourse_solved/topics_controller_extension.rbindex 8640fdc7225..56a52aeb825 100644--- a/plugins/discourse-solved/lib/discourse_solved/topics_controller_extension.rb+++ b/plugins/discourse-solved/lib/discourse_solved/topics_controller_extension.rb@@ -13,7 +13,14 @@ module DiscourseSolvedsolution_post_id = topic.solved.answer_post_idif post_ids.map(&:to_i).include?(solution_post_id)solution_post = Post.find_by(id: solution_post_id)- DiscourseSolved.unaccept_answer!(solution_post) if solution_post+ if solution_post+ DiscourseSolved::UnacceptAnswer.call(+ params: {+ post_id: solution_post.id,+ },+ guardian: Discourse.system_user.guardian,+ )+ endendendenddiff --git a/plugins/discourse-solved/plugin.rb b/plugins/discourse-solved/plugin.rbindex 15e4f7506c6..a259011ba99 100644--- a/plugins/discourse-solved/plugin.rb+++ b/plugins/discourse-solved/plugin.rb@@ -19,6 +19,7 @@ register_asset "stylesheets/mobile/solutions.scss", :mobilemodule ::DiscourseSolvedPLUGIN_NAME = "discourse-solved"ENABLE_ACCEPTED_ANSWERS_CUSTOM_FIELD = "enable_accepted_answers"+ MAX_AUTO_CLOSE_HOURS = 20.years.to_i / 1.hour.to_iendrequire_relative "lib/discourse_solved/engine"@@ -28,152 +29,6 @@ after_initialize doSeedFu.fixture_paths << Rails.root.join("plugins", "discourse-solved", "db", "fixtures").to_s- module ::DiscourseSolved- def self.accept_answer!(post, acting_user, topic: nil)- topic ||= post.topic-- DistributedMutex.synchronize("discourse_solved_toggle_answer_#{topic.id}") do- solved = topic.solved-- ActiveRecord::Base.transaction do- if previous_accepted_post_id = solved&.answer_post_id- UserAction.where(- action_type: UserAction::SOLVED,- target_post_id: previous_accepted_post_id,- ).destroy_all- solved.destroy!- else- UserAction.log_action!(- action_type: UserAction::SOLVED,- user_id: post.user_id,- acting_user_id: acting_user.id,- target_post_id: post.id,- target_topic_id: post.topic_id,- )- end-- solved =- DiscourseSolved::SolvedTopic.new(topic:, answer_post: post, accepter: acting_user)-- if acting_user.id != post.user_id && notify_solved?(recipient: post.user, acting_user:)- Notification.create!(- notification_type: Notification.types[:custom],- user_id: post.user_id,- topic_id: post.topic_id,- post_number: post.post_number,- data: {- message: "solved.accepted_notification",- display_username: acting_user.username,- topic_title: topic.title,- title: "solved.notification.title",- }.to_json,- )- end-- if SiteSetting.notify_on_staff_accept_solved && acting_user.id != topic.user_id &&- notify_solved?(recipient: topic.user, acting_user:)- Notification.create!(- notification_type: Notification.types[:custom],- user_id: topic.user_id,- topic_id: post.topic_id,- post_number: post.post_number,- data: {- message: "solved.accepted_notification",- display_username: acting_user.username,- topic_title: topic.title,- title: "solved.notification.title",- }.to_json,- )- end-- auto_close_hours = 0- if topic&.category.present?- auto_close_hours = topic.category.custom_fields["solved_topics_auto_close_hours"].to_i- auto_close_hours = 175_200 if auto_close_hours > 175_200 # 20 years- end-- auto_close_hours = SiteSetting.solved_topics_auto_close_hours if auto_close_hours == 0-- if (auto_close_hours > 0) && !topic.closed- topic_timer =- topic.set_or_create_timer(- TopicTimer.types[:silent_close],- nil,- based_on_last_post: true,- duration_minutes: auto_close_hours * 60,- )- solved.topic_timer = topic_timer-- MessageBus.publish("/topic/#{topic.id}", reload_topic: true)- end-- solved.save!- end-- if WebHook.active_web_hooks(:accepted_solution).exists?- payload = WebHook.generate_payload(:post, post)- WebHook.enqueue_solved_hooks(:accepted_solution, post, payload)- end-- accepted_answer = topic.reload.accepted_answer_post_info-- message = { type: :accepted_solution, accepted_answer: }-- DiscourseEvent.trigger(:accepted_solution, post)-- secure_audience = topic.secure_audience_publish_messages- # MessageBus.publish will raise an error if user_ids or group_ids are an empty array.- if secure_audience[:user_ids] != [] && secure_audience[:group_ids] != []- MessageBus.publish("/topic/#{topic.id}", message, secure_audience)- end-- accepted_answer- end- end-- def self.unaccept_answer!(post, topic: nil)- topic ||= post.topic- topic ||= Topic.unscoped.find_by(id: post.topic_id)- return if topic.nil?- return if topic.solved.nil?- return if topic.solved.answer_post_id != post.id-- DistributedMutex.synchronize("discourse_solved_toggle_answer_#{topic.id}") do- solved = topic.solved-- ActiveRecord::Base.transaction do- UserAction.where(action_type: UserAction::SOLVED, target_post_id: post.id).destroy_all- Notification.find_by(- notification_type: Notification.types[:custom],- user_id: post.user_id,- topic_id: post.topic_id,- post_number: post.post_number,- )&.destroy!- solved.destroy!- end-- if WebHook.active_web_hooks(:unaccepted_solution).exists?- payload = WebHook.generate_payload(:post, post)- WebHook.enqueue_solved_hooks(:unaccepted_solution, post, payload)- end-- DiscourseEvent.trigger(:unaccepted_solution, post)- MessageBus.publish("/topic/#{topic.id}", type: :unaccepted_solution)- end- end-- def self.notify_solved?(recipient:, acting_user:)- !UserCommScreener.new(- acting_user_id: acting_user.id,- target_user_ids: recipient.id,- ).ignoring_or_muting_actor?(recipient.id)- end-- def self.skip_db?- defined?(GlobalSetting.skip_db?) && GlobalSetting.skip_db?- end- end-reloadable_patch do::Guardian.prepend(DiscourseSolved::GuardianExtensions)::WebHook.prepend(DiscourseSolved::WebHookExtension)@@ -275,12 +130,19 @@ after_initialize doadd_to_serializer(:user_summary, :solved_count) { object.solved_count }add_to_serializer(:post, :can_accept_answer) { scope.can_accept_answer?(topic, object) }add_to_serializer(:post, :can_unaccept_answer) do- scope.can_accept_answer?(topic, object) && accepted_answer+ scope.can_unaccept_answer?(topic, object) && accepted_answerendadd_to_serializer(:post, :accepted_answer) { topic&.solved&.answer_post_id == object.id }add_to_serializer(:post, :topic_accepted_answer) { topic&.solved&.present? }- on(:post_destroyed) { |post| DiscourseSolved.unaccept_answer!(post) }+ on(:post_destroyed) do |post|+ DiscourseSolved::UnacceptAnswer.call(+ params: {+ post_id: post.id,+ },+ guardian: Discourse.system_user.guardian,+ )+ endon(:filter_auto_bump_topics) do |_category, filters|filters.push(@@ -317,7 +179,14 @@ after_initialize doif !new_allowedif topic.solved.present?post = topic.solved.answer_post- DiscourseSolved.unaccept_answer!(post, topic: topic) if post+ if post+ DiscourseSolved::UnacceptAnswer.call(+ params: {+ post_id: post.id,+ },+ guardian: Discourse.system_user.guardian,+ )+ endendendenddiff --git a/plugins/discourse-solved/spec/components/composer_messages_finder_spec.rb b/plugins/discourse-solved/spec/components/composer_messages_finder_spec.rbindex 4b1d2b08f29..3fe67fdc327 100644--- a/plugins/discourse-solved/spec/components/composer_messages_finder_spec.rb+++ b/plugins/discourse-solved/spec/components/composer_messages_finder_spec.rb@@ -6,10 +6,13 @@ require "composer_messages_finder"describe ComposerMessagesFinder dodescribe ".check_topic_is_solved" dofab!(:user)- fab!(:topic)+ fab!(:topic, :topic_with_op)fab!(:post) { Fabricate(:post, topic: topic, user: Fabricate(:user)) }- before { SiteSetting.disable_solved_education_message = false }+ before do+ SiteSetting.disable_solved_education_message = false+ SiteSetting.allow_solved_on_all_topics = true+ endit "does not show message without a topic id" doexpect(@@ -31,7 +34,12 @@ describe ComposerMessagesFinder doit "does not show message if disable_solved_education_message is true" doSiteSetting.disable_solved_education_message = true- DiscourseSolved.accept_answer!(post, Discourse.system_user)+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: post.id,+ },+ guardian: Discourse.system_user.guardian,+ )expect(described_class.new(user,@@ -42,7 +50,12 @@ describe ComposerMessagesFinder doendit "shows message if the topic is solved" do- DiscourseSolved.accept_answer!(post, Discourse.system_user)+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: post.id,+ },+ guardian: Discourse.system_user.guardian,+ )message =described_class.new(user,diff --git a/plugins/discourse-solved/spec/components/post_revisor_spec.rb b/plugins/discourse-solved/spec/components/post_revisor_spec.rbindex ed1eec57984..a70510208ba 100644--- a/plugins/discourse-solved/spec/components/post_revisor_spec.rb+++ b/plugins/discourse-solved/spec/components/post_revisor_spec.rb@@ -38,7 +38,7 @@ describe PostRevisor dobefore doSiteSetting.solved_enabled = true- DiscourseSolved.accept_answer!(reply, admin)+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: reply.id }, guardian: admin.guardian)topic.reloadend@@ -86,7 +86,7 @@ describe PostRevisor doit "unaccepts the answer when the solved tag is removed" doSiteSetting.enable_solved_tags = solved_tag.name- DiscourseSolved.accept_answer!(reply, admin)+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: reply.id }, guardian: admin.guardian)described_class.new(post).revise!(admin, tags: [])expect(topic.reload.solved).to be_nil@@ -106,7 +106,7 @@ describe PostRevisor dotopic = Fabricate(:topic, category: category_solved, tags: [solved_tag])post = Fabricate(:post, topic: topic)reply = Fabricate(:post, topic: topic, post_number: 2)- DiscourseSolved.accept_answer!(reply, admin)+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: reply.id }, guardian: admin.guardian)described_class.new(post).revise!(admin, { category_id: category.id })topic.reload@@ -119,7 +119,7 @@ describe PostRevisor dotopic = Fabricate(:topic, category: category_solved, tags: [solved_tag])post = Fabricate(:post, topic: topic)reply = Fabricate(:post, topic: topic, post_number: 2)- DiscourseSolved.accept_answer!(reply, admin)+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: reply.id }, guardian: admin.guardian)described_class.new(post).revise!(admin, tags: [])topic.reload@@ -132,7 +132,7 @@ describe PostRevisor dotopic = Fabricate(:topic, category: category_solved, tags: [solved_tag])post = Fabricate(:post, topic: topic)reply = Fabricate(:post, topic: topic, post_number: 2)- DiscourseSolved.accept_answer!(reply, admin)+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: reply.id }, guardian: admin.guardian)described_class.new(post).revise!(admin, { category_id: category.id, tags: [] })expect(topic.reload.solved).to be_nildiff --git a/plugins/discourse-solved/spec/integration/solved_spec.rb b/plugins/discourse-solved/spec/integration/solved_spec.rbindex 4161a706667..378030a5a9c 100644--- a/plugins/discourse-solved/spec/integration/solved_spec.rb+++ b/plugins/discourse-solved/spec/integration/solved_spec.rb@@ -111,21 +111,18 @@ RSpec.describe "Managing Posts solved status" doafter { SearchIndexer.disable }it "can prioritize solved topics in search" do- normal_post =- Fabricate(- :post,- raw: "My reply carrot",- topic: Fabricate(:topic, title: "A topic that is not solved but open"),- )+ normal_topic = Fabricate(:topic_with_op, title: "A topic that is not solved but open")+ normal_post = Fabricate(:post, raw: "My reply carrot", topic: normal_topic)- solved_post =- Fabricate(- :post,- raw: "My solution carrot",- topic: Fabricate(:topic, title: "A topic that will be closed", closed: true),- )+ solved_topic = Fabricate(:topic_with_op, title: "A topic that will be closed", closed: true)+ solved_post = Fabricate(:post, raw: "My solution carrot", topic: solved_topic)- DiscourseSolved.accept_answer!(solved_post, Discourse.system_user)+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: solved_post.id,+ },+ guardian: Discourse.system_user.guardian,+ )result = Search.execute("carrot")expect(result.posts.pluck(:id)).to eq([normal_post.id, solved_post.id])@@ -173,7 +170,12 @@ RSpec.describe "Managing Posts solved status" dofab!(:post_unsolved_2) { Fabricate(:post, topic: topic_unsolved_2) }fab!(:post_solved) dopost = Fabricate(:post, topic: topic_solved)- DiscourseSolved.accept_answer!(post, Discourse.system_user)+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: post.id,+ },+ guardian: Discourse.system_user.guardian,+ )postendfab!(:post_disabled_1) { Fabricate(:post, topic: topic_disabled_1) }@@ -226,9 +228,15 @@ RSpec.describe "Managing Posts solved status" docategory = Fabricate(:category_with_definition)post = create_post(category: category)+ reply = create_post(topic_id: post.topic_id)post2 = create_post(category: category)- DiscourseSolved.accept_answer!(post, Discourse.system_user)+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: reply.id,+ },+ guardian: Discourse.system_user.guardian,+ )category.num_auto_bump_daily = 2category.save!@@ -241,7 +249,7 @@ RSpec.describe "Managing Posts solved status" doexpect(category.auto_bump_topic!).to eq(false)- expect(post.topic.reload.posts_count).to eq(1)+ expect(post.topic.reload.posts_count).to eq(2)expect(post2.topic.reload.posts_count).to eq(2)endend@@ -300,9 +308,14 @@ RSpec.describe "Managing Posts solved status" doop = topic.useruser = post.user- expect { DiscourseSolved.accept_answer!(post, Discourse.system_user) }.to change {- user.notifications.count- }.by(1) & change { op.notifications.count }.by(1)+ expect {+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: post.id,+ },+ guardian: Discourse.system_user.guardian,+ )+ }.to change { user.notifications.count }.by(1) & change { op.notifications.count }.by(1)notification = user.notifications.lastexpect(notification.notification_type).to eq(Notification.types[:custom])@@ -328,18 +341,28 @@ RSpec.describe "Managing Posts solved status" dotopic = Fabricate(:topic, user: Fabricate(:user))post = Fabricate(:post, post_number: 2, topic: topic, user: author)- expect { DiscourseSolved.accept_answer!(post, solution_accepter) }.not_to change {- author.notifications.count- }+ expect {+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: post.id,+ },+ guardian: solution_accepter.guardian,+ )+ }.not_to change { author.notifications.count }endit "does not send notification to topic author" dotopic = Fabricate(:topic, user: author)post = Fabricate(:post, post_number: 2, topic: topic, user: Fabricate(:user))- expect { DiscourseSolved.accept_answer!(post, solution_accepter) }.not_to change {- author.notifications.count- }+ expect {+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: post.id,+ },+ guardian: solution_accepter.guardian,+ )+ }.not_to change { author.notifications.count }endend@@ -361,7 +384,7 @@ RSpec.describe "Managing Posts solved status" dotopic.trash!(Discourse.system_user)post "/solution/accept.json", params: { id: p1.id }- expect(response.status).to eq(403)+ expect(response.status).to eq(404)sign_in(Fabricate(:admin))post "/solution/accept.json", params: { id: p1.id }@@ -434,7 +457,7 @@ RSpec.describe "Managing Posts solved status" dodescribe "when solved_topics_auto_close_hours is enabled" dobefore doSiteSetting.solved_topics_auto_close_hours = 2- DiscourseSolved.accept_answer!(p1, user)+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: p1.id }, guardian: user.guardian)topic.reloadend@@ -451,7 +474,7 @@ RSpec.describe "Managing Posts solved status" doendit "triggers a webhook" do- DiscourseSolved.accept_answer!(p1, user)+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: p1.id }, guardian: user.guardian)Fabricate(:solved_web_hook)post "/solution/unaccept.json", params: { id: p1.id }@@ -482,37 +505,195 @@ RSpec.describe "Managing Posts solved status" doendend- describe "#unaccept_answer!" do+ context "with discourse-assign installed", if: defined?(DiscourseAssign) do+ let(:admin) { Fabricate(:admin) }+ fab!(:group)+ before do+ SiteSetting.solved_enabled = true+ SiteSetting.assign_enabled = true+ SiteSetting.enable_assign_status = true+ SiteSetting.assign_allowed_on_groups = "#{group.id}"+ SiteSetting.assigns_public = true+ SiteSetting.assignment_status_on_solve = "Done"+ SiteSetting.assignment_status_on_unsolve = "New"+ SiteSetting.ignore_solved_topics_in_assigned_reminder = false+ group.add(p1.acting_user)+ group.add(user)++ sign_in(user)+ end++ describe "updating assignment status on solve when assignment_status_on_solve is set" do+ it "update all assignments to this status when a post is accepted" do+ assigner = Assigner.new(p1.topic, user)+ result = assigner.assign(user)+ expect(result[:success]).to eq(true)++ expect(p1.topic.assignment.status).to eq("New")+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: p1.id }, guardian: user.guardian)+ topic.reload++ expect(topic.solved.answer_post_id).to eq(p1.id)+ expect(p1.topic.assignment.reload.status).to eq("Done")+ end++ it "update all assignments to this status when a post is unaccepted" do+ assigner = Assigner.new(p1.topic, user)+ result = assigner.assign(user)+ expect(result[:success]).to eq(true)++ DiscourseSolved::AcceptAnswer.call!(params: { post_id: p1.id }, guardian: user.guardian)++ expect(p1.reload.topic.assignment.reload.status).to eq("Done")++ DiscourseSolved::UnacceptAnswer.call!(+ params: {+ post_id: p1.id,+ },+ guardian: Discourse.system_user.guardian,+ )++ expect(p1.reload.topic.assignment.reload.status).to eq("New")+ end++ it "does not update the assignee when a post is accepted" do+ user = Fabricate(:user)+ user_2 = Fabricate(:user)+ user_3 = Fabricate(:user)+ group.add(user)+ group.add(user_2)+ group.add(user_3)++ topic_question = Fabricate(:topic, user: user)++ Fabricate(:post, topic: topic_question, user: user)+ Fabricate(:post, topic: topic_question, user: user_2)++ result = Assigner.new(topic_question, user_2).assign(user_2)+ expect(result[:success]).to eq(true)++ post_response = Fabricate(:post, topic: topic_question, user: user_3)+ Assigner.new(post_response, user_3).assign(user_3)++ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: post_response.id,+ },+ guardian: user.guardian,+ )++ expect(topic_question.assignment.assigned_to_id).to eq(user_2.id)+ expect(post_response.assignment.assigned_to_id).to eq(user_3.id)+ DiscourseSolved::UnacceptAnswer.call!(+ params: {+ post_id: post_response.id,+ },+ guardian: Discourse.system_user.guardian,+ )++ expect(topic_question.assignment.assigned_to_id).to eq(user_2.id)+ expect(post_response.assignment.assigned_to_id).to eq(user_3.id)+ end++ describe "assigned topic reminder" do+ it "excludes solved topics when ignore_solved_topics_in_assigned_reminder is false" do+ other_topic = Fabricate(:topic_with_op, title: "Topic that should be there")+ post = Fabricate(:post, topic: other_topic, user: user)++ other_topic2 = Fabricate(:topic_with_op, title: "Topic that should be there2")+ post2 = Fabricate(:post, topic: other_topic2, user: user)++ Assigner.new(post.topic, user).assign(user)+ Assigner.new(post2.topic, user).assign(user)++ reminder = PendingAssignsReminder.new+ topics = reminder.send(:assigned_topics, user, order: :asc)+ expect(topics.to_a.length).to eq(2)++ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: post2.id,+ },+ guardian: Discourse.system_user.guardian,+ )+ topics = reminder.send(:assigned_topics, user, order: :asc)+ expect(topics.to_a.length).to eq(2)+ expect(topics).to include(other_topic2)++ SiteSetting.ignore_solved_topics_in_assigned_reminder = true+ topics = reminder.send(:assigned_topics, user, order: :asc)+ expect(topics.to_a.length).to eq(1)+ expect(topics).not_to include(other_topic2)+ expect(topics).to include(other_topic)+ end+ end++ describe "assigned count for user" do+ it "does not count solved topics using assignment_status_on_solve status" do+ SiteSetting.ignore_solved_topics_in_assigned_reminder = true++ other_topic = Fabricate(:topic_with_op, title: "Topic that should be there")+ post = Fabricate(:post, topic: other_topic, user: user)++ other_topic2 = Fabricate(:topic_with_op, title: "Topic that should be there2")+ post2 = Fabricate(:post, topic: other_topic2, user: user)++ Assigner.new(post.topic, user).assign(user)+ Assigner.new(post2.topic, user).assign(user)++ reminder = PendingAssignsReminder.new+ expect(reminder.send(:assigned_count_for, user)).to eq(2)++ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: post2.id,+ },+ guardian: Discourse.system_user.guardian,+ )+ expect(reminder.send(:assigned_count_for, user)).to eq(1)+ end+ end+ end+ end++ describe "UnacceptAnswer service" doit "works even when the topic has been deleted" douser = Fabricate(:user, trust_level: 1)topic = Fabricate(:topic, user:)reply = Fabricate(:post, topic:, user:, post_number: 2)- DiscourseSolved.accept_answer!(reply, user)+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: reply.id }, guardian: user.guardian)topic.trash!(Discourse.system_user)reply.reloadexpect(reply.topic).to eq(nil)- expect { DiscourseSolved.unaccept_answer!(reply) }.not_to raise_error+ expect {+ DiscourseSolved::UnacceptAnswer.call!(+ params: {+ post_id: reply.id,+ },+ guardian: Discourse.system_user.guardian,+ )+ }.not_to raise_errorendend- describe "#accept_answer!" do+ describe "AcceptAnswer service" doit "marks the post as the accepted answer correctly" douser = Fabricate(:user, trust_level: 1)topic = Fabricate(:topic, user:)reply1 = Fabricate(:post, topic:, user:, post_number: 2)reply2 = Fabricate(:post, topic:, user:, post_number: 3)- DiscourseSolved.accept_answer!(reply1, user)+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: reply1.id }, guardian: user.guardian)topic.reloadexpect(topic.solved.answer_post_id).to eq(reply1.id)expect(topic.solved.topic_timer).to eq(topic.public_topic_timer)- DiscourseSolved.accept_answer!(reply2, user)+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: reply2.id }, guardian: user.guardian)topic.reloadexpect(topic.solved.answer_post_id).to eq(reply2.id)@@ -521,17 +702,32 @@ RSpec.describe "Managing Posts solved status" dodescribe "user actions stream modifier" doit "correctly list solutions" do- t1 = Fabricate(:topic)- t2 = Fabricate(:topic)- t3 = Fabricate(:topic)+ t1 = Fabricate(:topic_with_op)+ t2 = Fabricate(:topic_with_op)+ t3 = Fabricate(:topic_with_op)p1 = Fabricate(:post, topic: t1, user:)p2 = Fabricate(:post, topic: t2, user:)p3 = Fabricate(:post, topic: t3, user:)- DiscourseSolved.accept_answer!(p1, Discourse.system_user)- DiscourseSolved.accept_answer!(p2, Discourse.system_user)- DiscourseSolved.accept_answer!(p3, Discourse.system_user)+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: p1.id,+ },+ guardian: Discourse.system_user.guardian,+ )+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: p2.id,+ },+ guardian: Discourse.system_user.guardian,+ )+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: p3.id,+ },+ guardian: Discourse.system_user.guardian,+ )t1.trash!(Discourse.system_user)t2.convert_to_private_message(Discourse.system_user)@@ -562,8 +758,18 @@ RSpec.describe "Managing Posts solved status" domessages =MessageBus.track_publish("/topic/#{reply.topic.id}") do- DiscourseSolved.accept_answer!(reply, admin)- DiscourseSolved.unaccept_answer!(reply)+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: reply.id,+ },+ guardian: admin.guardian,+ )+ DiscourseSolved::UnacceptAnswer.call!(+ params: {+ post_id: reply.id,+ },+ guardian: Discourse.system_user.guardian,+ )endexpect(messages.count).to eq(2)expect(messages.map(&:data).map { |m| m[:type] }.uniq).to match_array(@@ -589,7 +795,12 @@ RSpec.describe "Managing Posts solved status" domessages =MessageBus.track_publish("/topic/#{private_post.topic.id}") do- DiscourseSolved.accept_answer!(reply, admin)+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: reply.id,+ },+ guardian: admin.guardian,+ )endexpect(messages.count).to eq(1)@@ -601,6 +812,32 @@ RSpec.describe "Managing Posts solved status" doexpect(unauthorized_user_messages).to eq(nil)end+ it "publishes unaccept MessageBus messages securely for PMs" do+ private_topic = Fabricate(:private_message_topic, user: private_user, recipient: admin)+ private_post = Fabricate(:post, topic: private_topic)+ reply = Fabricate(:post, topic: private_topic, user:, post_number: 2)++ DiscourseSolved::AcceptAnswer.call!(params: { post_id: reply.id }, guardian: admin.guardian)++ messages =+ MessageBus.track_publish("/topic/#{private_post.topic.id}") do+ DiscourseSolved::UnacceptAnswer.call!(+ params: {+ post_id: reply.id,+ },+ guardian: Discourse.system_user.guardian,+ )+ end++ expect(messages.count).to eq(1)++ authorized_user_messages = messages.find { |m| m.user_ids.include?(private_user.id) }+ expect(authorized_user_messages.data[:type]).to eq(:unaccepted_solution)++ unauthorized_user_messages = messages.find { |m| m.user_ids.include?(user.id) }+ expect(unauthorized_user_messages).to eq(nil)+ end+it "publishes MessageBus messages securely for secure categories" dogroup = Fabricate(:group).tap { |g| g.add(private_user) }other_group = Fabricate(:group).tap { |g| g.add(user) }@@ -611,7 +848,12 @@ RSpec.describe "Managing Posts solved status" domessages =MessageBus.track_publish("/topic/#{private_post.topic.id}") do- DiscourseSolved.accept_answer!(private_reply, admin)+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: private_reply.id,+ },+ guardian: admin.guardian,+ )endexpect(messages.count).to eq(1)@@ -622,5 +864,39 @@ RSpec.describe "Managing Posts solved status" dounauthorized_user_messages = messages.find { |m| m.group_ids.include?(other_group.id) }expect(unauthorized_user_messages).to eq(nil)end++ it "publishes unaccept MessageBus messages securely for secure categories" do+ group = Fabricate(:group).tap { |g| g.add(private_user) }+ other_group = Fabricate(:group).tap { |g| g.add(user) }+ private_category = Fabricate(:private_category, group: group)+ private_topic = Fabricate(:topic, category: private_category)+ private_post = Fabricate(:post, topic: private_topic)+ private_reply = Fabricate(:post, topic: private_topic, post_number: 2)++ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: private_reply.id,+ },+ guardian: admin.guardian,+ )++ messages =+ MessageBus.track_publish("/topic/#{private_post.topic.id}") do+ DiscourseSolved::UnacceptAnswer.call!(+ params: {+ post_id: private_reply.id,+ },+ guardian: Discourse.system_user.guardian,+ )+ end++ expect(messages.count).to eq(1)++ authorized_user_messages = messages.find { |m| m.group_ids.include?(group.id) }+ expect(authorized_user_messages.data[:type]).to eq(:unaccepted_solution)++ unauthorized_user_messages = messages.find { |m| m.group_ids.include?(other_group.id) }+ expect(unauthorized_user_messages).to eq(nil)+ endendenddiff --git a/plugins/discourse-solved/spec/lib/first_accepted_post_solution_validator_spec.rb b/plugins/discourse-solved/spec/lib/first_accepted_post_solution_validator_spec.rbindex 87bd0277045..6c0f1657489 100644--- a/plugins/discourse-solved/spec/lib/first_accepted_post_solution_validator_spec.rb+++ b/plugins/discourse-solved/spec/lib/first_accepted_post_solution_validator_spec.rb@@ -3,20 +3,40 @@describe DiscourseSolved::FirstAcceptedPostSolutionValidator dofab!(:user_tl1) { Fabricate(:user, trust_level: TrustLevel[1], refresh_auto_groups: true) }+ before { SiteSetting.allow_solved_on_all_topics = true }+context "when trust level is 'any'" doit "validates the post" do- post = Fabricate(:post, user: user_tl1)- DiscourseSolved.accept_answer!(post, Discourse.system_user)+ topic = Fabricate(:topic_with_op)+ post = Fabricate(:post, topic:, user: user_tl1)+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: post.id,+ },+ guardian: Discourse.system_user.guardian,+ )expect(described_class.check(post, trust_level: "any")).to eq(true)endit "invalidates if post user already has an accepted post" do- previously_accepted_post = Fabricate(:post, user: user_tl1)- DiscourseSolved.accept_answer!(previously_accepted_post, Discourse.system_user)+ topic1 = Fabricate(:topic_with_op)+ previously_accepted_post = Fabricate(:post, topic: topic1, user: user_tl1)+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: previously_accepted_post.id,+ },+ guardian: Discourse.system_user.guardian,+ )- newly_accepted_post = Fabricate(:post, user: user_tl1)- DiscourseSolved.accept_answer!(newly_accepted_post, Discourse.system_user)+ topic2 = Fabricate(:topic_with_op)+ newly_accepted_post = Fabricate(:post, topic: topic2, user: user_tl1)+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: newly_accepted_post.id,+ },+ guardian: Discourse.system_user.guardian,+ )expect(described_class.check(newly_accepted_post, trust_level: "any")).to eq(false)end@@ -26,16 +46,28 @@ describe DiscourseSolved::FirstAcceptedPostSolutionValidator do# the automation indicates "users under this Trust Level will trigger this automation"it "invalidates if the user is higher than or equal to the specified trust level" do- post = Fabricate(:post, user: user_tl1)- DiscourseSolved.accept_answer!(post, Discourse.system_user)+ topic = Fabricate(:topic_with_op)+ post = Fabricate(:post, topic:, user: user_tl1)+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: post.id,+ },+ guardian: Discourse.system_user.guardian,+ )expect(described_class.check(post, trust_level: TrustLevel[0])).to eq(false)expect(described_class.check(post, trust_level: TrustLevel[1])).to eq(false)endit "validates the post when user is under specified trust level" do- post = Fabricate(:post, user: user_tl1)- DiscourseSolved.accept_answer!(post, Discourse.system_user)+ topic = Fabricate(:topic_with_op)+ post = Fabricate(:post, topic:, user: user_tl1)+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: post.id,+ },+ guardian: Discourse.system_user.guardian,+ )expect(described_class.check(post, trust_level: TrustLevel[2])).to eq(true)enddiff --git a/plugins/discourse-solved/spec/lib/queries_spec.rb b/plugins/discourse-solved/spec/lib/queries_spec.rbindex 14e2c135774..1e77543a2b7 100644--- a/plugins/discourse-solved/spec/lib/queries_spec.rb+++ b/plugins/discourse-solved/spec/lib/queries_spec.rb@@ -5,20 +5,22 @@ describe DiscourseSolved::Queries dofab!(:admin)describe ".solved_count" do+ before { SiteSetting.allow_solved_on_all_topics = true }+it "returns the correct count of solved topics for a user" doexpect(described_class.solved_count(user.id)).to eq(0)topic1 = Fabricate(:topic)Fabricate(:post, topic: topic1)post1 = Fabricate(:post, topic: topic1, user: user)- DiscourseSolved.accept_answer!(post1, admin)+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: post1.id }, guardian: admin.guardian)expect(described_class.solved_count(user.id)).to eq(1)topic2 = Fabricate(:topic)Fabricate(:post, topic: topic2)post2 = Fabricate(:post, topic: topic2, user: user)- DiscourseSolved.accept_answer!(post2, admin)+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: post2.id }, guardian: admin.guardian)expect(described_class.solved_count(user.id)).to eq(2)end@@ -28,7 +30,7 @@ describe DiscourseSolved::Queries doFabricate(:post, topic: topic)post = Fabricate(:post, topic: topic, user: user)- DiscourseSolved.accept_answer!(post, admin)+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: post.id }, guardian: admin.guardian)expect(described_class.solved_count(user.id)).to eq(1)post.update!(deleted_at: Time.zone.now)@@ -40,7 +42,7 @@ describe DiscourseSolved::Queries doFabricate(:post, topic: topic)post = Fabricate(:post, topic: topic, user: user)- DiscourseSolved.accept_answer!(post, admin)+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: post.id }, guardian: admin.guardian)expect(described_class.solved_count(user.id)).to eq(1)topic.update!(deleted_at: Time.zone.now)@@ -51,12 +53,12 @@ describe DiscourseSolved::Queries dotopic = Fabricate(:topic)Fabricate(:post, topic: topic)post = Fabricate(:post, topic: topic, user: user)- DiscourseSolved.accept_answer!(post, admin)+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: post.id }, guardian: admin.guardian)pm = Fabricate(:topic, archetype: Archetype.private_message, category_id: nil)Fabricate(:post, topic: pm)pm_post = Fabricate(:post, topic: pm, user: user)- DiscourseSolved.accept_answer!(pm_post, admin)+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: pm_post.id }, guardian: admin.guardian)expect(described_class.solved_count(user.id)).to eq(1)enddiff --git a/plugins/discourse-solved/spec/models/directory_item_spec.rb b/plugins/discourse-solved/spec/models/directory_item_spec.rbindex 45c90f8f859..d5fc1733406 100644--- a/plugins/discourse-solved/spec/models/directory_item_spec.rb+++ b/plugins/discourse-solved/spec/models/directory_item_spec.rb@@ -5,20 +5,28 @@ describe DirectoryItem, type: :model dofab!(:user)fab!(:admin)- fab!(:topic1) { Fabricate(:topic, archetype: "regular", user:) }+ fab!(:topic1) { Fabricate(:topic_with_op, archetype: "regular", user:) }fab!(:topic_post1) { Fabricate(:post, topic: topic1, user:, created_at: 10.years.ago) }- fab!(:topic2) { Fabricate(:topic, archetype: "regular", user:) }+ fab!(:topic2) { Fabricate(:topic_with_op, archetype: "regular", user:) }fab!(:topic_post2) { Fabricate(:post, topic: topic2, user:, created_at: 10.years.ago) }- fab!(:pm) { Fabricate(:topic, archetype: "private_message", user:, category_id: nil) }+ fab!(:pm) { Fabricate(:topic_with_op, archetype: "private_message", user:, category_id: nil) }fab!(:pm_post) { Fabricate(:post, topic: pm, user:) }- before { SiteSetting.solved_enabled = true }+ before do+ SiteSetting.solved_enabled = true+ SiteSetting.allow_solved_on_all_topics = true+ endit "excludes PM post solutions from solutions" do- DiscourseSolved.accept_answer!(topic_post1, admin)- DiscourseSolved.accept_answer!(pm_post, admin)+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: topic_post1.id,+ },+ guardian: admin.guardian,+ )+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: pm_post.id }, guardian: admin.guardian)DirectoryItem.refresh!@@ -31,8 +39,18 @@ describe DirectoryItem, type: :model doendit "excludes deleted posts from solutions" do- DiscourseSolved.accept_answer!(topic_post1, admin)- DiscourseSolved.accept_answer!(topic_post2, admin)+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: topic_post1.id,+ },+ guardian: admin.guardian,+ )+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: topic_post2.id,+ },+ guardian: admin.guardian,+ )topic_post2.update(deleted_at: Time.zone.now)DirectoryItem.refresh!@@ -46,8 +64,18 @@ describe DirectoryItem, type: :model doendit "excludes deleted topics from solutions" do- DiscourseSolved.accept_answer!(topic_post1, admin)- DiscourseSolved.accept_answer!(topic_post2, admin)+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: topic_post1.id,+ },+ guardian: admin.guardian,+ )+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: topic_post2.id,+ },+ guardian: admin.guardian,+ )topic2.update(deleted_at: Time.zone.now)DirectoryItem.refresh!@@ -63,7 +91,12 @@ describe DirectoryItem, type: :model doit "excludes solutions for silenced users" douser.update(silenced_till: 1.day.from_now)- DiscourseSolved.accept_answer!(topic_post1, admin)+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: topic_post1.id,+ },+ guardian: admin.guardian,+ )DirectoryItem.refresh!@@ -76,7 +109,12 @@ describe DirectoryItem, type: :model doendit "excludes solutions for suspended users" do- DiscourseSolved.accept_answer!(topic_post1, admin)+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: topic_post1.id,+ },+ guardian: admin.guardian,+ )user.update(suspended_till: 1.day.from_now)DirectoryItem.refresh!@@ -90,7 +128,12 @@ describe DirectoryItem, type: :model doendit "includes solutions for active users" do- DiscourseSolved.accept_answer!(topic_post1, admin)+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: topic_post1.id,+ },+ guardian: admin.guardian,+ )DirectoryItem.refresh!@@ -105,7 +148,12 @@ describe DirectoryItem, type: :model docontext "when refreshing across dates" doit "updates the user's solution count from 1 to 0" dofreeze_time 40.days.ago- DiscourseSolved.accept_answer!(topic_post1, Discourse.system_user)+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: topic_post1.id,+ },+ guardian: Discourse.system_user.guardian,+ )DirectoryItem.refresh!diff --git a/plugins/discourse-solved/spec/models/discourse_solved/solved_topic_spec.rb b/plugins/discourse-solved/spec/models/discourse_solved/solved_topic_spec.rbnew file mode 100644index 00000000000..cd2cb4d89ff--- /dev/null+++ b/plugins/discourse-solved/spec/models/discourse_solved/solved_topic_spec.rb@@ -0,0 +1,72 @@+# frozen_string_literal: true++RSpec.describe DiscourseSolved::SolvedTopic do+ fab!(:topic, :topic_with_op)+ fab!(:post) { Fabricate(:post, topic: topic) }+ fab!(:user)++ before { SiteSetting.allow_solved_on_all_topics = true }++ describe "Associations" do+ it { is_expected.to belong_to(:topic) }+ it { is_expected.to belong_to(:answer_post) }+ it { is_expected.to belong_to(:accepter) }+ it { is_expected.to belong_to(:topic_timer).dependent(:destroy) }+ end++ describe "Validations" do+ it { is_expected.to validate_presence_of(:topic_id) }+ it { is_expected.to validate_presence_of(:answer_post_id) }+ it { is_expected.to validate_presence_of(:accepter_user_id) }+ end++ describe "Callbacks" do+ describe "#auto_close_topic_timer" do+ subject(:solved) { described_class.create(topic:, answer_post: post, accepter: user) }++ context "when auto close hours is greater than zero" do+ before { SiteSetting.solved_topics_auto_close_hours = 2 }++ it "creates a silent close timer based on last post" do+ expect(solved.topic_timer).to have_attributes(+ topic:,+ status_type: TopicTimer.types[:silent_close],+ based_on_last_post: true,+ duration_minutes: 120,+ )+ end++ context "when the topic is already closed" do+ before { topic.update!(closed: true) }++ it "does not create a timer" do+ expect(solved.topic_timer).to be_nil+ end+ end+ end++ context "when auto close hours is zero" do+ before { SiteSetting.solved_topics_auto_close_hours = 0 }++ it "does not create a timer" do+ expect(solved.topic_timer).to be_nil+ end+ end++ context "when category overrides auto close hours" do+ fab!(:category)++ before do+ topic.update!(category:)+ category.custom_fields["solved_topics_auto_close_hours"] = 5+ category.save!+ SiteSetting.solved_topics_auto_close_hours = 2+ end++ it "uses the category value" do+ expect(solved.topic_timer).to have_attributes(duration_minutes: 300)+ end+ end+ end+ end+enddiff --git a/plugins/discourse-solved/spec/requests/answer_controller_spec.rb b/plugins/discourse-solved/spec/requests/answer_controller_spec.rbindex 39466c82972..f286ac14799 100644--- a/plugins/discourse-solved/spec/requests/answer_controller_spec.rb+++ b/plugins/discourse-solved/spec/requests/answer_controller_spec.rb@@ -1,6 +1,6 @@# frozen_string_literal: true-describe DiscourseSolved::AnswerController do+RSpec.describe DiscourseSolved::AnswerController dofab!(:user)fab!(:staff_user, :admin)fab!(:category)diff --git a/plugins/discourse-solved/spec/requests/list_controller_spec.rb b/plugins/discourse-solved/spec/requests/list_controller_spec.rbindex 0240bb36d7c..9515f0f6a39 100644--- a/plugins/discourse-solved/spec/requests/list_controller_spec.rb+++ b/plugins/discourse-solved/spec/requests/list_controller_spec.rb@@ -9,7 +9,7 @@ RSpec.describe ListController doit "shows the user who posted the accepted answer second" doTopicFeaturedUsers.ensure_consistency!- DiscourseSolved.accept_answer!(p3, p1.user, topic: p1.topic)+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: p3.id }, guardian: p1.user.guardian)get "/latest.json"posters = response.parsed_body["topic_list"]["topics"].first["posters"]diff --git a/plugins/discourse-solved/spec/serializers/user_card_serializer_spec.rb b/plugins/discourse-solved/spec/serializers/user_card_serializer_spec.rbindex ebc28a4c041..e01981f8e38 100644--- a/plugins/discourse-solved/spec/serializers/user_card_serializer_spec.rb+++ b/plugins/discourse-solved/spec/serializers/user_card_serializer_spec.rb@@ -5,6 +5,8 @@ describe UserCardSerializer dolet(:serializer) { described_class.new(user, scope: Guardian.new, root: false) }describe "accepted_answers" do+ before { SiteSetting.allow_solved_on_all_topics = true }+it "uses DiscourseSolved::Queries.solved_count" doallow(DiscourseSolved::Queries).to receive(:solved_count).with(user.id).and_return(42)expect(serializer.as_json[:accepted_answers]).to eq(42)@@ -17,7 +19,12 @@ describe UserCardSerializer dotopic = Fabricate(:topic)Fabricate(:post, topic:)post = Fabricate(:post, topic:, user:)- DiscourseSolved.accept_answer!(post, Discourse.system_user)+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: post.id,+ },+ guardian: Discourse.system_user.guardian,+ )expect(serializer.as_json[:accepted_answers]).to eq(1)enddiff --git a/plugins/discourse-solved/spec/serializers/user_summary_serializer_spec.rb b/plugins/discourse-solved/spec/serializers/user_summary_serializer_spec.rbindex b58916e9f01..e241fb89b7e 100644--- a/plugins/discourse-solved/spec/serializers/user_summary_serializer_spec.rb+++ b/plugins/discourse-solved/spec/serializers/user_summary_serializer_spec.rb@@ -8,6 +8,8 @@ describe UserSummarySerializer dolet(:serializer) { described_class.new(user_summary, scope: guardian, root: false) }describe "solved_count" do+ before { SiteSetting.allow_solved_on_all_topics = true }+it "uses DiscourseSolved::Queries.solved_count" doallow(DiscourseSolved::Queries).to receive(:solved_count).with(user.id).and_return(42)expect(serializer.as_json[:solved_count]).to eq(42)@@ -20,7 +22,12 @@ describe UserSummarySerializer dotopic = Fabricate(:topic)Fabricate(:post, topic:)post = Fabricate(:post, topic:, user:)- DiscourseSolved.accept_answer!(post, Discourse.system_user)+ DiscourseSolved::AcceptAnswer.call!(+ params: {+ post_id: post.id,+ },+ guardian: Discourse.system_user.guardian,+ )expect(serializer.as_json[:solved_count]).to eq(1)enddiff --git a/plugins/discourse-solved/spec/services/discourse_solved/accept_answer_spec.rb b/plugins/discourse-solved/spec/services/discourse_solved/accept_answer_spec.rbnew file mode 100644index 00000000000..eb0be5789c8--- /dev/null+++ b/plugins/discourse-solved/spec/services/discourse_solved/accept_answer_spec.rb@@ -0,0 +1,208 @@+# frozen_string_literal: true++RSpec.describe DiscourseSolved::AcceptAnswer do+ describe described_class::Contract, type: :model do+ it { is_expected.to validate_presence_of(:post_id) }+ end++ describe ".call" do+ subject(:result) { described_class.call(params:, **dependencies) }++ fab!(:acting_user, :user)+ fab!(:category)+ fab!(:topic) { Fabricate(:topic, category:, user: acting_user) }+ fab!(:post_1, :post) { Fabricate(:post, topic:) }+ fab!(:post) { Fabricate(:post, topic:) }++ let(:params) { { post_id: post.id } }+ let(:dependencies) { { guardian: } }+ let(:guardian) { acting_user.guardian }++ before do+ SiteSetting.solved_enabled = true+ SiteSetting.allow_solved_on_all_topics = true+ end++ context "when contract is invalid" do+ let(:params) { {} }++ it { is_expected.to fail_a_contract }+ end++ context "when post is not found" do+ let(:params) { { post_id: -1 } }++ it { is_expected.to fail_to_find_a_model(:post) }+ end++ context "when topic is not found" do+ before { post.topic.destroy! }++ it { is_expected.to fail_to_find_a_model(:topic) }+ end++ context "when topic is trashed" do+ before { post.topic.trash! }++ it { is_expected.to fail_to_find_a_model(:topic) }++ context "when user is staff" do+ fab!(:acting_user, :admin)++ it { is_expected.to run_successfully }+ end+ end++ context "when user cannot accept answer" do+ let(:guardian) { Guardian.new }++ it { is_expected.to fail_a_policy(:can_accept_answer) }+ end++ context "when everything is valid" do+ let(:messages) { MessageBus.track_publish("/topic/#{topic.id}") { result } }+ let(:events) { DiscourseEvent.track_events(:accepted_solution) { result } }++ it { is_expected.to run_successfully }++ context "when a previous answer was already accepted" do+ fab!(:existing_solved) do+ Fabricate(:solved_topic, topic:, answer_post: post_1, accepter: acting_user)+ end+ fab!(:previous_user_action) do+ UserAction.log_action!(+ action_type: UserAction::SOLVED,+ user_id: post_1.user_id,+ acting_user_id: acting_user.id,+ target_post_id: post_1.id,+ target_topic_id: topic.id,+ )+ end++ it "keeps only one solution per topic" do+ expect { result }.not_to change { DiscourseSolved::SolvedTopic.count }+ end++ it "replaces the accepted answer" do+ expect { result }.to change { topic.reload.solved.answer_post }.from(post_1).to(post)+ end++ it "revokes the previous answer's solved credit" do+ expect { result }.to change {+ UserAction.where(action_type: UserAction::SOLVED, target_post: post_1).count+ }.by(-1)+ end+ end++ it "credits the post author with a solved action" do+ expect { result }.to change {+ UserAction.where(action_type: UserAction::SOLVED, target_post: post).count+ }.by(1)+ end++ it "marks the topic as solved" do+ expect(result[:solved]).to have_attributes(+ topic: topic,+ answer_post: post,+ accepter: acting_user,+ )+ end++ context "when the acting user is not the post author" do+ fab!(:acting_user, :admin)++ it "notifies the post author" do+ expect { result }.to change {+ Notification.where(+ notification_type: Notification.types[:custom],+ user: post.user,+ ).count+ }.by(1)+ end+ end++ context "when the acting user is the post author" do+ let(:guardian) { post.user.guardian }++ it "does not notify the post author" do+ expect { result }.not_to change {+ Notification.where(+ notification_type: Notification.types[:custom],+ user: post.user,+ ).count+ }+ end+ end++ context "when notify_on_staff_accept_solved is enabled" do+ before { SiteSetting.notify_on_staff_accept_solved = true }++ context "when a staff member accepts on behalf of the topic owner" do+ fab!(:acting_user, :admin)++ it "notifies the topic owner" do+ expect { result }.to change {+ Notification.where(+ notification_type: Notification.types[:custom],+ user: topic.user,+ ).count+ }.by(1)+ end+ end++ context "when the acting user is the topic owner" do+ it "does not notify the topic owner" do+ expect { result }.not_to change {+ Notification.where(+ notification_type: Notification.types[:custom],+ user: topic.user,+ ).count+ }+ end+ end+ end++ context "when notify_on_staff_accept_solved is disabled" do+ before { SiteSetting.notify_on_staff_accept_solved = false }++ it "does not notify the topic owner" do+ expect { result }.not_to change {+ Notification.where(+ notification_type: Notification.types[:custom],+ user: topic.user,+ ).count+ }+ end+ end++ context "when an accepted_solution webhook is active" do+ fab!(:web_hook) { Fabricate(:web_hook, active: true) }+ fab!(:accepted_solution_event_type) { WebHookEventType.find_by(name: "accepted_solution") }++ before { web_hook.web_hook_event_types << accepted_solution_event_type }++ it "enqueues the webhook" do+ expect { result }.to change { Jobs::EmitWebHookEvent.jobs.size }.by(1)+ end+ end++ context "when a topic timer is created" do+ before { SiteSetting.solved_topics_auto_close_hours = 48 }++ it "broadcasts a topic reload" do+ expect(messages.map(&:data)).to include(reload_topic: true)+ end+ end++ it "triggers the :accepted_solution event" do+ expect(events).to include(a_hash_including(params: [post]))+ end++ it "broadcasts the accepted solution" do+ expect(messages).to include(+ an_object_having_attributes(data: a_hash_including(type: :accepted_solution)),+ )+ end+ end+ end+enddiff --git a/plugins/discourse-solved/spec/services/discourse_solved/unaccept_answer_spec.rb b/plugins/discourse-solved/spec/services/discourse_solved/unaccept_answer_spec.rbnew file mode 100644index 00000000000..91c8a91e098--- /dev/null+++ b/plugins/discourse-solved/spec/services/discourse_solved/unaccept_answer_spec.rb@@ -0,0 +1,169 @@+# frozen_string_literal: true++RSpec.describe DiscourseSolved::UnacceptAnswer do+ describe described_class::Contract, type: :model do+ it { is_expected.to validate_presence_of(:post_id) }+ end++ describe ".call" do+ subject(:result) { described_class.call(params:, **dependencies) }++ fab!(:user)+ fab!(:topic) { Fabricate(:topic, user:) }+ fab!(:post_1, :post) { Fabricate(:post, topic:) }+ fab!(:post) { Fabricate(:post, topic:) }++ let(:params) { { post_id: post.id } }+ let(:guardian) { user.guardian }+ let(:dependencies) { { guardian: } }++ before do+ SiteSetting.solved_enabled = true+ SiteSetting.allow_solved_on_all_topics = true+ end++ context "when contract is invalid" do+ let(:params) { {} }++ it { is_expected.to fail_a_contract }+ end++ context "when post is not found" do+ let(:params) { { post_id: -1 } }++ it { is_expected.to fail_to_find_a_model(:post) }+ end++ context "when post is trashed" do+ before { post.trash! }++ it { is_expected.to fail_to_find_a_model(:post) }++ context "when user is staff" do+ fab!(:user, :admin)++ it { is_expected.to run_successfully }+ end+ end++ context "when topic is not found" do+ before { post.topic.destroy! }++ it { is_expected.to fail_to_find_a_model(:topic) }+ end++ context "when topic is trashed" do+ before { post.topic.trash! }++ it { is_expected.to fail_to_find_a_model(:topic) }++ context "when user is staff" do+ fab!(:user, :admin)++ it { is_expected.to run_successfully }+ end+ end++ context "when user cannot unaccept answer" do+ let(:guardian) { Guardian.new }++ it { is_expected.to fail_a_policy(:can_unaccept_answer) }+ end++ context "when the post is not the accepted answer" do+ it { is_expected.to run_successfully }++ it "does not mark the topic as unsolved" do+ expect { result }.not_to change { DiscourseSolved::SolvedTopic.count }+ end+ end++ context "when the post is the accepted answer" do+ fab!(:solved_topic) { Fabricate(:solved_topic, topic:, answer_post: post, accepter: user) }++ let(:messages) { MessageBus.track_publish("/topic/#{topic.id}") { result } }+ let(:events) { DiscourseEvent.track_events(:unaccepted_solution) { result } }++ before do+ UserAction.log_action!(+ action_type: UserAction::SOLVED,+ user_id: post.user_id,+ acting_user_id: user.id,+ target_post_id: post.id,+ target_topic_id: topic.id,+ )+ Notification.create!(+ notification_type: Notification.types[:custom],+ user_id: post.user_id,+ topic_id: post.topic_id,+ post_number: post.post_number,+ data: { message: "solved.accepted_notification" }.to_json,+ )+ end++ it { is_expected.to run_successfully }++ it "revokes the post author's solved credit" do+ expect { result }.to change {+ UserAction.where(action_type: UserAction::SOLVED, target_post: post).count+ }.by(-1)+ end++ it "removes the accepted answer notification" do+ expect { result }.to change {+ Notification.where(+ notification_type: Notification.types[:custom],+ user: post.user,+ topic: post.topic,+ post_number: post.post_number,+ ).count+ }.by(-1)+ end++ it "marks the topic as unsolved" do+ expect { result }.to change { DiscourseSolved::SolvedTopic.count }.by(-1)+ end++ context "when an unaccepted_solution webhook is active" do+ fab!(:web_hook) { Fabricate(:web_hook, active: true) }+ fab!(:unaccepted_solution_event_type) do+ WebHookEventType.find_by(name: "unaccepted_solution")+ end++ before { web_hook.web_hook_event_types << unaccepted_solution_event_type }++ it "enqueues the webhook" do+ expect { result }.to change { Jobs::EmitWebHookEvent.jobs.size }.by(1)+ end+ end++ it "triggers the :unaccepted_solution event" do+ expect(events).to include(a_hash_including(params: [post]))+ end++ it "broadcasts the unaccepted solution" do+ expect(messages).to include(+ an_object_having_attributes(data: a_hash_including(type: :unaccepted_solution)),+ )+ end++ context "when the post is trashed" do+ fab!(:user, :admin)++ before { post.trash! }++ it "still marks the topic as unsolved" do+ expect { result }.to change { DiscourseSolved::SolvedTopic.count }.by(-1)+ end+ end++ context "when a different post is the accepted answer" do+ before { solved_topic.update!(answer_post: post_1) }++ it "does not mark the topic as unsolved" do+ expect { result }.not_to change { DiscourseSolved::SolvedTopic.count }+ end+ end+ end+ end+end