Beispiel #1
0
class RequestTv(APIView):
    """Request a TV show by TMDB ID."""
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.msg = {"success": True, "detail": None}

    @swagger_auto_schema(
        request_body=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            properties={
                "seasons":
                openapi.Schema(
                    type=openapi.TYPE_ARRAY,
                    items=openapi.Items(type=openapi.TYPE_INTEGER),
                ),
                "episodes":
                openapi.Schema(
                    type=openapi.TYPE_ARRAY,
                    items=openapi.Items(type=openapi.TYPE_INTEGER),
                ),
            },
        ),
        responses={
            status.HTTP_200_OK:
            openapi.Schema(
                type=openapi.TYPE_OBJECT,
                properties={
                    "success": openapi.Schema(type=openapi.TYPE_BOOLEAN, ),
                    "detail": openapi.Schema(type=openapi.TYPE_STRING, ),
                },
            ),
        },
    )
    def post(self, request, tmdb_id):
        """Request a TV show by TMDB ID. Optionally, you can request specific seasons or episodes."""
        content_manager = ArrManager()
        content_discovery = TmdbDiscovery()
        tvdb_id = content_discovery.get_external_ids(tmdb_id, "tv")
        request_parameters = json.loads(request.body.decode("utf-8"))

        # Request the show by the TVDB ID
        if tvdb_id:
            sonarr_request(
                tvdb_id["tvdb_id"],
                tmdb_id,
                request,
                request_parameters,
                content_manager,
                content_discovery,
            )
            return Response(self.msg)
        return Response({
            "success": False,
            "detail": "Could not determine TVDB ID."
        })
Beispiel #2
0
class CurrencyExchangeHandler(APIView):

    @swagger_auto_schema(
        operation_description="get USD and EUR currencies rate",
        manual_parameters=[
            openapi.Parameter('api_token', openapi.IN_QUERY, description="test manual param", type=openapi.TYPE_STRING),
            openapi.Parameter('currencies', openapi.IN_QUERY, description="test manual param", type=openapi.TYPE_ARRAY,
                              items=openapi.Items(type=openapi.TYPE_STRING))],
        responses={200: """example:\n{'USD': 0.05, 'EUR': 0.06}"""},
    )
    def get(self, request):
        is_allowed = MerchantShop.objects.filter(api_token=request.query_params['api_token'])
        if is_allowed:
            converter = CurrencyConverter()
            currencies = request.query_params['currencies'].split(',')
            USD_rate = get_usd_rate()
            result = {}
            for currency in currencies:
                try:
                    rate = converter.convert(1, currency, 'USD')
                    result.update({currency: USD_rate / rate})
                except ValueError as err:
                    raise ValidationError(str(err))

            return Response(result)

        raise PermissionDenied
Beispiel #3
0
class ReprocessAPIView(ReprocessMixin, APIView):
    @swagger_auto_schema(
        operation_id='reprocess',
        request_body=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            properties={
                'hashes': openapi.Schema(type=openapi.TYPE_ARRAY,
                                         items=openapi.Items(type=openapi.TYPE_STRING),
                                         default=[]),
                'force_reprocess': openapi.Schema(type=openapi.TYPE_BOOLEAN,
                                                  description='To reprocess the file regardless the decompiler version.',
                                                  default=False),
                'callback': openapi.Schema(type=openapi.TYPE_STRING,
                                           description='Callback URL.')
            },
            required=[]
        ),
        responses={
            status.HTTP_202_ACCEPTED: openapi.Response(
                description='Request accepted. Files will be reprocessed soon.',
            )
        }
    )
    def post(self, request: Request) -> Response:
        hashes = request.data.getlist('hashes', [])
        samples = Sample.objects.with_hash_in(hashes)
        force_reprocess = bool(request.data.get('force_reprocess', False))
        callback = request.data.get('callback', None)

        submitted_samples = self.reprocess(samples=samples, force_reprocess=force_reprocess, callback=callback)

        return Response({'submitted_samples': submitted_samples}, status.HTTP_202_ACCEPTED)
Beispiel #4
0
class PaymentMethodView(GenericViewSet, ResponseViewMixin):
    permission_classes = [IsAuthenticated]

    @swagger_auto_schema(
        tags=['user'],
        request_body=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            properties={
                'user_id':
                openapi.Schema(type=openapi.TYPE_INTEGER),
                'payment_type':
                openapi.Schema(type=openapi.TYPE_ARRAY,
                               items=openapi.Items(type=openapi.TYPE_STRING)),
            }))
    def create(self, request):
        user_id = request.data.get('user_id')
        payment_type = request.data.get('payment_type')
        try:
            for value in payment_type:
                UserPaymentMethod.objects.get_or_create(
                    user_id=user_id, payment_method_id=value)
            UserPaymentMethod.objects.exclude(
                payment_method_id__in=payment_type).delete()
            return self.success_response(code='HTTP_200_OK',
                                         message=DATA_SAVED_SUCCESSFULLY)
        except Exception as e:
            db_logger.exception(e)
            return self.error_response(code='HTTP_500_INTERNAL_SERVER_ERROR',
                                       message=GENERAL_ERROR)

    def retrieve(self, request, pk=None):
        try:
            payment_methods = UserPaymentMethod.objects.filter(user=pk)
            serializer = UserPaymentSerializer(payment_methods, many=True)
            return self.success_response(code='HTTP_200_OK',
                                         data=serializer.data,
                                         message=SUCCESS)
        except UserPaymentMethod.DoesNotExist:
            return self.error_response(code='HTTP_500_INTERNAL_SERVER_ERROR',
                                       message=GENERAL_ERROR)

    @swagger_auto_schema(tags=['user'], request_body=ShopDetailSerializer)
    def update(self, request, pk=None):
        try:
            shop = Shop.objects.get(id=pk)
            serializer = ShopLocationDataSerializer(instance=shop,
                                                    data=request.data)
            if serializer.is_valid():
                serializer.save()
                return self.success_response(code='HTTP_200_OK',
                                             data=serializer.data,
                                             message=SUCCESS)
            else:
                return self.error_response(
                    code='HTTP_500_INTERNAL_SERVER_ERROR',
                    message=GENERAL_ERROR)
        except Exception as e:
            db_logger.exception(e)
            return self.error_response(code='HTTP_500_INTERNAL_SERVER_ERROR',
                                       message=GENERAL_ERROR)
class WeatherApi(APIView, WeatherResponse):
    """Weather API view to calcule average current temperature."""
    @swagger_auto_schema(
        operation_description="Request average temp from services.",
        request_body=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            required=["latitude", "longitude", "services"],
            properties={
                "latitude":
                openapi.Schema(
                    type=openapi.TYPE_NUMBER,
                    format=openapi.FORMAT_FLOAT,
                    description="""Value that indicates the latitude.
                    Can go from -180 to 180.""",
                ),
                "longitude":
                openapi.Schema(
                    type=openapi.TYPE_NUMBER,
                    format=openapi.FORMAT_FLOAT,
                    description="""Value that indicates the longitude.
                    Can go from -180 to 180.""",
                ),
                "services":
                openapi.Schema(
                    type=openapi.TYPE_ARRAY,
                    items=openapi.Items(type=openapi.TYPE_STRING),
                    description="""List of services to query.
                    Example:
                        ["NOAA", "ACCUWEATHER", "WEATHER_DOT_COM"]
                    """,
                ),
            },
        ),
        responses={
            200:
            openapi.Response(
                "Average current temp from services queried in Fahrenheint."),
            400:
            openapi.Response("""When services, latitude or longitud
                are not provided properly."""),
        },
    )
    def post(self, request):  # noqa: D102
        try:
            serializer = AverageTempRequestSchema().loads(request.body)
            average_temp = self.generic_average_weather(serializer)

            return JsonResponse(data={"average_temp": average_temp},
                                status=200)
        except ExternalServiceException:
            return JsonResponse(
                data={"message": ExternalServiceException.message}, status=400)
        except ValidationError:
            return JsonResponse(data={"message": "Some fields are not right."},
                                status=400)
        except Exception as e:
            logger.exception("This exception was raised. %s", e)
            return JsonResponse(data={"message": "There is an error."},
                                status=400)
Beispiel #6
0
def get_prefetch_schema(methods, serializer):
    """ Swagger / OpenAPI v2 (drf-yasg) Return a composable swagger schema that contains in the query the fields that can be prefetch from the model
        supported by the serializer and in the reponse the structure of these fields in a new top-level attribute
        named prefetch.

        Returns:
            ComposableSchema: A swagger schema
    """
    prefetcher = _Prefetcher()
    fields = _get_prefetchable_fields(serializer())

    field_to_serializer = dict([(name, prefetcher._find_serializer(field_type))
                                for name, field_type in fields
                                if prefetcher._find_serializer(field_type)])
    fields_to_refname = dict([
        (name, utils.get_serializer_ref_name(serializer()))
        for name, serializer in field_to_serializer.items()
    ])
    fields_name = [
        name for name, field_type in fields
        if prefetcher._find_serializer(field_type)
    ]

    # New openapi parameter corresponding to the prefetchable fields
    prefetch_params = [
        openapi.Parameter("prefetch",
                          in_=openapi.IN_QUERY,
                          required=False,
                          type=openapi.TYPE_ARRAY,
                          items=openapi.Items(type=openapi.TYPE_STRING,
                                              enum=fields_name))
    ]

    additional_props = dict([
        (name,
         openapi.Schema(type=openapi.TYPE_OBJECT,
                        read_only=True,
                        additional_properties=LazySchemaRef(
                            fields_to_refname[name], True)))
        for name in fields_name
    ])
    prefetch_response = {
        "200": {
            "prefetch":
            openapi.Schema(type=openapi.TYPE_OBJECT,
                           properties=additional_props)
        }
    }

    schema = extra_schema.IdentitySchema()
    for method in methods:
        schema = schema.composeWith(
            extra_schema.ExtraParameters(method, prefetch_params))
        schema = schema.composeWith(
            extra_schema.ExtraResponseField(method, prefetch_response))

    return schema
Beispiel #7
0
    def coreapi_field_to_parameter(self, field, schema=None):
        """
        Convert an instance of `coreapi.Field` to a swagger :class:`.Parameter` object.

        :param coreapi.Field field:
        :param coreschema..Schema schema:
        :rtype: openapi.Parameter
        """
        location_to_in = {
            'query': openapi.IN_QUERY,
            'path': openapi.IN_PATH,
            'form': openapi.IN_FORM,
            'body': openapi.IN_FORM,
        }
        coreapi_types = {
            coreschema.Integer: openapi.TYPE_INTEGER,
            coreschema.Number: openapi.TYPE_NUMBER,
            coreschema.String: openapi.TYPE_STRING,
            coreschema.Boolean: openapi.TYPE_BOOLEAN,
            coreschema.Array: openapi.TYPE_ARRAY,
        }

        coreschema_attrs = [
            'format', 'pattern', 'enum', 'min_length', 'max_length'
        ]
        schema_field = schema or field.schema
        attributes = {}
        if isinstance(schema_field, coreschema.Array):
            attributes['collectionFormat'] = 'csv'
            param = self.coreapi_field_to_parameter(field, schema_field.items)
            attributes['items'] = openapi.Items(**OrderedDict(
                (attr, getattr(param, attr, None))
                for attr in coreschema_attrs + ['type']))
            attributes['minItems'] = schema_field.min_items
            attributes['maxItems'] = schema_field.max_items
            attributes['uniqueItems'] = schema_field.unique_items
            coreschema_attrs = ()

        schema_type = coreapi_types.get(type(schema_field),
                                        openapi.TYPE_STRING)
        if schema is not None and \
           field.name in ('id', 'id__not') and \
           isinstance(self.fields_map.get(field.name.split('__')[0]), (models.AutoField, models.IntegerField)):
            schema_type = openapi.TYPE_INTEGER

        return openapi.Parameter(
            name=field.name,
            in_=location_to_in[field.location],
            required=field.required,
            description=force_real_str(schema_field.description)
            if schema_field else None,
            type=schema_type,
            **OrderedDict((attr, getattr(schema_field, attr, None))
                          for attr in coreschema_attrs),
            **attributes)
Beispiel #8
0
    def get_default_response_data(self, default_serializer):
        default_data_schema = ''
        if default_serializer and not isinstance(default_serializer,
                                                 openapi.Schema):
            default_data_schema = self.serializer_to_schema(
                default_serializer) or ''

        if is_list_view(self.path, self.method,
                        self.view) and self.method.lower() == 'get':
            default_data_schema = openapi.Schema(
                type=openapi.TYPE_ARRAY,
                items=openapi.Items(default_data_schema))

        return default_data_schema
Beispiel #9
0
class RunSurveyView(APIView):
    '''прохождение опроса'''
    def _get_available_question_ids(self, survey):
        return (Question.objects.filter(survey=survey).values_list('id',
                                                                   flat=True))

    @swagger_auto_schema(
        tags=['survey'],
        operation_id='run_survey',
        operation_decription='Прохождение опроса',
        responses={
            '201': 'survey_id',
            '400': 'bad request'
        },
        request_body=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            properties={
                'answers':
                openapi.Schema(type=openapi.Items(
                    type='array',
                    items={
                        'question_id':
                        openapi.Schema(type=openapi.TYPE_INTEGER,
                                       description='id вопроса'),
                        'text':
                        openapi.Schema(type=openapi.TYPE_STRING,
                                       description='текст ответа'),
                    }))
            }))
    def post(self, request, survey_id, user_id):
        answers = request.data.get('answers')
        try:
            survey = Survey.objects.get(id=survey_id, is_active=True)
        except ObjectDoesNotExist:
            return Response(SURVEY_DOES_NOT_EXIST,
                            status=status.HTTP_400_BAD_REQUEST)
        user, _ = User.objects.get_or_create(id=user_id)

        if answers:
            survey_session = SurveySession.objects.create(user=user,
                                                          survey=survey)
            for answer in answers:
                question = answer.get('question')
                if question in self._get_available_question_ids(survey):
                    question = Question.objects.get(id=question)
                    Answer.objects.create(question=question,
                                          text=answer.get('text'),
                                          survey_session=survey_session)

        return Response({'user_id': user.id}, status=status.HTTP_200_OK)
Beispiel #10
0
 class Meta:
     swagger_schema_fields = {
         'type': openapi.TYPE_ARRAY,
         'items': openapi.Items(
             type=openapi.TYPE_ARRAY,
             items=openapi.Schema(
                 type=openapi.TYPE_INTEGER,
             ),
             properties={
                 'minItems' : 2,
                 'maxItems' : 2
             }
         ),
         'properties' : {
             'minItems': 2,
             'maxItems': 2
         }
     }
