Skip to content

Commit

Permalink
feat(dépôt de besoins): Ajout des dépôts de besoins sur Brevo (1/3) (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
madjid-asa authored May 3, 2024
1 parent 8db0c7f commit 5825776
Show file tree
Hide file tree
Showing 6 changed files with 131 additions and 17 deletions.
17 changes: 17 additions & 0 deletions lemarche/tenders/migrations/0087_tender_brevo_deal_id.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Generated by Django 4.2.9 on 2024-05-03 09:40

from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [
("tenders", "0086_alter_tender_limit_nb_siae_interested"),
]

operations = [
migrations.AddField(
model_name="tender",
name="brevo_deal_id",
field=models.CharField(blank=True, max_length=80, null=True, verbose_name="Brevo deal id"),
),
]
3 changes: 3 additions & 0 deletions lemarche/tenders/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -614,6 +614,9 @@ class Tender(models.Model):
)
# partner data
partner_approch_id = models.IntegerField("Partenaire APProch : ID", blank=True, null=True)

# services data
brevo_deal_id = models.CharField("Brevo deal id", max_length=80, blank=True, null=True)
# stats
siae_count = models.IntegerField(
"Nombre de structures concernées", help_text=RECALCULATED_FIELD_HELP_TEXT, default=0
Expand Down
17 changes: 17 additions & 0 deletions lemarche/users/migrations/0033_user_brevo_contact_id.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Generated by Django 4.2.9 on 2024-05-03 09:40

from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [
("users", "0032_alter_user_kind"),
]

operations = [
migrations.AddField(
model_name="user",
name="brevo_contact_id",
field=models.PositiveIntegerField(blank=True, null=True, verbose_name="Brevo contact id"),
),
]
3 changes: 3 additions & 0 deletions lemarche/users/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,9 @@ class User(AbstractUser):
c4_email_verified = models.BooleanField(default=False)
c4_id_card_verified = models.BooleanField(default=False)

# services data
brevo_contact_id = models.PositiveIntegerField("Brevo contact id", blank=True, null=True)

# admin
notes = GenericRelation("notes.Note", related_query_name="user")

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

from lemarche.tenders.constants import AMOUNT_RANGE_CHOICE_EXACT
from lemarche.utils.constants import EMAIL_SUBJECT_PREFIX
from lemarche.utils.urls import get_object_admin_url, get_object_share_url

Expand Down Expand Up @@ -145,3 +146,78 @@ def send_transactional_email_with_template(
print(f"Exception when calling SMTPApi->send_transac_email: {e}")
else:
logger.info("Brevo: email not sent (DEV or TEST environment detected)")


def create_deal(tender, owner_email: str):
"""
Creates a new deal in Brevo CRM from a tender and logs the result.
This function configures a deal using the tender's details and the owner's email, and posts it to the Brevo CRM.
If successful, it updates the tender with the new deal ID. If it encounters issues, it logs an error.
Args:
tender (Tender): Object with tender details like title, description, amount, and deadlines.
owner_email (str): The email address of the deal's owner.
Raises:
ApiException: If the Brevo API encounters an error during deal creation.
"""
api_client = get_api_client()
api_instance = sib_api_v3_sdk.DealsApi(api_client)
body_deal = sib_api_v3_sdk.Body3(
name=tender.title,
attributes={
"deal_description": tender.description,
# "deal_pipeline": "...",
# "deal_stage": "...",
"deal_owner": owner_email,
"amount": AMOUNT_RANGE_CHOICE_EXACT.get(tender.amount, 0),
"tender_admin_url": tender.get_admin_url(),
"close_date": tender.deadline_date.strftime("%Y-%m-%d"),
},
)

try:
# create deal
new_deal = api_instance.crm_deals_post(body_deal).to_dict()
logger.info("Succes Brevo->Create a deal : %s\n" % new_deal)
# save brevo deal id
tender.brevo_deal_id = new_deal.get("id")
tender.save()
except ApiException as e:
logger.error("Exception when calling Brevo->DealApi->create_deal: %s\n" % e)


def link_deal_with_list_contact(tender, contact_list: list = None):
"""
Links a Brevo deal to a list of contacts. If no contact list is provided, it defaults
to linking the deal with the tender's author.
This function uses the tender's stored deal ID and either a provided list of contact IDs or the
tender author's contact ID to link contacts to the deal in the Brevo CRM.
Args:
tender (Tender): The tender object containing the Brevo deal ID and author's contact ID.
contact_list (list of int, optional): List of contact IDs to be linked with the deal. Defaults to None.
Raises:
ApiException: If an error occurs during the linking process in the Brevo API.
"""
api_client = get_api_client()
api_instance = sib_api_v3_sdk.DealsApi(api_client)

try:
# get brevo ids
brevo_crm_deal_id = tender.brevo_deal_id
# Default to the author's contact ID if no contact list is provided
if not contact_list:
brevo_crm_author_deal_id = tender.author.brevo_contact_id
contact_list = [brevo_crm_author_deal_id]

# link deal with author
# https://github.com/sendinblue/APIv3-python-library/blob/master/docs/Body5.md
body_link_deal_contact = sib_api_v3_sdk.Body5(link_contact_ids=contact_list)
api_instance.crm_deals_link_unlink_id_patch(brevo_crm_deal_id, body_link_deal_contact)

except ApiException as e:
logger.error("Exception when calling Brevo->DealApi->crm_deals_link_unlink_id_patch: %s\n" % e)
32 changes: 15 additions & 17 deletions lemarche/www/tenders/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -506,28 +506,26 @@ def send_siae_interested_email_to_author(tender: Tender):
def notify_admin_tender_created(tender: Tender):
email_subject = f"Marché de l'inclusion : dépôt de besoin, ajout d'un nouveau {tender.get_kind_display()}"
tender_admin_url = get_object_admin_url(tender)
email_body = render_to_string(
"tenders/create_notification_email_admin_body.txt",
{
"tender_id": tender.id,
"tender_title": tender.title,
"tender_kind": tender.get_kind_display(),
"tender_location": tender.location_display,
"tender_deadline_date": tender.deadline_date,
"tender_author_full_name": tender.contact_full_name,
"tender_author_company": tender.author.company_name,
"tender_scale_marche_useless": tender.get_scale_marche_useless_display(),
"tender_status": tender.get_status_display(),
"tender_source": tender.get_source_display(),
"tender_admin_url": tender_admin_url,
},
)
data_to_send = {
"tender_id": tender.id,
"tender_title": tender.title,
"tender_kind": tender.get_kind_display(),
"tender_location": tender.location_display,
"tender_deadline_date": tender.deadline_date,
"tender_author_full_name": tender.contact_full_name,
"tender_author_email": tender.author.email,
"tender_author_company": tender.author.company_name,
"tender_scale_marche_useless": tender.get_scale_marche_useless_display(),
"tender_status": tender.get_status_display(),
"tender_source": tender.get_source_display(),
"tender_admin_url": tender_admin_url,
}
email_body = render_to_string("tenders/create_notification_email_admin_body.txt", data_to_send)
send_mail_async(
email_subject=email_subject,
email_body=email_body,
recipient_list=[settings.NOTIFY_EMAIL],
)

api_slack.send_message_to_channel(text=email_body, service_id=settings.SLACK_WEBHOOK_C4_TENDER_CHANNEL)


Expand Down

0 comments on commit 5825776

Please sign in to comment.