Skip to content
Snippets Groups Projects
mailutils.py 2.84 KiB
import logging

from typing import Optional
from typing import Union
from django.conf import settings
from django.template.context import Context
from django_q.tasks import async_task

from greg.models import InvitationLink
from gregui.models import EmailTemplate

logger = logging.getLogger(__name__)


def prepare_arguments(
        template: EmailTemplate, context: dict[str, str], mail_to: str
) -> dict[str, Union[str, list[str]]]:
    """Combine input to a dict ready for use as arguments ti django's send_mail"""
    return {
        "subject": template.get_subject(context),
        "message": template.get_body(context),
        "from_email": template.from_email or None,
        "recipient_list": [mail_to],
    }


def registration_template(
        institution: str, sponsor: str, mail_to: str
) -> dict[str, Union[str, list[str]]]:
    """
    Prepare email for registration

    Produces a complete set of arguments ready for use with django.core.mail.send_mail
    when sending a registration email to the guest.
    """
    template = EmailTemplate.objects.get(
        template_key=EmailTemplate.EmailType.GUEST_REGISTRATION
    )
    context = Context(
        {
            "institution": institution,
            "sponsor": sponsor,
            "registration_link": "www.google.com",
        }
    )
    return prepare_arguments(template, context, mail_to)


def confirmation_template(guest: str, mail_to: str) -> dict[str, Union[str, list[str]]]:
    """
    Prepare email for confirmation

    Produces a complete set of arguments ready for use with django.core.mail.send_mail
    when sending a confirmation email to the sponsor.
    """
    template = EmailTemplate.objects.get(
        template_key=EmailTemplate.EmailType.SPONSOR_CONFIRMATION
    )
    context = Context({"guest": guest, "confirmation_link": "www.google.com"})
    return prepare_arguments(template, context, mail_to)


def send_registration_mail(mail_to: str, sponsor: str) -> str:
    arguments = registration_template(settings.INSTANCE_NAME, sponsor, mail_to)
    return async_task("django.core.mail.send_mail", **arguments)


def send_confirmation_mail(mail_to: str, guest: str) -> str:
    arguments = confirmation_template(guest, mail_to)
    return async_task("django.core.mail.send_mail", **arguments)


def send_invite_mail(link: InvitationLink) -> Optional[str]:
    email_address = link.invitation.role.person.private_email
    if not email_address:
        logger.warning(
            "No e-mail address found for invitation link with ID: {%s}" % link.id
        )
        return None

    sponsor = link.invitation.role.sponsor
    if not sponsor:
        logger.warning(
            "Unable to determine sponsor for invitation link with ID: {link.id}"
        )
        return None

    return send_registration_mail(
        email_address.value, f"{sponsor.first_name} {sponsor.last_name}"
    )