125 lines
5.1 KiB
Python
125 lines
5.1 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):
|
|
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)
|
|
content_type = attrs.get('content_type', getattr(self.instance, 'content_type', None))
|
|
object_id = attrs.get('object_id', getattr(self.instance, 'object_id', None))
|
|
|
|
# If both are present, validate that the target object exists and is accessible
|
|
if content_type and object_id:
|
|
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)
|
|
|
|
if not qs.filter(id=object_id).exists():
|
|
raise serializers.ValidationError({
|
|
'object_id': f'Invalid pk "{object_id}" - object does not exist or unauthorized.'
|
|
})
|
|
elif (content_type and not object_id) or (object_id and not content_type):
|
|
# If one is provided without the other (or changed to null), ensure consistency
|
|
if content_type is None or object_id is None:
|
|
pass
|
|
|
|
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)
|