class UserCheckView(views.APIView): response_schema_dict = { "200": openapi.Response( description="Success", examples={"application/json": { "user_exists": True, }}), "200: ok": openapi.Response( description="Success", examples={"application/json": { "user_exists": False, }}), } username_param = openapi.Parameter('username', openapi.IN_QUERY, description="Enter user's username", type=openapi.TYPE_STRING) @swagger_auto_schema(method='get', manual_parameters=[username_param], responses=response_schema_dict) @action(detail=False, methods=['GET']) def get(self, request): username = request.GET.get('username', None) if not username: raise ValidationError({"message": "Username is Required."}) user = User.objects.filter(username=username) if user: return JsonResponse({"user_exists": True}) else: return JsonResponse({"user_exists": False})
class JoinDepartment(views.APIView): authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) serializer_class = serializers.DepartmentSerializer @swagger_auto_schema( request_body = openapi.Schema( title = "Join department request", type=openapi.TYPE_OBJECT, properties={ 'org_id': openapi.Schema(type=openapi.TYPE_STRING), 'dept_id': openapi.Schema(type=openapi.TYPE_STRING), } ), responses={ 200: openapi.Response("OK- Successful POST Request"), 401: openapi.Response("Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired"), 422: openapi.Response("Unprocessable Entity- Make sure that all the required field values are passed"), 500: openapi.Response("Internal Server Error- Error while processing the POST Request Function.") } ) @validate_org @validate_dept def post(self, request, *args, **kwargs): data = request.data dept_id = data.get("dept_id", 0) organization = kwargs.get("organization") if not organization.accepting_req: errors = [ 'This organization is not accepting requests currently.' ] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) department = kwargs.get("department") if not department.organization == organization: errors = [ 'Invalid dept_id' ] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) if request.user in department.requesting_users.all() or request.user == department.user: errors = [ 'Request already sent' ] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) department.requesting_users.add(request.user.id) department.save() msgs = [ 'Join request sent' ] return Response({'details': msgs}, status.HTTP_200_OK)
class EssayQuestion(views.APIView): serializer_class = serializers.EssayQuestionSerializer # authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.AllowAny, ) @swagger_auto_schema( request_body=openapi.Schema( title="Essay question", type=openapi.TYPE_OBJECT, properties={ 'content': openapi.Schema(type=openapi.TYPE_STRING), 'explanation': openapi.Schema(type=openapi.TYPE_STRING), 'category': openapi.Schema(type=openapi.TYPE_INTEGER), 'sub-category': openapi.Schema(type=openapi.TYPE_INTEGER), 'quiz': openapi.Schema(type=openapi.TYPE_INTEGER), }), responses={ 200: openapi.Response("OK- Successful POST Request"), 401: openapi.Response( "Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired" ), 422: openapi.Response( "Unprocessable Entity- Make sure that all the required field values are passed" ), 500: openapi.Response( "Internal Server Error- Error while processing the POST Request Function." ) }) def post(self, request): data = request.data quiz = data.get('quiz') category = data.get('category') sub_category = data.get('sub_category', "") content = data.get('content', "") explanation = data.get('explanation', "") data_dict = { "content": content, "quiz": [quiz], "category": category, "sub_category": sub_category, "explanation": explanation, } serializer = self.serializer_class(data=data_dict) if serializer.is_valid(): serializer.save() return Response(serializer.data, status.HTTP_201_CREATED) return Response({'details': serializer.errors}, status.HTTP_400_BAD_REQUEST)
class SubmittedAssignmentFile(views.APIView): authentication_classes = (authentication.TokenAuthentication, ) permission_classes = (permissions.IsAuthenticated, ) @swagger_auto_schema( request_body=openapi.Schema( title="Add Submitted Assignment files", type=openapi.TYPE_OBJECT, properties={ 'org_id': openapi.Schema(type=openapi.TYPE_STRING), 'submitted_assignment': openapi.Schema(type=openapi.TYPE_INTEGER), 'file': openapi.Schema(type=openapi.TYPE_FILE), }), responses={ 200: openapi.Response("OK- Successful POST Request"), 401: openapi.Response( "Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired" ), 422: openapi.Response( "Unprocessable Entity- Make sure that all the required field values are passed" ), 500: openapi.Response( "Internal Server Error- Error while processing the POST Request Function." ) }) @is_student @validate_submitted_assignment def post(self, request, *args, **kwargs): data = request.data file = data.get("file", None) submitted_assignment = kwargs.get("submitted_assignment") if not file: return Response({'details': ['file is required']}, status.HTTP_400_BAD_REQUEST) data_dict = {"submission": submitted_assignment.id, "file": file} serializer = events_serializer.SubmittedAssignmentFileSerializer( data=data_dict) if not serializer.is_valid(): return Response({'details': [str(serializer.errors)]}, status.HTTP_400_BAD_REQUEST) serializer.save() msgs = ['successfully saved assignment file'] return Response({'details': msgs}, status.HTTP_200_OK)
class CompleteOrderViewSet(views.APIView): authentication_classes = (authentication.TokenAuthentication, ) permission_classes = (permissions.IsAuthenticated, ) @swagger_auto_schema( request_body=openapi.Schema( title="Complete Order", type=openapi.TYPE_OBJECT, properties={ 'order_uuid': openapi.Schema(type=openapi.TYPE_STRING), }), responses={ 200: openapi.Response("OK- Successful POST Request"), 401: openapi.Response( "Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired" ), 422: openapi.Response( "Unprocessable Entity- Make sure that all the required field values are passed" ), 500: openapi.Response( "Internal Server Error- Error while processing the POST Request Function." ) }) @validate_order_with_uuid def post(self, request, *args, **kwargs): order = kwargs.get("order") order.ordered = True order.ordered_at = datetime.datetime.now() order.save() if order.discount_code: discount = order.discount_code discount.copies -= 1 if discount.copies < 1: discount.is_available = False discount.save() serializer = orders_serializers.OrderSerializer(order) return response.Response(serializer.data, status.HTTP_200_OK) details = { "message": "Order completed successfully", "order": serializer.data } return response.Response(details, status.HTTP_201_CREATED)
class RefreshTokenView(views.APIView): """ API endpoint that allows users to get access token from refresh token. """ response_schema_dict = { "200": openapi.Response(description="Success", examples={"application/json": { "access": "string", }}), "400": openapi.Response(description="Failed", examples={ "application/json": { "message": "Token is invalid or expired." } }), "400: Bad": openapi.Response( description="Failed", examples={"application/json": { "message": "Token is required." }}), } @swagger_auto_schema(method='post', request_body=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'refresh': openapi.Schema(type=openapi.TYPE_STRING, description='string') }), responses=response_schema_dict) @action(detail=False, methods=['POST']) def post(self, request, *args, **kwargs): refresh = request.data.get('refresh', None) if refresh: try: refresh_token = RefreshToken(refresh) except: raise ValidationError( {"message": "Refresh Token is invalid or expired."}) return JsonResponse({ "refresh": str(refresh_token), "access": str(refresh_token.access_token), "x-karza-key": str(settings.CORE_X_KARZA_KEY) }) raise ValidationError({"message": "Refresh Token is required."})
class VerifyDeptId(views.APIView): permission_classes = (permissions.AllowAny,) @swagger_auto_schema( responses={ 200: openapi.Response("OK- Successful GET Request"), 401: openapi.Response("Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired"), 500: openapi.Response("Internal Server Error- Error while processing the GET Request Function.") }, manual_parameters=[ openapi.Parameter(name="dept_id", in_="query", type=openapi.TYPE_STRING), ] ) @validate_dept def get(self, request, *args, **kwargs): serializer = serializers.DepartmentSerializer(kwargs.get("department")) return Response(serializer.data, status.HTTP_200_OK)
class DetailViewSet(viewsets.ViewSet): serializer_class = DetailSerializer @swagger_auto_schema(responses={ 404: openapi.Response("Not found or Not accessible", DetailSerializer) }) def retrieve(self, request, pk=None): serializer = DetailSerializer({"detail": None}) return Response(serializer.data)
class ZeroPaymentViewSet(views.APIView): authentication_classes = (authentication.TokenAuthentication, ) permission_classes = (permissions.IsAuthenticated, ) @swagger_auto_schema( request_body=openapi.Schema( title="Complete Zero Order", type=openapi.TYPE_OBJECT, properties={ 'uuid': openapi.Schema(type=openapi.TYPE_STRING), }), responses={ 200: openapi.Response("OK- Successful GET Request"), 401: openapi.Response( "Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired" ), 500: openapi.Response( "Internal Server Error- Error while processing the GET Request Function." ) }) @validate_order def post(self, request, *args, **kwargs): order = kwargs.get("order") if not order.user == request.user or int(order.total_amount) != 0: errors = { 'message': 'Invalid request', } return response.Response(errors, status.HTTP_400_BAD_REQUEST) order.ordered_at = datetime.datetime.now() order.ordered = True order.save() if order.discount_code: discount_code = order.discount_code discount_code.copies -= 1 discount_code.save() details = {"message": "Order completed successfully"} return response.Response(details, status.HTTP_200_OK)
class AvailableCoupons(views.APIView): authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) @swagger_auto_schema( responses={ 200: openapi.Response("OK- Successful GET Request"), 401: openapi.Response("Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired"), 500: openapi.Response("Internal Server Error- Error while processing the GET Request Function.") } ) @coupons_available def get(self, request, *args, **kwargs): data = { "available_coupons": kwargs.get("available_coupons", 0), "used_coupons": kwargs.get("used_coupons", 0) } return response.Response(data, status.HTTP_200_OK)
class RedeemCodeAvailablity(views.APIView): permission_classes = (permissions.AllowAny,) @swagger_auto_schema( responses={ 200: openapi.Response("OK- Successful GET Request"), 401: openapi.Response("Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired"), 500: openapi.Response("Internal Server Error- Error while processing the GET Request Function.") }, manual_parameters=[ openapi.Parameter(name="code", in_="query", type=openapi.TYPE_STRING), ] ) @validate_coupon_code def get(self, request, *args, **kwargs): coupons = kwargs.get("coupons") uuid = coupons[0].uuid data = { "uuid": uuid, } return response.Response(data, status.HTTP_200_OK)
class AssignedClass(views.APIView): authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) @swagger_auto_schema( responses={ 200: openapi.Response("OK- Successful GET Request"), 401: openapi.Response("Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired"), 500: openapi.Response("Internal Server Error- Error while processing the GET Request Function.") }, manual_parameters=[ openapi.Parameter(name="dept_id", in_="query", type=openapi.TYPE_STRING), ] ) def get(self, request): dept_id = self.request.query_params.get('dept_id', "") if not dept_id: errors = [ 'dept_id is not passed' ] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) departments = models.Department.objects.filter(department_id=str(dept_id), is_active=True) if not len(departments): errors = [ 'Invalid dept_id' ] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) department = departments[0] qs = classes_models.Class.objects.filter(department=department, is_active=True) serializer = classes_serializers.ClassSerializer(qs, many=True) return Response(serializer.data, status.HTTP_200_OK)
class TotalSpent(views.APIView): authentication_classes = (authentication.TokenAuthentication, ) permission_classes = (permissions.IsAuthenticated, ) @swagger_auto_schema( responses={ 200: openapi.Response("OK- Successful GET Request"), 401: openapi.Response( "Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired" ), 500: openapi.Response( "Internal Server Error- Error while processing the GET Request Function." ) }) def get(self, request, *args, **kwargs): user = request.user total_spent = 0 orders = orders_models.Order.objects.filter( Q(user=user) & Q(ordered=True)).order_by("ordered_at") coupons = coupons_models.Coupon.objects.filter( Q(user=user) & Q(redeemed=True)) since = orders[0].ordered_at if len(orders) else None for _ in orders: total_spent += _.total_amount for _ in coupons: total_spent += _.amount return response.Response({ "total_spent": total_spent, "since": since }, status.HTTP_200_OK)
class SnippetDetail(generics.RetrieveUpdateDestroyAPIView): """ SnippetDetail classdoc put: put class docstring patch: patch class docstring """ queryset = Snippet.objects.all() serializer_class = SnippetSerializer pagination_class = None parser_classes = (CamelCaseJSONParser, ) renderer_classes = (CamelCaseJSONRenderer, ) swagger_schema = CamelCaseOperationIDAutoSchema def patch(self, request, *args, **kwargs): """patch method docstring""" return super(SnippetDetail, self).patch(request, *args, **kwargs) @swagger_auto_schema( manual_parameters=[ openapi.Parameter( name="id", in_=openapi.IN_PATH, type=openapi.TYPE_INTEGER, description="path parameter override", required=True, ), ], responses={ status.HTTP_204_NO_CONTENT: openapi.Response( description= "this should not crash (response object with no schema)") }, ) def delete(self, request, *args, **kwargs): """delete method docstring""" return super(SnippetDetail, self).patch(request, *args, **kwargs)
class EmployerViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to list, create,retrieve, update, delete. """ queryset = Employer.objects.all().order_by('-id') serializer_class = EmployerSerializer permission_classes = [] response_schema_dict = { "200": openapi.Response( description="source == 'web' and fieldset == 'principal'", examples={ "application/json": { "count": 1, "next": "", "previous": "", "results": [ { "id": 22, "user": { "id": 44, "username": "******" }, "rid": "string", "name": "string", "phone": "string", "email": "string", "company": 1, "department": 1, "designation": 1, "principal_companies": [ 1 ] }, ] } } ), } name_param = openapi.Parameter( 'name', openapi.IN_QUERY, description="Enter employer's name", type=openapi.TYPE_STRING) email_param = openapi.Parameter( 'email', openapi.IN_QUERY, description="Enter employer's email", type=openapi.TYPE_STRING ) source_param = openapi.Parameter( 'source', openapi.IN_QUERY, description="Enter source param", type=openapi.TYPE_STRING) fieldset_param = openapi.Parameter( 'fieldset', openapi.IN_QUERY, description="Enter fieldset param", type=openapi.TYPE_STRING ) @swagger_auto_schema(manual_parameters=[ name_param, email_param, source_param, fieldset_param], responses=response_schema_dict) def list(self, request, *args, **kwargs): queryset = Employer.objects.all().order_by('-id') name = self.request.query_params.get('name', None) email = self.request.query_params.get('email', None) source = self.request.query_params.get('source', None) fieldset = self.request.query_params.get('fieldset', None) if name: queryset = queryset.filter(name__icontains=name) if email: queryset = queryset.filter(email=email) if email and source == 'web' and fieldset == 'principal': employer = queryset.first() principal_companies = employer.principal_companies.all() page = self.paginate_queryset(principal_companies) serializer = PrincipalCompanyListSerializer(page, many=True) response = self.get_paginated_response(serializer.data) return response page = self.paginate_queryset(queryset) serializer = EmployerSerializer(page, many=True) response = self.get_paginated_response(serializer.data) return response @swagger_auto_schema(request_body=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'user': openapi.Schema( type=openapi.TYPE_OBJECT, description='object'), 'name': openapi.Schema(type=openapi.TYPE_STRING, description='string'), 'phone': openapi.Schema(type=openapi.TYPE_STRING, description='string'), 'email': openapi.Schema(type=openapi.TYPE_STRING, description='string'), 'department': openapi.Schema( type=openapi.TYPE_INTEGER, description='integer'), 'designation': openapi.Schema( type=openapi.TYPE_INTEGER, description='integer'), 'company': openapi.Schema( type=openapi.TYPE_INTEGER, description='integer'), } )) def create(self, request): employer_data = request.data # user data validation username = employer_data['user'].get('username', None) if not username: raise ValidationError({"message": "username is required field"}) if username: user = User.objects.filter(username=username).first() if user: raise ValidationError({ "message": "User already exists with this username."}) # employer_data validation name = employer_data.get('name', None) phone = employer_data.get('phone', None) email = employer_data.get('email', None) photo = employer_data.get('photo', None) department = employer_data.get('department', None) designation = employer_data.get('designation', None) company = employer_data.get('company', None) if not email: raise ValidationError({"message": "email is required."}) if not name: raise ValidationError({"message": "name is required."}) if not phone: raise ValidationError({"message": "phone is required."}) if email: employer = Employer.objects.filter(email=email).first() if employer: raise ValidationError({ "message": "employer already exists with this email."}) if department: try: Department.objects.get(id=department) except: raise ValidationError({"message": "department does not exist."}) if designation: try: Designation.objects.get(id=designation) except: raise ValidationError({"message": "designation does not exist."}) if company: try: Company.objects.get(id=company) except: raise ValidationError({"message": "company does not exist."}) serializer = EmployerSerializer(data=employer_data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) raise ValidationError({"message": "Invalid arguments"})
class SmsOtpView(views.APIView): """ API endpoint that allows users to send sms """ permission_classes = [] response_schema_dict = { "200": openapi.Response( description="Success", examples={ "application/json": { "body": "Hello! Your OTP for login is 154622. And this OTP is valid for 2 minutes only.", "sender": "NSQURD", "type": "OTP", "source": "API", "id": "83fd53e3-e183-401e-8411-9a3d2e409c02", "createdDateTime": "2020-12-12 12:22:11+00:00", "totalCount": 1, "data": [{ "message_id": "83fd53e3-e183-401e-8411-9a3d2e409c02:1", "recipient": "917007501490" }], "error": {}, "otp": "154622" } }), } @swagger_auto_schema(method='post', request_body=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'phone': openapi.Schema(type=openapi.TYPE_STRING, description='string'), 'template': openapi.Schema(type=openapi.TYPE_STRING, description='string'), }), responses=response_schema_dict) @action(detail=False, methods=['POST']) def post(self, request, *args, **kwargs): phone = request.data.get('phone', None) template = request.data.get('template', None) if not phone: raise ValidationError({"message": "Phone is Required."}) if not template: raise ValidationError({"message": "Template is Required."}) user = User.objects.filter(username=phone).first() # get otp and send to the user otp = utilities.generate_random_number(6) data = call(phone, template, otp) data['otp'] = str(otp) if otp else "" if user: user.otp = otp expiry_datetime = datetime.datetime.now() + datetime.timedelta( seconds=120) expiry_datetime = get_utc_datetime(expiry_datetime) user.otp_valid_till = expiry_datetime user.save() return JsonResponse(data)
class SubmittedAssignment(views.APIView): authentication_classes = (authentication.TokenAuthentication, ) permission_classes = (permissions.IsAuthenticated, ) @swagger_auto_schema(responses={ 200: openapi.Response("OK- Successful GET Request"), 401: openapi.Response( "Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired" ), 500: openapi.Response( "Internal Server Error- Error while processing the GET Request Function." ) }, manual_parameters=[ openapi.Parameter(name="org_id", in_="query", type=openapi.TYPE_STRING), openapi.Parameter(name="assignment", in_="query", type=openapi.TYPE_INTEGER), openapi.Parameter(name="submitted_assignment", in_="query", type=openapi.TYPE_INTEGER), openapi.Parameter(name="event", in_="query", type=openapi.TYPE_INTEGER), openapi.Parameter(name="subject", in_="query", type=openapi.TYPE_INTEGER), ]) @validate_org @is_teacher def get(self, request, *args, **kwargs): query_params = self.request.query_params submitted_assignment_id = query_params.get('assignment', None) assignment_id = query_params.get('assignment', None) event_id = query_params.get('event', None) subject_id = query_params.get('subject', None) qs = events_models.SubmittedAssignment.objects.filter(is_active=True) if submitted_assignment_id: qs = qs.filter(id=int(submitted_assignment_id)) if assignment_id: qs = qs.filter(assignment__id=int(assignment_id)) if event_id: qs = qs.filter(assignment__event__id=int(event_id)) if subject_id: qs = qs.filter(assignment__event__subject__id=int(subject_id)) serializer = events_serializer.SubmittedAssignmentSerializer(qs, many=True) return Response(serializer.data, status.HTTP_200_OK) @swagger_auto_schema( request_body=openapi.Schema( title="Create Assignment", type=openapi.TYPE_OBJECT, properties={ 'org_id': openapi.Schema(type=openapi.TYPE_STRING), 'assignment': openapi.Schema(type=openapi.TYPE_INTEGER), 'is_completed': openapi.Schema(type=openapi.TYPE_BOOLEAN), }), responses={ 200: openapi.Response("OK- Successful POST Request"), 401: openapi.Response( "Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired" ), 422: openapi.Response( "Unprocessable Entity- Make sure that all the required field values are passed" ), 500: openapi.Response( "Internal Server Error- Error while processing the POST Request Function." ) }) @validate_org @validate_assignment @is_student def post(self, request, *args, **kwargs): data = request.data student = kwargs.get("student") assignment = kwargs.get("assignment") is_completed = data.get('is_completed', False) data_dict = { "assignment": assignment.id, "student": student.id, "is_completed": True if is_completed else False } if is_completed: data_dict.update({"submitted_at": datetime.datetime.now()}) serializer = events_serializer.SubmittedAssignmentSerializer( data=data_dict) if not serializer.is_valid(): return Response({'details': [str(serializer.errors)]}, status.HTTP_400_BAD_REQUEST) serializer.save() msgs = ['successfully submitted assignment'] return Response({'details': msgs}, status.HTTP_200_OK) @swagger_auto_schema( request_body=openapi.Schema( title="Create Assignment", type=openapi.TYPE_OBJECT, properties={ 'org_id': openapi.Schema(type=openapi.TYPE_STRING), 'submitted_assignment': openapi.Schema(type=openapi.TYPE_INTEGER), 'assignment': openapi.Schema(type=openapi.TYPE_INTEGER), 'is_completed': openapi.Schema(type=openapi.TYPE_BOOLEAN), }), responses={ 200: openapi.Response("OK- Successful POST Request"), 401: openapi.Response( "Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired" ), 422: openapi.Response( "Unprocessable Entity- Make sure that all the required field values are passed" ), 500: openapi.Response( "Internal Server Error- Error while processing the POST Request Function." ) }) @validate_org @validate_submitted_assignment @is_student def put(self, request, *args, **kwargs): data = request.data student = kwargs.get("student") submitted_assignment = kwargs.get("submitted_assignment") is_completed = data.get('is_completed', False) data_dict = {"is_completed": True if is_completed else False} if is_completed: data_dict.update({"submitted_at": datetime.datetime.now()}) submitted_assignment = kwargs.get("submitted_assignment") if not submitted_assignment.student == student: return Response({'details': ["Invalid request"]}, status.HTTP_400_BAD_REQUEST) serializer = events_serializer.SubmittedAssignmentSerializer( submitted_assignment, data=data_dict, partial=True) if not serializer.is_valid(): return Response({'details': [str(serializer.errors)]}, status.HTTP_400_BAD_REQUEST) serializer.save() msgs = ['successfully updated assignment'] return Response({'details': msgs}, status.HTTP_200_OK)
class Event(views.APIView): authentication_classes = (authentication.TokenAuthentication, ) permission_classes = (permissions.IsAuthenticated, ) @swagger_auto_schema(responses={ 200: openapi.Response("OK- Successful GET Request"), 401: openapi.Response( "Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired" ), 500: openapi.Response( "Internal Server Error- Error while processing the GET Request Function." ) }, manual_parameters=[ openapi.Parameter(name="event", in_="query", type=openapi.TYPE_INTEGER), openapi.Parameter(name="subject", in_="query", type=openapi.TYPE_INTEGER), ]) def get(self, request): query_params = self.request.query_params event_id = query_params.get('event', None) subject_id = query_params.get('subject', None) qs = events_models.Event.objects.filter(is_active=True) if event_id: qs = qs.filter(id=event_id) if subject_id: qs = qs.filter(subject__id=int(subject_id)) serializer = events_serializer.EventSerializer(qs, many=True) return Response(serializer.data, status.HTTP_200_OK) @swagger_auto_schema( request_body=openapi.Schema( title="Create event", type=openapi.TYPE_OBJECT, properties={ 'org_id': openapi.Schema(type=openapi.TYPE_STRING), 'type': openapi.Schema(type=openapi.TYPE_STRING), 'data': openapi.Schema(type=openapi.TYPE_OBJECT), 'subject_id': openapi.Schema(type=openapi.TYPE_NUMBER), 'date': openapi.Schema(type=openapi.FORMAT_DATETIME), }), responses={ 200: openapi.Response("OK- Successful POST Request"), 401: openapi.Response( "Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired" ), 422: openapi.Response( "Unprocessable Entity- Make sure that all the required field values are passed" ), 500: openapi.Response( "Internal Server Error- Error while processing the POST Request Function." ) }) @is_teacher def post(self, request, *args, **kwargs): data = json.loads(json.dumps(request.data)) event_type = data.get("type", "") event_data = data.get("data", "") subject_id = data.get("subject_id", "") date = data.get("date", "") if not event_data or not event_type or not subject_id or not data: errors = [ 'event_data, event_type, subject_id and data are required' ] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) subjects = subject_models.Subject.objects.filter(is_active=True, id=subject_id) if not len(subjects): errors = ['Invalid subjects_id'] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) subject = subjects[0] EVENT_TYPES_keys = [i[0] for i in events_models.EVENT_TYPES] if not str(event_type) in EVENT_TYPES_keys: errors = [f"invalid type, options are {EVENT_TYPES_keys}"] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) events_models.Event.objects.create(data=str(event_data), subject=subject, date=date, type=str(event_type)) msgs = ['successfully created daily class'] return Response({'details': msgs}, status.HTTP_200_OK)
class Assignment(views.APIView): authentication_classes = (authentication.TokenAuthentication, ) permission_classes = (permissions.IsAuthenticated, ) @swagger_auto_schema(responses={ 200: openapi.Response("OK- Successful GET Request"), 401: openapi.Response( "Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired" ), 500: openapi.Response( "Internal Server Error- Error while processing the GET Request Function." ) }, manual_parameters=[ openapi.Parameter(name="assignment", in_="query", type=openapi.TYPE_INTEGER), openapi.Parameter(name="event", in_="query", type=openapi.TYPE_INTEGER), openapi.Parameter(name="subject", in_="query", type=openapi.TYPE_INTEGER), ]) def get(self, request): query_params = self.request.query_params assignment_id = query_params.get('assignment', None) event_id = query_params.get('event', None) subject_id = query_params.get('subject', None) qs = events_models.Assignment.objects.filter(is_active=True) if assignment_id: qs = qs.filter(id=int(assignment_id)) if event_id: qs = qs.filter(event__id=int(event_id)) if subject_id: qs = qs.filter(event__subject__id=int(subject_id)) serializer = events_serializer.AssignmentSerializer(qs, many=True) return Response(serializer.data, status.HTTP_200_OK) @swagger_auto_schema( request_body=openapi.Schema( title="Create Assignment", type=openapi.TYPE_OBJECT, properties={ 'org_id': openapi.Schema(type=openapi.TYPE_STRING), 'event': openapi.Schema(type=openapi.TYPE_INTEGER), 'title': openapi.Schema(type=openapi.TYPE_STRING), 'description': openapi.Schema(type=openapi.TYPE_STRING), 'due_date': openapi.Schema(type=openapi.FORMAT_DATETIME), }), responses={ 200: openapi.Response("OK- Successful POST Request"), 401: openapi.Response( "Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired" ), 422: openapi.Response( "Unprocessable Entity- Make sure that all the required field values are passed" ), 500: openapi.Response( "Internal Server Error- Error while processing the POST Request Function." ) }) @is_teacher @validate_event def post(self, request, *args, **kwargs): event = kwargs.get("event") if not event.type == 'AS': errors = ['Invalid event type must be AS (Assignment).'] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) already = events_models.Assignment.objects.filter(event=event) if len(already): errors = [ 'This event is already assigned to an assignment. Please create a new event.' ] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) data = json.loads(json.dumps(request.data)) title = data.get("title", "") description = data.get("description", "") due_date = data.get("due_date", "") event = kwargs.get("event") events_models.Assignment.objects.create(title=str(title), event=event, description=str(description), due_date=due_date) msgs = ['successfully created assignment'] return Response({'details': msgs}, status.HTTP_200_OK)
class JoinRequestsDepartment(views.APIView): authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) @swagger_auto_schema( responses={ 200: openapi.Response("OK- Successful GET Request"), 401: openapi.Response("Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired"), 500: openapi.Response("Internal Server Error- Error while processing the GET Request Function.") }, manual_parameters=[ openapi.Parameter(name="org_id", in_="query", type=openapi.TYPE_STRING), ] ) @is_organization def get(self, request, *args, **kwargs): departments = departments_models.Department.objects.filter( Q(organization=kwargs.get("organization")) & Q(is_active=True)) serializer = departments_serializers.DepartmentSerializer(departments, many=True) return Response(serializer.data, status.HTTP_200_OK) @swagger_auto_schema( request_body = openapi.Schema( title = "Join department request", type=openapi.TYPE_OBJECT, properties={ 'org_id': openapi.Schema(type=openapi.TYPE_STRING), 'dept_id': openapi.Schema(type=openapi.TYPE_STRING), 'requesting_user_id': openapi.Schema(type=openapi.TYPE_INTEGER), } ), responses={ 200: openapi.Response("OK- Successful POST Request"), 401: openapi.Response("Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired"), 422: openapi.Response("Unprocessable Entity- Make sure that all the required field values are passed"), 500: openapi.Response("Internal Server Error- Error while processing the POST Request Function.") } ) @is_organization @validate_dept def post(self, request, *args, **kwargs): data = request.data requesting_user_id = data.get("requesting_user_id", 0) if not requesting_user_id: errors = [ 'requesting_user_id is not passed' ] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) organization = kwargs.get("organization") department = kwargs.get("department") if not department.organization == organization: errors = [ 'Invalid dept_id' ] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) request_list = [] for i in department.requesting_users.all(): request_list.append(str(i.id)) if not str(requesting_user_id) in request_list: errors = [ 'Invalid requesting_user_id' ] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) department.requesting_users.remove(int(requesting_user_id)) department.user = users_models.User.objects.get(id=int(requesting_user_id)) department.save() msgs = [ 'Request accepted successfully' ] return Response({'details': msgs}, status.HTTP_200_OK)
class DetailViewSet(viewsets.ViewSet): @swagger_auto_schema( responses={200: openapi.Response("OK", DetailSerializer)}) def retrieve(self, request, pk=None): return Response({"detail": None})
class CreateSection(views.APIView): serializer_class = serializers.SectionSerializer authentication_classes = (authentication.TokenAuthentication, ) permission_classes = (permissions.IsAuthenticated, ) @swagger_auto_schema(responses={ 200: openapi.Response("OK- Successful GET Request"), 401: openapi.Response( "Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired" ), 500: openapi.Response( "Internal Server Error- Error while processing the GET Request Function." ) }, manual_parameters=[ openapi.Parameter(name="id", in_="query", type=openapi.TYPE_INTEGER), openapi.Parameter(name="org_id", in_="query", type=openapi.TYPE_STRING), openapi.Parameter(name="dept_id", in_="query", type=openapi.TYPE_STRING), openapi.Parameter(name="class_id", in_="query", type=openapi.TYPE_INTEGER), ]) def get(self, request): query_params = self.request.query_params id = query_params.get('id', None) class_id = query_params.get('class_id', None) dept_id = query_params.get('dept_id', None) org_id = query_params.get('org_id', None) qs = models.Section.objects.filter(is_active=True) if id: qs = qs.filter(id=int(id)) if class_id: qs = qs.filter(of_class__id=int(class_id)) if dept_id: qs = qs.filter(of_class__department__department_id=dept_id) if org_id: qs = qs.filter(of_class__department__organization__org_id=org_id) serializer = serializers.SectionSerializer(qs, many=True) return Response(serializer.data, status.HTTP_200_OK) @swagger_auto_schema( request_body=openapi.Schema( title="Create Section", type=openapi.TYPE_OBJECT, properties={ 'title': openapi.Schema(type=openapi.TYPE_STRING), 'of_class_id': openapi.Schema(type=openapi.TYPE_INTEGER) }), responses={ 200: openapi.Response("OK- Successful POST Request"), 401: openapi.Response( "Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired" ), 422: openapi.Response( "Unprocessable Entity- Make sure that all the required field values are passed" ), 500: openapi.Response( "Internal Server Error- Error while processing the POST Request Function." ) }) def post(self, request): data = request.data title = data.get('title', "") of_class_id = data.get('of_class_id', 0) if not title: errors = ['title is not passed'] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) if not of_class_id: errors = ['of_class_id is not passed'] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) qr_class = class_models.Class.objects.filter(id=int(of_class_id), is_active=True) if not len(qr_class): errors = ['Invalid of_class_id'] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) of_class_id = qr_class[0] if models.Section.objects.filter(title=title, of_class=of_class_id).exists(): errors = ['Section already exists'] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) models.Section.objects.create(title=title, of_class=of_class_id) msgs = ['successfully created section'] return Response({'details': msgs}, status.HTTP_200_OK)
class Organization(views.APIView): authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) serializer_class = serializers.OrganizationSerializer @swagger_auto_schema( responses={ 200: openapi.Response("OK- Successful GET Request"), 401: openapi.Response( "Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired"), 500: openapi.Response("Internal Server Error- Error while processing the GET Request Function.") }, manual_parameters=[ openapi.Parameter(name="org_id", in_="query", type=openapi.TYPE_STRING), ] ) @is_organization def get(self, request, **kwargs): query_params = self.request.query_params organization = kwargs.get('organization') org_id = organization.id qs = models.Organization.objects.filter(id=org_id, is_active=True) serializer = serializers.OrganizationSerializer(qs, many=True) return Response(serializer.data, status.HTTP_200_OK) @swagger_auto_schema( request_body=openapi.Schema( title="Update Organization", type=openapi.TYPE_OBJECT, properties={ 'org_id': openapi.Schema(type=openapi.TYPE_STRING), 'join_id': openapi.Schema(type=openapi.TYPE_STRING), 'name': openapi.Schema(type=openapi.TYPE_STRING), 'contact_name': openapi.Schema(type=openapi.TYPE_STRING), 'contact_phone': openapi.Schema(type=openapi.TYPE_STRING), 'contact_email': openapi.Schema(type=openapi.TYPE_STRING), 'location': openapi.Schema(type=openapi.TYPE_STRING), 'accepting_req': openapi.Schema(type=openapi.TYPE_BOOLEAN) } ), manual_parameters=[ openapi.Parameter(name="org_id", in_="query", type=openapi.TYPE_STRING), ], responses={ 200: openapi.Response("OK- Successful POST Request"), 401: openapi.Response( "Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired"), 422: openapi.Response("Unprocessable Entity- Make sure that all the required field values are passed"), 500: openapi.Response("Internal Server Error- Error while processing the POST Request Function.") } ) @is_organization def put(self, request, *args, **kwargs): query_params = self.request.query_params data = request.data data = pop_from_data(["is_active", "user"], data) organization = kwargs.get("organization") serializer = serializers.OrganizationSerializer(organization, data=data, partial=True) if not serializer.is_valid(): return Response({'details': [str(serializer.errors)]}, status.HTTP_400_BAD_REQUEST) serializer.save() msgs = [ 'successfully updated department' ] return Response({'details': msgs}, status.HTTP_200_OK)
class JoinRequestsTeacher(views.APIView): queryset = models.Organization.objects.filter(is_active=True) serializer_class = teachers_serializers.TeacherSerializer authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) @swagger_auto_schema( responses={ 200: openapi.Response("OK- Successful GET Request"), 401: openapi.Response("Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired"), 500: openapi.Response("Internal Server Error- Error while processing the GET Request Function.") }, manual_parameters=[ openapi.Parameter(name="org_id", in_="query", type=openapi.TYPE_STRING), ] ) @is_organization def get(self, request, **kwargs): query_params = self.request.query_params organizations=kwargs.get("organization") teachers = teachers_models.Teacher.objects.filter( Q(requested_organization__id=organizations.id) & Q(is_active=True)) serializer = teachers_serializers.TeacherSerializer(teachers, many=True) return Response(serializer.data, status.HTTP_200_OK) @swagger_auto_schema( request_body = openapi.Schema( title = "Join teacher request", type=openapi.TYPE_OBJECT, properties={ 'org_id': openapi.Schema(type=openapi.TYPE_STRING), 'teachers': openapi.Schema(type=openapi.TYPE_STRING), } ), responses={ 200: openapi.Response("OK- Successful POST Request"), 401: openapi.Response("Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired"), 422: openapi.Response("Unprocessable Entity- Make sure that all the required field values are passed"), 500: openapi.Response("Internal Server Error- Error while processing the POST Request Function.") } ) def post(self, request): data = request.data org_id = data.get('org_id',"") teachers = str(data.get("teachers", "[]")) if not org_id: errors = [ 'org_id is not passed' ] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) organizations = self.queryset.filter(Q(user__id=request.user.id) & Q(org_id=org_id)) if not len(organizations): errors = [ 'Invalid org_id' ] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) if len(teachers) < 3: errors = [ "teachers not passed or teachers format should be like this. [1, 2, 3] where 1, 2 and 3 are teacher ID's" ] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) try: teachers = teachers.replace(" ", "") teachers = teachers[1:len(teachers) - 1].split(",") teachers = [int(i) for i in teachers] except Exception as e: errors = [ "teachers format should be like this. [1, 2, 3] where 1, 2 and 3 are teacher ID's", str(e) ] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) teach_qs = teachers_models.Teacher.objects.filter(is_active=True) valid_teachers = [] for i in teachers: temp_teach = teach_qs.filter(id=i) if not len(temp_teach): errors = [ 'Invalid teacher ID' ] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) temp_teach = temp_teach[0] if not temp_teach.requested_organization or temp_teach.requested_organization.user.id != request.user.id: errors = [ 'already accepted requests' ] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) valid_teachers.append(temp_teach) for temp_teach in valid_teachers: temp_teach.organization = temp_teach.requested_organization temp_teach.requested_organization = None temp_teach.save() return Response({"details": ["Successfully accepted all provided requests."]}, status.HTTP_200_OK)
class QuizViewApi(views.APIView): serializer_class = serializers.QuizSerializer # authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.AllowAny, ) @swagger_auto_schema( request_body=openapi.Schema( title="Quiz", type=openapi.TYPE_OBJECT, properties={ 'title': openapi.Schema(type=openapi.TYPE_STRING), 'description': openapi.Schema(type=openapi.TYPE_STRING), 'url': openapi.Schema(type=openapi.TYPE_STRING), 'category': openapi.Schema(type=openapi.TYPE_INTEGER), 'random_order': openapi.Schema(type=openapi.TYPE_BOOLEAN), 'max_questions': openapi.Schema(type=openapi.TYPE_INTEGER), 'answers_at_end': openapi.Schema(type=openapi.TYPE_BOOLEAN), 'exam_paper': openapi.Schema(type=openapi.TYPE_BOOLEAN), 'single_attempt': openapi.Schema(type=openapi.TYPE_BOOLEAN), 'pass_mark': openapi.Schema(type=openapi.TYPE_INTEGER), 'success_text': openapi.Schema(type=openapi.TYPE_STRING), 'fail_text': openapi.Schema(type=openapi.TYPE_STRING), 'draft': openapi.Schema(type=openapi.TYPE_BOOLEAN), }), responses={ 200: openapi.Response("OK- Successful POST Request"), 401: openapi.Response( "Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired" ), 422: openapi.Response( "Unprocessable Entity- Make sure that all the required field values are passed" ), 500: openapi.Response( "Internal Server Error- Error while processing the POST Request Function." ) }) def post(self, request): data = request.data title = data.get('title', "") description = data.get('description') url = data.get('url') category = data.get('category') random_order = data.get('random_order') max_questions = data.get('max_questions') answer_at_end = data.get('answers_at_end') exam_paper = data.get('exam_paper') single_attempt = data.get('single_attempt') pass_mark = data.get('pass_mark') success_text = data.get('success_text') fail_text = data.get('fail_text') draft = data.get('draft') data_dict = { "title": title, "description": description, "url": url, "category": category, "random_order": random_order, "max_questions": max_questions, "answers_at_end": answer_at_end, "exam_paper": exam_paper, "single_attempt": single_attempt, "pass_mark": pass_mark, "success_text": success_text, "fail_text": fail_text, "draft": draft, } serializer = self.serializer_class(data=data_dict) if serializer.is_valid(): serializer.save() return Response(serializer.data, status.HTTP_201_CREATED) return Response({'details': serializer.errors}, status.HTTP_400_BAD_REQUEST)
class DepartmentViewSet(views.APIView): authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) serializer_class = serializers.DepartmentSerializer @swagger_auto_schema( responses={ 200: openapi.Response("OK- Successful GET Request"), 401: openapi.Response("Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired"), 500: openapi.Response("Internal Server Error- Error while processing the GET Request Function.") }, manual_parameters=[ openapi.Parameter(name="id", in_="query", type=openapi.TYPE_INTEGER), openapi.Parameter(name="dept_id", in_="query", type=openapi.TYPE_STRING), openapi.Parameter(name="org_id", in_="query", type=openapi.TYPE_STRING), ] ) def get(self, request): query_params = self.request.query_params id = query_params.get('id', None) dept_id = query_params.get('dept_id', None) org_id = query_params.get('org_id', None) qs = models.Department.objects.filter(is_active=True) if id: qs = qs.filter(id=int(id)) if dept_id: qs = qs.filter(department_id=str(dept_id)) if org_id: qs = qs.filter(organization__org_id=org_id) serializer = serializers.DepartmentSerializer(qs, many=True) return Response(serializer.data, status.HTTP_200_OK) @swagger_auto_schema( request_body = openapi.Schema( title = "Create department", type=openapi.TYPE_OBJECT, properties={ 'org_id': openapi.Schema(type=openapi.TYPE_STRING), 'name': openapi.Schema(type=openapi.TYPE_STRING), } ), responses={ 200: openapi.Response("OK- Successful POST Request"), 401: openapi.Response("Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired"), 422: openapi.Response("Unprocessable Entity- Make sure that all the required field values are passed"), 500: openapi.Response("Internal Server Error- Error while processing the POST Request Function.") } ) @validate_org def post(self, request, **kwargs): data = json.loads(json.dumps(request.data)) name = data.get("name", None) if not name: return Response({'details': ["name is required"]}, status.HTTP_400_BAD_REQUEST) organization = kwargs.get("organization") data_dict = { "organization" : organization.id, "name": str(name), "requesting_users": [request.user.id], } serializer = self.serializer_class(data=data_dict) if serializer.is_valid(): serializer.save() return Response(serializer.data, status.HTTP_201_CREATED) return Response(serializer.errors, status.HTTP_400_BAD_REQUEST) @swagger_auto_schema( request_body=openapi.Schema( title="Update Department", type=openapi.TYPE_OBJECT, properties={ 'org_id': openapi.Schema(type=openapi.TYPE_STRING), 'dept_id': openapi.Schema(type=openapi.TYPE_STRING), 'name': openapi.Schema(type=openapi.TYPE_STRING), 'contact_name': openapi.Schema(type=openapi.TYPE_STRING), 'contact_phone': openapi.Schema(type=openapi.TYPE_STRING), 'contact_email': openapi.Schema(type=openapi.TYPE_STRING), 'department_id': openapi.Schema(type=openapi.TYPE_STRING) } ), responses={ 200: openapi.Response("OK- Successful POST Request"), 401: openapi.Response( "Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired"), 422: openapi.Response("Unprocessable Entity- Make sure that all the required field values are passed"), 500: openapi.Response("Internal Server Error- Error while processing the POST Request Function.") } ) @is_org_or_department def put(self, request, *args, **kwargs): data = request.data data = pop_from_data(["is_active", "user", "organization"], data) department = kwargs.get("department") serializer = serializers.DepartmentSerializer(department, data=data, partial=True) if not serializer.is_valid(): return Response({'details': [str(serializer.errors)]}, status.HTTP_400_BAD_REQUEST) serializer.save() msgs = [ 'successfully updated department' ] return Response({'details': msgs}, status.HTTP_200_OK) @swagger_auto_schema( request_body=openapi.Schema( title="Delete Department", type=openapi.TYPE_OBJECT, properties={ 'dept_id': openapi.Schema(type=openapi.TYPE_STRING), 'org_id': openapi.Schema(type=openapi.TYPE_STRING) } ), responses={ 200: openapi.Response("OK- Successful POST Request"), 401: openapi.Response( "Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired"), 422: openapi.Response("Unprocessable Entity- Make sure that all the required field values are passed"), 500: openapi.Response("Internal Server Error- Error while processing the POST Request Function.") } ) @is_organization def delete(self, request, *args, **kwargs): data = request.data dept_id = data.get('dept_id', None) org_id = data.get('org_id', None) departments = models.Department.objects.filter(Q(department_id=dept_id) & Q(organization__org_id=org_id) & Q(is_active=True)) if not len(departments): errors = [ 'invalid id' ] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) department = departments[0] department.is_active = False department.save() msgs = [ "Successfully deleted department" ] return Response({'details': msgs}, status.HTTP_200_OK)
class AssignTeacher(views.APIView): authentication_classes = (authentication.TokenAuthentication, ) permission_classes = (permissions.IsAuthenticated, ) @swagger_auto_schema( request_body=openapi.Schema( title="Assign class teacher to section", type=openapi.TYPE_OBJECT, properties={ 'teacher': openapi.Schema(type=openapi.TYPE_INTEGER), 'section': openapi.Schema(type=openapi.TYPE_INTEGER) }), responses={ 200: openapi.Response("OK- Successful POST Request"), 401: openapi.Response( "Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired" ), 422: openapi.Response( "Unprocessable Entity- Make sure that all the required field values are passed" ), 500: openapi.Response( "Internal Server Error- Error while processing the POST Request Function." ) }) def post(self, request): data = request.data teacher = data.get('teacher', None) section = data.get('section', None) if not teacher or not section: errors = ["teacher and sction ID's are required"] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) sections = models.Section.objects.filter( Q(id=int(section)) & Q(is_active=True)) if not len(sections): errors = ["Invalid sction id"] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) section = sections[0] teachers = teachers_models.Teacher.objects.filter( Q(id=int(teacher)) & Q(is_active=True)) if not len(teachers): errors = ["Invalid teacher id"] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) teacher = teachers[0] if section.class_teacher == teacher: errors = ["teacher is already assigned to this section"] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) section.class_teacher = teacher section.save() msgs = ['successfully assigned class teacher'] return Response({'details': msgs}, status.HTTP_200_OK)
class OptionalMethodViewSet(viewsets.ViewSet): @swagger_auto_schema( responses={200: openapi.Response("OK", OptionalMethodSerializer)}) def retrieve(self, request, pk=None): return Response({"optional": None})
class CompanyViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = Company.objects.all().order_by('-id') serializer_class = CompanySerializer permission_classes = [] response_schema_dict = { "200": openapi.Response(description="source=app and fieldset=autocomplete", examples={ "application/json": { "count": 1, "next": "", "previous": "", "results": [{ "id": 1, "name": "string" }] } }), "200:ok": openapi.Response( description="source == 'web' and fieldset == 'principal'", examples={ "application/json": { "count": 1, "next": "", "previous": "", "results": [{ "id": 1, "name": "string", "rid": "53973782-0198-4511-9d5e-ab11b50f780e" }] } }), } source_param = openapi.Parameter('source', openapi.IN_QUERY, description="Enter source param", type=openapi.TYPE_STRING) fieldset_param = openapi.Parameter('fieldset', openapi.IN_QUERY, description="Enter fieldset param", type=openapi.TYPE_STRING) domain_param = openapi.Parameter('domain', openapi.IN_QUERY, description="Enter domain param", type=openapi.TYPE_STRING) longitude_param = openapi.Parameter('longitude', openapi.IN_QUERY, description="Enter longitude param", type=openapi.TYPE_STRING) latitude_param = openapi.Parameter('latitude', openapi.IN_QUERY, description="Enter latitude param", type=openapi.TYPE_STRING) name_param = openapi.Parameter('name', openapi.IN_QUERY, description="Enter company name", type=openapi.TYPE_STRING) qr_id_param = openapi.Parameter('qr_id', openapi.IN_QUERY, description="Enter company qr_id", type=openapi.TYPE_STRING) @swagger_auto_schema(manual_parameters=[ source_param, fieldset_param, domain_param, longitude_param, latitude_param, name_param, qr_id_param ], responses=response_schema_dict) def list(self, request, *args, **kwargs): queryset = Company.objects.all().order_by('-id') name = self.request.query_params.get('name', None) qr_id = self.request.query_params.get('qr_id', None) source = self.request.query_params.get('source', None) fieldset = self.request.query_params.get('fieldset', None) domain = self.request.query_params.get('domain', None) if source == 'app' and fieldset == 'autocomplete': page = self.paginate_queryset(queryset) serializer = CompanyAutoCompleteListSerializer(page, many=True) response = self.get_paginated_response(serializer.data) return response if source == 'web' and fieldset == 'principal': queryset = queryset.filter(category=1) page = self.paginate_queryset(queryset) serializer = PrincipalCompanyListSerializer(page, many=True) response = self.get_paginated_response(serializer.data) return response if source == 'web' and fieldset == 'name': queryset = queryset.filter(name=name) page = self.paginate_queryset(queryset) serializer = CompanySerializer(page, many=True) response = self.get_paginated_response(serializer.data) return response if source == 'app' and fieldset == 'domain': if not domain: raise ValidationError({"message": "Domain Param is required"}) queryset = queryset.filter(domain=domain) page = self.paginate_queryset(queryset) serializer = CompanyDomainListSerializer(page, many=True) response = self.get_paginated_response(serializer.data) return response if name is not None: queryset = queryset.filter(name__icontains=name) if qr_id: queryset = queryset.filter(qr_id=qr_id) page = self.paginate_queryset(queryset) serializer = CompanySerializer(page, many=True) response = self.get_paginated_response(serializer.data) return response @swagger_auto_schema(request_body=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'employer_set': openapi.Schema(type=openapi.TYPE_ARRAY, items=openapi.TYPE_OBJECT, description='string'), 'name': openapi.Schema(type=openapi.TYPE_STRING, description='string'), 'office_address': openapi.Schema(type=openapi.TYPE_STRING, description='string'), 'pincode': openapi.Schema(type=openapi.TYPE_STRING, description='string'), 'gstin': openapi.Schema(type=openapi.TYPE_STRING, description='string'), 'average_monthly_salary_payout': openapi.Schema(type=openapi.TYPE_INTEGER, description='integer'), 'monthly_salary_day': openapi.Schema(type=openapi.TYPE_INTEGER, description='integer'), 'industry': openapi.Schema(type=openapi.TYPE_INTEGER, description='integer'), 'employee_range': openapi.Schema(type=openapi.TYPE_INTEGER, description='integer'), 'city': openapi.Schema(type=openapi.TYPE_INTEGER, description='integer'), 'state': openapi.Schema(type=openapi.TYPE_INTEGER, description='integer'), })) def create(self, request): company_data = request.data employers_data = company_data.get('employer_set') # employers_data data validation for employer in employers_data: username = employer.get('username', None) if username: user_object = User.objects.filter(username=username).first() if user_object: raise ValidationError( {"message": "User already exists with this username."}) department = employer.get('department', None) if department: try: Department.objects.get(id=department) except: raise ValidationError( {"message": "department does not exist."}) designation = employer.get('designation', None) if designation: try: Designation.objects.get(id=designation) except: raise ValidationError( {"message": "designation does not exist."}) # company data validation company_name = company_data.get('name', None) industry = company_data.get('industry', None) employee_range = company_data.get('employee_range', None) office_address = company_data.get('office_address', None) city = company_data.get('city', None) state = company_data.get('state', None) pincode = company_data.get('pincode', None) gstin = company_data.get('gstin', None) if not company_name: raise ValidationError({"message": "company_name is required."}) if not industry: raise ValidationError({"message": "industry is required."}) if not employee_range: raise ValidationError({"message": "employee_range is required."}) if not office_address: raise ValidationError({"message": "office_address is required."}) if not city: raise ValidationError({"message": "city is required."}) if not state: raise ValidationError({"message": "state is required."}) if not pincode: raise ValidationError({"message": "pincode is required."}) if not gstin: raise ValidationError({"message": "gstin is required."}) if company_name: company = Company.objects.filter(name=company_name) if len(company) > 0: raise ValidationError( {"message": "company exists with the same name"}) if industry: try: Industry.objects.get(id=industry) except: raise ValidationError({"message": "Industry does not exist."}) if employee_range: try: EmployeeRange.objects.get(id=employee_range) except: raise ValidationError( {"message": "employee_range does not exist."}) if city: try: City.objects.get(id=city) except: raise ValidationError({"message": "city does not exist."}) if state: try: State.objects.get(id=state) except: raise ValidationError({"message": "state does not exist."}) serializer = CompanySerializer(data=company_data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) raise ValidationError({"message": "Invalid company arguments"})
class JoinRequestsStudent(views.APIView): serializer_class = student_serializers.StudentSerializer authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) @swagger_auto_schema( responses={ 200: openapi.Response("OK- Successful GET Request"), 401: openapi.Response("Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired"), 500: openapi.Response("Internal Server Error- Error while processing the GET Request Function.") }, manual_parameters=[ openapi.Parameter(name="dept_id", in_="query", type=openapi.TYPE_STRING), openapi.Parameter(name="sec_id", in_="query", type=openapi.TYPE_STRING), ] ) def get(self, request): query_params = self.request.query_params dept_id = query_params.get('dept_id', None) sec_id = query_params.get('sec_id',None) if not dept_id: errors = [ 'dept_id is not passed' ] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) if not sec_id: errors = [ 'sec_id is not passed' ] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) departments = models.Department.objects.filter(Q(user__id=request.user.id) & Q(department_id=dept_id)) if not len(departments): errors = [ 'Invalid dept_id' ] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) students = student_models.Student.objects.filter( Q(requested_section__id = sec_id) & Q(is_active=True)& Q(requested_section__of_class__department__department_id=dept_id) ) if not len(students): errors = [ f'no request pending for this section_id: {sec_id}' ] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) serializer = student_serializers.StudentSerializer(students, many=True) return Response(serializer.data, status.HTTP_200_OK) @swagger_auto_schema( request_body = openapi.Schema( title = "Join Department request", type=openapi.TYPE_OBJECT, properties={ 'dept_id': openapi.Schema(type=openapi.TYPE_STRING), 'org_id': openapi.Schema(type=openapi.TYPE_STRING), 'students': openapi.Schema(type=openapi.TYPE_STRING), } ), responses={ 200: openapi.Response("OK- Successful POST Request"), 401: openapi.Response("Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired"), 422: openapi.Response("Unprocessable Entity- Make sure that all the required field values are passed"), 500: openapi.Response("Internal Server Error- Error while processing the POST Request Function.") } ) @validate_org @validate_dept def post(self, request, *args, **kwargs): data = request.data dept_id = data.get('dept_id',"") org_id = kwargs.get("org_id") students = str(data.get("students", "[]")) if not dept_id: errors = [ 'dept_id is not passed' ] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) if len(students) < 3: errors = [ "students not passed or students format should be like this. [1, 2, 3] where 1, 2 and 3 are student ID's" ] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) departments = models.Department.objects.filter(Q(user__id=request.user.id) & Q(department_id=dept_id)) if not len(departments): errors = [ 'Invalid dept_id' ] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) try: students = students.replace(" ", "") students = students[1:len(students) - 1].split(",") students = [int(i) for i in students] except Exception as e: errors = [ "students format should be like this. [1, 2, 3] where 1, 2 and 3 are student ID's", str(e) ] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) stud_qs = student_models.Student.objects.filter(is_active=True) valid_students = [] for i in students: temp_stud = stud_qs.filter(id=i) if not len(temp_stud): errors = [ 'Invalid student ID' ] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) temp_stud = temp_stud[0] if not temp_stud.requested_section: errors = [ 'no students in waiting list' ] return Response({'details': errors}, status.HTTP_400_BAD_REQUEST) valid_students.append(temp_stud) for temp_stud in valid_students: temp_stud.section = temp_stud.requested_section temp_stud.requested_section = None temp_stud.save() return Response({"details": ["Successfully accepted all provided requests."]}, status.HTTP_200_OK)