Merge pull request #14044 from shreyashah115/fix-promotion-doc

[Fix] Updation of new values in Employee Property History
diff --git a/erpnext/__init__.py b/erpnext/__init__.py
index a20b21a..3eaf994 100644
--- a/erpnext/__init__.py
+++ b/erpnext/__init__.py
@@ -5,7 +5,7 @@
 from erpnext.hooks import regional_overrides
 from frappe.utils import getdate
 
-__version__ = '10.1.31'
+__version__ = '10.1.33'
 
 def get_default_company(user=None):
 	'''Get default company for user'''
diff --git a/erpnext/controllers/taxes_and_totals.py b/erpnext/controllers/taxes_and_totals.py
index 5ecff3f..658c7b4 100644
--- a/erpnext/controllers/taxes_and_totals.py
+++ b/erpnext/controllers/taxes_and_totals.py
@@ -567,7 +567,8 @@
 			itemised_tax=itemised_tax,
 			itemised_taxable_amount=itemised_taxable_amount,
 			tax_accounts=tax_accounts,
-			company_currency=erpnext.get_company_currency(doc.company)
+			conversion_rate=doc.conversion_rate,
+			currency=doc.currency
 		)
 	)
 
diff --git a/erpnext/hr/doctype/attendance/attendance.py b/erpnext/hr/doctype/attendance/attendance.py
index 7a4cb64..ad162c6 100644
--- a/erpnext/hr/doctype/attendance/attendance.py
+++ b/erpnext/hr/doctype/attendance/attendance.py
@@ -21,17 +21,19 @@
 		set_employee_name(self)
 
 	def check_leave_record(self):
-		leave_record = frappe.db.sql("""select leave_type, half_day from `tabLeave Application`
-			where employee = %s and %s between from_date and to_date
+		leave_record = frappe.db.sql("""select leave_type, half_day, half_day_date from `tabLeave Application`
+			where employee = %s and %s between from_date and to_date and status = 'Approved'
 			and docstatus = 1""", (self.employee, self.attendance_date), as_dict=True)
 		if leave_record:
-			if leave_record[0].half_day:
-				self.status = 'Half Day'
-				frappe.msgprint(_("Employee {0} on Half day on {1}").format(self.employee, self.attendance_date))
-			else:
-				self.status = 'On Leave'
-				self.leave_type = leave_record[0].leave_type
-				frappe.msgprint(_("Employee {0} on Leave on {1}").format(self.employee, self.attendance_date))
+			for d in leave_record:
+				if d.half_day_date == getdate(self.attendance_date):
+					self.status = 'Half Day'
+					frappe.msgprint(_("Employee {0} on Half day on {1}").format(self.employee, self.attendance_date))
+				else:
+					self.status = 'On Leave'
+					self.leave_type = d.leave_type
+					frappe.msgprint(_("Employee {0} on Leave on {1}").format(self.employee, self.attendance_date))
+
 		if self.status == "On Leave" and not leave_record:
 			frappe.throw(_("No leave record found for employee {0} for {1}").format(self.employee, self.attendance_date))
 
diff --git a/erpnext/hr/doctype/department/department.js b/erpnext/hr/doctype/department/department.js
index 71cf2d2..a945312 100644
--- a/erpnext/hr/doctype/department/department.js
+++ b/erpnext/hr/doctype/department/department.js
@@ -2,7 +2,16 @@
 // For license information, please see license.txt
 
 frappe.ui.form.on('Department', {
-	onload: function(frm) {
-
+	refresh: function(frm) {
+		// read-only for root department
+		if(!frm.doc.parent_department) {
+			cur_frm.set_read_only();
+			cur_frm.set_intro(__("This is a root customer group and cannot be edited."));
+		}
+	},
+	validate: function(frm) {
+		if(frm.doc.name=="All Departments") {
+			frappe.throw(__("You cannot edit root node."));
+		}
 	}
 });
diff --git a/erpnext/hr/doctype/department/department.py b/erpnext/hr/doctype/department/department.py
index 19994ae..6544390 100644
--- a/erpnext/hr/doctype/department/department.py
+++ b/erpnext/hr/doctype/department/department.py
@@ -11,8 +11,11 @@
 	nsm_parent_field = 'parent_department'
 
 	def autoname(self):
-		abbr = frappe.db.get_value('Company', self.company, 'abbr')
-		self.name = '{0} - {1}'.format(self.department_name, abbr)
+		if not self.department_name=="All Departments":
+			abbr = frappe.db.get_value('Company', self.company, 'abbr')
+			self.name = '{0} - {1}'.format(self.department_name, abbr)
+		else:
+			self.name = self.department_name
 
 	def update_nsm_model(self):
 		frappe.utils.nestedset.update_nsm(self)
diff --git a/erpnext/hr/doctype/employee/employee.js b/erpnext/hr/doctype/employee/employee.js
index 6f6873a..7d153d4 100755
--- a/erpnext/hr/doctype/employee/employee.js
+++ b/erpnext/hr/doctype/employee/employee.js
@@ -37,6 +37,15 @@
 
 });
 frappe.ui.form.on('Employee',{
+	setup: function(frm) {
+		frm.set_query("leave_policy", function() {
+			return {
+				"filters": {
+					"docstatus": 1
+				}
+			};
+		});
+	},
 	onload:function(frm) {
 		frm.set_query("department", function() {
 			return {
diff --git a/erpnext/hr/doctype/employee_onboarding/employee_onboarding.py b/erpnext/hr/doctype/employee_onboarding/employee_onboarding.py
index 3390e8f..fab0846 100644
--- a/erpnext/hr/doctype/employee_onboarding/employee_onboarding.py
+++ b/erpnext/hr/doctype/employee_onboarding/employee_onboarding.py
@@ -10,7 +10,7 @@
 
 
 class EmployeeOnboarding(EmployeeBoardingController):
-	def validate():
+	def validate(self):
 		super(EmployeeOnboarding, self).validate()
 
 	def validate_employee_creation(self):
diff --git a/erpnext/hr/doctype/leave_application/leave_application.js b/erpnext/hr/doctype/leave_application/leave_application.js
index b53852a..5f1c883 100755
--- a/erpnext/hr/doctype/leave_application/leave_application.js
+++ b/erpnext/hr/doctype/leave_application/leave_application.js
@@ -138,6 +138,9 @@
 					if (!r.exc && r.message) {
 						frm.set_value('leave_balance', r.message);
 					}
+					else {
+						frm.set_value('leave_balance', "0");
+					}
 				}
 			});
 		}
diff --git a/erpnext/hr/doctype/leave_application/leave_application.py b/erpnext/hr/doctype/leave_application/leave_application.py
index 91397fc..d8a2fe3 100755
--- a/erpnext/hr/doctype/leave_application/leave_application.py
+++ b/erpnext/hr/doctype/leave_application/leave_application.py
@@ -9,6 +9,8 @@
 from erpnext.hr.utils import set_employee_name, get_leave_period
 from erpnext.hr.doctype.leave_block_list.leave_block_list import get_applicable_block_dates
 from erpnext.hr.doctype.employee.employee import get_holiday_list_for_employee
+from erpnext.hr.doctype.employee_leave_approver.employee_leave_approver import get_approver_list
+from erpnext.buying.doctype.supplier_scorecard.supplier_scorecard import daterange
 
 class LeaveDayBlockedError(frappe.ValidationError): pass
 class OverlapError(frappe.ValidationError): pass
@@ -47,6 +49,7 @@
 			frappe.throw(_("Only Leave Applications with status 'Approved' and 'Rejected' can be submitted"))
 
 		self.validate_back_dated_application()
+		self.update_attendance()
 
 		# notify leave applier about approval
 		self.notify_employee()
@@ -112,6 +115,41 @@
 			frappe.throw(_("Leave cannot be applied/cancelled before {0}, as leave balance has already been carry-forwarded in the future leave allocation record {1}")
 				.format(formatdate(future_allocation[0].from_date), future_allocation[0].name))
 
+	def update_attendance(self):
+		if self.status == "Approved":
+			attendance = frappe.db.sql("""select name from `tabAttendance` where employee = %s\
+				and (attendance_date between %s and %s) and docstatus < 2""",(self.employee, self.from_date, self.to_date), as_dict=1)
+
+			if attendance:
+				for d in attendance:
+					doc = frappe.get_doc("Attendance", d.name)
+					if getdate(self.half_day_date) == doc.attendance_date:
+						status = "Half Day"
+					else:
+						status = "On Leave"
+					frappe.db.sql("""update `tabAttendance` set status = %s, leave_type = %s\
+						where name = %s""",(status, self.leave_type, d.name))
+
+			elif self.from_date <= nowdate():
+				for dt in daterange(getdate(self.from_date), getdate(self.to_date)):
+					date = dt.strftime("%Y-%m-%d")
+					if not date == self.half_day_date:
+						doc = frappe.new_doc("Attendance")
+						doc.employee = self.employee
+						doc.attendance_date = date
+						doc.company = self.company
+						doc.status = "On Leave"
+						doc.leave_type = self.leave_type
+						doc.submit()
+					else:
+						doc = frappe.new_doc("Attendance")
+						doc.employee = self.employee
+						doc.attendance_date = date
+						doc.company = self.company
+						doc.status = "Half Day"
+						doc.leave_type = self.leave_type
+						doc.submit()
+
 	def validate_salary_processed_days(self):
 		if not frappe.db.get_value("Leave Type", self.leave_type, "is_lwp"):
 			return
@@ -456,29 +494,18 @@
 		and company=%s""", (department, company))
 
 	match_conditions = "and employee in (\"%s\")" % '", "'.join(department_employees)
