Skip to content

Commit

Permalink
Merge pull request #149 from unb-mds/task/get-schedule
Browse files Browse the repository at this point in the history
task(get-schedule): Cria API para obtenção de grades do usuário
  • Loading branch information
caio-felipee authored Dec 8, 2023
2 parents d39a16d + 610c520 commit 16813ab
Show file tree
Hide file tree
Showing 8 changed files with 136 additions and 5 deletions.
19 changes: 19 additions & 0 deletions api/api/migrations/0008_schedule_created_at.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Generated by Django 4.2.5 on 2023-12-08 01:10

from django.db import migrations, models
import django.utils.timezone


class Migration(migrations.Migration):

dependencies = [
('api', '0007_schedule'),
]

operations = [
migrations.AddField(
model_name='schedule',
name='created_at',
field=models.DateTimeField(default=django.utils.timezone.now),
),
]
3 changes: 2 additions & 1 deletion api/api/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from unidecode import unidecode
from django.contrib.postgres.fields import ArrayField
from users.models import User

from django.utils import timezone

class Department(models.Model):
"""Classe que representa um departamento.
Expand Down Expand Up @@ -76,6 +76,7 @@ class Schedule(models.Model):
user = models.ForeignKey(
User, on_delete=models.CASCADE, related_name='schedules')
classes = models.JSONField(default=list)
created_at = models.DateTimeField(default=timezone.now)

def __str__(self):
return f'Class: {self.id} - User: {self.user.email}'
7 changes: 6 additions & 1 deletion api/api/serializers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from rest_framework.serializers import ModelSerializer
from api.models import Department, Discipline, Class
from api.models import Department, Discipline, Class, Schedule


class DepartmentSerializer(ModelSerializer):
Expand Down Expand Up @@ -28,3 +28,8 @@ class DisciplineSerializer(DisciplineSerializerSchedule):

class ClassSerializerSchedule(ClassSerializer):
discipline = DisciplineSerializerSchedule()

class ScheduleSerializer(ModelSerializer):
class Meta:
model = Schedule
exclude = ['user']
70 changes: 70 additions & 0 deletions api/api/tests/test_get_schedules_api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework.test import APITestCase
from rest_framework.reverse import reverse

import utils.db_handler as dbh

from users.models import User

import json


class TestGetSchedules(APITestCase):
def setUp(self):
self.department = dbh.get_or_create_department('518', '2023', '2')
self.discipline = dbh.get_or_create_discipline(
'CÁLCULO 1', 'MAT0025', self.department)
self._class = dbh.create_class(['EDSON ALVES DA COSTA JUNIOR'], 'FGA - I8', '35T23', [
'Terça-feira 14:00 às 15:50', 'Quinta-feira 14:00 às 15:50'], '1', [], self.discipline)

body = json.dumps(
{
"classes": [self._class.id]
}
)

self.user, _ = User.objects.get_or_create(
first_name='Aroldo',
last_name='Silva',
picture_url='https://www.photo.com',
email="[email protected]"
)
self.user.save()

tokens = TokenObtainPairSerializer.get_token(self.user)
self.access_token = tokens.access_token

self.url = reverse('api:get-schedules')
self.content_type = 'application/json'

self.schedules = self.client.post(
reverse('api:schedule'), body, content_type=self.content_type).data

self.schedule_json = json.dumps(self.schedules[0])

self.headers = {
'Authorization': 'Bearer ' + str(self.access_token)
}
self.client.post(reverse('api:save-schedule'),
self.schedule_json, content_type=self.content_type, headers=self.headers)

def test_get_schedules(self):
"""
Testa a obtenção de horários salvos
"""

content = self.client.get(
self.url, headers=self.headers)

self.assertEqual(len(content.data), 1)
self.assertEqual(content.status_code, 200)

def test_get_schedules_with_invalid_token(self):
"""
Testa a obtenção de horários salvos com um token inválido
"""

content = self.client.get(
self.url, headers={'Authorization': 'Bearer ' + str(self.access_token) + '1'})

self.assertEqual(content.status_code, 403)
1 change: 0 additions & 1 deletion api/api/tests/test_schedule_save.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,6 @@ def test_save_correct_schedule(self):

response = self.make_post_request(schedule=schedule)

self.assertEqual(self.user.schedules.all()[0].classes, schedule)
self.assertEqual(len(self.user.schedules.all()), 1)
self.assertEqual(response.status_code, 201)

Expand Down
5 changes: 3 additions & 2 deletions api/api/urls.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
from django.urls import path
from api.views import save_schedule, views
from api.views import save_schedule, get_schedules, views

app_name = 'api'

urlpatterns = [
path('', views.Search.as_view(), name="search"),
path('year-period/', views.YearPeriod.as_view(), name="year-period"),
path('schedule/save/', save_schedule.SaveSchedule.as_view(), name="save-schedule"),
path('schedule/', views.Schedule.as_view(), name="schedule")
path('schedule/', views.Schedule.as_view(), name="schedule"),
path('schedules/', get_schedules.GetSchedules.as_view(), name="get-schedules")
]
32 changes: 32 additions & 0 deletions api/api/views/get_schedules.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi

from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from rest_framework import status, request, response

from api.swagger import Errors
from api.serializers import ScheduleSerializer

from utils.db_handler import get_schedules

class GetSchedules(APIView):

permission_classes = [IsAuthenticated]

@swagger_auto_schema(
operation_description="Retorna as grades horárias do usuário logado.",
security=[{'Bearer': []}],
responses={
200: openapi.Response('OK', ScheduleSerializer(many=True)),
**Errors([401, 403]).retrieve_erros()
}
)
def get(self, request: request.Request) -> response.Response:
"""Retorna as grades horárias do usuário logado."""

user = request.user
schedules = get_schedules(user)
data = ScheduleSerializer(schedules, many=True).data

return response.Response(status=status.HTTP_200_OK, data=data)
4 changes: 4 additions & 0 deletions api/utils/db_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,7 @@ def save_schedule(user: User, schedule_to_save: list[Class]) -> bool:
return False

return True

def get_schedules(user: User) -> QuerySet:
"""Retorna as grades horárias de um usuário."""
return Schedule.objects.filter(user=user).all()

0 comments on commit 16813ab

Please sign in to comment.