UX: use existing guardian method to check messageable group. (#14174)

UX: use existing guardian method to check messageable group. (#14174)

We should display “Message” button only if personal messages are enabled. Currently, it’s not respecting that site setting.

diff --git a/app/controllers/groups_controller.rb b/app/controllers/groups_controller.rb
index 462d73d..7930a90 100644
--- a/app/controllers/groups_controller.rb
+++ b/app/controllers/groups_controller.rb
@@ -449,7 +449,7 @@ class GroupsController < ApplicationController
     group = find_group(:group_id, ensure_can_see: false)
 
     if group
-      render json: { messageable: Group.messageable(current_user).where(id: group.id).present? }
+      render json: { messageable: guardian.can_send_private_message?(group) }
     else
       raise Discourse::InvalidAccess.new
     end
diff --git a/app/serializers/group_show_serializer.rb b/app/serializers/group_show_serializer.rb
index 9cdf1f8..826b2c6 100644
--- a/app/serializers/group_show_serializer.rb
+++ b/app/serializers/group_show_serializer.rb
@@ -95,7 +95,7 @@ class GroupShowSerializer < BasicGroupSerializer
   end
 
   def messageable
-    Group.messageable(scope.user).exists?(id: object.id)
+    scope.can_send_private_message?(object)
   end
 
   def include_flair_icon?
diff --git a/spec/requests/groups_controller_spec.rb b/spec/requests/groups_controller_spec.rb
index 22af48c..e57f593 100644
--- a/spec/requests/groups_controller_spec.rb
+++ b/spec/requests/groups_controller_spec.rb
@@ -384,6 +384,23 @@ describe GroupsController do
       expect(response.headers['X-Robots-Tag']).to eq('noindex')
     end
 
+    it "returns the right response for 'messageable' field" do
+      sign_in(user)
+      group.update!(messageable_level: Group::ALIAS_LEVELS[:everyone])
+
+      get "/groups/#{group.name}.json"
+
+      expect(response.status).to eq(200)
+      expect(response.parsed_body['group']['messageable']).to eq(true)
+
+      SiteSetting.enable_personal_messages = false
+
+      get "/groups/#{group.name}.json"
+
+      expect(response.status).to eq(200)
+      expect(response.parsed_body['group']['messageable']).to eq(false)
+    end
+
     context 'as an admin' do
       it "returns the right response" do
         sign_in(Fabricate(:admin))
@@ -624,6 +641,14 @@ describe GroupsController do
 
       body = response.parsed_body
       expect(body["messageable"]).to eq(true)
+
+      SiteSetting.enable_personal_messages = false
+
+      get "/groups/#{group.name}/messageable.json"
+      expect(response.status).to eq(200)
+
+      body = response.parsed_body
+      expect(body["messageable"]).to eq(false)
     end
   end
 

GitHub sha: 08dce4f477b006f0bf830507aa0f75ac6c3ce895

This commit appears in #14174 which was approved by eviltrout and tgxworld. It was merged by vinothkannans.