FIX: Never update alert information in closed topics (#10)

FIX: Never update alert information in closed topics (#10)

diff --git a/app/models/alert_receiver_alert.rb b/app/models/alert_receiver_alert.rb
index 5aa6711..25fa1fe 100644
--- a/app/models/alert_receiver_alert.rb
+++ b/app/models/alert_receiver_alert.rb
@@ -83,8 +83,10 @@ class AlertReceiverAlert < ActiveRecord::Base
         VALUES #{values_string}
       ),
       stale_alerts AS (
-        SELECT id FROM alert_receiver_alerts db_alerts
-        WHERE NOT EXISTS (
+        SELECT db_alerts.id FROM alert_receiver_alerts db_alerts
+        JOIN topics t ON t.id = db_alerts.topic_id
+        WHERE NOT t.closed
+        AND NOT EXISTS (
           SELECT 1 FROM active_alerts
           WHERE db_alerts.topic_id = active_alerts.topic_id::integer
             AND db_alerts.identifier = active_alerts.identifier
@@ -114,6 +116,11 @@ class AlertReceiverAlert < ActiveRecord::Base
   def self.update_alerts(alerts, mark_stale_external_url: nil)
     alerts = alerts.uniq { |a| [a[:topic_id], a[:external_url], a[:identifier]] }
 
+    # Never update alert data for closed topics
+    all_topic_ids = alerts.map { |a| a[:topic_id] }.uniq
+    open_topic_ids = Topic.where(id: all_topic_ids).where("not closed").pluck(:id).to_set
+    alerts = alerts.filter { |a| open_topic_ids.include?(a[:topic_id]) }
+
     groups = alerts.group_by { |a| a[:status] }
 
     topic_ids = self.update_firing(groups['firing'])
diff --git a/spec/model/alert_receiver_alert_spec.rb b/spec/model/alert_receiver_alert_spec.rb
index 366b823..c5f1e57 100644
--- a/spec/model/alert_receiver_alert_spec.rb
+++ b/spec/model/alert_receiver_alert_spec.rb
@@ -125,4 +125,26 @@ RSpec.describe 'alert_receiver_alert' do
     expect(AlertReceiverAlert.count).to eq(2)
     expect(AlertReceiverAlert.firing.count).to eq(2)
   end
+
+  it "never updates status in closed topics" do
+    AlertReceiverAlert.update_alerts([
+      alert(identifier: 'myid1'),
+      alert(identifier: 'myid2'),
+      alert(identifier: 'myid3')
+    ])
+
+    expect(AlertReceiverAlert.count).to eq(3)
+    expect(AlertReceiverAlert.firing.count).to eq(3)
+
+    topic1.update!(closed: true)
+
+    AlertReceiverAlert.update_alerts([
+      alert(identifier: 'myid1', status: "resolved"),
+      alert(identifier: 'myid2', status: "suppressed"),
+      # myid3 stale
+    ])
+
+    expect(AlertReceiverAlert.count).to eq(3)
+    expect(AlertReceiverAlert.firing.count).to eq(3)
+  end
 end

GitHub sha: 327373d0

This commit appears in #10 which was approved by SamSaffron. It was merged by SamSaffron.