Blame view

src/core/pyros_django/api/views.py 9.54 KB
98621b46   Alexis Koralewski   add DRF, pyros ap...
1
2
3
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
4b904014   Alexis Koralewski   Add view to get s...
4
from rest_framework import viewsets, renderers
98621b46   Alexis Koralewski   add DRF, pyros ap...
5
from rest_framework.permissions import IsAuthenticated, AllowAny
4b904014   Alexis Koralewski   Add view to get s...
6
from rest_framework.decorators import api_view, permission_classes, action
98621b46   Alexis Koralewski   add DRF, pyros ap...
7
8
from django.core.validators import ValidationError
from src.core.pyros_django.user_manager import views as user_views
0d6aa42f   Alexis Koralewski   Add vuejs in agen...
9
10
from api.serializers import AgentSurveySerializer, AlbumSerializer, FullSequenceSerializer, PlanSerializer, SPPeriodSerializer, ScientificProgramSerializer, SequenceSerializer, UserSerializer
from common.models import PyrosUser, SP_Period, ScientificProgram, Sequence, Album, Plan, UserLevel, SP_Period_User, AgentSurvey
98621b46   Alexis Koralewski   add DRF, pyros ap...
11
from routine_manager.functions import check_sequence_file_validity
c2589779   Alexis Koralewski   Adding API views ...
12
from rest_framework.request import Request
4b904014   Alexis Koralewski   Add view to get s...
13
from django.db.models import Q
0ab234ad   Alexis Koralewski   Filter agent stat...
14
from datetime import datetime, timezone, timedelta
0318e3c9   Alexis Koralewski   Add tests for F05...
15
from src.pyros_logger import log
c2589779   Alexis Koralewski   Adding API views ...
16

98621b46   Alexis Koralewski   add DRF, pyros ap...
17
18
19
# Create your views here.


0318e3c9   Alexis Koralewski   Add tests for F05...
20
21
@api_view(["GET"])
def user_logout(request):
995a2ae6   Alexis Koralewski   adding scientific...
22
23
24
    """
    Log out user and delete authentification token
    """
98621b46   Alexis Koralewski   add DRF, pyros ap...
25

0318e3c9   Alexis Koralewski   Add tests for F05...
26
    request.user.auth_token.delete()
98621b46   Alexis Koralewski   add DRF, pyros ap...
27

0318e3c9   Alexis Koralewski   Add tests for F05...
28
    user_views.logout(request)
98621b46   Alexis Koralewski   add DRF, pyros ap...
29

0318e3c9   Alexis Koralewski   Add tests for F05...
30
    return Response('User Logged out successfully')
98621b46   Alexis Koralewski   add DRF, pyros ap...
31
32
33
34


class UserViewSet(viewsets.ModelViewSet):
    """
c2589779   Alexis Koralewski   Adding API views ...
35
    API endpoint that allows users to be viewed.
98621b46   Alexis Koralewski   add DRF, pyros ap...
36
37
38
39
    """
    queryset = PyrosUser.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer
    permission_classes = [IsAuthenticated]
42bf33a2   Alexis Koralewski   renaming configpy...
40
    http_method_names = ["get"]
98621b46   Alexis Koralewski   add DRF, pyros ap...
41

c2589779   Alexis Koralewski   Adding API views ...
42
43
44
45
46
47
48
    def list(self, request):
        serializer_context = {
            'request': request,
        }
        queryset = None
        current_user = self.request.user
        user = self.request.user
0318e3c9   Alexis Koralewski   Add tests for F05...
49
50
        user_role = str(UserLevel.objects.get(
            priority=user.get_priority()).name)
a61943b5   Alexis Koralewski   Reworking Unit-bo...
51
        if user_role in ("Unit-PI",  "Admin"):
