Skip to content

Commit

Permalink
[#53] Ensuring auto-incrementing klantnummer works as expected
Browse files Browse the repository at this point in the history
  • Loading branch information
alextreme committed Sep 4, 2023
1 parent fc5996f commit ccde650
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
11 changes: 10 additions & 1 deletion src/openklant/components/klanten/api/tests/test_klant.py
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,16 @@ def test_create_klant_website_url_optional(self):

self.assertEqual(klant.bronorganisatie, "950428139")
self.assertEqual(klant.website_url, "")
self.assertTrue(klant.klantnummer != 0)
self.assertEqual(klant.klantnummer, "1")

with requests_mock.Mocker() as m:
m.get(SUBJECT, json={})
response = self.client.post(list_url, data)

self.assertEqual(response.status_code, status.HTTP_201_CREATED)

klant = Klant.objects.get(klantnummer__gt=1)
self.assertEqual(klant.klantnummer, "2")

def test_create_klant_website_url_duplicate_klantnummer(self):
list_url = reverse(Klant)
Expand Down
8 changes: 6 additions & 2 deletions src/openklant/components/klanten/models/klanten.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@

class KlantManager(models.Manager):
def get_next_klantnummer(self):
id_max = Klant.objects.all().aggregate(Max("klantnummer"))["id__max"]
return id_max + 1 if id_max else 1
id_max = Klant.objects.all().aggregate(models.Max("klantnummer"))[
"klantnummer__max"
]
return int(id_max) + 1 if id_max else 1


class Klant(APIMixin, models.Model):
Expand Down Expand Up @@ -102,6 +104,8 @@ class Meta:
verbose_name_plural = "klanten"

def save(self, *args, **kwargs):
if not self.klantnummer:
self.klantnummer = Klant.objects.get_next_klantnummer()
if not self.pk:
if Klant.objects.filter(klantnummer=self.klantnummer):
raise Conflict("Klantnummer bestaat al")
Expand Down

0 comments on commit ccde650

Please sign in to comment.