add - import validator for organization quota stats
This commit is contained in:
0
apps/product/validators/__init__.py
Normal file
0
apps/product/validators/__init__.py
Normal file
60
apps/product/validators/quota_stats_validator.py
Normal file
60
apps/product/validators/quota_stats_validator.py
Normal file
@@ -0,0 +1,60 @@
|
||||
from django.apps import apps
|
||||
from django.core.exceptions import ValidationError
|
||||
from rest_framework.exceptions import APIException
|
||||
|
||||
|
||||
def get_model(app_label, model_name):
|
||||
return apps.get_model(app_label, model_name)
|
||||
|
||||
|
||||
class QuotaStatsValidator:
|
||||
"""
|
||||
Validator static methods for distribution/sale/quota edits.
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def _get_stat(quota, organization):
|
||||
organization_quota_stats = get_model("product", "OrganizationQuotaStats")
|
||||
return organization_quota_stats.objects.filter(quota=quota, organization=organization).first()
|
||||
|
||||
@staticmethod
|
||||
def validate_assigner_has_enough(assigner_org, quota, amount, allow_zero=False):
|
||||
"""
|
||||
if organization has enough remaining weight
|
||||
"""
|
||||
stat = QuotaStatsValidator._get_stat(quota, assigner_org)
|
||||
if not stat:
|
||||
raise APIException(f"Organization {assigner_org} has no quota record for quota {quota}.")
|
||||
|
||||
remaining = getattr(stat, "remaining_amount", None)
|
||||
if remaining is None:
|
||||
# fallback to quota.remaining_weight subtraction from totals
|
||||
raise APIException("remaining_amount field missing in OrganizationQuotaStats.")
|
||||
|
||||
if amount < 0:
|
||||
raise APIException("Amount must be non-negative.")
|
||||
|
||||
if remaining < amount and not allow_zero:
|
||||
raise APIException(
|
||||
f"Assigning {amount} exceeds remaining amount {remaining} for organization {assigner_org}."
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def validate_distribution_create(assigner_org, assigned_org, quota, amount, parent_distribution=None):
|
||||
# rule: assigner must have enough remaining weight
|
||||
QuotaStatsValidator.validate_assigner_has_enough(assigner_org, quota, amount)
|
||||
|
||||
@staticmethod
|
||||
def validate_distribution_update(assigner_org, assigned_org, quota, old_amount, new_amount,
|
||||
parent_distribution=None):
|
||||
# if diff is positive we must check
|
||||
diff = new_amount - (old_amount or 0)
|
||||
if diff > 0:
|
||||
QuotaStatsValidator.validate_assigner_has_enough(assigner_org, quota, diff)
|
||||
|
||||
@staticmethod
|
||||
def validate_distribution_delete(distribution):
|
||||
# اگر already sold (been_sold > 0) نباید حذف شود
|
||||
been_sold = getattr(distribution, "been_sold", None)
|
||||
if been_sold and been_sold > 0:
|
||||
raise ValidationError("Cannot delete distribution: it has sold items.")
|
||||
Reference in New Issue
Block a user