Merge pull request #3591 from rmehta/salary-manager-fix

[fixes] salary manager #3554
diff --git a/erpnext/__version__.py b/erpnext/__version__.py
index 1d65332..c8b2f49 100644
--- a/erpnext/__version__.py
+++ b/erpnext/__version__.py
@@ -1,2 +1,2 @@
 from __future__ import unicode_literals
-__version__ = '5.1.2'
+__version__ = '5.1.3'
diff --git a/erpnext/accounts/doctype/pos_profile/pos_profile.json b/erpnext/accounts/doctype/pos_profile/pos_profile.json
index ad224f1..0c5a4bb 100644
--- a/erpnext/accounts/doctype/pos_profile/pos_profile.json
+++ b/erpnext/accounts/doctype/pos_profile/pos_profile.json
@@ -78,6 +78,51 @@
    "reqd": 1
   }, 
   {
+   "fieldname": "warehouse", 
+   "fieldtype": "Link", 
+   "label": "Warehouse", 
+   "oldfieldname": "warehouse", 
+   "oldfieldtype": "Link", 
+   "options": "Warehouse", 
+   "permlevel": 0, 
+   "read_only": 0, 
+   "reqd": 0
+  }, 
+  {
+   "allow_on_submit": 1, 
+   "fieldname": "letter_head", 
+   "fieldtype": "Link", 
+   "label": "Letter Head", 
+   "oldfieldname": "letter_head", 
+   "oldfieldtype": "Select", 
+   "options": "Letter Head", 
+   "permlevel": 0, 
+   "print_hide": 1, 
+   "read_only": 0
+  }, 
+  {
+   "fieldname": "tc_name", 
+   "fieldtype": "Link", 
+   "label": "Terms and Conditions", 
+   "oldfieldname": "tc_name", 
+   "oldfieldtype": "Link", 
+   "options": "Terms and Conditions", 
+   "permlevel": 0, 
+   "read_only": 0
+  }, 
+  {
+   "allow_on_submit": 1, 
+   "fieldname": "select_print_heading", 
+   "fieldtype": "Link", 
+   "in_filter": 0, 
+   "label": "Print Heading", 
+   "oldfieldname": "select_print_heading", 
+   "oldfieldtype": "Select", 
+   "options": "Print Heading", 
+   "permlevel": 0, 
+   "read_only": 0
+  }, 
+  {
    "fieldname": "column_break0", 
    "fieldtype": "Column Break", 
    "oldfieldtype": "Column Break", 
@@ -106,6 +151,14 @@
    "reqd": 0
   }, 
   {
+   "fieldname": "mode_of_payment", 
+   "fieldtype": "Link", 
+   "label": "Mode of Payment", 
+   "options": "Mode of Payment", 
+   "permlevel": 0, 
+   "precision": ""
+  }, 
+  {
    "fieldname": "cash_bank_account", 
    "fieldtype": "Link", 
    "label": "Cash/Bank Account", 
@@ -140,17 +193,6 @@
    "reqd": 0
   }, 
   {
-   "fieldname": "warehouse", 
-   "fieldtype": "Link", 
-   "label": "Warehouse", 
-   "oldfieldname": "warehouse", 
-   "oldfieldtype": "Link", 
-   "options": "Warehouse", 
-   "permlevel": 0, 
-   "read_only": 0, 
-   "reqd": 0
-  }, 
-  {
    "fieldname": "cost_center", 
    "fieldtype": "Link", 
    "label": "Cost Center", 
@@ -162,16 +204,6 @@
    "reqd": 1
   }, 
   {
-   "fieldname": "taxes_and_charges", 
-   "fieldtype": "Link", 
-   "label": "Taxes and Charges", 
-   "oldfieldname": "charge", 
-   "oldfieldtype": "Link", 
-   "options": "Sales Taxes and Charges Template", 
-   "permlevel": 0, 
-   "read_only": 0
-  }, 
-  {
    "fieldname": "write_off_account", 
    "fieldtype": "Link", 
    "label": "Write Off Account", 
@@ -190,43 +222,19 @@
    "reqd": 1
   }, 
   {
-   "allow_on_submit": 1, 
-   "fieldname": "letter_head", 
+   "fieldname": "taxes_and_charges", 
    "fieldtype": "Link", 
-   "label": "Letter Head", 
-   "oldfieldname": "letter_head", 
-   "oldfieldtype": "Select", 
-   "options": "Letter Head", 
-   "permlevel": 0, 
-   "print_hide": 1, 
-   "read_only": 0
-  }, 
-  {
-   "fieldname": "tc_name", 
-   "fieldtype": "Link", 
-   "label": "Terms and Conditions", 
-   "oldfieldname": "tc_name", 
+   "label": "Taxes and Charges", 
+   "oldfieldname": "charge", 
    "oldfieldtype": "Link", 
-   "options": "Terms and Conditions", 
-   "permlevel": 0, 
-   "read_only": 0
-  }, 
-  {
-   "allow_on_submit": 1, 
-   "fieldname": "select_print_heading", 
-   "fieldtype": "Link", 
-   "in_filter": 0, 
-   "label": "Print Heading", 
-   "oldfieldname": "select_print_heading", 
-   "oldfieldtype": "Select", 
-   "options": "Print Heading", 
+   "options": "Sales Taxes and Charges Template", 
    "permlevel": 0, 
    "read_only": 0
   }
  ], 
  "icon": "icon-cog", 
  "idx": 1, 
