Fakultas Ilmu Komputer UI

vacancies.py 26 KB
Newer Older
1
from django.utils import timezone
2
from django.db.models import Q
3
from rest_framework import viewsets, status
4
from rest_framework.decorators import detail_route
5
from rest_framework.exceptions import ValidationError
6
from rest_framework.generics import get_object_or_404
Zamil Majdy's avatar
Zamil Majdy committed
7
from rest_framework.pagination import PageNumberPagination
8
from rest_framework.permissions import IsAuthenticated
9
from rest_framework.response import Response
Zamil Majdy's avatar
Zamil Majdy committed
10

11
from core.lib.mixins import MultiSerializerViewSetMixin
Zamil Majdy's avatar
Zamil Majdy committed
12
from core.lib.permissions import IsAdminOrStudent, IsAdminOrCompany, IsAdminOrVacancyOwner, AsAdminOrSupervisor, \
13
    VacancyApprovalPermission, IsAdminOrVacancyOwnerOrAuthenticatedReadOnly
14
from core.models import Student, Company
15
from core.models.vacancies import Vacancy, Application, ReasonRejected
Refo Ilmiya Akbar's avatar
Refo Ilmiya Akbar committed
16
from core.serializers.vacancies import VacancySerializer, ApplicationSerializer, ApplicationStatusSerializer, \
17
    VacancyVerifiedSerializer, SupervisorStudentApplicationSerializer, \
18
    VacancyMilestoneSerializer
Zamil Majdy's avatar
Zamil Majdy committed
19
from core.views.accounts import StudentViewSet
20

21
from datetime import datetime, time
22
from rest_framework import serializers
23

24
25
26

def date_validator(open_time, close_time):
    if open_time < str(datetime.today()):
Refo Ilmiya Akbar's avatar
Refo Ilmiya Akbar committed
27
28
        return {'is_valid': False, 'error': 'Waktu buka lowongan harus lebih dari hari ini!',
                'status': status.HTTP_400_BAD_REQUEST}
29
    elif close_time < open_time:
Refo Ilmiya Akbar's avatar
Refo Ilmiya Akbar committed
30
31
        return {'is_valid': False, 'error': 'Waktu tutup lowongan harus lebih dari waktu buka lowongan!',
                'status': status.HTTP_400_BAD_REQUEST}
32
    elif close_time == open_time:
33
34
        return {'is_valid': False, 'error': 'Waktu tutup dan buka lowongan tidak boleh sama!',
                'status': status.HTTP_400_BAD_REQUEST}
35
    else:
Refo Ilmiya Akbar's avatar
Refo Ilmiya Akbar committed
36
        return {'is_valid': True, 'error': '', 'status': status.HTTP_200_OK}
37
38


39
class VacancyViewSet(MultiSerializerViewSetMixin, viewsets.ModelViewSet):
40
    queryset = Vacancy.objects.all()
41
    serializer_class = VacancySerializer
42
    permission_classes = [IsAdminOrCompany]
43
    pagination_class = PageNumberPagination
44

45
    def get_permissions(self):
46
        if self.action in ["retrieve", "list"]:
47
48
49
            return [IsAuthenticated()]
        return super(VacancyViewSet, self).get_permissions()

50
    def list(self, request, *args, **kwargs):
51
        search = request.query_params['search'] if 'search' in request.query_params else None
52
        verified = request.query_params['verified'] if 'verified' in request.query_params else "True"
53
54
55
        order_by = request.GET.get('sort', None)
        order = request.GET.get('order', 'ascending')

56
57
58
59
        opened_only = str(request.query_params['opened_only']) \
            if 'opened_only' in request.query_params else "False"
        companies = [int(x) for x in request.query_params.getlist('company', [])]

60
61
62
63
        if search is not None:
            vacancies = Vacancy.objects.filter(Q(name__icontains=search) | Q(company__user__username__icontains=search))
        else:
            vacancies = Vacancy.objects.all()
64

