Merge pull request #16740 from nabinhait/leave-calendar

fix: Calendar events for leaves considering user permissions
diff --git a/erpnext/hr/doctype/leave_application/leave_application.py b/erpnext/hr/doctype/leave_application/leave_application.py
index 6b7c0f7..b85f38b 100755
--- a/erpnext/hr/doctype/leave_application/leave_application.py
+++ b/erpnext/hr/doctype/leave_application/leave_application.py
@@ -487,7 +487,6 @@
 
 	add_block_dates(events, start, end, employee, company)
 	add_holidays(events, start, end, employee, company)
-
 	return events
 
 def add_department_leaves(events, start, end, employee, company):
@@ -500,10 +499,22 @@
 	department_employees = frappe.db.sql_list("""select name from tabEmployee where department=%s
 		and company=%s""", (department, company))
 
-	match_conditions = "and employee in (\"%s\")" % '", "'.join(department_employees)
-	add_leaves(events, start, end, match_conditions=match_conditions)
+	filter_conditions = "employee in (\"%s\")" % '", "'.join(department_employees)
+	add_leaves(events, start, end, filter_conditions=filter_conditions)
 
-def add_leaves(events, start, end, match_conditions=None):
+def add_leaves(events, start, end, filter_conditions=None):
+	conditions = []
+
+	if filter_conditions:
+		conditions.append(filter_conditions)
+
+	if not cint(frappe.db.get_value("HR Settings", None, "show_leaves_of_all_department_members_in_calendar")):
+		from frappe.desk.reportview import build_match_conditions
+		match_conditions = build_match_conditions("Leave Application")
+
+		if match_conditions:
+			conditions.append(match_conditions)
+
 	query = """select name, from_date, to_date, employee_name, half_day,
 		status, employee, docstatus
 		from `tabLeave Application` where
@@ -511,8 +522,8 @@
 		and docstatus < 2
 		and status!="Rejected" """
 
-	if match_conditions:
-		query += match_conditions
+	if conditions:
+		query += ' and ' + ' and '.join(conditions)
 
 	for d in frappe.db.sql(query, {"start":start, "end": end}, as_dict=True):
 		e = {