Fakultas Ilmu Komputer UI

Commit 53b06d5f authored by Dave Nathanael's avatar Dave Nathanael
Browse files

[GREEN] Rework on CaseSubject model

parent be1ac84b
Pipeline #40881 failed with stages
in 1 minute and 22 seconds
from django_filters import FilterSet
from django_filters.rest_framework import FilterSet
from apps.cases.models import (
CaseSubject,
InvestigationCase,
MonitoringCase,
)
from apps.cases.models import InvestigationCase, MonitoringCase
CASE_SUBJECT_FILTERSET_FIELDS = [
"name",
"age",
"is_male",
"address",
"district",
"sub_district",
"created_at",
]
class CaseSubjectFilter(FilterSet):
class Meta:
model = CaseSubject
fields = [
"age",
"is_male",
"address",
"district",
"sub_district",
]
CASE_SUBJECT_SEARCH_FIELDS = [
"name",
"age",
"address",
"district",
"sub_district",
"created_at",
]
class InvestigationCaseFilter(FilterSet):
......
# Generated by Django 3.0.1 on 2020-04-16 16:34
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
('accounts', '0001_initial'),
('cases', '0004_casesubject_author'),
]
operations = [
migrations.RenameField(
model_name='casesubject',
old_name='revision_id',
new_name='id',
),
migrations.RemoveField(
model_name='casesubject',
name='is_active',
),
migrations.RemoveField(
model_name='casesubject',
name='subject_id',
),
migrations.CreateModel(
name='CaseSubjectHistory',
fields=[
('revision_id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('object_id', models.UUIDField(default=uuid.uuid4, editable=False)),
('action_type', models.CharField(choices=[('Create', 'Create'), ('Edit', 'Edit'), ('Delete', 'Delete')], max_length=64)),
('recorded_at', models.DateTimeField(auto_now_add=True)),
('name', models.CharField(max_length=128)),
('age', models.IntegerField()),
('is_male', models.BooleanField(db_index=True)),
('address', models.CharField(max_length=256)),
('district', models.CharField(max_length=128)),
('sub_district', models.CharField(max_length=128)),
('author', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='case_subject_history', to='accounts.Account')),
],
options={
'verbose_name_plural': 'case subject histories',
'db_table': 'case_subject_history',
'ordering': ['-recorded_at'],
},
),
]
......@@ -5,22 +5,55 @@ from django.core.exceptions import ValidationError
from django.db import models
from apps.accounts.models import Account
from apps.commons.managers import SoftObjectManager
from apps.constants import TIMEZONE
from apps.commons.managers import SoftObjectManager, SoftDeleteManager
from apps.commons.models import HistoryEnabledModel
from apps.constants import (
TIMEZONE,
ACTIVITY_TYPE_CHOICES,
ACTIVITY_TYPE_CREATE,
ACTIVITY_TYPE_DELETE,
ACTIVITY_TYPE_EDIT,
)
class CaseSubjectHistory(models.Model):
revision_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
object_id = models.UUIDField(default=uuid.uuid4, editable=False)
action_type = models.CharField(choices=ACTIVITY_TYPE_CHOICES, max_length=64)
recorded_at = models.DateTimeField(auto_now_add=True)
name = models.CharField(max_length=128)
age = models.IntegerField()
is_male = models.BooleanField(db_index=True)
address = models.CharField(max_length=256)
district = models.CharField(max_length=128)
sub_district = models.CharField(max_length=128)
author = models.ForeignKey(
Account,
blank=True,
null=True,
on_delete=models.DO_NOTHING,
related_name="case_subject_history",
)
class Meta:
db_table = "case_subject_history"
verbose_name_plural = "case subject histories"
ordering = ["-recorded_at"]
class CaseSubject(models.Model):
revision_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
subject_id = models.UUIDField(default=uuid.uuid4, editable=False)
def __str__(self):
return (
f"[History] Rev. {self.revision_id} - {self.name} | "
+ f"{self.district}, {self.sub_district}"
)
class CaseSubject(HistoryEnabledModel):
name = models.CharField(max_length=128)
age = models.IntegerField()
is_male = models.BooleanField(db_index=True)
address = models.CharField(max_length=256)
district = models.CharField(max_length=128)
sub_district = models.CharField(max_length=128)
deleted_at = models.DateTimeField(blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True, db_index=True)
author = models.ForeignKey(
Account,
blank=True,
......@@ -28,8 +61,9 @@ class CaseSubject(models.Model):
on_delete=models.DO_NOTHING,
related_name="case_subject",
)
history_class = CaseSubjectHistory
objects = SoftObjectManager()
objects = SoftDeleteManager()
class Meta:
db_table = "case_subject"
......@@ -37,22 +71,11 @@ class CaseSubject(models.Model):
ordering = ["-created_at"]
def __str__(self):
if self.is_active:
return (
f"[Active] Rev. {self.revision_id} - {self.name} | "
+ f"{self.district}, {self.sub_district}"
)
return (
f"[Inactive] Rev. {self.revision_id} - {self.name} | "
f"[Active] ID. {self.id} - {self.name} | "
+ f"{self.district}, {self.sub_district}"
)
def delete(self):
if self.deleted_at is None:
self.is_active = False
self.deleted_at = datetime.now(tz=pytz.timezone(TIMEZONE))
self.save()
class InvestigationCase(models.Model):
revision_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
......
......@@ -3,6 +3,7 @@ from rest_framework import serializers
from apps.accounts.serializers import AccountSerializer
from apps.cases.models import (
CaseSubject,
CaseSubjectHistory,
InvestigationCase,
MonitoringCase,
)
......@@ -13,9 +14,27 @@ class CaseSubjectSerializer(serializers.ModelSerializer):
class Meta:
model = CaseSubject
fields = [
"id",
"name",
"age",
"is_male",
"address",
"district",
"sub_district",
"is_active",
"created_at",
]
class CaseSubjectHistorySerializer(serializers.ModelSerializer):
is_active = serializers.BooleanField(read_only=True)
class Meta:
model = CaseSubjectHistory
fields = [
"revision_id",
"subject_id",
"object_id",
"name",
"age",
"is_male",
......@@ -23,6 +42,8 @@ class CaseSubjectSerializer(serializers.ModelSerializer):
"district",
"sub_district",
"is_active",
"action_type",
"recorded_at",
]
......
......@@ -7,6 +7,7 @@ from rest_framework import status, viewsets
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination
from rest_framework.decorators import action
from rest_framework.filters import SearchFilter, OrderingFilter
from django_filters import FilterSet
from django_filters.rest_framework import DjangoFilterBackend
......@@ -23,7 +24,8 @@ from apps.cases.serializers import (
MonitoringCaseSerializer,
)
from apps.cases.filters import (
CaseSubjectFilter,
CASE_SUBJECT_FILTERSET_FIELDS,
CASE_SUBJECT_SEARCH_FIELDS,
InvestigationCaseFilter,
MonitoringCaseFilter,
)
......@@ -39,91 +41,15 @@ from apps.constants import (
)
class CaseSubjectViewSet(viewsets.ViewSet):
class CaseSubjectViewSet(viewsets.ModelViewSet):
serializer_class = CaseSubjectSerializer
queryset = CaseSubject.objects.active_revisions()
filter_backends = (DjangoFilterBackend,)
permission_classes = [
IsAuthorOrAdministrator,
]
def list(self, request):
paginator = PageNumberPagination()
filtered_set = CaseSubjectFilter(request.GET, queryset=self.queryset).qs
context = paginator.paginate_queryset(filtered_set, request)
serializer = self.serializer_class(context, many=True)
return paginator.get_paginated_response(serializer.data)
def retrieve(self, request, pk=None):
instance = get_object_or_404(self.queryset, pk=pk)
self.check_object_permissions(request, instance)
serializer = self.serializer_class(instance)
return Response(serializer.data, status=status.HTTP_200_OK)
def create(self, request):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
serializer_data = serializer.data
instance = CaseSubject.objects.create(
**serializer_data, author=request.user.account
)
# Add case subject creation log
Log.objects.create(
model_name=MODEL_NAME_CASE_SUBJECT,
object_id=instance.subject_id,
revision_id=instance.revision_id,
action_type=ACTIVITY_TYPE_CREATE,
author=request.user.account,
)
return Response(
self.serializer_class(instance).data,
status=status.HTTP_201_CREATED,
)
def update(self, request, pk=None):
previous_instance = get_object_or_404(self.queryset, pk=pk)
self.check_object_permissions(request, previous_instance)
serializer = self.serializer_class(previous_instance, data=request.data)
serializer.is_valid(raise_exception=True)
serializer_data = serializer.validated_data
serializer_data["subject_id"] = previous_instance.subject_id
new_instance = CaseSubject.objects.create(**serializer_data, is_active=True,)
previous_instance.is_active = False
previous_instance.save()
# Add case subject update log
Log.objects.create(
model_name=MODEL_NAME_CASE_SUBJECT,
object_id=previous_instance.subject_id,
revision_id=previous_instance.revision_id,
action_type=ACTIVITY_TYPE_EDIT,
author=request.user.account,
)
update_serializer = self.serializer_class(instance=new_instance)
return Response(update_serializer.data, status=status.HTTP_200_OK)
def destroy(self, request, pk=None):
instance = get_object_or_404(self.queryset, pk=pk)
self.check_object_permissions(request, instance)
instance.delete()
# Add case subject deletion log
Log.objects.create(
model_name=MODEL_NAME_CASE_SUBJECT,
object_id=instance.subject_id,
revision_id=instance.revision_id,
action_type=ACTIVITY_TYPE_DELETE,
author=request.user.account,
)
serializer = self.serializer_class(instance=instance)
return Response(serializer.data, status=status.HTTP_200_OK)
queryset = CaseSubject.objects.all()
filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter)
filterset_fields = CASE_SUBJECT_FILTERSET_FIELDS
permission_classes = (IsAuthorOrAdministrator,)
pagination_class = PageNumberPagination
search_fields = CASE_SUBJECT_SEARCH_FIELDS
ordering_fields = CASE_SUBJECT_FILTERSET_FIELDS
class InvestigationCaseViewSet(viewsets.ViewSet):
......
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