65
66
67
68
        # Filter vacancies here
        vacancies = self.verifiedFilter(vacancies, verified)
        vacancies = self.openedJobFilter(vacancies, opened_only)
        vacancies = self.companyFilter(vacancies, companies)
69
        vacancies = self.sort(order_by, vacancies, order)
70

71
        page = self.paginate_queryset(vacancies)
root's avatar
root committed
72
73
        print(vacancies)
        print(request)
74
75
        if page is not None:
            return self.get_paginated_response(VacancySerializer(page, many=True, context={'request': request}).data)
76
        vacancies = Vacancy.objects.all()
77
78
        return Response(VacancySerializer(vacancies, many=True, context={'request': request}).data)

79
80
81
82
83
84
    def verifiedFilter(self, vacancies, flag):
        if flag.lower() in ("yes", "true", "t", "1"):
            vacancies = vacancies.filter(verified=True)
        if flag.lower() in {"no", "false", "f", "0"}:
            vacancies = vacancies.filter(verified=False)
        return vacancies
Refo Ilmiya Akbar's avatar
Refo Ilmiya Akbar committed
85

86
87
88
89
90
91
92
93
94
95
    def openedJobFilter(self, vacancies, flag):
        if flag.lower() in ("yes", "true", "t", "1"):
            today = datetime.combine(datetime.now().date(), time())
            vacancies = vacancies.filter(close_time__gte=today)
        return vacancies

    def companyFilter(self, vacancies, companies):
        if len(companies) > 0:
            vacancies = vacancies.filter(company__id__in=companies)
        return vacancies
96

97
    def sort(self, order_by, vacancies, order):
98
99
100
101
102
        if (order_by is not None) and (order_by in ['name', 'salary']) and (order in ['ascending', 'descending']):
            order_query = ""
            if order == 'descending':
                order_query = "-"
            return vacancies.order_by('{}{}'.format(order_query, order_by))
103
        return vacancies
104

105
106
107
    def name_position_validator(self, names):
        for name in names.split(" "):
            if not name.isalpha():
108
                raise ValidationError("Name must alphabets only")
109
110
        return name

111
112
    def salary_validator(self, salary):
        if not isinstance(salary, int):
113
            raise ValidationError("Salary must number only")
114
115
116

    def amount_validator(self, amount):
        if not isinstance(amount, int):
117
            raise ValidationError("Amount must number only")
118

119
120
121
122
123
    def responsibilities_validator(self, responsibilities):
        if not isinstance(responsibilities, basestring):
            raise ValidationError("Responsibilities must be string")

    def recruiter_activity_validator(self, recruiter_activity):
Refo Ilmiya Akbar's avatar
Refo Ilmiya Akbar committed
124
        enum_recruiter_activity = ['Selalu', 'Sering', 'Kadang', 'Jarang', 'Tidak Pernah']
125
126
        if (not isinstance(recruiter_activity, basestring)) or (recruiter_activity not in enum_recruiter_activity):
            raise ValidationError('Tingkat Respons Perekrut harus salah '
Refo Ilmiya Akbar's avatar
Refo Ilmiya Akbar committed
127
                                              'satu dari Selalu, Sering, Kadang, '
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
                                              'Jarang, dan Tidak Pernah!')

    def date_range_validator(self, open_time, close_time):
        validity = date_validator(open_time, close_time)
        if not validity['is_valid']:
            raise ValidationError(validity['error'])

    def __get_company(self, company_id):
        company_set = Company.objects.filter(id=company_id)
        if len(company_set) == 0:
            raise ValidationError('No company exists with that ID')
        return company_set[0]

    def __parse_vacancy_data(self, raw_data):
        data = {
            "open_time": raw_data['open_time'],
            "close_time": raw_data['close_time'],
            "name": raw_data['name'],
            "salary": raw_data.get('salary', 0),
            "description": raw_data['description'],
            "working_period": raw_data['working_period'],
            "max_accepted_applicants": raw_data['max_accepted_applicants']
        }
        if 'benefits' in raw_data:
            data['benefits'] = raw_data['benefits']
        if 'amount' in raw_data:
            data['amount'] = raw_data['amount']
        if 'responsibilities' in raw_data:
            data['responsibilities'] = raw_data['responsibilities']
        if 'recruiter_activity' in raw_data:
            data['recruiter_activity'] = raw_data['recruiter_activity']
        return data

    def __validate_vacancy_data(self, data):
        self.date_range_validator(data['open_time'], data['close_time'])
        self.name_position_validator(data['name'])
        self.salary_validator(data['salary'])
        if data.get('amount'):
            self.amount_validator(data['amount'])
        if data.get('responsibilities'):
            self.responsibilities_validator(data['responsibilities'])
        if data.get('recruiter_activity'):
            self.recruiter_activity_validator(data['recruiter_activity'])
