Fakultas Ilmu Komputer UI

Commit 3d50e470 authored by Glenda Emanuella Sutanto's avatar Glenda Emanuella Sutanto
Browse files

Merge branch 'PBI-11-ProfileDietkuClient' into 'staging'

Diet recommendation from nutritionist for client

See merge request !58
parents dc1454ce 8064b274
Pipeline #76241 passed with stages
in 12 minutes and 18 seconds
......@@ -21,7 +21,7 @@ class DietQuestionnaireViewSet(viewsets.ModelViewSet):
return Response(serializer.data, status=status.HTTP_200_OK)
def retrieve(self, request, pk=None):
instance = get_object_or_404(self.get_queryset(), pk=pk)
instance = get_object_or_404(DietQuestionnaire.objects.all(), pk=pk)
serializer = DietQuestionnaireSerializer(instance)
return Response(serializer.data, status=status.HTTP_200_OK)
......
......@@ -212,3 +212,4 @@ REST_AUTH_REGISTER_SERIALIZERS = {
}
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
......@@ -10,4 +13,4 @@ urlpatterns = [
path('', include('authentication.urls')),
path('', include('diet_questionnaire.urls')),
path('', include('profile_dietku.urls')),
]
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
......@@ -14,6 +14,7 @@ from dietela_program.models import DietelaProgram
from nutritionists.models import Nutritionist
from authentication.models import CustomUser
from diet_questionnaire.models import DietQuestionnaire
from profile_dietku.models import DietRecommendation
class CartTests(APITestCase):
......@@ -24,8 +25,6 @@ class CartTests(APITestCase):
cls.SET_TRANSACTION_STATUS_URL = "/payment/set-transaction-status/"
cls.MIDTRANS_REDIRECTION_URL = "/payment/midtrans-redirection/"
cls.custom_user = CustomUser.objects.create_user(name='tes', email='email@email.com', password='abc')
cls.dietela_program_1 = DietelaProgram.objects.create(
unique_code="PRG1",
name="Program 1",
......@@ -55,6 +54,13 @@ class CartTests(APITestCase):
languages="Bahasa Indonesia, Bahasa Inggris",
)
cls.custom_user = CustomUser.objects.create_user(
name='tes',
email='email@email.com',
password='abc',
nutritionist=cls.nutritionist_1,
)
cls.cart_1 = Cart.objects.create(
program = cls.dietela_program_1,
nutritionist = cls.nutritionist_1,
......@@ -165,6 +171,10 @@ class CartTests(APITestCase):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(DietQuestionnaire.objects.count(), 1)
self.assertEqual(DietQuestionnaire.objects.last().user, self.cart_3.user)
self.assertEqual(DietRecommendation.objects.count(), 1)
self.assertEqual(DietRecommendation.objects.last().client, self.cart_3.user)
self.assertEqual(DietRecommendation.objects.last().nutritionist, self.cart_3.user.nutritionist)
def test_midtrans_redirection_failed_because_cart_does_not_exist(self):
url = self.MIDTRANS_REDIRECTION_URL
......
......@@ -8,6 +8,7 @@ from constants.string_constants import CART_NOT_FOUND_MESSAGE
from dietela_program.serializers import DietelaProgramSerializer
from dietela_program.models import DietelaProgram
from diet_questionnaire.models import DietQuestionnaire
from profile_dietku.models import DietRecommendation
from .serializers import CartSerializer
from .models import Cart
......@@ -121,5 +122,9 @@ class MidtransRedirectionViewSet(viewsets.ViewSet):
cart.save()
DietQuestionnaire.objects.create(user=cart.user)
DietRecommendation.objects.create(
client=cart.user,
nutritionist=cart.user.nutritionist
)
return Response(status=status.HTTP_200_OK)
#from django.contrib import admin
from django.contrib import admin
from .models import DietRecommendation
# Register your models here.
admin.site.register(DietRecommendation)
# Generated by Django 3.1 on 2021-05-09 18:22
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('nutritionists', '0002_nutritionist_profile_picture'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='DietRecommendation',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('client_plan_meal', models.FileField(upload_to='')),
('nutritional_advice', models.TextField(blank=True, null=True)),
('lifestyle_advice', models.TextField(blank=True, null=True)),
('client', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
('nutritionist', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='nutritionists.nutritionist')),
],
),
]
# Generated by Django 3.1 on 2021-05-10 07:46
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('nutritionists', '0002_nutritionist_profile_picture'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('profile_dietku', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='dietrecommendation',
name='client',
field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='diet_recommendation', to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='dietrecommendation',
name='client_plan_meal',
field=models.FileField(blank=True, null=True, upload_to=''),
),
migrations.AlterField(
model_name='dietrecommendation',
name='nutritionist',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='diet_recommendation', to='nutritionists.nutritionist'),
),
]
# Generated by Django 3.1 on 2021-05-10 07:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('profile_dietku', '0002_auto_20210510_1446'),
]
operations = [
migrations.AlterField(
model_name='dietrecommendation',
name='client_plan_meal',
field=models.FileField(blank=True, null=True, upload_to='diet-recommendation'),
),
]
from django.db import models
from nutritionists.models import Nutritionist
from authentication.models import CustomUser
class DietRecommendation(models.Model):
nutritionist = models.ForeignKey(
Nutritionist,
on_delete=models.CASCADE,
related_name='diet_recommendation'
)
client = models.OneToOneField(
CustomUser,
on_delete=models.CASCADE,
related_name='diet_recommendation'
)
client_plan_meal = models.FileField(blank=True, null=True, upload_to='diet-recommendation')
nutritional_advice = models.TextField(blank=True, null=True)
lifestyle_advice = models.TextField(blank=True, null=True)
def __str__(self):
return f"{self.client} - {self.nutritionist}"
from rest_framework import serializers
from .models import DietRecommendation
class DietRecommendationSerializer(serializers.ModelSerializer):
class Meta:
model = DietRecommendation
fields = "__all__"
import json
from django.test import TestCase
from django.contrib.auth.models import Group
from django.core.files.uploadedfile import SimpleUploadedFile
from rest_framework.test import APITestCase, APIClient
from rest_framework import status
from dietela_quiz.models import DietProfile
from authentication.models import CustomUser
from nutritionists.models import Nutritionist
from diet_questionnaire.models import DietQuestionnaire
from authentication.serializers import CustomUserDetailsSerializer
from django.db.models import Q
from .models import DietRecommendation
class GetProfilesTest(APITestCase):
client = APIClient()
@classmethod
def setUpTestData(cls):
cls.BASE_URL = "/profiles/"
cls.SPECIFIC_URL = "/profiles/?nutritionist=1"
cls.diet_profile = DietProfile.objects.create(
cls.diet_profile_1 = DietProfile.objects.create(
name="test",
email="test@test.com",
age=20,
......@@ -38,6 +41,28 @@ class GetProfilesTest(APITestCase):
problem_to_solve=1,
health_problem=[2, 3])
cls.diet_profile_2 = DietProfile.objects.create(
name="test2",
email="test2@test.com",
age=20,
weight=61,
height=172,
gender=2,
special_condition=1,
body_activity=1,
vegetables_in_one_day=1,
fruits_in_one_day=1,
fried_food_in_one_day=1,
sweet_snacks_in_one_day=1,
sweet_drinks_in_one_day=1,
packaged_food_in_one_day=1,
large_meal_in_one_day=1,
snacks_in_one_day=1,
breakfast_type=1,
current_condition=1,
problem_to_solve=1,
health_problem=[2, 3])
cls.nutritionist = Nutritionist.objects.create(
id=1,
full_name_and_degree="Test, S.Gz",
......@@ -53,16 +78,45 @@ class GetProfilesTest(APITestCase):
name='tes',
email='test@test.com',
password='abc',
diet_profile=cls.diet_profile,
nutritionist=cls.nutritionist)
diet_profile=cls.diet_profile_1,
nutritionist=cls.nutritionist
)
cls.custom_user_2 = CustomUser.objects.create_user(name='tes', email='email2@gmail.com', password='abc')
cls.custom_user_2 = CustomUser.objects.create_user(
name='tes',
email='email2@gmail.com',
password='abc',
diet_profile=cls.diet_profile_2,
nutritionist=cls.nutritionist
)
cls.custom_user_3 = CustomUser.objects.create_user(
name='tesb',
email='test2@2test.com',
password='abc',
nutritionist=cls.nutritionist)
cls.diet_questionnaire_1 = DietQuestionnaire.objects.create(
user=cls.custom_user_1,
agree_to_all_statements_consent=1,
personal_data_consent=1
)
cls.diet_recommendation_1 = DietRecommendation.objects.create(
client=cls.custom_user_1,
nutritionist=cls.custom_user_1.nutritionist
)
cls.diet_questionnaire_2 = DietQuestionnaire.objects.create(
user=cls.custom_user_2,
agree_to_all_statements_consent=1,
personal_data_consent=1
)
cls.diet_recommendation_2 = DietRecommendation.objects.create(
client=cls.custom_user_2,
nutritionist=cls.custom_user_2.nutritionist
)
cls.g0 = Group.objects.get(name='client')
cls.g0.user_set.remove(cls.custom_user_3)
......@@ -73,9 +127,19 @@ class GetProfilesTest(APITestCase):
def test_get_all_users(self):
response = self.client.get(self.BASE_URL)
expected_response = []
users = CustomUser.objects.all()
serializer = CustomUserDetailsSerializer(users, many=True)
self.assertEqual(response.data, serializer.data)
for user in users:
expected_response.append({
'user': CustomUserDetailsSerializer(user).data,
'diet_profile_id': user.diet_profile.id \
if user.diet_profile is not None else None,
'diet_questionnaire_id': user.diet_questionnaire.id \
if hasattr(user, 'diet_questionnaire') else None,
'diet_recommendation_id': user.diet_recommendation.id \
if hasattr(user, 'diet_recommendation') else None
})
self.assertEqual(response.data, expected_response)
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_get_user_belonging_to_a_nutritionist(self):
......@@ -93,8 +157,18 @@ class GetProfilesTest(APITestCase):
self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + json_response['access_token'])
response = self.client.get(self.BASE_URL,secure=True)
users = CustomUser.objects.filter(Q(nutritionist=1) & ~Q(email='test2@2test.com'))
serializer = CustomUserDetailsSerializer(users, many=True)
self.assertEqual(response.data, serializer.data)
expected_response = []
for user in users:
expected_response.append({
'user': CustomUserDetailsSerializer(user).data,
'diet_profile_id': user.diet_profile.id \
if user.diet_profile is not None else None,
'diet_questionnaire_id': user.diet_questionnaire.id \
if hasattr(user, 'diet_questionnaire') else None,
'diet_recommendation_id': user.diet_recommendation.id \
if hasattr(user, 'diet_recommendation') else None
})
self.assertEqual(response.data, expected_response)
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_get_user_by_non_nutritionist(self):
......@@ -112,11 +186,136 @@ class GetProfilesTest(APITestCase):
self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + json_response['access_token'])
response = self.client.get(self.BASE_URL,secure=True)
users = CustomUser.objects.all()
serializer = CustomUserDetailsSerializer(users, many=True)
self.assertEqual(response.data, serializer.data)
expected_response = []
for user in users:
expected_response.append({
'user': CustomUserDetailsSerializer(user).data,
'diet_profile_id': user.diet_profile.id \
if user.diet_profile is not None else None,
'diet_questionnaire_id': user.diet_questionnaire.id \
if hasattr(user, 'diet_questionnaire') else None,
'diet_recommendation_id': user.diet_recommendation.id \
if hasattr(user, 'diet_recommendation') else None
})
self.assertEqual(response.data, expected_response)
self.assertEqual(response.status_code, status.HTTP_200_OK)
class DietRecommendationTests(APITestCase):
@classmethod
def setUpTestData(cls):
cls.BASE_URL = "/diet-recommendation/"
cls.nutritionist = Nutritionist.objects.create(
id=1,
full_name_and_degree="Test, S.Gz",
registration_certificate_no="1234567890",
university="Universitas Indonesia",
mastered_nutritional_problems="Manajemen berat badan, hipertensi",
handled_age_group="12-17 tahun (Remaja)",
another_practice_place="RSCM",
languages="Bahasa Indonesia, Bahasa Inggris",
)
cls.custom_user_1 = CustomUser.objects.create_user(
name='tes',
email='email@email.com',
password='abc',
nutritionist=cls.nutritionist
)
cls.custom_user_2 = CustomUser.objects.create_user(
name='tes2',
email='email2@email.com',
password='abc',
nutritionist=cls.nutritionist
)
cls.diet_recommendation = DietRecommendation.objects.create(
client=cls.custom_user_2,
nutritionist=cls.custom_user_2.nutritionist
)
cls.SPECIFIC_URL = f"{cls.BASE_URL}{cls.diet_recommendation.id}/"
def test_string_representation(self):
self.assertEqual(str(self.diet_recommendation), 'email2@email.com - Test, S.Gz')
def test_create_diet_recommendation_succeed(self):
tmp_file = SimpleUploadedFile("testfile.pdf", bytes("abc", 'utf-8'), content_type="application/pdf")
data = {
'client': self.custom_user_1.id,
'nutritionist': self.custom_user_1.nutritionist.id,
'client_plan_meal': tmp_file,
'nutritional_advice': 'baik baik ya',
'lifestyle_advice': 'baik baik ya',
}
response = self.client.post(self.BASE_URL, data, format='multipart')
json_response = json.loads(response.content)
self.assertIn('.pdf', json_response.get('client_plan_meal'))
self.assertEqual(json_response.get('client'), self.custom_user_1.id)
self.assertEqual(json_response.get('nutritionist'), self.custom_user_1.nutritionist.id)
self.assertEqual(json_response.get('nutritional_advice'), 'baik baik ya')
self.assertEqual(json_response.get('lifestyle_advice'), 'baik baik ya')
self.assertEqual(DietRecommendation.objects.count(), 2)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
def test_create_diet_recommendation_failed(self):
data = {
'client': self.custom_user_1.id,
'nutritionist': self.custom_user_1.nutritionist.id,
'client_plan_meal': 'tesfile.pdf',
'nutritional_advice': 'baik baik ya',
'lifestyle_advice': 'baik baik ya',
}
response = self.client.post(self.BASE_URL, data, format='multipart')
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_get_all_diet_recommendation(self):
response = self.client.get(self.BASE_URL)
json_response = json.loads(response.content)
self.assertEqual(len(json_response), 1)
self.assertEqual(json_response[0].get('client'), self.custom_user_2.id)
self.assertEqual(json_response[0].get('nutritionist'), self.custom_user_2.nutritionist.id)
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_get_single_diet_recommendation_succeed(self):
response = self.client.get(self.SPECIFIC_URL)
json_response = json.loads(response.content)
self.assertEqual(json_response.get('client'), self.custom_user_2.id)
self.assertEqual(json_response.get('nutritionist'), self.custom_user_2.nutritionist.id)
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_get_single_diet_recommendation_failed(self):
response = self.client.get(f"{self.BASE_URL}-1/")
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_update_diet_recommendation_succeed(self):
tmp_file = SimpleUploadedFile("testfile2.pdf", bytes("abc", 'utf-8'), content_type="application/pdf")
data = {
'client_plan_meal': tmp_file,
'nutritional_advice': 'makan yang banyak ya',
'lifestyle_advice': 'yuk hidup sehat'
}
response = self.client.patch(self.SPECIFIC_URL, data, format='multipart')
json_response = json.loads(response.content)
self.assertEqual(json_response.get('client'), self.custom_user_2.id)
self.assertEqual(json_response.get('nutritionist'), self.custom_user_2.nutritionist.id)
self.assertIn('.pdf', json_response.get('client_plan_meal'))
self.assertEqual(json_response.get('nutritional_advice'), 'makan yang banyak ya')
self.assertEqual(json_response.get('lifestyle_advice'), 'yuk hidup sehat')
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_update_diet_recommendation_failed(self):
data = {
'client_plan_meal': 'testfile2.pdf',
'nutritional_advice': 'makan yang banyak ya',
'lifestyle_advice': 'yuk hidup sehat'
}
response = self.client.post(self.BASE_URL, data, format='multipart')
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
from rest_framework import routers
from django.urls import path
from .views import GetProfilesViewSet
from .views import GetProfilesViewSet, DietRecommendationViewSet
router = routers.SimpleRouter()
router.register('diet-recommendation', DietRecommendationViewSet)
urlpatterns = [
path('profiles/', GetProfilesViewSet.as_view(), name='get_profiles'),
......
from rest_framework import generics
from rest_framework import generics, viewsets, status
from rest_framework.response import Response
from django.db.models import Q
from authentication.models import CustomUser
from authentication.serializers import CustomUserDetailsSerializer
from .serializers import DietRecommendationSerializer
from .models import DietRecommendation
class GetProfilesViewSet(generics.ListAPIView):
......@@ -22,3 +25,24 @@ class GetProfilesViewSet(generics.ListAPIView):
queryset = queryset.filter(
Q(nutritionist=nutritionist_id) & ~Q(id=self.request.user.id))
return queryset
def list(self, request):
queryset = self.get_queryset()
response = []
for user in queryset:
response.append({
'user': CustomUserDetailsSerializer(user).data,
'diet_profile_id': user.diet_profile.id \
if user.diet_profile is not None else None,
'diet_questionnaire_id': user.diet_questionnaire.id \
if hasattr(user, 'diet_questionnaire') else None,
'diet_recommendation_id': user.diet_recommendation.id \
if hasattr(user, 'diet_recommendation') else None
})
return Response(response, status=status.HTTP_200_OK)
class DietRecommendationViewSet(viewsets.ModelViewSet):
serializer_class = DietRecommendationSerializer
queryset = DietRecommendation.objects.all()
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