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

fix(Brevo): mieux gérer le rattachement des contact avec leur company / deal #1212

Merged
merged 2 commits into from
May 15, 2024
Merged
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
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
Loading