From 52288d90cbbddcf435b5f30caa3344dd1ce2d911 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Chlo=C3=A9?= <chloerndt@gmail.com>
Date: Wed, 20 Nov 2024 16:32:31 +0100
Subject: [PATCH] =?UTF-8?q?Mise=20=C3=A0=20jour=20de=20siae.extra=5Fdata?=
 =?UTF-8?q?=20lors=20de=20la=20synchronisation?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 .../commands/crm_brevo_sync_companies.py      | 20 ++++++++++++++++---
 1 file changed, 17 insertions(+), 3 deletions(-)

diff --git a/lemarche/crm/management/commands/crm_brevo_sync_companies.py b/lemarche/crm/management/commands/crm_brevo_sync_companies.py
index c8f71c99a..6740e1f89 100644
--- a/lemarche/crm/management/commands/crm_brevo_sync_companies.py
+++ b/lemarche/crm/management/commands/crm_brevo_sync_companies.py
@@ -8,7 +8,7 @@
 from lemarche.utils.commands import BaseCommand
 
 
-ten_days_ago = timezone.now() - timedelta(days=10)
+two_weeks_ago = timezone.now() - timedelta(weeks=2)
 
 
 class Command(BaseCommand):
@@ -34,11 +34,25 @@ def handle(self, recently_updated: bool, **options):
         self.stdout.write(f"Sync Siae > Brevo: we have {Siae.objects.count()} siaes")
         # Update only the recently updated siaes
         if recently_updated:
-            siaes_qs = siaes_qs.filter(updated_at__gte=ten_days_ago)
+            siaes_qs = siaes_qs.filter(updated_at__gte=two_weeks_ago)
             self.stdout.write(f"Sync Siae > Brevo: {siaes_qs.count()} recently updated")
 
-        # Step 2: loop on the siaes
+        # Step 2: Add the 90-day limited annotations
+        siaes_qs = siaes_qs.with_tender_stats(since_days=90)
+
+        # Step 3: loop on the siaes
         for index, siae in enumerate(siaes_qs):
+            new_extra_data = {
+                "completion_rate": siae.completion_rate,
+                "recent_tender_email_send_count": siae.tender_email_send_count_annotated,
+                "recent_tender_detail_click_count": siae.tender_detail_contact_click_count_annotated,
+            }
+
+            # extra_data update if needed
+            if siae.extra_data != new_extra_data:
+                siae.extra_data = new_extra_data
+                siae.save(update_fields=["extra_data"])
+
             api_brevo.create_or_update_company(siae)
             if (index % 10) == 0:  # avoid API rate-limiting
                 time.sleep(1)