Skip to content

Commit

Permalink
[#233] Fix validators messages
Browse files Browse the repository at this point in the history
  • Loading branch information
danielmursa-dev committed Dec 20, 2024
1 parent 01f82ee commit bc2b67a
Show file tree
Hide file tree
Showing 4 changed files with 112 additions and 57 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@
Vertegenwoordigden,
)
from openklant.components.klantinteracties.models.rekeningnummers import Rekeningnummer
from openklant.components.klantinteracties.models.validators import (
PartijIdentificatorValidator,
)
from openklant.utils.serializers import get_field_value


class PartijForeignkeyBaseSerializer(serializers.HyperlinkedModelSerializer):
Expand Down Expand Up @@ -399,6 +403,11 @@ class Meta:
},
}

def validate(self, attrs):
partij_identificator = get_field_value(self, attrs, "partij_identificator")
PartijIdentificatorValidator(**partij_identificator).validate()
return super().validate(attrs)

@transaction.atomic
def update(self, instance, validated_data):
if "partij" in validated_data:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import datetime

from django.core.exceptions import ValidationError
from django.utils.translation import gettext as _

from rest_framework import status
Expand Down Expand Up @@ -2116,11 +2115,19 @@ def test_invalid_validation_partij_identificator_code_objecttype(self):
"codeRegister": "brp",
},
}

# ValidationError, "ObjectType keuzes zijn beperkt op basis van CodeRegister."
with self.subTest("doesn'actor_is_wrong_instance"):
with self.assertRaises(ValidationError):
self.client.post(url, data)
response = self.client.post(url, data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.data["code"], "invalid")
self.assertEqual(response.data["title"], "Invalid input.")
self.assertEqual(
response.data["invalid_params"][0]["name"],
"partijIdentificator.codeObjecttype",
)
self.assertEqual(response.data["invalid_params"][0]["code"], "invalid")
self.assertEqual(
response.data["invalid_params"][0]["reason"],
"codeObjecttype keuzes zijn beperkt op basis van codeRegister.",
)

def test_invalid_validation_partij_identificator_code_soort_object_id(self):
url = reverse("klantinteracties:partijidentificator-list")
Expand All @@ -2135,10 +2142,20 @@ def test_invalid_validation_partij_identificator_code_soort_object_id(self):
"codeRegister": "brp",
},
}
# "CodeSoortObjectId keuzes zijn beperkt op basis van CodeObjectType.",
with self.subTest("doesn'actor_is_wrong_instance"):
with self.assertRaises(ValidationError):
self.client.post(url, data)

response = self.client.post(url, data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.data["code"], "invalid")
self.assertEqual(response.data["title"], "Invalid input.")
self.assertEqual(
response.data["invalid_params"][0]["name"],
"partijIdentificator.codeSoortObjectId",
)
self.assertEqual(response.data["invalid_params"][0]["code"], "invalid")
self.assertEqual(
response.data["invalid_params"][0]["reason"],
"codeSoortObjectId keuzes zijn beperkt op basis van codeObjecttype.",
)

def test_invalid_validation_partij_identificator_object_id(self):
url = reverse("klantinteracties:partijidentificator-list")
Expand All @@ -2153,10 +2170,20 @@ def test_invalid_validation_partij_identificator_object_id(self):
"codeRegister": "brp",
},
}
# "De lengte van de ObjectId moet tussen 8 en 9 liggen."
with self.subTest("doesn'actor_is_wrong_instance"):
with self.assertRaises(ValidationError):
self.client.post(url, data)

response = self.client.post(url, data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.data["code"], "invalid")
self.assertEqual(response.data["title"], "Invalid input.")
self.assertEqual(
response.data["invalid_params"][0]["name"],
"partijIdentificator.objectId",
)
self.assertEqual(response.data["invalid_params"][0]["code"], "invalid")
self.assertEqual(
response.data["invalid_params"][0]["reason"],
"De lengte van de objectId moet tussen 8 en 9 liggen.",
)

def test_valid_validation_partij_identificator(self):
# All validations pass
Expand Down
14 changes: 1 addition & 13 deletions src/openklant/components/klantinteracties/models/partijen.py
Original file line number Diff line number Diff line change
Expand Up @@ -422,16 +422,4 @@ def save(self, *args, **kwargs):

def clean(self):
super().clean()

partij_validator = PartijIdentificatorValidator(
self.partij_identificator_code_register,
self.partij_identificator_code_objecttype,
self.partij_identificator_code_soort_object_id,
self.partij_identificator_object_id,
)
try:
partij_validator.validate_code_object_type()
partij_validator.validate_code_soort_object_id()
partij_validator.validate_object_id()
except ValidationError as err:
raise ValidationError("eeeeeeeeeeeeeeeeeeeeeee")
PartijIdentificatorValidator(**self.partij_identificator).validate()
91 changes: 61 additions & 30 deletions src/openklant/components/klantinteracties/models/validators.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _

