api.py 2.98 KB
from rest_framework import viewsets, mixins, status, serializers
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
from .serializer import EdictoSerializer, PrecioSerializer
from .utils import contador
# from .precio import contador


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

    serializer_class = EdictoSerializer
    permission_classes = [IsAuthenticated, ]

    def get_queryset(self):

        return Edicto.objects.all().order_by('usuario_id')

    def list(self, request, *args, **kwargs):
        fields_to_select = [
            'id',
            'estado',
            'cuerpo_edicto',
            'cantidad_palabras',
            'dias_publicar',
            'cantidad_sellos',
            'cantidad_copias',
            'archivo',
            'fecha_creacion',
            'observaciones',
            'fecha_publicacion',
        ]
        queryset = self.filter_queryset(self.get_queryset().values(*fields_to_select))
        user_id = request.user.id
        response_data = {
            'user_id': user_id,
            'edictos': queryset,
        }
        return Response(response_data)

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

    @action(detail=True, methods=['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(mixins.CreateModelMixin,
                    mixins.RetrieveModelMixin,
                    mixins.ListModelMixin,
                    viewsets.GenericViewSet):

    queryset = Precio.objects.all().order_by('id')
    serializer_class = PrecioSerializer
    permission_classes = [IsAuthenticated, ]

    def create(self, request, *args, **kwargs):
        user = request.user

        if not user.is_staff:
            raise serializers.ValidationError("El usuario no es parte del personal designado.")

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

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        data = serializer.data
        data['id'] = instance.id
        return Response(data)