Skip to content

Commit

Permalink
Implementation of working days to vacations
Browse files Browse the repository at this point in the history
  • Loading branch information
Heibert committed Jul 17, 2024
1 parent 6af16b7 commit 3ba24bf
Show file tree
Hide file tree
Showing 7 changed files with 238 additions and 41 deletions.
3 changes: 1 addition & 2 deletions INSIGHTSAPI/services/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,6 @@ def test_non_holiday(self):

def test_get_holidays(self):
"""Test that the holidays are retrieved."""
data = {"year": 2024}
response = self.client.get("/services/holidays/", data)
response = self.client.get("/services/holidays/2024/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data, holidays.CO(years=2024).items())
2 changes: 1 addition & 1 deletion INSIGHTSAPI/services/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
urlpatterns = [
path("send-ethical-line/", send_report_ethical_line, name="send_ethical_line"),
path("trigger-error/", trigger_error, name="trigger_error"),
path("holidays/", get_holidays, name="get_holidays"),
path("holidays/<int:year>/", get_holidays, name="get_holidays"),
]
if settings.DEBUG:
urlpatterns.append(path("test-endpoint/", test_endpoint, name="test_endpoint"))
5 changes: 1 addition & 4 deletions INSIGHTSAPI/services/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,8 @@ def trigger_error(request):
raise Exception("Test error")

@api_view(["GET"])
def get_holidays(request):
def get_holidays(request, year):
"""Get the holidays of the year."""
year = request.GET.get("year", None)
if year is None:
return Response({"error": "El año es requerido"}, status=400)
try:
year = int(year)
except ValueError:
Expand Down
12 changes: 9 additions & 3 deletions INSIGHTSAPI/users/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,14 @@ def login_staffnet():
else:
url = "https://staffnet-api.cyc-bpo.com/login"
response = requests.post(url, json=data)
if response.status_code != 200:
if response.status_code != 200 or "StaffNet" not in response.cookies:
logger.error("Error logging in StaffNet: {}".format(response.text))
mail_admins(
"Error logging in StaffNet",
"Error logging in StaffNet: {}".format(response.text),
)
# delete the token to try to login again
del os.environ["StaffNetToken"]
return None
os.environ["StaffNetToken"] = response.cookies["StaffNet"]
return True
Expand Down Expand Up @@ -61,8 +63,10 @@ def get_profile(request):
url.format(user.cedula),
cookies={"StaffNet": os.environ["StaffNetToken"]},
)
if response.status_code != 200:
if response.status_code != 200 or "error" in response.json():
logger.error("Error getting user profile: {}".format(response.text))
# delete the token to try to login again
del os.environ["StaffNetToken"]
return Response(
{
"error": "Encontramos un error obteniendo tu perfil, por favor intenta más tarde."
Expand Down Expand Up @@ -143,8 +147,10 @@ def update_profile(request):
},
status=400,
)
elif response.status_code != 200:
elif response.status_code != 200 or "error" in response.json():
logger.error("Error updating user profile: {}".format(response.text))
# delete the token to try to login again
del os.environ["StaffNetToken"]
return Response(
{
"error": "Encontramos un error actualizando tu perfil, por favor intenta más tarde."
Expand Down
55 changes: 43 additions & 12 deletions INSIGHTSAPI/vacation/serializers.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
"""Serializers for the vacation app."""

import datetime
from datetime import datetime
from rest_framework import serializers
from users.models import User
from distutils.util import strtobool
from .utils import is_working_day, get_working_days
from .models import VacationRequest


Expand Down Expand Up @@ -59,10 +61,43 @@ def validate(self, attrs):
# Check if is a creation or an update
if not self.instance:
# Creation
created_at = datetime.datetime.now()
if created_at.day >= 20:
created_at = datetime.now()
request = self.context["request"]
if request.data.get("mon_to_sat") is None:
raise serializers.ValidationError(
"No puedes solicitar vacaciones después del día 20."
"Debes especificar si trabajas los sábados."
)
else:
try:
mon_to_sat = bool(strtobool(request.data["mon_to_sat"]))
except ValueError:
raise serializers.ValidationError(
"Debes especificar si trabajas los sábados o no."
)

if not is_working_day(attrs["start_date"], mon_to_sat):
raise serializers.ValidationError(
"No puedes iniciar tus vacaciones un día no laboral."
)
if not is_working_day(attrs["end_date"], mon_to_sat):
raise serializers.ValidationError(
"No puedes terminar tus vacaciones un día no laboral."
)
if request.data["mon_to_sat"] == True:
if attrs["start_date"].weekday() == 5:
raise serializers.ValidationError(
"No puedes iniciar tus vacaciones un sábado."
)
if get_working_days(attrs["start_date"], attrs["end_date"], mon_to_sat) > 15:
raise serializers.ValidationError(
"No puedes solicitar más de 15 días de vacaciones."
)
if (
created_at.day >= 20
and created_at.month + 1 == attrs["start_date"].month
):
raise serializers.ValidationError(
"Después del día 20 no puedes solicitar vacaciones para el mes siguiente."
)
if (
attrs["start_date"].month == created_at.month
Expand All @@ -75,15 +110,11 @@ def validate(self, attrs):
raise serializers.ValidationError(
"La fecha de inicio no puede ser mayor a la fecha de fin."
)
if (attrs["end_date"] - attrs["start_date"]).days > 30:
if attrs["end_date"].weekday() == 6:
raise serializers.ValidationError(
"Tu solicitud no puede ser mayor a 30 días."
"No puedes terminar tus vacaciones un domingo."
)
uploaded_by = (
self.instance.uploaded_by
if self.instance
else self.context["request"].user
)
uploaded_by = self.instance.uploaded_by if self.instance else request.user
if attrs["user"] == uploaded_by:
raise serializers.ValidationError(
"No puedes subir solicitudes para ti mismo."
Expand All @@ -101,7 +132,7 @@ def create(self, validated_data):
validated_data.pop("payroll_approbation", None)
validated_data.pop("manager_approbation", None)
validated_data["uploaded_by"] = self.context["request"].user
created_at = datetime.datetime.now()
created_at = datetime.now()
if created_at.day >= 20:
raise serializers.ValidationError(
"No puedes solicitar vacaciones después del día 20."
Expand Down
Loading

0 comments on commit 3ba24bf

Please sign in to comment.