[UPDT] EMPLOYEE: Badge prefix and auto next badge id

This commit is contained in:
Horilla
2024-02-03 13:57:02 +05:30
parent ff73d2c7a1
commit 7dba7f458f
6 changed files with 126 additions and 48 deletions

View File

@@ -152,45 +152,33 @@ class EmployeeForm(ModelForm):
"""
This method is used to generate badge id
"""
try:
# total_employee_count = Employee.objects.count()
badge_ids = Employee.objects.filter(~Q(badge_id=None)).order_by("-badge_id")
greatest_id = badge_ids.first().badge_id
match = re.findall(r"\d+", greatest_id[::-1])
total_employee_count = 0
if match:
total_employee_count = int(match[0][::-1])
except Exception:
total_employee_count = 0
try:
string = (
Employee.objects.filter(~Q(badge_id=None))
.order_by("-badge_id")
.last()
.badge_id
)
except Exception:
string = "DUDE"
# Find the index of the last integer group in the string
integer_group_index = None
for i in range(len(string) - 1, -1, -1):
if string[i].isdigit():
integer_group_index = i
elif integer_group_index is not None:
break
from base.context_processors import get_intial_prefix
from employee.methods.methods import get_ordered_badge_ids
if integer_group_index is None:
# There is no integer group in the string, so just append #01
return string + "#01"
# Extract the integer group from the string
integer_group = string[integer_group_index:]
prefix = string[:integer_group_index]
prefix = get_intial_prefix(None)["get_intial_prefix"]
data = get_ordered_badge_ids()
result = []
for sublist in data:
for item in sublist:
if isinstance(item, str) and item.lower().startswith(prefix.lower()):
# Find the index of the item in the sublist
index = sublist.index(item)
# Check if there is a next item in the sublist
if index + 1 < len(sublist):
result = sublist[index + 1]
result = re.findall(r"[a-zA-Z]+|\d+|[^a-zA-Z\d\s]", result)
# Set the integer group to the total number of employees plus one
new_integer_group = str(total_employee_count + 1).zfill(len(integer_group))
if result:
prefix = []
incremented = False
for item in reversed(result):
if not incremented and isinstance(eval(str(item)), int):
item = eval(item) + 1
incremented = True
prefix.insert(0, str(item))
prefix = "".join(prefix)
# Return the new string
return prefix + new_integer_group
return prefix
def clean_badge_id(self):
"""
@@ -442,9 +430,9 @@ class BulkUpdateFieldForm(forms.Form):
]
self.fields["update_fields"].choices = updated_choices
for visible in self.visible_fields():
visible.field.widget.attrs["class"] = (
"oh-select oh-select-2 select2-hidden-accessible oh-input w-100"
)
visible.field.widget.attrs[
"class"
] = "oh-select oh-select-2 select2-hidden-accessible oh-input w-100"
class EmployeeNoteForm(ModelForm):
@@ -571,7 +559,6 @@ class DisciplinaryActionForm(ModelForm):
class ActiontypeForm(ModelForm):
class Meta:
model = Actiontype
fields = "__all__"

View File

@@ -0,0 +1,51 @@
"""
employee/methods.py
"""
from employee.models import Employee
from itertools import groupby
from base.context_processors import get_intial_prefix
def dynamic_prefix_sort(item):
# Assuming the dynamic prefix length is 3
prefix = get_intial_prefix(None)["get_intial_prefix"]
prefix_length = len(prefix) if len(prefix) >= 3 else 3
return item[:prefix_length]
def get_ordered_badge_ids():
"""
This method is used to return ordered badge ids
"""
employees = Employee.objects.all()
data = (
employees.exclude(badge_id=None)
.order_by("badge_id")
.values_list("badge_id", flat=True)
)
# Separate pure number strings and convert them to integers
pure_numbers = [int(item) for item in data if item.isdigit()]
# Remove pure number strings from the original data
data = [item for item in data if not item.isdigit()]
# Sort the remaining data by dynamic prefixes
sorted_data = sorted(data, key=dynamic_prefix_sort)
# Group the sorted data by dynamic prefixes
grouped_data = [
list(group) for _, group in groupby(sorted_data, key=dynamic_prefix_sort)
]
# Sort each subgroup alphabetically and numerically
for group in grouped_data:
group.sort()
group.sort(key=lambda x: int("".join(filter(str.isdigit, x))))
# Create a list containing the first and last items from each group
result = [[group[0], group[-1]] for group in grouped_data]
# Add the list of pure numbers at the beginning
result.insert(0, [pure_numbers[0], pure_numbers[-1]])
return result

View File

@@ -1,4 +1,13 @@
{% load i18n %}
<div class="oh-modal" id="badgeModal" role="dialog" aria-hidden="true">
<div class="oh-modal__dialog" style="max-width: 550px">
<div class="oh-modal__dialog-header">
<button type="button" class="oh-modal__close" aria-label="Close"><ion-icon name="close-outline"></ion-icon></button>
</div>
<div class="oh-modal__dialog-body" id="badgeModalBody"></div>
</div>
</div>
<div class="oh-wrapper" data-select2-id="select2-data-40-yu7x">
<div class="oh-general__tab-target oh-profile-section mb-4" id="personal" data-select2-id="select2-data-personal">
@@ -58,7 +67,11 @@
</div>
<div class="row">
<div class="col-12 col-sm-12 col-md-12 col-lg-6">
<label class="oh-label" for="firstname">{% trans "Badge Id" %}</label>
<label class="oh-label" for="firstname">{% trans "Badge Id" %}
<div hx-get="{% url 'get-first-last-badge-id' %}" hx-target="#badgeModalBody" data-target="#badgeModal" data-toggle="oh-modal-toggle" class="oh-checkpoint-badge text-success mb-2" id="selectAllInstances" style="cursor: pointer">
{% trans "Show" %}
</div>
</label>
{{form.badge_id}}
{{form.badge_id.errors}}
</div>

View File

@@ -0,0 +1,5 @@
{% for badge in badge_ids %}
<div class="oh-checkpoint-badge text-warning mb-2" id="selectAllInstances" style="">
{{badge.0}} - {{badge.1}}
</div>
{% endfor %}

View File

@@ -347,5 +347,6 @@ urlpatterns = [
views.encashment_condition_create,
name="encashment-condition-create",
),
path("initial-prefix",views.initial_prefix,name="initial-prefix")
path("initial-prefix",views.initial_prefix,name="initial-prefix"),
path("get-first-last-badge-id",views.first_last_badge,name="get-first-last-badge-id"),
]

View File

@@ -35,6 +35,7 @@ from django.forms import CharField, ChoiceField, DateInput, Select
from asset.models import AssetAssignment, AssetRequest
from django.utils.translation import gettext_lazy as _
from attendance.models import Attendance, AttendanceOverTime
from employee.methods.methods import get_ordered_badge_ids
from leave.models import LeaveRequest
from notifications.signals import notify
from horilla.decorators import (
@@ -1529,7 +1530,7 @@ def employee_filter_view(request):
employees = employees.order_by(field_copy)
employees = employees.exclude(employee_work_info__isnull=True)
template = "employee_personal_info/group_by.html"
employees = sortby(request, employees, "orderby")
return render(
request,
template,
@@ -1754,12 +1755,13 @@ def employee_archive(request, obj_id):
if save:
employee.save()
messages.success(request, message)
return HttpResponse("<script>window.location.reload();</script>")
else:
related_models = ", ".join(model for model in result.get("related_models"))
messages.warning(
request, _(f"Can't archive.Employee assigned as {related_models}")
return render(
request,
"related_models.html",
{"employee": employee, "related_models": result.get("related_models")},
)
return HttpResponseRedirect(request.META.get("HTTP_REFERER"))
@login_required
@@ -2340,6 +2342,8 @@ def get_employees_birthday(_):
"name": name,
"dob": dob,
"daysUntilBirthday": days_till_birthday,
"department": emp.get_department().department,
"job_position": emp.get_job_position().job_position,
}
)
return JsonResponse({"birthdays": birthdays})
@@ -2902,5 +2906,22 @@ def initial_prefix(request):
instance = instance if instance else EmployeeGeneralSetting()
instance.badge_id_prefix = request.POST["initial_prefix"]
instance.save()
messages.success(request,"Initial prefix update")
messages.success(request, "Initial prefix update")
return HttpResponseRedirect(request.META.get("HTTP_REFERER", "/"))
@login_required
@manager_can_enter("employee.view_employee")
def first_last_badge(request):
"""
This method is used to return the first last badge ids in grouped and ordere
"""
badge_ids =get_ordered_badge_ids()
return render(
request,
"employee_personal_info/first_last_badge.html",
{"badge_ids": badge_ids},
)