oncall-engine/engine/apps/email/alert_rendering.py
Michael Derynck aebd98b8f9
Change email templating to not wrap user defined templates (#3862)
# What this PR does
Change email notification templates to not wrap the user template in a
fixed body. Info has been moved to a footer. The title now also matches
the template from the user exactly and will only get a default message
if the user template result is empty.
Example:

![Screenshot from 2024-02-08
12-16-38](https://github.com/grafana/oncall/assets/28077050/bb59b7a7-7ec8-4d9d-8aef-8aff012c74f7)

## Which issue(s) this PR fixes
#3857 

## Checklist

- [x] Unit, integration, and e2e (if applicable) tests updated
- [x] Documentation added (or `pr:no public docs` PR label added if not
required)
- [x] `CHANGELOG.md` updated (or `pr:no changelog` PR label added if not
required)
2024-02-09 19:03:25 +00:00

55 lines
2.1 KiB
Python

from django.template.loader import render_to_string
from emoji.core import emojize
from apps.alerts.incident_appearance.renderers.constants import DEFAULT_BACKUP_TITLE
from apps.alerts.incident_appearance.templaters.alert_templater import AlertTemplater
from common.utils import convert_md_to_html, str_or_backup
class AlertEmailTemplater(AlertTemplater):
RENDER_FOR_EMAIL = "email"
def _render_for(self):
return self.RENDER_FOR_EMAIL
def _postformat(self, templated_alert):
templated_alert.title = self._slack_format_for_email(templated_alert.title)
templated_alert.message = self._slack_format_for_email(templated_alert.message)
return templated_alert
def _slack_format_for_email(self, data):
sf = self.slack_formatter
sf.hyperlink_mention_format = "{title} - {url}"
return sf.format(data)
def build_subject_and_message(alert_group, emails_left):
alert = alert_group.alerts.first()
templated_alert = AlertEmailTemplater(alert).render()
title_fallback = (
f"#{alert_group.inside_organization_number} " f"{DEFAULT_BACKUP_TITLE} via {alert_group.channel.verbal_name}"
)
# default templates are the same as web templates, which are in Markdown format
message = templated_alert.message
if message:
message = convert_md_to_html(templated_alert.message) if templated_alert.message else ""
content = render_to_string(
"email_notification.html",
{
"message": str_or_backup(message, title_fallback),
"limit_notification": emails_left <= 20,
"emails_left": emails_left,
"url": alert_group.slack_permalink or alert_group.web_link,
"alert_group_number": str(alert_group.inside_organization_number),
"integration": emojize(alert_group.channel.short_name, language="alias"),
"instance_url": alert_group.channel.organization.grafana_url,
},
)
title = str_or_backup(templated_alert.title, title_fallback)
subject = f"{title}".replace("\n", "")
return subject, content