FIX: clean up holidays from deactivated/suspended/silenced users (#72)

FIX: clean up holidays from deactivated/suspended/silenced users (#72)

Since we’re generating holidays for the next 6 months, there might be some leftovers whenever a user is deactivated/suspended/silenced.

PERF: only load timezones informations from concerned users. We only care about the timezones of the users we will be generating holidays for.

DEV: rename user_ids_and_timezones to the clear-but-shorter timezones

diff --git a/jobs/scheduled/create_holiday_events.rb b/jobs/scheduled/create_holiday_events.rb
index 334cd9a..6f4243b 100644
--- a/jobs/scheduled/create_holiday_events.rb
+++ b/jobs/scheduled/create_holiday_events.rb
@@ -26,12 +26,19 @@ module Jobs
         .pluck(:id, :username)
         .to_h
 
-      user_ids_and_timezones = UserOption
+      timezones = UserOption
+        .where(user_id: usernames.keys)
         .where.not(timezone: nil)
         .pluck(:user_id, :timezone)
         .map { |user_id, timezone| [user_id, (TZInfo::Timezone.get(timezone) rescue nil)] }
         .to_h
 
+      # Remove holidays for deactivated/suspended/silenced users
+      CalendarEvent
+        .where(post_id: nil)
+        .where.not(user_id: usernames.keys)
+        .delete_all
+
       regions_and_user_ids.each do |region, user_ids|
         Holidays
           .between(Date.today, 6.months.from_now, [region], :observed)
@@ -41,7 +48,7 @@ module Jobs
           user_ids.each do |user_id|
             next unless usernames[user_id]
 
-            date = if tz = user_ids_and_timezones[user_id]
+            date = if tz = timezones[user_id]
               datetime = holiday[:date].in_time_zone(tz)
               datetime = datetime.change(hour_adjustment) if hour_adjustment
               datetime
diff --git a/spec/jobs/scheduled/create_holiday_events_spec.rb b/spec/jobs/scheduled/create_holiday_events_spec.rb
index 00eb8e3..a2cc2e8 100644
--- a/spec/jobs/scheduled/create_holiday_events_spec.rb
+++ b/spec/jobs/scheduled/create_holiday_events_spec.rb
@@ -69,6 +69,21 @@ describe DiscourseCalendar::CreateHolidayEvents do
     expect(CalendarEvent.pluck(:region, :description, :start_date, :username)).to eq([])
   end
 
+  it "cleans up holidays from deactivated/silenced/suspended users" do
+    frenchy
+    freeze_time Time.zone.local(2019, 8, 1)
+    subject.execute(nil)
+
+    expect(CalendarEvent.exists?(username: frenchy.username)).to eq(true)
+
+    frenchy.active = false
+    frenchy.save!
+
+    subject.execute(nil)
+
+    expect(CalendarEvent.exists?(username: frenchy.username)).to eq(false)
+  end
+
   context "when user_options.timezone column exists" do
     it "uses the user TZ when available" do
       frenchy.user_option.update!(timezone: "Europe/Paris")

GitHub sha: 8d80d868

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