Files
ihrm/base/forms.py

1151 lines
36 KiB
Python
Raw Normal View History

2023-08-01 16:48:48 +05:30
"""
forms.py
2023-05-10 15:06:57 +05:30
2023-08-01 16:48:48 +05:30
This module is used to register forms for base module
"""
import calendar
from typing import Any, Dict
import uuid
2023-05-10 15:06:57 +05:30
import datetime
2023-08-01 16:48:48 +05:30
from datetime import timedelta
2023-05-10 15:06:57 +05:30
from django import forms
from django.contrib.auth.models import Group, Permission
from django.forms import DateInput
from django.core.exceptions import ValidationError
from django.utils.translation import gettext as _
2023-08-01 16:48:48 +05:30
from employee.models import Employee
from base.models import (
Company,
Department,
JobPosition,
JobRole,
WorkType,
EmployeeType,
EmployeeShift,
EmployeeShiftSchedule,
RotatingShift,
RotatingShiftAssign,
RotatingWorkType,
RotatingWorkTypeAssign,
WorkTypeRequest,
ShiftRequest,
EmployeeShiftDay,
)
2023-05-10 15:06:57 +05:30
# your form here
def validate_time_format(value):
2023-08-01 16:48:48 +05:30
"""
2023-05-10 15:06:57 +05:30
this method is used to validate the format of duration like fields.
2023-08-01 16:48:48 +05:30
"""
2023-05-10 15:06:57 +05:30
if len(value) > 6:
raise ValidationError("Invalid format, it should be HH:MM format")
2023-08-01 16:48:48 +05:30
try:
2023-05-10 15:06:57 +05:30
hour, minute = value.split(":")
hour = int(hour)
minute = int(minute)
if len(str(hour)) > 3 or minute not in range(60):
2023-08-01 16:48:48 +05:30
raise ValidationError("Invalid format, it should be HH:MM format")
except ValueError as error:
raise ValidationError("Invalid format, it should be HH:MM format") from error
2023-05-10 15:06:57 +05:30
BASED_ON = [
2023-08-01 16:48:48 +05:30
("after", "After"),
("weekly", "Weekend"),
("monthly", "Monthly"),
2023-05-10 15:06:57 +05:30
]
def get_next_week_date(target_day, start_date):
"""
Calculates the date of the next occurrence of the target day within the next week.
Parameters:
target_day (int): The target day of the week (0-6, where Monday is 0 and Sunday is 6).
start_date (datetime.date): The starting date.
Returns:
datetime.date: The date of the next occurrence of the target day within the next week.
2023-08-01 16:48:48 +05:30
"""
2023-05-10 15:06:57 +05:30
if start_date.weekday() == target_day:
return start_date
days_until_target_day = (target_day - start_date.weekday()) % 7
if days_until_target_day == 0:
days_until_target_day = 7
return start_date + timedelta(days=days_until_target_day)
def get_next_monthly_date(start_date, rotate_every):
"""
2023-08-01 16:48:48 +05:30
Given a start date and a rotation day (specified as an integer between 1 and 31, or
the string 'last'),calculates the next rotation date for a monthly rotation schedule.
2023-05-10 15:06:57 +05:30
2023-08-01 16:48:48 +05:30
If the rotation day has not yet occurred in the current month, the next rotation date
will be on the rotation day of the current month. If the rotation day has already
occurred in the current month, the next rotation date will be on the rotation day of
the next month.
2023-05-10 15:06:57 +05:30
2023-08-01 16:48:48 +05:30
If 'last' is specified as the rotation day, the next rotation date will be on the
last day of the current month.
2023-05-10 15:06:57 +05:30
Parameters:
- start_date: The start date of the rotation schedule, as a datetime.date object.
2023-08-01 16:48:48 +05:30
- rotate_every: The rotation day, specified as an integer between 1 and 31, or the
string 'last'.
2023-05-10 15:06:57 +05:30
Returns:
- A datetime.date object representing the next rotation date.
"""
2023-08-01 16:48:48 +05:30
if rotate_every == "last":
2023-05-10 15:06:57 +05:30
# Set rotate_every to the last day of the current month
last_day = calendar.monthrange(start_date.year, start_date.month)[1]
rotate_every = str(last_day)
rotate_every = int(rotate_every)
# Calculate the next change date
if start_date.day <= rotate_every or rotate_every == 0:
2023-08-01 16:48:48 +05:30
# If the rotation day has not occurred yet this month, or if it's the last-
# day of the month, set the next change date to the rotation day of this month
2023-05-10 15:06:57 +05:30
try:
2023-08-01 16:48:48 +05:30
next_change = datetime.date(start_date.year, start_date.month, rotate_every)
2023-05-10 15:06:57 +05:30
except ValueError:
next_change = datetime.date(
2023-08-01 16:48:48 +05:30
start_date.year, start_date.month + 1, 1
) # Advance to next month
2023-05-10 15:06:57 +05:30
# Set day to rotate_every
next_change = datetime.date(
2023-08-01 16:48:48 +05:30
next_change.year, next_change.month, rotate_every
)
2023-05-10 15:06:57 +05:30
else:
2023-08-01 16:48:48 +05:30
# If the rotation day has already occurred this month, set the next change
# date to the rotation day of the next month
2023-05-10 15:06:57 +05:30
last_day = calendar.monthrange(start_date.year, start_date.month)[1]
next_month_start = start_date.replace(day=last_day) + timedelta(days=1)
try:
next_change = next_month_start.replace(day=rotate_every)
except ValueError:
2023-08-01 16:48:48 +05:30
next_change = (
next_month_start.replace(month=next_month_start.month + 1)
+ timedelta(days=1)
).replace(day=rotate_every)
2023-05-10 15:06:57 +05:30
return next_change
class ModelForm(forms.ModelForm):
2023-08-01 16:48:48 +05:30
"""
Override django model's form to add initial styling
"""
2023-05-10 15:06:57 +05:30
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field_name, field in self.fields.items():
widget = field.widget
2023-08-01 16:48:48 +05:30
if isinstance(
widget,
(forms.NumberInput, forms.EmailInput, forms.TextInput, forms.FileInput),
):
if field.label is not None:
label = _(field.label.title())
2023-05-10 15:06:57 +05:30
field.widget.attrs.update(
2023-08-01 16:48:48 +05:30
{"class": "oh-input w-100", "placeholder": label}
)
2023-05-10 15:06:57 +05:30
elif isinstance(widget, (forms.Select,)):
label = ""
2023-05-10 15:06:57 +05:30
if field.label is not None:
label = _(field.label)
field.empty_label = _("---Choose {label}---").format(label=label)
2023-05-10 15:06:57 +05:30
field.widget.attrs.update(
2023-08-01 16:48:48 +05:30
{"class": "oh-select oh-select-2 select2-hidden-accessible"}
)
2023-05-10 15:06:57 +05:30
elif isinstance(widget, (forms.Textarea)):
2023-08-01 16:48:48 +05:30
field.widget.attrs.update(
{
"class": "oh-input w-100",
"placeholder": _(field.label),
"rows": 2,
"cols": 40,
}
)
elif isinstance(
widget,
(
forms.CheckboxInput,
forms.CheckboxSelectMultiple,
),
):
field.widget.attrs.update({"class": "oh-switch__checkbox"})
2023-05-10 15:06:57 +05:30
class Form(forms.Form):
2023-08-01 16:48:48 +05:30
"""
Overrides to add initial styling to the django Form instance
"""
2023-05-10 15:06:57 +05:30
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field_name, field in self.fields.items():
widget = field.widget
2023-08-01 16:48:48 +05:30
if isinstance(
widget, (forms.NumberInput, forms.EmailInput, forms.TextInput)
):
if field.label is not None:
label = _(field.label)
field.widget.attrs.update(
{"class": "oh-input w-100", "placeholder": label}
)
2023-05-10 15:06:57 +05:30
elif isinstance(widget, (forms.Select,)):
label = ""
2023-05-10 15:06:57 +05:30
if field.label is not None:
label = field.label.replace("id", " ")
field.empty_label = _("---Choose {label}---").format(label=label)
2023-08-01 16:48:48 +05:30
field.widget.attrs.update(
{"class": "oh-select oh-select-2 select2-hidden-accessible"}
)
2023-05-10 15:06:57 +05:30
elif isinstance(widget, (forms.Textarea)):
label = _(field.label)
2023-08-01 16:48:48 +05:30
field.widget.attrs.update(
{
"class": "oh-input w-100",
"placeholder": label,
"rows": 2,
"cols": 40,
}
)
elif isinstance(
widget,
(
forms.CheckboxInput,
forms.CheckboxSelectMultiple,
),
):
field.widget.attrs.update({"class": "oh-switch__checkbox"})
2023-05-10 15:06:57 +05:30
class UserGroupForm(ModelForm):
2023-08-01 16:48:48 +05:30
"""
Django user groups form
"""
2023-05-10 15:06:57 +05:30
class Meta:
2023-08-01 16:48:48 +05:30
"""
Meta class for additional options
"""
2023-05-10 15:06:57 +05:30
model = Group
2023-08-01 16:48:48 +05:30
fields = "__all__"
2023-05-10 15:06:57 +05:30
class AssignUserGroup(Form):
2023-08-01 16:48:48 +05:30
"""
Form to assign groups
"""
2023-05-10 15:06:57 +05:30
employee = forms.ModelMultipleChoiceField(queryset=Employee.objects.all())
group = forms.ModelMultipleChoiceField(queryset=Group.objects.all())
def save(self):
2023-08-01 16:48:48 +05:30
"""
Save method to assign group to employees
"""
employees = self.cleaned_data["employee"]
group = self.cleaned_data["group"]
2023-05-10 15:06:57 +05:30
for employee in employees:
employee.employee_user_id.groups.add(*group)
return group
class AssignPermission(Form):
2023-08-01 16:48:48 +05:30
"""
Forms to assign user permision
"""
2023-05-10 15:06:57 +05:30
employee = forms.ModelMultipleChoiceField(queryset=Employee.objects.all())
2023-08-01 16:48:48 +05:30
permission = forms.ModelMultipleChoiceField(queryset=Permission.objects.all())
2023-05-10 15:06:57 +05:30
def save(self):
2023-08-01 16:48:48 +05:30
"""
Save method to assign permission to employee
"""
employees = self.cleaned_data["employee"]
permissions = self.cleaned_data["permission"]
2023-05-10 15:06:57 +05:30
for emp in employees:
user = emp.employee_user_id
user.user_permissions.add(*permissions)
2023-08-01 16:48:48 +05:30
return self
2023-05-10 15:06:57 +05:30
class CompanyForm(ModelForm):
2023-08-01 16:48:48 +05:30
"""
Company model's form
"""
2023-05-10 15:06:57 +05:30
class Meta:
2023-08-01 16:48:48 +05:30
"""
Meta class for additional options
"""
2023-05-10 15:06:57 +05:30
2023-08-01 16:48:48 +05:30
model = Company
fields = "__all__"
2023-05-10 15:06:57 +05:30
class DepartmentForm(ModelForm):
2023-08-01 16:48:48 +05:30
"""
Department model's form
"""
2023-05-10 15:06:57 +05:30
class Meta:
2023-08-01 16:48:48 +05:30
"""
Meta class for additional options
"""
2023-05-10 15:06:57 +05:30
2023-08-01 16:48:48 +05:30
model = Department
fields = "__all__"
2023-05-10 15:06:57 +05:30
class JobPositionForm(ModelForm):
2023-08-01 16:48:48 +05:30
"""
JobPosition model's form
"""
2023-05-10 15:06:57 +05:30
class Meta:
2023-08-01 16:48:48 +05:30
"""
Meta class for additional options
"""
2023-05-10 15:06:57 +05:30
2023-08-01 16:48:48 +05:30
model = JobPosition
fields = "__all__"
2023-05-10 15:06:57 +05:30
class JobRoleForm(ModelForm):
2023-08-01 16:48:48 +05:30
"""
JobRole model's form
"""
2023-05-10 15:06:57 +05:30
class Meta:
2023-08-01 16:48:48 +05:30
"""
Meta class for additional options
"""
2023-05-10 15:06:57 +05:30
2023-08-01 16:48:48 +05:30
model = JobRole
fields = "__all__"
2023-05-10 15:06:57 +05:30
class WorkTypeForm(ModelForm):
2023-08-01 16:48:48 +05:30
"""
WorkType model's form
"""
2023-05-10 15:06:57 +05:30
class Meta:
2023-08-01 16:48:48 +05:30
"""
Meta class for additional options
"""
2023-05-10 15:06:57 +05:30
2023-08-01 16:48:48 +05:30
model = WorkType
fields = "__all__"
2023-05-10 15:06:57 +05:30
class RotatingWorkTypeForm(ModelForm):
2023-08-01 16:48:48 +05:30
"""
RotatingWorkType model's form
"""
2023-05-10 15:06:57 +05:30
class Meta:
2023-08-01 16:48:48 +05:30
"""
Meta class for additional options
"""
2023-05-10 15:06:57 +05:30
model = RotatingWorkType
2023-08-01 16:48:48 +05:30
fields = "__all__"
exclude = ("employee_id",)
2023-05-10 15:06:57 +05:30
widgets = {
2023-08-01 16:48:48 +05:30
"start_date": DateInput(attrs={"type": "date"}),
2023-05-10 15:06:57 +05:30
}
class RotatingWorkTypeAssignForm(forms.ModelForm):
2023-08-01 16:48:48 +05:30
"""
RotatingWorkTypeAssign model's form
"""
2023-05-10 15:06:57 +05:30
employee_id = forms.ModelMultipleChoiceField(
2023-08-01 16:48:48 +05:30
label="Employee",
queryset=Employee.objects.filter(employee_work_info__isnull=False),
)
based_on = forms.ChoiceField(choices=BASED_ON, initial="daily")
rotate_after_day = forms.IntegerField(
initial=5,
)
start_date = forms.DateField(initial=datetime.date.today, widget=forms.DateInput)
2023-05-10 15:06:57 +05:30
class Meta:
2023-08-01 16:48:48 +05:30
"""
Meta class for additional options
"""
2023-05-10 15:06:57 +05:30
model = RotatingWorkTypeAssign
2023-08-01 16:48:48 +05:30
fields = "__all__"
exclude = ("next_change_date", "current_work_type", "next_work_type")
2023-05-10 15:06:57 +05:30
widgets = {
2023-08-01 16:48:48 +05:30
"start_date": DateInput(attrs={"type": "date"}),
2023-05-10 15:06:57 +05:30
}
labels = {
2023-08-01 16:48:48 +05:30
"rotating_work_type_id": "Rotating work type",
2023-05-10 15:06:57 +05:30
}
def __init__(self, *args, **kwargs):
2023-08-01 16:48:48 +05:30
super().__init__(*args, **kwargs)
self.fields["rotate_every_weekend"].widget.attrs.update(
{
"class": "w-100",
"style": "display:none; height:50px; border-radius:0;border:1px \
solid hsl(213deg,22%,84%);",
"data-hidden": True,
}
)
self.fields["rotate_every"].widget.attrs.update(
{
"class": "w-100",
"style": "display:none; height:50px; border-radius:0;border:1px \
solid hsl(213deg,22%,84%);",
"data-hidden": True,
}
)
self.fields["rotate_after_day"].widget.attrs.update(
{
"class": "w-100 oh-input",
"style": " height:50px; border-radius:0;",
}
)
self.fields["based_on"].widget.attrs.update(
{
"class": "w-100",
"style": " height:50px; border-radius:0;border:1px solid hsl(213deg,22%,84%);",
}
)
self.fields["start_date"].widget = forms.DateInput(
attrs={
"class": "w-100 oh-input",
"type": "date",
"style": " height:50px; border-radius:0;",
}
)
self.fields["rotating_work_type_id"].widget.attrs.update(
{
"class": "oh-select oh-select-2",
}
)
self.fields["employee_id"].widget.attrs.update(
{
"class": "oh-select oh-select-2",
}
)
2023-05-10 15:06:57 +05:30
def clean_employee_id(self):
2023-08-01 16:48:48 +05:30
employee_ids = self.cleaned_data.get("employee_id")
2023-05-10 15:06:57 +05:30
if employee_ids:
return employee_ids[0]
else:
2023-08-01 16:48:48 +05:30
return ValidationError("This field is required")
2023-05-10 15:06:57 +05:30
def clean(self):
cleaned_data = super().clean()
2023-08-01 16:48:48 +05:30
if "rotate_after_day" in self.errors:
del self.errors["rotate_after_day"]
2023-05-10 15:06:57 +05:30
return cleaned_data
def save(self, commit=False, manager=None):
2023-08-01 16:48:48 +05:30
employee_ids = self.data.getlist("employee_id")
2023-05-10 15:06:57 +05:30
rotating_work_type = RotatingWorkType.objects.get(
2023-08-01 16:48:48 +05:30
id=self.data["rotating_work_type_id"]
)
day_name = self.cleaned_data["rotate_every_weekend"]
day_names = [
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday",
"sunday",
]
2023-05-10 15:06:57 +05:30
target_day = day_names.index(day_name.lower())
for employee_id in employee_ids:
employee = Employee.objects.filter(id=employee_id).first()
rotating_work_type_assign = RotatingWorkTypeAssign()
rotating_work_type_assign.rotating_work_type_id = rotating_work_type
rotating_work_type_assign.employee_id = employee
2023-08-01 16:48:48 +05:30
rotating_work_type_assign.based_on = self.cleaned_data["based_on"]
rotating_work_type_assign.start_date = self.cleaned_data["start_date"]
rotating_work_type_assign.next_change_date = self.cleaned_data["start_date"]
2023-05-10 15:06:57 +05:30
rotating_work_type_assign.rotate_after_day = self.data.get(
2023-08-01 16:48:48 +05:30
"rotate_after_day"
)
rotating_work_type_assign.rotate_every = self.cleaned_data["rotate_every"]
2023-05-10 15:06:57 +05:30
rotating_work_type_assign.rotate_every_weekend = self.cleaned_data[
2023-08-01 16:48:48 +05:30
"rotate_every_weekend"
]
rotating_work_type_assign.next_change_date = self.cleaned_data["start_date"]
rotating_work_type_assign.current_work_type = (
employee.employee_work_info.work_type_id
)
2023-05-10 15:06:57 +05:30
rotating_work_type_assign.next_work_type = rotating_work_type.work_type2
2023-08-01 16:48:48 +05:30
based_on = self.cleaned_data["based_on"]
start_date = self.cleaned_data["start_date"]
2023-05-10 15:06:57 +05:30
if based_on == "weekly":
next_date = get_next_week_date(target_day, start_date)
rotating_work_type_assign.next_change_date = next_date
elif based_on == "monthly":
# 0, 1, 2, ..., 31, or "last"
2023-08-01 16:48:48 +05:30
rotate_every = self.cleaned_data["rotate_every"]
start_date = self.cleaned_data["start_date"]
2023-05-10 15:06:57 +05:30
next_date = get_next_monthly_date(start_date, rotate_every)
rotating_work_type_assign.next_change_date = next_date
elif based_on == "after":
2023-08-01 16:48:48 +05:30
rotating_work_type_assign.next_change_date = (
rotating_work_type_assign.start_date
+ datetime.timedelta(days=int(self.data.get("rotate_after_day")))
)
2023-05-10 15:06:57 +05:30
rotating_work_type_assign.save()
class RotatingWorkTypeAssignUpdateForm(forms.ModelForm):
2023-08-01 16:48:48 +05:30
"""
RotatingWorkTypeAssign model's form
"""
2023-05-10 15:06:57 +05:30
class Meta:
2023-08-01 16:48:48 +05:30
"""
Meta class for additional options
"""
2023-05-10 15:06:57 +05:30
model = RotatingWorkTypeAssign
2023-08-01 16:48:48 +05:30
fields = "__all__"
exclude = ("next_change_date", "current_work_type", "next_work_type")
2023-05-10 15:06:57 +05:30
widgets = {
2023-08-01 16:48:48 +05:30
"start_date": DateInput(attrs={"type": "date"}),
2023-05-10 15:06:57 +05:30
}
def __init__(self, *args, **kwargs):
2023-08-01 16:48:48 +05:30
super().__init__(*args, **kwargs)
2023-05-10 15:06:57 +05:30
2023-08-01 16:48:48 +05:30
self.fields["rotate_every_weekend"].widget.attrs.update(
{
"class": "w-100",
"style": "display:none; height:50px; border-radius:0;border:1px\
solid hsl(213deg,22%,84%);",
"data-hidden": True,
}
)
self.fields["rotate_every"].widget.attrs.update(
{
"class": "w-100",
"style": "display:none; height:50px; border-radius:0;border:1px \
solid hsl(213deg,22%,84%);",
"data-hidden": True,
}
)
self.fields["rotate_after_day"].widget.attrs.update(
{
"class": "w-100 oh-input",
"style": " height:50px; border-radius:0;",
}
)
self.fields["based_on"].widget.attrs.update(
{
"class": "w-100",
"style": " height:50px; border-radius:0; border:1px solid \
hsl(213deg,22%,84%);",
}
)
self.fields["start_date"].widget = forms.DateInput(
attrs={
"class": "w-100 oh-input",
"type": "date",
"style": " height:50px; border-radius:0;",
}
)
self.fields["rotating_work_type_id"].widget.attrs.update(
{
"class": "oh-select oh-select-2",
}
)
self.fields["employee_id"].widget.attrs.update(
{
"class": "oh-select oh-select-2",
}
)
2023-05-10 15:06:57 +05:30
2023-08-01 16:48:48 +05:30
def save(self, *args, **kwargs):
day_name = self.cleaned_data["rotate_every_weekend"]
day_names = [
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday",
"sunday",
]
2023-05-10 15:06:57 +05:30
target_day = day_names.index(day_name.lower())
2023-08-01 16:48:48 +05:30
based_on = self.cleaned_data["based_on"]
2023-05-10 15:06:57 +05:30
start_date = self.instance.start_date
if based_on == "weekly":
next_date = get_next_week_date(target_day, start_date)
self.instance.next_change_date = next_date
elif based_on == "monthly":
rotate_every = self.instance.rotate_every # 0, 1, 2, ..., 31, or "last"
start_date = self.instance.start_date
next_date = get_next_monthly_date(start_date, rotate_every)
self.instance.next_change_date = next_date
elif based_on == "after":
2023-08-01 16:48:48 +05:30
self.instance.next_change_date = (
self.instance.start_date
+ datetime.timedelta(days=int(self.data.get("rotate_after_day")))
)
2023-05-10 15:06:57 +05:30
return super().save()
class EmployeeTypeForm(ModelForm):
2023-08-01 16:48:48 +05:30
"""
EmployeeType form
"""
2023-05-10 15:06:57 +05:30
class Meta:
2023-08-01 16:48:48 +05:30
"""
Meta class for additional options
"""
2023-05-10 15:06:57 +05:30
2023-08-01 16:48:48 +05:30
model = EmployeeType
fields = "__all__"
2023-05-10 15:06:57 +05:30
class EmployeeShiftForm(ModelForm):
2023-08-01 16:48:48 +05:30
"""
EmployeeShift Form
"""
2023-05-10 15:06:57 +05:30
class Meta:
2023-08-01 16:48:48 +05:30
"""
Meta class for additional options
"""
2023-05-10 15:06:57 +05:30
2023-08-01 16:48:48 +05:30
model = EmployeeShift
fields = "__all__"
exclude = ("days",)
2023-05-10 15:06:57 +05:30
2023-08-01 16:48:48 +05:30
def clean(self) -> Dict[str, Any]:
full_time = self.data["full_time"]
2023-05-10 15:06:57 +05:30
validate_time_format(full_time)
2023-08-01 16:48:48 +05:30
full_time = self.data["weekly_full_time"]
validate_time_format(full_time)
return super().clean()
2023-05-10 15:06:57 +05:30
class EmployeeShiftScheduleUpdateForm(ModelForm):
2023-08-01 16:48:48 +05:30
"""
EmployeeShiftSchedule model's form
"""
2023-05-10 15:06:57 +05:30
class Meta:
2023-08-01 16:48:48 +05:30
"""
Meta class for additional options
"""
2023-05-10 15:06:57 +05:30
2023-08-01 16:48:48 +05:30
fields = "__all__"
widgets = {
"start_time": DateInput(attrs={"type": "time"}),
"end_time": DateInput(attrs={"type": "time"}),
2023-05-10 15:06:57 +05:30
}
model = EmployeeShiftSchedule
def __init__(self, *args, **kwargs):
2023-08-01 16:48:48 +05:30
if instance := kwargs.get("instance"):
# """
# django forms not showing value inside the date, time html element.
# so here overriding default forms instance method to set initial value
# """
2023-05-10 15:06:57 +05:30
initial = {
2023-08-01 16:48:48 +05:30
"start_time": instance.start_time.strftime("%H:%M"),
"end_time": instance.end_time.strftime("%H:%M"),
2023-05-10 15:06:57 +05:30
}
2023-08-01 16:48:48 +05:30
kwargs["initial"] = initial
2023-05-10 15:06:57 +05:30
super().__init__(*args, **kwargs)
class EmployeeShiftScheduleForm(ModelForm):
2023-08-01 16:48:48 +05:30
"""
EmployeeShiftSchedule model's form
"""
2023-05-10 15:06:57 +05:30
day = forms.ModelMultipleChoiceField(
2023-08-01 16:48:48 +05:30
queryset=EmployeeShiftDay.objects.all(),
)
2023-05-10 15:06:57 +05:30
class Meta:
2023-08-01 16:48:48 +05:30
"""
Meta class for additional options
"""
2023-05-10 15:06:57 +05:30
model = EmployeeShiftSchedule
2023-08-01 16:48:48 +05:30
fields = "__all__"
2023-05-10 15:06:57 +05:30
widgets = {
2023-08-01 16:48:48 +05:30
"start_time": DateInput(attrs={"type": "time"}),
"end_time": DateInput(attrs={"type": "time"}),
2023-05-10 15:06:57 +05:30
}
def __init__(self, *args, **kwargs):
2023-08-01 16:48:48 +05:30
if instance := kwargs.get("instance"):
# """
# django forms not showing value inside the date, time html element.
# so here overriding default forms instance method to set initial value
# """
2023-05-10 15:06:57 +05:30
initial = {
2023-08-01 16:48:48 +05:30
"start_time": instance.start_time.strftime("%H:%M"),
"end_time": instance.end_time.strftime("%H:%M"),
2023-05-10 15:06:57 +05:30
}
2023-08-01 16:48:48 +05:30
kwargs["initial"] = initial
super().__init__(*args, **kwargs)
self.fields["day"].widget.attrs.update({"id": str(uuid.uuid4())})
self.fields["shift_id"].widget.attrs.update({"id": str(uuid.uuid4())})
2023-05-10 15:06:57 +05:30
def save(self, commit=True):
instance = super().save(commit=False)
2023-08-01 16:48:48 +05:30
for day in self.data.getlist("day"):
2023-05-10 15:06:57 +05:30
if int(day) != int(instance.day.id):
data_copy = self.data.copy()
2023-08-01 16:48:48 +05:30
data_copy.update({"day": str(day)})
shift_schedule = EmployeeShiftScheduleUpdateForm(data_copy).save(
commit=False
)
2023-05-10 15:06:57 +05:30
shift_schedule.save()
if commit:
instance.save()
return instance
def clean_day(self):
2023-08-01 16:48:48 +05:30
"""
Validation to day field
"""
days = self.cleaned_data["day"]
2023-05-10 15:06:57 +05:30
for day in days:
attendance = EmployeeShiftSchedule.objects.filter(
2023-08-01 16:48:48 +05:30
day=day, shift_id=self.data["shift_id"]
).first()
2023-05-10 15:06:57 +05:30
if attendance is not None:
2023-08-01 16:48:48 +05:30
raise ValidationError(f"Shift schedule is already exist for {day}")
2023-05-10 15:06:57 +05:30
if days.first() is None:
2023-08-01 16:48:48 +05:30
raise ValidationError("Employee not chosen")
2023-05-10 15:06:57 +05:30
return days.first()
class RotatingShiftForm(ModelForm):
2023-08-01 16:48:48 +05:30
"""
RotatingShift model's form
"""
2023-05-10 15:06:57 +05:30
class Meta:
2023-08-01 16:48:48 +05:30
"""
Meta class for additional options
"""
2023-05-10 15:06:57 +05:30
2023-08-01 16:48:48 +05:30
model = RotatingShift
fields = "__all__"
exclude = ("employee_id",)
2023-05-10 15:06:57 +05:30
class RotatingShiftAssignForm(forms.ModelForm):
2023-08-01 16:48:48 +05:30
"""
RotatingShiftAssign model's form
"""
2023-05-10 15:06:57 +05:30
employee_id = forms.ModelMultipleChoiceField(
2023-08-01 16:48:48 +05:30
label="Employee",
queryset=Employee.objects.filter(employee_work_info__isnull=False),
)
based_on = forms.ChoiceField(choices=BASED_ON, initial="daily")
rotate_after_day = forms.IntegerField(
initial=5,
)
start_date = forms.DateField(initial=datetime.date.today, widget=forms.DateInput)
2023-05-10 15:06:57 +05:30
class Meta:
2023-08-01 16:48:48 +05:30
"""
Meta class for additional options
"""
2023-05-10 15:06:57 +05:30
model = RotatingShiftAssign
2023-08-01 16:48:48 +05:30
fields = "__all__"
exclude = ("next_change_date", "current_shift", "next_shift")
2023-05-10 15:06:57 +05:30
widgets = {
2023-08-01 16:48:48 +05:30
"start_date": DateInput(attrs={"type": "date"}),
2023-05-10 15:06:57 +05:30
}
labels = {
2023-08-01 16:48:48 +05:30
"rotating_shift_id": "Rotating shift",
2023-05-10 15:06:57 +05:30
}
def __init__(self, *args, **kwargs):
2023-08-01 16:48:48 +05:30
super().__init__(*args, **kwargs)
self.fields["rotate_every_weekend"].widget.attrs.update(
{
"class": "w-100 ",
"style": "display:none; height:50px; border-radius:0;border:1px \
solid hsl(213deg,22%,84%);",
"data-hidden": True,
}
)
self.fields["rotate_every"].widget.attrs.update(
{
"class": "w-100 ",
"style": "display:none; height:50px; border-radius:0;border:1px \
solid hsl(213deg,22%,84%);",
"data-hidden": True,
}
)
self.fields["rotate_after_day"].widget.attrs.update(
{
"class": "w-100 oh-input",
"style": " height:50px; border-radius:0;",
}
)
self.fields["based_on"].widget.attrs.update(
{
"class": "w-100",
"style": " height:50px; border-radius:0;border:1px solid hsl(213deg,22%,84%);",
}
)
self.fields["start_date"].widget = forms.DateInput(
attrs={
"class": "w-100 oh-input",
"type": "date",
"style": " height:50px; border-radius:0;",
}
)
self.fields["rotating_shift_id"].widget.attrs.update(
{
"class": "oh-select oh-select-2",
}
)
self.fields["employee_id"].widget.attrs.update(
{
"class": "oh-select oh-select-2",
}
)
2023-05-10 15:06:57 +05:30
def clean_employee_id(self):
2023-08-01 16:48:48 +05:30
"""
Validation to employee_id field
"""
employee_ids = self.cleaned_data.get("employee_id")
2023-05-10 15:06:57 +05:30
if employee_ids:
return employee_ids[0]
else:
2023-08-01 16:48:48 +05:30
return ValidationError("This field is required")
2023-05-10 15:06:57 +05:30
def clean(self):
cleaned_data = super().clean()
2023-08-01 16:48:48 +05:30
if "rotate_after_day" in self.errors:
del self.errors["rotate_after_day"]
2023-05-10 15:06:57 +05:30
return cleaned_data
2023-08-01 16:48:48 +05:30
def save(
self,
commit=False,
):
employee_ids = self.data.getlist("employee_id")
rotating_shift = RotatingShift.objects.get(id=self.data["rotating_shift_id"])
day_name = self.cleaned_data["rotate_every_weekend"]
day_names = [
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday",
"sunday",
]
2023-05-10 15:06:57 +05:30
target_day = day_names.index(day_name.lower())
for employee_id in employee_ids:
employee = Employee.objects.filter(id=employee_id).first()
rotating_shift_assign = RotatingShiftAssign()
rotating_shift_assign.rotating_shift_id = rotating_shift
rotating_shift_assign.employee_id = employee
2023-08-01 16:48:48 +05:30
rotating_shift_assign.based_on = self.cleaned_data["based_on"]
rotating_shift_assign.start_date = self.cleaned_data["start_date"]
rotating_shift_assign.next_change_date = self.cleaned_data["start_date"]
rotating_shift_assign.rotate_after_day = self.data.get("rotate_after_day")
rotating_shift_assign.rotate_every = self.cleaned_data["rotate_every"]
rotating_shift_assign.rotate_every_weekend = self.cleaned_data[
"rotate_every_weekend"
]
rotating_shift_assign.next_change_date = self.cleaned_data["start_date"]
2023-05-10 15:06:57 +05:30
rotating_shift_assign.current_shift = employee.employee_work_info.shift_id
rotating_shift_assign.next_shift = rotating_shift.shift2
2023-08-01 16:48:48 +05:30
based_on = self.cleaned_data["based_on"]
start_date = self.cleaned_data["start_date"]
2023-05-10 15:06:57 +05:30
if based_on == "weekly":
next_date = get_next_week_date(target_day, start_date)
rotating_shift_assign.next_change_date = next_date
elif based_on == "monthly":
# 0, 1, 2, ..., 31, or "last"
2023-08-01 16:48:48 +05:30
rotate_every = self.cleaned_data["rotate_every"]
start_date = self.cleaned_data["start_date"]
2023-05-10 15:06:57 +05:30
next_date = get_next_monthly_date(start_date, rotate_every)
rotating_shift_assign.next_change_date = next_date
elif based_on == "after":
2023-08-01 16:48:48 +05:30
rotating_shift_assign.next_change_date = (
rotating_shift_assign.start_date
+ datetime.timedelta(days=int(self.data.get("rotate_after_day")))
)
2023-05-10 15:06:57 +05:30
rotating_shift_assign.save()
class RotatingShiftAssignUpdateForm(forms.ModelForm):
2023-08-01 16:48:48 +05:30
"""
RotatingShiftAssign model's form
"""
2023-05-10 15:06:57 +05:30
class Meta:
2023-08-01 16:48:48 +05:30
"""
Meta class for additional options
"""
2023-05-10 15:06:57 +05:30
model = RotatingShiftAssign
2023-08-01 16:48:48 +05:30
fields = "__all__"
exclude = ("next_change_date", "current_shift", "next_shift")
2023-05-10 15:06:57 +05:30
widgets = {
2023-08-01 16:48:48 +05:30
"start_date": DateInput(attrs={"type": "date"}),
2023-05-10 15:06:57 +05:30
}
def __init__(self, *args, **kwargs):
2023-08-01 16:48:48 +05:30
super().__init__(*args, **kwargs)
self.fields["rotate_every_weekend"].widget.attrs.update(
{
"class": "w-100 ",
"style": "display:none; height:50px; border-radius:0; border:1px \
solid hsl(213deg,22%,84%);",
"data-hidden": True,
}
)
self.fields["rotate_every"].widget.attrs.update(
{
"class": "w-100 ",
"style": "display:none; height:50px; border-radius:0; border:1px \
solid hsl(213deg,22%,84%);",
"data-hidden": True,
}
)
self.fields["rotate_after_day"].widget.attrs.update(
{
"class": "w-100 oh-input",
"style": " height:50px; border-radius:0;",
}
)
self.fields["based_on"].widget.attrs.update(
{
"class": "w-100",
"style": " height:50px; border-radius:0; border:1px solid hsl(213deg,22%,84%);",
}
)
self.fields["start_date"].widget = forms.DateInput(
attrs={
"class": "w-100 oh-input",
"type": "date",
"style": " height:50px; border-radius:0;",
}
)
self.fields["rotating_shift_id"].widget.attrs.update(
{
"class": "oh-select oh-select-2",
}
)
self.fields["employee_id"].widget.attrs.update(
{
"class": "oh-select oh-select-2",
}
)
2023-05-10 15:06:57 +05:30
def save(self, *args, **kwargs):
2023-08-01 16:48:48 +05:30
day_name = self.cleaned_data["rotate_every_weekend"]
day_names = [
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday",
"sunday",
]
2023-05-10 15:06:57 +05:30
target_day = day_names.index(day_name.lower())
2023-08-01 16:48:48 +05:30
based_on = self.cleaned_data["based_on"]
2023-05-10 15:06:57 +05:30
start_date = self.instance.start_date
if based_on == "weekly":
next_date = get_next_week_date(target_day, start_date)
self.instance.next_change_date = next_date
elif based_on == "monthly":
rotate_every = self.instance.rotate_every # 0, 1, 2, ..., 31, or "last"
start_date = self.instance.start_date
next_date = get_next_monthly_date(start_date, rotate_every)
self.instance.next_change_date = next_date
elif based_on == "after":
2023-08-01 16:48:48 +05:30
self.instance.next_change_date = (
self.instance.start_date
+ datetime.timedelta(days=int(self.data.get("rotate_after_day")))
)
2023-05-10 15:06:57 +05:30
return super().save()
class ShiftRequestForm(ModelForm):
2023-08-01 16:48:48 +05:30
"""
ShiftRequest model's form
"""
2023-05-10 15:06:57 +05:30
class Meta:
2023-08-01 16:48:48 +05:30
"""
Meta class for additional options
"""
2023-05-10 15:06:57 +05:30
model = ShiftRequest
2023-08-01 16:48:48 +05:30
fields = "__all__"
exclude = (
"approved",
"canceled",
"previous_shift_id",
"is_active",
"shift_changed",
)
2023-05-10 15:06:57 +05:30
widgets = {
2023-08-01 16:48:48 +05:30
"requested_date": DateInput(attrs={"type": "date"}),
"requested_till": DateInput(attrs={"type": "date"}),
2023-05-10 15:06:57 +05:30
}
2023-08-01 16:48:48 +05:30
labels = {"employee_id": "Employee", "shift_id": "Shift"}
2023-05-10 15:06:57 +05:30
def save(self, commit: bool = ...):
if not self.instance.approved:
employee = self.instance.employee_id
self.instance.previous_shift_id = employee.employee_work_info.shift_id
return super().save(commit)
# here set default filter for all the employees those have work information filled.
class WorkTypeRequestForm(ModelForm):
2023-08-01 16:48:48 +05:30
"""
WorkTypeRequest model's form
"""
2023-05-10 15:06:57 +05:30
class Meta:
2023-08-01 16:48:48 +05:30
"""
Meta class for additional options
"""
2023-05-10 15:06:57 +05:30
model = WorkTypeRequest
2023-08-01 16:48:48 +05:30
fields = "__all__"
exclude = (
"approved",
"canceled",
"previous_work_type_id",
"is_active",
"work_type_changed",
)
2023-05-10 15:06:57 +05:30
widgets = {
2023-08-01 16:48:48 +05:30
"requested_date": DateInput(attrs={"type": "date"}),
"requested_till": DateInput(attrs={"type": "date"}),
2023-05-10 15:06:57 +05:30
}
2023-08-01 16:48:48 +05:30
labels = {"employee_id": "Employee", "work_type_id": "Work type"}
2023-05-10 15:06:57 +05:30
def save(self, commit: bool = ...):
if not self.instance.approved:
employee = self.instance.employee_id
2023-08-01 16:48:48 +05:30
self.instance.previous_work_type_id = (
employee.employee_work_info.work_type_id
)
2023-05-10 15:06:57 +05:30
return super().save(commit)
class ResetPasswordForm(forms.Form):
2023-08-01 16:48:48 +05:30
"""
ResetPasswordForm
"""
2023-05-10 15:06:57 +05:30
password = forms.CharField(
label="New password",
strip=False,
2023-08-01 16:48:48 +05:30
widget=forms.PasswordInput(
attrs={
"autocomplete": "new-password",
"placeholder": "Enter Strong Password",
"class": "oh-input oh-input--password w-100 mb-2",
}
),
2023-05-10 15:06:57 +05:30
help_text="Enter your new password.",
)
confirm_password = forms.CharField(
label="New password confirmation",
strip=False,
2023-08-01 16:48:48 +05:30
widget=forms.PasswordInput(
attrs={
"autocomplete": "new-password",
"placeholder": "Re-Enter Password",
"class": "oh-input oh-input--password w-100 mb-2",
}
),
2023-05-10 15:06:57 +05:30
help_text="Enter the same password as before, for verification.",
)
def clean_password(self):
2023-08-01 16:48:48 +05:30
"""
Validation to password field"""
password = self.cleaned_data.get("password")
2023-05-10 15:06:57 +05:30
try:
if len(password) < 7:
2023-08-01 16:48:48 +05:30
raise ValidationError("Password must contain at least 8 characters.")
2023-05-10 15:06:57 +05:30
elif not any(char.isupper() for char in password):
raise ValidationError(
2023-08-01 16:48:48 +05:30
"Password must contain at least one uppercase letter."
)
2023-05-10 15:06:57 +05:30
elif not any(char.islower() for char in password):
raise ValidationError(
2023-08-01 16:48:48 +05:30
"Password must contain at least one lowercase letter."
)
2023-05-10 15:06:57 +05:30
elif not any(char.isdigit() for char in password):
2023-08-01 16:48:48 +05:30
raise ValidationError("Password must contain at least one digit.")
2023-05-10 15:06:57 +05:30
elif all(
2023-08-01 16:48:48 +05:30
char not in "!@#$%^&*()_+-=[]{}|;:,.<>?'\"`~\\/" for char in password
2023-05-10 15:06:57 +05:30
):
raise ValidationError(
2023-08-01 16:48:48 +05:30
"Password must contain at least one special character."
)
except ValidationError as error:
raise forms.ValidationError(list(error)[0])
2023-05-10 15:06:57 +05:30
return password
def clean_confirm_password(self):
2023-08-01 16:48:48 +05:30
"""
validation method for confirm password field
"""
password = self.cleaned_data.get("password")
confirm_password = self.cleaned_data.get("confirm_password")
2023-05-10 15:06:57 +05:30
if password == confirm_password:
return confirm_password
2023-08-01 16:48:48 +05:30
raise forms.ValidationError("Password must be same.")
2023-05-10 15:06:57 +05:30
def save(self, *args, user=None, **kwargs):
2023-08-01 16:48:48 +05:30
"""
Save method to ResetPasswordForm
"""
2023-05-10 15:06:57 +05:30
if user is not None:
2023-08-01 16:48:48 +05:30
user.set_password(self.data["password"])
2023-05-10 15:06:57 +05:30
user.save()