DEV: calls user_added_to_group on group/TL enforcement (#13222)

DEV: calls user_added_to_group on group/TL enforcement (#13222)

diff --git a/app/models/group.rb b/app/models/group.rb
index 4aad4ea..c7313fa 100644
--- a/app/models/group.rb
+++ b/app/models/group.rb
@@ -603,7 +603,8 @@ class Group < ActiveRecord::Base
     desired.each do |id|
       if group = find_by(id: id)
         unless GroupUser.where(group_id: id, user_id: user_id).exists?
-          group.group_users.create!(user_id: user_id)
+          group_user = group.group_users.create!(user_id: user_id)
+          DiscourseEvent.trigger(:user_added_to_group, group_user.user, group, automatic: true)
         end
       else
         name = AUTO_GROUP_IDS[trust_level]
diff --git a/spec/models/group_spec.rb b/spec/models/group_spec.rb
index 07e7c98..75630e5 100644
--- a/spec/models/group_spec.rb
+++ b/spec/models/group_spec.rb
@@ -546,6 +546,22 @@ describe Group do
     expect(user.groups.map(&:name).sort).to eq ["trust_level_0"]
   end
 
+  it "generates an event when applying group from trust level change" do
+    called = nil
+    block = Proc.new { |user, group| called = { user_id: user.id, group_id: group.id } }
+
+    begin
+      DiscourseEvent.on(:user_added_to_group, &block)
+
+      user = Fabricate(:user, trust_level: 2)
+      Group.user_trust_level_change!(user.id, 2)
+
+      expect(called).to eq(user_id: user.id, group_id: Group.find_by(name: 'trust_level_2').id)
+    ensure
+      DiscourseEvent.off(:user_added_to_group, &block)
+    end
+  end
+
   context "group management" do
     fab!(:group) { Fabricate(:group) }
 

GitHub sha: 624edac3

This commit appears in #13222 which was approved by ZogStriP. It was merged by jjaffeux.