add - WarehouseAllocationService

This commit is contained in:
2025-11-18 16:51:34 +03:30
parent 23e927a631
commit 4bf900a1e2
7 changed files with 152 additions and 2 deletions

View File

@@ -0,0 +1,57 @@
from django.db import transaction
from rest_framework import status
from apps.product.models import QuotaDistribution, OrganizationQuotaStats
from apps.warehouse.exceptions import WareHouseException
from apps.warehouse.models import InventoryEntry, InventoryEntryAllocation
class WarehouseAllocationService:
@staticmethod
def allocate(entry: InventoryEntry):
"""
Auto allocate entry.total_weight between multiple distributions
"""
with transaction.atomic():
distributions = QuotaDistribution.objects.filter(
assigned_organization=entry.organization,
quota=entry.distribution.quota
).select_related('quota').order_by('-create_date')
if not distributions.exists():
raise WareHouseException("توزیعی برای این انبار وجود ندارد", status.HTTP_403_FORBIDDEN) # noqa
remaining = entry.weight
for dist in distributions:
if remaining <= 0:
break
stat = OrganizationQuotaStats.objects.get(
quota=dist.quota,
organization=dist.assigned_organization
)
capacity = stat.remaining_amount
if capacity <= 0:
continue
allocate_weight = min(remaining, capacity)
InventoryEntryAllocation.objects.create(
distribution=dist,
entry=entry,
weight=allocate_weight
)
stat.inventory_received += allocate_weight
stat.save()
remaining -= allocate_weight
if remaining > 0:
raise WareHouseException(
"مقدار ورد شده از انبار بیشتر از مقدار کل سهمیه توزیع داده شده است",
status.HTTP_400_BAD_REQUEST
)