openforce/custom_objects/serializers.py
Goose 4def894801
Some checks failed
Build, Test, and Deploy / build-and-deploy (push) Failing after 29s
feat(formulas): implement safe AST formula execution engine and pre-save evaluation signals (Sprint 4.5A & 4.5B)
- Add zero-trust AST-based formula engine in custom_objects/formula_engine.py supporting arithmetic, logical, string, and date operations.
- Enforce strict AST whitelisting and attribute/function safety checks.
- Add cycle detection and topological sorting of formula dependencies.
- Extend CustomFieldDefinition model with formula_expression and formula_return_type fields.
- Wire pre-save signals to evaluate formula fields across standard models and CustomRecord.
- Expose AST syntax validator endpoint at POST /api/custom-fields/validate-formula/.
- Add comprehensive test suite in tests/test_formula_engine.py with 100% pass rate.
2026-09-27 07:17:04 +00:00

73 lines
3.3 KiB
Python

from rest_framework import serializers
from .models import CustomObjectDefinition, CustomFieldDefinition, CustomRecord
from .schema_engine import validate_record_data
class OwnerScopedRelationMixin:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
request = self.context.get('request')
if request and hasattr(request, 'user') and request.user.is_authenticated:
user = request.user
if not (user.is_superuser or user.is_staff):
for field_name, field in self.fields.items():
if isinstance(field, serializers.PrimaryKeyRelatedField):
model = getattr(field.queryset, 'model', None)
if model:
if hasattr(model, 'owner'):
field.queryset = field.queryset.filter(owner=user)
elif hasattr(model, 'created_by'):
field.queryset = field.queryset.filter(created_by=user)
class CustomFieldDefinitionSerializer(OwnerScopedRelationMixin, serializers.ModelSerializer):
class Meta:
model = CustomFieldDefinition
fields = '__all__'
read_only_fields = ['id', 'created_at', 'updated_at']
def validate(self, attrs):
field_type = attrs.get('field_type') or getattr(self.instance, 'field_type', None)
formula_expression = attrs.get('formula_expression') or getattr(self.instance, 'formula_expression', None)
if field_type == 'formula':
if not formula_expression:
raise serializers.ValidationError({'formula_expression': 'Formula fields require a formula_expression.'})
from custom_objects.formula_engine import validate_formula_syntax
try:
validate_formula_syntax(formula_expression)
except Exception as e:
raise serializers.ValidationError({'formula_expression': str(e)})
return super().validate(attrs)
class CustomObjectDefinitionSerializer(serializers.ModelSerializer):
fields = CustomFieldDefinitionSerializer(many=True, read_only=True)
class Meta:
model = CustomObjectDefinition
fields = '__all__'
read_only_fields = ['id', 'created_by', 'created_at', 'updated_at']
class CustomRecordSerializer(serializers.ModelSerializer):
class Meta:
model = CustomRecord
fields = '__all__'
read_only_fields = ['id', 'custom_object', 'owner', 'created_at', 'updated_at']
def validate(self, attrs):
view = self.context.get('view')
custom_object = attrs.get('custom_object') or getattr(self.instance, 'custom_object', None)
if not custom_object and view and hasattr(view, 'get_custom_object'):
custom_object = view.get_custom_object()
data = attrs.get('data') or getattr(self.instance, 'data', {})
if custom_object:
validate_record_data(custom_object, data, partial=self.partial)
return attrs
def update(self, instance, validated_data):
if self.partial and 'data' in validated_data:
merged_data = dict(instance.data)
merged_data.update(validated_data['data'])
validated_data['data'] = merged_data
return super().update(instance, validated_data)