Fakultas Ilmu Komputer UI

Commit 85534b21 authored by Muhammad Rafif Elfazri's avatar Muhammad Rafif Elfazri
Browse files

Refactor Fasilitas and Likes Disilikes API

parent 9460065c
# Generated by Django 3.1.7 on 2021-06-01 05:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('informasi_fasilitas', '0019_auto_20210527_2251'),
]
operations = [
migrations.AlterField(
model_name='kegiatan',
name='zona_waktu',
field=models.CharField(choices=[('WIB', 'WIB'), ('WITA', 'WITA'), ('WIT', 'WIT')], default='WIB', max_length=4),
),
migrations.AlterUniqueTogether(
name='fasilitas',
unique_together={('lokasi', 'tag')},
),
]
# Generated by Django 3.1.7 on 2021-06-01 06:31
from django.conf import settings
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('informasi_fasilitas', '0020_auto_20210601_0503'),
]
operations = [
migrations.AlterUniqueTogether(
name='dislikes',
unique_together={('user', 'fasilitas')},
),
migrations.AlterUniqueTogether(
name='likes',
unique_together={('user', 'fasilitas')},
),
]
......@@ -79,6 +79,9 @@ class Fasilitas(models.Model):
image = models.ImageField(upload_to="fasilitas/", null=True, default=None)
is_verified = models.BooleanField(default=False)
class Meta:
unique_together = ('lokasi', 'tag')
class Kegiatan(models.Model):
objects = models.Manager()
......@@ -111,12 +114,18 @@ class Likes(models.Model):
fasilitas = models.ForeignKey(Fasilitas, on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
class Meta:
unique_together = ('user', 'fasilitas')
class Dislikes(models.Model):
objects = models.Manager()
user = models.ForeignKey(User, on_delete=models.CASCADE)
fasilitas = models.ForeignKey(Fasilitas, on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
class Meta:
unique_together = ('user', 'fasilitas')
class KomentarKegiatan(models.Model):
objects = models.Manager()
user = models.ForeignKey(User, on_delete=models.CASCADE)
......
from rest_framework import serializers
from .models import Lokasi, Kegiatan, KomentarKegiatan, FotoKegiatan
from .models import Lokasi, Fasilitas, Kegiatan, \
KomentarKegiatan, FotoKegiatan, Likes, Dislikes
import pytz
TIMEZONE_INDONESIA = {
......@@ -33,6 +34,70 @@ class LokasiSerializer(serializers.ModelSerializer):
}
class FasilitasSerializer(serializers.ModelSerializer):
class Meta:
model = Fasilitas
fields = ("id", "date_time", "deskripsi", "like",
"dislike", "rating", "tag", "disabilitas",
"jumlah", "image", "is_verified")
class FasilitasSerializerWrite(FasilitasSerializer):
class Meta:
model = FasilitasSerializer.Meta.model
fields = FasilitasSerializer.Meta.fields + ('lokasi', 'user')
extra_kwargs = {
'lokasi': {'required': True},
'user': {'required': True},
'tag': {"required": True},
'deskripsi':{"required": True},
'rating': {"required": True},
'disabilitas': {"required": True},
'jumlah': {"required": True},
}
class FasilitasSerializerRead(FasilitasSerializer):
place_id = serializers.CharField(source='lokasi.place_id', read_only=True)
creator = serializers.CharField(source='user.last_name', read_only=True)
creator_email = serializers.CharField(source='user.email', read_only=True)
date_time = serializers.SerializerMethodField()
image = serializers.SerializerMethodField()
like = serializers.SerializerMethodField()
dislike = serializers.SerializerMethodField()
def get_date_time(self, obj):
time = obj.date_time
return time.strftime("%d-%m-%Y %H:%M:%S")
def get_image(self, obj):
image = obj.image
return '/media/' + str(image)
def get_like(self, obj):
likes = obj.likes_set.count()
return likes
def get_dislike(self, obj):
dislike = obj.dislikes_set.count()
return dislike
class Meta:
model = FasilitasSerializer.Meta.model
fields = FasilitasSerializer.Meta.fields + ('place_id', 'creator', "creator_email")
class LikesSerializer(serializers.ModelSerializer):
class Meta:
model = Likes
fields = '__all__'
class DislikesSerializer(serializers.ModelSerializer):
class Meta:
model = Dislikes
fields = '__all__'
class FotoKegiatanSerializer(serializers.ModelSerializer):
place_id = serializers.CharField(source='kegiatan.lokasi.place_id', read_only=True)
......
......@@ -21,8 +21,11 @@ class UpdatePlaceIdTest(TestCase):
"place_id": "IEUBJWLNDSOHIUJL",
"timestamp": time - timedelta(days=120)
})
fasilitas_dict = factory.mock_fasilitas_test.copy()
fasilitas_dict.update({"tag": 'RT'})
fasilitas1 = factory.create_fasilitas_test(user=user, lokasi=lokasi2)
fasilitas2 = factory.create_fasilitas_test(user=user, lokasi=lokasi2)
fasilitas2 = factory.create_fasilitas_test(user=user, lokasi=lokasi2,
fasilitas_dict=fasilitas_dict)
@patch('informasi_fasilitas.management.commands.update_place_id.requests.get')
def test_lokasi_expired(self, mock_get):
......
......@@ -170,6 +170,5 @@ class FasilitasRelatedViewTest(InformasiFasilitasViewTest):
'rating': 3,
'tag': 'KR',
}
response = self.client.put(self.update_fasilitas_url, data=send_data,
content_type=self.put_content_type)
response = self.client.put(self.update_fasilitas_url, data=send_data)
self.assertEqual(response.status_code, HTTPStatus.ACCEPTED)
from http import HTTPStatus
from django.http import JsonResponse
from django.db.utils import IntegrityError
from rest_framework.decorators import api_view, permission_classes, authentication_classes
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import viewsets
from rest_framework.exceptions import ValidationError
from notification.utils import send_komentar_notification
from .serializers import LokasiSerializer
from .serializers import LokasiSerializer, FasilitasSerializerRead,\
FasilitasSerializerWrite, LikesSerializer, DislikesSerializer
from .models import Lokasi, Fasilitas, Komentar, Likes, Dislikes
from .permissions import UserPermission
......@@ -56,31 +59,10 @@ def list_fasilitas(request, place_id):
try:
lokasi = Lokasi.objects.get(place_id=place_id)
list_fasilitas = Fasilitas.objects.filter(lokasi=lokasi)
return_json = {}
for fasilitas in list_fasilitas:
user = fasilitas.user
fasilitas.like = Likes.objects.filter(
fasilitas=fasilitas).count()
fasilitas.dislike = Dislikes.objects.filter(
fasilitas=fasilitas).count()
return_json[fasilitas.id] = {}
fasilitas_details = return_json[fasilitas.id]
fasilitas_details["id"] = fasilitas.id
fasilitas_details["creator_email"] = user.email
fasilitas_details["place_id"] = fasilitas.lokasi.place_id
fasilitas_details["deskripsi"] = fasilitas.deskripsi
fasilitas_details["creator"] = fasilitas.user.last_name
fasilitas_details["date_time"] = fasilitas.date_time.strftime(
TIME_FORMAT)
fasilitas_details["like"] = fasilitas.like
fasilitas_details["dislike"] = fasilitas.dislike
fasilitas_details["rating"] = fasilitas.rating
fasilitas_details["tag"] = fasilitas.tag
fasilitas_details["disabilitas"] = fasilitas.disabilitas
fasilitas_details["jumlah"] = fasilitas.jumlah
fasilitas_details["image"] = '/media/'+str(fasilitas.image)
fasilitas_details["is_verified"] = fasilitas.is_verified
return JsonResponse(return_json, status=HTTPStatus.OK)
serializer = FasilitasSerializerRead(list_fasilitas, many=True)
data_response = serializer.data
new_dict = {item['id']: dict(item) for item in data_response}
return JsonResponse(new_dict, status=HTTPStatus.OK)
except Exception as error:
return JsonResponse({'response': str(error)}, status=HTTPStatus.NOT_FOUND)
......@@ -91,34 +73,28 @@ def list_fasilitas(request, place_id):
def add_fasilitas(request, place_id):
try:
lokasi = Lokasi.objects.get(place_id=place_id)
deskripsi = request.POST['deskripsi']
rating = request.POST['rating']
tag = request.POST['tag']
disabilitas = request.POST['disabilitas']
jumlah = request.POST['jumlah']
image = ""
if Fasilitas.objects.filter(lokasi=lokasi.pk, tag=tag).count() > 0:
return JsonResponse({'response': 'fasilitas already exist'},
status=HTTPStatus.OK)
if tag == "":
return JsonResponse({'response': 'tag cannot be null'},
status=HTTPStatus.BAD_REQUEST)
if 'image' in request.FILES.keys():
image = request.FILES['image']
fasilitas = Fasilitas.objects.create(lokasi=lokasi,
user=request.user,
deskripsi=deskripsi,
rating=rating,
tag=tag,
disabilitas=disabilitas,
jumlah=jumlah,
image=image)
user = request.user
data = request.data.dict()
data.update({"lokasi": lokasi.id, "user": user.id})
serializer = FasilitasSerializerWrite(data=data)
serializer.is_valid(raise_exception=True)
fasilitas = serializer.save()
return JsonResponse({'response': 'fasilitas added', 'id': fasilitas.id},
status=HTTPStatus.CREATED)
except KeyError as missing_key:
return JsonResponse({'response': missing_key_message(str(missing_key))},
status=HTTPStatus.BAD_REQUEST)
except Exception as error:
except ValidationError as error:
error_detail = error.get_full_details()
if 'non_field_errors' in error_detail:
return JsonResponse({'response': 'fasilitas already exist'},
status=HTTPStatus.OK)
if "tag" in error_detail:
if error_detail["tag"][0]["code"] == 'invalid_choice':
return JsonResponse({'response': 'tag cannot be null'},
status=HTTPStatus.BAD_REQUEST)
else:
return JsonResponse({'response': "Bad Request. 'tag' key is needed"},
status=HTTPStatus.BAD_REQUEST)
raise error
except Lokasi.DoesNotExist as error:
return JsonResponse({'response': str(error)}, status=HTTPStatus.NOT_FOUND)
......@@ -128,28 +104,8 @@ def add_fasilitas(request, place_id):
def detail_fasilitas(request, place_id, id):
try:
fasilitas = Fasilitas.objects.get(lokasi__place_id=place_id, id=id)
user = fasilitas.user
fasilitas.like = Likes.objects.filter(fasilitas=fasilitas).count()
fasilitas.dislike = Dislikes.objects.filter(
fasilitas=fasilitas).count()
return_json = {"id": fasilitas.id,
"place_id": fasilitas.lokasi.place_id,
"deskripsi": fasilitas.deskripsi,
"creator": user.last_name,
"creator_email": user.email,
"date_time": fasilitas.date_time.strftime(TIME_FORMAT),
"like": fasilitas.like,
"dislike": fasilitas.dislike,
"rating": fasilitas.rating,
"tag": fasilitas.tag,
"disabilitas": fasilitas.disabilitas,
"jumlah": fasilitas.jumlah,
"image": '/media/' + str(fasilitas.image),
"is_verified": fasilitas.is_verified}
return JsonResponse(return_json, status=HTTPStatus.OK)
except KeyError as missing_key:
return JsonResponse({'response': missing_key_message(str(missing_key))},
status=HTTPStatus.BAD_REQUEST)
serializer = FasilitasSerializerRead(fasilitas, many=False)
return JsonResponse(serializer.data, status=HTTPStatus.OK)
except Exception as error:
return JsonResponse({'response': str(error)}, status=HTTPStatus.NOT_FOUND)
......@@ -161,35 +117,15 @@ def update_fasilitas(request, place_id, id):
try:
fasilitas = Fasilitas.objects.get(lokasi__place_id=place_id, id=id)
user_creator = fasilitas.user
desc = fasilitas.deskripsi
tag = fasilitas.tag
jumlah = fasilitas.jumlah
image = fasilitas.image
disabilitas = fasilitas.disabilitas
if user_creator == request.user:
if 'deskripsi' in request.data.keys():
desc = request.data['deskripsi']
if 'tag' in request.data.keys():
tag = request.data['tag'].split()
if 'jumlah' in request.data.keys():
jumlah = request.data['jumlah']
if 'image' in request.data.keys():
image = request.data['image']
if 'disabilitas' in request.data.keys():
disabilitas = request.data['disabilitas']
fasilitas.deskripsi = desc
fasilitas.tag = tag
fasilitas.jumlah = jumlah
fasilitas.image = image
fasilitas.disabilitas = disabilitas
fasilitas.save()
data = request.data.dict()
serializer = FasilitasSerializerWrite(fasilitas, data=data, partial=True)
serializer.is_valid(raise_exception=True)
serializer.save()
return JsonResponse({'response': '{} in fasilitas edited'.format(str(request.data.keys())), },
status=HTTPStatus.ACCEPTED)
return JsonResponse({'response': 'Authentication failed'},
status=HTTPStatus.UNAUTHORIZED)
except KeyError as missing_key:
return JsonResponse({'response': missing_key_message(str(missing_key))},
status=HTTPStatus.BAD_REQUEST)
except Exception as error:
return JsonResponse({'response': str(error)}, status=HTTPStatus.NOT_FOUND)
......@@ -201,35 +137,32 @@ def update_like_fasilitas(request, place_id, id, operation):
try:
fasilitas = Fasilitas.objects.get(lokasi__place_id=place_id, id=id)
user = request.user
try:
like = Likes.objects.get(fasilitas=fasilitas, user=user)
except Likes.DoesNotExist:
like = None
try:
dislike = Dislikes.objects.get(fasilitas=fasilitas, user=user)
except Dislikes.DoesNotExist:
dislike = None
serializer_kwargs = {"user": user.id, "fasilitas": fasilitas.id}
if operation == "like":
if like != None:
return JsonResponse({'response': "You have already liked this facility"}, status=HTTPStatus.ACCEPTED)
else:
Likes.objects.create(fasilitas=fasilitas, user=user)
if dislike != None:
dislike.delete()
try:
serializer = LikesSerializer(data=serializer_kwargs)
serializer.is_valid(raise_exception=True)
serializer.save()
Dislikes.objects.filter(**serializer_kwargs).delete()
except ValidationError:
return JsonResponse({'response': "You have already liked this facility"},
status=HTTPStatus.ACCEPTED)
elif operation == "dislike":
if dislike != None:
return JsonResponse({'response': "You have already disliked this facility"}, status=HTTPStatus.ACCEPTED)
else:
Dislikes.objects.create(fasilitas=fasilitas, user=user)
if like != None:
like.delete()
try:
serializer = DislikesSerializer(data=serializer_kwargs)
serializer.is_valid(raise_exception=True)
serializer.save()
Likes.objects.filter(**serializer_kwargs).delete()
except ValidationError:
return JsonResponse({'response': "You have already disliked this facility"},
status=HTTPStatus.ACCEPTED)
fasilitas.like = Likes.objects.filter(fasilitas=fasilitas).count()
fasilitas.dislike = Dislikes.objects.filter(
fasilitas=fasilitas).count()
return JsonResponse({'response': "You have successfuly {}d this facility".format(operation)}, status=HTTPStatus.CREATED)
except KeyError as missing_key:
return JsonResponse({'response': missing_key_message(str(missing_key))}, status=HTTPStatus.BAD_REQUEST)
fasilitas.save()
return JsonResponse({'response': "You have successfuly {}d this facility".format(operation)},
status=HTTPStatus.CREATED)
except Exception as error:
return JsonResponse({'response': str(error)}, status=HTTPStatus.NOT_FOUND)
......
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