Files
RasadDam_Backend/apps/warehouse/web/api/v1/serializers.py

103 lines
3.4 KiB
Python

from django.db import models
from rest_framework import serializers
from apps.product.exceptions import QuotaExpiredTimeException
from apps.warehouse import models as warehouse_models
from apps.warehouse.exceptions import (
InventoryEntryWeightException
)
class InventoryEntrySerializer(serializers.ModelSerializer):
class Meta:
model = warehouse_models.InventoryEntry
fields = [
"id",
"create_date",
"modify_date",
"organization",
"distribution",
"weight",
"balance",
"lading_number",
"delivery_address",
"is_confirmed",
"notes",
]
def validate(self, attrs):
"""
check if inventory entries weight is not more than
distribution weight & check quota expired time
"""
distribution = attrs['distribution']
# check for quota expired time
if not distribution.quota.is_in_valid_time():
raise QuotaExpiredTimeException()
# total inventory entries weight
total_entered = distribution.inventory_entry.filter(is_confirmed=True).aggregate(
total=models.Sum('weight')
)['total'] or 0
# if instance exists, for update check weight with distribution weight
if self.instance:
if self.instance.weight == 0:
if total_entered + attrs['weight'] > distribution.weight:
raise InventoryEntryWeightException()
elif self.instance.weight != 0:
if total_entered - self.instance.weight + attrs['weight'] > distribution.weight:
raise InventoryEntryWeightException()
# if instance is not exists for create, check entry weight with distribution
else:
if total_entered + attrs['weight'] > distribution.weight or \
total_entered + attrs['weight'] > distribution.remaining_weight:
raise InventoryEntryWeightException()
return attrs
def to_representation(self, instance):
""" custom output of inventory entry serializer """
representation = super().to_representation(instance)
if instance.document:
representation['document'] = instance.document
if instance.distribution:
# distribution data
representation['distribution'] = {
'distribution': instance.distribution.distribution_id,
'sale_unit': instance.distribution.quota.sale_unit.unit,
'id': instance.distribution.id
}
representation['product'] = {
'name': instance.distribution.quota.product.name
}
return representation
class InventoryQuotaSaleTransactionSerializer(serializers.ModelSerializer):
class Meta:
model = warehouse_models.InventoryQuotaSaleTransaction
fields = '__all__'
depth = 0
def validate(self, attrs):
"""
validate total inventory sale should be fewer than
inventory entry from distribution
"""
inventory_entry = attrs['inventory_entry']
distribution = attrs['quota_distribution']
return attrs
class InventoryQuotaSaleItemSerializer(serializers.ModelSerializer):
class Meta:
model = warehouse_models.InventoryQuotaSaleItem
fields = '__all__'