Files
zod-backend/junior/serializers.py

309 lines
13 KiB
Python

"""Serializer file for junior"""
"""Import Django 3rd party app"""
from rest_framework import serializers
from django.contrib.auth.models import User
from django.db import transaction
import random
from django.utils import timezone
from rest_framework_simplejwt.tokens import RefreshToken
"""Import django app"""
from account.utils import send_otp_email, generate_code
from junior.models import Junior, JuniorPoints
from guardian.tasks import generate_otp
from base.messages import ERROR_CODE, SUCCESS_CODE
from base.constants import PENDING, IN_PROGRESS, REJECTED, REQUESTED, COMPLETED, NUMBER, JUN, ZOD
from guardian.models import Guardian, JuniorTask
from account.models import UserEmailOtp
from junior.utils import junior_notification_email, junior_approval_mail
class ListCharField(serializers.ListField):
"""Serializer for Array field"""
child = serializers.CharField()
def to_representation(self, data):
"""to represent the data"""
return data
def to_internal_value(self, data):
"""internal value"""
if isinstance(data, list):
return data
raise serializers.ValidationError({"details":ERROR_CODE['2025']})
class CreateJuniorSerializer(serializers.ModelSerializer):
"""Create junior serializer"""
first_name = serializers.SerializerMethodField('get_first_name')
last_name = serializers.SerializerMethodField('get_last_name')
email = serializers.SerializerMethodField('get_email')
phone = serializers.CharField(max_length=20, required=False)
country_code = serializers.IntegerField(required=False)
dob = serializers.DateField(required=False)
referral_code = serializers.CharField(max_length=100, required=False)
guardian_code = ListCharField(required=False)
image = serializers.URLField(required=False)
class Meta(object):
"""Meta info"""
model = Junior
fields = ['id', 'first_name', 'last_name', 'email', 'phone', 'gender', 'country_code', 'dob', 'referral_code',
'passcode', 'is_complete_profile', 'guardian_code', 'referral_code_used',
'country_name', 'image', 'is_invited']
def get_first_name(self,obj):
"""first name of junior"""
return obj.auth.first_name
def get_last_name(self,obj):
"""last name of junior"""
return obj.auth.last_name
def get_email(self,obj):
"""email of junior"""
return obj.auth.email
def create(self, validated_data):
"""Create junior profile"""
guardian_code = validated_data.get('guardian_code',None)
user = User.objects.filter(username=self.context['user']).last()
if user:
"""Save first and last name of junior"""
if self.context.get('first_name') != '' and self.context.get('first_name') is not None:
user.first_name = self.context.get('first_name')
if self.context.get('last_name') != '' and self.context.get('last_name') is not None:
user.last_name = self.context.get('last_name')
user.save()
"""Create junior data"""
junior = Junior.objects.filter(auth=self.context['user']).last()
if junior:
"""update details according to the data get from request"""
junior.gender = validated_data.get('gender',junior.gender)
"""Update guardian code"""
junior.guardian_code = validated_data.get('guardian_code', junior.guardian_code)
"""condition for guardian code"""
if guardian_code:
junior.guardian_code = guardian_code
junior.dob = validated_data.get('dob',junior.dob)
junior.passcode = validated_data.get('passcode', junior.passcode)
junior.country_name = validated_data.get('country_name', junior.country_name)
"""Update country code and phone number"""
junior.phone = validated_data.get('phone', junior.phone)
junior.country_code = validated_data.get('country_code', junior.country_code)
junior.referral_code_used = validated_data.get('referral_code_used', junior.referral_code_used)
junior.image = validated_data.get('image', junior.image)
"""Complete profile of the junior if below all data are filled"""
complete_profile_field = all([junior.gender, junior.country_name, junior.image,
junior.dob, user.first_name])
junior.is_complete_profile = False
if complete_profile_field:
junior.is_complete_profile = True
junior.save()
return junior
def save(self, **kwargs):
"""Save the data into junior table"""
with transaction.atomic():
instance = super().save(**kwargs)
return instance
class JuniorDetailSerializer(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.auth.username
def get_first_name(self, obj):
"""user first name"""
return obj.auth.first_name
def get_last_name(self, obj):
"""user last name"""
return obj.auth.last_name
class Meta(object):
"""Meta info"""
model = Junior
fields = ['id', 'email', 'first_name', 'last_name', 'country_code', 'phone', 'gender', 'dob',
'guardian_code', 'is_invited', 'referral_code','is_active', 'is_complete_profile', 'created_at',
'image', 'updated_at']
class JuniorDetailListSerializer(serializers.ModelSerializer):
"""junior serializer"""
email = serializers.SerializerMethodField('get_auth')
first_name = serializers.SerializerMethodField('get_first_name')
last_name = serializers.SerializerMethodField('get_last_name')
assigned_task = serializers.SerializerMethodField('get_assigned_task')
points = serializers.SerializerMethodField('get_points')
in_progress_task = serializers.SerializerMethodField('get_in_progress_task')
completed_task = serializers.SerializerMethodField('get_completed_task')
requested_task = serializers.SerializerMethodField('get_requested_task')
rejected_task = serializers.SerializerMethodField('get_rejected_task')
pending_task = serializers.SerializerMethodField('get_pending_task')
position = serializers.SerializerMethodField('get_position')
def get_auth(self, obj):
return obj.auth.username
def get_first_name(self, obj):
return obj.auth.first_name
def get_last_name(self, obj):
return obj.auth.last_name
def get_assigned_task(self, obj):
data = JuniorTask.objects.filter(junior=obj).count()
return data
def get_position(self, obj):
data = JuniorPoints.objects.filter(junior=obj).last()
if data:
return data.position
return 99999
def get_points(self, obj):
data = sum(JuniorTask.objects.filter(junior=obj, task_status=COMPLETED).values_list('points', flat=True))
return data
def get_in_progress_task(self, obj):
data = JuniorTask.objects.filter(junior=obj, task_status=IN_PROGRESS).count()
return data
def get_completed_task(self, obj):
data = JuniorTask.objects.filter(junior=obj, task_status=COMPLETED).count()
return data
def get_requested_task(self, obj):
data = JuniorTask.objects.filter(junior=obj, task_status=REQUESTED).count()
return data
def get_rejected_task(self, obj):
data = JuniorTask.objects.filter(junior=obj, task_status=REJECTED).count()
return data
def get_pending_task(self, obj):
data = JuniorTask.objects.filter(junior=obj, task_status=PENDING).count()
return data
class Meta(object):
"""Meta info"""
model = Junior
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', 'assigned_task','points', 'pending_task', 'in_progress_task', 'completed_task',
'requested_task', 'rejected_task', 'position', 'is_invited']
class JuniorProfileSerializer(serializers.ModelSerializer):
"""junior serializer"""
email = serializers.SerializerMethodField('get_auth')
first_name = serializers.SerializerMethodField('get_first_name')
last_name = serializers.SerializerMethodField('get_last_name')
notification_count = serializers.SerializerMethodField('get_notification_count')
total_count = serializers.SerializerMethodField('get_total_count')
complete_field_count = serializers.SerializerMethodField('get_complete_field_count')
def get_auth(self, obj):
"""user email address"""
return obj.auth.username
def get_first_name(self, obj):
"""user first name"""
return obj.auth.first_name
def get_last_name(self, obj):
"""user last name"""
return obj.auth.last_name
def get_notification_count(self, obj):
"""total notification count"""
return 0
def get_total_count(self, obj):
"""total fields count"""
return NUMBER['five']
def get_complete_field_count(self, obj):
"""total filled fields count"""
field_list = [obj.auth.first_name, obj.country_name,
obj.gender, obj.dob, obj.image]
complete_field = [data for data in field_list if data is not None and data != '']
return len(complete_field)
class Meta(object):
"""Meta info"""
model = Junior
fields = ['id', 'email', 'first_name', 'last_name', 'country_name', 'country_code', 'phone', 'gender', 'dob',
'guardian_code', 'referral_code','is_active', 'is_complete_profile', 'created_at', 'image',
'updated_at', 'notification_count', 'total_count', 'complete_field_count', 'signup_method',
'is_invited', 'passcode']
class AddJuniorSerializer(serializers.ModelSerializer):
"""Add junior serializer"""
auth_token = serializers.SerializerMethodField('get_auth_token')
def get_auth_token(self, obj):
"""auth token"""
refresh = RefreshToken.for_user(obj)
access_token = str(refresh.access_token)
return access_token
class Meta(object):
"""Meta info"""
model = Junior
fields = ['id', 'gender','dob', 'relationship', 'auth_token', 'is_invited']
def create(self, validated_data):
""" create junior"""
with transaction.atomic():
email = self.context['email']
guardian = self.context['user']
full_name = self.context['first_name'] + ' ' + self.context['last_name']
guardian_data = Guardian.objects.filter(user__username=guardian).last()
user_data = User.objects.create(username=email, email=email,
first_name=self.context['first_name'],
last_name=self.context['last_name'])
password = User.objects.make_random_password()
user_data.set_password(password)
user_data.save()
junior_data = Junior.objects.create(auth=user_data, gender=validated_data.get('gender'),
dob=validated_data.get('dob'), is_invited=True,
relationship=validated_data.get('relationship'),
junior_code=generate_code(JUN, user_data.id),
referral_code=generate_code(ZOD, user_data.id),
referral_code_used=guardian_data.referral_code,
is_password_set=False, is_verified=True)
"""Generate otp"""
otp_value = generate_otp()
expiry_time = timezone.now() + timezone.timedelta(days=1)
UserEmailOtp.objects.create(email=email, otp=otp_value,
user_type='1', expired_at=expiry_time, is_verified=True)
"""Send email to the register user"""
send_otp_email(email, otp_value)
"""Notification email"""
junior_notification_email(email, full_name, email, password)
junior_approval_mail(guardian, full_name)
return junior_data
class RemoveJuniorSerializer(serializers.ModelSerializer):
"""User Update Serializer"""
class Meta(object):
"""Meta class"""
model = Junior
fields = ('id', 'is_invited')
def update(self, instance, validated_data):
if instance:
instance.is_invited = False
instance.guardian_code = '{}'
instance.save()
return instance