c2589779   Alexis Koralewski   Adding API views ...
52
53
54
55
56
57
            queryset = PyrosUser.objects.all().order_by("-created")
        else:
            sp_of_current_user = user.get_scientific_program()
            pyros_users_with_roles = []
            for sp in sp_of_current_user:
                for sp_period in sp.SP_Periods.all():
0318e3c9   Alexis Koralewski   Add tests for F05...
58
59
60
61
62
                    for user in SP_Period_User.objects.filter(SP_Period=sp_period).exclude(user=current_user).values_list("user", flat=True):
                        pyros_users_with_roles.append(
                            PyrosUser.objects.get(id=user))
                    pyros_users_with_roles.append(
                        sp_period.scientific_program.sp_pi)
995a2ae6   Alexis Koralewski   adding scientific...
63
64
65
66
            # Include unit_pi and unit_board users
            unit_users = PyrosUser.objects.filter(
                user_level__name__in=("Unit-PI", "Unit-board")).distinct()
            queryset = pyros_users_with_roles + list(unit_users)
0318e3c9   Alexis Koralewski   Add tests for F05...
67
68
        serializer = UserSerializer(
            queryset, context=serializer_context, many=True)
c2589779   Alexis Koralewski   Adding API views ...
69
        return Response(serializer.data)
0318e3c9   Alexis Koralewski   Add tests for F05...
70
71


98621b46   Alexis Koralewski   add DRF, pyros ap...
72
73
class SequenceViewSet(viewsets.ModelViewSet):
    """
c2589779   Alexis Koralewski   Adding API views ...
74
    API endpoint that allows users to view their sequences.
98621b46   Alexis Koralewski   add DRF, pyros ap...
75
    """
c2589779   Alexis Koralewski   Adding API views ...
76
    queryset = Sequence.objects.all().order_by("-updated")
98621b46   Alexis Koralewski   add DRF, pyros ap...
77
78
    serializer_class = SequenceSerializer
    permission_classes = [IsAuthenticated]
42bf33a2   Alexis Koralewski   renaming configpy...
79
    http_method_names = ["get"]
0318e3c9   Alexis Koralewski   Add tests for F05...
80

98621b46   Alexis Koralewski   add DRF, pyros ap...
81
82
    def get_queryset(self):
        """
c2589779   Alexis Koralewski   Adding API views ...
83
84
85
86
        This view should return a list of all the sequences
        for the currently authenticated user.
        """
        user = self.request.user
0318e3c9   Alexis Koralewski   Add tests for F05...
87
88
        user_role = str(UserLevel.objects.get(
            priority=user.get_priority()).name)
a61943b5   Alexis Koralewski   Reworking Unit-bo...
89
        if user_role in ("Unit-PI",  "Admin"):
c2589779   Alexis Koralewski   Adding API views ...
90
91
92
93
94
            return Sequence.objects.all().order_by("-updated")
        else:
            return Sequence.objects.filter(pyros_user=user).order_by("-updated")


995a2ae6   Alexis Koralewski   adding scientific...
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
class ScientificProgramViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to view their scientific programs.
    """
    queryset = ScientificProgram.objects.all().order_by("-created")
    serializer_class = ScientificProgramSerializer
    permission_classes = [IsAuthenticated]
    http_method_names = ["get"]

    def get_queryset(self):
        """
        This view should return a list of all the sequences
        for the currently authenticated user.
        """
        user = self.request.user
        user_role = str(UserLevel.objects.get(
            priority=user.get_priority()).name)
a61943b5   Alexis Koralewski   Reworking Unit-bo...
112
        if user_role in ("Unit-PI",  "Admin"):
995a2ae6   Alexis Koralewski   adding scientific...
113
114
115
116
117
            return ScientificProgram.objects.all().order_by("-updated")
        else:
            return user.get_scientific_program().order_by("-updated")


33c8da07   Alexis Koralewski   Adding SP_Period ...
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
class SPPeriodViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to view their sp_periods
    """
    queryset = SP_Period.objects.all()
    serializer_class = SPPeriodSerializer

    permission_classes = [IsAuthenticated]
    http_method_names = ["get"]

    def get_queryset(self):
        """
        This view should return a list of all the sp_period
        for the currently authenticated user.
        """
        user = self.request.user
        user_role = str(UserLevel.objects.get(
            priority=user.get_priority()).name)
