"""Serializer of Guardian""" """Third party Django app""" import logging import random from rest_framework import serializers from rest_framework_simplejwt.tokens import RefreshToken from django.db import transaction from django.contrib.auth.models import User """Import Django app""" from .models import Guardian, JuniorTask from account.models import UserProfile, UserEmailOtp from account.serializers import JuniorSerializer from junior.serializers import JuniorDetailSerializer from base.messages import ERROR_CODE, SUCCESS_CODE from .utils import upload_image_to_alibaba from junior.models import Junior, JuniorPoints class UserSerializer(serializers.ModelSerializer): """User serializer""" auth_token = serializers.SerializerMethodField('get_auth_token') class Meta(object): """Meta info""" model = User fields = ['email', 'password', 'auth_token'] def get_auth_token(self, obj): """generate auth token""" refresh = RefreshToken.for_user(obj) access_token = str(refresh.access_token) return access_token def create(self, validated_data): """fetch data""" email = validated_data.get('email') user_type = self.context password = validated_data.get('password') try: """Create user profile""" user = User.objects.create_user(username=email, email=email, password=password) UserProfile.objects.create(user=user, user_type=user_type) if user_type == '1': Junior.objects.create(auth=user, junior_code=''.join([str(random.randrange(9)) for _ in range(6)]), referral_code=''.join([str(random.randrange(9)) for _ in range(6)])) if user_type == '2': Guardian.objects.create(user=user, guardian_code=''.join([str(random.randrange(9)) for _ in range(6)]), referral_code=''.join([str(random.randrange(9)) for _ in range(6)])) return user except Exception as e: """Error handling""" logging.error(e) otp = UserEmailOtp.objects.filter(email=email).last() otp_verified = False if otp and otp.is_verified: otp_verified = True raise serializers.ValidationError({"details":ERROR_CODE['2021'], "otp_verified":bool(otp_verified), "code": 400, "status":"failed", }) class CreateGuardianSerializer(serializers.ModelSerializer): """Create guardian serializer""" """Basic info""" first_name = serializers.SerializerMethodField('get_first_name') last_name = serializers.SerializerMethodField('get_last_name') email = serializers.SerializerMethodField('get_email') """Contact details""" phone = serializers.CharField(max_length=20, required=False) country_code = serializers.IntegerField(required=False) family_name = serializers.CharField(max_length=100, required=False) dob = serializers.DateField(required=False) referral_code = serializers.CharField(max_length=100, required=False) image = serializers.ImageField(required=False) class Meta(object): """Meta info""" model = Guardian fields = ['first_name', 'last_name', 'email', 'phone', 'family_name', 'gender', 'country_code', 'dob', 'referral_code', 'passcode', 'is_complete_profile', 'referral_code_used', 'country_name', 'image'] def get_first_name(self,obj): """first name of guardian""" return obj.user.first_name def get_last_name(self,obj): """last name of guardian""" return obj.user.last_name def get_email(self,obj): """emailof guardian""" return obj.user.email def create(self, validated_data): """Create guardian profile""" user = User.objects.filter(username=self.context['user']).last() if user: """Save first and last name of guardian""" if self.context.get('first_name') != '' and self.context.get('last_name') != '': user.first_name = self.context.get('first_name', user.first_name) user.last_name = self.context.get('last_name', user.last_name) user.save() """Create guardian data""" guardian, created = Guardian.objects.get_or_create(user=self.context['user']) if created: """Create referral code and guardian code""" guardian.referral_code = ''.join([str(random.randrange(9)) for _ in range(4)]) guardian.guardian_code = ''.join([str(random.randrange(9)) for _ in range(4)]) if guardian: """update details according to the data get from request""" guardian.gender = validated_data.get('gender',guardian.gender) guardian.family_name = validated_data.get('family_name', guardian.family_name) guardian.dob = validated_data.get('dob',guardian.dob) """Update country code and phone number""" guardian.phone = validated_data.get('phone', guardian.phone) guardian.country_code = validated_data.get('country_code', guardian.country_code) guardian.passcode = validated_data.get('passcode', guardian.passcode) guardian.country_name = validated_data.get('country_name', guardian.country_name) guardian.referral_code_used = validated_data.get('referral_code_used', guardian.referral_code_used) image = validated_data.pop('image', None) if image: filename = f"images/{image.name}" image_url = upload_image_to_alibaba(image, filename) guardian.image = image_url """Complete profile of the junior if below all data are filled""" complete_profile_field = all([guardian.phone, guardian.gender, guardian.country_name, guardian.dob, guardian.country_code, user.first_name, user.last_name, user.email, guardian.image]) guardian.is_complete_profile = False if complete_profile_field: guardian.is_complete_profile = True guardian.save() return guardian def save(self, **kwargs): """Save the data into junior table""" with transaction.atomic(): instance = super().save(**kwargs) return instance class TaskSerializer(serializers.ModelSerializer): """Task serializer""" class Meta(object): """Meta info""" model = JuniorTask fields = ['task_name','task_description','points', 'due_date', 'junior', 'default_image'] def create(self, validated_data): """create default task image data""" validated_data['guardian'] = Guardian.objects.filter(user=self.context['user']).last() images = self.context['image'] validated_data['default_image'] = images instance = JuniorTask.objects.create(**validated_data) return instance class GuardianDetailSerializer(serializers.ModelSerializer): """junior serializer""" email = serializers.SerializerMethodField('get_auth') first_name = serializers.SerializerMethodField('get_first_name') last_name = serializers.SerializerMethodField('get_last_name') def get_auth(self, obj): """user email address""" return obj.user.username def get_first_name(self, obj): """user first name""" return obj.user.first_name def get_last_name(self, obj): """user last name""" return obj.user.last_name class Meta(object): """Meta info""" model = Guardian fields = ['id', 'email', 'first_name', 'last_name', 'country_code', 'phone', 'gender', 'dob', 'guardian_code', 'referral_code','is_active', 'is_complete_profile', 'created_at', 'image', 'updated_at'] class TaskDetailsSerializer(serializers.ModelSerializer): junior = JuniorDetailSerializer() class Meta(object): """Meta info""" model = JuniorTask fields = ['id', 'guardian', 'task_name', 'task_description', 'points', 'due_date','default_image', 'image', 'junior', 'task_status', 'is_active', 'created_at','updated_at'] class TopJuniorSerializer(serializers.ModelSerializer): """Top junior serializer""" junior = JuniorDetailSerializer() position = serializers.IntegerField() class Meta: """Meta info""" model = JuniorPoints fields = ['id', 'junior', 'total_task_points', 'position', 'created_at', 'updated_at'] def to_representation(self, instance): """Convert instance to representation""" representation = super().to_representation(instance) representation['position'] = instance.position return representation class GuardianProfileSerializer(serializers.ModelSerializer): """junior serializer""" email = serializers.SerializerMethodField('get_auth') first_name = serializers.SerializerMethodField('get_first_name') last_name = serializers.SerializerMethodField('get_last_name') total_count = serializers.SerializerMethodField('get_total_count') complete_field_count = serializers.SerializerMethodField('get_complete_field_count') notification_count = serializers.SerializerMethodField('get_notification_count') def get_auth(self, obj): """user email address""" return obj.user.username def get_first_name(self, obj): """user first name""" return obj.user.first_name def get_last_name(self, obj): """user last name""" return obj.user.last_name def get_total_count(self, obj): """total fields count""" return 9 def get_complete_field_count(self, obj): """total filled fields count""" total_field_list = [obj.user.first_name, obj.user.last_name, obj.user.email, obj.country_name, obj.country_code, obj.phone, obj.gender, obj.dob, obj.image] total_complete_field = [data for data in total_field_list if data != '' and data is not None] return len(total_complete_field) def get_notification_count(self, obj): """total notification count""" return 0 class Meta(object): """Meta info""" model = Guardian fields = ['id', 'email', 'first_name', 'last_name', 'country_name','country_code', 'phone', 'gender', 'dob', 'guardian_code', 'notification_count', 'total_count', 'complete_field_count', 'referral_code', 'is_active', 'is_complete_profile', 'created_at', 'image', 'updated_at']