From 0676ae03b131c9fff6a22f606b0924edf59269ce Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jan=20Bedna=C5=99=C3=ADk?= <jan.bednarik@gmail.com>
Date: Tue, 31 Jan 2023 12:21:32 +0100
Subject: [PATCH] calendar utils: Delete orphaned callendars when updating

---
 .../management/commands/update_callendars.py   | 18 +++++++++++++++++-
 calendar_utils/models.py                       |  2 --
 tests/calendar_utils/test_models.py            |  1 -
 3 files changed, 17 insertions(+), 4 deletions(-)

diff --git a/calendar_utils/management/commands/update_callendars.py b/calendar_utils/management/commands/update_callendars.py
index e8375498..912faaf8 100644
--- a/calendar_utils/management/commands/update_callendars.py
+++ b/calendar_utils/management/commands/update_callendars.py
@@ -9,9 +9,25 @@ logger = logging.getLogger(__name__)
 
 class Command(BaseCommand):
     def handle(self, *args, **options):
+        self.stdout.write("Removing orphaned calendars...")
+        for cal in Calendar.objects.filter(
+            districtcenterpage=None,
+            districthomepage=None,
+            elections2021calendarpage=None,
+            senatcampaignhomepage=None,
+            uniwebhomepage=None,
+        ):
+            try:
+                self.stdout.write(f"- {cal.id} | {cal.url}")
+                cal.delete()
+            except Exception as e:
+                logger.error("Calendar delete failed for %s", cal.url, exc_info=True)
+                self.stdout.write("  - failed")
+                self.stdout.write(str(e))
+
         self.stdout.write("Updating calendars...")
         for cal in Calendar.objects.all():
-            self.stdout.write(f"\n@ {cal.url}")
+            self.stdout.write(f"\n@ {cal.id} | {cal.url}")
             try:
                 cal.update_source()
                 self.stdout.write("+ ok")
diff --git a/calendar_utils/models.py b/calendar_utils/models.py
index b16d2137..33516125 100644
--- a/calendar_utils/models.py
+++ b/calendar_utils/models.py
@@ -99,8 +99,6 @@ class CalendarMixin(models.Model):
 
         # delete related Calendar when URL is cleared
         if not self.calendar_url and self.calendar:
-            # TODO handle revisions and maybe other live pages with the same calendar
-            # self.calendar.delete()
             self.calendar = None
 
         super().save(*args, **kwargs)
diff --git a/tests/calendar_utils/test_models.py b/tests/calendar_utils/test_models.py
index 7b2f62c4..52743746 100644
--- a/tests/calendar_utils/test_models.py
+++ b/tests/calendar_utils/test_models.py
@@ -145,4 +145,3 @@ def test_calendar_mixin__clear_calendar_url(mocker):
     assert obj.calendar_url is None
     assert obj.calendar is None
     assert m_update.call_count == 0
-    assert Calendar.objects.count() == 0
-- 
GitLab