Beispiel #11
0
class PaymentStatusView(APIView):
    @swagger_auto_schema(request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        required=['tx_hashes'],
        properties={
            'tx_hashes':
            openapi.Schema(type=openapi.TYPE_ARRAY,
                           items=openapi.Items(type=openapi.TYPE_STRING)),
            'chain':
            openapi.Schema(type=openapi.TYPE_STRING)
        }),
                         responses={200: PaymentStatusSerializer()})
    def post(self, request):
        q = Q(tx_hash__in=request.data.get('tx_hashes'))
        if request.data.get('chain'):
            q &= Q(currency=request.data['chain'])
        payments_qs = Payment.objects.filter(q)
        serializer = PaymentStatusSerializer(payments_qs, many=True)
        return Response(
            {
                'is_testnet': IS_TESTNET_PAYMENTS,
                'payments': serializer.data
            }, status.HTTP_200_OK)
from drf_yasg.utils import swagger_auto_schema
from django.utils.html import strip_tags
from django.template.loader import render_to_string, get_template
import os
from api.models import (User, Partner, Quarter, ProductQuarterDate)
from api.tasks import send_bulk_email
from MPP_API.settings import FROM_EMAIL_ID
from datetime import datetime, tzinfo

request_body_reminder_mail = openapi.Schema(
    type=openapi.TYPE_OBJECT,
    properties={
        'partner_id':
        openapi.Schema(type=openapi.TYPE_INTEGER),
        'template_type':
        openapi.Items(type=openapi.TYPE_STRING,
                      enum=["PDT", "Filing Plans", "Sales"])
    })

request_body_bulk_reminder_mail = openapi.Schema(
    type=openapi.TYPE_OBJECT,
    properties={
        'data':
        openapi.Schema(type=openapi.TYPE_ARRAY,
                       items=openapi.Items(type=openapi.TYPE_OBJECT)),
    })


class ReminderMailView(APIView):

    permission_classes = [IsAdmin]
try:
    import typing
    from typing import Dict, List, Union, Optional, Set
except ImportError:
    typing = None

