FEATURE: Add new :topic_tags_changed DiscourseEvent (#12530)

FEATURE: Add new :topic_tags_changed DiscourseEvent (#12530)

This is called in DiscourseTagging.tag_topic_by_names only after all the validations etc. have been passed, and after topic.tags = X has been called (because this is when the associations are created/ destroyed). The event has the topic, then a second param with the old and new tag names in arrays for easy inspection.

diff --git a/lib/discourse_tagging.rb b/lib/discourse_tagging.rb
index f2a4e4b..3fcd53a 100644
--- a/lib/discourse_tagging.rb
+++ b/lib/discourse_tagging.rb
@@ -127,6 +127,12 @@ module DiscourseTagging
         topic.tags = []
       end
       topic.tags_changed = true
+
+      DiscourseEvent.trigger(
+        :topic_tags_changed,
+        topic, old_tag_names: old_tag_names, new_tag_names: topic.tags.map(&:name)
+      )
+
       return true
     end
     false
diff --git a/spec/components/discourse_tagging_spec.rb b/spec/components/discourse_tagging_spec.rb
index ab96f47..ffd27a8 100644
--- a/spec/components/discourse_tagging_spec.rb
+++ b/spec/components/discourse_tagging_spec.rb
@@ -265,12 +265,30 @@ describe DiscourseTagging do
         expect(topic.errors[:base]&.first).to eq(I18n.t("tags.restricted_tag_disallowed", tag: 'alpha'))
       end
 
+      it "does not send a discourse event for regular users who can't add staff-only tags" do
+        events = DiscourseEvent.track_events do
+          DiscourseTagging.tag_topic_by_names(topic, Guardian.new(user), ['alpha'])
+        end
+        expect(events.count).to eq(0)
+      end
+
       it 'staff can add staff-only tags' do
         valid = DiscourseTagging.tag_topic_by_names(topic, Guardian.new(admin), ['alpha'])
         expect(valid).to eq(true)
         expect(topic.errors[:base]).to be_empty
       end
 
+      it 'sends a discourse event when the staff adds a staff-only tag' do
+        old_tag_names = topic.tags.pluck(:name)
+        tag_changed_event = DiscourseEvent.track_events do
+          DiscourseTagging.tag_topic_by_names(topic, Guardian.new(admin), ['alpha'])
+        end.last
+        expect(tag_changed_event[:event_name]).to eq(:topic_tags_changed)
+        expect(tag_changed_event[:params].first).to eq(topic)
+        expect(tag_changed_event[:params].second[:old_tag_names]).to eq(old_tag_names)
+        expect(tag_changed_event[:params].second[:new_tag_names]).to eq(['alpha'])
+      end
+
       context 'non-staff users in tag group groups' do
         fab!(:non_staff_group) { Fabricate(:group, name: 'non_staff_group') }
 

GitHub sha: 8de07181

This commit appears in #12530 which was approved by OsamaSayegh. It was merged by martin.