Example #1
0
class SnippetList(generics.ListCreateAPIView):
    """SnippetList classdoc"""

    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer

    parser_classes = (FormParser, CamelCaseJSONParser, FileUploadParser)
    renderer_classes = (CamelCaseJSONRenderer, )
    swagger_schema = CamelCaseOperationIDAutoSchema

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)

    def post(self, request, *args, **kwargs):
        """post method docstring"""
        return super(SnippetList, self).post(request, *args, **kwargs)

    @swagger_auto_schema(
        operation_id="snippets_delete_bulk",
        request_body=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            properties={
                "body":
                openapi.Schema(
                    type=openapi.TYPE_STRING,
                    description=
                    "this should not crash (request body on DELETE method)",
                )
            },
        ),
    )
    def delete(self, *args, **kwargs):
        """summary from docstring
Example #2
0
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)
Example #3
0
class FCMDeviceViewSet(viewsets.ModelViewSet):

    queryset = FCMDevice.objects.all().order_by('-id')
    serializer_class = serializers.FCMDeviceSerializer
    permission_classes = []

    @swagger_auto_schema(request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        properties={
            'fcm_registration_token':
            openapi.Schema(type=openapi.TYPE_STRING, description='string'),
            'employee_id':
            openapi.Schema(type=openapi.TYPE_INTEGER, description='integer'),
            'device_type':
            openapi.Schema(type=openapi.TYPE_STRING, description='string'),
        }))
    def create(self, request):
        fcm_registration_token = request.data.get('fcm_registration_token',
                                                  None)
        device_type = request.data.get('device_type', None)
        employee_id = request.data.get('employee_id', None)
        if not fcm_registration_token:
            raise ValidationError(
                {"message": "fcm_registration_token is required field"})
        if not device_type:
            raise ValidationError({"message": "device_type is required field"})
        if device_type not in ['web', 'android', 'ios']:
            raise ValidationError(
                {"message": "Invalid device_type is required field"})
        if not employee_id:
            raise ValidationError({"message": "employee_id is required field"})
        if employee_id:
            employee = Employee.objects.filter(id=employee_id,
                                               deleted_at=None).first()
            if not employee:
                raise ValidationError({"message": "Employee Does Not Exists."})
        fcm_obj = FCMDevice.objects.filter(user=employee.user).first()
        if fcm_obj:
            fcm_obj.registration_id = fcm_registration_token
            fcm_obj.device_type = device_type
            fcm_obj.active = True
            fcm_obj.save()
            return JsonResponse({"status": "True"})
        device_data = {
            "registration_id": fcm_registration_token,
            "user": employee.user.id,
            "type": device_type,
            "active": True
        }
        serializer = serializers.FCMDeviceSerializer(data=device_data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data)
        raise ValidationError({"message": "Invalid arguments"})
Example #4
0
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)
Example #5
0
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)
Example #6
0
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."})
def test_optional_return_type(py_type, expected_type):
    class OptionalMethodSerializer(serializers.Serializer):
        x = serializers.SerializerMethodField()

        def get_x(self, instance):
            pass

        # Add the type annotation here in order to avoid a SyntaxError in py27
        get_x.__annotations__["return"] = typing.Optional[py_type]

    class OptionalMethodViewSet(viewsets.ViewSet):
        @swagger_auto_schema(
            responses={200: openapi.Response("OK", OptionalMethodSerializer)})
        def retrieve(self, request, pk=None):
            return Response({"optional": None})

    router = routers.DefaultRouter()
    router.register(r"optional", OptionalMethodViewSet,
                    **_basename_or_base_name("optional"))

    generator = OpenAPISchemaGenerator(
        info=openapi.Info(title="Test optional parameter",
                          default_version="v1"),
        patterns=router.urls,
    )
    swagger = generator.get_schema(None, True)
    property_schema = swagger["definitions"]["OptionalMethod"]["properties"][
        "x"]
    assert property_schema == openapi.Schema(title="X",
                                             type=expected_type,
                                             readOnly=True)
def test_choice_field(choices, expected_type):
    class DetailSerializer(serializers.Serializer):
        detail = serializers.ChoiceField(choices)

    class DetailViewSet(viewsets.ViewSet):
        @swagger_auto_schema(
            responses={200: openapi.Response("OK", DetailSerializer)})
        def retrieve(self, request, pk=None):
            return Response({"detail": None})

    router = routers.DefaultRouter()
    router.register(r"details", DetailViewSet,
                    **_basename_or_base_name("details"))

    generator = OpenAPISchemaGenerator(
        info=openapi.Info(title="Test generator", default_version="v1"),
        patterns=router.urls,
    )

    swagger = generator.get_schema(None, True)
    property_schema = swagger["definitions"]["Detail"]["properties"]["detail"]

    assert property_schema == openapi.Schema(title="Detail",
                                             type=expected_type,
                                             enum=choices)
Example #9
0
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)
Example #10
0
class UserProfileViewSet(viewsets.ModelViewSet):
    serializer_class = serializers.UserProfileSerializer
    queryset = models.UserProfile.objects.all()
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]

    @swagger_auto_schema(
        request_body=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            required=['username', 'password'],
            properties={
                'username':
                openapi.Schema(type=openapi.TYPE_STRING,
                               description='用户名(或手机号)'),
                'password':
                openapi.Schema(type=openapi.TYPE_STRING),
            }),
        responses={'201': openapi.Schema(type=openapi.TYPE_OBJECT)},
        operation_summary='登录或注册')
    @action(detail=False,
            methods=['POST'],
            permission_classes=[permissions.AllowAny])
    def sign_up(self, request):
        """登录或注册功能, 如果用户名和密码存在则登录, 反之则创建新用户, 两种操作都会返回一个token"""
        username = request.data.get('username')
        password = request.data.get('password')
        if User.objects.filter(username=username).exists():
            # user_obj: User = User.objects.get(username=username)
            user_obj: User = authenticate(request,
                                          username=username,
                                          password=password)
            if user_obj is None:
                return Response({
                    'successful': False,
                    'detail': '登录失败,用户名或密码错误'
                })
        else:
            user_obj: User = User.objects.create_user(username=username,
                                                      password=password)
        token, created = Token.objects.get_or_create(user=user_obj)
        return Response({'successful': True, 'token': token.key})
Example #11
0
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)
Example #12
0
class UserList(APIView):
    """UserList cbv classdoc"""

    @swagger_auto_schema(
        query_serializer=UserListQuerySerializer,
        responses={200: UserSerializerrr(many=True)},
        tags=["Users"],
    )
    def get(self, request):
        queryset = User.objects.all()
        serializer = UserSerializerrr(queryset, many=True)
        return Response(serializer.data)

    @swagger_auto_schema(
        operation_description="apiview post description override",
        request_body=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            required=["username"],
            properties={"username": openapi.Schema(type=openapi.TYPE_STRING)},
        ),
        security=[],
        tags=["Users"],
    )
    def post(self, request):
        serializer = UserSerializerrr(request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)

    @swagger_auto_schema(
        operation_id="users_dummy",
        operation_description="dummy operation",
        tags=["Users"],
    )
    def patch(self, request):
        pass
Example #13
0
def test_json_field():
    class TestJSONFieldSerializer(serializers.Serializer):
        json = serializers.JSONField()

    class JSONViewSet(viewsets.ModelViewSet):
        serializer_class = TestJSONFieldSerializer

    router = routers.DefaultRouter()
    router.register(r"jsons", JSONViewSet, **_basename_or_base_name("jsons"))

    generator = OpenAPISchemaGenerator(
        info=openapi.Info(title="Test json field generator",
                          default_version="v1"),
        patterns=router.urls,
    )

    swagger = generator.get_schema(None, True)
    property_schema = swagger["definitions"]["TestJSONField"]["properties"][
        "json"]
    assert property_schema == openapi.Schema(title="Json",
                                             type=openapi.TYPE_OBJECT)
Example #14
0
def test_nested_choice_in_array_field(choices, field, expected_type):

    # Create a model class on the fly to avoid warnings about using the several
    # model class name several times
    model_class = type(
        "%sModel" % field.__name__,
        (fake_models.FakeModel, ),
        {
            "array":
            postgres_fields.ArrayField(
                field(choices=((i, "choice %s" % i) for i in choices))),
            "__module__":
            "test_models",
        },
    )

    class ArraySerializer(serializers.ModelSerializer):
        class Meta:
            model = model_class
            fields = ("array", )

    class ArrayViewSet(viewsets.ModelViewSet):
        serializer_class = ArraySerializer

    router = routers.DefaultRouter()
    router.register(r"arrays", ArrayViewSet,
                    **_basename_or_base_name("arrays"))

    generator = OpenAPISchemaGenerator(
        info=openapi.Info(title="Test array model generator",
                          default_version="v1"),
        patterns=router.urls,
    )

    swagger = generator.get_schema(None, True)
    property_schema = swagger["definitions"]["Array"]["properties"]["array"][
        "items"]
    assert property_schema == openapi.Schema(title="Array",
                                             type=expected_type,
                                             enum=choices)
Example #15
0
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)
Example #16
0
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)
Example #17
0
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)
Example #18
0
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"})
Example #19
0
class AttendanceViewSet(viewsets.ModelViewSet):
    queryset = Attendance.objects.filter(
        employee__deleted_at=None).order_by('-id')
    serializer_class = AttendanceSerializer
    permission_classes = []

    employee_id_param = openapi.Parameter('employee_id',
                                          openapi.IN_QUERY,
                                          description="Enter employee ID",
                                          type=openapi.TYPE_INTEGER)
    source_param = openapi.Parameter('source',
                                     openapi.IN_QUERY,
                                     description="Enter source",
                                     type=openapi.TYPE_STRING)
    date_param = openapi.Parameter('fieldset',
                                   openapi.IN_QUERY,
                                   description="Enter fieldset",
                                   type=openapi.TYPE_STRING)

    @swagger_auto_schema(manual_parameters=[employee_id_param])
    def list(self, request, *args, **kwargs):
        queryset = Attendance.objects.filter(
            employee__deleted_at=None).order_by('-id')
        source = self.request.query_params.get('source', None)
        fieldset = self.request.query_params.get('fieldset', None)
        employee_id = self.request.query_params.get('employee_id', None)
        if source == "app" and fieldset == "statement":
            if employee_id:
                queryset = queryset.filter(
                    employee=employee_id,
                    date__month=datetime.datetime.now().month,
                    date__year=datetime.datetime.now().year,
                )
            serializer = AttendanceStatementListSerializer(queryset, many=True)
            employee_obj = Employee.objects.filter(id=employee_id,
                                                   deleted_at=None).first()
            if employee_obj:
                last_statement = employee_obj.statement_set.all().order_by(
                    'id').last()

            statements = Statement.objects.filter(
                employee=employee_obj,
                date__month=datetime.datetime.now().month,
                date__year=datetime.datetime.now().year,
            )
            withdraw = sum([s.withdraw for s in statements if s.withdraw])
            return Response({
                "total_due": float(withdraw) if withdraw else 0.0,
                "statements": serializer.data
            })
        raise ValidationError({"message": "Invalid arguments"})

    response_schema_dict = {
        "200":
        openapi.Response(description="custom 200 description",
                         examples={
                             "application/json": {
                                 "status": True,
                                 "message": "Attendance marked successfully",
                                 "employee": {
                                     "daily_salary": 0.0,
                                     "balance": 0.0
                                 }
                             }
                         }),
        "400":
        openapi.Response(
            description="Duplicate attendance error",
            examples={
                "application/json": {
                    "status": False,
                    "message": "Attendance already created for this employee.",
                    "employee": {}
                }
            }),
        "400:bad":
        openapi.Response(description="custom 400 description",
                         examples={
                             "application/json": {
                                 "status": False,
                                 "message": "Invalid arguments",
                                 "employee": {}
                             }
                         }),
    }

    @swagger_auto_schema(request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        properties={
            'status':
            openapi.Schema(type=openapi.TYPE_STRING, description='string'),
            'duration':
            openapi.Schema(type=openapi.TYPE_STRING, description='string'),
            'start_time':
            openapi.Schema(type=openapi.TYPE_STRING, description='string'),
            'end_time':
            openapi.Schema(type=openapi.TYPE_STRING, description='string'),
            'qr_code_scanned':
            openapi.Schema(type=openapi.TYPE_BOOLEAN, description='boolean'),
            'face_detected':
            openapi.Schema(type=openapi.TYPE_BOOLEAN, description='boolean'),
            'location':
            openapi.Schema(type=openapi.TYPE_STRING, description='string'),
            'employee':
            openapi.Schema(type=openapi.TYPE_INTEGER, description='integer'),
            'company':
            openapi.Schema(type=openapi.TYPE_INTEGER, description='integer'),
            'image':
            openapi.Schema(type=openapi.TYPE_STRING, description='string'),
        }),
                         responses=response_schema_dict)
    def create(self, request):
        today_date = str(datetime.datetime.now().date())
        date = request.data.get('date', None)
        duration = request.data.get('duration', None)
        start_at = request.data.get('start_time', None)
        end_at = request.data.get('end_time', None)
        qr_code_scanned = request.data.get('qr_code_scanned', None)
        face_detected = request.data.get('face_detected', None)
        work_location = request.data.get('location', None)
        employee = request.data.get('employee', None)
        company = request.data.get('company', None)
        image = request.data.get('image', None)
        status = request.data.get('status', None)
        if not employee:
            raise ValidationError({
                "status": False,
                "message": "Employee is Required.",
                "employee": {}
            })
        if not company:
            raise ValidationError({
                "status": False,
                "message": "Company is Required.",
                "employee": {}
            })
        if not status:
            raise ValidationError({
                "status": False,
                "message": "Status is Required.",
                "employee": {}
            })
        if date:
            try:
                datetime.datetime.strptime(date, "%Y-%m-%d")
            except:
                raise ValidationError({
                    "status": False,
                    "message": "Date format should be like %Y-%m-%d.",
                    "employee": {}
                })
        if start_at or end_at:
            try:
                time.strptime(start_at, "%I:%M %p")
                time.strptime(end_at, "%I:%M %p")
            except:
                raise ValidationError({
                    "status": False,
                    "message": "Time format should be like 'HH:MM AM/PM'",
                    "employee": {}
                })
        if status:
            if status not in ['present', 'absent']:
                raise ValidationError({
                    "status": False,
                    "message": "Invalid Status",
                    "employee": {}
                })
        if duration:
            if duration not in ['full_day', 'half_day']:
                raise ValidationError({
                    "status": False,
                    "message": "Invalid Duration",
                    "employee": {}
                })
        if work_location:
            if work_location not in ['office', 'home', 'other']:
                raise ValidationError({
                    "status": False,
                    "message": "Invalid Work Location.",
                    "employee": {}
                })

        employee_obj = Employee.objects.filter(id=employee,
                                               deleted_at=None).first()
        company_obj = Company.objects.get(id=company)

        # to find working day
        is_working = find_employee_is_working(employee_obj)

        # check attendance already exists
        attendance = Attendance.objects.all().filter(
            date=date if date else today_date,
            employee_id=employee,
            company_id=company)
        if attendance:
            raise ValidationError({
                "status": False,
                "message":
                "Today's allowance has already been added to your wallet",
                "employee": {},
                "company": {},
                "working_day": is_working,
                "attendance_marked": True
            })

        if status == 'absent':
            attendance_data = {
                "date": date if date else today_date,
                "status": status,
                "employee": employee,
                "company": company,
            }
            serializer = AttendanceSerializer(data=attendance_data)
            if serializer.is_valid():
                serializer.save()
                response_data = {
                    "status": True,
                    "message": "Attendance marked successfully",
                    "employee": {
                        "id": int(employee_obj.id),
                        "name": str(employee_obj.name),
                        "balance": float(employee_obj.balance) \
                            if employee_obj.balance else 0.0,
                        "daily_salary": float(employee_obj.daily_salary) \
                            if employee_obj.daily_salary else 0.0,
                        "bank_account_number": str(employee_obj.bank_account_number) \
                            if employee_obj.bank_account_number else "",
                        "ifs": {
                            "code": str(employee_obj.ifs.code) if employee_obj.ifs else "",
                            "bank": {
                                "name": str(employee_obj.ifs.bank.name) \
                                    if employee_obj.ifs else ""
                            }
                        }
                    },
                    "company": {
                        "id": int(employee_obj.company.id) if employee_obj.company else None,
                        "Name": str(employee_obj.company.name) if employee_obj.company else ""
                    },
                    "working_day": is_working,
                    "attendance_marked": True
                }
                return JsonResponse(response_data)
            raise ValidationError({
                "status": False,
                "message": "Invalid arguments",
                "employee": {},
                "company": {},
                "working_day": is_working,
                "attendance_marked": False
            })
        else:
            attendance_data = {
                "date": date if date else today_date,
                "status": status,
                "duration": duration,
                "start_at": start_at,
                "end_at": end_at,
                "work_location": work_location,
                "qr_code_scanned": qr_code_scanned,
                "face_detected": face_detected,
                "employee": employee,
                "company": company,
                "image": image if image else '',
            }
            serializer = AttendanceSerializer(data=attendance_data)
            if serializer.is_valid():
                serializer.save()
                try:
                    # update 'balance' of employee after attendance created
                    employee_obj.balance = float(employee_obj.balance) + float(
                        employee_obj.daily_salary)
                    employee_obj.save()
                    response_data = {
                        "status": True,
                        "message": "Attendance marked successfully",
                        "employee": {
                            "id": int(employee_obj.id),
                            "name": str(employee_obj.name),
                            "balance": float(employee_obj.balance) \
                                if employee_obj.balance else 0.0,
                            "daily_salary": float(employee_obj.daily_salary) \
                                if employee_obj.daily_salary else 0.0,
                            "bank_account_number": str(employee_obj.bank_account_number) \
                                if employee_obj.bank_account_number else "",
                            "ifs": {
                                "code": str(employee_obj.ifs.code) if employee_obj.ifs else "",
                                "bank": {
                                    "name": str(employee_obj.ifs.bank.name) \
                                        if employee_obj.ifs else ""
                                }
                            }
                        },
                        "company": {
                            "id": int(employee_obj.company.id) if employee_obj.company else None,
                            "Name": str(employee_obj.company.name) if employee_obj.company else ""
                        },
                        "working_day": is_working,
                        "attendance_marked": True
                    }
                    return JsonResponse(response_data)
                except:
                    raise ValidationError({
                        "status": False,
                        "message": "Something Went Wrong",
                        "employee": {},
                        "company": {},
                        "working_day": is_working,
                        "attendance_marked": False
                    })
            print(str(serializer.errors))
            raise ValidationError({
                "status": False,
                "message": "Invalid arguments",
                "employee": {},
                "company": {},
                "working_day": is_working,
                "attendance_marked": False
            })
Example #20
0
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)
Example #21
0
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"})
Example #22
0
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)
Example #23
0
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)
Example #24
0
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)
Example #25
0
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)
Example #26
0
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)
Example #27
0
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)
Example #28
0
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)
Example #29
0
class VerifierViewSet(viewsets.ModelViewSet):
    queryset = Verifier.objects.all().order_by('-id')
    serializer_class = serializers.VerifierSerializer
    permission_classes = []

    email_param = openapi.Parameter(
        'email', openapi.IN_QUERY,
        description="Enter Email",
        type=openapi.TYPE_STRING
    )

    @swagger_auto_schema(manual_parameters=[email_param])
    def list(self, request, *args, **kwargs):
        queryset = Verifier.objects.all().order_by('-id')
        email = self.request.query_params.get('email', None)
        if email is not None:
            queryset = queryset.filter(email__icontains=email)
        page = self.paginate_queryset(queryset)
        serializer = serializers.VerifierSerializer(page, many=True)
        response = self.get_paginated_response(serializer.data)
        return response

    @swagger_auto_schema(request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        properties={
            'employee_id': openapi.Schema(
                type=openapi.TYPE_STRING, description='string'),
            'verifiers': openapi.Schema(
                type=openapi.TYPE_STRING, description='array of string')
        }
    ))
    def create(self, request, *args, **kwargs):
        employee_id = request.data.get('employee_id', None)
        verifiers = request.data.get('verifiers', None)     # Array of string
        if not employee_id:
            raise ValidationError({
                "status": "False",
                "message": "EmployeeId is required"})
        if employee_id:
            employee = Employee.objects.filter(id=employee_id, deleted_at=None).first()
            if not employee:
                raise ValidationError({
                    "status": "False",
                    "message": "Employee does not exists"
                })
        if not verifiers:
            raise ValidationError({
                "status": "False",
                "message": "Verifiers list is required"})
        if verifiers:
            if len(verifiers) < 1:
                raise ValidationError({
                    "status": "False",
                    "message": "No Verifiers in list."})
        for verifier_email in verifiers:
            if verifier_email.split('@')[1] == str(employee.email).split('@')[1]:
                verifier_obj = Verifier.objects.create(
                    email=verifier_email
                )
                verifier_obj.employee.add(employee)
                verifier_obj.save()
        return JsonResponse({
            "status": "True",
            "message": "Verifiers created successfully"
        })
Example #30
0
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)