a61943b5   Alexis Koralewski   Reworking Unit-bo...
136
        if user_role in ("Unit-PI",  "Admin"):
33c8da07   Alexis Koralewski   Adding SP_Period ...
137
138
139
140
141
142
            return SP_Period.objects.all().order_by("-scientific_program")
        else:
            user_scientific_programs = user.get_scientific_program()
            return SP_Period.objects.filter(scientific_program__in=user_scientific_programs).order_by("-scientific_program")


c2589779   Alexis Koralewski   Adding API views ...
143
144
class FullSequenceViewSet(viewsets.ModelViewSet):
    """
995a2ae6   Alexis Koralewski   adding scientific...
145
    API endpoint that allows users to view their full sequences.
c2589779   Alexis Koralewski   Adding API views ...
146
147
148
149
150
    """
    queryset = Sequence.objects.all().order_by("-updated")
    serializer_class = FullSequenceSerializer
    permission_classes = [IsAuthenticated]
    http_method_names = ["get"]
0318e3c9   Alexis Koralewski   Add tests for F05...
151

c2589779   Alexis Koralewski   Adding API views ...
152
153
154
    def get_queryset(self):
        """
        This view should return a list of all the sequences
98621b46   Alexis Koralewski   add DRF, pyros ap...
155
156
157
        for the currently authenticated user.
        """
        user = self.request.user
0318e3c9   Alexis Koralewski   Add tests for F05...
158
159
        user_role = str(UserLevel.objects.get(
            priority=user.get_priority()).name)
a61943b5   Alexis Koralewski   Reworking Unit-bo...
160
        if user_role in ("Unit-PI",  "Admin"):
c2589779   Alexis Koralewski   Adding API views ...
161
162
163
            return Sequence.objects.all().order_by("-updated")
        else:
            return Sequence.objects.filter(pyros_user=user).order_by("-updated")
98621b46   Alexis Koralewski   add DRF, pyros ap...
164

4b904014   Alexis Koralewski   Add view to get s...
165
166
167
168
169
170
    @action(detail=False, methods=["get"])
    def get_sequences_for_period(self, request):
        """
        Return the list of sequences corresponding to the requested period 
        """
        params = request.query_params
0318e3c9   Alexis Koralewski   Add tests for F05...
171
172
173
174
175
        start_date = datetime.strptime(params.get("start_date"), "%d/%m/%Y")
        end_date = datetime.strptime(params.get("end_date"), "%d/%m/%Y")
        queryset = Sequence.objects.filter(
            Q(start_date__gte=start_date) | Q(start_date__lte=end_date))
        serializer = self.get_serializer(queryset, many=True)
4b904014   Alexis Koralewski   Add view to get s...
176
177
        response = Response(serializer.data)
        return response
c2589779   Alexis Koralewski   Adding API views ...
178

0318e3c9   Alexis Koralewski   Add tests for F05...
179

c2589779   Alexis Koralewski   Adding API views ...
180
181
class AlbumViewSet(viewsets.ModelViewSet):
    """
995a2ae6   Alexis Koralewski   adding scientific...
182
    API endpoint that allows users to view their Albums.
c2589779   Alexis Koralewski   Adding API views ...
183
184
185
186
187
    """
    queryset = Album.objects.all().order_by("-updated")
    serializer_class = AlbumSerializer
    permission_classes = [IsAuthenticated]
    http_method_names = ["get"]
0318e3c9   Alexis Koralewski   Add tests for F05...
188