-	add_leaves(events, start, end, filter_conditions=match_conditions)
+	add_leaves(events, start, end, match_conditions=match_conditions)
 
-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)
-
+def add_leaves(events, start, end, match_conditions=None):
 	query = """select name, from_date, to_date, employee_name, half_day,
 		status, employee, docstatus
 		from `tabLeave Application` where
 		from_date <= %(end)s and to_date >= %(start)s <= to_date
-		and docstatus < 2"""
+		and docstatus < 2
+		and status!="Rejected" """
 
-	if conditions:
-		query += ' and '.join(conditions)
+	if match_conditions:
+		query += match_conditions
 
 	for d in frappe.db.sql(query, {"start":start, "end": end}, as_dict=True):
 		e = {
diff --git a/erpnext/hr/doctype/leave_period/leave_period.py b/erpnext/hr/doctype/leave_period/leave_period.py
index 1ef6f19..4097169 100644
--- a/erpnext/hr/doctype/leave_period/leave_period.py
+++ b/erpnext/hr/doctype/leave_period/leave_period.py
@@ -60,7 +60,6 @@
 			frappe.throw(_("Employee {0} already have Leave Allocation {1} for this period").format(employee, leave_alloc[0][0])\
 			+ """ <b><a href="#Form/Leave Allocation/{0}">{0}</a></b>""".format(leave_alloc[0][0]))
 
-
 	def validate_dates(self):
 		if getdate(self.from_date) >= getdate(self.to_date):
 			frappe.throw(_("To date can not be equal or less than from date"))
@@ -79,3 +78,4 @@
 				allocation.carry_forward = self.carry_forward_leaves
 		allocation.save(ignore_permissions = True)
 		allocation.submit()
+		frappe.msgprint(_("Leave Allocation {0} created").format(allocation.name))
diff --git a/erpnext/hr/report/monthly_attendance_sheet/monthly_attendance_sheet.py b/erpnext/hr/report/monthly_attendance_sheet/monthly_attendance_sheet.py
index 698c4fb..0c338e0 100644
--- a/erpnext/hr/report/monthly_attendance_sheet/monthly_attendance_sheet.py
+++ b/erpnext/hr/report/monthly_attendance_sheet/monthly_attendance_sheet.py
@@ -22,6 +22,10 @@
 	holiday_map = get_holiday(holiday_list, filters["month"])
 
 	data = []
+	leave_types = frappe.db.sql("""select name from `tabLeave Type`""", as_list=True)
+	leave_list = [d[0] for d in leave_types]
+	columns.extend(leave_list)
+
 	for emp in sorted(att_map):
 		emp_det = emp_map.get(emp)
 		if not emp_det:
@@ -49,10 +53,35 @@
 			elif status == "Half Day":
 				total_p += 0.5
 				total_a += 0.5
+				total_l += 0.5
 
 		row += [total_p, total_l, total_a]
-		data.append(row)
 
+		if not filters.get("employee"):
+			filters.update({"employee": emp})
+			conditions += " and employee = %(employee)s"
+		elif not filters.get("employee") == emp:
+			filters.update({"employee": emp})
+
+		leave_details = frappe.db.sql("""select leave_type, status, count(*) as count from `tabAttendance`\
+			where leave_type is not NULL %s group by leave_type, status""" % conditions, filters, as_dict=1)
+
+		leaves = {}
+		for d in leave_details:
+			if d.status == "Half Day":
+				d.count = d.count * 0.5
+			if d.leave_type in leaves:
+				leaves[d.leave_type] += d.count
+			else:
+				leaves[d.leave_type] = d.count
+
+		for d in leave_list:
+			if d in leaves:
+				row.append(leaves[d])
+			else:
+				row.append("0.0")
+
+		data.append(row)
 	return columns, data
 
 def get_columns(filters):
diff --git a/erpnext/patches/v10_0/set_qty_in_transactions_based_on_serial_no_input.py b/erpnext/patches/v10_0/set_qty_in_transactions_based_on_serial_no_input.py
index 5dbcb1d..083b7f4 100644
--- a/erpnext/patches/v10_0/set_qty_in_transactions_based_on_serial_no_input.py
+++ b/erpnext/patches/v10_0/set_qty_in_transactions_based_on_serial_no_input.py
@@ -9,4 +9,13 @@
 
 	ss = frappe.get_doc("Stock Settings")
 	ss.set_qty_in_transactions_based_on_serial_no_input = 1
+
+	if ss.default_warehouse \
+		and not frappe.db.exists("Warehouse", ss.default_warehouse):
+			ss.default_warehouse = None
+
+	if ss.stock_uom and not frappe.db.exists("UOM", ss.stock_uom):
+		ss.stock_uom = None
+
+	ss.flags.ignore_mandatory = True
 	ss.save()
\ No newline at end of file
diff --git a/erpnext/patches/v11_0/create_department_records_for_each_company.py b/erpnext/patches/v11_0/create_department_records_for_each_company.py
index 4cfe960..6f869b0 100644
--- a/erpnext/patches/v11_0/create_department_records_for_each_company.py
+++ b/erpnext/patches/v11_0/create_department_records_for_each_company.py
@@ -2,7 +2,7 @@
 from frappe.utils.nestedset import rebuild_tree
 
 def execute():
-	for doctype in ['department', 'leave_period', 'staffing_plan']:
+	for doctype in ['department', 'leave_period', 'staffing_plan', 'job_opening']:
 		frappe.reload_doc("hr", "doctype", doctype)
 
 	companies = frappe.db.get_all("Company", fields=["name", "abbr"])
diff --git a/erpnext/projects/doctype/project/project.py b/erpnext/projects/doctype/project/project.py
index abb497c..93ff62d 100644
--- a/erpnext/projects/doctype/project/project.py
+++ b/erpnext/projects/doctype/project/project.py
@@ -77,8 +77,8 @@
 	def validate_weights(self):
 		sum = 0
 		for task in self.tasks:
-			if task.task_weight or 0 > 0:
-				sum = sum + task.task_weight
+			if task.task_weight > 0:
+				sum = flt(sum + task.task_weight, task.precision('task_weight'))
 		if sum > 0 and sum != 1:
 			frappe.throw(
 				_("Total of all task weights should be 1. Please adjust weights of all Project tasks accordingly"))
diff --git a/erpnext/public/js/controllers/transaction.js b/erpnext/public/js/controllers/transaction.js
index 2130d2b..53a4cbb 100644
--- a/erpnext/public/js/controllers/transaction.js
+++ b/erpnext/public/js/controllers/transaction.js
@@ -106,7 +106,7 @@
 		}
 
 		if(
-			this.frm.docstatus < 2 
+			this.frm.docstatus < 2
 			&& this.frm.fields_dict["payment_terms_template"]
 			&& this.frm.fields_dict["payment_schedule"]
 			&& this.frm.doc.payment_terms_template
@@ -1097,6 +1097,8 @@
 					me.in_apply_price_list = false;
 				}
 			}
+		}).always(() => {
+			me.in_apply_price_list = false;
 		});
 	},
 
diff --git a/erpnext/selling/doctype/customer/customer.py b/erpnext/selling/doctype/customer/customer.py
index 239b532..5a95b55 100644
--- a/erpnext/selling/doctype/customer/customer.py
+++ b/erpnext/selling/doctype/customer/customer.py
@@ -317,7 +317,7 @@
 	return address
 
 def get_customer_primary_contact(doctype, txt, searchfield, start, page_len, filters):
-	customer = frappe.db.escape(filters.get('customer'))
+	customer = filters.get('customer')
 	return frappe.db.sql("""
 		select `tabContact`.name from `tabContact`, `tabDynamic Link`
 			where `tabContact`.name = `tabDynamic Link`.parent and `tabDynamic Link`.link_name = %(customer)s
