Skip to content

Commit

Permalink
Mail log creation on task end
Browse files Browse the repository at this point in the history
  • Loading branch information
Guilouf committed Dec 31, 2024
1 parent ee54367 commit daa98f6
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 9 deletions.
12 changes: 3 additions & 9 deletions lemarche/conversations/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -309,9 +309,6 @@ def get_template_id(self):
return self.brevo_id
return None

def create_send_log(self, **kwargs):
TemplateTransactionalSendLog.objects.create(template_transactional=self, **kwargs)

def send_transactional_email(
self,
recipient_email,
Expand All @@ -325,6 +322,9 @@ def send_transactional_email(
):
if self.is_active:
args = {
"object_model_id": self.id,
"recipient_content_object": recipient_content_object,
"parent_content_object": parent_content_object,
"template_id": self.get_template_id,
"recipient_email": recipient_email,
"recipient_name": recipient_name,
Expand All @@ -337,12 +337,6 @@ def send_transactional_email(
api_mailjet.send_transactional_email_with_template(**args)
elif self.source == conversation_constants.SOURCE_BREVO:
api_brevo.send_transactional_email_with_template(**args)
# create log
self.create_send_log(
recipient_content_object=recipient_content_object,
parent_content_object=parent_content_object,
extra_data={"source": self.source, "args": args}, # "response": result()
)


class TemplateTransactionalSendLog(models.Model):
Expand Down
31 changes: 31 additions & 0 deletions lemarche/utils/apis/api_brevo.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
from huey.contrib.djhuey import task
from sib_api_v3_sdk.rest import ApiException

from lemarche.conversations.constants import SOURCE_BREVO
from lemarche.conversations.models import TemplateTransactional
from lemarche.tenders import constants as tender_constants
from lemarche.utils.constants import EMAIL_SUBJECT_PREFIX
from lemarche.utils.data import sanitize_to_send_by_email
Expand Down Expand Up @@ -348,6 +350,9 @@ def get_all_users_from_list(

@task()
def send_transactional_email_with_template(
object_model_id: int,
recipient_content_object,
parent_content_object,
template_id: int,
recipient_email: str,
recipient_name: str,
Expand All @@ -368,12 +373,38 @@ def send_transactional_email_with_template(
if subject:
data["subject"] = EMAIL_SUBJECT_PREFIX + subject

log_args = {
"source": SOURCE_BREVO,
"args": {
"template_id": template_id,
"recipient_email": recipient_email,
"recipient_name": recipient_name,
"variables": variables,
"subject": subject,
"from_email": from_email,
"from_name": from_name,
},
}

# create log
template_transactional = TemplateTransactional.objects.get(pk=object_model_id)
template_transactional.send_logs.create(
recipient_content_object=recipient_content_object,
parent_content_object=parent_content_object,
extra_data={
**log_args,
"sent": settings.BITOUBI_ENV in ENV_NOT_ALLOWED, # considered successfully in tests and dev
},
)

if settings.BITOUBI_ENV not in ENV_NOT_ALLOWED:
try:
send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(**data)
response = api_instance.send_transac_email(send_smtp_email)
logger.info("Brevo: send transactional email with template")
# {'message_id': '<[email protected]>', 'message_ids': None}
template_transactional.extra_data = {**log_args, "sent": True}
template_transactional.save(update_fields=["extra_data"])
return response.to_dict()
except ApiException as e:
print(f"Exception when calling SMTPApi->send_transac_email: {e}")
Expand Down
32 changes: 32 additions & 0 deletions lemarche/utils/apis/api_mailjet.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from django.conf import settings
from huey.contrib.djhuey import task

from lemarche.conversations.constants import SOURCE_MAILJET
from lemarche.users import constants as user_constants
from lemarche.utils.constants import EMAIL_SUBJECT_PREFIX

Expand Down Expand Up @@ -95,6 +96,9 @@ def add_to_contact_list_async(email_address, properties, contact_list_id, client

@task()
def send_transactional_email_with_template(
object_model_id: int,
recipient_content_object,
parent_content_object,
template_id: int,
recipient_email: str,
recipient_name: str,
Expand All @@ -104,6 +108,8 @@ def send_transactional_email_with_template(
from_name=settings.DEFAULT_FROM_NAME,
client=None,
):
from lemarche.conversations.models import TemplateTransactional

data = {
"Messages": [
{
Expand All @@ -122,12 +128,38 @@ def send_transactional_email_with_template(
if not client:
client = get_default_client()

log_args = {
"source": SOURCE_MAILJET,
"args": {
"template_id": template_id,
"recipient_email": recipient_email,
"recipient_name": recipient_name,
"variables": variables,
"subject": subject,
"from_email": from_email,
"from_name": from_name,
},
}

# create log
template_transactional = TemplateTransactional.objects.get(pk=object_model_id)
template_transactional.send_logs.create(
recipient_content_object=recipient_content_object,
parent_content_object=parent_content_object,
extra_data={
**log_args,
"sent": settings.BITOUBI_ENV in ENV_NOT_ALLOWED, # considered successfully in tests and dev
},
)

if settings.BITOUBI_ENV not in ENV_NOT_ALLOWED:
try:
response = client.post(SEND_URL, json=data)
response.raise_for_status()
logger.info("Mailjet: send transactional email with template")
# {'Messages': [{'Status': 'success', 'CustomID': '', 'To': [{'Email': '<recipient_email>', 'MessageUUID': '<uuid>', 'MessageID': <id>, 'MessageHref': 'https://api.mailjet.com/v3/REST/message/<id>'}], 'Cc': [], 'Bcc': []}]} # noqa
template_transactional.extra_data = {**log_args, "sent": True}
template_transactional.save(update_fields=["extra_data"])
return response.json()
except requests.exceptions.HTTPError as e:
logger.error("Error while fetching `%s`: %s", e.request.url, e)
Expand Down

0 comments on commit daa98f6

Please sign in to comment.