c2589779   Alexis Koralewski   Adding API views ...
189
190
191
192
193
194
    def get_queryset(self):
        """
        This view should return a list of all the albums
        for the currently authenticated user.
        """
        user = self.request.user
0318e3c9   Alexis Koralewski   Add tests for F05...
195
196
        user_role = str(UserLevel.objects.get(
            priority=user.get_priority()).name)
a61943b5   Alexis Koralewski   Reworking Unit-bo...
197
        if user_role in ("Unit-PI",  "Admin"):
c2589779   Alexis Koralewski   Adding API views ...
198
199
            sequences = Sequence.objects.all().order_by("-updated")
        else:
0318e3c9   Alexis Koralewski   Add tests for F05...
200
201
            sequences = Sequence.objects.filter(
                pyros_user=user).order_by("-updated")
c2589779   Alexis Koralewski   Adding API views ...
202
203
204
205
206
207
208
209
210
211
212
        return Album.objects.filter(sequence__in=sequences).order_by("-updated")


class PlanViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to view their sequences.
    """
    queryset = Plan.objects.all().order_by("-updated")
    serializer_class = PlanSerializer
    permission_classes = [IsAuthenticated]
    http_method_names = ["get"]
0318e3c9   Alexis Koralewski   Add tests for F05...
213

c2589779   Alexis Koralewski   Adding API views ...
214
215
216
217
218
219
    def get_queryset(self):
        """
        This view should return a list of all the plans
        for the currently authenticated user.
        """
        user = self.request.user
0318e3c9   Alexis Koralewski   Add tests for F05...
220
221
        user_role = str(UserLevel.objects.get(
            priority=user.get_priority()).name)
a61943b5   Alexis Koralewski   Reworking Unit-bo...
222
        if user_role in ("Unit-PI",  "Admin"):
c2589779   Alexis Koralewski   Adding API views ...
223
224
            sequences = Sequence.objects.all().order_by("-updated")
        else:
0318e3c9   Alexis Koralewski   Add tests for F05...
225
226
227
228
            sequences = Sequence.objects.filter(
                pyros_user=user).order_by("-updated")
        albums = Album.objects.filter(
            sequence__in=sequences).order_by("-updated")
c2589779   Alexis Koralewski   Adding API views ...
229
        return Plan.objects.filter(album__in=albums).order_by("-updated")
0318e3c9   Alexis Koralewski   Add tests for F05...
230
231


98621b46   Alexis Koralewski   add DRF, pyros ap...
232
233
234
@api_view(["PUT"])
def submit_sequence_with_json(request):
    sequence_json = request.data
0318e3c9   Alexis Koralewski   Add tests for F05...
235
236
    response = check_sequence_file_validity(sequence_json, request)
    if response.get("succeed") == True:
0318e3c9   Alexis Koralewski   Add tests for F05...
237
238
239
        seq = Sequence.objects.get(id=response.get("sequence_id"))
        log.info(
            f"User {request.user} did action submit sequence {seq} for period {seq.period} ")
98621b46   Alexis Koralewski   add DRF, pyros ap...
240
    return Response(response)
0d6aa42f   Alexis Koralewski   Add vuejs in agen...
241
242
243
244
245
246
247
248
249
250



class AgentSurveyViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to view their sequences.
    """
    queryset = AgentSurvey.objects.all()
    serializer_class = AgentSurveySerializer
    permission_classes = [IsAuthenticated]
0228f249   Alexis Koralewski   Add link to agent...
251
    http_method_names = ["get"]
0ab234ad   Alexis Koralewski   Filter agent stat...
252
253
254
255
256
257
258
259
    lookup_field = "name"
    def get_queryset(self):
        agents = AgentSurvey.objects.all()
        datetime_now = datetime.utcnow()
        date_minus_two_days =  datetime_now - timedelta(days=2)
        date_minus_two_days = date_minus_two_days.replace(tzinfo=timezone.utc)
        agents = agents.exclude(updated__lt=date_minus_two_days)
        return agents