mixins.py 2.84 KB
from typing import Optional
from actstream import action
from actstream.models import Action
from django.contrib.contenttypes.models import ContentType
from rest_framework.response import Response
from rest_framework import status

from core.constants import iniciado
from core.serializers import ActionSerializer


# class FiltroObligatorioMixin(object):
#     nombre_filtro_obligatorio: Optional[str] = None
#
#     def get_queryset(self):
#         queryset = super().get_queryset()
#
#         if not self.action == 'list':
#             return queryset
#
#         # en el caso de que la accion sea listar, controlar que vengan los datos del filtro indicado
#         filtro = self.request.GET.get(self.get_nombre_filtro_obligatorio(), None)
#         if filtro:
#             return queryset
#
#         return queryset.none()
#
#     def get_nombre_filtro_obligatorio(self):
#         assert self.nombre_filtro_obligatorio is not None, (
#                 "Debe definir el atributo nombre_filtro_obligatorio a la clase '%s'"
#                 % self.__class__.__name__
#         )
#
#         return self.nombre_filtro_obligatorio


class AuditoriaMixin:

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        action_object = serializer.instance

        self.registrar_accion(usuario=self.request.user, verb=iniciado, instance=serializer.instance,
                              data=serializer.data)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def perform_update(self, serializer):
        serializer_modificado = self.get_serializer(data=self.request.data)
        serializer_modificado.is_valid()
        serializer_accion = self.get_serializer(instance=serializer.instance)

        data = {'data_inicial': serializer_accion.data, 'data_modificada': serializer_modificado.data}

        self.registrar_accion(usuario=self.request.user, verb=serializer_modificado.data["estado"], instance=serializer.instance,
                              data=data)
        serializer.save()

    @staticmethod
    def registrar_accion(usuario, verb, instance, data=None, target=None):
        action.send(usuario, verb=verb, action_object=instance, target=target, data=data)

    @staticmethod
    def obtener_historial_acciones(content_type, action_objects_id, request):
        content_type = ContentType.objects.get(model=content_type)
        historial_actividades = Action.objects.filter(
            action_object_object_id__in=action_objects_id,
            action_object_content_type_id=content_type.id
        )
        serializer = ActionSerializer(historial_actividades, many=True, context={'request': request})
        return serializer