Refo Ilmiya Akbar's avatar
Refo Ilmiya Akbar committed
171

172
173
174
175
176
177
178
179
180
181
182
183
    def create(self, request):
        print("[LOG] data: " + str(request.data))
        try:
            data = self.__parse_vacancy_data(request.data)
            data['company'] = self.__get_company(request.data['company'])
            data['tag'] = request.data.get('tag', '')
            self.__validate_vacancy_data(data)
            vacancy = Vacancy(**data)
            vacancy.save()
        except ValidationError as e:
            print("[LOG] error: " + str(e))
            return Response({"error": str(e.detail[0])}, status=status.HTTP_400_BAD_REQUEST)
Yusuf Sholeh's avatar
Yusuf Sholeh committed
184
185
186
        except ValueError as e:
            print("[LOG] error: " + str(e))
            return Response({"error": str(e)}, status=status.HTTP_400_BAD_REQUEST)
187
188
189
        return Response(status=status.HTTP_200_OK)

    def partial_update(self, request, pk):
190
191
192
193
194
195
196
197
198
199
200
        print("[LOG] data: " + str(request.data))
        try:
            data = self.__parse_vacancy_data(request.data)
            self.__validate_vacancy_data(data)
            vacancy = Vacancy.objects.get(pk=pk)
            for (key, value) in data.items():
                setattr(vacancy, key, value)
            vacancy.save()
        except ValidationError as e:
            print("[LOG] error: " + str(e))
            return Response({"error": str(e.detail[0])}, status=status.HTTP_400_BAD_REQUEST)
201
202
        return Response(status=status.HTTP_200_OK)

203
204
205
206
207
208
209
    @detail_route(permission_classes=[IsAdminOrCompany])
    def count(self, request, pk=None):
        vacancy = self.get_object()
        count = Application.objects.filter(vacancy=vacancy).count()
        count_new = Application.objects.filter(vacancy=vacancy, status=Application.NEW).count()
        return Response({"count": count, "count_new": count_new}, status=status.HTTP_200_OK)

Zamil Majdy's avatar
Zamil Majdy committed
210
211
    @detail_route(methods=['patch'], permission_classes=[VacancyApprovalPermission],
                  serializer_class=VacancyVerifiedSerializer)
