from django.db.models.signals import post_save, pre_save from django.dispatch import receiver from django.conf import settings from django.contrib.sites.shortcuts import get_current_site from django.core.exceptions import ObjectDoesNotExist from .models import Order, Product, PaymentError from .emails import ( send_order_confirmation, send_order_status_update, send_shipping_confirmation, send_admin_notification, send_low_stock_notification ) @receiver(post_save, sender=Order) def handle_order_notifications(sender, instance, created, **kwargs): """ Sendet E-Mail-Benachrichtigungen basierend auf Bestellstatus """ if created: # Neue Bestellung - Admin benachrichtigen notification_type = 'fursuit_order' if any(p.product_type == 'fursuit' for p in instance.products.all()) else 'new_order' if hasattr(instance, 'customer_design') and instance.customer_design: notification_type = 'custom_design' send_admin_notification(None, instance, notification_type) else: # Status-Änderung try: old_instance = Order.objects.get(id=instance.id) if old_instance.status != instance.status: # Status hat sich geändert - Kunde benachrichtigen send_order_status_update(None, instance) # Bei Versand zusätzlich Versandbestätigung senden if instance.status == 'completed' and instance.tracking_number: send_shipping_confirmation(None, instance) except ObjectDoesNotExist: pass @receiver(post_save, sender=PaymentError) def handle_payment_error(sender, instance, created, **kwargs): """ Benachrichtigt den Admin über Zahlungsfehler """ if created: send_admin_notification(None, instance.order, 'payment_failed', { 'payment_error': instance }) @receiver(pre_save, sender=Product) def check_stock_level(sender, instance, **kwargs): """ Überprüft den Lagerbestand und sendet Benachrichtigungen bei niedrigem Stand """ if not instance.pk: # Neues Produkt return try: old_instance = Product.objects.get(pk=instance.pk) # Wenn der Lagerbestand unter den Schwellenwert fällt if (old_instance.stock > settings.LOW_STOCK_THRESHOLD and instance.stock <= settings.LOW_STOCK_THRESHOLD): send_low_stock_notification(None, instance) except ObjectDoesNotExist: pass