[UPDT] EMPLOYEE: Disciplinary action login block and unblock options and scheduler

This commit is contained in:
Horilla
2024-03-05 14:21:42 +05:30
parent 11ff3a3d54
commit c768b1ef5b
7 changed files with 167 additions and 112 deletions

View File

@@ -154,6 +154,9 @@ class EmployeeForm(ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['email'].widget.attrs['autocomplete'] = 'email'
self.fields['phone'].widget.attrs['autocomplete'] = 'phone'
self.fields['address'].widget.attrs['autocomplete'] = 'address'
if instance := kwargs.get("instance"):
# ----
# django forms not showing value inside the date, time html element.
@@ -255,6 +258,7 @@ class EmployeeWorkInformationForm(ModelForm):
def __init__(self, *args, disable=False, **kwargs):
super().__init__(*args, **kwargs)
self.fields['email'].widget.attrs['autocomplete'] = 'email'
for field in self.fields:
self.fields[field].widget.attrs["placeholder"] = self.fields[field].label
if disable:
@@ -349,6 +353,7 @@ class EmployeeBankDetailsForm(ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['address'].widget.attrs['autocomplete'] = 'address'
for visible in self.visible_fields():
visible.field.widget.attrs["class"] = "oh-input w-100"
@@ -606,3 +611,12 @@ class ActiontypeForm(ModelForm):
class Meta:
model = Actiontype
fields = "__all__"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["action_type"].widget.attrs.update(
{
"onchange": "actionChange($(this))",
}
)

View File

@@ -766,6 +766,8 @@ class Actiontype(models.Model):
title = models.CharField(max_length=50)
action_type = models.CharField(max_length=30, choices=choice_actions)
block_option = models.BooleanField(default = False, verbose_name=_("Enable login block :"),
help_text="If is enabled, employees log in will be blocked based on period of suspension or dismissal.")
def __str__(self) -> str:
return f"{self.title}"

View File

@@ -26,6 +26,7 @@ from django.contrib.auth.models import User
from django.utils.translation import gettext_lazy as _
from notifications.signals import notify
from base.methods import (
filtersubordinates,
get_key_instances,
)
@@ -165,10 +166,17 @@ def disciplinary_actions(request):
"""
This method is used to view all Disciplinaryaction
"""
form = DisciplinaryActionFilter()
queryset = DisciplinaryAction.objects.all()
employee = Employee.objects.filter(employee_user_id=request.user).first()
dis_actions = filtersubordinates(
request, DisciplinaryAction.objects.all(), "base.add_disciplinaryaction"
).distinct()
dis_actions = dis_actions | DisciplinaryAction.objects.filter(
employee_id=employee
).distinct()
form = DisciplinaryActionFilter(request.GET, queryset=dis_actions)
page_number = request.GET.get("page")
page_obj = paginator_qry(queryset, page_number)
page_obj = paginator_qry(form.qs, page_number)
previous_data = request.GET.urlencode()
return render(
@@ -198,27 +206,6 @@ def get_action_type_delete(action_id):
return action.action_type
def employee_account_block_unblock(emp_id):
employee = get_object_or_404(Employee, id=emp_id)
if not employee:
# messages.info(request, _("Employee not found"))
return redirect(disciplinary_actions)
user = get_object_or_404(User, id=employee.employee_user_id.id)
if not user:
# messages.info(request, _("Employee not found"))
return redirect(disciplinary_actions)
user.is_active = not user.is_active
action_message = _("blocked") if not user.is_active else _("unblocked")
user.save()
# messages.success(
# request,
# _("{employee}'s account {action_message} successfully!").format(
# employee=employee, action_message=action_message
# ),
# )
return HttpResponse("<script>window.location.reload()</script>")
def get_action_type(action_id):
"""
This function is used to get the action type by the selection of title in the form.
@@ -235,24 +222,16 @@ def get_action_type_delete(action_id):
return action.action_type
def employee_account_block_unblock(emp_id):
def employee_account_block_unblock(emp_id, result):
employee = get_object_or_404(Employee, id=emp_id)
if not employee:
# messages.info(request, _("Employee not found"))
return redirect(disciplinary_actions)
user = get_object_or_404(User, id=employee.employee_user_id.id)
if not user:
# messages.info(request, _("Employee not found"))
return redirect(disciplinary_actions)
user.is_active = not user.is_active
action_message = _("blocked") if not user.is_active else _("unblocked")
user.is_active = result
user.save()
# messages.success(
# request,
# _("{employee}'s account {action_message} successfully!").format(
# employee=employee, action_message=action_message
# ),
# )
return HttpResponse("<script>window.location.reload()</script>")
@@ -274,34 +253,11 @@ def create_actions(request):
form = DisciplinaryActionForm(request.POST, request.FILES)
if form.is_valid():
employee_ids = form.cleaned_data["employee_id"]
start_date = form.cleaned_data["start_date"]
day = form.cleaned_data["days"]
action_id = form.cleaned_data
action_type = get_action_type(action_id)
for employee in employee_ids:
user = employee.employee_user_id
if action_type == "suspension":
end_date = start_date + timedelta(days=day)
if (
datetime.date.today() >= start_date
or datetime.date.today() >= end_date
):
employee_account_block_unblock(emp_id=employee.id)
messages.warning(
request, "Employees login credentials will be bloked."
)
if action_type == "dismissal":
if datetime.date.today() >= start_date:
employee_account_block_unblock(emp_id=employee.id)
messages.warning(
request, "Employees login credentials will be bloked."
)
employees.append(user)
form.save()
messages.success(request, _("Disciplinary action taken."))
notify.send(
@@ -335,35 +291,10 @@ def update_actions(request, action_id):
form = DisciplinaryActionForm(request.POST, request.FILES, instance=action)
if form.is_valid():
emp = form.cleaned_data["employee_id"]
start_date = form.cleaned_data["start_date"]
day = form.cleaned_data["days"]
action_id = form.cleaned_data
action_type = get_action_type(action_id)
for i in emp:
name = i.employee_user_id
if action_type == "suspension":
end_date = start_date + timedelta(days=day)
if (
datetime.date.today() >= start_date
or datetime.date.today() >= end_date
):
employee_account_block_unblock(emp_id=i.id)
messages.warning(
request, "Employees login credentials will be bloked."
)
if action_type == "dismissal":
if datetime.date.today() >= start_date:
employee_account_block_unblock(emp_id=i.id)
messages.warning(
request, "Employees login credentials will be bloked."
)
employee_ids = form.cleaned_data["employee_id"]
for employee in employee_ids:
name = employee.employee_user_id
employees.append(name)
form.save()
@@ -394,16 +325,16 @@ def delete_actions(request, action_id):
action_type = get_action_type_delete(dis.action)
for i in dis.employee_id.all():
for dis_emp in dis.employee_id.all():
if action_type == "dismissal" or action_type == "suspension":
employee = get_object_or_404(Employee, id=i.id)
employee = get_object_or_404(Employee, id=dis_emp.id)
user = get_object_or_404(User, id=employee.employee_user_id.id)
if user.is_active:
pass
else:
messages.warning(
request, "Employees login credentials will be unbloked."
request, "Employees login credentials will be unblocked."
)
user.is_active = True
user.save()
@@ -424,6 +355,14 @@ def action_type_details(request):
return JsonResponse({"action_type": action_type})
@login_required
def action_type_name(request):
"""
This method is used to get the action type name by the selection of type in the form.
"""
action_type = request.POST["action_type"]
return JsonResponse({"action_type": action_type})
@login_required
def disciplinary_filter_view(request):
"""

View File

@@ -1,9 +1,7 @@
# import datetime
import datetime
from datetime import timedelta
from apscheduler.schedulers.background import BackgroundScheduler
# from employee.models import DisciplinaryAction
# from employee.policies import employee_account_block_unblock
def update_experience():
from employee.models import EmployeeWorkInformation
@@ -19,24 +17,92 @@ def update_experience():
return
# def block_unblock_disciplinary():
# from employee.models import Employee
# """
# This scheduled task to trigger the experience calculator
# to update the employee work experience
# """
# dis_action = DisciplinaryAction.objects.all()
# for i in dis_action:
# if i.action.action_type == 'suspension':
# if datetime.date.today() >= i.start_date or datetime.date.today() >= i.end_date:
# for emp in i.employee_id:
# employee_account_block_unblock(emp_id=emp.id)
def block_unblock_disciplinary():
"""
This scheduled task to trigger the Disciplinary action and take the suspens
"""
from employee.models import DisciplinaryAction
from base.models import EmployeeShiftSchedule
from employee.policies import employee_account_block_unblock
dis_action = DisciplinaryAction.objects.all()
for dis in dis_action:
if dis.action.block_option:
if dis.action.action_type == 'suspension':
if dis.days:
day = dis.days
end_date = dis.start_date + timedelta(days=day)
if datetime.date.today() >= dis.start_date or datetime.date.today() >= end_date:
if datetime.date.today() >= dis.start_date:
r = False
if datetime.date.today() >= end_date:
r = True
# return
employees = dis.employee_id.all()
for emp in employees:
employee_account_block_unblock(emp_id=emp.id, result= r)
if dis.hours:
hour_str = dis.hours + ':00'
if hour_str > '00:00:00':
# Checking the date of action date.
if datetime.date.today() >= dis.start_date:
employees = dis.employee_id.all()
for emp in employees:
# Taking the shift of employee for taking the work start time
shift = emp.employee_work_info.shift_id
shift_detail = EmployeeShiftSchedule.objects.filter(shift_id = shift)
for shi in shift_detail:
today = datetime.datetime.today()
day_of_week = today.weekday()
# List of weekday names
weekday_names = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
if weekday_names[day_of_week] == shi.day.day:
st_time = shi.start_time
hour_time = datetime.datetime.strptime(hour_str, "%H:%M:%S").time()
time1 = st_time
time2 = hour_time
# Convert them to datetime objects
datetime1 = datetime.datetime.combine(datetime.date.today(), time1)
datetime2 = datetime.datetime.combine(datetime.date.today(), time2)
# Add the datetime objects
result_datetime = datetime1 + datetime.timedelta(hours=datetime2.hour, minutes=datetime2.minute, seconds=datetime2.second)
# Extract the time component from the result
result_time = result_datetime.time()
# Get the current time
current_time = datetime.datetime.now().time()
# Check if the current time matches st_time
if current_time >= st_time:
r = False
if current_time >= result_time:
r = True
employee_account_block_unblock(emp_id=emp.id, result= r)
if dis.action.action_type == "dismissal":
if datetime.date.today() >= dis.start_date:
if datetime.date.today() >= dis.start_date:
r = False
employees = dis.employee_id.all()
for emp in employees:
employee_account_block_unblock(emp_id=emp.id, result= r )
return
scheduler = BackgroundScheduler()
scheduler.add_job(update_experience, "interval", days=1)
scheduler.add_job(block_unblock_disciplinary, "interval", seconds=10)
scheduler.start()

View File

@@ -214,6 +214,31 @@
</div>
<!-- end of update modal -->
<script>
function actionChange(selectElement) {
var selectedActiontype = selectElement.val();
var parentForm = selectElement.parents().closest("form");
$.ajax({
type: "post",
url: "{% url 'action-type-name' %}",
data: {
csrfmiddlewaretoken: getCookie("csrftoken"),
"action_type": selectedActiontype,
},
success: function (response) {
// Check if the response.action_type is "warning"
if (response.action_type === "warning") {
// Hide the 'block_option' field
parentForm.find('[id=id_block_option]').parent().hide();
} else {
// Show the 'block_option' field
parentForm.find('[id=id_block_option]').parent().show();
}
},
});
}
</script>
{% endblock %}

View File

@@ -40,6 +40,7 @@
{% trans "Employee" %}
</div>
<div data-cell-index="1" data-cell-title='{% trans "Action Taken" %}' class="oh-sticky-table__th">{% trans "Action Taken" %}</div>
<div data-cell-index="5" data-cell-title='{% trans "Login Block" %}' class="oh-sticky-table__th">{% trans "Login Block" %}</div>
<div data-cell-index="2" data-cell-title='{% trans "Action Date" %}' class="oh-sticky-table__th">{% trans "Action Date" %}</div>
<div data-cell-index="3" data-cell-title='{% trans "Attachments" %}' class="oh-sticky-table__th">{% trans "Attachments" %}</div>
<div data-cell-index="4" data-cell-title='{% trans "Description" %}' class="oh-sticky-table__th">{% trans "Description" %}</div>
@@ -76,12 +77,11 @@
/>
</div>
<span class="oh-profile__name oh-text--dark" title="{{emp}}"
>{{emp.employee_first_name|truncatechars:8}}</span
>
>{{emp.get_full_name}}</span>
</div>
<a title="{% trans "Remove" %}" hx-target="#recruitment-container"class="oh-user-panel__remove">
{% comment %} <a title="{% trans "Remove" %}" hx-target="#recruitment-container"class="oh-user-panel__remove">
<ion-icon name="close-outline"></ion-icon>
</a>
</a> {% endcomment %}
</span>
{% endfor %}
</div>
@@ -98,6 +98,10 @@
{% else %}
<div data-cell-index="1" class="oh-sticky-table__td">{{ i.action }}</div>
{% endif %}
<div data-cell-index="5" class="oh-sticky-table__td">
{% if i.action.block_option %} {% trans "Yes" %}
{% else %}{% trans "No" %}{% endif %}
</div>
{% if i.action.action_type == 'suspension' and i.unit_in == "days" %}
<div data-cell-index="2" class="oh-sticky-table__td">
<span class="dateformat_changer">{{ i.start_date }}</span>

View File

@@ -356,6 +356,11 @@ urlpatterns = [
policies.action_type_details,
name="action-type-details",
),
path(
"action-type-name",
policies.action_type_name,
name="action-type-name",
),
path(
"disciplinary-filter-view",
policies.disciplinary_filter_view,