Fakultas Ilmu Komputer UI

serializers.py 4.83 KB
Newer Older
1
import datetime
2
from django.contrib.auth.models import Group
Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
3
4
from rest_framework import serializers, exceptions
from dj_rest_auth.serializers import LoginSerializer
5
from dj_rest_auth.registration.serializers import RegisterSerializer
Glenda Emanuella Sutanto's avatar
Glenda Emanuella Sutanto committed
6
7
from .models import CustomUser

8

9
class UserAuthSerializer(serializers.ModelSerializer):
Glenda Emanuella Sutanto's avatar
Glenda Emanuella Sutanto committed
10

Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
11
12
    def to_representation(self, instance):
        result = super().to_representation(instance)
13
14

        result['is_finished_onboarding'] = True
Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
15
16
        if instance.groups.exists():
            result['role'] = instance.groups.first().name
17
18
19
20
21
22
23
            if result['role'] == 'client':
                if hasattr(instance, 'diet_questionnaire'):
                    result['is_finished_onboarding'] = \
                        (len(instance.diet_questionnaire.finished_steps) == 6)
                else:
                    result['is_finished_onboarding'] = False

24
25
        if instance.is_staff:
            result['role'] = 'admin'
26

27
28
        result['transaction_status'] = None
        result['cart_id'] = None
29
        result['all_carts_are_expired'] = False
30

31
        if instance.cart.exists():
32
33
34
            result['transaction_status'] = instance.cart.last().transaction_status
            result['cart_id'] = instance.cart.last().id

35
36
            something_is_paid = False

37
38
39
40
            all_carts_are_expired = True
            for cart in instance.cart.all():
                if cart.program_end_date is None:
                    continue
41
                something_is_paid = True
42
43
44
45
                if cart.program_end_date >= datetime.date.today():
                    all_carts_are_expired = False
                    break

46
47
48
49
            if not something_is_paid:
                result['all_carts_are_expired'] = False
            else:
                result['all_carts_are_expired'] = all_carts_are_expired
50

51
52
53
54
55
56
57
58
        result['nutritionist'] = None

        if instance.nutritionist is not None:
            result['nutritionist'] = {
                'full_name_and_degree': instance.nutritionist.full_name_and_degree,
                'phone_number': instance.nutritionist.phone_number
            }

59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
        return result

    class Meta:
        model = CustomUser
        fields = ('id', 'name', 'email',)
        read_only_fields = ('id', 'email',)


class CustomUserDetailsSerializer(serializers.ModelSerializer):

    def to_representation(self, instance):
        result = super().to_representation(instance)
        if instance.groups.exists():
            result['role'] = instance.groups.first().name
        if instance.is_staff:
            result['role'] = 'admin'
Muzaki Azami's avatar
Muzaki Azami committed
75
76
77
78
        onboarding_status = UserAuthSerializer(instance).data
        if onboarding_status['is_finished_onboarding'] is True\
            and 'role' in onboarding_status:
            phone_number = instance.diet_questionnaire.whatsapp_no
Ami's avatar
Ami committed
79
            if (phone_number is None) or (phone_number == ""):
Muzaki Azami's avatar
Muzaki Azami committed
80
81
                phone_number = instance.diet_questionnaire.handphone_no
            result['phone_number'] = phone_number
Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
82
83
        return result

Glenda Emanuella Sutanto's avatar
Glenda Emanuella Sutanto committed
84
85
    class Meta:
        model = CustomUser
86
87
        fields = ('id', 'name', 'email','deadline')
        read_only_fields = ('id', 'email','deadline')
Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
88

89

Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
90
91
92
93
94
95
96
97
98
99
100
101
class CustomLoginSerializer(LoginSerializer):

    def validate_auth_user_status(self, user):
        request = self.context.get('request')
        if not request.data.get('role'):
            msg = 'Role is missing from the payload.'
            raise exceptions.ValidationError(msg)
        if not user.groups.filter(name=request.data.get('role')).exists():
            msg = 'Invalid role for the user.'
            raise exceptions.ValidationError(msg)

    def create(self, validated_data):
102
103
        pass    # Empty because the function is not needed
                # but Pylint demanded to implement it anyway
Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
104
105

    def update(self, instance, validated_data):
106
107
        pass    # Empty because the function is not needed
                # but Pylint demanded to implement it anyway
108
109
110
111
112
113
114
115
116
117
118
119
120
121


class CustomRegisterSerializer(RegisterSerializer):
    name = serializers.CharField()

    def get_cleaned_data(self):
        super().get_cleaned_data()
        return {
            'email': self.validated_data.get('email', ''),
            'password1': self.validated_data.get('password1', ''),
            'name': self.validated_data.get('name', '')
        }

    def create(self, validated_data):
122
123
        pass    # Empty because the function is not needed
                # but Pylint demanded to implement it anyway
124
125

    def update(self, instance, validated_data):
126
127
        pass    # Empty because the function is not needed
                # but Pylint demanded to implement it anyway
128
129
130
131
132
133
134
135

    def save(self, request):
        user = super().save(request)
        user.name = self.get_cleaned_data().get('name')
        user.save()
        client_role, _created = Group.objects.get_or_create(name='client')
        user.groups.add(client_role)
        return user