Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Supprimer mailjet #1632

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions lemarche/conversations/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,21 +140,19 @@ class TemplateTransactionalAdmin(admin.ModelAdmin):
"id",
"name",
"code",
"mailjet_id",
"brevo_id",
"source",
"is_active",
"template_transactional_send_log_count_with_link",
"created_at",
"updated_at",
]
search_fields = ["id", "name", "code", "mailjet_id", "brevo_id"]
search_fields = ["id", "name", "code", "brevo_id"]

readonly_fields = ["code", "template_transactional_send_log_count_with_link", "created_at", "updated_at"]

fieldsets = (
(None, {"fields": ("name", "code", "description", "group")}),
("Paramètres d'envoi", {"fields": ("mailjet_id", "brevo_id", "source", "is_active")}),
("Paramètres d'envoi", {"fields": ("brevo_id", "is_active")}),
("Stats", {"fields": ("template_transactional_send_log_count_with_link",)}),
("Dates", {"fields": ("created_at", "updated_at")}),
)
Expand Down
10 changes: 0 additions & 10 deletions lemarche/conversations/constants.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,2 @@
ATTRIBUTES_TO_SAVE_FOR_INBOUND = ["From", "To", "CC", "ReplyTo", "SentAtDate", "Attachments"]
ATTRIBUTES_TO_NOT_ANONYMIZE_FOR_INBOUND = ["SentAtDate", "Attachments"]

SOURCE_MAILJET = "MAILJET"
SOURCE_BREVO = "BREVO"
SOURCE_DJANGO = "DJANGO"

SOURCE_CHOICES = (
(SOURCE_MAILJET, "Mailjet"),
(SOURCE_BREVO, "Brevo"),
(SOURCE_DJANGO, "Django"),
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Generated by Django 4.2.15 on 2025-01-13 13:07

from django.db import migrations


class Migration(migrations.Migration):
dependencies = [
("conversations", "0018_conversation_is_anonymized"),
]

operations = [
migrations.RemoveField(
model_name="templatetransactional",
name="mailjet_id",
),
migrations.RemoveField(
model_name="templatetransactional",
name="source",
),
]
53 changes: 6 additions & 47 deletions lemarche/conversations/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,8 @@
from django_extensions.db.fields import ShortUUIDField
from shortuuid import uuid

from lemarche.conversations import constants as conversation_constants
from lemarche.users import constants as user_constants
from lemarche.utils.apis import api_brevo, api_mailjet
from lemarche.utils.apis import api_brevo
from lemarche.utils.data import add_validation_error


Expand Down Expand Up @@ -226,35 +225,7 @@ class TemplateTransactional(models.Model):
)
description = models.TextField(verbose_name="Description", blank=True)
group = models.ForeignKey("EmailGroup", on_delete=models.CASCADE, null=True)

# email_subject = models.CharField(
# verbose_name="E-mail : objet",
# help_text="Laisser vide pour utiliser l'objet présent dans Mailjet/Brevo",
# max_length=255,
# blank=True,
# null=True,
# )
# email_from_email = models.EmailField(
# verbose_name="E-mail : expéditeur (e-mail)",
# help_text=f"Laisser vide pour utiliser l'e-mail expéditeur par défaut ({settings.DEFAULT_FROM_EMAIL})",
# blank=True,
# null=True,
# )
# email_from_name = models.CharField(
# verbose_name="E-mail : expéditeur (nom)",
# help_text=f"Laisser vide pour utiliser le nom expéditeur par défaut ({settings.DEFAULT_FROM_NAME})",
# max_length=255,
# blank=True,
# null=True,
# )

mailjet_id = models.IntegerField(
verbose_name="Identifiant Mailjet", unique=True, db_index=True, blank=True, null=True
)
brevo_id = models.IntegerField(verbose_name="Identifiant Brevo", unique=True, db_index=True, blank=True, null=True)
source = models.CharField(
verbose_name="Source", max_length=20, choices=conversation_constants.SOURCE_CHOICES, blank=True
)
is_active = models.BooleanField(verbose_name="Actif", default=False)