212
213
214
215
216
217
    def verify(self, request, pk=None):
        vacancy = self.get_object()
        serializer = self.get_serializer_class()(vacancy, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
Zamil Majdy's avatar
Zamil Majdy committed
218
        return Response({"error": "bad request"}, status=status.HTTP_400_BAD_REQUEST)
219

220

Zamil Majdy's avatar
Zamil Majdy committed
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
class ApplicationViewSet(MultiSerializerViewSetMixin, viewsets.GenericViewSet):
    queryset = Application.objects.all()
    serializer_class = ApplicationSerializer
    serializer_action_classes = {
        'update': ApplicationStatusSerializer,
        'partial_update': ApplicationStatusSerializer,
        'list': SupervisorStudentApplicationSerializer
    }
    permission_classes = [IsAdminOrVacancyOwner]
    pagination_class = PageNumberPagination

    def list(self, request):
        applications = Application.objects.order_by('student')
        page = self.paginate_queryset(applications)
        serializer = self.get_serializer_class()
        if page is not None:
            return self.get_paginated_response(
                serializer(applications, many=True, context={'request': request}).data)
        return Response(serializer(applications, many=True, context={'request': request}).data)

241
242
243
244
245
    @detail_route(methods=['get'], permission_classes=[IsAdminOrStudent])
    def count(self, request, pk=None):
        count = Application.objects.filter(vacancy_id=pk).count()
        return Response({"count": count}, status=status.HTTP_200_OK)

Zamil Majdy's avatar
Zamil Majdy committed
246
247
248
249
250
    def partial_update(self, request, pk=None):
        application = self.get_object()
        serializer = self.get_serializer_class()(application, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
251
252
            if request.data['status'] == 3:
                ReasonRejected.objects.create(application=application, reason=request.data['reason'])
Zamil Majdy's avatar
Zamil Majdy committed
253
254
255
256
257
258
259
            return Response(serializer.data, status=status.HTTP_202_ACCEPTED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    @detail_route(methods=['get'], permission_classes=[IsAdminOrVacancyOwner])
    def transcript(self, request, pk):
        """
Zamil Majdy's avatar
Zamil Majdy committed
260
        Get student's academic transcript on application {application_id}
Zamil Majdy's avatar
Zamil Majdy committed
261
262
263
        ---
        """
        application = self.get_object()
Zamil Majdy's avatar
Zamil Majdy committed
264
        return StudentViewSet.transcript(StudentViewSet(), request, application.student.pk)
Zamil Majdy's avatar
Zamil Majdy committed
265
266
267
268
269
270
271
272

    def get_permissions(self):
        if self.action == "list":
            return [AsAdminOrSupervisor()]
        return super(ApplicationViewSet, self).get_permissions()


class StudentApplicationViewSet(viewsets.GenericViewSet):
273
    serializer_class = ApplicationSerializer
274
    permission_classes = [IsAdminOrStudent]
275
    pagination_class = PageNumberPagination
276

277
    def list(self, request, student_id):
278
        """
279
        Get list of a student {student_id}'s applied vacancies
280
281
        ---
        """
282
        student = get_object_or_404(Student.objects.all(), pk=student_id)
283
        vacancy_ids = Application.objects.filter(student=student).values('vacancy')
284
285
        search = request.query_params['search'] if 'search' in request.query_params else None
        if search is not None:
Refo Ilmiya Akbar's avatar
Refo Ilmiya Akbar committed
286
287
            vacancies = Vacancy.objects.filter(
                Q(id__in=vacancy_ids) & (Q(name__icontains=search) | Q(company__user__username__icontains=search)))
288
289
        else:
            vacancies = Vacancy.objects.filter(id__in=vacancy_ids)
290
291
292
293
        page = self.paginate_queryset(vacancies)
        if page is not None:
            return self.get_paginated_response(VacancySerializer(page, many=True, context={'request': request}).data)
        return Response(VacancySerializer(vacancies, many=True, context={'request': request}).data)
294
295

    def create(self, request, student_id):
296
297
298
299
300
        """
        Create a new application for student {student_id}
        ---
        parameters:
            - name: body
301
              description: JSON object containing an integer 'vacancy_id' and a string 'cover_letter'
302
303
304
305
              required: true
              type: string
              paramType: body
        """
306
307
        cover_letter = request.data.get('cover_letter')
        vacancy = get_object_or_404(Vacancy.objects.all(), pk=request.data.get('vacancy_id'))
308
309
        if vacancy.close_time < timezone.now():
            return Response({"error": "vacancy is closed"}, \
Refo Ilmiya Akbar's avatar
Refo Ilmiya Akbar committed
310
                            status=status.HTTP_400_BAD_REQUEST)
311
        student = get_object_or_404(Student.objects.all(), pk=student_id)
312
313
        if Application.objects.filter(vacancy=vacancy, student=student).exists():
            raise ValidationError("You have already applied for the vacancy")
314
315
316
        application = Application(vacancy=vacancy, student=student, cover_letter=cover_letter)
        application.save()
        return Response(ApplicationSerializer(application, context={'request': request}).data)
317
318

    def destroy(self, request, student_id, pk):
319
320
321
322
        """
        Remove a application {id} for student {student_id}
        ---
        """
323
324
        vacancy = get_object_or_404(Vacancy.objects.all(), pk=pk)
        student = get_object_or_404(Student.objects.all(), pk=student_id)
325
        application = get_object_or_404(Application.objects.all(), student=student, vacancy=vacancy)
326
        application.delete()
327
        return Response(ApplicationSerializer(application, context={'request': request}).data)
328

329

330
331
332
class StatusError(Exception):
    pass

333

334
335
class UnauthorizeError(Exception):
    pass
336

337

338
339
class CompanyApplicationViewSet(viewsets.GenericViewSet):
    queryset = Application.objects.all()
340
    permission_classes = [IsAdminOrCompany]
341
    pagination_class = PageNumberPagination
342
343
344
345
346
347

    def list(self, request, company_id):
        """
        Get list of company {company_id}'s applications
        ---
        """
348
349
350
351
        try:
            company = self.__get_company_list_by_company_id(request, company_id)
            vacancies = self.__get_vacancy_list_filter_by_company(company)
            applications = self.__get_application_list_filter_by_vacancies(vacancies)
352
353
            applications = self.__filter_application_list_by_status(request, applications)
            return self.__get_paginated_application_list(request, applications)
354
        except UnauthorizeError:
355
            return Response({"error": "forbidden"}, status=status.HTTP_403_FORBIDDEN)
356
357
        except (StatusError, ValueError):
            return Response({"error": "status must be an integer between 0 and 4"}, \
358
                            status=status.HTTP_400_BAD_REQUEST)
359

360
361
    @detail_route(methods=["get"])
    def by_vacancy(self, request, company_id, pk=None):
Zamil Majdy's avatar
Zamil Majdy committed
362
363
364
365
        """
        Get list of company {company_id}'s applications by vacancy {id}
        ---
        """
366
367
368
369
370
        try:
            if pk is None:
                return list(self, request, company_id)
            company = self.__get_company_list_by_company_id(request, company_id)
            vacancy = self.__get_vacancy_list_by_pk(pk, company)
371
372
373
            applications = self.__get_application_by_vacancy(vacancy)
            applications = self.__filter_application_list_by_status(request, applications)
            return self.__get_paginated_application_list(request, applications)
374
375
376
377
        except UnauthorizeError:
            return Response({"error": "forbidden"}, status=status.HTTP_403_FORBIDDEN)
        except (StatusError, ValueError):
            return Response({"error": "status must be an integer between 0 and 4"}, \
378
                            status=status.HTTP_400_BAD_REQUEST)
379
380
381
382
383

    def __get_company_list_by_company_id(self, request, company_id):
        company = get_object_or_404(Company.objects.all().order_by('-updated'), pk=company_id)
        if not self.__validating_user(request, company):
            raise UnauthorizeError
Refo Ilmiya Akbar's avatar
Refo Ilmiya Akbar committed
384
        return company
385
386
387

    def __validating_user(self, request, company):
        return request.user.is_superuser or request.user == company.user
Refo Ilmiya Akbar's avatar
Refo Ilmiya Akbar committed
388

389
    def __get_vacancy_list_by_pk(self, pk, company):
390
        vacancy = get_object_or_404(Vacancy.objects.all(), pk=pk)
391
392
393
394
395
396
397
398
399
        if not self.__validating_vacancy(vacancy, company):
            raise UnauthorizeError
        return vacancy

    def __validating_vacancy(self, vacancy, company):
        return vacancy.company == company

    def __get_vacancy_list_filter_by_company(self, company):
        return Vacancy.objects.filter(company=company)
400

401
402
403
    def __get_application_list_filter_by_vacancies(self, vacancies):
        return Application.objects.filter(vacancy__in=vacancies)

404
    def __get_application_by_vacancy(self, vacancy):
405
        return Application.objects.filter(vacancy=vacancy)
406

407
408
    def __get_status_from_request_param(self, request):
        return request.query_params.get('status', None)
Refo Ilmiya Akbar's avatar
Refo Ilmiya Akbar committed
409

410
    def __validating_application_status(self, status):
Refo Ilmiya Akbar's avatar
Refo Ilmiya Akbar committed
411
        list_status = {0: "NEW", 1: "READ", 2: "BOOKMARKED", 3: "REJECTED", 4: "ACCEPTED", 6: "FINISHED"}
412
413
414
        if status not in list_status:
            raise StatusError
        return True
415

416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
    def __filter_application_list_by_status(self, request, applications):
        status = self.__get_status_from_request_param(request)
        if status is not None:
            status = int(status)
            self.__validating_application_status(status)
            return applications.filter(status=status)
        return applications

    def __get_paginated_application_list(self, request, applications):
        page = self.paginate_queryset(applications)
        if page is not None:
            return self.get_paginated_response(
                ApplicationSerializer(page, many=True, context={'request': request}).data)
        return Response(ApplicationSerializer(applications, many=True, context={'request': request}).data)


432
class CompanyVacanciesViewSet(viewsets.GenericViewSet):
433
    queryset = Vacancy.objects.all()
434
    pagination_class = PageNumberPagination
435
    permission_classes = [IsAdminOrCompany]
436
437
438
439
440
441

    def list(self, request, company_id):
        """
        Get list of company {company_id}'s vacancies
        ---
        """
442
        company = get_object_or_404(Company.objects.all().order_by('-updated'), pk=company_id)
443
444
        if not request.user.is_superuser and request.user != company.user:
            return Response({"error": "forbidden"}, status=status.HTTP_403_FORBIDDEN)
445
        vacancies = Vacancy.objects.filter(company=company)
446
447
448
        page = self.paginate_queryset(vacancies)
        if page is not None:
            return self.get_paginated_response(VacancySerializer(page, many=True, context={'request': request}).data)
449
450
451
        return Response(VacancySerializer(vacancies, many=True, context={'request': request}).data)


452
453
454
455
456
class BookmarkedVacancyByStudentViewSet(viewsets.GenericViewSet):
    serializer_class = VacancySerializer
    permission_classes = [IsAdminOrStudent]

    def list(self, request, student_id):
457
458
459
460
        """
        Get list of a student {student_id}'s bookmarked vacancies
        ---
        """
461
        student = get_object_or_404(Student.objects.all(), pk=student_id)
462
463
        search = request.query_params['search'] if 'search' in request.query_params else None
        if search is not None:
Refo Ilmiya Akbar's avatar
Refo Ilmiya Akbar committed
464
465
            vacancies = student.bookmarked_vacancies.filter(
                Q(name__icontains=search) | Q(company__user__username__icontains=search))
466
467
        else:
            vacancies = student.bookmarked_vacancies.all()
468
469
470
471
        page = self.paginate_queryset(vacancies)
        if page is not None:
            return self.get_paginated_response(VacancySerializer(page, many=True, context={'request': request}).data)
        return Response(VacancySerializer(vacancies, many=True, context={'request': request}).data)
472
473

    def create(self, request, student_id):
474
475
476
477
478
479
480
481
482
483
        """
        Bookmarks a vacancy for student {student_id}
        ---
        parameters:
            - name: body
              description: JSON object containing only one string: vacancy_id
              required: true
              type: string
              paramType: body
        """
484
485
486
        vacancy = get_object_or_404(Vacancy.objects.all(), pk=request.data['vacancy_id'])
        student = get_object_or_404(Student.objects.all(), pk=student_id)
        student.bookmarked_vacancies.add(vacancy)
Zamil Majdy's avatar
Zamil Majdy committed
487
488
        return Response(
            self.serializer_class(student.bookmarked_vacancies, many=True, context={'request': request}).data)
489
490

    def destroy(self, request, student_id, pk):
491
492
493
494
        """
        Remove bookmark {id} for student {student_id}
        ---
        """
495
496
497
        vacancy = get_object_or_404(Vacancy.objects.all(), pk=pk)
        student = get_object_or_404(Student.objects.all(), pk=student_id)
        student.bookmarked_vacancies.remove(vacancy)
Zamil Majdy's avatar
Zamil Majdy committed
498
499
        return Response(
            self.serializer_class(student.bookmarked_vacancies, many=True, context={'request': request}).data)
500

501
502
503
504
505
506
507
508
509
510
511
512
513
514
515

class VacancyMilestoneViewSet(viewsets.GenericViewSet):
    serializer_class = VacancyMilestoneSerializer
    permission_classes = [IsAdminOrVacancyOwnerOrAuthenticatedReadOnly]

    def list(self, request, vacancy_id):
        """
        Get list of a vacancy {vacancy_id}'s milestone plans
        ---
        """
        vacancy = get_object_or_404(Vacancy.objects.all(), pk=vacancy_id)
        milestones = vacancy.milestones.all()
        page = self.paginate_queryset(milestones)
        if page is not None:
            return self.get_paginated_response(
Refo Ilmiya Akbar's avatar
Refo Ilmiya Akbar committed
516
                self.serializer_class(page, many=True, context={'request': request}).data)
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
        return Response(self.serializer_class(milestones, many=True, context={'request': request}).data)

    def create(self, request, vacancy_id):
        """
        Create a new milestone for vacancy {vacancy_id}
        ---
        parameters:
            - name: body
              description: JSON object containing 'name' string, 'detail' string, 'expected_start' date string, and
                           'expected_finish' date string
              required: true
              type: string
              paramType: body
        """
        vacancy = get_object_or_404(Vacancy.objects.all(), pk=vacancy_id)
        milestone_serializer = self.serializer_class(data=request.data)
        if milestone_serializer.is_valid():
            milestone = milestone_serializer.save(vacancy=vacancy)
            return Response(self.serializer_class(milestone, context={'request': request}).data,
                            status=status.HTTP_200_OK)
        return Response(milestone_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def update(self, request, vacancy_id, pk):
        """
        Create existing milestone {pk} for vacancy {vacancy_id}
        ---
        parameters:
            - name: body
              description: JSON object containing 'name' string, 'detail' string, 'expected_start' date string, and
                           'expected_finish' date string
              required: true
              type: string
              paramType: body
        """
        vacancy = get_object_or_404(Vacancy.objects.all(), pk=vacancy_id)
        old_milestone = get_object_or_404(vacancy.milestones.all(), pk=pk)
        milestone_serializer = self.serializer_class(old_milestone, data=request.data)
        if milestone_serializer.is_valid():
            milestone = milestone_serializer.save(vacancy=vacancy)
            return Response(self.serializer_class(milestone, context={'request': request}).data,
                            status=status.HTTP_200_OK)
        return Response(milestone_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def destroy(self, request, vacancy_id, pk):
        """
        Remove existing milestone {pk} from vacancy {vacancy_id}
        ---
        """
        vacancy = get_object_or_404(Vacancy.objects.all(), pk=vacancy_id)
        milestone = get_object_or_404(vacancy.milestones.all(), pk=pk)
        milestone.delete()
        return Response(
            self.serializer_class(vacancy.milestones.all(), many=True, context={'request': request}).data)


572
573
574
575
576
577
578
579
580
581
582
class AcceptOfferByStudentViewSet(MultiSerializerViewSetMixin, viewsets.GenericViewSet):
    queryset = Application.objects.all()
    permission_classes = [IsAdminOrStudent]

    def partial_update(self, request, student_id, pk=None):
        """
        Get list of a student {student_id}'s cancel offered vacancies
        ---
        """
        student = get_object_or_404(Student.objects.all().order_by('-updated'), pk=student_id)
        apps = Application.objects.filter(student=student)
583

584
585
586
587
588
        for a in apps:
            if a.vacancy_id != int(pk):
                serializer = ApplicationStatusSerializer(a, data={'status': 5}, partial=True)
                if serializer.is_valid():
                    serializer.save()
589
590

        return Response(SupervisorStudentApplicationSerializer(apps, many=True, context={'request': request}).data)