- "modified": "2015-05-20 05:38:44.482696", 
+ "modified": "2015-07-07 08:56:04.381471", 
  "modified_by": "Administrator", 
  "module": "Accounts", 
  "name": "POS Profile", 
diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.json b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.json
index dcbc605..69b0708 100755
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.json
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.json
@@ -38,7 +38,7 @@
    "fieldtype": "Data", 
    "hidden": 0, 
    "in_list_view": 0, 
-   "label": "Name", 
+   "label": "Supplier Name", 
    "oldfieldname": "supplier_name", 
    "oldfieldtype": "Data", 
    "permlevel": 0, 
@@ -940,7 +940,7 @@
  "icon": "icon-file-text", 
  "idx": 1, 
  "is_submittable": 1, 
- "modified": "2015-06-22 07:30:06.743438", 
+ "modified": "2015-07-03 03:26:32.934540", 
  "modified_by": "Administrator", 
  "module": "Accounts", 
  "name": "Purchase Invoice", 
diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
index 50a79ec..af144cb 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
@@ -124,20 +124,11 @@
 			}
 		})
 
-		if cint(frappe.defaults.get_global_default('maintain_same_rate')):
-			super(PurchaseInvoice, self).validate_with_previous_doc({
-				"Purchase Order Item": {
-					"ref_dn_field": "po_detail",
-					"compare_fields": [["rate", "="]],
-					"is_child_table": True,
-					"allow_duplicate_prev_row_id": True
-				},
-				"Purchase Receipt Item": {
-					"ref_dn_field": "pr_detail",
-					"compare_fields": [["rate", "="]],
-					"is_child_table": True
-				}
-			})
+		if cint(frappe.db.get_single_value('Buying Settings', 'maintain_same_rate')):
+			self.validate_rate_with_reference_doc([
+				["Purchase Order", "purchase_order", "po_detail"], 
+				["Purchase Receipt", "purchase_receipt", "pr_detail"]
+			])
 
 	def set_against_expense_account(self):
 		auto_accounting_for_stock = cint(frappe.defaults.get_global_default("auto_accounting_for_stock"))
diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.json b/erpnext/accounts/doctype/sales_invoice/sales_invoice.json
index 045678d..70d5f4a 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.json
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.json
@@ -47,7 +47,7 @@
    "fieldtype": "Data", 
    "hidden": 0, 
    "in_list_view": 0, 
-   "label": "Name", 
+   "label": "Customer Name", 
    "oldfieldname": "customer_name", 
    "oldfieldtype": "Data", 
    "permlevel": 0, 
@@ -1253,7 +1253,7 @@
  "icon": "icon-file-text", 
  "idx": 1, 
  "is_submittable": 1, 
- "modified": "2015-06-22 06:39:22.072544", 
+ "modified": "2015-07-03 03:25:40.519956", 
  "modified_by": "Administrator", 
  "module": "Accounts", 
  "name": "Sales Invoice", 
diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
index 604370b..f3acc74 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
@@ -169,6 +169,7 @@
 		if pos:
 			if not for_validate and not self.customer:
 				self.customer = pos.customer
