if not workcalendarconfig:
raise ValueError(f"WorkCalendarConfig with UUID {policy.workcalendarconfig['uuid']} not found.")
# Parse the JSON fields
apply_for_list = self._parse_json(getattr(workcalendarconfig, 'apply_for', "[]"))
title_list = self._parse_json(getattr(workcalendarconfig, 'title', "[]"))
employees = self._parse_json(getattr(workcalendarconfig, 'employees', "[]"))
# If no valid data is available, raise an error
if not any([employees, apply_for_list, title_list]):
raise ValueError("No data available to create work shifts.")
# Helper function to create a RegisterShift object
def create_registershift(employee, day):
start_time = datetime.combine(day, policy.shift_start_time)
end_time = datetime.combine(day, policy.shift_end_time)
return RegisterShift(
name=f"Ca làm việc - {day} - {policy.shift_start_time} - {policy.shift_end_time}",
employees={
'uuid': employee.uuid,
'code': employee.code,
'name': employee.name,
'friendly_code': employee.friendly_code,
'employee_code': employee.employee_code
},
start_time=start_time,
end_time=end_time,
friendly_code=policy.friendly_code,
dayswork=str(day),
shift_check=policy.shift_check,
employees_planning=policy.employees_planning,
employees_counter=0,
day_week=policy.weekday,
work_shift={
"uuid": self.uuid,
"friendly_code": self.friendly_code,
"name": self.name,
"code": self.code,
},
calendar_type=workcalendarconfig.calendar_type,
end_register=workcalendarconfig.close_time,
level_detail=self.level_detail if self.level_detail else None,
title=self.title if self.title else None,
number_approver=0,
hr_created_by=self.hr_created_by,
shift_status='Chưa mở',
)
# If employees list is provided, create shifts only for those employees
if employees:
for employee in employees:
for day in shift_days:
#Kiểm tra lặp lại theo tuần
if self.week_repeat:
week_order = (day - self.start_date).days // 7
repeat_cycle = self.num_repeat_rest + self.num_repeat_work
if week_order % repeat_cycle >= self.num_repeat_work:
continue
#Kiểm tra lặp lại theo tháng
elif self.month_repeat:
if self.repeat_fisrt_month:
week_order = (day - date(day.year, day.month, 1)).days // 7
else:
week_order = (calendar.monthrange(day.year, day.month) - day.day) // 7
if week_order >= self.num_work_for_month:
continue
start_time = datetime.combine(day, policy.shift_start_time)
end_time = datetime.combine(day, policy.shift_end_time)
register_shift = RegisterShift(
name=f"Ca làm việc - {day} - {policy.shift_start_time} - {policy.shift_end_time}",
employees={
'uuid': employee['uuid'],
'code': employee['code'],
'name': employee['name'],
'friendly_code': employee['friendly_code'],
'employee_code': employee['employee_code']
},
start_time=start_time,
end_time=end_time,
friendly_code=policy.friendly_code,
dayswork=str(day),
shift_check=policy.shift_check,
employees_planning=policy.employees_planning,
employees_counter=0,
day_week=policy.weekday,
work_shift={
"uuid": self.uuid,
"friendly_code": self.friendly_code,
"name": self.name,
"code": self.code,
},
calendar_type=workcalendarconfig.calendar_type,
end_register=workcalendarconfig.close_time,
level_detail=self.level_detail if self.level_detail else None,
title=self.title if self.title else None,
number_approver=0,
hr_created_by=self.hr_created_by,
shift_status='Chưa mở',
)
shifts_for_register.append(register_shift)
else:
seen_employees = set()
if apply_for_list and title_list:
for apply_for in apply_for_list:
for title in title_list:
if isinstance(apply_for, dict) and isinstance(title, dict):
# Fetch employees that match both conditions
employees_list = Employees.objects.filter(
Q(level_detail__uuid=apply_for['uuid']) & Q(title__uuid=title['uuid'])
)
for employee in employees_list:
# Check if we've already added this employee (to avoid duplicates)
if employee.uuid not in seen_employees:
for day in shift_days:
shifts_for_register.append(create_registershift(employee, day))
seen_employees.add(employee.uuid)
# Generate shifts for employees in specific departments (apply_for_list)
elif apply_for_list:
for apply_for in apply_for_list:
if isinstance(apply_for, dict):
employee_list = Employees.objects.filter(level_detail__uuid=apply_for['uuid'])
for employee in employee_list:
# Check if we've already added this employee (to avoid duplicates)
if employee.uuid not in seen_employees:
for day in shift_days:
shifts_for_register.append(create_registershift(employee, day))
seen_employees.add(employee.uuid)
# Generate shifts for employees with specific titles (title_list)
elif title_list:
for title in title_list:
if isinstance(title, dict):
employee_list = Employees.objects.filter(title__uuid=title['uuid'])
for employee in employee_list:
# Check if we've already added this employee (to avoid duplicates)
if employee.uuid not in seen_employees:
for day in shift_days:
shifts_for_register.append(create_registershift(employee, day))
seen_employees.add(employee.uuid)
# Generate shifts for employees that meet both apply_for_list and title_list criteria
return # The function modifies shifts_for_register in place, no need for an explicit return
Tối ưu đoạn code trên
To optimize the provided code, we can focus on reducing redundancy, enhancing clarity, and ensuring efficient database queries. Below are several suggestions that can help streamline the logic while maintaining functionality:
Extract Repetitive Logic: We can refactor the logic that's used to create RegisterShift objects into a separate function. This will improve readability and maintainability.
Reduce Filtering Redundancy: Instead of querying employees multiple times, we can group the employee fetching logic under one query per relevant parameter.
Combine Similar Checks: The checks for applying for lists and titles can be unified wherever possible to reduce the number of loops.
Use set for Seen Employees Early: A set can be employed to ensure that we don’t fetch duplicate employees initially.
Here is a modified version of your code that incorporates the above improvements:
python
def create_register_shifts(self, policy, shift_days, shifts_for_register):
workcalendarconfig = WorkCalendarConfig.objects.filter(uuid=policy.workcalendarconfig['uuid']).first()
if not workcalendarconfig:
raise ValueError(f"WorkCalendarConfig with UUID {policy.workcalendarconfig['uuid']} not found.")
# Parse the JSON fields
apply_for_list = self._parse_json(getattr(workcalendarconfig, 'apply_for', "[]"))
title_list = self._parse_json(getattr(workcalendarconfig, 'title', "[]"))
employees = self._parse_json(getattr(workcalendarconfig, 'employees', "[]"))
# If no valid data is available, raise an error
if not any([employees, apply_for_list, title_list]):
raise ValueError("No data available to create work shifts.")
# Helper function to create a RegisterShift object
def create_registershift(employee, day):
start_time = datetime.combine(day, policy.shift_start_time)
end_time = datetime.combine(day, policy.shift_end_time)
return RegisterShift(
name=f"Ca làm việc - {day} - {policy.shift_start_time} - {policy.shift_end_time}",
employees={
'uuid': employee.uuid,
'code': employee.code,
'name': employee.name,
'friendly_code': employee.friendly_code,
'employee_code': employee.employee_code
},
start_time=start_time,
end_time=end_time,
friendly_code=policy.friendly_code,
dayswork=str(day),
shift_check=policy.shift_check,
employees_planning=policy.employees_planning,
employees_counter=0,
day_week=policy.weekday,
work_shift={
"uuid": self.uuid,
"friendly_code": self.friendly_code,
"name": self.name,
"code": self.code,
},
calendar_type=workcalendarconfig.calendar_type,
end_register=workcalendarconfig.close_time,
level_detail=self.level_detail if self.level_detail else None,
title=self.title if self.title else None,
number_approver=0,
hr_created_by=self.hr_created_by,
shift_status='Chưa mở',
)
def should_create_shift(day):
# Kiểm tra lặp lại theo tuần
if self.week_repeat:
week_order = (day - self.start_date).days // 7
repeat_cycle = self.num_repeat_rest + self.num_repeat_work
return week_order % repeat_cycle < self.num_repeat_work
# Kiểm tra lặp lại theo tháng
if self.month_repeat:
if self.repeat_fisrt_month:
week_order = (day - date(day.year, day.month, 1)).days // 7
else:
week_order = (calendar.monthrange(day.year, day.month)[1] - day.day) // 7
return week_order < self.num_work_for_month
return True
seen_employees = set()
# Gather all employees to avoid redundant queries
employee_filter_uuids = set()
if employees:
employee_filter_uuids.update(emp['uuid'] for emp in employees)
if apply_for_list or title_list:
employee_filters = []
if apply_for_list:
employee_filters.append(Q(level_detail__uuid__in=[apply_for['uuid'] for apply_for in apply_for_list if isinstance(apply_for, dict)]))
if title_list:
employee_filters.append(Q(title__uuid__in=[title['uuid'] for title in title_list if isinstance(title, dict)]))
# Compound query to fetch the relevant employees
employees_list = Employees.objects.filter(*employee_filters).distinct()
for employee in employees_list:
if employee.uuid in seen_employees:
continue
for day in shift_days:
if should_create_shift(day):
shifts_for_register.append(create_registershift(employee, day))
seen_employees.add(employee.uuid)
return # The function modifies shifts_for_register in place, no need for an explicit return
Key Changes Made:
Centralized Employee Queries: We now gather all applicable employees at once based on the filters, reducing database calls.
Unified Shift Creation Logic: The logic for creating shifts is centralized in a function to eliminate redundancy.
Improved Shift Creation Checks: Encapsulated the shift creation criteria in a helper function should_create_shift to improve code organization.
These changes aim to make the code more concise, maintainable, and efficient while preserving its core logic and functionality.