From 05b46a82b16ca58436d3865a1fea999dcea8143f Mon Sep 17 00:00:00 2001 From: Mojtaba-z Date: Mon, 16 Jun 2025 09:08:01 +0330 Subject: [PATCH] add company code to organization serialzier & handle quota weight exception --- apps/product/exceptions.py | 10 +++++++ .../api/v1/quota_distribution_serializers.py | 26 +++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 apps/product/exceptions.py diff --git a/apps/product/exceptions.py b/apps/product/exceptions.py new file mode 100644 index 0000000..a4fb90f --- /dev/null +++ b/apps/product/exceptions.py @@ -0,0 +1,10 @@ +from rest_framework.exceptions import APIException +from rest_framework import status + + +class QuotaWeightException(APIException): + """ if quota distributions weight is more """ + + status_code = status.HTTP_401_UNAUTHORIZED + default_detail = '' + default_code = 'unauthorized' diff --git a/apps/product/web/api/v1/quota_distribution_serializers.py b/apps/product/web/api/v1/quota_distribution_serializers.py index 85ecbc9..a9a7a79 100644 --- a/apps/product/web/api/v1/quota_distribution_serializers.py +++ b/apps/product/web/api/v1/quota_distribution_serializers.py @@ -1,6 +1,9 @@ from rest_framework import serializers from apps.product import models as product_models from apps.product.web.api.v1.product_serializers import QuotaSerializer +from django.db import models +from rest_framework.exceptions import APIException +from rest_framework import status class QuotaDistributionSerializer(serializers.ModelSerializer): @@ -13,6 +16,29 @@ class QuotaDistributionSerializer(serializers.ModelSerializer): } } + def validate(self, data): + """ to validate if distribution weight + more than quota weight raise exception """ + + quota = data['quota'] + amount = data['weight'] + instance_id = self.instance.id if self.instance else None + + total = product_models.QuotaDistribution.objects.filter( + quota_id=quota + ).exclude(id=instance_id).aggregate( + total=models.Sum('weight') + )['total'] or 0 + print(total) + if total + amount > self.instance.weight: + raise APIException( + "مقدار وارد شده باعث می‌شود مجموع سهمیه‌ها از مقدار کل سهمیه بیشتر شود.", # noqa + status.HTTP_400_BAD_REQUEST, + + ) + + return data + def to_representation(self, instance): """ Custom output of serializer """