diff --git a/erpnext/setup/setup_wizard/operations/install_fixtures.py b/erpnext/setup/setup_wizard/operations/install_fixtures.py
index c686ed3..8f64d4e 100644
--- a/erpnext/setup/setup_wizard/operations/install_fixtures.py
+++ b/erpnext/setup/setup_wizard/operations/install_fixtures.py
@@ -104,22 +104,6 @@
 		{'doctype': 'Employment Type', 'employee_type_name': _('Intern')},
 		{'doctype': 'Employment Type', 'employee_type_name': _('Apprentice')},
 
-		# Department
-		{'doctype': 'Department', 'department_name': _('All Departments'), 'is_group': 1, 'parent_department': ''},
-		{'doctype': 'Department', 'department_name': _('Accounts'), 'parent_department': _('All Departments')},
-		{'doctype': 'Department', 'department_name': _('Marketing'), 'parent_department': _('All Departments')},
-		{'doctype': 'Department', 'department_name': _('Sales'), 'parent_department': _('All Departments')},
-		{'doctype': 'Department', 'department_name': _('Purchase'), 'parent_department': _('All Departments')},
-		{'doctype': 'Department', 'department_name': _('Operations'), 'parent_department': _('All Departments')},
-		{'doctype': 'Department', 'department_name': _('Production'), 'parent_department': _('All Departments')},
-		{'doctype': 'Department', 'department_name': _('Dispatch'), 'parent_department': _('All Departments')},
-		{'doctype': 'Department', 'department_name': _('Customer Service'), 'parent_department': _('All Departments')},
-		{'doctype': 'Department', 'department_name': _('Human Resources'), 'parent_department': _('All Departments')},
-		{'doctype': 'Department', 'department_name': _('Management'), 'parent_department': _('All Departments')},
-		{'doctype': 'Department', 'department_name': _('Quality Management'), 'parent_department': _('All Departments')},
-		{'doctype': 'Department', 'department_name': _('Research & Development'), 'parent_department': _('All Departments')},
-		{'doctype': 'Department', 'department_name': _('Legal'), 'parent_department': _('All Departments')},
-
 		# Designation
 		{'doctype': 'Designation', 'designation_name': _('CEO')},
 		{'doctype': 'Designation', 'designation_name': _('Manager')},
