Skip to content

Commit

Permalink
fix(Structures): Correction sur le contrôle d'unicité du nom commerci…
Browse files Browse the repository at this point in the history
…al (#1606)
  • Loading branch information
SebastienReuiller authored Jan 8, 2025
1 parent b554abf commit 171abff
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
10 changes: 10 additions & 0 deletions lemarche/siaes/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -1262,7 +1262,17 @@ def clean(self):
Does not use a unique constraint on model because it allows blank values and checks two fields simultaneously.
"""
super().clean()

# Check only if brand is set and different from the original brand
# (to avoid validation error on update without brand change)
check_brand_uniqueness = False
if self.brand:
check_brand_uniqueness = True
if self.pk:
original_brand = Siae.objects.get(pk=self.pk).brand
check_brand_uniqueness = original_brand != self.brand

if check_brand_uniqueness:
# 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:
Expand Down
40 changes: 40 additions & 0 deletions lemarche/siaes/tests/test_models.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from django.core.exceptions import ValidationError
from django.test import TestCase
from django.utils import timezone

Expand Down Expand Up @@ -418,6 +419,45 @@ def test_set_super_badge(self):
self.assertTrue(siae_super_badge_2.super_badge)
self.assertEqual(siae_super_badge_2.super_badge_last_updated, siae_super_badge_last_updated_current_value)

def test_brand_uniqueness(self):
SiaeFactory(name="Name 1", brand="Brand 1")
SiaeFactory(brand="Brand 2")
siae_3 = SiaeFactory(brand="Brand 1")
self.assertEqual(Siae.objects.filter(brand="Brand 1").count(), 2)

# can update something else than brand
siae_3.contact_first_name = "Contact 1"
siae_3.clean()
siae_3.save()

self.assertEqual(Siae.objects.filter(brand="Brand 1").count(), 2)
siae_3.refresh_from_db()
self.assertEqual(siae_3.contact_first_name, "Contact 1")

# can't update brand to an existing brand
siae_3.brand = "Brand 2"
with self.assertRaises(ValidationError):
siae_3.clean()
siae_3.save()
self.assertEqual(Siae.objects.filter(brand="Brand 1").count(), 2)

# can't update brand to an existing name
siae_3.brand = "Name 1"
with self.assertRaises(ValidationError):
siae_3.clean()
siae_3.save()

siae_3.refresh_from_db()
self.assertEqual(siae_3.brand, "Brand 1")

# can update brand to a non existing brand
siae_3.brand = "Brand 3"
siae_3.name = "Name 3"
siae_3.clean()
siae_3.save()
siae_3.refresh_from_db()
self.assertEqual(siae_3.brand, "Brand 3")


class SiaeModelQuerysetTest(TestCase):
@classmethod
Expand Down

0 comments on commit 171abff

Please sign in to comment.