from django.db.models.signals import post_save
from django.dispatch import receiver
from goods_reception.models import GoodsReception
from warehouse.models import StockOperation, Warehouse, StorageLocation

@receiver(post_save, sender=GoodsReception)
def handle_goods_reception(sender, instance, created, **kwargs):
    if created and instance.is_accepted:
        # операция прихода
        operation = StockOperation.objects.create(
            product=instance.product,
            warehouse=Warehouse.objects.get(name="Основной склад"),
            storage_location=StorageLocation.objects.filter(warehouse__name="Основной склад").first(),
            operation_type='Incoming',
            quantity=instance.quantity,
            expiration_date=None  # Укажите срок годности, если известно
        )

        # логика распределения по местам хранения
        if instance.product.storage_temperature == "+4C":
            cold_storage = StorageLocation.objects.filter(warehouse=operation.warehouse, temperature_control=True).first()
            if cold_storage:
                operation.storage_location = cold_storage
                operation.save()