created_at = models.DateTimeField(verbose_name="Date de création", default=timezone.now)
Expand All @@ -276,13 +247,7 @@ def clean(self, *args, **kwargs):
validation_errors = dict()
# validation rules
if self.is_active:
if self.source == conversation_constants.SOURCE_MAILJET and not self.mailjet_id:
validation_errors = add_validation_error(
validation_errors,
"mailjet_id",
"Le mailjet_id est requis pour un template actif",
)
elif self.source == conversation_constants.SOURCE_BREVO and not self.brevo_id:
if not self.brevo_id:
validation_errors = add_validation_error(
validation_errors,
"brevo_id",
Expand All @@ -302,11 +267,8 @@ def save(self, *args, **kwargs):

@property
def get_template_id(self):
if self.source and self.code:
if self.source == conversation_constants.SOURCE_MAILJET:
return self.mailjet_id
elif self.source == conversation_constants.SOURCE_BREVO:
return self.brevo_id
if self.code:
return self.brevo_id
return None

def create_send_log(self, **kwargs):
Expand Down Expand Up @@ -338,13 +300,10 @@ def send_transactional_email(
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()
extra_data={"source": "BREVO", "args": args}, # "response": result()
)

if self.source == conversation_constants.SOURCE_MAILJET:
api_mailjet.send_transactional_email_with_template(**args)
elif self.source == conversation_constants.SOURCE_BREVO:
api_brevo.send_transactional_email_with_template(**args)
api_brevo.send_transactional_email_with_template(**args)


class TemplateTransactionalSendLog(models.Model):
Expand Down
52 changes: 5 additions & 47 deletions lemarche/conversations/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,9 @@

from django.core.exceptions import ValidationError
from django.core.management import call_command
from django.db import IntegrityError
from django.test import TestCase, TransactionTestCase, override_settings
from django.utils import timezone

from lemarche.conversations import constants as conversation_constants
from lemarche.conversations.constants import ATTRIBUTES_TO_NOT_ANONYMIZE_FOR_INBOUND, ATTRIBUTES_TO_SAVE_FOR_INBOUND
from lemarche.conversations.factories import ConversationFactory, TemplateTransactionalFactory
from lemarche.conversations.models import Conversation, TemplateTransactional
Expand Down Expand Up @@ -113,56 +111,16 @@ def test_anonymize_command(self):
class TemplateTransactionalModelTest(TestCase):
@classmethod
def setUpTestData(cls):
cls.tt_inactive = TemplateTransactional(
code="EMAIL_1", mailjet_id=10, brevo_id=11, source=conversation_constants.SOURCE_MAILJET, is_active=False
)
cls.tt_active_empty = TemplateTransactional(
code="EMAIL_2", source=conversation_constants.SOURCE_MAILJET, is_active=False
)
cls.tt_active_mailjet = TemplateTransactional(
code="EMAIL_3", mailjet_id=30, brevo_id=31, source=conversation_constants.SOURCE_MAILJET, is_active=True
)
cls.tt_active_brevo = TemplateTransactional(
code="EMAIL_4", mailjet_id=40, brevo_id=41, source=conversation_constants.SOURCE_BREVO, is_active=True
)
cls.tt_inactive = TemplateTransactional(code="EMAIL_1", brevo_id=11, is_active=False)
cls.tt_active_empty = TemplateTransactional(code="EMAIL_2", is_active=False)
cls.tt_active_brevo = TemplateTransactional(code="EMAIL_3", brevo_id=41, is_active=True)

def test_get_template_id(self):
self.assertIsNone(self.tt_active_empty.get_template_id)
self.assertEqual(self.tt_inactive.get_template_id, self.tt_inactive.mailjet_id)
self.assertEqual(self.tt_active_mailjet.get_template_id, self.tt_active_mailjet.mailjet_id)
self.assertEqual(self.tt_inactive.get_template_id, self.tt_inactive.brevo_id)
self.assertEqual(self.tt_active_brevo.get_template_id, self.tt_active_brevo.brevo_id)


class TemplateTransactionalModelSaveTest(TransactionTestCase):
reset_sequences = True

@classmethod
def setUpTestData(cls):
pass

def test_template_transactional_field_rules(self):
self.assertRaises(IntegrityError, TemplateTransactionalFactory, source=None)

def test_template_transactional_validation_on_save(self):
TemplateTransactionalFactory(
mailjet_id=None, brevo_id=None, source=conversation_constants.SOURCE_BREVO, is_active=False
)
TemplateTransactionalFactory(
mailjet_id=None, brevo_id=123, source=conversation_constants.SOURCE_BREVO, is_active=True
)
self.assertRaises(
ValidationError,
TemplateTransactionalFactory,
mailjet_id=123,
brevo_id=None,
source=conversation_constants.SOURCE_BREVO,
is_active=True,
)
self.assertRaises(
ValidationError,
TemplateTransactionalFactory,
mailjet_id=None,
brevo_id=123,
source=conversation_constants.SOURCE_MAILJET,
is_active=True,
)
self.assertRaises(ValidationError, TemplateTransactionalFactory, brevo_id=None, is_active=True, group=None)
3 changes: 1 addition & 2 deletions lemarche/users/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
from django.utils import timezone

from lemarche.companies.factories import CompanyFactory
from lemarche.conversations.constants import SOURCE_BREVO
from lemarche.conversations.models import TemplateTransactional, TemplateTransactionalSendLog
from lemarche.favorites.factories import FavoriteListFactory
from lemarche.siaes.factories import SiaeFactory
Expand Down Expand Up @@ -219,7 +218,7 @@ def setUp(self):
first_name="about_to_be_inactive",
)
# Set email as active to check if it's really sent
TemplateTransactional.objects.all().update(is_active=True, source=SOURCE_BREVO)
TemplateTransactional.objects.all().update(is_active=True)

def test_set_inactive_user(self):
"""Select users that last logged for more than a year and flag them as inactive"""
Expand Down
43 changes: 0 additions & 43 deletions lemarche/utils/apis/api_mailjet.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,49 +93,6 @@ def add_to_contact_list_async(email_address, properties, contact_list_id, client
logger.info("Mailjet: not add contact in contact list (DEV or TEST environment detected)")


@task()
def send_transactional_email_with_template(
template_id: int,
recipient_email: str,
recipient_name: str,
variables: dict,
subject=None,
from_email=settings.DEFAULT_FROM_EMAIL,
from_name=settings.DEFAULT_FROM_NAME,
client=None,
):
data = {
"Messages": [
{
"From": {"Email": from_email, "Name": from_name},
"To": [{"Email": recipient_email, "Name": recipient_name}],
"TemplateID": template_id,
"TemplateLanguage": True,
"Variables": variables,
}
]
}
# if subject empty, defaults to Mailjet's template subject
if subject:
data["Messages"][0]["Subject"] = EMAIL_SUBJECT_PREFIX + subject

if not client:
client = get_default_client()

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
return response.json()
except requests.exceptions.HTTPError as e:
logger.error("Error while fetching `%s`: %s", e.request.url, e)
raise e
else:
logger.info("Mailjet: email not sent (DEV or TEST environment detected)")


@task()
def send_transactional_email_many_recipient_with_template(
template_id,
Expand Down
Loading