Skip to content

Commit

Permalink
Attributs structures
Browse files Browse the repository at this point in the history
  • Loading branch information
chloend committed Nov 3, 2024
1 parent 57817e1 commit 55395fb
Show file tree
Hide file tree
Showing 3 changed files with 138 additions and 23 deletions.
4 changes: 2 additions & 2 deletions lemarche/crm/management/commands/crm_brevo_sync_companies.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -34,7 +34,7 @@ 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
Expand Down
97 changes: 97 additions & 0 deletions lemarche/crm/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
from datetime import timedelta

from django.core.management import call_command
from django.test import TestCase
from django.utils import timezone

from lemarche.siaes.factories import SiaeFactory
from lemarche.users.factories import UserFactory
from lemarche.utils.apis.api_brevo import create_or_update_company
from lemarche.utils.urls import get_object_admin_url, get_object_share_url

from unittest.mock import patch, MagicMock


class CrmBrevoSyncCompaniesCommandTest(TestCase):
@patch("lemarche.utils.apis.api_brevo.sib_api_v3_sdk.Body")
def test_create_or_update_company_with_mocked_body(self, mock_body):
# Créer un mock pour `Body`
mock_body_instance = MagicMock()
mock_body.return_value = mock_body_instance

# Créer un objet `Siae` de test
siae = SiaeFactory(name="Test Company", completion_rate=0.5)

# Appeler la fonction que l'on souhaite tester
create_or_update_company(siae)

expected_attributes = {
"domain": siae.website,
"phone_number": siae.contact_phone_display,
"app_id": siae.id,
"siae": True,
"active": siae.is_active,
"description": siae.description,
"kind": siae.kind,
"address_street": siae.address,
"address_post_code": siae.post_code,
"address_city": siae.city,
"contact_email": siae.contact_email,
"logo_url": siae.logo_url,
"geo_range": siae.geo_range,
"app_url": get_object_share_url(siae),
"app_admin_url": get_object_admin_url(siae),
# Champs de extra_data
**siae.extra_data, # inclut completion_rate, tender_email_send_count, etc.
}

mock_body.assert_called_once_with(name="Test Company", attributes=expected_attributes)

@patch('lemarche.utils.apis.api_brevo.create_or_update_company')
def test_command_syncs_companies(self, mock_create_or_update_company):
# Créer quelques objets Siae pour le test
siae1 = SiaeFactory()
siae2 = SiaeFactory()

# Appeler la commande
call_command('crm_brevo_sync_companies')

# Vérifier que la méthode `create_or_update_company` a été appelée pour chaque `Siae`
mock_create_or_update_company.assert_any_call(siae1)
mock_create_or_update_company.assert_any_call(siae2)
self.assertEqual(mock_create_or_update_company.call_count, 2)

@patch('lemarche.utils.apis.api_brevo.create_or_update_company')
def test_siae_updates_only_recent_and_if_extra_data_changed(self, mock_create_or_update_company):
# Créer deux `Siae`: un récemment mis à jour et un autre plus ancien
recent_siae = SiaeFactory(updated_at=timezone.now() - timedelta(days=7))
old_siae = SiaeFactory(updated_at=timezone.now() - timedelta(days=20))
print("recent : ", recent_siae)
print("old : ", old_siae)

# Modifier `extra_data` pour `recent_siae` uniquement
recent_siae.extra_data = {'completion_rate': 50}
recent_siae.save(update_fields=["extra_data", "updated_at"])

# Modifier `extra_data` pour `old_siae` aussi
old_siae.extra_data = {'completion_rate': 25}
old_siae.save(update_fields=["extra_data", "updated_at"])

# Appeler la commande avec `recently_updated=True`
call_command('crm_brevo_sync_companies')

# Vérifier que `create_or_update_company` a été appelé pour `recent_siae` mais pas pour `old_siae`
mock_create_or_update_company.assert_called_once_with(recent_siae)

@patch('lemarche.utils.apis.api_brevo.create_or_update_company')
def test_siae_not_updated_if_extra_data_unchanged(self, mock_create_or_update_company):
# Créer un `Siae` récent sans changement dans `extra_data`
siae = SiaeFactory(updated_at=timezone.now() - timedelta(days=7))
siae.extra_data = {'completion_rate': 0.8}
siae.save(update_fields=["extra_data", "updated_at"])

# Appeler la commande sans changement dans `extra_data`
call_command('crm_brevo_sync_companies', recently_updated=True)

# Vérifier qu'aucun appel à `create_or_update_company` n'est effectué
mock_create_or_update_company.assert_not_called()
60 changes: 39 additions & 21 deletions lemarche/utils/apis/api_brevo.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import json
import logging
import time

import sib_api_v3_sdk

from datetime import timedelta
from django.conf import settings
from django.utils import timezone
from huey.contrib.djhuey import task
from sib_api_v3_sdk.rest import ApiException

Expand Down Expand Up @@ -116,28 +118,44 @@ def create_or_update_company(siae):
api_client = get_api_client()
api_instance = sib_api_v3_sdk.CompaniesApi(api_client)

# TenderSiae data
now = timezone.now()
three_months_ago = now - timedelta(days=90)
# tenders clicked in last 90 days
recent_tender_detail_click_count = siae.tendersiae_set.filter(detail_contact_click_date__gte=three_months_ago).count()

siae.extra_data = {
"completion_rate": siae.completion_rate,
"tender_email_send_count": siae.tender_email_send_count,
"recent_tender_detail_click_count": recent_tender_detail_click_count,
}

attributes = {
# default attributes
# name, owner, linked_contacts, revenue, number_of_employees, created_at, last_updated_at, next_activity_date, owner_assign_date, number_of_contacts, number_of_activities, industry # noqa
"domain": siae.website,
"phone_number": siae.contact_phone_display,
# custom attributes
"app_id": siae.id,
"siae": True,
"active": siae.is_active,
"description": siae.description,
"kind": siae.kind,
"address_street": siae.address,
"address_post_code": siae.post_code,
"address_city": siae.city,
"contact_email": siae.contact_email,
"logo_url": siae.logo_url,
"geo_range": siae.geo_range,
"app_url": get_object_share_url(siae),
"app_admin_url": get_object_admin_url(siae),
# Champs de extra_data
**siae.extra_data, # inclut completion_rate, tender_email_send_count, etc.
}

siae_brevo_company_body = sib_api_v3_sdk.Body(
name=siae.name,
attributes={
# default attributes
# name, owner, linked_contacts, revenue, number_of_employees, created_at, last_updated_at, next_activity_date, owner_assign_date, number_of_contacts, number_of_activities, industry # noqa
"domain": siae.website,
"phone_number": siae.contact_phone_display,
# custom attributes
"app_id": siae.id,
"siae": True,
"active": siae.is_active,
"description": siae.description,
"kind": siae.kind,
"address_street": siae.address,
"address_post_code": siae.post_code,
"address_city": siae.city,
"contact_email": siae.contact_email,
"logo_url": siae.logo_url,
"geo_range": siae.geo_range,
"app_url": get_object_share_url(siae),
"app_admin_url": get_object_admin_url(siae),
},
attributes=attributes,
)

if siae.brevo_company_id: # update
Expand Down

0 comments on commit 55395fb

Please sign in to comment.