openforce/crm_core/serializers.py

147 lines
6.2 KiB
Python

from rest_framework import serializers
from .models import Account, Contact, Lead, Opportunity, Activity
from custom_objects.schema_engine import validate_entity_custom_fields
class CustomFieldsValidationMixin:
entity_name = None
def validate_custom_fields(self, value):
if value:
validate_entity_custom_fields(self.entity_name, value, partial=self.partial)
return value
def validate(self, attrs):
attrs = super().validate(attrs)
custom_fields = attrs.get('custom_fields')
if custom_fields is not None:
validate_entity_custom_fields(self.entity_name, custom_fields, partial=self.partial)
return attrs
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 AccountSerializer(OwnerScopedRelationMixin, CustomFieldsValidationMixin, serializers.ModelSerializer):
entity_name = 'Account'
class Meta:
model = Account
fields = '__all__'
read_only_fields = ['id', 'owner', 'created_at', 'updated_at']
class ContactSerializer(OwnerScopedRelationMixin, CustomFieldsValidationMixin, serializers.ModelSerializer):
entity_name = 'Contact'
class Meta:
model = Contact
fields = '__all__'
read_only_fields = ['id', 'owner', 'created_at', 'updated_at']
class LeadSerializer(OwnerScopedRelationMixin, CustomFieldsValidationMixin, serializers.ModelSerializer):
entity_name = 'Lead'
class Meta:
model = Lead
fields = '__all__'
read_only_fields = [
'id', 'owner', 'is_converted', 'converted_date',
'converted_account', 'converted_contact',
'converted_opportunity', 'created_at', 'updated_at'
]
class OpportunitySerializer(OwnerScopedRelationMixin, CustomFieldsValidationMixin, serializers.ModelSerializer):
entity_name = 'Opportunity'
class Meta:
model = Opportunity
fields = '__all__'
read_only_fields = ['id', 'owner', 'expected_revenue', 'created_at', 'updated_at']
class ActivitySerializer(OwnerScopedRelationMixin, serializers.ModelSerializer):
ALLOWED_TARGET_MODELS = {
('crm_core', 'account'),
('crm_core', 'contact'),
('crm_core', 'lead'),
('crm_core', 'opportunity'),
('crm_core', 'activity'),
('custom_objects', 'customrecord'),
}
class Meta:
model = Activity
fields = '__all__'
read_only_fields = ['id', 'assigned_to', 'completed_at', 'created_at', 'updated_at']
def validate(self, attrs):
attrs = super().validate(attrs)
# For partial updates, check attrs first, then fall back to instance
content_type = attrs['content_type'] if 'content_type' in attrs else getattr(self.instance, 'content_type', None)
object_id = attrs['object_id'] if 'object_id' in attrs else getattr(self.instance, 'object_id', None)
# Disallow half-cleared or half-specified polymorphic relationship
if (content_type is not None and object_id is None) or (content_type is None and object_id is not None):
raise serializers.ValidationError({
'non_field_errors': ['Polymorphic parent requires both content_type and object_id to be set together, or both cleared.']
})
# If both are present, validate against the allowed model registry and actor-scoped queryset
if content_type and object_id:
target_key = (content_type.app_label, content_type.model)
if target_key not in self.ALLOWED_TARGET_MODELS:
raise serializers.ValidationError({
'content_type': f'Target model "{content_type.app_label}.{content_type.model}" is not allowed for Activity association.'
})
model_cls = content_type.model_class()
if model_cls is None:
raise serializers.ValidationError({'content_type': 'Invalid content type.'})
request = self.context.get('request')
user = getattr(request, 'user', None) if request else None
qs = model_cls.objects.all()
if user and user.is_authenticated and not (user.is_superuser or user.is_staff):
if hasattr(model_cls, 'owner'):
qs = qs.filter(owner=user)
elif hasattr(model_cls, 'created_by'):
qs = qs.filter(created_by=user)
elif hasattr(model_cls, 'assigned_to'):
qs = qs.filter(assigned_to=user)
else:
# Default-deny for models without tenant ownership fields
raise serializers.ValidationError({
'content_type': f'Target model "{content_type.app_label}.{content_type.model}" has no tenant ownership mapping.'
})
if not qs.filter(id=object_id).exists():
raise serializers.ValidationError({
'object_id': f'Invalid pk "{object_id}" - object does not exist or unauthorized.'
})
return attrs
class LeadConvertSerializer(serializers.Serializer):
create_opportunity = serializers.BooleanField(required=False, default=False)
account_name = serializers.CharField(required=False, allow_blank=True)
opportunity_name = serializers.CharField(required=False, allow_blank=True)
opportunity_amount = serializers.DecimalField(required=False, max_digits=15, decimal_places=2, allow_null=True)
opportunity_close_date = serializers.DateField(required=False, allow_null=True)