from rest_framework import serializers

from .constants import (
PartijIdentificatorCodeObjectType,
PartijIdentificatorCodeRegister,
Expand Down Expand Up @@ -35,18 +36,23 @@ class PartijIdentificatorValidator:
def __init__(
self,
code_register: str,
code_object_type: str,
code_objecttype: str,
code_soort_object_id: str,
object_id: str,
):
self.code_register = code_register
self.code_object_type = code_object_type
self.code_objecttype = code_objecttype
self.code_soort_object_id = code_soort_object_id
self.object_id = object_id

def validate_code_object_type(self) -> None:
"""Validates the CodeObjectType based on the provided CodeRegister"""
if not self.code_object_type:
def validate(self) -> None:
self.validate_code_objecttype()
self.validate_code_soort_object_id()
self.validate_object_id()

def validate_code_objecttype(self) -> None:
"""Validates the codeObjecttype based on the provided codeRegister"""
if not self.code_objecttype:
return

if (
Expand All @@ -55,32 +61,40 @@ def validate_code_object_type(self) -> None:
):
return

if self.code_object_type not in self.REGISTERS.get(self.code_register, {}):
raise ValidationError(
_("ObjectType keuzes zijn beperkt op basis van CodeRegister.")
if self.code_objecttype not in self.REGISTERS.get(self.code_register, {}):
raise serializers.ValidationError(
{
"partijIdentificator.codeObjecttype": _(
"codeObjecttype keuzes zijn beperkt op basis van codeRegister."
)
}
)

def validate_code_soort_object_id(self) -> None:
"""Validates the CodeSoortObjectId based on register and CodeObjectType"""
"""Validates the codeSoortObjectId based on register and codeObjecttype"""
if not self.code_soort_object_id:
return

if (
not self.code_object_type
or self.code_object_type == PartijIdentificatorCodeObjectType.overige
not self.code_objecttype
or self.code_objecttype == PartijIdentificatorCodeObjectType.overige
):
return

if not any(
self.code_soort_object_id in d.get(self.code_object_type, [])
self.code_soort_object_id in d.get(self.code_objecttype, [])
for d in self.REGISTERS.values()
):
raise ValidationError(
_("CodeSoortObjectId keuzes zijn beperkt op basis van CodeObjectType.")
raise serializers.ValidationError(
{
"partijIdentificator.codeSoortObjectId": _(
"codeSoortObjectId keuzes zijn beperkt op basis van codeObjecttype."
)
}
)

def validate_object_id(self) -> None:
"""Validates the object ID based on the SoortObjectId"""
"""Validates the object ID based on the codeSoortObjectId"""
if not self.object_id:
return

Expand All @@ -90,40 +104,57 @@ def validate_object_id(self) -> None:
):
return

method_name = f"_validate_{self.code_soort_object_id}"
validator = getattr(self, method_name, None)
if validator:
if validator := getattr(self, f"_validate_{self.code_soort_object_id}", None):
validator()
else:
raise ValidationError(
code="object_id",
message=(_("Ongeldige Partij Identificator CodeSoortObjectId.")),
raise serializers.ValidationError(
{
"partijIdentificator.objectId": _(
"Ongeldige Partij Identificator codeSoortObjectId."
)
}
)

def _validate_bsn(self) -> None:
"""Validates the BSN Object ID length"""
if len(self.object_id) not in [8, 9]:
raise ValidationError(
{"object_id": "De lengte van de ObjectId moet tussen 8 en 9 liggen."}
raise serializers.ValidationError(
{
"partijIdentificator.objectId": _(
"De lengte van de objectId moet tussen 8 en 9 liggen."
)
}
)

def _validate_vestigingsnummer(self) -> None:
"""Validates the VestigingsNummer Object ID length"""
if len(self.object_id) not in [12]:
raise ValidationError(
{"object_id": _("De lengte van de ObjectId moet 12 tekens zijn.")}
raise serializers.ValidationError(
{
"partijIdentificator.objectId": _(
"De lengte van de objectId moet 12 tekens zijn."
)
}
)

def _validate_rsin(self) -> None:
"""Validates the Rsin Object ID length"""
if len(self.object_id) not in [8, 9]:
raise ValidationError(
{"object_id": _("De lengte van de ObjectId moet tussen 8 en 9 liggen.")}
raise serializers.ValidationError(
{
"partijIdentificator.objectId": _(
"De lengte van de objectId moet tussen 8 en 9 liggen."
)
}
)

def _validate_kvknummer(self) -> None:
"""Validates the KvkNummer Object ID length"""
if len(self.object_id) not in [8]:
raise ValidationError(
{"object_id": _("De lengte van de ObjectId moet 8 tekens zijn.")}
raise serializers.ValidationError(
{
"partijIdentificator.objectId": _(
"De lengte van de objectId moet 8 tekens zijn."
)
}
)

0 comments on commit bc2b67a

Please sign in to comment.