fix: postchecks fix, added validation to target type

btw small refactoring
This commit is contained in:
ITQ
2025-01-29 19:22:02 +03:00
parent 9f3a08d39d
commit 2cb8f81cb1
3 changed files with 25 additions and 8 deletions
+23 -2
View File
@@ -1,9 +1,9 @@
import datetime import datetime
import uuid import uuid
from typing import ClassVar, Literal from typing import Any, ClassVar, Literal
from ninja import ModelSchema, Schema from ninja import ModelSchema, Schema
from pydantic import Field, StrictInt from pydantic import Field, StrictInt, field_validator
from pydantic_extra_types.country import CountryAlpha2 from pydantic_extra_types.country import CountryAlpha2
from apps.business.models import Business from apps.business.models import Business
@@ -64,6 +64,16 @@ class CreatePromocodeIn(ModelSchema):
Promocode.promo_common.field.name, Promocode.promo_common.field.name,
] ]
@field_validator("target", mode="before")
def validate_target(cls, value: Any) -> Any:
if not isinstance(value, dict) and not isinstance(
value,
PromocodeTarget,
):
err = "The 'target' field must be a valid object."
raise ValueError(err)
return value
class CreatePromocodeOut(Schema): class CreatePromocodeOut(Schema):
id: uuid.UUID id: uuid.UUID
@@ -113,6 +123,17 @@ class PatchPromocodeIn(Schema):
active_from: datetime.date | None = None active_from: datetime.date | None = None
active_until: datetime.date | None = None active_until: datetime.date | None = None
@staticmethod
@field_validator("target", mode="before")
def validate_target(value: Any) -> Any:
if not isinstance(value, dict) and not isinstance(
value,
PromocodeTarget,
):
err = "The 'target' field must be a valid object."
raise TypeError(err)
return value
class PromocodeStatsForCountry(Schema): class PromocodeStatsForCountry(Schema):
country: str country: str
+1 -3
View File
@@ -12,9 +12,7 @@ def map_promocode_to_schema(promocode: Promocode) -> schemas.PromocodeViewOut:
target=schemas.PromocodeTargetViewOut( target=schemas.PromocodeTargetViewOut(
age_from=promocode.target.age_from, age_from=promocode.target.age_from,
age_until=promocode.target.age_until, age_until=promocode.target.age_until,
country=promocode.target.country_raw country=promocode.target.country_raw or None,
if promocode.target.country_raw
else None,
categories=promocode.target.categories, categories=promocode.target.categories,
), ),
max_count=promocode.max_count, max_count=promocode.max_count,
+1 -3
View File
@@ -170,9 +170,7 @@ def feed(
category_lower = filters.category.lower() category_lower = filters.category.lower()
def matches_category(promocode: Promocode) -> bool: def matches_category(promocode: Promocode) -> bool:
categories = ( categories = promocode.target.categories or []
promocode.target.categories or []
)
return any( return any(
category.lower() == category_lower for category in categories category.lower() == category_lower for category in categories
) )