Fakultas Ilmu Komputer UI

Commit 803449bf authored by Jonathan Christopher Jakub's avatar Jonathan Christopher Jakub
Browse files

[RED] Implement new combined logs list endpoint

parent c6d5e1a3
......@@ -12,31 +12,10 @@ ACTIVITY_TYPE_CHOICES = (
("Delete", "Delete"),
)
MODEL_NAME_CHOICES = (
("Account", "Account"),
("CaseSubject", "CaseSubject"),
("InvestigationCase", "InvestigationCase"),
("MonitoringCase", "MonitoringCase"),
)
MODEL_APP_MAPPING = {
"Account": "accounts",
"CaseSubject": "cases",
"InvestigationCase": "cases",
"MonitoringCase": "cases",
}
MODEL_OBJECT_ID_MAPPING = {
"Account": "id",
"CaseSubject": "subject_id",
"InvestigationCase": "case_id",
"MonitoringCase": "case_id",
}
MODEL_NAME_ACCOUNT = "Account"
MODEL_NAME_CASE_SUBJECT = "CaseSubject"
MODEL_NAME_INVESTIGATION_CASE = "InvestigationCase"
MODEL_NAME_MONITORING_CASE = "MonitoringCase"
MODEL_NAME_CASE_SUBJECT = "Case Subject"
MODEL_NAME_INVESTIGATION_CASE = "Investigation Case"
MODEL_NAME_MONITORING_CASE = "Monitoring Case"
ACTIVITY_TYPE_CREATE = "Create"
ACTIVITY_TYPE_EDIT = "Edit"
......
from django.contrib import admin
from apps.logs.models import Log
admin.site.register(Log)
# Generated by Django 3.0.1 on 2020-04-18 18:56
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('logs', '0002_auto_20200413_2102'),
]
operations = [
migrations.DeleteModel(
name='Log',
),
]
import uuid
from django.apps import apps
from django.db import models
from apps.accounts.models import Account
from apps.constants import (
MODEL_APP_MAPPING,
ACTIVITY_TYPE_CHOICES,
MODEL_NAME_CHOICES,
MODEL_OBJECT_ID_MAPPING,
)
class Log(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
model_name = models.CharField(choices=MODEL_NAME_CHOICES, max_length=64)
revision_id = models.UUIDField(blank=True, null=True)
object_id = models.UUIDField()
action_type = models.CharField(choices=ACTIVITY_TYPE_CHOICES, max_length=64)
created_at = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(
Account, blank=True, null=True, on_delete=models.DO_NOTHING, related_name="log",
)
objects = models.Manager()
class Meta:
db_table = "activity_log"
verbose_name_plural = "activity logs"
ordering = ["-created_at"]
def __str__(self):
return f"{self.created_at} | [{self.action_type}] {self.model_name} - {self.author}"
def get_model(self):
model_app = MODEL_APP_MAPPING.get(self.model_name)
Model = apps.get_model(model_app, self.model_name)
return Model
@property
def latest_version(self):
Model = self.get_model()
id_field_name = MODEL_OBJECT_ID_MAPPING.get(self.model_name)
model_object = (
Model.objects.filter(**{id_field_name: self.object_id})
.order_by("-created_at")
.first()
)
return model_object
from rest_framework import serializers
from apps.logs.models import Log
from apps.accounts.serializers import AccountSerializer
from apps.accounts.models import AccountHistory
from apps.cases.models import (
CaseSubjectHistory,
InvestigationCaseHistory,
MonitoringCaseHistory,
)
from apps.constants import (
MODEL_NAME_ACCOUNT,
MODEL_NAME_CASE_SUBJECT,
MODEL_NAME_INVESTIGATION_CASE,
MODEL_NAME_MONITORING_CASE,
)
class LogSummarySerializer(serializers.ModelSerializer):
author = AccountSerializer()
latest_version = serializers.SerializerMethodField()
class LogSerializer(serializers.Serializer):
author = serializers.SerializerMethodField()
model_name = serializers.SerializerMethodField()
revision_id = serializers.UUIDField()
object_id = serializers.UUIDField()
action_type = serializers.CharField()
recorded_at = serializers.DateTimeField()
class Meta:
model = Log
fields = [
"id",
"model_name",
"revision_id",
"object_id",
"latest_version",
"model_name",
"action_type",
"created_at",
"recorded_at",
"author",
]
def get_latest_version(self, instance):
if instance.latest_version:
return str(instance.latest_version.pk)
def get_model_name(self, instance):
if isinstance(instance, AccountHistory):
return MODEL_NAME_ACCOUNT
if isinstance(instance, CaseSubjectHistory):
return MODEL_NAME_CASE_SUBJECT
if isinstance(instance, InvestigationCaseHistory):
return MODEL_NAME_INVESTIGATION_CASE
if isinstance(instance, MonitoringCaseHistory):
return MODEL_NAME_CASE_SUBJECT
def get_author(self, instance):
if hasattr(instance, "author"):
return AccountSerializer(instance.author).data
from django.contrib import admin
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from django.urls import path
from apps.logs.views import LogViewSet
from apps.logs.views import LogAPIView
router = DefaultRouter()
router.register(r"", LogViewSet, basename="log")
urlpatterns = [
path("", include(router.urls)),
path("", LogAPIView.as_view()),
]
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404
from rest_framework import status, viewsets
from itertools import chain
from rest_framework import status
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination
from django_filters.rest_framework import DjangoFilterBackend
from apps.logs.models import Log
from apps.logs.serializers import LogSummarySerializer
from apps.commons.permissions import IsAuthorOrAdministrator
from apps.accounts.models import AccountHistory
from apps.cases.models import (
CaseSubjectHistory,
InvestigationCaseHistory,
MonitoringCaseHistory,
)
from apps.commons.permissions import IsAuthenticated
from apps.logs.serializers import LogSerializer
class LogViewSet(viewsets.ViewSet):
queryset = Log.objects.all().select_related("author")
class LogAPIView(ListAPIView):
filter_backends = (DjangoFilterBackend,)
permission_classes = [
IsAuthorOrAdministrator,
]
permission_classes = (IsAuthenticated,)
def _get_logs_queryset(self, queryset, request):
account = request.user.account
if account.is_admin:
return queryset
return queryset.filter(author=account)
def get_queryset(self, request):
account = request.user.account
if account.is_admin:
account_logs = AccountHistory.objects.all()
else:
account_logs = AccountHistory.objects.filter(object_id=account.id)
case_subject_logs = (
self._get_logs_queryset(CaseSubjectHistory.objects.all(), request))
investigation_case_logs = (
self._get_logs_queryset(InvestigationCaseHistory.objects.all(), request))
monitoring_case_logs = (
self._get_logs_queryset(MonitoringCaseHistory.objects.all(), request))
return list(chain(
account_logs,
case_subject_logs,
investigation_case_logs,
monitoring_case_logs,
))
def get(self, request):
serializer_data = []
logs_querysets = self.get_queryset(request)
def list(self, request):
paginator = PageNumberPagination()
queryset = self.queryset.filter(author=request.user.account)
context = paginator.paginate_queryset(logs_querysets, request)
if request.user.account.is_admin:
queryset = Log.objects.all()
serializer = LogSerializer(data=logs_querysets, many=True, context=context)
serializer.is_valid()
serializer_data = serializer.data
context = paginator.paginate_queryset(queryset, request)
serializer = LogSummarySerializer(context, many=True)
return paginator.get_paginated_response(serializer.data)
return paginator.get_paginated_response(serializer_data)
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment