示例#1
0
class CouponViewSet(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="uuid", in_="query", type=openapi.TYPE_STRING),
        ]
    )
    def get(self, request, *args, **kwargs):
        query_params = self.request.query_params
        uuid = query_params.get('uuid', None)
        
        coupons = coupons_models.Coupon.objects.filter(Q(user=request.user) & Q(is_active=True)).order_by("-created_at")

        if uuid:
            coupons = coupons.filter(uuid=uuid)

        serializer = coupons_serializers.CouponSerializer(coupons, many=True)
        data = {
            "coupons": serializer.data
        }
        return response.Response(data, status.HTTP_200_OK)

    @swagger_auto_schema(
        request_body = openapi.Schema(
            title = "Create Coupon",
            type=openapi.TYPE_OBJECT,
            properties={
                'amount': openapi.Schema(type=openapi.TYPE_NUMBER),
            }
        ),
        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.")
        }
    )
    @coupons_available
    def post(self, request, *args, **kwargs):
        data = request.data
        amount = data.get("amount", None)

        if kwargs.get("available_coupons", 0) < 1:
            errors = {
                'message': 'No coupons left',
            }
            return response.Response(errors, status.HTTP_400_BAD_REQUEST)

        if not amount or float(amount) <= 0:
            errors = {
                'message': 'Invalid amount',
            }
            return response.Response(errors, status.HTTP_400_BAD_REQUEST)

        data = {
            "user": request.user.id,
            "amount": float(amount)
        }
        
        serializer = coupons_serializers.CouponSerializer(data=data)

        if serializer.is_valid():
            serializer.save()

            details = {
                "message": "Coupon Successfully created.",
                "coupon": serializer.data,
            }
            return response.Response(details, status.HTTP_201_CREATED)    

        errors = {
            'message': str(serializer.errors),
        }
        return response.Response(errors, status.HTTP_400_BAD_REQUEST)

    @swagger_auto_schema(
        request_body = openapi.Schema(
            title = "Update Coupon",
            type=openapi.TYPE_OBJECT,
            properties={
                'amount': openapi.Schema(type=openapi.TYPE_NUMBER),
                'valid_from': openapi.Schema(type=openapi.FORMAT_DATE),
                'valid_till': openapi.Schema(type=openapi.FORMAT_DATE),
                'payment_methods': openapi.Schema(type=openapi.TYPE_STRING),
                'message': openapi.Schema(type=openapi.TYPE_STRING),
                'is_available': openapi.Schema(type=openapi.TYPE_BOOLEAN),
                'paid': 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.")
        },
        manual_parameters=[
            openapi.Parameter(name="uuid", in_="query", type=openapi.TYPE_STRING),
        ]
    )
    def put(self, request, *args, **kwargs):
        query_params = self.request.query_params
        data = request.data
        uuid = query_params.get('uuid', "")
        
        coupons = coupons_models.Coupon.objects.filter(Q(user=request.user) & Q(uuid=str(uuid)) & Q(is_active=True))

        if not len(coupons):
            errors = {
                'message': 'Invalid uuid',
            }
            return response.Response(errors, status.HTTP_400_BAD_REQUEST)
        
        coupon = coupons[0]
        serializer = coupons_serializers.CouponSerializer(instance=coupon, data=data, partial=True)

        if serializer.is_valid():
            serializer.save()
            details = {
                "message": "Coupon Successfully updated.",
            }
            return response.Response(details, status.HTTP_200_OK)

        errors = {
            'message': str(serializer.errors),
        }
        return response.Response(errors, status.HTTP_400_BAD_REQUEST)


    @swagger_auto_schema(
        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.")
        },
        manual_parameters=[
            openapi.Parameter(name="uuid", in_="query", type=openapi.TYPE_STRING),
        ]
    )
    def delete(self, request, *args, **kwargs):
        query_params = self.request.query_params
        uuid = query_params.get('uuid', "")
        
        coupons = coupons_models.Coupon.objects.filter(Q(user=request.user) & Q(uuid=str(uuid)) & Q(is_active=True))

        if not len(coupons):
            errors = {
                'message': 'Invalid uuid',
            }
            return response.Response(errors, status.HTTP_400_BAD_REQUEST)
        
        coupon = coupons[0]
        coupon.is_active = False
        coupon.save()

        details = {
            "message": "Coupon Successfully deleted.",
        }
        return response.Response(details, status.HTTP_200_OK)
示例#2
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)
示例#3
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)
示例#4
0
class CapabilitiesViewsetMixin:
    """Mixin that allows a ViewSet to take advantage of the RBAC system
    """

    model = None

    @classmethod
    def add_to_router(cls, router):
        """Will return a nested router if the view model has role fields on it
        """
        if cls.model and hasattr(cls.model, '__implicit_role_fields'):
            return cls.add_as_nested_router(router)
        return super().add_to_router(router)

    @classmethod
    def add_as_nested_router(cls, parent_router):
        """Adds the viewset to the parent_router and then returns a router instance to use under the viewset
        """
        router = super().add_as_nested_router(parent_router)
        # TODO: add the role viewset
        # if cls.model and hasattr(cls.model, '__implicit_role_fields'):
        #     RoleViewset.add_to_router(router)
        return router

    @swagger_auto_schema(method='get', manual_parameters=[
        openapi.Parameter(
            name='action', in_=openapi.IN_QUERY,
            type=openapi.TYPE_ARRAY,
            description='Filter to check only certain action(s) on the model\'s accessor.',
            items=openapi.Items(type=openapi.TYPE_STRING),
            collection_format='multi'
        )
    ])
    @drf_action(detail=True, methods=['GET'], url_path='capabilities')
    def capabilities(self, request, **kwargs):
        """
        ===
        title: Get Capable Actions for the {verbose_name} Resource
        ---
        Returns a list of actions and whether or not the current user has permission to perform
        those actions against the given resource.
        """
        lookup_kwarg = self.lookup_url_kwarg
        kwarg_value = kwargs.get(lookup_kwarg, None)
        if not kwarg_value:
            raise APIException(
                f'Could not find URL lookup \'{lookup_kwarg}\' in the URL parameters. Please '
                'note the attempted URL and contact the Babka team to fix this server issue.'
            )
        try:
            instance = self.get_object(permission_check=False)
        except ObjectDoesNotExist:
            raise NotFound(
                f'A matching {self.model._meta.verbose_name} could not be found. If this is '
                'a recurring issue, please contact the Babka team.'
            )

        method_list = request.GET.getlist('action', [])
        if not method_list:
            # If the request does not specify what actions to check, then we try to inspect the
            # instance's model accessor to get _all possible_ actions to test each of them
            accessor = access_registry[self.model](request.user, instance=instance)
            raw_methods = inspect.getmembers(accessor, predicate=inspect.ismethod)
            method_list = [x.replace('can_', '') for x, _ in raw_methods if x.startswith('can_')]
        logger.debug('capabilities for "%s" for actions "%s" against "%s"', request.user, method_list, instance)
        accessor = instance_to_accessor(instance)(request.user, request=request, instance=instance, view=self)
        capabilities = accessor.get_user_capabilities(method_list=method_list)
        return Response({'username': request.user.username, 'capabilities': capabilities})

    def __getattr__(self, name):
        """
        Allows for the dynamic creation of a serializer class that returns the capabilities of a
        user for that specific object
        """
        if name == 'capabilities_serializer_class':
            accessor = access_registry.get(self.model, None)
            if not accessor:
                return None
            if self.model in _capabilities_serializer_classes:
                return _capabilities_serializer_classes[self.model]

            raw_methods = inspect.getmembers(accessor(self.request.user, view=self), predicate=inspect.ismethod)
            method_list = [x.replace('can_', '') for x, _ in raw_methods if x.startswith('can_')]
            attrs = {
                method: BooleanField(
                    read_only=True,
                    help_text=(
                        f'Describes whether or not the user can perform "{method}" actions '
                        f'against the given {self.model.__name__} instance.'
                    )
                ) for method in method_list
            }
            serializer_class = type(f'{self.model.__name__}CapabilitiesSerializer', (Serializer,), attrs)
            _capabilities_serializer_classes[self.model] = serializer_class

            return serializer_class
        return self.__getattribute__(name)
示例#5
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)
示例#6
0
        self.permission_classes = [permissions.IsAuthenticated]
        return super().create(request, *args, **kwargs)

    def list(self, request, *args, **kwargs):
        self.queryset = RepositoryTranslatedExample.objects.all()
        self.filter_class = TranslationsFilter
        return super().list(request, *args, **kwargs)


