Skip to content

Commit

Permalink
fix(Brevo): mieux gérer le rattachement des contact avec leur company…
Browse files Browse the repository at this point in the history
… / deal (#1212)
  • Loading branch information
raphodn authored May 15, 2024
1 parent 24868e4 commit 1daf3b8
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 31 deletions.
43 changes: 18 additions & 25 deletions lemarche/crm/management/commands/crm_brevo_sync_contacts.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,26 @@
import time

from django.conf import settings

from lemarche.users.models import User

# from lemarche.users.constants import User
from lemarche.utils.apis import api_brevo
from lemarche.utils.commands import BaseCommand


class Command(BaseCommand):
"""
Command script to send Users to Brevo CRM (companies) or set Brevo CRM IDs to Users models
Command script to send Users to Brevo CRM and/or save their Brevo contact ID
Usage:
python manage.py crm_brevo_sync_contacts --dry-run
python manage.py crm_brevo_sync_contacts --brevo-list-id=23 --kind-users=SIAE
python manage.py crm_brevo_sync_contacts --brevo-list-id=10 --kind-users=SIAE --dry-run
python manage.py crm_brevo_sync_contacts --kind-users=SIAE --brevo-list-id=23
python manage.py crm_brevo_sync_contacts --kind-users=BUYER --brevo-list-id=10 --dry-run
"""

def add_arguments(self, parser):
parser.add_argument(
"--kind-users", dest="kind_users", type=str, default=User.KIND_SIAE, help="set kind of users"
)
parser.add_argument("--kind-users", dest="kind_users", type=str, required=True, help="set kind of users")
parser.add_argument(
"--brevo-list-id",
dest="brevo_list_id",
type=int,
default=settings.BREVO_CL_SIGNUP_BUYER_ID,
required=True,
help="set brevo list id",
)
parser.add_argument("--dry-run", dest="dry_run", action="store_true", help="Dry run (no changes to the DB)")
Expand All @@ -44,7 +37,6 @@ def handle(self, dry_run: bool, kind_users: str, brevo_list_id: int, with_existi
self.stdout.write("Script to sync with Contact Brevo CRM...")

users_qs = User.objects.filter(kind=kind_users)
progress = 0

self.stdout.write(f"User: find {users_qs.count()} users {kind_users}.")
existing_contacts = None
Expand All @@ -53,26 +45,27 @@ def handle(self, dry_run: bool, kind_users: str, brevo_list_id: int, with_existi
self.stdout.write(f"Contacts in brevo list: find {len(existing_contacts)} contacts.")

if not dry_run:
for user in users_qs:
for index, user in enumerate(users_qs):
brevo_contact_id = None

# if we have existing_contacts in brevo
if existing_contacts:
# try to get id by dictionnary of existing contacts
brevo_contact_id = existing_contacts.get(user.email)
if brevo_contact_id == user.brevo_contact_id:
# if brevo contact id and user brevo contact id we skip user
if user.brevo_contact_id and (user.brevo_contact_id == brevo_contact_id):
# skip user
self.stdout.write(f"Contact {user.email} already in Brevo.")
continue
# if we still not have contact id
if not brevo_contact_id:
self.stdout.write(f"Create and save contact {user.email} in Brevo.")
api_brevo.create_contact(user=user, list_id=brevo_list_id, with_user_save=True)
# if we already have the brevo_contact_id, we can simply save it
else:

# found a brevo_contact_id, save it
if brevo_contact_id:
self.stdout.write(f"Save existing contact {user.email}.")
user.brevo_contact_id = brevo_contact_id
user.save()
user.save(update_fields=["brevo_contact_id"])
# we still don't have a contact id, add to brevo
else:
self.stdout.write(f"Create and save contact {user.email} in Brevo.")
api_brevo.create_contact(user=user, list_id=brevo_list_id, with_user_save=True)

progress += 1
if (progress % 10) == 0: # avoid API rate-limiting
if (index % 10) == 0: # avoid API rate-limiting
time.sleep(1)
20 changes: 14 additions & 6 deletions lemarche/utils/apis/api_brevo.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,10 +219,14 @@ def link_deal_with_contact_list(tender, contact_list: list = None):
if not contact_list:
contact_list = [tender.author.brevo_contact_id]

# cleanup
contact_list = [id for id in contact_list if id is not None]

# link deal with contact_list
# 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)
if len(contact_list):
# 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)
Expand Down Expand Up @@ -254,10 +258,14 @@ def link_company_with_contact_list(siae, contact_list: list = None):
if not contact_list:
contact_list = list(siae.users.values_list("brevo_contact_id", flat=True))

# cleanup
contact_list = [id for id in contact_list if id is not None]

# link company with contact_list
# https://github.com/sendinblue/APIv3-python-library/blob/master/docs/Body2.md
body_link_company_contact = sib_api_v3_sdk.Body2(link_contact_ids=contact_list)
api_instance.companies_link_unlink_id_patch(brevo_crm_company_id, body_link_company_contact)
if len(contact_list):
# https://github.com/sendinblue/APIv3-python-library/blob/master/docs/Body2.md
body_link_company_contact = sib_api_v3_sdk.Body2(link_contact_ids=contact_list)
api_instance.companies_link_unlink_id_patch(brevo_crm_company_id, body_link_company_contact)

except ApiException as e:
logger.error("Exception when calling Brevo->DealApi->companies_link_unlink_id_patch: %s\n" % e)
Expand Down

0 comments on commit 1daf3b8

Please sign in to comment.