api.py 3.76 KB
from rest_framework import viewsets, filters, mixins, status
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import action
from datetime import datetime

from .models import Edicto, Precio, ComprobantePago
from .serializer import EdictoSerializer, PrecioSerializer, PagoSerializer, ComprobanteSerializer
from .filters import EdictoFilter, PrecioFilter
from .permissions import IsAdminOrAuthorized
from .utils import contador
from .precio import calculadora


class EdictoViewSet(mixins.CreateModelMixin,
                    mixins.RetrieveModelMixin,
                    mixins.UpdateModelMixin,
                    mixins.DestroyModelMixin,
                    mixins.ListModelMixin,
                    viewsets.GenericViewSet):

    serializer_class = EdictoSerializer
    permission_classes = [IsAuthenticated, ]
    filter_backends = (DjangoFilterBackend, filters.OrderingFilter)
    filterset_class = EdictoFilter
    queryset = Edicto.objects.all()
    ordering_fields = ('usuario',)
    ordering = 'usuario'

    def perform_create(self, serializer):
        edicto = self.request.data.get('cuerpo_edicto')
        cantidad_palabras = contador(edicto)
        usuario = self.request.user
        serializer.save(cantidad_palabras=cantidad_palabras, usuario=usuario)

    @action(detail=True, methods=['put', 'patch'])
    def custom_update(self, request):
        edicto = request.data.get('cuerpo_edicto')
        cantidad_palabras = contador(edicto)

        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(cantidad_palabras=cantidad_palabras, fecha_actualizacion=datetime.now())

        return Response(serializer.data, status=status.HTTP_200_OK)


class PrecioViewSet(viewsets.ReadOnlyModelViewSet):
    serializer_class = PrecioSerializer
    permission_classes = [IsAuthenticated, IsAdminOrAuthorized]
    filter_backends = (DjangoFilterBackend, filters.OrderingFilter)
    filterset_class = PrecioFilter
    ordering_fields = ('usuario', )
    ordering = 'usuario'
    queryset = Precio.objects.all()


class PagoViewSets(mixins.CreateModelMixin,
                   mixins.RetrieveModelMixin,
                   mixins.UpdateModelMixin,
                   mixins.DestroyModelMixin,
                   mixins.ListModelMixin,
                   viewsets.GenericViewSet):
    serializer_class = PagoSerializer
    permission_classes = [IsAuthenticated, IsAdminOrAuthorized]
    queryset = ComprobantePago.objects.all()

    def perform_create(self, serializer):
        try:
            edicto = Edicto.objects.get(estado='aprobado')
            precio_admi = Precio.objects.latest('id')
            precio = Precio.objects.get(id=precio_admi.id)
            monto = calculadora(edicto, precio)
            usuario_actual = self.request.user
            if edicto.usuario != usuario_actual:
                raise UsuarioNoAutorizado
            serializer.validated_data['monto'] = monto
            serializer.validated_data['edicto'] = edicto
            serializer.save()
        except Edicto.DoesNotExist:
            raise EdictoNoEncontrado
        except Precio.DoesNotExist:
            raise PrecioNoEncontrado


class ComprobanteViewSets(mixins.CreateModelMixin,
                          mixins.RetrieveModelMixin,
                          mixins.UpdateModelMixin,
                          mixins.DestroyModelMixin,
                          mixins.ListModelMixin,
                          viewsets.GenericViewSet):
    serializer_class = ComprobanteSerializer
    queryset = ComprobantePago.objects.all()
    permission_classes = [IsAuthenticated, ]