@@ -276,6 +260,14 @@
 	from erpnext.buying.doctype.supplier_scorecard.supplier_scorecard import make_default_records
 	make_default_records()
 
+	make_fixture_records(records)
+
+	# set default customer group and territory
+	selling_settings = frappe.get_doc("Selling Settings")
+	selling_settings.set_default_customer_group_and_territory()
+	selling_settings.save()
+
+def make_fixture_records(records):
 	from frappe.modules import scrub
 	for r in records:
 		doc = frappe.new_doc(r.get("doctype"))
@@ -296,7 +288,23 @@
 			else:
 				raise
 
-	# set default customer group and territory
-	selling_settings = frappe.get_doc("Selling Settings")
-	selling_settings.set_default_customer_group_and_territory()
-	selling_settings.save()
+def install_post_company_fixtures(company=None):
+	records = [
+		# Department
+		{'doctype': 'Department', 'department_name': _('All Departments'), 'is_group': 1, 'parent_department': ''},
+		{'doctype': 'Department', 'department_name': _('Accounts'), 'parent_department': _('All Departments'), 'company': company},
+		{'doctype': 'Department', 'department_name': _('Marketing'), 'parent_department': _('All Departments'), 'company': company},
+		{'doctype': 'Department', 'department_name': _('Sales'), 'parent_department': _('All Departments'), 'company': company},
+		{'doctype': 'Department', 'department_name': _('Purchase'), 'parent_department': _('All Departments'), 'company': company},
+		{'doctype': 'Department', 'department_name': _('Operations'), 'parent_department': _('All Departments'), 'company': company},
+		{'doctype': 'Department', 'department_name': _('Production'), 'parent_department': _('All Departments'), 'company': company},
+		{'doctype': 'Department', 'department_name': _('Dispatch'), 'parent_department': _('All Departments'), 'company': company},
+		{'doctype': 'Department', 'department_name': _('Customer Service'), 'parent_department': _('All Departments'), 'company': company},
+		{'doctype': 'Department', 'department_name': _('Human Resources'), 'parent_department': _('All Departments'), 'company': company},
+		{'doctype': 'Department', 'department_name': _('Management'), 'parent_department': _('All Departments'), 'company': company},
+		{'doctype': 'Department', 'department_name': _('Quality Management'), 'parent_department': _('All Departments'), 'company': company},
+		{'doctype': 'Department', 'department_name': _('Research & Development'), 'parent_department': _('All Departments'), 'company': company},
+		{'doctype': 'Department', 'department_name': _('Legal'), 'parent_department': _('All Departments'), 'company': company},
+	]
+
+	make_fixture_records(records)
diff --git a/erpnext/setup/setup_wizard/setup_wizard.py b/erpnext/setup/setup_wizard/setup_wizard.py
index d6491a8..101b6aa 100644
--- a/erpnext/setup/setup_wizard/setup_wizard.py
+++ b/erpnext/setup/setup_wizard/setup_wizard.py
@@ -56,6 +56,11 @@
 				'fail_msg': 'Failed to set defaults',
 				'tasks': [
 					{
+						'fn': setup_post_company_fixtures,
+						'args': args,
+						'fail_msg': _("Failed to setup post company fixtures")
+					},
+					{
 						'fn': stage_three,
 						'args': args,
 						'fail_msg': _("Failed to set defaults")
@@ -92,6 +97,7 @@
 	stage_fixtures(args)
 	setup_company(args)
 	setup_taxes(args)
+	setup_post_company_fixtures(args)
 	stage_three(args)
 	stage_four(args)
 	fin(args)
@@ -108,6 +114,9 @@
 def setup_taxes(args):
 	taxes_setup.create_sales_tax(args)
 
+def setup_post_company_fixtures(args):
+	install_fixtures.install_post_company_fixtures(args.get("company_name"))
+
 def stage_three(args):
 	defaults_setup.create_employee_for_self(args)
 	defaults_setup.set_default_settings(args)
diff --git a/erpnext/templates/includes/itemised_tax_breakup.html b/erpnext/templates/includes/itemised_tax_breakup.html
index 4162b3a..982397e 100644
--- a/erpnext/templates/includes/itemised_tax_breakup.html
+++ b/erpnext/templates/includes/itemised_tax_breakup.html
@@ -16,16 +16,16 @@
 				<tr>
 					<td>{{ item }}</td>
 					<td class='text-right'>
-						{{ frappe.utils.fmt_money(itemised_taxable_amount.get(item), None, company_currency) }}
+						{{ frappe.utils.fmt_money(itemised_taxable_amount.get(item), None, currency) }}
 					</td>
 					{% for tax_account in tax_accounts %}
 						{% set tax_details = taxes.get(tax_account) %}
 						{% if tax_details %}
 							<td class='text-right'>
 								{% if tax_details.tax_rate or not tax_details.tax_amount %}
-									({{ tax_details.tax_rate }}%) 
+									({{ tax_details.tax_rate }}%)
 								{% endif %}
-								{{ frappe.utils.fmt_money(tax_details.tax_amount, None, company_currency) }}
+								{{ frappe.utils.fmt_money(tax_details.tax_amount / conversion_rate, None, currency) }}
 							</td>
 						{% else %}
 							<td></td>