Merge branch 'leave-management' of https://github.com/Mangesh-Khairnar/erpnext into leave-management
diff --git a/erpnext/hr/doctype/leave_allocation/test_leave_allocation.py b/erpnext/hr/doctype/leave_allocation/test_leave_allocation.py
index 308f224..dfae329 100644
--- a/erpnext/hr/doctype/leave_allocation/test_leave_allocation.py
+++ b/erpnext/hr/doctype/leave_allocation/test_leave_allocation.py
@@ -158,7 +158,6 @@
 		"from_date": args.from_date or nowdate(),
 		"new_leaves_allocated": args.new_leaves_created or 15,
 		"carry_forward": args.carry_forward or 0,
-		"carry_forwarded_leaves": args.carry_forwarded_leaves or 0,
 		"to_date": args.to_date or add_months(nowdate(), 12)
 	})
 	return leave_allocation
diff --git a/erpnext/hr/doctype/leave_application/leave_application.py b/erpnext/hr/doctype/leave_application/leave_application.py
index 8e8e47e..f3bb9f7 100755
--- a/erpnext/hr/doctype/leave_application/leave_application.py
+++ b/erpnext/hr/doctype/leave_application/leave_application.py
@@ -354,7 +354,7 @@
 			self.to_date, self.from_date)
 
 		if expiry_date:
-			self.create_ledger_entry_for_intermediate_expiry(expiry_date, submit)
+			self.create_ledger_entry_for_intermediate_allocation_expiry(expiry_date, submit)
 		else:
 			args = dict(
 				leaves=self.total_leave_days * -1,
@@ -363,33 +363,32 @@
 			)
 			create_leave_ledger_entry(self, args, submit)
 
-	def create_ledger_entry_for_intermediate_expiry(self, expiry_date, submit):
-		''' splits leave application into two ledger entries to consider expiry '''
+	def create_ledger_entry_for_intermediate_allocation_expiry(self, expiry_date, submit):
+		''' splits leave application into two ledger entries to consider expiry of allocation '''
 		args = dict(
 			from_date=self.from_date,
 			to_date=self.to_date,
-			leaves=date_diff(expiry_date, self.from_date) * -1
+			leaves=(date_diff(expiry_date, self.from_date) + 1) * -1
 		)
 		create_leave_ledger_entry(self, args, submit)
+
 		start_date = add_days(expiry_date, 1)
 		args.update(dict(
 			from_date=start_date,
 			to_date=self.to_date,
-			leaves=date_diff(self.to_date, start_date) * -1
+			leaves=date_diff(self.to_date, expiry_date) * -1
 		))
 		create_leave_ledger_entry(self, args, submit)
 
 def get_allocation_expiry(employee, leave_type, to_date, from_date):
-	return frappe.db.sql("""
-		SELECT
-			to_date
-		FROM `tabLeave Ledger Entry`
-		WHERE
-			employee='%s'
-			AND leave_type='%s'
-			AND transaction_type='Leave Allocation'
-			AND (to_date BETWEEN %s AND %s)
-		""" %(employee, leave_type, from_date, to_date), as_dict=1)
+	expiry =  frappe.get_all("Leave Ledger Entry",
+		filters={
+			'employee': employee,
+			'leave_type': leave_type,
+			'transaction_type': 'Leave Allocation',
+			'to_date': ['between', (from_date, to_date)]
+		},fields=['to_date'])
+	return expiry[0]['to_date'] if expiry else None
 
 @frappe.whitelist()
 def get_number_of_leave_days(employee, leave_type, from_date, to_date, half_day = None, half_day_date = None):
@@ -452,10 +451,12 @@
 		if remaining_leaves > 0:
 			remaining_days = date_diff(end_date, date) + 1
 			remaining_leaves = min(remaining_days, remaining_leaves)
+
 		return remaining_leaves
 
 	if expiry:
 		remaining_leaves = _get_remaining_leaves(allocation.carry_forwarded_leaves, expiry)
+
 		return flt(allocation.new_leaves_allocated) + flt(remaining_leaves)
 	else:
 		return _get_remaining_leaves(allocation.total_leaves_allocated, allocation.to_date)
@@ -543,7 +544,7 @@
 			"total_leaves_allocated": d.total_leaves_allocated,
 			"carry_forward": d.carry_forward,
 			"carry_forwarded_leaves": d.carry_forwarded_leaves,
-			"new_leaves": d.new_leaves_allocated,
+			"new_leaves_allocated": d.new_leaves_allocated,
 			"leave_type": d.leave_type
 		}))
 	return allocated_leaves
diff --git a/erpnext/hr/doctype/leave_application/test_leave_application.py b/erpnext/hr/doctype/leave_application/test_leave_application.py
index 4dea413..f5f4fa5 100644
--- a/erpnext/hr/doctype/leave_application/test_leave_application.py
+++ b/erpnext/hr/doctype/leave_application/test_leave_application.py
@@ -7,7 +7,7 @@
 
 from erpnext.hr.doctype.leave_application.leave_application import LeaveDayBlockedError, OverlapError, NotAnOptionalHoliday, get_leave_balance_on
 from frappe.permissions import clear_user_permissions_for_doctype
-from frappe.utils import add_days, nowdate, now_datetime, getdate
+from frappe.utils import add_days, nowdate, now_datetime, getdate, add_months
 from erpnext.hr.doctype.leave_type.test_leave_type import create_leave_type
 from erpnext.hr.doctype.leave_allocation.test_leave_allocation import create_leave_allocation
 
@@ -287,7 +287,6 @@
 		# check leave balance is reduced
 		self.assertEqual(get_leave_balance_on(employee.name, leave_type, today), 9)
 
