diff --git a/hc/api/management/commands/backfillchannels.py b/hc/api/management/commands/backfillchannels.py new file mode 100644 index 00000000..a0ab0a45 --- /dev/null +++ b/hc/api/management/commands/backfillchannels.py @@ -0,0 +1,24 @@ +from django.core.management.base import BaseCommand + +from hc.api.models import Channel, Notification + + +class Command(BaseCommand): + help = "Backfill Channel.last_notify and Channel.last_error" + + def handle(self, *args, **options): + total = 0 + + for channel in Channel.objects.all(): + q = Channel.objects.filter(id=channel.id) + + try: + n = channel.latest_notification() + q.update(last_notify=n.created, last_error=n.error) + total += 1 + except Notification.DoesNotExist: + if channel.last_error: + q.update(last_error="") + total += 1 + + return "Done! Updated %d channels." % total diff --git a/hc/api/migrations/0081_channel_last_notify.py b/hc/api/migrations/0081_channel_last_notify.py new file mode 100644 index 00000000..66d328b2 --- /dev/null +++ b/hc/api/migrations/0081_channel_last_notify.py @@ -0,0 +1,18 @@ +# Generated by Django 3.2.8 on 2021-10-21 07:42 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('api', '0080_fill_slug'), + ] + + operations = [ + migrations.AddField( + model_name='channel', + name='last_notify', + field=models.DateTimeField(blank=True, null=True), + ), + ] diff --git a/hc/api/models.py b/hc/api/models.py index 0c7325d8..3d63b8f3 100644 --- a/hc/api/models.py +++ b/hc/api/models.py @@ -412,6 +412,7 @@ class Channel(models.Model): kind = models.CharField(max_length=20, choices=CHANNEL_KINDS) value = models.TextField(blank=True) email_verified = models.BooleanField(default=False) + last_notify = models.DateTimeField(null=True, blank=True) last_error = models.CharField(max_length=200, blank=True) checks = models.ManyToManyField(Check) @@ -540,7 +541,9 @@ class Channel(models.Model): error = self.transport.notify(check) or "" Notification.objects.filter(id=n.id).update(error=error) - Channel.objects.filter(id=self.id).update(last_error=error) + Channel.objects.filter(id=self.id).update( + last_notify=timezone.now(), last_error=error + ) return error diff --git a/hc/front/tests/test_send_test_notification.py b/hc/front/tests/test_send_test_notification.py index df42b571..2192941a 100644 --- a/hc/front/tests/test_send_test_notification.py +++ b/hc/front/tests/test_send_test_notification.py @@ -31,6 +31,10 @@ class SendTestNotificationTestCase(BaseTestCase): self.assertTrue("X-Status-Url" in email.extra_headers) self.assertTrue("List-Unsubscribe" in email.extra_headers) + # It should update self.channel.last_notify + self.channel.refresh_from_db() + self.assertIsNotNone(self.channel.last_notify) + # It should create a notification n = Notification.objects.get() self.assertEqual(n.channel, self.channel)