Coverage for modules\email\signals.py: 44%

16 statements  

« prev     ^ index     » next       coverage.py v7.16.0, created at 2026-09-05 09:19 +0800

1""" 

2Email Signals - Automatic behaviors for email module 

3""" 

4from django.db.models.signals import post_save, pre_delete 

5from django.dispatch import receiver 

6 

7from .models import EmailAccount, EmailMessage, InternalEmailRecipient 

8 

9 

10@receiver(post_save, sender=EmailAccount) 

11def set_primary_account(sender, instance, created, **kwargs): 

12 """ 

13 When a new email account is created, if it's the first one, 

14 automatically set it as primary. 

15 """ 

16 if created: 

17 # Check if this is the first account for this user 

18 existing_count = EmailAccount.objects.filter( 

19 user=instance.user, 

20 tenant_id=instance.tenant_id 

21 ).count() 

22 

23 if existing_count == 1: 

24 # First account, set as primary 

25 instance.is_primary = True 

26 instance.save(update_fields=['is_primary']) 

27 

28 

29@receiver(post_save, sender=InternalEmailRecipient) 

30def notify_new_internal_email(sender, instance, created, **kwargs): 

31 """ 

32 When a new internal email is received, trigger a notification. 

33 """ 

34 if created: 

35 # Import here to avoid circular imports 

36 from modules.notifications.services import NotificationService 

37 

38 # Get sender info 

39 sender = instance.email.sender 

40 

41 # Create in-app notification 

42 NotificationService.create_notification( 

43 user_id=instance.recipient_id, 

44 tenant_id=instance.tenant_id, 

45 title=f"New internal email from {sender.display_name or sender.email}", 

46 message=instance.email.subject, 

47 notification_type='email', 

48 reference_id=str(instance.email.id), 

49 reference_type='internal_email', 

50 )