if typing:
    @pytest.mark.parametrize('hint_class, expected_swagger_type_info', [
        (int, {'type': openapi.TYPE_INTEGER, 'format': None}),
        (str, {'type': openapi.TYPE_STRING, 'format': None}),
        (bool, {'type': openapi.TYPE_BOOLEAN, 'format': None}),
        (dict, {'type': openapi.TYPE_OBJECT, 'format': None}),
        (Dict[int, int], {'type': openapi.TYPE_OBJECT, 'format': None}),
        (uuid.UUID, {'type': openapi.TYPE_STRING, 'format': openapi.FORMAT_UUID}),
        (List[int], {'type': openapi.TYPE_ARRAY, 'items': openapi.Items(openapi.TYPE_INTEGER)}),
        (List[str], {'type': openapi.TYPE_ARRAY, 'items': openapi.Items(openapi.TYPE_STRING)}),
        (List[bool], {'type': openapi.TYPE_ARRAY, 'items': openapi.Items(openapi.TYPE_BOOLEAN)}),
        (Set[int], {'type': openapi.TYPE_ARRAY, 'items': openapi.Items(openapi.TYPE_INTEGER)}),
        (Optional[bool], {'type': openapi.TYPE_BOOLEAN, 'format': None, 'x-nullable': True}),
        (Optional[List[int]], {
            'type': openapi.TYPE_ARRAY, 'items': openapi.Items(openapi.TYPE_INTEGER), 'x-nullable': True
        }),
        (Union[List[int], type(None)], {
            'type': openapi.TYPE_ARRAY, 'items': openapi.Items(openapi.TYPE_INTEGER), 'x-nullable': True
        }),
        # Following cases are not 100% correct, but it should work somehow and not crash.
        (Union[int, float], None),
        (List, {'type': openapi.TYPE_ARRAY, 'items': openapi.Items(openapi.TYPE_STRING)}),
        ('SomeType', None),
        (type('SomeType', (object,), {}), None),
Beispiel #14
0
    description='Response with all items in category',
    schema=openapi.Schema(
        type=openapi.TYPE_ARRAY,
        items=openapi.Items(
            type=openapi.TYPE_OBJECT,
            properties={
                'items':
                openapi.Schema(
                    type=openapi.TYPE_OBJECT,
                    properties={
                        'id': openapi.Schema(type=openapi.TYPE_NUMBER),
                        'group': openapi.Schema(type=openapi.TYPE_STRING),
                        'name': openapi.Schema(type=openapi.TYPE_STRING),
                        'images': openapi.Schema(type=openapi.TYPE_OBJECT),
                        'total_supply':
                        openapi.Schema(type=openapi.TYPE_NUMBER),
                        'supply': openapi.Schema(type=openapi.TYPE_NUMBER),
                        'sold': openapi.Schema(type=openapi.TYPE_NUMBER),
                        'price': openapi.Schema(type=openapi.TYPE_NUMBER),
                        'description':
                        openapi.Schema(type=openapi.TYPE_STRING),
                        'bonus_coins':
                        openapi.Schema(type=openapi.TYPE_NUMBER),
                        'lucky_prize': openapi.Schema(type=openapi.TYPE_NUMBER)
                    },
                ),
            },
        ),
    ))

store_response = openapi.Response(
 }),
 (dict, {
     'type': openapi.TYPE_OBJECT,
     'format': None
 }),
 (Dict[int, int], {
     'type': openapi.TYPE_OBJECT,
     'format': None
 }),
 (uuid.UUID, {
     'type': openapi.TYPE_STRING,
     'format': openapi.FORMAT_UUID
 }),
 (List[int], {
     'type': openapi.TYPE_ARRAY,
     'items': openapi.Items(openapi.TYPE_INTEGER)
 }),
 (List[str], {
     'type': openapi.TYPE_ARRAY,
     'items': openapi.Items(openapi.TYPE_STRING)
 }),
 (List[bool], {
     'type': openapi.TYPE_ARRAY,
     'items': openapi.Items(openapi.TYPE_BOOLEAN)
 }),
 (Set[int], {
     'type': openapi.TYPE_ARRAY,
     'items': openapi.Items(openapi.TYPE_INTEGER)
 }),
 (Optional[bool], {
     'type': openapi.TYPE_BOOLEAN,
Beispiel #16
0
                        ProductNotes, FilingPlan, Country, SalesReport,
                        TemplateMessage)
from api.helpers.generate_csv import generate_csv
import datetime, json
from django.template.defaultfilters import date
from django.core.paginator import Paginator

from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema

request_body_pdt = openapi.Schema(
    type=openapi.TYPE_OBJECT,
    properties={
        'partner_id':
        openapi.Schema(type=openapi.TYPE_ARRAY,
                       items=openapi.Items(type=openapi.TYPE_INTEGER)),
        'product_id':
        openapi.Schema(type=openapi.TYPE_ARRAY,
                       items=openapi.Items(type=openapi.TYPE_INTEGER)),
        'status':
        openapi.Schema(type=openapi.TYPE_ARRAY,
                       items=openapi.Items(type=openapi.TYPE_STRING)),
        'stages':
        openapi.Schema(type=openapi.TYPE_ARRAY,
                       items=openapi.Items(type=openapi.TYPE_STRING))
    })

request_body_filing = openapi.Schema(
    type=openapi.TYPE_OBJECT,
    properties={
        'partner_id':
Beispiel #17
0
get_response = openapi.Response(
    description="Response with all user's payments",
    schema=openapi.Schema(
        type=openapi.TYPE_ARRAY,
        items=openapi.Items(
            type=openapi.TYPE_OBJECT,
            properties={
                'payments':
                openapi.Schema(type=openapi.TYPE_OBJECT,
                               properties={
                                   'id':
                                   openapi.Schema(type=openapi.TYPE_NUMBER),
                                   'user':
                                   openapi.Schema(type=openapi.TYPE_STRING),
                                   'item_id':
                                   openapi.Schema(type=openapi.TYPE_NUMBER),
                                   'item_name':
                                   openapi.Schema(type=openapi.TYPE_STRING),
                                   'item_images':
                                   openapi.Schema(type=openapi.TYPE_OBJECT),
                                   'quantity':
                                   openapi.Schema(type=openapi.TYPE_NUMBER),
                                   'created_date':
                                   openapi.Schema(
                                       type=openapi.TYPE_STRING,
                                       format=openapi.FORMAT_DATETIME),
                               }),
            })))

get_single_response = openapi.Response(
    description="Response with single user's payments",
    schema=openapi.Schema(type=openapi.TYPE_OBJECT,
Beispiel #18
0
class ReportWorkerChart(APIView):
    permission_classes = (ReportWorkerChartAccessPolicy,)

    @swagger_auto_schema(
        tags=['Reports Chart'],
        operation_description="The method returns an aggregated data object, "
                              "Worker object by period.",
        manual_parameters=[
            openapi.Parameter(
                'period',
                openapi.IN_QUERY,
                description="Type of Period (day, week, month, year)",
                type=openapi.TYPE_STRING,
                default='day'
            ),
            openapi.Parameter(
                'types',
                openapi.IN_QUERY,
                description="Type of Aggregation Schedules Required "
                            "(profit, avg)",
                type=openapi.TYPE_ARRAY,
                items=openapi.Items(type=openapi.TYPE_STRING),
            ),
        ],
        responses=base_swagger_responses(
            204, 401, 403,
            kparams={200: ReportChartStatisticSerializer(many=True)}
        )
    )
    def get(self, request, worker_id):
        worker = get_object_or_404(Worker, id=worker_id)
        period = request.GET.get('period', 'day')
        types = request.GET.get('types', 'profit,avg')
        types = types.split(',')
        labels = None
        datasets = []

        type_ = 'profit'
        if type_ in types:
            qs = DateTimeStatistic(
                worker.tasks, 'created_at', 'created_at', period, 'sum',
                'delivery_cost'
            )
            result = qs.get_chart_data()
            # TODO: refactoring, outgoing to templates
            dataset = {
                'label': type_, 'data': result['count'].values(),
                'backgroundColor': '#ffc1079c', 'borderColor': 'danger',
                'borderWidth': 1
            }
            datasets.append(dataset)
            labels = qs.labels

        type_ = 'avg'
        if type_ in types:
            qs = DateTimeStatistic(
                worker.tasks, 'created_at', 'created_at', period, 'avg',
                'delivery_cost'
            )
            result = qs.get_chart_data()
            # TODO: refactoring, outgoing to templates
            dataset = {
                'label': type_, 'data': result['count'].values(),
                'backgroundColor': '#3bafdac7', 'borderColor': 'danger',
                'borderWidth': 1
            }
            datasets.append(dataset)
            labels = qs.labels

        if not labels:
            return Response(
                {"type": "No such type {0}".format(types)}, 403
            )

        serializer = ReportChartStatisticSerializer(
            {'labels': labels, 'datasets': datasets}
        )
        if serializer.data:
            return Response(serializer.data, 200)
        return Response(serializer.data, 204)
Beispiel #19
0
class ReportCustomersChart(APIView):
    permission_classes = [ReportCustomersChartAccessPolicy, ]

    @swagger_auto_schema(
        tags=['Reports Chart'],
        operation_description="The method displays aggregated data for "
                              "periods.",
        manual_parameters=[
            openapi.Parameter(
                'period',
                openapi.IN_QUERY,
                description="Type of Period (day, week, month, year)",
                type=openapi.TYPE_STRING,
                default='day'
            ),
            openapi.Parameter(
                'types',
                openapi.IN_QUERY,
                description="Type of Aggregation Schedules Required "
                            "(registered, profit, avg)",
                type=openapi.TYPE_ARRAY,
                items=openapi.Items(type=openapi.TYPE_STRING),
            ),
        ],
        responses=base_swagger_responses(
            204, 401, 403,
            kparams={200: ReportChartStatisticSerializer()}
        )
    )
    def get(self, request):
        period = request.GET.get('period', 'day')
        types = request.GET.get('types', 'registered,profit,avg')
        types = types.split(',')
        labels = None
        datasets = []
        type_ = 'profit'
        if type_ in types:
            qs = DateTimeStatistic(
                Customer.objects, 'tasks__created_at', 'created_at', period,
                'sum', 'tasks__delivery_cost'
            )
            result = qs.get_chart_data()
            # TODO: refactoring, outgoing to templates
            dataset = {
                'label': type_, 'data': result['count'].values(),
                'backgroundColor': '#ffc1079c', 'borderColor': 'info',
                'borderWidth': 1
            }
            datasets.append(dataset)
            labels = qs.labels

        type_ = 'avg'
        if type_ in types:
            qs = DateTimeStatistic(
                Customer.objects, 'tasks__created_at', 'created_at', period,
                'avg', 'tasks__delivery_cost'
            )
            result = qs.get_chart_data()
            # TODO: refactoring, outgoing to templates
            dataset = {
                'label': type_, 'data': result['count'].values(),
                'backgroundColor': '#3bafdac7', 'borderColor': 'danger',
                'borderWidth': 1
            }
            datasets.append(dataset)
            labels = qs.labels

        type_ = 'registered'
        if type_ in types:
            qs = DateTimeStatistic(
                Customer.objects, 'user__date_joined', 'date_joined', period,
                'count', 'id'
            )
            result = qs.get_chart_data()
            # TODO: refactoring, outgoing to templates
            dataset = {
                'label': type_, 'data': result['count'].values(),
                'backgroundColor': '#20C997', 'borderColor': 'danger',
                'borderWidth': 1
            }
            datasets.append(dataset)
            labels = qs.labels

        if not labels:
            return Response(
                {"type": "not one of the passed types is acceptable {0}".
                    format(types)}, 403
            )
        serializer = ReportChartStatisticSerializer(
            {'labels': labels, 'datasets': datasets}
        )
        if serializer.data:
            return Response(serializer.data, 200)
        return Response(serializer.data, 204)
Beispiel #20
0
class MonsterViewSet(viewsets.ModelViewSet):
    serializer_class = MonsterSerializer
    pagination_class = LargeResultsSetPagination
    http_method_names = ['get']

    @swagger_auto_schema(
        manual_parameters=[
            openapi.Parameter('base_class', openapi.IN_QUERY, "Monster Natural Stars",
                              type=openapi.TYPE_STRING, enum=[1, 2, 3, 4, 5, 6]),
            openapi.Parameter('family', openapi.IN_QUERY, "Monster Family", type=openapi.TYPE_STRING, enum=list(
                MonsterFamily.objects.values_list('name', flat=True))),
            openapi.Parameter('attribute', openapi.IN_QUERY, "Monster Attribute",
                              type=openapi.TYPE_STRING, enum=MonsterBase.get_monster_attributes()),
            openapi.Parameter('archetype', openapi.IN_QUERY, "Monster Archetype",
                              type=openapi.TYPE_STRING, enum=MonsterBase.get_monster_archetypes()),
            openapi.Parameter('base_monster', openapi.IN_QUERY, "Base Monster", type=openapi.TYPE_STRING, enum=list(
                MonsterBase.objects.values_list('name', flat=True))),
            openapi.Parameter('awaken', openapi.IN_QUERY, "Monster Awaken Status",
                              type=openapi.TYPE_STRING, enum=MonsterBase.get_monster_awakens()),
            openapi.Parameter('level_min', openapi.IN_QUERY,
                              "Monster Minimum Level", type=openapi.TYPE_INTEGER),
            openapi.Parameter('stars', openapi.IN_QUERY, "Monster Stars",
                              type=openapi.TYPE_INTEGER, enum=[1, 2, 3, 4, 5, 6]),

            openapi.Parameter('hp', openapi.IN_QUERY, "Monster HP (min,max)", type=openapi.TYPE_ARRAY,
                              items=openapi.Items(type=openapi.TYPE_INTEGER), min_items=2, max_items=2),
            openapi.Parameter('attack', openapi.IN_QUERY, "Monster Attack (min,max)", type=openapi.TYPE_ARRAY,
                              items=openapi.Items(type=openapi.TYPE_INTEGER), min_items=2, max_items=2),
            openapi.Parameter('defense', openapi.IN_QUERY, "Monster Defense (min,max)", type=openapi.TYPE_ARRAY,
                              items=openapi.Items(type=openapi.TYPE_INTEGER), min_items=2, max_items=2),
            openapi.Parameter('speed', openapi.IN_QUERY, "Monster Speed (min,max)", type=openapi.TYPE_ARRAY,
                              items=openapi.Items(type=openapi.TYPE_INTEGER), min_items=2, max_items=2),
            openapi.Parameter('res', openapi.IN_QUERY, "Monster Resistance (min,max)", type=openapi.TYPE_ARRAY,
                              items=openapi.Items(type=openapi.TYPE_INTEGER), min_items=2, max_items=2),
            openapi.Parameter('acc', openapi.IN_QUERY, "Monster Accuracy (min,max)", type=openapi.TYPE_ARRAY,
                              items=openapi.Items(type=openapi.TYPE_INTEGER), min_items=2, max_items=2),
            openapi.Parameter('crit_rate', openapi.IN_QUERY, "Monster Critical rate (min,max)",
                              type=openapi.TYPE_ARRAY, items=openapi.Items(type=openapi.TYPE_INTEGER), min_items=2, max_items=2),
            openapi.Parameter('crit_dmg', openapi.IN_QUERY, "Monster Critical Damage (min,max)",
                              type=openapi.TYPE_ARRAY, items=openapi.Items(type=openapi.TYPE_INTEGER), min_items=2, max_items=2),
            openapi.Parameter('eff_hp', openapi.IN_QUERY, "Monster Effective HP (min,max)", type=openapi.TYPE_ARRAY,
                              items=openapi.Items(type=openapi.TYPE_INTEGER), min_items=2, max_items=2),
            openapi.Parameter('avg_eff', openapi.IN_QUERY, "Monster Average Efficiency (min,max)",
                              type=openapi.TYPE_ARRAY, items=openapi.Items(type=openapi.TYPE_NUMBER), min_items=2, max_items=2),

            openapi.Parameter('transmog', openapi.IN_QUERY,
                              "If Monster has Transmog", type=openapi.TYPE_BOOLEAN),
            openapi.Parameter('storage', openapi.IN_QUERY,
                              "If Monster is in Storage", type=openapi.TYPE_BOOLEAN),
            openapi.Parameter('locked', openapi.IN_QUERY,
                              "If Monster is Locked", type=openapi.TYPE_BOOLEAN),
            openapi.Parameter('runes', openapi.IN_QUERY,
                              "If Monster has 6 equipped Runes", type=openapi.TYPE_BOOLEAN),
            openapi.Parameter('runes_rta', openapi.IN_QUERY,
                              "If Monster has 6 equipped Runes in RTA Rune Management System", type=openapi.TYPE_BOOLEAN),
            openapi.Parameter('artifacts', openapi.IN_QUERY,
                              "If Monster has 2 equipped Artifacts", type=openapi.TYPE_BOOLEAN),
            openapi.Parameter('artifacts_rta', openapi.IN_QUERY,
                              "If Monster has 2 equipped Artifacts in RTA Rune Management System", type=openapi.TYPE_BOOLEAN),
        ],
    )
    def list(self, request):
        return super().list(request)

    def get_queryset(self):
        queryset = Monster.objects.all()

        base_class = self.request.query_params.get('base_class', None)
        family = self.request.query_params.get('family', None)
        attribute = self.request.query_params.get('attribute', None)
        archetype = self.request.query_params.get('archetype', None)
        base_monster = self.request.query_params.get('base_monster', None)
        awaken = self.request.query_params.get('awaken', None)
        level_min = self.request.query_params.get('level_min', None)
        stars = self.request.query_params.get('stars', None)
        hp = self.request.query_params.get('hp', None)
        attack = self.request.query_params.get('attack', None)
        defense = self.request.query_params.get('defense', None)
        speed = self.request.query_params.get('speed', None)
        res = self.request.query_params.get('res', None)
        acc = self.request.query_params.get('acc', None)
        crit_rate = self.request.query_params.get('crit_rate', None)
        crit_dmg = self.request.query_params.get('crit_dmg', None)
        eff_hp = self.request.query_params.get('eff_hp', None)
        avg_eff = self.request.query_params.get('avg_eff', None)
        transmog = self.request.query_params.get('transmog', None)
        storage = self.request.query_params.get('storage', None)
        locked = self.request.query_params.get('locked', None)
        runes = self.request.query_params.get('runes', None)
        runes_rta = self.request.query_params.get('runes_rta', None)
        artifacts = self.request.query_params.get('artifacts', None)
        artifacts_rta = self.request.query_params.get('artifacts_rta', None)

        if base_class is not None:
            queryset = queryset.filter(base_monster__base_class=base_class)
        if family is not None:
            queryset = queryset.filter(base_monster__family__name=family)
        if attribute is not None:
            queryset = queryset.filter(
                base_monster__attribute=MonsterBase().get_attribute_id(attribute))
        if archetype is not None:
            queryset = queryset.filter(
                base_monster__archetype=MonsterBase().get_archetype_id(archetype))
        if base_monster is not None:
            queryset = queryset.filter(base_monster__name=base_monster)
        if awaken is not None:
            queryset = queryset.filter(
                base_monster__awaken=MonsterBase().get_awaken_id(awaken))
        if level_min is not None:
            queryset = queryset.filter(level__gte=level_min)
        if stars is not None:
            queryset = queryset.filter(stars=stars)
        if hp is not None and ',' in hp:
            if len(hp.split(',')) == 2:
                hp_min, hp_max = hp.split(',')
                queryset = queryset.filter(hp__gte=hp_min, hp__lte=hp_max)
        if attack is not None and ',' in attack:
            if len(attack.split(',')) == 2:
                attack_min, attack_max = attack.split(',')
                queryset = queryset.filter(
                    attack__gte=attack_min, attack__lte=attack_max)
        if defense is not None and ',' in defense:
            if len(defense.split(',')) == 2:
                defense_min, defense_max = defense.split(',')
                queryset = queryset.filter(
                    defense__gte=defense_min, defense__lte=defense_max)
        if speed is not None and ',' in speed:
            if len(speed.split(',')) == 2:
                speed_min, speed_max = speed.split(',')
                queryset = queryset.filter(
                    speed__gte=speed_min, speed__lte=speed_max)
        if res is not None and ',' in res:
            if len(res.split(',')) == 2:
                res_min, res_max = res.split(',')
                queryset = queryset.filter(res__gte=res_min, res__lte=res_max)
        if acc is not None and ',' in acc:
            if len(acc.split(',')) == 2:
                acc_min, acc_max = acc.split(',')
                queryset = queryset.filter(acc__gte=acc_min, acc__lte=acc_max)
        if crit_rate is not None and ',' in crit_rate:
            if len(crit_rate.split(',')) == 2:
                crit_rate_min, crit_rate_max = crit_rate.split(',')
                queryset = queryset.filter(
                    crit_rate__gte=crit_rate_min, crit_rate__lte=crit_rate_max)
        if crit_dmg is not None and ',' in crit_dmg:
            if len(crit_dmg.split(',')) == 2:
                crit_dmg_min, crit_dmg_max = crit_dmg.split(',')
                queryset = queryset.filter(
                    crit_dmg__gte=crit_dmg_min, crit_dmg__lte=crit_dmg_max)
        if eff_hp is not None and ',' in eff_hp:
            if len(eff_hp.split(',')) == 2:
                eff_hp_min, eff_hp_max = eff_hp.split(',')
                queryset = queryset.filter(
                    eff_hp__gte=eff_hp_min, eff_hp__lte=eff_hp_max)
        if avg_eff is not None and ',' in avg_eff:
            if len(avg_eff.split(',')) == 2:
                avg_eff_total_min, avg_eff_total_max = avg_eff.split(',')
                queryset = queryset.filter(
                    avg_eff_total__gte=avg_eff_total_min, avg_eff_total__lte=avg_eff_total_max)
        if transmog is not None:
            if transmog.lower() == 'true':
                queryset = queryset.filter(transmog=True)
            else:
                queryset = queryset.filter(transmog=False)
        if storage is not None:
            if storage.lower() == 'true':
                queryset = queryset.filter(storage=True)
            else:
                queryset = queryset.filter(storage=False)
        if locked is not None:
            if locked.lower() == 'true':
                queryset = queryset.filter(locked=True)
            else:
                queryset = queryset.filter(locked=False)
        if runes is not None:
            if runes.lower() == 'true':
                queryset = queryset.annotate(
                    runes_count=Count('runes')).filter(runes_count=6)
            else:
                queryset = queryset.annotate(
                    runes_count=Count('runes')).filter(runes_count__lt=6)
        if runes_rta is not None:
            if runes_rta.lower() == 'true':
                queryset = queryset.annotate(runes_rta_count=Count(
                    'runes_rta')).filter(runes_rta_count=6)
            else:
                queryset = queryset.annotate(runes_rta_count=Count(
                    'runes_rta')).filter(runes_rta_count__lt=6)
        if artifacts is not None:
            if artifacts.lower() == 'true':
                queryset = queryset.annotate(artifacts_count=Count(
                    'artifacts')).filter(artifacts_count=2)
            else:
                queryset = queryset.annotate(artifacts_count=Count(
                    'artifacts')).filter(artifacts_count__lt=2)
        if artifacts_rta is not None:
            if artifacts_rta.lower() == 'true':
                queryset = queryset.annotate(artifacts_rta_count=Count(
                    'artifacts_rta')).filter(artifacts_rta_count=2)
            else:
                queryset = queryset.annotate(artifacts_rta_count=Count(
                    'artifacts_rta')).filter(artifacts_rta_count__lt=2)

        return queryset.select_related('base_monster', 'base_monster__family').prefetch_related('runes', 'runes_rta', 'runes__rune_set', 'runes_rta__rune_set', 'artifacts', 'artifacts_rta', ).order_by('id')
Beispiel #21
0
from drf_yasg import openapi

community_schema = openapi.Schema(
    type=openapi.TYPE_OBJECT,
    properties={
        "name":
        openapi.Schema(type=openapi.TYPE_STRING,
                       description="Unique community slug"),
        "readable_name":
        openapi.Schema(type=openapi.TYPE_STRING,
                       description="Human-readable community name"),
        "plugins":
        openapi.Schema(
            type=openapi.TYPE_ARRAY,
            description="List of activated plugins and their configs",
            items=openapi.Items(openapi.TYPE_OBJECT),
        )
        #     openapi.Schema(
        #         type=openapi.TYPE_OBJECT,
        #         properties={
        #             "name": openapi.Schema(
        #                 type=openapi.TYPE_STRING,
        #                 description='plugin name'
        #             ),
        #             "config": openapi.Schema(
        #                 type=openapi.TYPE_OBJECT,
        #                 description='plugin config'
        #             )
        #         }))
        # ),
    },
Beispiel #22
0
from testers.serializers import TesterSerializer, DeviceSerializer
from .models import Tester, SUPPORTED_COUNTRIES, Device

SUPPORTED_COUNTRIES_VALUES = [c[0] for c in SUPPORTED_COUNTRIES]

# Values needed for generating swagger schema
testers_response = openapi.Response('response description',
                                    TesterSerializer(many=True))

devices_param = openapi.Parameter(
    'devices',
    openapi.IN_QUERY,
    description=
    "devices for which experience should be calculated, empty means all",
    type=openapi.TYPE_ARRAY,
    items=openapi.Items(type=openapi.TYPE_INTEGER))
countries_param = openapi.Parameter(
    'countries',
    openapi.IN_QUERY,
    description=
    "countries from which testers should be included, empty means any",
    type=openapi.TYPE_ARRAY,
    explode=True,
    items=openapi.Items(type=openapi.TYPE_STRING,
                        enum=SUPPORTED_COUNTRIES_VALUES),
)


@swagger_auto_schema(
    method='get',
    manual_parameters=[devices_param, countries_param],
Beispiel #23
0
        user_duc_address=duc_address,
        dividends=0,
    )
    deposit.save()

    response_data = DepositSerializer().to_representation(deposit)
    return Response(response_data)


@swagger_auto_schema(
    method='get',
    manual_parameters=[
        openapi.Parameter('wallet_ids',
                          openapi.IN_QUERY,
                          type=openapi.TYPE_ARRAY,
                          items=openapi.Items(type=openapi.TYPE_STRING))
    ],
    responses={200: DepositSerializer()},
)
@api_view(http_method_names=['GET'])
def get_deposits(request):
    wallet_ids = request.query_params.get('wallet_ids').split(',')
    deposits = Deposit.objects.filter(wallet_id__in=wallet_ids,
                                      cltv_details__withdrawn=False)

    response_data = DepositSerializer(many=True).to_representation(deposits)

    return Response(response_data)


@swagger_auto_schema(
                      description="customer id",
                      type=openapi.TYPE_INTEGER)
]

report_response_schema = openapi.Schema(
    type=openapi.TYPE_OBJECT,
    properties={
        'quiz':
        openapi.Schema(type=openapi.TYPE_ARRAY,
                       items=openapi.Items(
                           type=openapi.TYPE_OBJECT,
                           properties={
                               'question':
                               openapi.Schema(type=openapi.TYPE_STRING,
                                              description='question_text'),
                               'answer_text':
                               openapi.Schema(type=openapi.TYPE_STRING,
                                              description='text'),
                               'choice':
                               openapi.Schema(type=openapi.TYPE_STRING,
                                              description='text'),
                           },
                       ),
                       description='quiz_name'),
    })

report_response = {
    "200":
    openapi.Response(
        description="Return dict of quizzes with customer answers",
        schema=report_response_schema,
        examples={
Beispiel #25
0
class ReportTasksChart(APIView):
    permission_classes = (ReportTasksChartAccessPolicy,)

    @swagger_auto_schema(
        tags=['Reports Chart'],
        operation_description="The method returns an aggregated data object, "
                              "Task entities by period.",
        manual_parameters=[
            openapi.Parameter(
                'period',
                openapi.IN_QUERY,
                description="Type of Period (day, week, month, year)",
                type=openapi.TYPE_STRING,
                default='day'
            ),
            openapi.Parameter(
                'types',
                openapi.IN_QUERY,
                description="Type of Aggregation Schedules Required "
                            "(ready, all)",
                type=openapi.TYPE_ARRAY,
                items=openapi.Items(type=openapi.TYPE_STRING),
            ),
        ],
        responses=base_swagger_responses(
            204, 401, 403,
            kparams={200: ReportChartStatisticSerializer(many=True)}
        )
    )
    def get(self, request):
        period = request.GET.get('period', 'day')
        types = request.GET.get('types', 'ready,all')
        types = types.split(',')
        labels = None
        datasets = []

        type_ = 'ready'
        if type_ in types:
            values_expression = Case(
                When(status=type_.upper(), then='status')
            )
            qs = DateTimeStatistic(
                Task.objects, 'created_at', 'created_at', period, 'count',
                values_expression
                )
            result = qs.get_chart_data()
            # TODO: refactoring, outgoing to templates
            dataset = {
                'label': type_, 'data': result['count'].values(),
                'backgroundColor': '#3bafdac7', 'borderColor': 'info',
                'borderWidth': 1
            }
            datasets.append(dataset)
            labels = qs.labels

        type_ = 'all'
        if type_ in types:
            qs = DateTimeStatistic(
                Task.objects, 'created_at', 'created_at', period, 'count', 'id'
            )
            result = qs.get_chart_data()
            # TODO: refactoring, outgoing to templates
            dataset = {
                'label': type_, 'data': result['count'].values(),
                'backgroundColor': '#ffc1079c', 'borderColor': 'danger',
                'borderWidth': 1
            }
            datasets.append(dataset)
            labels = qs.labels

        if not labels:
            return Response(
                {"type": "not one of the passed types is acceptable {0}".
                    format(types)}, 403
            )
        serializer = ReportChartStatisticSerializer(
            {'labels': labels, 'datasets': datasets}
        )
        if serializer.data:
            return Response(serializer.data, 200)
        return Response(serializer.data, 204)
Beispiel #26
0
from drf_yasg import openapi


hash_item = openapi.Items(
    type=openapi.TYPE_STRING, pattern='base58 representation of sha256 hash(xpub, recovery_key, instant_key)'
)

result_schema = openapi.Schema(type=openapi.TYPE_STRING, description='success or error')
session_token_schema = openapi.Schema(type=openapi.TYPE_STRING, description='token for follow-up requests')
msg_schema = openapi.Schema(type=openapi.TYPE_STRING, description='error description or empty string')
error_code_schema = openapi.Schema(type=openapi.TYPE_INTEGER, description='internal error code')

def xresponse_ok(json_example={'result': 'success', 'error_code': 0, 'msg': '', 'data': {'actual_response': 'content'}}):
    return openapi.Response(
        description='OK response',
        examples={'application/json': json_example},
        schema=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            properties={
                'result': result_schema,
                'error_code': error_code_schema,
                'msg': msg_schema,
                'data': openapi.Schema(type=openapi.TYPE_OBJECT, description='response data')
            },
        ),
    )


def xresponse_nok(
    json_example={
        'result': 'error',
Beispiel #27
0
    name='retrieve',
    decorator=swagger_auto_schema(
        operation_description=
        "Downloads the project based on given project id and file format",
        manual_parameters=[
            openapi.Parameter(
                name='id',
                in_=openapi.IN_PATH,
                type=openapi.TYPE_INTEGER,
                description="Id of a project",
            ),
            openapi.Parameter(
                name='chapters',
                in_=openapi.IN_PATH,
                type=openapi.TYPE_ARRAY,
                items=openapi.Items(type=openapi.TYPE_INTEGER),
                description="Filter by chapters",
            ),
            openapi.Parameter(
                name='file_format',
                in_=openapi.IN_QUERY,
                type=openapi.TYPE_STRING,
                description="It can be 'mp3' or 'wav'",
            )
        ]))
class ExportViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Take.objects.all()
    serializer_class = TakeForZipSerializer
    authentication_classes = (TokenAuthentication, )
    permission_classes = (IsAuthenticated, )
class PublicacionDetail(APIView):
    def get_object(self, pk):
        try:
            pk = ObjectId(pk)
            return Publicacion.objects.get(pk=pk)
        except Publicacion.DoesNotExist:
            raise Http404

    @swagger_auto_schema(
        operation_description=
        "Devuelve la publicación según el id. \n Ejemplo: id = 5fbab0abbcbecf56728297aa",
        responses={200: PublicacionSerializer})
    def get(self, request, pk=None):
        if pk:
            pk = ObjectId(pk)
            publicacion = self.get_object(pk)
            serializer = PublicacionSerializer(publicacion)

        else:
            publicacion = Publicacion.objects.all()
            serializer = PublicacionSerializer(publicacion, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    @swagger_auto_schema(
        operation_description=
        'Modifica una publicación existente. Solo se permiten modificar los campos que aparecen en el request body. El resto no está permitido.\n Ejemplo: id = 5fbab0abbcbecf56728297aa \n data = \n {\n"titulo": "Titulo",\n  "descripcion": "Descripcion",\n  "localizacion": "Localizacion",\n  "tematica": [\n"Gato"\n],\n  "autor": "Marco"\n}',
        request_body=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            properties={
                'titulo':
                openapi.Schema(type=openapi.TYPE_STRING),
                'descripcion':
                openapi.Schema(type=openapi.TYPE_STRING),
                'localizacion':
                openapi.Schema(type=openapi.TYPE_STRING),
                'tematica':
                openapi.Schema(type=openapi.TYPE_ARRAY,
                               items=openapi.Items(type=openapi.TYPE_STRING)),
                'autor':
                openapi.Schema(type=openapi.TYPE_STRING),
            }),
        responses={
            202: "Modificación aceptada",
            400: "Error y sus causas"
        })
    def put(self, request, pk):
        pk = ObjectId(pk)
        publicacion = self.get_object(pk)
        publicacion.creador.listaPublicaciones.remove(publicacion)

        serializer = PublicacionSerializer(publicacion,
                                           data=request.data,
                                           partial=True)

        if serializer.is_valid():
            serializer.save()
            publicacion.creador.listaPublicaciones.append(publicacion)
            publicacion.creador.save()
            return Response(serializer.data, status=status.HTTP_202_ACCEPTED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    @swagger_auto_schema(
        operation_description=
        "Elimina una publicacion. Esto provocará cambios en los datos del usuario como listasComentariosPublicaciones y listasGraffitisPublicaciones  \n Ejemplo : id = 5fbab0abbcbecf56728297aa",
        responses={
            '204': 'Publicacion Eliminada',
            '404': 'Publicacion no encontrada'
        })
    def delete(self, request, pk):
        pk = ObjectId(pk)
        publicacion = self.get_object(pk)
        # Actualizar la lista de publicaciones del creador
        publicacion.creador.listaPublicaciones.remove(publicacion)
        publicacion.creador.save()

        # Actualizar la lista de graffitis de cada usuario relacionado
        for graffiti in publicacion.listaGraffitis:
            graffiti.autor.listaGraffitisPublicaciones.remove(publicacion)
            graffiti.autor.save()

        for comentario in publicacion.listaComentarios:
            comentario.autor.listaComentariosPublicaciones.remove(publicacion)
            comentario.autor.save()

        publicacion.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
Beispiel #29
0
class CreatePaymentView(APIView):
    '''
    Creating order, cancelling previous order if found.
    '''
    @swagger_auto_schema(
        operation_description="post user's payments",
        request_body=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            properties={
                'items':
                openapi.Schema(
                    type=openapi.TYPE_ARRAY,
                    items=openapi.Items(
                        type=openapi.TYPE_OBJECT,
                        properties={
                            'item_id':
                            openapi.Schema(type=openapi.TYPE_NUMBER),
                            'quantity':
                            openapi.Schema(type=openapi.TYPE_NUMBER),
                        },
                    ),
                ),
                'currency':
                openapi.Schema(type=openapi.TYPE_STRING),
                'paypal_id':
                openapi.Schema(type=openapi.TYPE_STRING),
                'shipping_address':
                openapi.Schema(
                    type=openapi.TYPE_OBJECT,
                    properties={
                        'first_name': openapi.Schema(type=openapi.TYPE_STRING),
                        'last_name': openapi.Schema(type=openapi.TYPE_STRING),
                        'company_name':
                        openapi.Schema(type=openapi.TYPE_STRING),
                        'country': openapi.Schema(type=openapi.TYPE_STRING),
                        'full_address':
                        openapi.Schema(type=openapi.TYPE_STRING),
                        'town': openapi.Schema(type=openapi.TYPE_STRING),
                        'county': openapi.Schema(type=openapi.TYPE_STRING),
                        'phone': openapi.Schema(type=openapi.TYPE_STRING),
                        'email': openapi.Schema(type=openapi.TYPE_STRING),
                    },
                )
            },
        ),
        responses={200: 'OK'},
    )
    def post(self, request, token):
        request_data = request.data
        print(request_data)
        token = Token.objects.get(key=token)
        user = AdvUser.objects.get(id=token.user_id)
        currency = request_data.get('currency')
        paypal_id = request.data.get('paypal_id')

        #cancelling previous order if found (only 1 order can be active for paying in crypto)
        previous = Order.objects.filter(user=user).filter(
            status="WAITING_FOR_PAYMENT")
        for prev in previous:
            if prev:
                prev.status = "CANCELLED"
                prev.save()
                prev_payments = Payment.objects.filter(order=prev)
                for payment in prev_payments:
                    item = Item.objects.get(id=payment.item_id)
                    item.supply += payment.quantity
                    item.reserved -= payment.quantity
                    item.save()
        order = Order(user=user, currency=currency)
        order.save()

        #check paypal currency
        if currency == 'paypal':
            res = check_paypal(paypal_id)
            if res != True:
                return Response(res, status=status.HTTP_400_BAD_REQUEST)

        #saving payment unique ShippingAddress if it is not saved in user info
        shipping_address = request.data.get('shipping_address')
        if shipping_address:
            address = ShippingAddress()
            address.save()
            serializer = PatchShippingAddressSerializer(
                address,
                data=request.data.get('shipping_address'),
                partial=True)
            if serializer.is_valid():
                serializer.save()
                order.shipping_address = address
                order.save()

        #save items in order, calculate total amount and fix current rates
        for request in request_data.get('items'):
            item_id = request.get('item_id')
            quantity = request.get('quantity')
            payment = Payment(order=order, item_id=item_id, quantity=quantity)
            payment.save()
            item = Item.objects.get(id=item_id)
            item.reserved += payment.quantity
            item.supply -= payment.quantity
            item.save()

        order.get_required_amount()
        order.fix_rates()

        response_data = {"id": order.id}
        if currency == 'paypal':
            process_correct_payment(order)
        return Response(response_data, status=status.HTTP_200_OK)
class PublicacionList(APIView):
    def get_object(self, pk):
        try:
            pk = ObjectId(pk)
            return Publicacion.objects.get(pk=pk)
        except Publicacion.DoesNotExist:
            raise Http404

    @swagger_auto_schema(
        operation_description=
        "Devuelve todos las publicaciones. \n Ejemplo: http://127.0.0.1:8000/publicaciones/",
        responses={'200': PublicacionSerializer(many=True)})
    def get(self, request, pk=None):
        if pk:
            pk = ObjectId(pk)
            publicacion = self.get_object(pk)
            serializer = PublicacionSerializer(publicacion)

        else:
            publicacion = Publicacion.objects.all()
            serializer = PublicacionSerializer(publicacion, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    @swagger_auto_schema(
        operation_description=
        'Crea una publicación. Mínimo deberá contener un graffiti y tanto el autor del graffiti como el creador de la publicación deberán ser identificadores de usuarios existentes en el sistema (Lo lógico es que sea el id del mismo usuario ya que es este el que está creando la publicación). \n Ejemplo: \n{\n"titulo": "Segundo graffiti",\n"descripcion": "El segundo de todos",\n"localizacion": "Malaga",\n"tematica": [\n"Perritos",\n"Calle"\n],\n"autor": "Marquitos",\n"creador": "5fbaaa1c875f83f6d3cb9a9d",\n"listaGraffitis": [\n {\n "imagen": "https://www.hola.com/imagenes/estar-bien/20190820147813/razas-perros-pequenos-parecen-grandes/0-711-550/razas-perro-pequenos-grandes-m.jpg",\n"estado": "perfecto",\n "fechaCaptura": "2020-11-26",\n "autor": "5fbaaa1c875f83f6d3cb9a9d"\n}\n]\n}',
        responses={
            '201': 'Publicacion creada',
            '400': 'Peticion mal formada'
        },
        request_body=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            properties={
                'titulo':
                openapi.Schema(type=openapi.TYPE_STRING),
                'descripcion':
                openapi.Schema(type=openapi.TYPE_STRING),
                'localizacion':
                openapi.Schema(type=openapi.TYPE_STRING),
                'tematica':
                openapi.Schema(type=openapi.TYPE_ARRAY,
                               items=openapi.Items(type=openapi.TYPE_STRING)),
                'autor':
                openapi.Schema(type=openapi.TYPE_STRING),
                'creador':
                openapi.Schema(type=openapi.TYPE_STRING),
                'listaGraffitis':
                openapi.Schema(
                    type=openapi.TYPE_ARRAY,
                    items=openapi.Items(
                        type=openapi.TYPE_OBJECT,
                        properties={
                            'imagen':
                            openapi.Schema(type=openapi.TYPE_STRING),
                            'estado':
                            openapi.Schema(type=openapi.TYPE_STRING),
                            'fechaCaptura':
                            openapi.Schema(type=openapi.TYPE_STRING,
                                           format=openapi.FORMAT_DATE),
                            'autor':
                            openapi.Schema(type=openapi.TYPE_STRING)
                        }))
            }),
    )
    def post(self, request, pk=None):
        """Permite crear una nueva publicacion, que deberá seguir el formato especificado. 
        Los cambos listaComentarios y meGusta deberán dejarse como listas vacías([]), mínimo deberá contener un graffiti y tanto el autor del graffiti como el creador de la publicación deberán ser identificadores de usuarios existentes en el sistema (Lo lógico es que sea el id del mismo usuario ya que es este el que está creando la publicación)."""
        serializer = PublicacionSerializer(data=request.data)
        if serializer.is_valid():
            publicacion = serializer.save()  # Guardar la publicacion

            # Actualizar los campos de los usuarios
            publicacion.creador.listaPublicaciones.append(publicacion)
            publicacion.creador.save()

            # Actualizar Graffiti...
            for graffiti in publicacion.listaGraffitis:
                graffiti.autor.listaGraffitisPublicaciones.append(publicacion)
                graffiti.autor.save()

            # Actualizar Comentarios...
            for comentario in publicacion.listaComentarios:
                comentario.autor.listaComentariosPublicaciones.append(
                    publicacion)
                comentario.autor.save()

            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)