Cruise signals
Cruise signals (English fallback)
Aug. 17, 2025
Posted by admin
Nhom |
Notes |
|
Django Signals in Cruise Application - Detailed Analysis What Are Django Signals? Django signals are a form of event-driven programming that allows certain senders to notify a set of receivers when specific actions occur. They implement the Observer Pattern and provide a way to automatically execute code when database operations happen. Your Current Signals Implementation Let me examine the complete signals file and explain each component: Read signals.py
|
|
Detailed Signal Analysis
|
|
1. Signal #1: calculate_commission (pre_save) Type: pre_save signal Trigger: Before a CruiseBooking instance is saved to the database Purpose: Automatic commission calculation for travel agents/booking platform @receiver(pre_save, sender=CruiseBooking) def calculate_commission(sender, instance, **kwargs): """Calculate commission amount before saving booking""" if instance.total_price and instance.commission_rate: instance.commission_amount = (instance.total_price * instance.commission_rate) / 100 Business Logic Explanation:
Real-World Scenario: # When this happens in your booking view: booking = CruiseBooking.objects.create( total_price=Decimal('2500.00'), commission_rate=Decimal('10.00'), # 10% # ... other fields ) # The signal automatically sets: # booking.commission_amount = 250.00 (before saving) Benefits:
|
|
2. Signal #2: update_cabin_availability (post_save) Type: post_save signal Trigger: After a CruiseBooking instance is saved to the database Purpose: Inventory management for cruise cabin availability @receiver(post_save, sender=CruiseBooking) def update_cabin_availability(sender, instance, created, **kwargs): """Update cabin availability when booking is created/confirmed""" if created and instance.status == 'confirmed': # Reduce available cabins cruise_price = instance.cruise.prices.filter( cabin_category=instance.cabin_category ).first() if cruise_price and cruise_price.available_cabins > 0: cruise_price.available_cabins -= 1 cruise_price.save()
|
|
Business Logic Explanation:
Inventory Management Flow:
|
|
Enhanced Signals Implementation Let me show you how to expand this signals system for a production-ready cruise booking platform: signals.py+195-2 Let me fix the import error: signals.py+1-0 signals.py+0-1 Now let me check if there are any additional signal-related issues and explain the comprehensive signal system: Checked signals.py, no problems found Perfect! Now let me provide you with a comprehensive explanation of the enhanced signals system:
|
|
Complete Django Signals Analysis for Cruise Application Signal Types and Their Uses 1. pre_save Signals - Data Preparation Purpose: Execute logic BEFORE an object is saved to the database Use Cases: Data validation, automatic calculations, field population 2. post_save Signals - Post-Processing Purpose: Execute logic AFTER an object is successfully saved Use Cases: Related model updates, notifications, logging, analytics 3. post_delete Signals - Cleanup Operations Purpose: Execute logic AFTER an object is deleted Use Cases: Cleanup, counter updates, cascade operations
|
|
Enhanced Signal Functions Explained
|
|
1. Commission Calculation (pre_save) @receiver(pre_save, sender=CruiseBooking) def calculate_commission(sender, instance, **kwargs): Business Purpose: Ensures every booking automatically calculates travel agent commissions Benefits:
|
|
2. Inventory Management (post_save) @receiver(post_save, sender=CruiseBooking) def update_cabin_availability(sender, instance, created, **kwargs): Business Purpose: Real-time cabin inventory management Benefits:
|
|
3. Booking Status Management (post_save) @receiver(post_save, sender=CruiseBooking) def handle_booking_status_changes(sender, instance, created, **kwargs): Business Purpose: Automated customer communication and workflow management Features:
|
|
4. Cancellation Processing (post_save) @receiver(post_save, sender=CruiseBooking) def restore_cabin_availability_on_cancellation(sender, instance, **kwargs): Business Purpose: Inventory restoration and cancellation fee processing Features:
Refund amount calculation |
|
5. Review Rating Updates (post_save) @receiver(post_save, sender=CruiseReview) def update_cruise_rating(sender, instance, created, **kwargs): Business Purpose: Dynamic cruise rating calculation Features:
|
|
6. Wishlist Analytics (post_save & post_delete) @receiver(post_save, sender=CruiseWishlist) def track_wishlist_analytics(sender, instance, created, **kwargs): Business Purpose: Customer preference tracking and marketing analytics Features:
|
|
Advanced Signal Features Email Notification System The signals include comprehensive email handling:
Logging and Monitoring logger = logging.getLogger(__name__) logger.info(f"Commission calculated for booking {instance.pk}: ${instance.commission_amount}") Benefits:
Error Handling try: # Email sending logic except Exception as e: logger.error(f"Failed to send email: {str(e)}") Features:
|
|
Business Rules Implementation Cancellation Policy Automation days_until_departure = (booking.cruise.departure_date - timezone.now().date()).days if days_until_departure < 30: cancellation_fee = booking.total_price * Decimal('0.25') # 25% fee
|
|
Business Logic:
|
|
Signal Registration and Apps.py Integration To ensure signals are properly loaded, you need to register them in your apps.py: Read apps.py Great! The signals are already properly registered in the apps.py file. Performance Considerations Signal Optimization Best Practices:
if created and instance.status == 'confirmed': # Only for new confirmed bookings
cruise.save(update_fields=['average_rating'])
try: # Signal logic except Exception as e: logger.error(f"Signal error: {str(e)}")
|
|
Testing Signals Here's how you would test these signals: from django.test import TestCase from apps.cruise.models import CruiseBooking from decimal import Decimal class SignalTests(TestCase): def test_commission_calculation(self): booking = CruiseBooking.objects.create( total_price=Decimal('1000.00'), commission_rate=Decimal('10.00'), # ... other required fields ) self.assertEqual(booking.commission_amount, Decimal('100.00'))
def test_cabin_availability_update(self): # Test that confirmed booking reduces availability initial_cabins = cruise_price.available_cabins CruiseBooking.objects.create( status='confirmed', # ... other fields ) cruise_price.refresh_from_db() self.assertEqual(cruise_price.available_cabins, initial_cabins - 1)
|
|
Production Considerations Monitoring and Alerting:
Scalability:
Data Consistency:
This comprehensive signal system transforms your cruise booking platform into an automated, business-rule-driven application that handles complex workflows without manual intervention, ensuring data consistency, customer communication, and operational efficienc
|
Nhom |
Notes |
|
Django Signals in Cruise Application - Detailed Analysis What Are Django Signals? Django signals are a form of event-driven programming that allows certain senders to notify a set of receivers when specific actions occur. They implement the Observer Pattern and provide a way to automatically execute code when database operations happen. Your Current Signals Implementation Let me examine the complete signals file and explain each component: Read signals.py
|
|
Detailed Signal Analysis
|
|
1. Signal #1: calculate_commission (pre_save) Type: pre_save signal Trigger: Before a CruiseBooking instance is saved to the database Purpose: Automatic commission calculation for travel agents/booking platform @receiver(pre_save, sender=CruiseBooking) def calculate_commission(sender, instance, **kwargs): """Calculate commission amount before saving booking""" if instance.total_price and instance.commission_rate: instance.commission_amount = (instance.total_price * instance.commission_rate) / 100 Business Logic Explanation:
Real-World Scenario: # When this happens in your booking view: booking = CruiseBooking.objects.create( total_price=Decimal('2500.00'), commission_rate=Decimal('10.00'), # 10% # ... other fields ) # The signal automatically sets: # booking.commission_amount = 250.00 (before saving) Benefits:
|
|
2. Signal #2: update_cabin_availability (post_save) Type: post_save signal Trigger: After a CruiseBooking instance is saved to the database Purpose: Inventory management for cruise cabin availability @receiver(post_save, sender=CruiseBooking) def update_cabin_availability(sender, instance, created, **kwargs): """Update cabin availability when booking is created/confirmed""" if created and instance.status == 'confirmed': # Reduce available cabins cruise_price = instance.cruise.prices.filter( cabin_category=instance.cabin_category ).first() if cruise_price and cruise_price.available_cabins > 0: cruise_price.available_cabins -= 1 cruise_price.save()
|
|
Business Logic Explanation:
Inventory Management Flow:
|
|
Enhanced Signals Implementation Let me show you how to expand this signals system for a production-ready cruise booking platform: signals.py+195-2 Let me fix the import error: signals.py+1-0 signals.py+0-1 Now let me check if there are any additional signal-related issues and explain the comprehensive signal system: Checked signals.py, no problems found Perfect! Now let me provide you with a comprehensive explanation of the enhanced signals system:
|
|
Complete Django Signals Analysis for Cruise Application Signal Types and Their Uses 1. pre_save Signals - Data Preparation Purpose: Execute logic BEFORE an object is saved to the database Use Cases: Data validation, automatic calculations, field population 2. post_save Signals - Post-Processing Purpose: Execute logic AFTER an object is successfully saved Use Cases: Related model updates, notifications, logging, analytics 3. post_delete Signals - Cleanup Operations Purpose: Execute logic AFTER an object is deleted Use Cases: Cleanup, counter updates, cascade operations
|
|
Enhanced Signal Functions Explained
|
|
1. Commission Calculation (pre_save) @receiver(pre_save, sender=CruiseBooking) def calculate_commission(sender, instance, **kwargs): Business Purpose: Ensures every booking automatically calculates travel agent commissions Benefits:
|
|
2. Inventory Management (post_save) @receiver(post_save, sender=CruiseBooking) def update_cabin_availability(sender, instance, created, **kwargs): Business Purpose: Real-time cabin inventory management Benefits:
|
|
3. Booking Status Management (post_save) @receiver(post_save, sender=CruiseBooking) def handle_booking_status_changes(sender, instance, created, **kwargs): Business Purpose: Automated customer communication and workflow management Features:
|
|
4. Cancellation Processing (post_save) @receiver(post_save, sender=CruiseBooking) def restore_cabin_availability_on_cancellation(sender, instance, **kwargs): Business Purpose: Inventory restoration and cancellation fee processing Features:
Refund amount calculation |
|
5. Review Rating Updates (post_save) @receiver(post_save, sender=CruiseReview) def update_cruise_rating(sender, instance, created, **kwargs): Business Purpose: Dynamic cruise rating calculation Features:
|
|
6. Wishlist Analytics (post_save & post_delete) @receiver(post_save, sender=CruiseWishlist) def track_wishlist_analytics(sender, instance, created, **kwargs): Business Purpose: Customer preference tracking and marketing analytics Features:
|
|
Advanced Signal Features Email Notification System The signals include comprehensive email handling:
Logging and Monitoring logger = logging.getLogger(__name__) logger.info(f"Commission calculated for booking {instance.pk}: ${instance.commission_amount}") Benefits:
Error Handling try: # Email sending logic except Exception as e: logger.error(f"Failed to send email: {str(e)}") Features:
|
|
Business Rules Implementation Cancellation Policy Automation days_until_departure = (booking.cruise.departure_date - timezone.now().date()).days if days_until_departure < 30: cancellation_fee = booking.total_price * Decimal('0.25') # 25% fee
|
|
Business Logic:
|
|
Signal Registration and Apps.py Integration To ensure signals are properly loaded, you need to register them in your apps.py: Read apps.py Great! The signals are already properly registered in the apps.py file. Performance Considerations Signal Optimization Best Practices:
if created and instance.status == 'confirmed': # Only for new confirmed bookings
cruise.save(update_fields=['average_rating'])
try: # Signal logic except Exception as e: logger.error(f"Signal error: {str(e)}")
|
|
Testing Signals Here's how you would test these signals: from django.test import TestCase from apps.cruise.models import CruiseBooking from decimal import Decimal class SignalTests(TestCase): def test_commission_calculation(self): booking = CruiseBooking.objects.create( total_price=Decimal('1000.00'), commission_rate=Decimal('10.00'), # ... other required fields ) self.assertEqual(booking.commission_amount, Decimal('100.00'))
def test_cabin_availability_update(self): # Test that confirmed booking reduces availability initial_cabins = cruise_price.available_cabins CruiseBooking.objects.create( status='confirmed', # ... other fields ) cruise_price.refresh_from_db() self.assertEqual(cruise_price.available_cabins, initial_cabins - 1)
|
|
Production Considerations Monitoring and Alerting:
Scalability:
Data Consistency:
This comprehensive signal system transforms your cruise booking platform into an automated, business-rule-driven application that handles complex workflows without manual intervention, ensuring data consistency, customer communication, and operational efficienc
|
Attached Files
You are viewing this article in public mode. Some features may be limited.