openforce/custom_objects/rollup_engine.py
Goose cbcc16d7e1
Some checks failed
Build, Test, and Deploy / build-and-deploy (push) Failing after 40s
feat(formulas): implement roll-up summary engine and frontend formula editor (Sprint 4.5C & 4.5D)
- Add custom_objects/rollup_engine.py supporting COUNT, SUM, MIN, MAX aggregations across child relationships with optional JSON filter criteria.
- Wire post_save and post_delete reverse relation signal handlers in custom_objects/signals.py for Opportunity, Contact, and Activity relationships.
- Add frontend formula editor & roll-up configurator in CustomObjectsView.vue with insert helpers (fields, operators, functions) and Check Syntax validation.
- Add validateFormula action to frontend/src/stores/crm.js.
- Add unit and integration tests in tests/test_rollup_engine.py with 100% pass rate.
2026-09-27 20:31:27 +00:00

158 lines
5.7 KiB
Python

from decimal import Decimal
from django.db.models import Sum, Count, Min, Max, Avg
from django.core.exceptions import ValidationError
from custom_objects.models import CustomFieldDefinition, CustomRecord
STANDARD_REVERSE_RELATIONS = {
'Account': {
'Opportunity': {'fk_field': 'account', 'related_name': 'opportunities'},
'Contact': {'fk_field': 'account', 'related_name': 'contacts'},
'Activity': {'fk_field': 'account', 'related_name': 'activities'},
},
'Contact': {
'Opportunity': {'fk_field': 'primary_contact', 'related_name': 'opportunities'},
'Activity': {'fk_field': 'contact', 'related_name': 'activities'},
},
'Lead': {
'Activity': {'fk_field': 'lead', 'related_name': 'activities'},
},
'Opportunity': {
'Activity': {'fk_field': 'opportunity', 'related_name': 'activities'},
}
}
def recalculate_rollups_for_record(parent_entity_or_object, parent_id):
"""
Recalculates all roll-up summary fields defined on the parent record.
parent_entity_or_object: Model class name (e.g. 'Account') or CustomObjectDefinition instance / name.
parent_id: Primary key of parent record.
"""
if not parent_id:
return
# Check for standard model vs custom object
if isinstance(parent_entity_or_object, str):
# Could be standard entity name or custom object api_name
from crm_core.models import Account, Contact, Lead, Opportunity, Activity
from outreach.models import Campaign
model_map = {
'Account': Account,
'Contact': Contact,
'Lead': Lead,
'Opportunity': Opportunity,
'Activity': Activity,
'Campaign': Campaign,
}
parent_model = model_map.get(parent_entity_or_object)
if parent_model:
rollup_fields = CustomFieldDefinition.objects.filter(
entity_name=parent_entity_or_object,
field_type='rollup'
)
try:
parent_instance = parent_model.objects.get(pk=parent_id)
except parent_model.DoesNotExist:
return
if not rollup_fields.exists():
return
if parent_instance.custom_fields is None:
parent_instance.custom_fields = {}
modified = False
for rf in rollup_fields:
val = compute_rollup_value(parent_instance, rf)
parent_instance.custom_fields[rf.name] = val
modified = True
if modified:
parent_instance.save(update_fields=['custom_fields'])
return
# Custom object records rollup
# If parent is custom object
rollup_fields = CustomFieldDefinition.objects.filter(
custom_object__name=str(parent_entity_or_object),
field_type='rollup'
)
if not rollup_fields.exists():
return
try:
parent_record = CustomRecord.objects.get(pk=parent_id)
except CustomRecord.DoesNotExist:
return
if parent_record.data is None:
parent_record.data = {}
modified = False
for rf in rollup_fields:
val = compute_rollup_value(parent_record, rf)
parent_record.data[rf.name] = val
modified = True
if modified:
parent_record.save(update_fields=['data'])
def compute_rollup_value(parent_instance, rollup_field_def):
"""
Computes aggregation for a given rollup field definition against parent instance.
rollup_field_def: CustomFieldDefinition with rollup attributes:
- rollup_summary_object (e.g. 'Opportunity' or 'invoice_item__c')
- rollup_type ('COUNT', 'SUM', 'MIN', 'MAX', 'AVG')
- rollup_field (e.g. 'amount')
- rollup_filter (dict or None)
"""
from crm_core.models import Account, Contact, Lead, Opportunity, Activity
from outreach.models import Campaign
model_map = {
'Account': Account,
'Contact': Contact,
'Lead': Lead,
'Opportunity': Opportunity,
'Activity': Activity,
'Campaign': Campaign,
}
child_entity = rollup_field_def.rollup_summary_object
rollup_type = (rollup_field_def.rollup_type or 'COUNT').upper()
target_field = rollup_field_def.rollup_field
filter_criteria = rollup_field_def.rollup_filter or {}
# Check standard child models
if child_entity in model_map:
child_model = model_map[child_entity]
parent_class_name = parent_instance.__class__.__name__
# Resolve foreign key lookup from child to parent
rel_info = STANDARD_REVERSE_RELATIONS.get(parent_class_name, {}).get(child_entity)
if rel_info:
filter_kwargs = {f"{rel_info['fk_field']}_id": parent_instance.id}
else:
filter_kwargs = {f"{parent_class_name.lower()}_id": parent_instance.id}
# Apply additional filter criteria if present
for k, v in filter_criteria.items():
filter_kwargs[k] = v
qs = child_model.objects.filter(**filter_kwargs)
if rollup_type == 'COUNT':
return qs.count()
elif rollup_type == 'SUM':
res = qs.aggregate(val=Sum(target_field))['val']
return float(res) if isinstance(res, (int, float, Decimal)) else 0.0
elif rollup_type == 'MIN':
res = qs.aggregate(val=Min(target_field))['val']
return float(res) if isinstance(res, (int, float, Decimal)) else (res or 0)
elif rollup_type == 'MAX':
res = qs.aggregate(val=Max(target_field))['val']
return float(res) if isinstance(res, (int, float, Decimal)) else (res or 0)
elif rollup_type == 'AVG':
res = qs.aggregate(val=Avg(target_field))['val']
return float(res) if isinstance(res, (int, float, Decimal)) else 0.0
return 0