diff --git a/lemarche/siaes/models.py b/lemarche/siaes/models.py index bfa284c54..24a16fdee 100644 --- a/lemarche/siaes/models.py +++ b/lemarche/siaes/models.py @@ -6,6 +6,7 @@ from django.contrib.gis.db.models.functions import Distance from django.contrib.gis.measure import D from django.contrib.postgres.search import TrigramSimilarity # SearchVector +from django.core.exceptions import ValidationError from django.db import IntegrityError, models, transaction from django.db.models import ( BooleanField, @@ -1279,6 +1280,18 @@ def set_super_badge(self): self.save(update_fields=update_fields_list) + def clean(self): + """ + Validate that brand is not used as a brand or name by another Siae + Does not use a unique constraint on model because it allows blank values and checks two fields simultaneously. + """ + super().clean() + if self.brand: + # Check if brand is used as name by another Siae + name_exists = Siae.objects.exclude(id=self.id).filter(Q(name=self.brand) | Q(brand=self.brand)).exists() + if name_exists: + raise ValidationError({"brand": "Ce nom commercial est déjà utilisé par une autre structure."}) + @receiver(post_save, sender=Siae) def siae_post_save(sender, instance, **kwargs): diff --git a/lemarche/www/dashboard_siaes/tests.py b/lemarche/www/dashboard_siaes/tests.py index f6fae991d..4346c968e 100644 --- a/lemarche/www/dashboard_siaes/tests.py +++ b/lemarche/www/dashboard_siaes/tests.py @@ -193,6 +193,19 @@ def test_siae_edit_info_form(self): self.assertEqual(self.siae_with_user.brand, "Nouveau nom commercial") self.assertEqual(self.siae_with_user.name_display, "Nouveau nom commercial") + def test_siae_edit_info_form_brand_unique(self): + SiaeFactory(brand="Nouveau nom commercial") + + self.client.force_login(self.user_siae) + url = reverse("dashboard_siaes:siae_edit_info", args=[self.siae_with_user.slug]) + + data = { + "brand": "Nouveau nom commercial", + } + response = self.client.post(url, data=data) + self.assertEqual(response.status_code, 200) + self.assertContains(response, "Ce nom commercial est déjà utilisé par une autre structure.") + class DashboardSiaeUserViewTest(TestCase): @classmethod