merge
diff --git a/hr/doctype/leave_application/leave_application.py b/hr/doctype/leave_application/leave_application.py
index 06652ad..5170e26 100755
--- a/hr/doctype/leave_application/leave_application.py
+++ b/hr/doctype/leave_application/leave_application.py
@@ -18,9 +18,8 @@
 import webnotes
 from webnotes import _
 
-from webnotes.utils import cint, cstr, date_diff, flt, formatdate, getdate, get_url_to_form, get_fullname
+from webnotes.utils import cint, cstr, date_diff, flt, formatdate, getdate, get_url_to_form
 from webnotes import msgprint
-from webnotes.utils.email_lib import sendmail
 
 class LeaveDayBlockedError(Exception): pass
 	
@@ -33,7 +32,6 @@
 			self.previous_doc = None
 		
 	def validate(self):
-		# if self.doc.leave_approver == self.doc.owner:
 		self.validate_to_date()
 		self.validate_balance_leaves()
 		self.validate_leave_overlap()
@@ -41,8 +39,8 @@
 		self.validate_block_days()
 		
 	def on_update(self):
-		if (not self.previous_doc and self.doc.leave_approver) or (self.doc.status == "Open" \
-				and self.previous_doc.leave_approver != self.doc.leave_approver):
+		if (not self.previous_doc and self.doc.leave_approver) or (self.previous_doc and \
+				self.doc.status == "Open" and self.previous_doc.leave_approver != self.doc.leave_approver):
 			# notify leave approver about creation
 			self.notify_leave_approver()
 		elif self.previous_doc and \
@@ -105,9 +103,7 @@
 			raise Exception
 			
 	def validate_balance_leaves(self):
-		if self.doc.from_date and self.doc.to_date and not is_lwp(self.doc.leave_type):
-			self.doc.leave_balance = get_leave_balance(self.doc.employee,
-				self.doc.leave_type, self.doc.fiscal_year)["leave_balance"]
+		if self.doc.from_date and self.doc.to_date:
 			self.doc.total_leave_days = self.get_total_leave_days()["total_leave_days"]
 			
 			if self.doc.total_leave_days == 0:
@@ -115,9 +111,13 @@
 					coincide with holiday(s). You need not apply for leave."),
 					raise_exception=1)
 			