+				self.mode_of_payment = pos.mode_of_payment
 				# self.set_customer_defaults()
 
 			for fieldname in ('territory', 'naming_series', 'currency', 'taxes_and_charges', 'letter_head', 'tc_name',
@@ -263,20 +264,11 @@
 			},
 		})
 
-		if cint(frappe.defaults.get_global_default('maintain_same_sales_rate')):
-			super(SalesInvoice, self).validate_with_previous_doc({
-				"Sales Order Item": {
-					"ref_dn_field": "so_detail",
-					"compare_fields": [["rate", "="]],
-					"is_child_table": True,
-					"allow_duplicate_prev_row_id": True
-				},
-				"Delivery Note Item": {
-					"ref_dn_field": "dn_detail",
-					"compare_fields": [["rate", "="]],
-					"is_child_table": True
-				}
-			})
+		if cint(frappe.db.get_single_value('Selling Settings', 'maintain_same_sales_rate')):
+			self.validate_rate_with_reference_doc([
+				["Sales Order", "sales_order", "so_detail"], 
+				["Delivery Note", "delivery_note", "dn_detail"]
+			])
 
 	def set_against_income_account(self):
 		"""Set against account for debit to account"""
diff --git a/erpnext/buying/doctype/purchase_order/purchase_order.json b/erpnext/buying/doctype/purchase_order/purchase_order.json
index f65ba40..8ca8ed0 100644
--- a/erpnext/buying/doctype/purchase_order/purchase_order.json
+++ b/erpnext/buying/doctype/purchase_order/purchase_order.json
@@ -53,7 +53,7 @@
    "fieldtype": "Data", 
    "hidden": 0, 
    "in_list_view": 0, 
-   "label": "Name", 
+   "label": "Supplier Name", 
    "permlevel": 0, 
    "read_only": 1
   }, 
@@ -882,7 +882,7 @@
  "icon": "icon-file-text", 
  "idx": 1, 
  "is_submittable": 1, 
- "modified": "2015-06-22 07:30:36.259753", 
+ "modified": "2015-07-03 03:26:43.080551", 
  "modified_by": "Administrator", 
  "module": "Buying", 
  "name": "Purchase Order", 
diff --git a/erpnext/change_log/v5/v5_1_3.md b/erpnext/change_log/v5/v5_1_3.md
new file mode 100644
index 0000000..9825a10
--- /dev/null
+++ b/erpnext/change_log/v5/v5_1_3.md
@@ -0,0 +1,3 @@
+- Hide zero balance rows in batch-wise balance history report
+- Autocomplete issue fixed in Manage Variants
+- Remove user permission (Employee role) if user id is unset from Employee record
\ No newline at end of file
diff --git a/erpnext/config/accounts.py b/erpnext/config/accounts.py
index 64508b8..f32aeed 100644
--- a/erpnext/config/accounts.py
+++ b/erpnext/config/accounts.py
@@ -75,6 +75,11 @@
 			"items": [
 				{
 					"type": "doctype",
+					"name": "Company",
+					"description": _("Company (not Customer or Supplier) master.")
+				},
+				{
+					"type": "doctype",
 					"name": "Fiscal Year",
 					"description": _("Financial / accounting year.")
 				},
diff --git a/erpnext/config/setup.py b/erpnext/config/setup.py
index 961e4f7..a660942 100644
--- a/erpnext/config/setup.py
+++ b/erpnext/config/setup.py
@@ -110,43 +110,7 @@
 					"description": _("Setup SMS gateway settings")
 				},
 			]
-		},
-		{
-			"label": _("Masters"),
-			"icon": "icon-star",
-			"items": [
-				{
-					"type": "doctype",
-					"name": "Company",
-					"description": _("Company (not Customer or Supplier) master.")
-				},
-				{
-					"type": "doctype",
-					"name": "Item",
-					"description": _("Item master.")
-				},
-				{
-					"type": "doctype",
-					"name": "Customer",
-					"description": _("Customer master.")
-				},
-				{
-					"type": "doctype",
-					"name": "Supplier",
-					"description": _("Supplier master.")
-				},
-				{
-					"type": "doctype",
-					"name": "Contact",
-					"description": _("Contact master.")
-				},
-				{
-					"type": "doctype",
-					"name": "Address",
-					"description": _("Address master.")
-				},
-			]
-		},
+		}
 	]
 
 	for module, label, icon in (
diff --git a/erpnext/crm/doctype/lead/lead.json b/erpnext/crm/doctype/lead/lead.json
index e095426..b2aa31a 100644
--- a/erpnext/crm/doctype/lead/lead.json
+++ b/erpnext/crm/doctype/lead/lead.json
@@ -29,7 +29,7 @@
    "fieldtype": "Data", 
    "in_filter": 1, 
    "in_list_view": 0, 
-   "label": "Contact Name", 
+   "label": "Person Name", 
    "oldfieldname": "lead_name", 
    "oldfieldtype": "Data", 
    "permlevel": 0, 
@@ -344,7 +344,7 @@
  ], 
  "icon": "icon-user", 
  "idx": 1, 