-
 	def test_leaves_allowed(self):
 		frappe.db.sql("delete from `tabLeave Allocation`")
 		frappe.db.sql("delete from `tabLeave Ledger Entry`")
@@ -404,6 +403,20 @@
 
 		self.assertRaises(frappe.ValidationError, leave_application.insert)
 
+	def test_leave_balance_near_allocaton_expiry(self):
+		frappe.db.sql("delete from `tabLeave Allocation`")
+		frappe.db.sql("delete from `tabLeave Ledger Entry`")
+		employee = get_employee()
+		leave_type = create_leave_type(
+			leave_type_name="_Test_CF_leave_expiry",
+			is_carry_forward=1,
+			carry_forward_leave_expiry=90)
+		leave_type.submit()
+
+		create_carry_forwarded_allocation(employee, leave_type)
+
+		self.assertEqual(get_leave_balance_on(employee.name, leave_type.name, nowdate(), add_days(nowdate(), 8)), 21)
+
 	def test_earned_leave(self):
 		leave_period = get_leave_period()
 		employee = get_employee()
@@ -492,6 +505,59 @@
 		leave_application.cancel()
 		self.assertFalse(frappe.db.exists("Leave Ledger Entry", {'transaction_name':leave_application.name}))
 
+	def test_ledger_entry_creation_on_intermediate_allocation_expiry(self):
+		frappe.db.sql("delete from `tabLeave Allocation`")
+		frappe.db.sql("delete from `tabLeave Ledger Entry`")
+		employee = get_employee()
+		leave_type = create_leave_type(
+			leave_type_name="_Test_CF_leave_expiry",
+			is_carry_forward=1,
+			carry_forward_leave_expiry=90)
+		leave_type.submit()
+
+		create_carry_forwarded_allocation(employee, leave_type)
+
+		leave_application = frappe.get_doc(dict(
+			doctype = 'Leave Application',
+			employee = employee.name,
+			leave_type = leave_type.name,
+			from_date = add_days(nowdate(), -3),
+			to_date = add_days(nowdate(), 7),
+			company = "_Test Company",
+			docstatus = 1,
+            status = "Approved"
+		))
+		leave_application.submit()
+
+		leave_ledger_entry = frappe.get_all('Leave Ledger Entry', '*', filters=dict(transaction_name=leave_application.name))
+
+		self.assertEquals(len(leave_ledger_entry), 2)
+		self.assertEquals(leave_ledger_entry[0].employee, leave_application.employee)
+		self.assertEquals(leave_ledger_entry[0].leave_type, leave_application.leave_type)
+		self.assertEquals(leave_ledger_entry[0].leaves, -9)
+		self.assertEquals(leave_ledger_entry[1].leaves, -2)
+
+def create_carry_forwarded_allocation(employee, leave_type):
+
+		# initial leave allocation
+		leave_allocation = create_leave_allocation(
+			leave_type="_Test_CF_leave_expiry",
+			employee=employee.name,
+			employee_name=employee.employee_name,
+			from_date=add_months(nowdate(), -24),
+			to_date=add_months(nowdate(), -12),
+			carry_forward=1)
+		leave_allocation.submit()
+
+		leave_allocation = create_leave_allocation(
+			leave_type="_Test_CF_leave_expiry",
+			employee=employee.name,
+			employee_name=employee.employee_name,
+			from_date=add_days(nowdate(), -85),
+			to_date=add_days(nowdate(), 100),
+			carry_forward=1)
+		leave_allocation.submit()
+
 def make_allocation_record(employee=None, leave_type=None):
 	frappe.db.sql("delete from `tabLeave Allocation`")
 
diff --git a/erpnext/hr/doctype/leave_encashment/test_leave_encashment.py b/erpnext/hr/doctype/leave_encashment/test_leave_encashment.py
index cfed780..7d4fb28 100644
--- a/erpnext/hr/doctype/leave_encashment/test_leave_encashment.py
+++ b/erpnext/hr/doctype/leave_encashment/test_leave_encashment.py
@@ -17,6 +17,7 @@
 	def setUp(self):
 		frappe.db.sql('''delete from `tabLeave Period`''')
 		frappe.db.sql('''delete from `tabLeave Allocation`''')
+		frappe.db.sql('''delete from `tabAdditional Salary`''')
 
 		# create the leave policy
 		leave_policy = create_leave_policy(
@@ -26,7 +27,9 @@
 
 		# create employee, salary structure and assignment
 		self.employee = make_employee("test_employee_encashment@example.com")
-		frappe.db.set_value("Employee", "test_employee_encashment@example.com", "leave_policy", leave_policy.name)
+
+		frappe.db.set_value("Employee", self.employee, "leave_policy", leave_policy.name)
+
 		salary_structure = make_salary_structure("Salary Structure for Encashment", "Monthly", self.employee,
 			other_details={"leave_encashment_amount_per_day": 50})
 
@@ -55,11 +58,11 @@
 	def test_creation_of_leave_ledger_entry_on_submit(self):
 		frappe.db.sql('''delete from `tabLeave Encashment`''')
 		leave_encashment = frappe.get_doc(dict(
-			doctype = 'Leave Encashment',
-			employee = self.employee,
-			leave_type = "_Test Leave Type Encashment",
-			leave_period = self.leave_period.name,
-			payroll_date = today()
+			doctype='Leave Encashment',
+			employee=self.employee,
+			leave_type="_Test Leave Type Encashment",
+			leave_period=self.leave_period.name,
+			payroll_date=today()
 		)).insert()
 
 		leave_encashment.submit()