notify/notify/models/template.py

81 lines
2.6 KiB
Python

import uuid
from django.db import models, transaction
from notify.models.choices import DeliveryChannel
from notify.rendering import render
__all__ = [
"NotificationTemplate",
]
class NotificationTemplate(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
channel = models.CharField(max_length=20, choices=DeliveryChannel.choices)
type = models.ForeignKey(
"notify.NotificationType",
null=True,
blank=True,
on_delete=models.CASCADE,
related_name="templates",
)
name = models.CharField(unique=True, max_length=255)
is_default = models.BooleanField(default=False)
subject_template = models.TextField(default="", blank=True)
body_template = models.TextField()
class Meta:
constraints = [
models.UniqueConstraint(
fields=["channel"],
condition=models.Q(is_default=True, type__isnull=True),
name="uniq_default_template_channel",
),
models.UniqueConstraint(
fields=["type", "channel"],
condition=models.Q(type__isnull=False),
name="uniq_template_type_channel",
),
]
def __str__(self):
return self.name
def save(self, *args, **kwargs):
update_fields = kwargs.get("update_fields")
touches_default = update_fields is None or "is_default" in update_fields
with transaction.atomic():
if self.is_default and touches_default and self.type_id is None:
others = type(self).objects.filter(
channel=self.channel,
type__isnull=True,
is_default=True,
)
if self.pk:
others = others.exclude(pk=self.pk)
others.update(is_default=False)
super().save(*args, **kwargs)
@classmethod
def default(cls, channel):
return (
cls.objects.filter(channel=channel, type__isnull=True, is_default=True)
.order_by("id")
.first()
)
@classmethod
def for_delivery(cls, channel, notification_type):
if notification_type is not None:
typed = cls.objects.filter(channel=channel, type=notification_type).order_by("id").first()
if typed is not None:
return typed
return cls.default(channel)
def render_subject(self, context):
return render(self.subject_template, context)
def render_body(self, context):
return render(self.body_template, context)