Skip to content

Commit

Permalink
clean management command
Browse files Browse the repository at this point in the history
  • Loading branch information
madjid-asa committed May 3, 2024
1 parent 9dab3ef commit 72b620e
Showing 1 changed file with 18 additions and 12 deletions.
30 changes: 18 additions & 12 deletions lemarche/crm/management/commands/crm_brevo_sync_contacts.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def add_arguments(self, parser):
parser.add_argument(
"--with-existing-contacts",
dest="with_existing_contacts",
action="store_true",
type=bool,
default=True,
help="make it with existing contacts in brevo",
)
Expand All @@ -41,26 +41,32 @@ def handle(self, dry_run: bool, kind_users: str, brevo_list_id: int, with_existi
self.stdout.write("-" * 80)
self.stdout.write("Script to sync with Contact Brevo CRM...")

# SIAE --> companies
# Update only the recently updated
users_qs = User.objects.filter(kind=kind_users)
progress = 0

self.stdout.write(f"User: updating our {users_qs.count()} users.")
self.stdout.write(f"User: find {users_qs.count()} users {kind_users}.")
existing_contacts = None
if with_existing_contacts:
existing_contacts = api_brevo.get_all_users_from_list(list_id=brevo_list_id)
self.stdout.write(f"Contacts in brevo list: find {len(existing_contacts)} contacts.")

for user in users_qs:
if not dry_run:
if not dry_run:
for user in 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 = brevo_contact_id
else:
# 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)
progress += 1
if (progress % 10) == 0: # avoid API rate-limiting
time.sleep(1)
# if we already have the brevo_contact_id, we can simply save it
else:
self.stdout.write(f"Save existing contact {user.email}.")
user.brevo_contact_id = brevo_contact_id
user.save()

progress += 1
if (progress % 10) == 0: # avoid API rate-limiting
time.sleep(1)

0 comments on commit 72b620e

Please sign in to comment.