-			if self.doc.leave_balance - self.doc.total_leave_days < 0:
-				msgprint("There is not enough leave balance for Leave Type: %s" % \
-					(self.doc.leave_type,), raise_exception=1)
+			if not is_lwp(self.doc.leave_type):
+				self.doc.leave_balance = get_leave_balance(self.doc.employee,
+					self.doc.leave_type, self.doc.fiscal_year)["leave_balance"]
+			
+				if self.doc.leave_balance - self.doc.total_leave_days < 0:
+					msgprint("There is not enough leave balance for Leave Type: %s" % \
+						(self.doc.leave_type,), raise_exception=1)
 
 	def validate_leave_overlap(self):
 		for d in webnotes.conn.sql("""select name, leave_type, posting_date, 
@@ -165,7 +165,7 @@
 		
 		def _get_message(url=False):
 			name = self.doc.name
-			employee_name = get_fullname(employee.user_id)
+			employee_name = cstr(employee.employee_name)
 			if url:
 				name = get_url_to_form(self.doc.doctype, self.doc.name)
 				employee_name = get_url_to_form("Employee", self.doc.employee, label=employee_name)
@@ -223,9 +223,22 @@
 	events = []
 	employee = webnotes.conn.get_default("employee", webnotes.session.user)
 	company = webnotes.conn.get_default("company", webnotes.session.user)
-
-	add_department_leaves(events, start, end, employee, company)
+	
+	from webnotes.widgets.reportview import build_match_conditions
+	match_conditions = build_match_conditions({"doctype": "Leave Application"})
+	
+	# show department leaves for employee
+	show_department_leaves = match_conditions and \
+		len(match_conditions.split("or"))==1 and "employee" in match_conditions
+	
+	if show_department_leaves:
+		add_department_leaves(events, start, end, employee, company)
+	else:
+		add_leaves(events, start, end, employee, company, match_conditions)
+		
 	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):
@@ -235,27 +248,33 @@
 		return
 	
 	# department leaves
-	department_employees = webnotes.conn.sql_list("select name from tabEmployee where department=%s", 
-		department)
+	department_employees = webnotes.conn.sql_list("""select name from tabEmployee where department=%s
+		and company=%s""", (department, company))
 	
-	for d in webnotes.conn.sql("""select name, from_date, to_date, employee_name, half_day, 
-		status, employee
+	match_conditions = "employee in (\"%s\")" % '", "'.join(department_employees)
+	add_leaves(events, start, end, employee, company, match_conditions=match_conditions)
+			
+def add_leaves(events, start, end, employee, company, match_conditions=None):
+	query = """select name, from_date, to_date, employee_name, half_day, 
+		status, employee, docstatus
 		from `tabLeave Application` where
 		(from_date between %s and %s or to_date between %s and %s)
 		and docstatus < 2
-		and status!="Rejected"
-		and employee in ('%s')""" % ("%s", "%s", "%s", "%s", "', '".join(department_employees)), 
-			(start, end, start, end), as_dict=True):
-			events.append({
-				"name": d.name,
-				"doctype": "Leave Application",
-				"from_date": d.from_date,
-				"to_date": d.to_date,
-				"status": d.status,
-				"title": _("Leave by") + " " +  d.employee_name + \
-					(d.half_day and _(" (Half Day)") or "")
-			})
+		and status!="Rejected" """
+	if match_conditions:
+		query += " and " + match_conditions
 	
+	for d in webnotes.conn.sql(query, (start, end, start, end), as_dict=True):
+		events.append({
+			"name": d.name,
+			"doctype": "Leave Application",
+			"from_date": d.from_date,
+			"to_date": d.to_date,
+			"status": d.status,
+			"title": _("Leave by") + " " +  cstr(d.employee_name) + \
+				(d.half_day and _(" (Half Day)") or ""),
+			"docstatus": d.docstatus
+		})
 
 def add_block_dates(events, start, end, employee, company):
 	# block days
@@ -272,4 +291,18 @@
 			"name": "_" + str(cnt),
 		})
 		cnt+=1
+
+def add_holidays(events, start, end, employee, company):
+	applicable_holiday_list = webnotes.conn.get_value("Employee", employee, "holiday_list")
+	if not applicable_holiday_list:
+		return
 	
+	for holiday in webnotes.conn.sql("""select name, holiday_date, description
+		from `tabHoliday` where parent=%s and holiday_date between %s and %s""", 
+		(applicable_holiday_list, start, end), as_dict=True):
+			events.append({
+				"doctype": "Holiday",
+				"from_date": holiday.holiday_date,
+				"title": _("Holiday") + ": " + cstr(holiday.description),
+				"name": holiday.name
+			})
diff --git a/hr/doctype/leave_application/leave_application.txt b/hr/doctype/leave_application/leave_application.txt
index f51a91a..1e19128 100644
--- a/hr/doctype/leave_application/leave_application.txt
+++ b/hr/doctype/leave_application/leave_application.txt
@@ -1,12 +1,13 @@
 [
  {
-  "creation": "2013-02-08 13:17:08", 
+  "creation": "2013-02-18 17:08:32", 
   "docstatus": 0, 
-  "modified": "2013-02-13 12:32:27", 
+  "modified": "2013-02-18 17:20:50", 
   "modified_by": "Administrator", 
   "owner": "Administrator"
  }, 
  {
+  "allow_import": 1, 
   "autoname": "LAP/.#####", 
   "description": "Apply / Approve Leaves", 
   "doctype": "DocType", 
@@ -44,7 +45,7 @@
   "label": "Status", 
   "no_copy": 1, 
   "options": "Open\nApproved\nRejected", 
-  "permlevel": 2
+  "permlevel": 1
  }, 
  {
   "description": "Leave can be approved by users with Role, \"Leave Approver\"", 
@@ -218,15 +219,6 @@
   "write": 1
  }, 
  {
-  "amend": 0, 
-  "cancel": 0, 
-  "create": 0, 
-  "doctype": "DocPerm", 
-  "permlevel": 1, 
-  "role": "All", 
-  "submit": 0
- }, 
- {
   "amend": 1, 
   "cancel": 1, 
   "create": 1, 
@@ -254,8 +246,17 @@
   "cancel": 0, 
   "create": 0, 
   "doctype": "DocPerm", 
-  "permlevel": 2, 
-  "report": 1, 
+  "permlevel": 1, 
+  "role": "All", 
+  "submit": 0
+ }, 
+ {
+  "amend": 0, 
+  "cancel": 0, 
+  "create": 0, 
+  "doctype": "DocPerm", 
+  "permlevel": 1, 
+  "report": 0, 
   "role": "HR User", 
   "submit": 0, 
   "write": 1
@@ -265,15 +266,10 @@
   "cancel": 0, 
   "create": 0, 
   "doctype": "DocPerm", 
-  "permlevel": 2, 
-  "report": 1, 
+  "permlevel": 1, 
+  "report": 0, 
   "role": "Leave Approver", 
   "submit": 0, 
   "write": 1
- }, 
- {
-  "doctype": "DocPerm", 
-  "permlevel": 2, 
-  "role": "Employee"
  }
 ]
\ No newline at end of file
diff --git a/patches/february_2013/fix_outstanding.py b/patches/february_2013/fix_outstanding.py
index 07ea51a..22a6ee1 100644
--- a/patches/february_2013/fix_outstanding.py
+++ b/patches/february_2013/fix_outstanding.py
@@ -1,15 +1,24 @@
 def execute():
 	import webnotes
 	from webnotes.utils import flt
-	for dt in ["Sales Invoice", "Purchase Invoice"]:
-		records = webnotes.conn.sql("""select name, outstanding_amount from `tab%s` 
-			where docstatus = 1""" % dt)
-		for r in records:
-			outstanding = webnotes.conn.sql("""
-				select sum(ifnull(debit, 0)) - sum(ifnull(credit, 0)) from `tabGL Entry`
-				where against_voucher = %s and against_voucher_type = %s 
-				and ifnull(is_cancelled, 'No') = 'No'""", (r[0], dt))
-			if flt(r[1]) != abs(flt(outstanding[0][0])):
-				# print r, outstanding
-				webnotes.conn.sql("update `tab%s` set outstanding_amount = %s where name = %s" %
-					(dt, '%s', '%s'), (abs(flt(outstanding[0][0])), r[0]))
\ No newline at end of file
+	records = webnotes.conn.sql("""
+		select against_voucher_type, against_voucher, 
+			sum(ifnull(debit, 0)) - sum(ifnull(credit, 0)) as outstanding from `tabGL Entry`
+		where ifnull(is_cancelled, 'No') = 'No' 
+		and against_voucher_type in ("Sales Invoice", "Purchase Invoice")
+		and ifnull(against_voucher, '') != ''
+		group by against_voucher_type, against_voucher""", as_dict=1)
+	for r in records:
+		outstanding = webnotes.conn.sql("""select name, outstanding_amount from `tab%s` 
+			where name = %s and docstatus = 1""" % 
+			(r["against_voucher_type"], '%s'), (r["against_voucher"]))
+			
+		if outstanding and abs(flt(r["outstanding"])) != flt(outstanding[0][1]):
+			if ((r["against_voucher_type"]=='Sales Invoice' and flt(r["outstanding"]) >= 0) \
+				or (r["against_voucher_type"]=="Purchase Invoice" and flt(["outstanding"]) <= 0)):
+				webnotes.conn.set_value(r["against_voucher_type"], r["against_voucher"], 
+					"outstanding_amount", abs(flt(r["outstanding"])))
+			else:
+				print r["against_voucher_type"], r["against_voucher"], \
+					outstanding[0][1], abs(flt(r["outstanding"]))
+		
\ No newline at end of file
diff --git a/patches/february_2013/gle_floating_point_issue_revisited.py b/patches/february_2013/gle_floating_point_issue_revisited.py
index 3fc57bd..e407d50 100644
--- a/patches/february_2013/gle_floating_point_issue_revisited.py
+++ b/patches/february_2013/gle_floating_point_issue_revisited.py
@@ -13,7 +13,7 @@
 			diff = round((flt(r.grand_total) - flt(gle[0]['debit'])), 2)
 		
 			if abs(diff) == 0.01:
-				# print r.name, r.grand_total, gle[0]['debit']
+				# print r.name, r.grand_total, gle[0]['debit'], diff
 				webnotes.conn.sql("""update `tabGL Entry` set debit = debit + %s 
 					where name = %s""", (diff, gle[0]['name']))
 				
diff --git a/patches/february_2013/p05_leave_application.py b/patches/february_2013/p05_leave_application.py
new file mode 100644
index 0000000..88d166e
--- /dev/null
+++ b/patches/february_2013/p05_leave_application.py
@@ -0,0 +1,9 @@
+import webnotes
+
+def execute():
+	webnotes.reload_doc("hr", "doctype", "leave_application")
+	
+	if not webnotes.get_doctype("Leave Application").get({"doctype": "DocField", 
+			"parent": "Leave Application", "permlevel": 2}):
+		webnotes.conn.sql("""update `tabDocPerm` set permlevel=1 
+			where parent="Leave Application" and permlevel=2""")
\ No newline at end of file
diff --git a/patches/patch_list.py b/patches/patch_list.py
index 78b3a50..d330de5 100644
--- a/patches/patch_list.py
+++ b/patches/patch_list.py
@@ -169,11 +169,13 @@
 	"patches.february_2013.update_company_in_leave_application",
 	"execute:webnotes.conn.sql_ddl('alter table tabSeries change `name` `name` varchar(100)')",
 	"execute:webnotes.conn.sql('update tabUserRole set parentfield=\"user_roles\" where parentfield=\"userroles\"')",
-	"patches.february_2013.fix_outstanding",
 	"patches.february_2013.p01_event",
 	"execute:webnotes.delete_doc('Page', 'Calendar')",
 	"patches.february_2013.p02_email_digest",
 	"patches.february_2013.p03_material_request",
 	"patches.february_2013.p04_remove_old_doctypes",
 	"execute:webnotes.delete_doc('DocType', 'Plot Control')"
+	"patches.february_2013.p05_leave_application",
+	"patches.february_2013.gle_floating_point_issue_revisited",
+	"patches.february_2013.fix_outstanding",
 ]
\ No newline at end of file