Skip to content

A platform for community discussion. Free, open, simple.

DEV: Refactor topic voting controller endpoints into services (#39312)

Martin Brennana5dca201d8c3
diff --git a/plugins/discourse-topic-voting/app/controllers/discourse_topic_voting/votes_controller.rb b/plugins/discourse-topic-voting/app/controllers/discourse_topic_voting/votes_controller.rb
index 7e0639d22a4..162d18b4dfe 100644
--- a/plugins/discourse-topic-voting/app/controllers/discourse_topic_voting/votes_controller.rb
+++ b/plugins/discourse-topic-voting/app/controllers/discourse_topic_voting/votes_controller.rb
@@ -15,60 +15,37 @@ module DiscourseTopicVoting
end
def vote
- topic_id = params["topic_id"].to_i
- topic = Topic.find_by(id: topic_id)
-
- raise Discourse::InvalidAccess if !topic.can_vote? || topic.user_voted?(current_user)
- guardian.ensure_can_see!(topic)
-
- voted = false
-
- if current_user.can_vote?
- DiscourseTopicVoting::Vote.find_or_create_by(user: current_user, topic_id: topic_id)
-
- topic.update_vote_count
- voted = true
- end
-
- obj = voting_response(topic)
- obj[:alert] = current_user.alert_low_votes?
-
- if WebHook.active_web_hooks(:topic_upvote).exists?
- payload = {
- topic_id: topic_id,
- topic_slug: topic.slug,
- voter_id: current_user.id,
- vote_count: obj[:vote_count],
- }
- WebHook.enqueue_topic_voting_hooks(:topic_upvote, topic, payload.to_json)
+ DiscourseTopicVoting::Votes::Cast.call(service_params) do
+ on_success do |topic:|
+ render json: voting_response(topic).merge(alert: current_user.alert_low_votes?)
+ end
+ on_failure { render json: failed_json, status: :unprocessable_entity }
+ on_model_not_found(:topic) { raise Discourse::NotFound }
+ on_failed_policy(:can_see_topic) { raise Discourse::InvalidAccess }
+ on_failed_policy(:topic_is_votable) { raise Discourse::InvalidAccess }
+ on_failed_policy(:topic_not_already_voted) { raise Discourse::InvalidAccess }
+ on_failed_policy(:current_user_can_vote) do |topic:|
+ render json: voting_response(topic).merge(alert: current_user.alert_low_votes?),
+ status: :forbidden
+ end
+ on_failed_contract do |contract|
+ render json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request
+ end
end
-
- render json: obj, status: voted ? 200 : 403
end
def unvote
- topic_id = params["topic_id"].to_i
- topic = Topic.find_by(id: topic_id)
-
- guardian.ensure_can_see!(topic)
-
- DiscourseTopicVoting::Vote.destroy_by(user: current_user, topic_id: topic_id)
-
- topic.update_vote_count
-
- obj = voting_response(topic)
-
- if WebHook.active_web_hooks(:topic_unvote).exists?
- payload = {
- topic_id: topic_id,
- topic_slug: topic.slug,
- voter_id: current_user.id,
- vote_count: obj[:vote_count],
- }
- WebHook.enqueue_topic_voting_hooks(:topic_unvote, topic, payload.to_json)
+ DiscourseTopicVoting::Votes::Remove.call(service_params) do
+ on_success { |topic:| render json: voting_response(topic) }
+ on_failure { render json: failed_json, status: :unprocessable_entity }
+ on_model_not_found(:topic) { raise Discourse::NotFound }
+ on_failed_policy(:can_see_topic) { raise Discourse::InvalidAccess }
+ on_failed_contract do |contract|
+ render json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request
+ end
end
-
- render json: obj
end
protected
diff --git a/plugins/discourse-topic-voting/app/services/discourse_topic_voting/votes/cast.rb b/plugins/discourse-topic-voting/app/services/discourse_topic_voting/votes/cast.rb
new file mode 100644
index 00000000000..b669c25646e
--- /dev/null
+++ b/plugins/discourse-topic-voting/app/services/discourse_topic_voting/votes/cast.rb
@@ -0,0 +1,72 @@
+# frozen_string_literal: true
+
+module DiscourseTopicVoting
+ module Votes
+ class Cast
+ include Service::Base
+
+ params do
+ attribute :topic_id, :integer
+
+ validates :topic_id, presence: true
+ end
+
+ model :topic
+
+ policy :can_see_topic
+ policy :topic_is_votable
+ policy :topic_not_already_voted
+ policy :current_user_can_vote
+
+ transaction do
+ step :create_vote
+ step :refresh_vote_count
+ end
+
+ step :enqueue_topic_upvote_webhook
+
+ private
+
+ def fetch_topic(params:)
+ Topic.find_by(id: params.topic_id)
+ end
+
+ def can_see_topic(guardian:, topic:)
+ guardian.can_see?(topic)
+ end
+
+ def topic_is_votable(topic:)
+ topic.can_vote?
+ end
+
+ def topic_not_already_voted(guardian:, topic:)
+ !topic.user_voted?(guardian.user)
+ end
+
+ def current_user_can_vote(guardian:)
+ guardian.user.can_vote?
+ end
+
+ def create_vote(guardian:, topic:)
+ DiscourseTopicVoting::Vote.create!(user: guardian.user, topic: topic)
+ end
+
+ def refresh_vote_count(topic:)
+ topic.update_vote_count
+ end
+
+ def enqueue_topic_upvote_webhook(guardian:, topic:)
+ return if !WebHook.active_web_hooks(:topic_upvote).exists?
+
+ payload = {
+ topic_id: topic.id,
+ topic_slug: topic.slug,
+ voter_id: guardian.user.id,
+ vote_count: topic.vote_count,
+ }
+
+ WebHook.enqueue_topic_voting_hooks(:topic_upvote, topic, payload.to_json)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-topic-voting/app/services/discourse_topic_voting/votes/remove.rb b/plugins/discourse-topic-voting/app/services/discourse_topic_voting/votes/remove.rb
new file mode 100644
index 00000000000..deaab6cb8f0
--- /dev/null
+++ b/plugins/discourse-topic-voting/app/services/discourse_topic_voting/votes/remove.rb
@@ -0,0 +1,67 @@
+# frozen_string_literal: true
+
+module DiscourseTopicVoting
+ module Votes
+ class Remove
+ include Service::Base
+
+ params do
+ attribute :topic_id, :integer
+
+ validates :topic_id, presence: true
+ end
+
+ model :topic
+ policy :can_see_topic
+ model :active_vote, optional: true
+
+ only_if :active_vote_present? do
+ transaction do
+ step :destroy_active_vote
+ step :refresh_vote_count
+ end
+
+ step :enqueue_topic_unvote_webhook
+ end
+
+ private
+
+ def fetch_topic(params:)
+ Topic.find_by(id: params.topic_id)
+ end
+
+ def can_see_topic(guardian:, topic:)
+ guardian.can_see?(topic)
+ end
+
+ def fetch_active_vote(guardian:, topic:)
+ DiscourseTopicVoting::Vote.find_by(user: guardian.user, topic: topic, archive: false)
+ end
+
+ def active_vote_present?(active_vote:)
+ active_vote.present?
+ end
+
+ def destroy_active_vote(active_vote:)
+ active_vote.destroy!
+ end
+
+ def refresh_vote_count(topic:)
+ topic.update_vote_count
+ end
+
+ def enqueue_topic_unvote_webhook(guardian:, topic:)
+ return if !WebHook.active_web_hooks(:topic_unvote).exists?
+
+ payload = {
+ topic_id: topic.id,
+ topic_slug: topic.slug,
+ voter_id: guardian.user.id,
+ vote_count: topic.vote_count,
+ }
+
+ WebHook.enqueue_topic_voting_hooks(:topic_unvote, topic, payload.to_json)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-topic-voting/spec/requests/votes_controller_spec.rb b/plugins/discourse-topic-voting/spec/requests/votes_controller_spec.rb
index 81b0470d934..f0aa42b3c20 100644
--- a/plugins/discourse-topic-voting/spec/requests/votes_controller_spec.rb
+++ b/plugins/discourse-topic-voting/spec/requests/votes_controller_spec.rb
@@ -19,6 +19,13 @@ describe DiscourseTopicVoting::VotesController do
expect(response.status).to eq(404)
end
+ it "returns not found for a stale topic id when voting" do
+ topic.destroy
+ post "/voting/vote.json", params: { topic_id: topic.id }
+
+ expect(response.status).to eq(404)
+ end
+
it "can correctly show deal with voting workflow" do
SiteSetting.public_send "topic_voting_tl#{user.trust_level}_vote_limit=", 2
@@ -44,6 +51,29 @@ describe DiscourseTopicVoting::VotesController do
expect(user.reload.vote_count).to eq(0)
end
+ it "returns 403 when the user already voted" do
+ DiscourseTopicVoting::Vote.create!(user: user, topic: topic)
+
+ post "/voting/vote.json", params: { topic_id: topic.id }
+
+ expect(response.status).to eq(403)
+ end
+
+ it "returns 403 with voting payload when the user reached the vote limit" do
+ SiteSetting.public_send("topic_voting_tl#{user.trust_level}_vote_limit=", 0)
+
+ post "/voting/vote.json", params: { topic_id: topic.id }
+
+ expect(response.status).to eq(403)
+
+ json = response.parsed_body
+ expect(json["can_vote"]).to eq(false)
+ expect(json["vote_limit"]).to eq(0)
+ expect(json["vote_count"]).to eq(0)
+ expect(json["votes_left"]).to eq(0)
+ expect(json["alert"]).to eq(true)
+ end
+
context "when vote limits are disabled" do
before do
SiteSetting.topic_voting_enable_vote_limits = false
@@ -88,6 +118,9 @@ describe DiscourseTopicVoting::VotesController do
end
it "triggers a topic_unvote webhook when unvoting" do
+ DiscourseTopicVoting::Vote.create!(user: user, topic: topic)
+ topic.update_vote_count
+
Fabricate(:topic_voting_web_hook)
post "/voting/unvote.json", params: { topic_id: topic.id }
expect(response.status).to eq(200)
@@ -100,6 +133,24 @@ describe DiscourseTopicVoting::VotesController do
expect(payload["vote_count"]).to eq(0)
end
+ it "does not remove an archived vote when unvoting" do
+ DiscourseTopicVoting::Vote.create!(user: user, topic: topic, archive: true)
+ topic.update_vote_count
+
+ post "/voting/unvote.json", params: { topic_id: topic.id }
+
+ expect(response.status).to eq(200)
+ expect(DiscourseTopicVoting::Vote.where(user: user, topic: topic, archive: true).count).to eq(1)
+ expect(topic.reload.vote_count).to eq(1)
+ end
+
+ it "returns 200 when there is no active vote to remove" do
+ post "/voting/unvote.json", params: { topic_id: topic.id }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["vote_count"]).to eq(0)
+ end
+
it "limits who-voted previews to VOTE_PREVIEW_LIMIT users by default" do
stub_const(DiscourseTopicVoting, "VOTER_PREVIEW_LIMIT", 10) do
Fabricate
diff --git a/plugins/discourse-topic-voting/spec/services/discourse_topic_voting/votes/cast_spec.rb b/plugins/discourse-topic-voting/spec/services/discourse_topic_voting/votes/cast_spec.rb
new file mode 100644
index 00000000000..7017b9b1a02
--- /dev/null
+++ b/plugins/discourse-topic-voting/spec/services/discourse_topic_voting/votes/cast_spec.rb
@@ -0,0 +1,105 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseTopicVoting::Votes::Cast do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:topic_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:user)
+ fab!(:category)
+ fab!(:topic) { Fabricate(:topic, category: category) }
+
+ let(:params) { { topic_id: topic_id } }
+ let(:dependencies) { { guardian: user.guardian } }
+ let(:topic_id) { topic.id }
+
+ before do
+ SiteSetting.topic_voting_enabled = true
+ DiscourseTopicVoting::CategorySetting.create!(category: category)
+ Category.reset_voting_cache
+ end
+
+ context "when params are invalid" do
+ let(:topic_id) { nil }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when topic is missing" do
+ let(:topic_id) { -1 }
+
+ it { is_expected.to fail_to_find_a_model(:topic) }
+ end
+
+ context "when topic is hidden from the actor" do
+ fab!(:private_category) { Fabricate(:private_category, group: Fabricate(:group)) }
+ fab!(:topic) { Fabricate(:topic, category: private_category) }
+
+ before do
+ DiscourseTopicVoting::CategorySetting.create!(category: private_category)
+ Category.reset_voting_cache
+ end
+
+ it { is_expected.to fail_a_policy(:can_see_topic) }
+ end
+
+ context "when topic is not votable" do
+ before do
+ category.discourse_topic_voting_category_setting.destroy!
+ Category.reset_voting_cache
+ end
+
+ it { is_expected.to fail_a_policy(:topic_is_votable) }
+ end
+
+ context "when actor already voted" do
+ before { DiscourseTopicVoting::Vote.create!(user: user, topic: topic) }
+
+ it { is_expected.to fail_a_policy(:topic_not_already_voted) }
+ end
+
+ context "when actor reached vote limit" do
+ before { SiteSetting.public_send("topic_voting_tl#{user.trust_level}_vote_limit=", 0) }
+
+ it { is_expected.to fail_a_policy(:current_user_can_vote) }
+ end
+
+ context "when everything is ok" do
+ it { is_expected.to run_successfully }
+
+ it "creates a vote" do
+ expect { result }.to change(DiscourseTopicVoting::Vote, :count).by(1)
+ end
+
+ it "updates the topic vote count" do
+ result
+
+ expect(topic.reload.vote_count).to eq(1)
+ end
+
+ it "enqueues the upvote webhook when configured" do
+ Fabricate(:topic_voting_web_hook)
+
+ expect { result }.to change(Jobs::EmitWebHookEvent.jobs, :size).by(1)
+
+ job_args = Jobs::EmitWebHookEvent.jobs.last["args"].first
+ expect(job_args["event_name"]).to eq("topic_upvote")
+
+ payload = JSON.parse(job_args["payload"])
+ expect(payload).to include(
+ "topic_id" => topic.id,
+ "topic_slug" => topic.slug,
+ "voter_id" => user.id,
+ "vote_count" => 1,
+ )
+ end
+
+ it "does not enqueue the upvote webhook when not configured" do
+ expect { result }.not_to change(Jobs::EmitWebHookEvent.jobs, :size)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-topic-voting/spec/services/discourse_topic_voting/votes/remove_spec.rb b/plugins/discourse-topic-voting/spec/services/discourse_topic_voting/votes/remove_spec.rb
new file mode 100644
index 00000000000..35435030efa
--- /dev/null
+++ b/plugins/discourse-topic-voting/spec/services/discourse_topic_voting/votes/remove_spec.rb
@@ -0,0 +1,123 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseTopicVoting::Votes::Remove do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:topic_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:user)
+ fab!(:category)
+ fab!(:topic) { Fabricate(:topic, category: category) }
+
+ let(:params) { { topic_id: topic_id } }
+ let(:dependencies) { { guardian: user.guardian } }
+ let(:topic_id) { topic.id }
+
+ before do
+ SiteSetting.topic_voting_enabled = true
+ DiscourseTopicVoting::CategorySetting.create!(category: category)
+ Category.reset_voting_cache
+ end
+
+ context "when params are invalid" do
+ let(:topic_id) { nil }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when topic is missing" do
+ let(:topic_id) { -1 }
+
+ it { is_expected.to fail_to_find_a_model(:topic) }
+ end
+
+ context "when topic is hidden" do
+ fab!(:private_category) { Fabricate(:private_category, group: Fabricate(:group)) }
+ fab!(:topic) { Fabricate(:topic, category: private_category) }
+
+ before do
+ DiscourseTopicVoting::CategorySetting.create!(category: private_category)
+ Category.reset_voting_cache
+ end
+
+ it { is_expected.to fail_a_policy(:can_see_topic) }
+ end
+
+ context "when no active vote exists" do
+ before { topic.update_vote_count }
+
+ it { is_expected.to run_successfully }
+
+ it "does not change vote rows" do
+ expect { result }.not_to change(DiscourseTopicVoting::Vote, :count)
+ end
+
+ it "does not change the topic vote count" do
+ expect { result }.not_to change { topic.reload.vote_count }
+ end
+ end
+
+ context "when only an archived vote exists" do
+ fab!(:archived_vote) { Fabricate(:topic_voting_votes, user: user, topic: topic) }
+
+ before do
+ archived_vote.update!(archive: true)
+ topic.update_vote_count
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "keeps the archived vote" do
+ expect { result }.not_to change(DiscourseTopicVoting::Vote, :count)
+ expect(archived_vote.reload.archive).to eq(true)
+ end
+
+ it "does not change the topic vote count" do
+ expect { result }.not_to change { topic.reload.vote_count }
+ end
+ end
+
+ context "when an active vote exists" do
+ fab!(:active_vote) { Fabricate(:topic_voting_votes, user: user, topic: topic) }
+
+ before { topic.update_vote_count }
+
+ it { is_expected.to run_successfully }
+
+ it "removes only the active vote" do
+ expect { result }.to change(DiscourseTopicVoting::Vote, :count).by(-1)
+ expect { active_vote.reload }.to raise_error(ActiveRecord::RecordNotFound)
+ end
+
+ it "updates the topic vote count" do
+ result
+
+ expect(topic.reload.vote_count).to eq(0)
+ end
+
+ it "enqueues the unvote webhook when configured" do
+ Fabricate(:topic_voting_web_hook)
+
+ expect { result }.to change(Jobs::EmitWebHookEvent.jobs, :size).by(1)
+
+ job_args = Jobs::EmitWebHookEvent.jobs.last["args"].first
+ expect(job_args["event_name"]).to eq("topic_unvote")
+
+ payload = JSON.parse(job_args["payload"])
+ expect(payload).to include(
+ "topic_id" => topic.id,
+ "topic_slug" => topic.slug,
+ "voter_id" => user.id,
+ "vote_count" => 0,
+ )
+ end
+
+ it "does not enqueue the unvote webhook when not configured" do
+ expect { result }.not_to change(Jobs::EmitWebHookEvent.jobs, :size)
+ end
+ end
+ end
+end