from django.db.models.signals import pre_save, post_save, post_delete from django.dispatch import receiver from custom_objects.models import CustomRecord from crm_core.models import Account, Contact, Lead, Opportunity, Activity from outreach.models import Campaign from custom_objects.formula_engine import evaluate_all_formulas_for_instance from custom_objects.rollup_engine import recalculate_rollups_for_record @receiver(pre_save, sender=Account) @receiver(pre_save, sender=Contact) @receiver(pre_save, sender=Lead) @receiver(pre_save, sender=Opportunity) @receiver(pre_save, sender=Activity) @receiver(pre_save, sender=Campaign) @receiver(pre_save, sender=CustomRecord) def evaluate_record_formulas(sender, instance, **kwargs): evaluate_all_formulas_for_instance(instance) # Roll-up summary triggers on child objects @receiver(post_save, sender=Opportunity) @receiver(post_delete, sender=Opportunity) def trigger_opportunity_rollup(sender, instance, **kwargs): if instance.account_id: recalculate_rollups_for_record('Account', instance.account_id) if instance.primary_contact_id: recalculate_rollups_for_record('Contact', instance.primary_contact_id) @receiver(post_save, sender=Contact) @receiver(post_delete, sender=Contact) def trigger_contact_rollup(sender, instance, **kwargs): if instance.account_id: recalculate_rollups_for_record('Account', instance.account_id) @receiver(post_save, sender=Activity) @receiver(post_delete, sender=Activity) def trigger_activity_rollup(sender, instance, **kwargs): if hasattr(instance, 'content_type') and instance.content_type: model_name = instance.content_type.model.capitalize() recalculate_rollups_for_record(model_name, instance.object_id) if getattr(instance, 'account_id', None): recalculate_rollups_for_record('Account', instance.account_id) if getattr(instance, 'contact_id', None): recalculate_rollups_for_record('Contact', instance.contact_id) if getattr(instance, 'opportunity_id', None): recalculate_rollups_for_record('Opportunity', instance.opportunity_id) if getattr(instance, 'lead_id', None): recalculate_rollups_for_record('Lead', instance.lead_id)