Skip to content

Commit

Permalink
code optimization
Browse files Browse the repository at this point in the history
  • Loading branch information
samdanikouser committed Jan 8, 2025
1 parent 6154bbf commit 0830752
Showing 1 changed file with 42 additions and 23 deletions.
65 changes: 42 additions & 23 deletions one_fm/patches/v15_0/update_employees_operation_role.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,48 @@

@frappe.whitelist()
def execute():
shift_employees = frappe.get_all("Employee",fields=['name'],filters={'shift_working':1,'status':'Active'})
employees_name = [employee_name['name'] for employee_name in shift_employees]
if not employees_name:
return []
# Fetch all employees and their schedules in a single query
query = """
SELECT es.employee,es.shift,es.operations_role
FROM `tabEmployee Schedule` as es
WHERE es.roster_type = 'Basic'
AND es.employee_availability = 'Working'
AND es.employee IN %(employee_names)s
AND es.date = (
SELECT MAX(date)
FROM `tabEmployee Schedule` AS sub
WHERE sub.employee = es.employee
)
SELECT e.name AS employee, e.shift AS current_shift, es.shift AS schedule_shift, es.operations_role
FROM `tabEmployee` AS e
LEFT JOIN (
SELECT es.employee, es.shift, es.operations_role
FROM `tabEmployee Schedule` AS es
WHERE es.roster_type = 'Basic'
AND es.employee_availability = 'Working'
AND es.date = (
SELECT MAX(date)
FROM `tabEmployee Schedule` AS sub
WHERE sub.employee = es.employee
)
) AS es
ON e.name = es.employee
WHERE e.shift_working = 1 AND e.status = 'Active';
"""
schedules = frappe.db.sql(query, {"employee_names": employees_name}, as_dict=True)
schedule_map = {schedule['employee']: schedule for schedule in schedules}
results = frappe.db.sql(query, as_dict=True)

for employee in employees_name:
update_operation_role = frappe.get_doc('Employee',employee)
schedule = schedule_map.get(employee)
if schedule and update_operation_role.shift and update_operation_role.shift == schedule['shift']:
update_operation_role.custom_operations_role_allocation = schedule['operations_role']
update_operation_role.save(ignore_permissions=True)
frappe.db.commit()
# Prepare bulk update data
updates = []
for schedule in results:
if schedule["schedule_shift"] and schedule["current_shift"] == schedule["schedule_shift"]:
updates.append((schedule["operations_role"], schedule["employee"]))

# Execute bulk update if there are matching records
if updates:
update_query = """
UPDATE `tabEmployee`
SET custom_operations_role_allocation = CASE name
"""
update_cases = []
employee_ids = []
for operations_role, employee_name in updates:
update_cases.append(f"WHEN '{employee_name}' THEN '{operations_role}'")
employee_ids.append(f"'{employee_name}'")

# Combine the query
update_query += " ".join(update_cases) + " END WHERE name IN (" + ", ".join(employee_ids) + ")"

# Execute the query
frappe.db.sql(update_query)
frappe.db.commit()
return results

0 comments on commit 0830752

Please sign in to comment.