- "modified": "2015-04-02 15:13:02.621854", 
+ "modified": "2015-07-03 03:26:18.579905", 
  "modified_by": "Administrator", 
  "module": "CRM", 
  "name": "Lead", 
diff --git a/erpnext/crm/doctype/opportunity/opportunity.py b/erpnext/crm/doctype/opportunity/opportunity.py
index 0225398..78729a3 100644
--- a/erpnext/crm/doctype/opportunity/opportunity.py
+++ b/erpnext/crm/doctype/opportunity/opportunity.py
@@ -79,7 +79,8 @@
 		if self.customer:
 			self.customer_name = frappe.db.get_value("Customer", self.customer, "customer_name")
 		elif self.lead:
-			self.customer_name = frappe.db.get_value("Lead", self.lead, "lead_name")
+			lead_name, company_name = frappe.db.get_value("Lead", self.lead, ["lead_name", "company_name"])
+			self.customer_name = company_name or lead_name
 
 	def get_cust_address(self,name):
 		details = frappe.db.sql("""select customer_name, address, territory, customer_group
diff --git a/erpnext/hooks.py b/erpnext/hooks.py
index b2ae87b..15d663c 100644
--- a/erpnext/hooks.py
+++ b/erpnext/hooks.py
@@ -5,7 +5,7 @@
 app_description = "Open Source Enterprise Resource Planning for Small and Midsized Organizations"
 app_icon = "icon-th"
 app_color = "#e74c3c"
-app_version = "5.1.2"
+app_version = "5.1.3"
 
 error_report_email = "support@erpnext.com"
 
@@ -25,8 +25,13 @@
 # website
 update_website_context = "erpnext.shopping_cart.utils.update_website_context"
 my_account_context = "erpnext.shopping_cart.utils.update_my_account_context"
+
 email_append_to = ["Job Applicant", "Opportunity", "Issue"]
 
+calendars = ["Task", "Production Order", "Time Log", "Leave Application"]
+
+website_generators = ["Item Group", "Item", "Sales Partner"]
+
 website_context = {
 	"favicon": 	"/assets/erpnext/images/favicon.png",
 	"splash_image": "/assets/erpnext/images/splash.png"
@@ -52,14 +57,10 @@
 
 before_tests = "erpnext.setup.utils.before_tests"
 
-website_generators = ["Item Group", "Item", "Sales Partner"]
-
 standard_queries = {
 	"Customer": "erpnext.selling.doctype.customer.customer.get_customer_list"
 }
 
-communication_covert_to = ["Lead", "Issue", "Job Application"]
-
 doc_events = {
 	"Stock Entry": {
 		"on_submit": "erpnext.stock.doctype.material_request.material_request.update_completed_and_requested_qty",
@@ -106,4 +107,3 @@
 	("page", "setup-wizard"): "frappe.geo.country_info.get_translated_dict",
 	("doctype", "Global Defaults"): "frappe.geo.country_info.get_translated_dict"
 }
-
diff --git a/erpnext/hr/doctype/employee/employee.py b/erpnext/hr/doctype/employee/employee.py
index cb0ce11..a2bb10c 100644
--- a/erpnext/hr/doctype/employee/employee.py
+++ b/erpnext/hr/doctype/employee/employee.py
@@ -45,6 +45,10 @@
 		if self.user_id:
 			self.validate_for_enabled_user_id()
 			self.validate_duplicate_user_id()
+		else:
+			existing_user_id = frappe.db.get_value("Employee", self.name, "user_id")
+			if existing_user_id:
+				frappe.permissions.remove_user_permission("Employee", self.name, existing_user_id)
 
 	def on_update(self):
 		if self.user_id:
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 e012d78..f53acca 100644
--- a/erpnext/hr/report/monthly_attendance_sheet/monthly_attendance_sheet.py
+++ b/erpnext/hr/report/monthly_attendance_sheet/monthly_attendance_sheet.py
@@ -75,8 +75,20 @@
 	filters["month"] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov",
 		"Dec"].index(filters["month"]) + 1
 
+	from frappe.model.document import Document
+	fiscal_years = frappe.get_doc("Fiscal Year",filters["fiscal_year"])
+	import datetime
+	year_start = fiscal_years.year_start_date.strftime("%Y")
+	year_end = fiscal_years.year_end_date.strftime("%Y")
+	dt_test = datetime.datetime.strptime(year_end + "-" + str(100+int(filters["month"]))[2:3] + "-01", "%Y-%m-%d")
+	date_test = datetime.date(dt_test.year, dt_test.month, dt_test.day)
+	if date_test > fiscal_years.year_end_date:
+		year_target = year_start
+	else:
+		year_target = year_end
+
 	from calendar import monthrange
-	filters["total_days_in_month"] = monthrange(cint(filters["fiscal_year"].split("-")[-1]),
+	filters["total_days_in_month"] = monthrange(cint(year_target),
 		filters["month"])[1]
 
 	conditions = " and month(att_date) = %(month)s and fiscal_year = %(fiscal_year)s"
diff --git a/erpnext/patches/v5_0/item_variants.py b/erpnext/patches/v5_0/item_variants.py
index 62e9ac9..66300be 100644
--- a/erpnext/patches/v5_0/item_variants.py
+++ b/erpnext/patches/v5_0/item_variants.py
@@ -11,6 +11,9 @@
 		manage_variant.attributes = frappe.db.sql("select item_attribute as attribute, item_attribute_value as attribute_value \
 			from `tabItem Variant` where parent = %s", d.name, as_dict=1)
 		if manage_variant.attributes:
-			manage_variant.generate_combinations()
-			manage_variant.create_variants()
+			if not frappe.get_list("Item", filters={"variant_of": d.name}, limit_page_length=1):
+				frappe.db.sql("delete from `tabItem Variant` where parent=%s", d.name)
+			else:			
+				manage_variant.generate_combinations()
+				manage_variant.create_variants()
 	frappe.delete_doc("DocType", "Item Variant")
\ No newline at end of file
diff --git a/erpnext/public/js/pos/pos.js b/erpnext/public/js/pos/pos.js
index 164e883..70f3023 100644
--- a/erpnext/public/js/pos/pos.js
+++ b/erpnext/public/js/pos/pos.js
@@ -401,7 +401,8 @@
 
 			this.with_modes_of_payment(function() {
 				// prefer cash payment!
-				var default_mode = me.modes_of_payment.indexOf(__("Cash"))!==-1 ? __("Cash") : undefined;
+				var default_mode = me.frm.doc.mode_of_payment ? me.frm.doc.mode_of_payment : 
+					me.modes_of_payment.indexOf(__("Cash"))!==-1 ? __("Cash") : undefined;
 
 				// show payment wizard
 				var dialog = new frappe.ui.Dialog({
diff --git a/erpnext/selling/doctype/quotation/quotation_list.js b/erpnext/selling/doctype/quotation/quotation_list.js
index add7aef..204ace1 100644
--- a/erpnext/selling/doctype/quotation/quotation_list.js
+++ b/erpnext/selling/doctype/quotation/quotation_list.js
@@ -2,7 +2,9 @@
 	add_fields: ["customer_name", "base_grand_total", "status",
 		"company", "currency"],
 	get_indicator: function(doc) {
-		if(doc.status==="Ordered") {
+		if(doc.status==="Submitted") {
+			return [__("Submitted"), "blue", "status,=,Submitted"];
+		} else if(doc.status==="Ordered") {
 			return [__("Ordered"), "green", "status,=,Ordered"];
 		} else if(doc.status==="Lost") {
 			return [__("Lost"), "darkgrey", "status,=,Lost"];
diff --git a/erpnext/selling/doctype/sales_order/sales_order.json b/erpnext/selling/doctype/sales_order/sales_order.json
index 59f54fb..28f98e4 100644
--- a/erpnext/selling/doctype/sales_order/sales_order.json
+++ b/erpnext/selling/doctype/sales_order/sales_order.json
@@ -52,7 +52,7 @@
    "fieldname": "customer_name", 
    "fieldtype": "Data", 
    "hidden": 0, 
-   "label": "Name", 
+   "label": "Customer Name", 
    "permlevel": 0, 
    "read_only": 1
   }, 
@@ -1089,7 +1089,7 @@
  "idx": 1, 
  "is_submittable": 1, 
  "issingle": 0, 
- "modified": "2015-06-22 07:29:24.379272", 
+ "modified": "2015-07-03 03:25:20.180721", 
  "modified_by": "Administrator", 
  "module": "Selling", 
  "name": "Sales Order", 
diff --git a/erpnext/stock/doctype/delivery_note/delivery_note.py b/erpnext/stock/doctype/delivery_note/delivery_note.py
index f52f7e5..90a8a6c 100644
--- a/erpnext/stock/doctype/delivery_note/delivery_note.py
+++ b/erpnext/stock/doctype/delivery_note/delivery_note.py
@@ -108,11 +108,9 @@
 		if not self.installation_status: self.installation_status = 'Not Installed'
 
 	def validate_with_previous_doc(self):
-		items = self.get("items")
-
 		for fn in (("Sales Order", "against_sales_order", "so_detail"), 
 				("Sales Invoice", "against_sales_invoice", "si_detail")):
-			if filter(None, [getattr(d, fn[1], None) for d in items]):
+			if filter(None, [getattr(d, fn[1], None) for d in self.get("items")]):
 				super(DeliveryNote, self).validate_with_previous_doc({
 					fn[0]: {
 						"ref_dn_field": fn[1],
@@ -120,15 +118,10 @@
 							["currency", "="]],
 					},
 				})
-
-				if cint(frappe.defaults.get_global_default('maintain_same_sales_rate')):
-					super(DeliveryNote, self).validate_with_previous_doc({
-						fn[0] + " Item": {
-							"ref_dn_field": fn[2],
-							"compare_fields": [["rate", "="]],
-							"is_child_table": True
-						}
-					})
+				
+		if cint(frappe.db.get_single_value('Selling Settings', 'maintain_same_sales_rate')):
+			self.validate_rate_with_reference_doc([["Sales Order", "sales_order", "so_detail"], 
+				["Sales Invoice", "sales_invoice", "si_detail"]])
 
 	def validate_proj_cust(self):
 		"""check for does customer belong to same project as entered.."""
diff --git a/erpnext/stock/doctype/item_attribute/item_attribute.py b/erpnext/stock/doctype/item_attribute/item_attribute.py
index d7c33a5..171e118 100644
--- a/erpnext/stock/doctype/item_attribute/item_attribute.py
+++ b/erpnext/stock/doctype/item_attribute/item_attribute.py
@@ -8,8 +8,14 @@
 
 class ItemAttribute(Document):
 	def validate(self):
+		self.validate_duplication()
+		self.validate_attribute_values()
+
+	
+	def validate_duplication(self):
 		values, abbrs = [], []
 		for d in self.item_attribute_values:
+			d.abbr = d.abbr.upper()
 			if d.attribute_value in values:
 				frappe.throw(_("{0} must appear only once").format(d.attribute_value))
 			values.append(d.attribute_value)
@@ -17,3 +23,14 @@
 			if d.abbr in abbrs:
 				frappe.throw(_("{0} must appear only once").format(d.abbr))
 			abbrs.append(d.abbr)
+			
+	def validate_attribute_values(self):
+		attribute_values = []
+		for d in self.item_attribute_values:
+			attribute_values.append(d.attribute_value)
+		
+		variant_attributes = frappe.db.sql("select DISTINCT attribute_value from `tabVariant Attribute` where attribute=%s", self.name)
+		if variant_attributes:
+			for d in variant_attributes:
+				if d[0] not in attribute_values:
+					frappe.throw(_("Attribute Value {0} cannot be removed from {1} as Item Variants exist with this Attribute.").format(d[0], self.name))
diff --git a/erpnext/stock/doctype/manage_variants/manage_variants.js b/erpnext/stock/doctype/manage_variants/manage_variants.js
index ba5c46e..e8b7ade 100644
--- a/erpnext/stock/doctype/manage_variants/manage_variants.js
+++ b/erpnext/stock/doctype/manage_variants/manage_variants.js
@@ -3,7 +3,7 @@
 
 frappe.ui.form.on("Manage Variants", {
 	onload: function(frm) {
-		var df = frappe.meta.get_docfield("Variant Attribute", "attribute_value");
+		var df = frappe.meta.get_docfield("Variant Attribute", "attribute_value", "Manage Variants");
 		df.on_make = function(field) {
 			$(field.input_area).addClass("ui-front");
 			field.$input.autocomplete({
diff --git a/erpnext/stock/doctype/manage_variants/manage_variants.py b/erpnext/stock/doctype/manage_variants/manage_variants.py
index b6784d3..4dcfb22 100644
--- a/erpnext/stock/doctype/manage_variants/manage_variants.py
+++ b/erpnext/stock/doctype/manage_variants/manage_variants.py
@@ -36,8 +36,8 @@
 	def get_attributes(self):
 		attributes = {}
 		self.set('attributes', [])
-		for d in frappe.db.sql("""select attribute, attribute_value from `tabVariant Attribute` as attribute, 
-			`tabItem` as item where attribute.parent= item.name and item.variant_of = %s""", self.item_code, as_dict=1):
+		for d in frappe.db.sql("""select attr.attribute, attr.attribute_value from `tabVariant Attribute` as attr, 
+			`tabItem` as item where attr.parent = item.name and item.variant_of = %s""", self.item_code, as_dict=1):
 				attributes.setdefault(d.attribute, []).append(d.attribute_value)
 		for d in attributes:
 			attribute_values = set(attributes[d])
diff --git a/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py b/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
index e56cd1e..e782889 100644
--- a/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
+++ b/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
@@ -104,15 +104,8 @@
 			}
 		})
 
-		if cint(frappe.defaults.get_global_default('maintain_same_rate')):
-			super(PurchaseReceipt, self).validate_with_previous_doc({
-				"Purchase Order Item": {
-					"ref_dn_field": "prevdoc_detail_docname",
-					"compare_fields": [["rate", "="]],
-					"is_child_table": True
-				}
-			})
-
+		if cint(frappe.db.get_single_value('Buying Settings', 'maintain_same_rate')):
+			self.validate_rate_with_reference_doc([["Purchase Order", "prevdoc_docname", "prevdoc_detail_docname"]])
 
 	def po_required(self):
 		if frappe.db.get_value("Buying Settings", None, "po_required") == 'Yes':
diff --git a/erpnext/stock/doctype/stock_entry/stock_entry.py b/erpnext/stock/doctype/stock_entry/stock_entry.py
index 813a61b..d896b25 100644
--- a/erpnext/stock/doctype/stock_entry/stock_entry.py
+++ b/erpnext/stock/doctype/stock_entry/stock_entry.py
@@ -870,8 +870,6 @@
 			"account": r.get("account"),
 			"party_type": r.get("party_type"),
 			"party": r.get("party"),
-			"against_invoice": r.get("against_invoice"),
-			"against_voucher": r.get("against_voucher"),
 			"balance": get_balance_on(r.get("account"), se.posting_date) if r.get("account") else 0
 		})
 
@@ -882,8 +880,7 @@
 	parent = {
 		"account": ref.doc.debit_to,
 		"party_type": "Customer",
-		"party": ref.doc.customer,
-		"against_invoice": ref.doc.name,
+		"party": ref.doc.customer
 	}
 
 	# income account entries
@@ -957,9 +954,6 @@
 
 			break
 
-	if len(invoices_against_delivery) == 1:
-		parent["against_invoice"] = invoices_against_delivery[0]
-
 	result = [parent] + [{"account": account} for account in children]
 
 	return result
@@ -1015,9 +1009,6 @@
 
 			break
 
-	if len(invoice_against_receipt) == 1:
-		parent["against_voucher"] = invoice_against_receipt[0]
-
 	result = [parent] + [{"account": account} for account in children]
 
 	return result
diff --git a/erpnext/stock/report/batch_wise_balance_history/batch_wise_balance_history.py b/erpnext/stock/report/batch_wise_balance_history/batch_wise_balance_history.py
index 69e1321..9cba203 100644
--- a/erpnext/stock/report/batch_wise_balance_history/batch_wise_balance_history.py
+++ b/erpnext/stock/report/batch_wise_balance_history/batch_wise_balance_history.py
@@ -20,10 +20,11 @@
 		for wh in sorted(iwb_map[item]):
 			for batch in sorted(iwb_map[item][wh]):
 				qty_dict = iwb_map[item][wh][batch]
-				data.append([item, item_map[item]["item_name"], item_map[item]["description"], wh, batch,
-					flt(qty_dict.opening_qty, float_precision), flt(qty_dict.in_qty, float_precision),
-					flt(qty_dict.out_qty, float_precision), flt(qty_dict.bal_qty, float_precision)
-				])
+				if qty_dict.opening_qty or qty_dict.in_qty or qty_dict.out_qty or qty_dict.bal_qty:
+					data.append([item, item_map[item]["item_name"], item_map[item]["description"], wh, batch,
+						flt(qty_dict.opening_qty, float_precision), flt(qty_dict.in_qty, float_precision),
+						flt(qty_dict.out_qty, float_precision), flt(qty_dict.bal_qty, float_precision)
+					])
 
 	return columns, data
 
diff --git a/erpnext/templates/print_formats/includes/item_table_description.html b/erpnext/templates/print_formats/includes/item_table_description.html
index f259626..ece5386 100644
--- a/erpnext/templates/print_formats/includes/item_table_description.html
+++ b/erpnext/templates/print_formats/includes/item_table_description.html
@@ -1,6 +1,7 @@
 {% if doc.in_format_data("image") and doc.get("image") and not doc.is_print_hide("image")-%}
 <div class="pull-left" style="max-width: 38.2%; margin-right: 10px;">
-    <img src="{{ doc.image }}" style="max-width: 100%">
+    <!-- width: 100% is a mozilla bug -->
+    <img src="{{ doc.image }}" class="img-responsive" style="width: 100%;">
 </div>
 {%- endif %}
 <div>
@@ -8,14 +9,14 @@
     	<div class="primary">{{ doc.item_code }}</div>
     {%- endif %}
     {% if (doc.in_format_data("item_name") and not doc.is_print_hide("item_name") and
-    	(not doc.in_format_data("item_code") or doc.is_print_hide("item_code") 
+    	(not doc.in_format_data("item_code") or doc.is_print_hide("item_code")
 			or doc.item_code != doc.item_name)) -%}
     	<div class="primary">{{ doc.get_formatted("item_name") }}</div>
     {%- endif %}
     {% if (doc.in_format_data("description") and doc.description and
     	(
 			(
-				(not doc.in_format_data("item_code") or doc.is_print_hide("item_code")) and 
+				(not doc.in_format_data("item_code") or doc.is_print_hide("item_code")) and
 				(not doc.in_format_data("item_name") or doc.is_print_hide("item_name"))
 			) or not (doc.item_code == doc.item_name == doc.description)
 		))
diff --git a/erpnext/utilities/transaction_base.py b/erpnext/utilities/transaction_base.py
index be74aeb..50b0319 100644
--- a/erpnext/utilities/transaction_base.py
+++ b/erpnext/utilities/transaction_base.py
@@ -4,7 +4,7 @@
 from __future__ import unicode_literals
 import frappe
 from frappe import _
-from frappe.utils import cstr, now_datetime, cint
+from frappe.utils import cstr, now_datetime, cint, flt
 import frappe.share
 
 from erpnext.controllers.status_updater import StatusUpdater
@@ -92,6 +92,17 @@
 				for field, condition in fields:
 					if prevdoc_values[field] is not None:
 						self.validate_value(field, condition, prevdoc_values[field], doc)
+						
+						
+	def validate_rate_with_reference_doc(self, ref_details):
+		for ref_dt, ref_dn_field, ref_link_field in ref_details:
+			for d in self.get("items"):
+				if d.get(ref_link_field):
+					ref_rate = frappe.db.get_value(ref_dt + " Item", d.get(ref_link_field), "rate")
+					
+					if abs(flt(d.rate - ref_rate, d.precision("rate"))) >= .01:
+						frappe.throw(_("Row #{0}: Rate must be same as {1}: {2} ({3} / {4}) ")
+							.format(d.idx, ref_dt, d.get(ref_dn_field), d.rate, ref_rate))
 
 
 def delete_events(ref_type, ref_name):
diff --git a/setup.py b/setup.py
index 8820356..a0e3f14 100644
--- a/setup.py
+++ b/setup.py
@@ -1,6 +1,6 @@
 from setuptools import setup, find_packages
 
-version = "5.1.2"
+version = "5.1.3"
 
 with open("requirements.txt", "r") as f:
 	install_requires = f.readlines()