@method_decorator(
    name="retrieve",
    decorator=swagger_auto_schema(manual_parameters=[
        openapi.Parameter(
            "with_translation",
            openapi.IN_QUERY,
            description=
            "Boolean that allows you to download or not all translations",
            type=openapi.TYPE_BOOLEAN,
            default=True,
        ),
        openapi.Parameter(
            "of_the_language",
            openapi.IN_QUERY,
            description="Choose the language to be translated",
            type=openapi.TYPE_STRING,
            required=True,
        ),
        openapi.Parameter(
            "for_the_language",
            openapi.IN_QUERY,
            description="Which language will be translated",
            type=openapi.TYPE_STRING,
示例#7
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
            })
示例#8
0
class ClassViewSet(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="dept_id",
                                               in_="query",
                                               type=openapi.TYPE_STRING),
                         ])
    @is_organization
    def get(self, request, **kwargs):
        query_params = self.request.query_params
        org_id = kwargs.get('organization', None)
        dept_id = query_params.get('dept_id', None)

        qs = models.Class.objects.filter(
            is_active=True, department__organization__id=org_id.id)

        if dept_id:
            qs = qs.filter(department__department_id=dept_id,
                           department__organization__id=org_id.id)

        serializer = serializers.ClassSerializer(qs, many=True)
        return Response(serializer.data, status.HTTP_200_OK)

    @swagger_auto_schema(
        request_body=openapi.Schema(
            title="Create Class",
            type=openapi.TYPE_OBJECT,
            properties={
                'title': openapi.Schema(type=openapi.TYPE_STRING),
                '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, **kwargs):
        data = request.data
        title = data.get('title', "")

        department = kwargs.get("department")
        organization = kwargs.get("organization")

        if not title:
            errors = ['title is not passed']
            return Response({'details': errors}, status.HTTP_400_BAD_REQUEST)

        if models.Class.objects.filter(title=title,
                                       department=department).exists():
            errors = ['Class already exists']
            return Response({'details': errors}, status.HTTP_400_BAD_REQUEST)

        data_dict = {
            "title": str(title),
            "department": department.id,
        }
        serializer = serializers.ClassSerializer(data=data_dict)
        if serializer.is_valid():
            serializer.save()
            msgs = [serializer.data]
            return Response({'details': msgs}, status.HTTP_200_OK)

        errors = [str(serializer.errors)]
        return Response({'details': errors}, status.HTTP_400_BAD_REQUEST)

    @swagger_auto_schema(
        request_body=openapi.Schema(
            title="Delete Class",
            type=openapi.TYPE_OBJECT,
            properties={
                'id': openapi.Schema(type=openapi.TYPE_INTEGER),
                '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
        id = data.get('id', None)
        org_id = data.get('org_id', None)

        if not id:
            errors = ['id is not passed']
            return Response({'details': errors}, status.HTTP_400_BAD_REQUEST)

        classes = models.Class.objects.filter(
            Q(id=int(id)) & Q(is_active=True)
            & Q(department__organization__org_id=org_id))
        if not len(classes):
            errors = ['invalid id']
            return Response({'details': errors}, status.HTTP_400_BAD_REQUEST)

        classes = classes[0]
        classes.is_active = False
        classes.save()

        msgs = ["Successfully deleted class"]
        return Response({'details': msgs}, status.HTTP_200_OK)
示例#9
0
class Student(views.APIView):
    authentication_classes = (authentication.TokenAuthentication, )
    permission_classes = (permissions.IsAuthenticated, )
    serializer_class = serializers.StudentSerializer

    @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="section_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
        org_id = query_params.get('org_id', None)
        section_id = query_params.get('section_id', None)
        dept_id = query_params.get('dept_id', None)
        class_id = query_params.get('class_id', None)

        qs = models.Student.objects.filter(is_active=True)

        if section_id:
            qs = qs.filter(section__id=section_id)
        if org_id:
            qs = qs.filter(
                section__of_class__department__organization__org_id=org_id)
        if dept_id:
            qs = qs.filter(
                section__of_class__department__department_id=dept_id)
        if class_id:
            qs = qs.filter(section__of_class__id=class_id)

        serializer = serializers.StudentSerializer(qs, 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={
                'sec_join_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."
            )
        })
    def post(self, request):
        data = json.loads(json.dumps(request.data))
        sec_join_id = data.get("sec_join_id")

        if not sec_join_id:
            errors = ['Sec_Join_ID  is not passed']
            return Response({'details': errors}, status.HTTP_400_BAD_REQUEST)

        sections = section_models.Section.objects.filter(join_id=sec_join_id)
        if not len(sections):
            errors = ['Invalid section Join ID']
            return Response({'details': errors}, status.HTTP_400_BAD_REQUEST)

        section = sections[0]

        if not section.is_active:
            errors = ['Invalid section Join ID']
            return Response({'details': errors}, status.HTTP_400_BAD_REQUEST)

        if not section.accepting_req:
            errors = ['This section is currently not accepting requests']
            return Response({'details': errors}, status.HTTP_400_BAD_REQUEST)

        data.update({"user": request.user.id, "requested_section": section.id})

        serializer = self.serializer_class(data=data)

        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 Student",
            type=openapi.TYPE_OBJECT,
            properties={
                'org_id': openapi.Schema(type=openapi.TYPE_STRING),
                'name': openapi.Schema(type=openapi.TYPE_STRING),
                'phone': openapi.Schema(type=openapi.TYPE_INTEGER),
                'student_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."
            )
        })
    @put_student
    def put(self, request, *args, **kwargs):
        data = request.data

        data = pop_from_data(["is_active", "user", "section"], data)

        student = kwargs.get("student")
        serializer = serializers.StudentSerializer(student,
                                                   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 assignment']
        return Response({'details': msgs}, status.HTTP_200_OK)

    @swagger_auto_schema(
        request_body=openapi.Schema(
            title="Delete Student",
            type=openapi.TYPE_OBJECT,
            properties={
                'org_id': openapi.Schema(type=openapi.TYPE_STRING),
                'sec_id': openapi.Schema(type=openapi.TYPE_STRING),
                'student_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
        student_id = data.get('student_id', None)
        sec_id = data.get('sec_id', None)

        org = kwargs.get('organization')
        students = models.Student.objects.filter(
            Q(student_id=student_id) & Q(section__id=sec_id)
            & Q(section__of_class__department__organization__org_id=org.org_id)
            & Q(is_active=True))

        if not len(students):
            errors = ['invalid stduent id']
            return Response({'details': errors}, status.HTTP_400_BAD_REQUEST)

        student = students[0]
        student.is_active = False
        student.save()

        msgs = ["Successfully deleted student"]
        return Response({'details': msgs}, status.HTTP_200_OK)
示例#10
0
    EnvironmentPermissionModel,
    UserEnvironmentPermission,
    UserPermissionGroupEnvironmentPermission,
)
from .serializers import EnvironmentSerializerLight, WebhookSerializer

logger = get_logger(__name__)


@method_decorator(
    name="list",
    decorator=swagger_auto_schema(manual_parameters=[
        openapi.Parameter(
            "project",
            openapi.IN_QUERY,
            "ID of the project to filter by.",
            required=False,
            type=openapi.TYPE_INTEGER,
        )
    ]),
)
class EnvironmentViewSet(viewsets.ModelViewSet):
    lookup_field = "api_key"
    permission_classes = [IsAuthenticated, EnvironmentPermissions]

    def get_serializer_class(self):
        if self.action == "trait_keys":
            return TraitKeysSerializer
        if self.action == "delete_traits":
            return DeleteAllTraitKeysSerializer
        return EnvironmentSerializerLight
示例#11
0
import coreapi
from django.db.models import Q
from django.utils.decorators import method_decorator
from drf_yasg2 import openapi
from drf_yasg2.utils import swagger_auto_schema
from rest_framework import mixins, viewsets

from audit.models import AuditLog
from audit.serializers import AuditLogSerializer

project_query_param = openapi.Parameter(
    "project",
    openapi.IN_QUERY,
    description="ID of the project to filter on",
    type=openapi.TYPE_INTEGER,
)
environment_query_param = openapi.Parameter(
    "environment",
    openapi.IN_QUERY,
    description="ID of the environment to filter on "
    "(Note `id` required, not `api_key`)",
    type=openapi.TYPE_INTEGER,
)


@method_decorator(
    name="list",
    decorator=swagger_auto_schema(
        manual_parameters=[project_query_param, environment_query_param]),
)
class AuditLogViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
示例#12
0
class CreateSubject(views.APIView):
    serializer_class = serializers.SubjectSerializer
    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),
                             openapi.Parameter(name="section_id",
                                               in_="query",
                                               type=openapi.TYPE_INTEGER),
                         ])
    def get(self, request):
        query_params = self.request.query_params
        id = query_params.get('id', None)
        section_id = query_params.get('section_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.Subject.objects.filter(is_active=True)

        if id:
            qs = qs.filter(id=int(id))

        if section_id:
            qs = qs.filter(section__id=int(section_id))

        if class_id:
            qs = qs.filter(section__of_class__id=int(class_id))

        if dept_id:
            qs = qs.filter(
                section__of_class__department__department_id=dept_id)

        if org_id:
            qs = qs.filter(
                section__of_class__department__organization__org_id=org_id)

        serializer = serializers.SubjectSerializer(qs, many=True)
        return Response(serializer.data, status.HTTP_200_OK)

    @swagger_auto_schema(
        request_body=openapi.Schema(
            title="Create Subject",
            type=openapi.TYPE_OBJECT,
            properties={
                'name': openapi.Schema(type=openapi.TYPE_STRING),
                'section_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
        name = data.get('name', "")
        section_id = data.get('section_id', 0)

        if not name:
            errors = ['name is not passed']
            return Response({'details': errors}, status.HTTP_400_BAD_REQUEST)

        if not section_id:
            errors = ['section_id is not passed']
            return Response({'details': errors}, status.HTTP_400_BAD_REQUEST)

        qr_section = sections_models.Section.objects.filter(id=int(section_id),
                                                            is_active=True)

        if not len(qr_section):
            errors = ['Invalid section_id']
            return Response({'details': errors}, status.HTTP_400_BAD_REQUEST)

        section_id = qr_section[0]

        if models.Subject.objects.filter(name=name,
                                         section=section_id).exists():
            errors = ['Subject already exists']
            return Response({'details': errors}, status.HTTP_400_BAD_REQUEST)

        models.Subject.objects.create(name=name, section=section_id)

        msgs = ['Successfully created subject']
        return Response({'details': msgs}, status.HTTP_200_OK)
示例#13
0
from .filters import EvaluatesFilter
from .filters import EvaluateResultsFilter
from .filters import EvaluateResultFilter

from .permissions import RepositoryEvaluatePermission
from .permissions import RepositoryEvaluateResultPermission


@method_decorator(
    name="list",
    decorator=swagger_auto_schema(manual_parameters=[
        openapi.Parameter(
            "repository_uuid",
            openapi.IN_QUERY,
            description="Repository UUID, calling "
            "the parameter through url",
            type=openapi.TYPE_STRING,
            required=True,
        )
    ]),
)
@method_decorator(
    name="create",
    decorator=swagger_auto_schema(manual_parameters=[
        openapi.Parameter(
            "repository_uuid",
            openapi.IN_QUERY,
            description="Repository UUID, calling "
            "the parameter through url",
            type=openapi.TYPE_STRING,
            required=True,
示例#14
0
文件: views.py 项目: gdalmau/drf-yasg
    @swagger_auto_schema(
        operation_id="users_dummy",
        operation_description="dummy operation",
        tags=["Users"],
    )
    def patch(self, request):
        pass


@swagger_auto_schema(method="put", request_body=UserSerializerrr, tags=["Users"])
@swagger_auto_schema(
    methods=["get"],
    manual_parameters=[
        openapi.Parameter(
            "test", openapi.IN_QUERY, "test manual param", type=openapi.TYPE_BOOLEAN
        ),
        openapi.Parameter(
            "test_array",
            openapi.IN_QUERY,
            "test query array arg",
            type=openapi.TYPE_ARRAY,
            items=openapi.Items(type=openapi.TYPE_STRING),
            required=True,
            collection_format="multi",
        ),
    ],
    responses={200: openapi.Response("response description", UserSerializerrr),},
    tags=["Users"],
)
@api_view(["GET", "PUT"])
示例#15
0
class ArticleViewSet(viewsets.ModelViewSet):
    """
    ArticleViewSet class docstring

    retrieve:
    retrieve class docstring

    destroy:
    destroy class docstring

    partial_update:
    partial_update class docstring
    """

    queryset = Article.objects.all()
    lookup_field = "slug"
    lookup_value_regex = r"[a-z0-9]+(?:-[a-z0-9]+)"
    serializer_class = serializers.ArticleSerializer

    pagination_class = ArticlePagination
    filter_backends = (DjangoFilterBackend, OrderingFilter)
    filterset_fields = ("title", )
    # django-filter 1.1 compatibility; was renamed to filterset_fields in 2.0
    # TODO: remove when dropping support for Django 1.11
    filter_fields = filterset_fields
    ordering_fields = ("date_modified", "date_created")
    ordering = ("date_created", )

    swagger_schema = NoTitleAutoSchema

    from rest_framework.decorators import action

    @swagger_auto_schema(
        auto_schema=NoPagingAutoSchema,
        filter_inspectors=[DjangoFilterDescriptionInspector],
    )
    @action(detail=False, methods=["get"])
    def today(self, request):
        today_min = datetime.datetime.combine(datetime.date.today(),
                                              datetime.time.min)
        today_max = datetime.datetime.combine(datetime.date.today(),
                                              datetime.time.max)
        articles = (self.get_queryset().filter(
            date_created__range=(today_min, today_max)).all())
        serializer = self.serializer_class(articles, many=True)
        return Response(serializer.data)

    @swagger_auto_schema(method="get",
                         operation_description="image GET description override"
                         )
    @swagger_auto_schema(method="post",
                         request_body=serializers.ImageUploadSerializer)
    @swagger_auto_schema(
        method="delete",
        manual_parameters=[
            openapi.Parameter(
                name="delete_form_param",
                in_=openapi.IN_FORM,
                type=openapi.TYPE_INTEGER,
                description=
                "this should not crash (form parameter on DELETE method)",
            )
        ],
    )
    @action(
        detail=True,
        methods=["get", "post", "delete"],
        parser_classes=(MultiPartParser, FileUploadParser),
    )
    def image(self, request, slug=None):
        """
        image method docstring
        """

    @swagger_auto_schema(request_body=no_body, operation_id="no_body_test")
    def update(self, request, *args, **kwargs):
        """update method docstring"""
        return super(ArticleViewSet, self).update(request, *args, **kwargs)

    @swagger_auto_schema(
        operation_description="partial_update description override",
        responses={404: "slug not found"},
        operation_summary="partial_update summary",
        deprecated=True,
    )
    def partial_update(self, request, *args, **kwargs):
        """partial_update method docstring"""
        return super(ArticleViewSet,
                     self).partial_update(request, *args, **kwargs)

    def destroy(self, request, *args, **kwargs):
        """destroy method docstring"""
        return super(ArticleViewSet, self).destroy(request, *args, **kwargs)
示例#16
0
from drf_yasg2 import openapi
from drf_yasg2.utils import swagger_auto_schema

from bothub.common.models import QAKnowledgeBase, QAtext
from .filters import QAKnowledgeBaseFilter, QAtextFilter
from .permissions import QAKnowledgeBasePermission, QAtextPermission
from .serializers import QAKnowledgeBaseSerializer, QAtextSerializer


@method_decorator(
    name="list",
    decorator=swagger_auto_schema(manual_parameters=[
        openapi.Parameter(
            "repository_uuid",
            openapi.IN_QUERY,
            description="Repository's UUID",
            required=True,
            type=openapi.TYPE_STRING,
            format="uuid",
        ),
    ]),
)
class QAKnowledgeBaseViewSet(
        mixins.ListModelMixin,
        mixins.CreateModelMixin,
        mixins.RetrieveModelMixin,
        mixins.DestroyModelMixin,
        mixins.UpdateModelMixin,
        GenericViewSet,
):
    queryset = QAKnowledgeBase.objects.all()
    serializer_class = QAKnowledgeBaseSerializer
示例#17
0
class BookingViewSet(viewsets.ModelViewSet):
    queryset = Booking.objects.all().order_by('-id')
    serializer_class = BookingSerializer
    permission_classes = []

    status_param = openapi.Parameter('status',
                                     openapi.IN_QUERY,
                                     description="Enter status",
                                     type=openapi.TYPE_STRING)

    @swagger_auto_schema(manual_parameters=[status_param])
    def list(self, request, *args, **kwargs):
        queryset = self.queryset
        status = self.request.query_params.get('status', None)
        if status is not None:
            queryset = queryset.filter(status=status)
        page = self.paginate_queryset(queryset)
        serializer = BookingSerializer(page, many=True)
        response = self.get_paginated_response(serializer.data)
        return response

    response_schema_dict = {
        "200":
        openapi.Response(description="Success",
                         examples={
                             "application/json": {
                                 "message": "Booking created successfully.",
                                 "status": "True"
                             }
                         }),
        "400":
        openapi.Response(description="Failed",
                         examples={
                             "application/json": {
                                 "message": "Invalid arguments",
                                 "status": "False"
                             }
                         }),
        "400:Bad":
        openapi.Response(description="Failed",
                         examples={
                             "application/json": {
                                 "message": "Phone is required.",
                                 "status": "False"
                             }
                         }),
    }

    @swagger_auto_schema(request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        properties={
            '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'),
            'company':
            openapi.Schema(type=openapi.TYPE_STRING, description='string'),
            'status':
            openapi.Schema(type=openapi.TYPE_INTEGER, description='integer'),
            'category':
            openapi.Schema(type=openapi.TYPE_INTEGER, description='integer'),
        }),
                         responses=response_schema_dict)
    def create(self, request, *args, **kwargs):
        name = request.data.get('name', None)
        if not name:
            raise ValidationError({
                "status": 'False',
                "message": "Name is required."
            })
        phone = request.data.get('phone', None)
        if not phone:
            raise ValidationError({
                "status": 'False',
                "message": "Phone is required."
            })
        if phone:
            if len(phone) != 10:
                raise ValidationError({
                    "status":
                    'False',
                    "message":
                    "Phone length should be 10 digits."
                })
        email = request.data.get('email', None)
        if not email:
            raise ValidationError({
                "status": 'False',
                "message": "Email is required"
            })
        if email:
            regex = '^[\w\.\+\-]+\@[\w]+\.[a-z]{2,3}$'
            match = re.match(regex, email)
            if not match:
                raise ValidationError({
                    "status": 'False',
                    "message": "Email is Invalid"
                })
        company = request.data.get('company', None)
        category = request.data.get('category', None)
        booking_data = {
            "name": name,
            "phone": phone,
            "email": email,
            "company": company,
            "category": category,
        }
        serializer = BookingSerializer(data=booking_data)
        if serializer.is_valid():
            serializer.save()

            company_first_name = company.split(' ')[0]

            # mail to user
            send_email(
                "Activate your " + str(company_first_name) +
                " Employee Wallet",
                "booking_email",
                [email],
                '*****@*****.**',
                None,
                name,
                company_first_name,
            )

            # mail to admin
            send_email(
                str(name) + " from " + str(company) +
                " wants to connect with you",
                "booking_admin_email",
                [
                    '*****@*****.**', '*****@*****.**',
                    '*****@*****.**'
                ],
                '*****@*****.**',
                None,
                name,
                company,
                email,
                phone,
            )

            return JsonResponse({
                "status": 'True',
                "message": "Booking created successfully."
            })
        raise ValidationError({
            "status": 'False',
            "message": "Invalid arguments"
        })
示例#18
0
    def create(self, request, *args, **kwargs):
        project_id = request.data.get('project')
        project = Project.objects.get(pk=project_id)

        if project.organisation not in request.user.organisations.all():
            return Response(status=status.HTTP_403_FORBIDDEN)

        return super().create(request, *args, **kwargs)


@method_decorator(
    name='list',
    decorator=swagger_auto_schema(manual_parameters=[
        openapi.Parameter('feature',
                          openapi.IN_QUERY,
                          'ID of the feature to filter by.',
                          required=False,
                          type=openapi.TYPE_INTEGER),
        openapi.Parameter(
            'anyIdentity',
            openapi.IN_QUERY,
            'Pass any value to get results that have an identity override. '
            'Do not pass for default behaviour.',
            required=False,
            type=openapi.TYPE_STRING)
    ]))
class FeatureStateViewSet(viewsets.ModelViewSet):
    """
    View set to manage feature states. Nested beneath environments and environments + identities
    to allow for filtering on both.
    """
示例#19
0
        query_serializer.is_valid(raise_exception=True)

        events_list = get_multiple_event_list_for_feature(
            feature_name=feature.name, **query_serializer.data)
        serializer = FeatureInfluxDataSerializer(
            instance={"events_list": events_list})
        return Response(serializer.data)


@method_decorator(
    name="list",
    decorator=swagger_auto_schema(manual_parameters=[
        openapi.Parameter(
            "feature",
            openapi.IN_QUERY,
            "ID of the feature to filter by.",
            required=False,
            type=openapi.TYPE_INTEGER,
        ),
        openapi.Parameter(
            "anyIdentity",
            openapi.IN_QUERY,
            "Pass any value to get results that have an identity override. "
            "Do not pass for default behaviour.",
            required=False,
            type=openapi.TYPE_STRING,
        ),
    ]),
)
class FeatureStateViewSet(viewsets.ModelViewSet):
    """
示例#20
0
class QrCodeViewSet(viewsets.ModelViewSet):
    queryset = QrCode.objects.all().order_by('-id')
    serializer_class = QrCodeSerializer
    permission_classes = []

    response_schema_dict = {
        "200":
        openapi.Response(description="Success",
                         examples={
                             "application/json": {
                                 "valid": True,
                                 "message": "Valid QR Code"
                             }
                         }),
        "200:ok":
        openapi.Response(description="Failed",
                         examples={
                             "application/json": {
                                 "valid": False,
                                 "message": "Invalid QR Code"
                             }
                         }),
        "200:Ok":
        openapi.Response(description="Failed",
                         examples={
                             "application/json": {
                                 "valid": False,
                                 "message": "Invalid Location"
                             }
                         }),
        "200:OK":
        openapi.Response(description="Failed",
                         examples={
                             "application/json": {
                                 "valid": False,
                                 "message": "You are not registered"
                             }
                         }),
        "200: OK":
        openapi.Response(description="Failed",
                         examples={
                             "application/json": {
                                 "valid": False,
                                 "message": "You are not verified"
                             }
                         }),
        "400":
        openapi.Response(description="Failed",
                         examples={
                             "application/json": {
                                 "valid": False,
                                 "message": "Params are missing"
                             }
                         }),
        "400: Bad":
        openapi.Response(description="Failed",
                         examples={
                             "application/json": {
                                 "valid": False,
                                 "message": "Employee's Company has no QrCode."
                             }
                         }),
    }

    qr_id_param = openapi.Parameter('qr_id',
                                    openapi.IN_QUERY,
                                    description="Enter Company QrCode",
                                    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)
    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)
    employee_id_param = openapi.Parameter('employee_id',
                                          openapi.IN_QUERY,
                                          description="Enter Employee ID",
                                          type=openapi.TYPE_INTEGER)

    @swagger_auto_schema(manual_parameters=[
        qr_id_param, source_param, fieldset_param, longitude_param,
        latitude_param, employee_id_param
    ],
                         responses=response_schema_dict)
    def list(self, request, *args, **kwargs):
        queryset = self.queryset
        qr_id = self.request.query_params.get('qr_id', None)
        employee_id = self.request.query_params.get('employee_id', None)
        source = self.request.query_params.get('source', None)
        fieldset = self.request.query_params.get('fieldset', None)
        if source == 'app' and fieldset == 'qr':
            longitude = self.request.query_params.get('longitude', None)
            latitude = self.request.query_params.get('latitude', None)
            if not (employee_id and qr_id and longitude and latitude):
                return JsonResponse({
                    "valid": "False",
                    "message": "Params are missing"
                })
            try:
                qr_code = QrCode.objects.get(qr_id=qr_id)
            except:
                raise ValidationError({
                    "valid": "False",
                    "message": "Invalid QR Code"
                })
            employee_obj = Employee.objects.filter(id=employee_id,
                                                   deleted_at=None).first()
            if not employee_obj:
                raise ValidationError({"message": "Employee Does not Exists"})
            if employee_obj.check_location:
                distance_between_location = distance_between_two_points(
                    longitude1=float(qr_code.longitude),
                    latitude1=float(qr_code.latitude),
                    longitude2=float(longitude),
                    latitude2=float(latitude),
                )
                with open(os.path.join(BASE_DIR, 'locations.log'), 'a') as f:
                    string = str(qr_code.longitude) + "," + str(qr_code.latitude) \
                             + "," + str(longitude) + "," + str(latitude) + "," + \
                             str(distance_between_location)
                    f.write(string)
                    f.write("\n")
                try:
                    distance = Setting.objects.get(key='distance')
                except:
                    raise ValidationError({
                        "valid": "False",
                        "message": "Setting Not Found"
                    })
                if distance_between_location < float(distance.value):
                    return JsonResponse({
                        "valid": "True",
                        "message": "Valid QR Code"
                    })
                return JsonResponse({
                    "valid": "False",
                    "message": "Invalid Location."
                })
            else:
                return JsonResponse({
                    "valid": "True",
                    "message": "Valid QR Code"
                })

        if qr_id:
            queryset = queryset.filter(qr_id=qr_id)
        page = self.paginate_queryset(queryset)
        serializer = QrCodeSerializer(page, many=True)
        response = self.get_paginated_response(serializer.data)
        return response

    @swagger_auto_schema(request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        properties={
            'qr_id':
            openapi.Schema(type=openapi.TYPE_STRING, description='string'),
            'longitude':
            openapi.Schema(type=openapi.TYPE_NUMBER, description='decimal'),
            'latitude':
            openapi.Schema(type=openapi.TYPE_NUMBER, description='decimal'),
        }))
    def create(self, request, *args, **kwargs):
        qr_id = request.data.get('qr_id', None)
        longitude = request.data.get('longitude', None)
        latitude = request.data.get('latitude', None)
        if not qr_id:
            raise ValidationError({
                'status': 'False',
                "message": "Empty QR Code"
            })
        if qr_id:
            try:
                company_code = qr_id.split('-')[0]
            except:
                raise ValidationError({
                    'status': 'False',
                    "message": "Invalid QR Code format"
                })
            try:
                company = Company.objects.get(code=company_code)
            except:
                raise ValidationError({
                    'status': 'False',
                    "message": "Company not found"
                })
        if qr_id and longitude and latitude:
            queryset = QrCode.objects.filter(qr_id=qr_id).first()
            if queryset:
                raise ValidationError({
                    'status': 'False',
                    "message": "QR Code already registered"
                })
        data = {
            "qr_id": qr_id,
            "longitude": longitude,
            "latitude": latitude,
            "company": company.id
        }
        serializer = QrCodeSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data)
        raise ValidationError({
            'status': 'False',
            "message": "Invalid details"
        })
示例#21
0
class EmployeeStatusView(views.APIView):
    response_schema_dict = {
        "200":
        openapi.Response(description="success",
                         examples={
                             "application/json": {
                                 "phone": "string",
                                 "registered": "true / false",
                                 "confirmed": "true / false",
                                 "otp": "string"
                             }
                         }),
    }

    phone_param = openapi.Parameter('phone',
                                    openapi.IN_QUERY,
                                    description="Enter phone number",
                                    type=openapi.TYPE_STRING)

    @swagger_auto_schema(method='get',
                         manual_parameters=[phone_param],
                         responses=response_schema_dict)
    @action(detail=False, methods=['GET'])
    def get(self, request):
        phone = request.GET.get('phone')
        user = User.objects.filter(username=phone).first()
        if user:
            employee = user.employee_set.filter(deleted_at=None)
        else:
            employee = []

        # get otp and send to the user
        otp = utilities.generate_random_number(6)
        template = "login"
        data = call(phone, template, otp)

        if user and employee:
            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({
                "phone": str(employee[0].phone),
                "registered": True,
                "confirmed": employee[0].confirmed,
                "otp": str(otp)
            })
        if user and not employee:
            return JsonResponse({
                "phone": phone,
                "registered": False,
                "confirmed": False,
                "otp": str(otp)
            })
        if not user:
            return JsonResponse({
                "phone": phone,
                "registered": False,
                "confirmed": False,
                "otp": str(otp)
            })
示例#22
0
class StatementViewSet(viewsets.ModelViewSet):
    queryset = Statement.objects.filter(
        employee__deleted_at=None).order_by('-id')
    serializer_class = StatementSerializer
    #permission_classes = [permissions.IsAuthenticated]

    from_date_param = openapi.Parameter(
        'from_date',
        openapi.IN_QUERY,
        description="Enter from_date (YYYY-MM-DD)",
        type=openapi.TYPE_STRING)
    to_date_param = openapi.Parameter('to_date',
                                      openapi.IN_QUERY,
                                      description="Enter to_date (YYYY-MM-DD)",
                                      type=openapi.TYPE_STRING)
    employee_param = openapi.Parameter('employee',
                                       openapi.IN_QUERY,
                                       description="Enter employee Id",
                                       type=openapi.TYPE_STRING)
    source_param = openapi.Parameter('source',
                                     openapi.IN_QUERY,
                                     description="Enter source",
                                     type=openapi.TYPE_STRING)
    fieldset_param = openapi.Parameter('fieldset',
                                       openapi.IN_QUERY,
                                       description="Enter fieldset",
                                       type=openapi.TYPE_STRING)

    @swagger_auto_schema(manual_parameters=[
        from_date_param, to_date_param, source_param, fieldset_param,
        employee_param
    ])
    def list(self, request, *args, **kwargs):
        queryset = Statement.objects.filter(
            employee__deleted_at=None).order_by('-id')
        from_date = self.request.query_params.get('from_date', None)
        to_date = self.request.query_params.get('to_date', None)
        employee = self.request.query_params.get('employee', None)
        source = self.request.query_params.get('source', None)
        fieldset = self.request.query_params.get('fieldset', None)
        if source == 'app' and fieldset == 'debit':
            queryset = queryset.filter(debit__gt=0.0)
        if from_date:
            try:
                datetime.datetime.strptime(from_date, "%Y-%m-%d")
            except:
                raise ValidationError({"message": "Invalid from_date format."})
            queryset = queryset.filter(date__gte=from_date)
        if to_date:
            try:
                datetime.datetime.strptime(to_date, "%Y-%m-%d")
            except:
                raise ValidationError({"message": "Invalid to_date format."})
            queryset = queryset.filter(date__lte=to_date)
        if employee:
            queryset = queryset.filter(employee_id=employee)
            serializer = StatementSerializer(queryset, many=True)

            last_statement = Statement.objects.filter(employee=employee).last()
            if last_statement:
                response_data = {
                    "total_due":
                    float(last_statement.balance) +
                    float(last_statement.previous_due),
                    "balance":
                    float(last_statement.balance),
                    "current_due":
                    float(last_statement.current_due),
                    "previous_due":
                    float(last_statement.previous_due),
                    "statements":
                    serializer.data,
                }
            else:
                response_data = {
                    "total_due": 0.0,
                    "balance": 0.0,
                    "current_due": 0.0,
                    "previous_due": 0.0,
                    "statements": []
                }
            return Response(response_data)

        page = self.paginate_queryset(queryset)
        serializer = StatementListSerializer(queryset, many=True)
        response = self.get_paginated_response(serializer.data)
        return response

    response_schema_dict = {
        "200":
        openapi.Response(description="Success",
                         examples={
                             "application/json": {
                                 "message": "Statement created successfully.",
                                 "otp": "154622"
                             }
                         }),
    }

    @swagger_auto_schema(request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        properties={
            'description':
            openapi.Schema(type=openapi.TYPE_STRING, description='string'),
            'credit':
            openapi.Schema(type=openapi.TYPE_NUMBER, description='decimal'),
            'debit':
            openapi.Schema(type=openapi.TYPE_NUMBER, description='decimal'),
            'balance':
            openapi.Schema(type=openapi.TYPE_NUMBER, description='decimal'),
            'status':
            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'),
        }),
                         manual_parameters=[source_param, fieldset_param])
    def create(self, request, *args, **kwargs):
        description = request.data.get('description', None)
        credit = request.data.get('credit', None)
        debit = request.data.get('debit', None)
        status = request.data.get('status', None)
        employee = request.data.get('employee', None)
        company = request.data.get('company', None)
        source = self.request.query_params.get('source', None)
        fieldset = self.request.query_params.get('fieldset', None)
        device_name = request.data.get('device_name', None)
        device_id = request.data.get('device_id', None)
        ip_address = request.data.get('ip_address', None)
        disbursement_id = request.data.get('disbursement_id', None)
        loan_id = request.data.get('loan_id', None)

        if not description:
            raise ValidationError({"message": "Description is required."})
        if not employee:
            raise ValidationError({"message": "Employee is required field."})
        if not company:
            raise ValidationError({"message": "Company is required field."})
        if employee:
            employee_object = Employee.objects.filter(id=employee,
                                                      deleted_at=None).first()
            if not employee_object:
                raise ValidationError({"message": "Employee does not exists."})
            if not employee_object.mail_enabled:
                raise ValidationError({"message": "Please Verify Your Email."})
            if not employee_object.ifs or not employee_object.bank_account_number:
                raise ValidationError(
                    {"message": "Please Add Your Bank Details."})

        if company:
            try:
                Company.objects.get(id=company)
            except:
                raise ValidationError({"message": "Company does not exists."})
        if source == 'app' and fieldset == 'debit':
            if debit:
                if float(debit) <= 0:
                    raise ValidationError({
                        "status": "False",
                        "message": "Invalid Transfer Amount"
                    })
                if float(debit) > float(
                        employee_object.get_available_balance()):
                    raise ValidationError({
                        "status": "False",
                        "message": "Insufficient Balance"
                    })
                if float(debit) < 500:
                    raise ValidationError({
                        "status":
                        "False",
                        "message":
                        "Minimum withdrawal amount: Rs.500"
                    })

            digital_time_stamp = None
            if employee_object.name and device_name and device_id and ip_address:
                digital_time_stamp = utilities.generate_digital_time_stamp(
                    employee_object.name, device_name, device_id, ip_address)

            fees, gst = calculate_fees_with_gst(debit)
            total_debit = debit + fees + gst
            last_statement = Statement.objects.filter(
                employee=employee_object).last()
            if last_statement:
                balance = last_statement.balance + total_debit
                current_due = last_statement.current_due
                previous_due = last_statement.previous_due
            else:
                balance = total_debit
                current_due = 0
                previous_due = 0

            statement_data = {
                "description": description,
                "debit": total_debit,
                "withdraw": debit,
                "fees": fees,
                "gst": gst,
                "balance": balance,
                "current_due": current_due,
                "previous_due": previous_due,
                "employee": employee,
                "company": company,
                "digital_time_stamp": digital_time_stamp
            }

            serializer = StatementSerializer(data=statement_data)
            if serializer.is_valid():
                serializer.save()

                employee_object.balance = float(
                    employee_object.balance) - float(debit)
                employee_object.debited = float(
                    employee_object.debited) + float(total_debit)
                employee_object.withdraw = float(
                    employee_object.withdraw) + float(debit)
                employee_object.fees = float(
                    employee_object.fees) + float(fees)
                employee_object.gst = float(employee_object.gst) + float(gst)

                employee_object.save()

                # send email to Admin for withdraw request
                if employee_object:
                    send_email(
                        "Withdraw Request",  # subject
                        "withdraw_request",  # template
                        [
                            '*****@*****.**', '*****@*****.**',
                            '*****@*****.**'
                        ],  # to_emails
                        '*****@*****.**',
                        None,  # attachment=None
                        str(employee_object.name),
                        str(debit),
                        str(employee_object.ifs.bank.name),
                        str(employee_object.bank_account_number),
                        str(employee_object.ifs.code),
                        str(employee_object.id),
                    )

                return JsonResponse({
                    "status":
                    "True",
                    "message":
                    "Statement created successfully.",
                    "description":
                    serializer.data.get('description', None),
                    "debit":
                    debit
                })
            raise ValidationError({
                "status": "False",
                "message": "Invalid Arguments."
            })
        raise ValidationError({
            "status": "False",
            "message": "Missing source and fieldset Params."
        })
示例#23
0
from environments.identities.models import Identity
from segments.serializers import SegmentSerializer
from util.views import SDKAPIView
from . import serializers
from .permissions import SegmentPermissions

logger = logging.getLogger()
logger.setLevel(logging.INFO)


@method_decorator(
    name='list',
    decorator=swagger_auto_schema(manual_parameters=[
        openapi.Parameter(
            'identity',
            openapi.IN_QUERY,
            'Optionally provide the id of an identity to get only the segments they match',
            required=False,
            type=openapi.TYPE_INTEGER)
    ]))
class SegmentViewSet(viewsets.ModelViewSet):
    serializer_class = serializers.SegmentSerializer
    permission_classes = [SegmentPermissions]

    def get_queryset(self):
        project = get_object_or_404(self.request.user.get_permitted_projects(
            ['VIEW_PROJECT']),
                                    pk=self.kwargs['project_pk'])
        queryset = project.segments.all()

        identity_pk = self.request.query_params.get('identity')
        if identity_pk:
示例#24
0
class TraitViewSet(viewsets.ModelViewSet):
    serializer_class = TraitSerializerFull

    def get_queryset(self):
        """
        Override queryset to filter based on provided URL parameters.
        """
        environment_api_key = self.kwargs["environment_api_key"]
        identity_pk = self.kwargs.get("identity_pk")
        environment = self.request.user.get_permitted_environments(
            ["VIEW_ENVIRONMENT"]
        ).get(api_key=environment_api_key)

        if identity_pk:
            identity = Identity.objects.get(pk=identity_pk, environment=environment)
        else:
            identity = None

        return Trait.objects.filter(identity=identity)

    def get_environment_from_request(self):
        """
        Get environment object from URL parameters in request.
        """
        return Environment.objects.get(api_key=self.kwargs["environment_api_key"])

    def get_identity_from_request(self, environment):
        """
        Get identity object from URL parameters in request.
        """
        return Identity.objects.get(pk=self.kwargs["identity_pk"])

    def create(self, request, *args, **kwargs):
        """
        Override create method to add identity (if present) from URL parameters.

        TODO: fix this - it doesn't work, the FE uses the SDK endpoint instead
        """
        data = request.data
        environment = self.get_environment_from_request()
        if (
            environment.project.organisation
            not in self.request.user.organisations.all()
        ):
            return Response(status=status.HTTP_403_FORBIDDEN)

        identity_pk = self.kwargs.get("identity_pk")

        # check if identity in data or in request
        if "identity" not in data and not identity_pk:
            error = {"detail": "Identity not provided"}
            return Response(error, status=status.HTTP_400_BAD_REQUEST)

        # TODO: do we give priority to request identity or data?
        # Override with request identity
        if identity_pk:
            data["identity"] = identity_pk

        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)

        return Response(
            serializer.data, status=status.HTTP_201_CREATED, headers=headers
        )

    def update(self, request, *args, **kwargs):
        """
        Override update method to always assume update request is partial and create / update
        trait value.
        """
        trait_to_update = self.get_object()
        trait_data = request.data

        # Check if trait value was provided with request data. If so, we need to figure out value_type from
        # the given value and also use correct value field e.g. boolean_value, float_value, integer_value or
        # string_value, and override request data
        if "trait_value" in trait_data:
            trait_data = trait_to_update.generate_trait_value_data(
                trait_data["trait_value"]
            )

        serializer = TraitSerializerFull(trait_to_update, data=trait_data, partial=True)

        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        return Response(serializer.data)

    def partial_update(self, request, *args, **kwargs):
        """
        Override partial_update as overridden update method assumes partial True for all requests.
        """
        return self.update(request, *args, **kwargs)

    @swagger_auto_schema(
        manual_parameters=[
            openapi.Parameter(
                "deleteAllMatchingTraits",
                openapi.IN_QUERY,
                "Deletes all traits in this environment matching the key of the deleted trait",
                type=openapi.TYPE_BOOLEAN,
            )
        ]
    )
    def destroy(self, request, *args, **kwargs):
        delete_all_traits = request.query_params.get("deleteAllMatchingTraits")
        if delete_all_traits and delete_all_traits in ("true", "True"):
            trait = self.get_object()
            self._delete_all_traits_matching_key(
                trait.trait_key, trait.identity.environment
            )
            return Response(status=status.HTTP_204_NO_CONTENT)
        else:
            return super(TraitViewSet, self).destroy(request, *args, **kwargs)

    def _delete_all_traits_matching_key(self, trait_key, environment):
        Trait.objects.filter(
            trait_key=trait_key, identity__environment=environment
        ).delete()
示例#25
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)
class ProjectViewSet(FiltersMixin, viewsets.ModelViewSet):
    """Project ModelViewSet

    Filters:
        is_demo
    """

    queryset = Project.objects.all()
    serializer_class = ProjectSerializer
    filter_backends = (filters.OrderingFilter,)
    filter_mappings = {"is_demo": "is_demo"}

    @swagger_auto_schema(operation_summary="Keep relabel alive.")
    @action(detail=True, methods=["post"])
    def relabel_keep_alive(self, request, pk=None) -> Response:
        """relabel_keep_alive."""
        queryset = self.get_queryset()
        instance = drf_get_object_or_404(queryset, pk=pk)
        instance.relabel_expired_time = timezone.now() + datetime.timedelta(
            seconds=PROJECT_RELABEL_TIME_THRESHOLD
        )
        instance.save(update_fields=["relabel_expired_time"])
        serializer = ProjectSerializer(instance)
        return Response(serializer.data)

    @swagger_auto_schema(
        operation_summary="Get training performace from Custom Vision.",
        responses={
            "200": ProjectPerformanesSerializer,
            "400": MSStyleErrorResponseSerializer,
        },
    )
    @action(detail=True, methods=["get"])
    def train_performance(self, request, pk=None) -> Response:
        """train_performance."""
        queryset = self.get_queryset()
        project_obj = drf_get_object_or_404(queryset, pk=pk)
        if project_obj.setting is None:
            raise ProjectWithoutSettingError
        if not project_obj.setting.is_trainer_valid:
            raise SettingCustomVisionAccessFailed

        trainer = project_obj.setting.get_trainer_obj()
        customvision_project_id = project_obj.customvision_id

        res_data: dict = {"iterations": []}

        def _parse(iteration, iteration_name: str):
            """_parse.

            Args:
                iteration:
            """
            iteration_id = iteration.id
            iteration = iteration.as_dict()
            iteration_status = iteration["status"]
            if iteration_status == "Completed":
                performance = trainer.get_iteration_performance(
                    customvision_project_id, iteration["id"]
                ).as_dict()
                precision = performance["precision"]
                recall = performance["recall"]
                mAP = performance["average_precision"]
            else:
                precision = 0.0
                recall = 0.0
                mAP = 0.0
            return {
                "iteration_name": iteration_name,
                "iteration_id": iteration_id,
                "status": iteration_status,
                "precision": precision,
                "recall": recall,
                "mAP": mAP,
            }

        if project_obj.is_demo:
            iteration_data = {
                "iteration_name": "demo",
                "iteration_id": "demo_iteration_id",
                "status": "ok",
                "precision": 1,
                "recall": 0.0,
                "mAP": 0.0,
            }
            iteration_serialzer = IterationPerformanceSerializer(data=iteration_data)
            if iteration_serialzer.is_valid(raise_exception=True):
                res_data["iterations"].append(iteration_serialzer.data)
            project_performance_serializer = ProjectPerformanesSerializer(data=res_data)
        else:
            iterations = trainer.get_iterations(customvision_project_id)
            for i in range(min(2, len(iterations))):
                iteration_data = _parse(
                    iterations[i], iteration_name=("new" if i == 0 else "previous")
                )
                iteration_serialzer = IterationPerformanceSerializer(
                    data=iteration_data
                )
                if iteration_serialzer.is_valid(raise_exception=True):
                    res_data["iterations"].append(iteration_serialzer.data)

        project_performance_serializer = ProjectPerformanesSerializer(data=res_data)
        if project_performance_serializer.is_valid(raise_exception=True):
            return Response(data=project_performance_serializer.data)

    @swagger_auto_schema(
        operation_summary="reset project",
        manual_parameters=[
            openapi.Parameter(
                "project_name",
                openapi.IN_QUERY,
                type=openapi.TYPE_STRING,
                description="Project name",
                required=True,
            )
        ],
        responses={"200": ProjectSerializer, "400": MSStyleErrorResponseSerializer},
    )
    @action(detail=True, methods=["get"])
    def reset_project(self, request, pk=None) -> Response:
        """reset_project."""

        queryset = self.get_queryset()
        project_obj = drf_get_object_or_404(queryset, pk=pk)
        project_name = request.query_params.get("project_name") or None
        try:
            project_obj.reset(name=project_name)
            project_obj.save()
            # Let Signals to handle if we need to delete Part/Image
            serializer = ProjectSerializer(project_obj)
            return Response(serializer.data)
        except CustomVisionErrorException:
            raise SettingCustomVisionAccessFailed

    @swagger_auto_schema(
        operation_summary="Pull a Custom Vision project.",
        manual_parameters=[
            openapi.Parameter(
                "customvision_project_id",
                openapi.IN_QUERY,
                type=openapi.TYPE_STRING,
                description="Custom Vision Id to Pull",
            ),
            openapi.Parameter(
                "partial",
                openapi.IN_QUERY,
                type=openapi.TYPE_BOOLEAN,
                description="partial download or not",
            ),
        ],
        responses={"200": SimpleOKSerializer, "400": MSStyleErrorResponseSerializer},
    )
    @action(detail=True, methods=["get"])
    def pull_cv_project(self, request, pk=None) -> Response:
        """pull_cv_project."""
        queryset = self.get_queryset()
        project_obj = drf_get_object_or_404(queryset, pk=pk)

        # Check Customvision Project id
        customvision_project_id = request.query_params.get("customvision_project_id")
        logger.info("Project customvision_id: %s", {customvision_project_id})

        # Check Partial
        try:
            is_partial = bool(strtobool(request.query_params.get("partial")))
        except Exception:
            is_partial = True

        # Pull Custom Vision Project
        pull_cv_project_helper(
            project_id=project_obj.id,
            customvision_project_id=customvision_project_id,
            is_partial=is_partial,
        )
        return Response({"status": "ok"})

    @swagger_auto_schema(
        operation_summary="Train project in background.",
        responses={"200": SimpleOKSerializer, "400": MSStyleErrorResponseSerializer},
    )
    @action(detail=True, methods=["get"])
    def train(self, request, pk=None) -> Response:
        """train."""
        queryset = self.get_queryset()
        project_obj = drf_get_object_or_404(queryset, pk=pk)
        project_obj.is_trainable(raise_exception=True)
        TRAINING_MANAGER.add(project_id=pk)
        return Response({"status": "ok"})
示例#27
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)
示例#28
0
class AnnouncenmentViewSet(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="id", in_="query", type=openapi.TYPE_STRING),
            openapi.Parameter(name="org_id", in_="query", type=openapi.TYPE_STRING),
            openapi.Parameter(name="start_date", in_="query", type=openapi.FORMAT_DATE),
            openapi.Parameter(name="end_date", in_="query", type=openapi.FORMAT_DATE),
            openapi.Parameter(name="is_public", in_="query", type=openapi.TYPE_BOOLEAN),
        ]
    )
    def get(self, request,**kwargs):
        query_params = self.request.query_params
        
        id = query_params.get('id', None)
        org_id = query_params.get('org_id', None)
        start_date = query_params.get('start_date', None)
        end_date = query_params.get('end_date', None)
        is_public = query_params.get('is_public', None)

        qs = models.Announcement.objects.filter(is_active=True)

        if id:
            qs = qs.filter(id=int(id))

        if org_id:
            qs = qs.filter(organization__org_id=org_id)

        if start_date:
            qs = qs.filter(date__gte=start_date)
        
        if end_date:
            qs = qs.filter(date__lte=end_date)
        
        if is_public:
            if is_public == "true":
                qs = qs.filter(is_public=True)
            if is_public == "false":
                qs = qs.filter(is_public=False)
        

        serializer = serializers.AnnouncementSerializer(qs, many=True)
        return Response({'details': serializer.data}, status.HTTP_200_OK)

    @swagger_auto_schema(
        request_body = openapi.Schema(
            title = "Create Announcement",
            type=openapi.TYPE_OBJECT,
            properties={
                'title': openapi.Schema(type=openapi.TYPE_STRING),
                'org_id': openapi.Schema(type=openapi.TYPE_STRING),
                'user_type': openapi.Schema(type=openapi.TYPE_STRING),
                'from': 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.")
        }
    )
    @validate_org
    def post(self, request, **kwargs):
        data = request.data
        title = data.get('title', None)
        user_type = data.get('user_type', None)
        From = data.get('from', None)

        if not title or not user_type:
            errors = [
                'title and user_type are required'
            ]
            return Response({'details': errors}, status.HTTP_400_BAD_REQUEST)

        organization = kwargs.get("organization")

        if not validate_user_type(user_type, organization, request.user):
            errors = [
                'invalid user_type options are org,dept,teacher'
            ]
            return Response({'details': errors}, status.HTTP_400_BAD_REQUEST)

        if user_type == 'dept':
            from1 = validate_from(user_type,organization,request.user, From)
            if from1 == False:
                errors = [
                    'Department user is not valid'
                ]
                return Response({'details': errors}, status.HTTP_400_BAD_REQUEST)

            fromDetail = {
                "class":str(from1.title),
                "Departemnt":str(from1.department),
            }
            data_dict = {
                "user": request.user.id,
                "organization": organization.id,
                "title": str(title),
                "From":str(fromDetail)
            }
        if user_type == 'teacher':
            from1 = validate_from(user_type,organization,request.user, From)
            if from1 == False:
                errors = [
                    'Teacher user is not valid'
                ]
                return Response({'details': errors}, status.HTTP_400_BAD_REQUEST)

            fromDetail = {
                "subject":str(from1),
                "teacher":str(request.user),
            }
            data_dict = {
                "user": request.user.id,
                "organization": organization.id,
                "title": str(title),
                "From":str(fromDetail)
            }
        if user_type == 'org':
            from1 = validate_from(user_type,organization,request.user, From)
            if from1 == False:
                errors = [
                    'organization user is not valid'
                ]
                return Response({'details': errors}, status.HTTP_400_BAD_REQUEST)

            fromDetail = {
                "organization":str(from1),
            }
            data_dict = {
                "user": request.user.id,
                "organization": organization.id,
                "title": str(title),
                "From":str(fromDetail)
            }
        serializer = serializers.AnnouncementSerializer(data=data_dict)
        if serializer.is_valid():
            serializer.save()
            msgs = [
                serializer.data
            ]
            return Response({'details': msgs}, status.HTTP_200_OK)

        errors = [
            str(serializer.errors)
        ]
        return Response({'details': errors}, status.HTTP_400_BAD_REQUEST)

    @swagger_auto_schema(
        request_body=openapi.Schema(
            title="Update Announcement",
            type=openapi.TYPE_OBJECT,
            properties={
                'id': openapi.Schema(type=openapi.TYPE_INTEGER),
                'org_id': openapi.Schema(type=openapi.TYPE_STRING),
                'title': openapi.Schema(type=openapi.TYPE_STRING),
                'description': openapi.Schema(type=openapi.TYPE_STRING),
                'data': openapi.Schema(type=openapi.TYPE_STRING),
                'date': openapi.Schema(type=openapi.FORMAT_DATE),
                'visible': openapi.Schema(type=openapi.TYPE_STRING),
                'is_public': openapi.Schema(type=openapi.TYPE_BOOLEAN),
                'acknowledge': 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
    def put(self, request, *args, **kwargs):
        data = request.data
        id = data.get('id', None)

        if not id:
            errors = [
                'id is not passed'
            ]
            return Response({'details': errors}, status.HTTP_400_BAD_REQUEST)

        announcements = models.Announcement.objects.filter(Q(id=int(id)) & Q(is_active=True) & Q(user=request.user))
        
        if not len(announcements):
            errors = [
                'invalid id'
            ]
            return Response({'details': errors}, status.HTTP_400_BAD_REQUEST)

        announcement = announcements[0]

        serializer = serializers.AnnouncementSerializer(instance=announcement, data=data, partial=True)

        if serializer.is_valid():
            serializer.save()
            msgs = [
                serializer.data
            ]
            return Response({'details': msgs}, status.HTTP_200_OK)

        errors = [
            str(serializer.errors)
        ]
        return Response({'details': errors}, status.HTTP_400_BAD_REQUEST)

    @swagger_auto_schema(
        request_body=openapi.Schema(
            title="Delete Announcement",
            type=openapi.TYPE_OBJECT,
            properties={
                'id': openapi.Schema(type=openapi.TYPE_INTEGER),
                '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.")
        }
    )
    @validate_org
    def delete(self, request, *args, **kwargs):
        data = request.data
        id = data.get('id', None)

        if not id:
            errors = [
                'id is not passed'
            ]
            return Response({'details': errors}, status.HTTP_400_BAD_REQUEST)

        announcements = models.Announcement.objects.filter(Q(id=int(id)) & Q(is_active=True) & Q(user=request.user))
        if not len(announcements):
            errors = [
                'invalid id'
            ]
            return Response({'details': errors}, status.HTTP_400_BAD_REQUEST)

        announcement = announcements[0]
        announcement.is_active = False
        announcement.save()
        
        msgs = [
            "Successfully deleted announcement"
        ]
        return Response({'details': msgs}, status.HTTP_200_OK)
示例#29
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)
示例#30
0
class RedeemCode(views.APIView):

    permission_classes = (permissions.AllowAny,)

    @swagger_auto_schema(
        responses={
            200: openapi.Response("OK- Successful GET Request"),
            401: openapi.Response("Unauthorized- Authentication credentials were not provided. || Token Missing or Session Expired"),
            500: openapi.Response("Internal Server Error- Error while processing the GET Request Function.")
        },
        manual_parameters=[
            openapi.Parameter(name="uuid", in_="query", type=openapi.TYPE_STRING),
        ]
    )
    @validate_coupon_code_with_uuid
    def get(self, request, *args, **kwargs):
        coupons = kwargs.get("coupons")
        if coupons:
            serializer = coupons_serializers.CouponSerializer(coupons, many=True)

            coupons = serializer.data
            coupon = coupons[0]

            coupon.pop("winner_name")
            coupon.pop("winner_phone")
            coupon.pop("winner_email")
            coupon.pop("feedback")

            coupon.update({
                "payment_preferences": "[]"
            })
            
            data = {
                "coupons": serializer.data,
            }
            return response.Response(data, status.HTTP_200_OK)

        errors = {
            'message': 'Code is not available',
        }
        return response.Response(errors, status.HTTP_400_BAD_REQUEST)

    @swagger_auto_schema(
        request_body = openapi.Schema(
            title = "Create Coupon",
            type=openapi.TYPE_OBJECT,
            properties={
                'winner_name': openapi.Schema(type=openapi.TYPE_STRING),
                'winner_phone': openapi.Schema(type=openapi.TYPE_STRING),
                'winner_email': openapi.Schema(type=openapi.TYPE_STRING),
                'payment_preferences': openapi.Schema(type=openapi.TYPE_STRING),
                'feedback': 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.")
        },
        manual_parameters=[
            openapi.Parameter(name="uuid", in_="query", type=openapi.TYPE_STRING),
        ]
    )
    def post(self, request, *args, **kwargs):
        query_params = self.request.query_params
        uuid = query_params.get('uuid', "")

        data = request.data
        winner_name = data.get("winner_name", "")
        winner_email = data.get("winner_email", "")
        winner_phone = data.get("winner_phone", "")
        feedback = data.get("feedback", "")
        payment_preferences = data.get("payment_preferences", "[]")

        if not winner_name:
            errors = {
                'message': 'Name is required',
            }
            return response.Response(errors, status.HTTP_400_BAD_REQUEST)
        
        if not winner_phone:
            errors = {
                'message': 'Mobile number is required',
            }
            return response.Response(errors, status.HTTP_400_BAD_REQUEST)

        if not winner_email:
            errors = {
                'message': 'E-mail is required',
            }
            return response.Response(errors, status.HTTP_400_BAD_REQUEST)
        
        coupons = coupons_models.Coupon.objects.filter(
            Q(uuid=uuid) &
            Q(is_available=True) &
            Q(is_active=True)
        )

        if not len(coupons):
            errors = {
                'message': 'Invalid code',
            }
            return response.Response(errors, status.HTTP_400_BAD_REQUEST)
            
        coupon = coupons[0]

        if coupon.redeemed:

            already = coupons_models.OtherResponses.objects.filter(
                Q(coupon__id=coupon.id) &
                Q(winner_name=winner_name) &
                Q(winner_phone=winner_phone) &
                Q(winner_email=winner_email) &
                Q(coupon__id=coupon.id)
            )
            if not already.exists():
                serializer = coupons_serializers.OtherResponsesSerializer(data={
                    "coupon": coupon.id,
                    "winner_name": winner_name,
                    "winner_phone": winner_phone,
                    "winner_email": winner_email,
                    "payment_preferences": payment_preferences,
                    "feedback": feedback,
                })
                if not serializer.is_valid():
                    errors = {'message': str(serializer.errors)}
                    return response.Response(errors, status.HTTP_400_BAD_REQUEST)            
                serializer.save()
            errors = {'message': f'Coupon is already redeemed by {coupon.winner_name}'}
            return response.Response(errors, status.HTTP_400_BAD_REQUEST)

        data = {
            "winner_name": winner_name,
            "winner_phone": winner_phone,
            "winner_email": winner_email,
            "payment_preferences": payment_preferences,
            "feedback": feedback,
            "redeemed": True,
            "redeemed_at": datetime.datetime.now(),
        }
        
        serializer = coupons_serializers.CouponSerializer(instance=coupon, data=data, partial=True)

        if serializer.is_valid():
            serializer.save()

            details = {
                "message": "Coupon Successfully redeemed.",
            }
            return response.Response(details, status.HTTP_201_CREATED)    

        errors = {
            'message': str(serializer.errors),
        }
        return response.Response(errors, status.HTTP_400_BAD_REQUEST)