Skip to content

Commit

Permalink
Merge pull request #137 from CodeHive-Solutions/dev
Browse files Browse the repository at this point in the history
Vacation module version 2
  • Loading branch information
S-e-b-a-s authored Nov 5, 2024
2 parents feea0b6 + 53473e0 commit ef1da5b
Show file tree
Hide file tree
Showing 39 changed files with 980 additions and 511 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ WSGI
*.csv
*.xlsx
*.xl*
# Don't ignore the test files
!INSIGHTSAPI/utils/excels/*.csv
venv
.venv
media/
Expand Down
32 changes: 9 additions & 23 deletions INSIGHTSAPI/INSIGHTSAPI/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@
https://docs.djangoproject.com/en/4.2/ref/settings/
"""

import sys
import os
import ssl
import sys
from datetime import datetime, timedelta
from pathlib import Path

import ldap
from datetime import timedelta, datetime
from django_auth_ldap.config import LDAPSearch, LDAPSearchUnion
from dotenv import load_dotenv
from pathlib import Path


ENV_PATH = Path("/var/env/INSIGHTS.env")

Expand Down Expand Up @@ -141,13 +141,15 @@ def str_to_bool(value: str) -> bool:

if not "test" in sys.argv:
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_HTTPONLY = True
SECURE_HSTS_SECONDS = 3600
SECURE_BROWSER_XSS_FILTER = True
SECURE_HSTS_SECONDS = 3600
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
# This tell to Django that is behind a proxy
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
SECURE_CONTENT_TYPE_NOSNIFF = True
X_FRAME_OPTIONS = "DENY"

Expand Down Expand Up @@ -208,7 +210,7 @@ def str_to_bool(value: str) -> bool:

# This is the email where the test emails are going to be sent
EMAIL_FOR_TEST = os.getenv("EMAIL_FOR_TEST", "").upper()
# This cedula need to be in the StaffNet database it's used in many tests
# This cédula need to be in the StaffNet database it's used in many tests
TEST_CEDULA = os.environ["TEST_CEDULA"]

# Database
Expand All @@ -232,22 +234,6 @@ def str_to_bool(value: str) -> bool:
"NAME": "staffnet",
"TEST": {"MIRROR": "staffnet"},
},
# 'llamadas': { # MySQL too old
# 'ENGINE': 'django.db.backends.mysql',
# 'HOST': '172.16.0.9',
# 'PORT': '3306',
# 'USER': 'blacklistuser',
# # 'PASSWORD': os.environ['black_list_pass'],
# 'PASSWORD': 'a4dnAGc-',
# 'NAME': 'asteriskdb',
# }
# 'intranet': { # MySQL too old
# "user": "root",
# "password": os.environ["LEYES"],
# "host": "172.16.0.6",
# "port": "3306",
# "database": "userscyc",
# }
}

# Password validation
Expand Down
48 changes: 43 additions & 5 deletions INSIGHTSAPI/INSIGHTSAPI/tests.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
"""This file contains the tests for the Celery app. """

from celery import current_app
from django.test import TestCase
from django.conf import settings
from django.core.mail import get_connection
from django.test import override_settings
from django.core.mail import EmailMessage
from django.core.mail import send_mail
from django.core.mail import EmailMessage, get_connection, send_mail
from django.test import TestCase, override_settings
from django.urls import reverse

from INSIGHTSAPI.tasks import add_numbers
from payslip.models import Payslip
from payslip.views import send_payslip


class CeleryTestCase(TestCase):
Expand All @@ -29,6 +29,44 @@ def test_add_numbers_task(self):
task_result = result.get(timeout=5)
self.assertEqual(task_result, 7)

# Check if the task is able to be executed
def test_send_payslip_task(self):
"""Test if the tasks are working."""
data = {
"title": "title",
"identification": "identification",
"name": "name",
"area": "area",
"job_title": "job_title",
"salary": 1000000,
"days": 15,
"biweekly_period": 15,
"transport_allowance": 150000,
"bearing": 300000,
"surcharge_night_shift_hours": 15,
"surcharge_night_shift_allowance": 150000,
"surcharge_night_shift_holiday_hours": 15,
"surcharge_night_shift_holiday_allowance": 150000,
"surcharge_holiday_hours": 15,
"surcharge_holiday_allowance": 150000,
"bonus_paycheck": 150000,
"biannual_bonus": 150000,
"severance": 150000,
"gross_earnings": 1000000,
"healthcare_contribution": 150000,
"pension_contribution": 150000,
"tax_withholding": 150000,
"additional_deductions": 150000,
"apsalpen": 150000,
"solidarity_fund_percentage": 0.015,
"solidarity_fund": 150000,
"total_deductions": 150000,
"net_pay": 150000,
}
payslip = Payslip(**data)
response = send_payslip([payslip])
self.assertEqual(response.status_code, 201)


@override_settings(
EMAIL_BACKEND="INSIGHTSAPI.custom.custom_email_backend.CustomEmailBackend",
Expand Down
1 change: 1 addition & 0 deletions INSIGHTSAPI/coexistence_committee/tests.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from django.contrib.auth.models import Group
from django.urls import reverse

from services.tests import BaseTestCase
from users.models import User

Expand Down
15 changes: 15 additions & 0 deletions INSIGHTSAPI/goals/models.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
"""This file contains the models for the goals app."""

from typing import Iterable

from django.db import models
from django.utils import timezone
from simple_history.models import HistoricalRecords
Expand Down Expand Up @@ -38,6 +41,18 @@ class Goals(models.Model):
last_update = models.DateTimeField(auto_now=True)
history = HistoricalRecords(excluded_fields=["last_update"])

def save(self, *args, **kwargs):
for field in self._meta.fields:
# Check if the field is a CharField or TextField
if (
isinstance(field, (models.CharField, models.TextField))
and field.name != "password"
and self.__dict__[field.name]
and isinstance(getattr(self, field.attname), str)
):
setattr(self, field.attname, getattr(self, field.attname).upper())
super(Goals, self).save(*args, **kwargs)

def pre_create_historical_record(self):
"""This method is used to save the date of the historical record."""
record = super().pre_create_historical_record() # type: ignore
Expand Down
4 changes: 2 additions & 2 deletions INSIGHTSAPI/goals/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ def test_borrado_accepted_with_another_upload(self):
self.test_metas_upload(called=True)
# See if there are goals created
number_goals = Goals.objects.all().count()
self.assertTrue(number_goals > 0)
self.assertTrue(number_goals > 0)
# put accepted to True and accepted_at to now() to Goals
Goals.objects.all().update(accepted=True, accepted_at=timezone.now())
# Read the file again and upload it
Expand Down Expand Up @@ -240,7 +240,7 @@ def test_get_only_my_history(self):
response = self.client.get("/goals/?date=ENERO-2022&column=delivery")
self.assertEqual(response.status_code, 200)
self.assertEqual(len(response.data), 1) # type: ignore
self.assertIn("StaffNet Pruebas", response.data[0].get("name")) # type: ignore
self.assertIn("STAFFNET PRUEBAS", response.data[0].get("name")) # type: ignore

def test_get_one_history(self):
"""Test the get-one-history view."""
Expand Down
35 changes: 33 additions & 2 deletions INSIGHTSAPI/goals/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -310,13 +310,44 @@ def get_queryset(self):
elif campaign is not None and date is not None and column is not None:
if column == "delivery":
column_name = "goal_date"
campaign_type = "campaign_goal"
elif column == "execution":
column_name = "execution_date"
campaign_type = "campaign_execution"
else:
return self.queryset.none()
return self.queryset.filter(
Q(campaign_goal=campaign) & Q(**{f"{column_name}": date.upper()})
filter_params = {f"{column_name}": date.upper()}
latest_history_dates = (
HistoricalGoals.objects.filter(Q(**filter_params))
.values("cedula")
.annotate(max_history_date=Max("history_date"))
)
# Filter records with the latest history_date
if column == "delivery":
history_goals = HistoricalGoals.objects.filter(
Q(
history_date__in=Subquery(
latest_history_dates.values("max_history_date")
)
)
& Q(campaign_goal=campaign.upper())
& Q(cedula__in=latest_history_dates.values("cedula"))
)
else:
history_goals = HistoricalGoals.objects.filter(
Q(
history_date__in=Subquery(
latest_history_dates.values("max_history_date")
)
)
& Q(campaign_execution=campaign.upper())
& Q(cedula__in=latest_history_dates.values("cedula"))
)
return history_goals
# return self.queryset.filter(
# Q(campaign_goal=campaign.upper())
# & Q(**{f"{column_name}": date.upper()})
# )
elif date is not None and column is not None:
if column == "delivery":
column_name = "goal_date"
Expand Down
20 changes: 12 additions & 8 deletions INSIGHTSAPI/payslip/templates/payslip.html
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@
alt="logo-cyc"
src="data:image/png;base64,{{ logo }}"
width="200px"
/>
/>

<table width="100%">
<thead>
Expand Down Expand Up @@ -176,14 +176,12 @@ <h3 style="margin: 0">DEDUCCIONES</h3>
${{ payslip.transport_allowance }}
</td>
</tr>
{ % if payslip.meal_allowance % }
<tr>
<td>Rodamiento</td>
<td style="border-left: solid 1px #ccc">
${{ payslip.fuel_allowance }}
${{ payslip.bearing }}
</td>
</tr>
{ % endif % }
<tr>
<td>Comision</td>
<td style="border-left: solid 1px #ccc">
Expand Down Expand Up @@ -286,16 +284,22 @@ <h3 style="margin: 0">DEDUCCIONES</h3>
</td>
</tr>
<tr>
<td style="height: 25px"></td>
<td>&#8203;</td> <!-- Empty row to adjust table styles -->
<td
style="border-left: solid 1px #ccc"
></td>
>&#8203;</td> <!-- Empty row to adjust table styles -->
</tr>
<tr>
<td style="height: 22px"></td>
<td>&#8203;</td> <!-- Empty row to adjust table styles -->
<td
style="border-left: solid 1px #ccc"
></td>
>&#8203;</td> <!-- Empty row to adjust table styles -->
</tr>
<tr>
<td>&#8203;</td> <!-- Empty row to adjust table styles -->
<td
style="border-left: solid 1px #ccc"
>&#8203;</td> <!-- Empty row to adjust table styles -->
</tr>
</tbody>
</table>
Expand Down
4 changes: 2 additions & 2 deletions INSIGHTSAPI/payslip/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ def test_resend_payslip(self):
)
self.assertEqual(
response.status_code,
201,
200,
response.data,
)
self.assertEqual(response.data["message"], "Desprendibles de nomina enviados")
self.assertEqual(response.data["message"], "Desprendible de nomina enviado")
11 changes: 6 additions & 5 deletions INSIGHTSAPI/payslip/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,10 @@ def resend_payslip(request, pk):
)
if "email" in request.data:
payslip.email = request.data["email"]
return send_payslip([payslip])
response = send_payslip([payslip])
if response.status_code == 201:
return Response({"message": "Desprendible de nomina enviado"}, status=200)
return response


class PayslipViewSet(viewsets.ModelViewSet):
Expand Down Expand Up @@ -115,8 +118,6 @@ def create(self, request):
if cursor.description and row:
columns = [col[0] for col in cursor.description]
result_dict = dict(zip(columns, row))
# print(result_dict)
# print(type(result_dict["apellidos"]))
User.objects.create(
username=result_dict["usuario_windows"],
cedula=result_dict["cedula"],
Expand All @@ -131,9 +132,9 @@ def create(self, request):
else:
return Response(
{
"Error": "No se encontró el usuario, asegúrate de que esta registrado en StaffNet",
"cedula": data[1],
"Error": f"No se encontró el usuario {data[1]}, asegúrate de que esta registrado en StaffNet",
},
status=400,
)
payslip = PayslipSerializer(
data={
Expand Down
41 changes: 38 additions & 3 deletions INSIGHTSAPI/pqrs/migrations/0006_auto_20241010_1537.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
def create_default_managements(apps, schema_editor):
# Get models through the `apps` registry to ensure consistency
Management = apps.get_model("pqrs", "Management")
Area = apps.get_model("hierarchy", "Area")
User = apps.get_model("users", "User")
general_manager = User.objects.filter(job_position__name="GERENTE GENERAL").first()
risk_manager = User.objects.filter(
Expand All @@ -25,9 +24,45 @@ def create_default_managements(apps, schema_editor):
job_position__name="GERENTE ADMINISTRATIVA"
).first()
legal_manager = User.objects.filter(job_position__name="GERENTE DE LEGAL").first()
physical_manager = User.objects.filter(
job_position__name="GERENTE DE INFRAESTRUCTURA"
physical_resources_manager = User.objects.filter(
job_position__name="DIRECTOR(A) DE RECURSOS FISICOS"
).first()
it_manager = User.objects.filter(
job_position__name="GERENTE JR. DE MESA DE SERVICIO"
).first()
operations_manager = User.objects.filter(
job_position__name="GERENTE DE OPERACIONES"
).first()
managers = {
"Gerencia General": general_manager,
"Gerencia de Riesgo y Control Interno": risk_manager,
"Gerencia de Gestión Humana": hr_manager,
"Gerencia de Planeación": planning_manager,
"Gerencia Administrativa": administration_manager,
"Gerencia de Legal": legal_manager,
"Recursos Físicos": physical_resources_manager,
"Gerencia de Tecnología": it_manager,
"Gerencia de Operaciones": operations_manager,
}
if not all(managers.values()):
if not "test" in sys.argv:
mail_admins(
"Error en la creación de gerentes por defecto",
f"No se encontraron todos los gerentes por defecto. \n {managers}",
)
print(
f"\nNo se encontraron todos los gerentes por defecto. \n {managers}",
)
Management.objects.bulk_create(
[
Management(
area=area_name,
attendant_id=manager.pk,
)
for area_name, manager in managers.items()
if manager
]
)


class Migration(migrations.Migration):
Expand Down
5 changes: 5 additions & 0 deletions INSIGHTSAPI/vacation/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.contrib import admin

from .models import VacationRequest

admin.site.register(VacationRequest)
Loading

0 comments on commit ef1da5b

Please sign in to comment.