Merge pull request #5556 from rohitwaghchaure/time_sheet_wages

[Fixes] Timesheet
diff --git a/erpnext/accounts/doctype/account/account.js b/erpnext/accounts/doctype/account/account.js
index 9364b59..c3a01b9 100644
--- a/erpnext/accounts/doctype/account/account.js
+++ b/erpnext/accounts/doctype/account/account.js
@@ -63,7 +63,7 @@
 			frappe.set_route("query-report", "General Ledger");
 		}, __("View"));
 
-		cur_frm.add_custom_button(__('Group to Group'),
+		cur_frm.add_custom_button(__('Non-Group to Group'),
 			function() { cur_frm.cscript.convert_to_group(); }, 'icon-retweet', 'btn-default')
 	}
 }
diff --git a/erpnext/accounts/doctype/account/account.py b/erpnext/accounts/doctype/account/account.py
index 9520928..cc86159 100644
--- a/erpnext/accounts/doctype/account/account.py
+++ b/erpnext/accounts/doctype/account/account.py
@@ -95,7 +95,7 @@
 			if self.check_gle_exists():
 				throw(_("Account with existing transaction cannot be converted to ledger"))
 			elif self.is_group:
-				if self.account_type:
+				if self.account_type and not self.flags.exclude_account_type_check:
 					throw(_("Cannot covert to Group because Account Type is selected."))
 			elif self.check_if_child_exists():
 				throw(_("Account with child nodes cannot be set as ledger"))
@@ -139,7 +139,7 @@
 	def convert_ledger_to_group(self):
 		if self.check_gle_exists():
 			throw(_("Account with existing transaction can not be converted to group."))
-		elif self.account_type:
+		elif self.account_type and not self.flags.exclude_account_type_check:
 			throw(_("Cannot covert to Group because Account Type is selected."))
 		else:
 			self.is_group = 1
diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
index 71e9c42..1e02415 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
@@ -35,6 +35,25 @@
 			'percent_join_field': 'purchase_order',
 			'overflow_type': 'billing'
 		}]
+		
+		self.prev_link_mapper = {
+			"Purchase Order": {
+				"fieldname": "purchase_order",
+				"doctype": "Purchase Invoice Item",
+				"filters": [
+					["Purchase Invoice Item", "parent", "=", self.name],
+					["Purchase Invoice Item", "purchase_order", "!=", ""]
+				]
+			},
+			"Purchase Receipt": {
+				"fieldname": "purchase_receipt",
+				"doctype": "Purchase Invoice Item",
+				"filters": [
+					["Purchase Invoice Item", "parent", "=", self.item],
+					["Purchase Invoice Item", "purchase_receipt", "!=", ""]
+				]
+			}
+		}
 
 	def validate(self):
 		if not self.is_opening:
diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
index 8f7c341..2f1ecf1 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
@@ -38,6 +38,25 @@
 			'keyword': 'Billed',
 			'overflow_type': 'billing'
 		}]
+		
+		self.prev_link_mapper = {
+			"Sales Order": {
+				"fieldname": "sales_order",
+				"doctype": "Sales Invoice Item",
+				"filters": [
+					["Sales Invoice Item", "parent", "=", self.name],
+					["Sales Invoice Item", "sales_order", "!=", ""]
+				]
+			},
+			"Delivery Note": {
+				"fieldname": "delivery_note",
+				"doctype": "Sales Invoice Item",
+				"filters": [
+					["Sales Invoice Item", "parent", "=", self.name],
+					["Sales Invoice Item", "delivery_note", "!=", ""]
+				]
+			}
+		}
 
 	def set_indicator(self):
 		"""Set indicator for portal"""
diff --git a/erpnext/buying/doctype/purchase_order/purchase_order.py b/erpnext/buying/doctype/purchase_order/purchase_order.py
index 6184236..d4b2221 100644
--- a/erpnext/buying/doctype/purchase_order/purchase_order.py
+++ b/erpnext/buying/doctype/purchase_order/purchase_order.py
@@ -32,6 +32,17 @@
 			'percent_join_field': 'prevdoc_docname',
 			'overflow_type': 'order'
 		}]
+		
+		self.prev_link_mapper = {
+			"Supplier Quotation": {
+				"fieldname": "supplier_quotation",
+				"doctype": "Purchase Order Item",
+				"filters": [
+					["Purchase Order Item", "parent", "=", self.name],
+					["Purchase Order Item", "supplier_quotation", "!=", ""]
+				]
+			}
+		}
 
 	def validate(self):
 		super(PurchaseOrder, self).validate()
diff --git a/erpnext/hr/doctype/holiday_list/holiday_list.py b/erpnext/hr/doctype/holiday_list/holiday_list.py
index 0412624..8935689 100644
--- a/erpnext/hr/doctype/holiday_list/holiday_list.py
+++ b/erpnext/hr/doctype/holiday_list/holiday_list.py
@@ -34,7 +34,7 @@
 			throw(_("To Date cannot be before From Date"))
 
 		for day in self.get("holidays"):
-			if not (self.from_date <= day.holiday_date <= self.to_date):
+			if not (getdate(self.from_date) <= getdate(day.holiday_date) <= getdate(self.to_date)):
 				frappe.throw(_("The holiday on {0} is not between From Date and To Date").format(formatdate(day.holiday_date)))
 
 	def get_weekly_off_date_list(self, start_date, end_date):
diff --git a/erpnext/patches.txt b/erpnext/patches.txt
index 0af9713..bcbe2da 100644
--- a/erpnext/patches.txt
+++ b/erpnext/patches.txt
@@ -281,3 +281,4 @@
 erpnext.patches.v7_0.convert_timelog_to_timesheet
 erpnext.patches.v7_0.move_timelogbatch_from_salesinvoiceitem_to_salesinvoicetimesheet
 erpnext.patches.v7_0.remove_doctypes_and_reports
+erpnext.patches.v7_0.set_is_group_for_warehouse
diff --git a/erpnext/patches/v7_0/create_warehouse_nestedset.py b/erpnext/patches/v7_0/create_warehouse_nestedset.py
index 80dbf2e..aaccfb9 100644
--- a/erpnext/patches/v7_0/create_warehouse_nestedset.py
+++ b/erpnext/patches/v7_0/create_warehouse_nestedset.py
@@ -15,7 +15,7 @@
 
 def set_parent_to_warehouses(warehouse, company):
 	warehouse = frappe.get_doc("Warehouse", warehouse.name)
-	warehouse.is_group = "Yes" if warehouse.is_group == "Yes" else "No"
+	warehouse.is_group = warehouse.is_group
 	
 	if not warehouse.parent_warehouse and warehouse.name != "{0} - {1}".format(_("All Warehouses"), company.abbr):
 		warehouse.parent_warehouse = "{0} - {1}".format(_("All Warehouses"), company.abbr)
@@ -42,7 +42,7 @@
 	frappe.get_doc({
 		"doctype": "Warehouse",
 		"warehouse_name": _("All Warehouses"),
-		"is_group": "Yes",
+		"is_group": 1,
 		"company": company.name,
 		"parent_warehouse": ""
 	}).insert(ignore_permissions=True)
\ No newline at end of file
diff --git a/erpnext/patches/v7_0/set_is_group_for_warehouse.py b/erpnext/patches/v7_0/set_is_group_for_warehouse.py
new file mode 100644
index 0000000..d3aca21
--- /dev/null
+++ b/erpnext/patches/v7_0/set_is_group_for_warehouse.py
@@ -0,0 +1,6 @@
+import frappe
+
+def execute():
+	frappe.reload_doc("stock", "doctype", "warehouse")
+	frappe.db.sql("""update tabWarehouse
+		set is_group = if ((ifnull(is_group, "No") = "Yes" or ifnull(is_group, 0) = 1), 1, 0)""")
\ No newline at end of file
diff --git a/erpnext/public/js/queries.js b/erpnext/public/js/queries.js
index acc0409..c1f09a5 100644
--- a/erpnext/public/js/queries.js
+++ b/erpnext/public/js/queries.js
@@ -73,7 +73,7 @@
 		return {
 			filters: [
 				["Warehouse", "company", "in", ["", cstr(doc.company)]],
-				["Warehouse", "is_group", "=", "No"]
+				["Warehouse", "is_group", "=",0]
 				
 			]
 		}
diff --git a/erpnext/selling/doctype/sales_order/sales_order.py b/erpnext/selling/doctype/sales_order/sales_order.py
index 2e0a272..8103756 100644
--- a/erpnext/selling/doctype/sales_order/sales_order.py
+++ b/erpnext/selling/doctype/sales_order/sales_order.py
@@ -21,6 +21,20 @@
 class WarehouseRequired(frappe.ValidationError): pass
 
 class SalesOrder(SellingController):
+	def __init__(self, arg1, arg2=None):
+		super(SalesOrder, self).__init__(arg1, arg2)
+		
+		self.prev_link_mapper = {
+			"Quotation": {
+				"fieldname": "prevdoc_docname",
+				"doctype": "Sales Order Item",
+				"filters": [
+					["Sales Order Item", "parent", "=", self.name],
+					["Sales Order Item", "prevdoc_docname", "!=", ""]
+				]
+			}
+		}
+		
 	def validate(self):
 		super(SalesOrder, self).validate()
 
@@ -306,7 +320,7 @@
 		mcount = month_map[reference_doc.recurring_type]
 		self.set("delivery_date", get_next_date(reference_doc.delivery_date, mcount,
 						cint(reference_doc.repeat_on_day_of_month)))
-
+		
 def get_list_context(context=None):
 	from erpnext.controllers.website_list_for_contact import get_list_context
 	list_context = get_list_context(context)
diff --git a/erpnext/setup/doctype/company/company.py b/erpnext/setup/doctype/company/company.py
index 7d88297..6b66324 100644
--- a/erpnext/setup/doctype/company/company.py
+++ b/erpnext/setup/doctype/company/company.py
@@ -88,10 +88,10 @@
 
 	def create_default_warehouses(self):
 		for wh_detail in [
-			{"warehouse_name": _("All Warehouses"), "is_group": "Yes"},
-			{"warehouse_name": _("Stores"), "is_group": "No"},
-			{"warehouse_name": _("Work In Progress"), "is_group": "No"},
-			{"warehouse_name": _("Finished Goods"), "is_group": "No"}]:
+			{"warehouse_name": _("All Warehouses"), "is_group": 1},
+			{"warehouse_name": _("Stores"), "is_group": 0},
+			{"warehouse_name": _("Work In Progress"), "is_group": 0},
+			{"warehouse_name": _("Finished Goods"), "is_group": 0}]:
 			
 			if not frappe.db.exists("Warehouse", "{0} - {1}".format(wh_detail["warehouse_name"], self.abbr)):
 				stock_group = frappe.db.get_value("Account", {"account_type": "Stock",
@@ -103,7 +103,7 @@
 						"is_group": wh_detail["is_group"],
 						"company": self.name,
 						"parent_warehouse": "{0} - {1}".format(_("All Warehouses"), self.abbr) \
-							if wh_detail["is_group"] == "No" else "",
+							if not wh_detail["is_group"] else "",
 						"create_account_under": stock_group
 					})
 					warehouse.flags.ignore_permissions = True
diff --git a/erpnext/setup/setup_wizard/setup_wizard.py b/erpnext/setup/setup_wizard/setup_wizard.py
index e3e47ae..1de376c 100644
--- a/erpnext/setup/setup_wizard/setup_wizard.py
+++ b/erpnext/setup/setup_wizard/setup_wizard.py
@@ -63,6 +63,7 @@
 		if roles.role == 'System Manager':
 			roles.role = 'Administrator'
 	setup_wizard.flags.ignore_permissions = 1
+	setup_wizard.flags.do_not_update_json = 1
 	setup_wizard.save()
 
 def create_fiscal_year_and_company(args):
diff --git a/erpnext/stock/doctype/delivery_note/delivery_note.py b/erpnext/stock/doctype/delivery_note/delivery_note.py
index 6c6a3b3..d8defc0 100644
--- a/erpnext/stock/doctype/delivery_note/delivery_note.py
+++ b/erpnext/stock/doctype/delivery_note/delivery_note.py
@@ -60,7 +60,19 @@
 			'source_field': '-1 * qty',
 			'extra_cond': """ and exists (select name from `tabDelivery Note` where name=`tabDelivery Note Item`.parent and is_return=1)"""
 		}]
+		
+		self.prev_link_mapper = {
+			"Sales Order": {
+				"fieldname": "against_sales_order",
+				"doctype": "Delivery Note Item",
+				"filters": [
+					["Delivery Note Item", "parent", "=", self.name],
+					["Delivery Note Item", "against_sales_order", "!=", ""]
+				]
+			}
+		}
 
+		
 	def before_print(self):
 		def toggle_print_hide(meta, fieldname):
 			df = meta.get_field(fieldname)
diff --git a/erpnext/stock/doctype/item/item.js b/erpnext/stock/doctype/item/item.js
index f35fa58..5bb0061 100644
--- a/erpnext/stock/doctype/item/item.js
+++ b/erpnext/stock/doctype/item/item.js
@@ -163,13 +163,13 @@
 		
 		frm.fields_dict['default_warehouse'].get_query = function(doc) {
 			return {
-				filters: { "is_group": "No" }
+				filters: { "is_group": 0 }
 			}
 		}
 		
 		frm.fields_dict.reorder_levels.grid.get_field("warehouse_group").get_query = function(doc, cdt, cdn) {
 			return {
-				filters: { "is_group": "Yes" }
+				filters: { "is_group": 1 }
 			}
 		}
 		
@@ -177,7 +177,7 @@
 			var d = locals[cdt][cdn];
 			return {
 				filters: {
-					"is_group": "No",
+					"is_group": 0,
 					"parent_warehouse": d.warehouse_group
 				}
 			}
diff --git a/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py b/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
index 70cef36..6c72d6b 100644
--- a/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
+++ b/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
@@ -45,6 +45,17 @@
 			# 'overflow_type': 'receipt',
 			'extra_cond': """ and exists (select name from `tabPurchase Receipt` where name=`tabPurchase Receipt Item`.parent and is_return=1)"""
 		}]
+		
+		self.prev_link_mapper = {
+			"Purchase Order": {
+				"fieldname": "prevdoc_docname",
+				"doctype": "Purchase Receipt Item",
+				"filters": [
+					["Purchase Receipt Item", "parent", "=", self.name],
+					["Purchase Receipt Item", "prevdoc_docname", "!=", ""]
+				]
+			}
+		}
 
 	def validate(self):
 		super(PurchaseReceipt, self).validate()
diff --git a/erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py b/erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py
index 9cc27b7..f9629a1 100644
--- a/erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py
+++ b/erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py
@@ -117,7 +117,7 @@
 	frappe.db.set_value("Item", item_code, "valuation_method", valuation_method)
 
 	for warehouse in frappe.get_all("Warehouse", filters={"company": "_Test Company"}, fields=["name", "is_group"]):
-		if warehouse.is_group == "No":
+		if not warehouse.is_group:
 			update_entries_after({
 				"item_code": item_code,
 				"warehouse": warehouse.name
diff --git a/erpnext/stock/doctype/warehouse/test_records.json b/erpnext/stock/doctype/warehouse/test_records.json
index c1dad5c..4dd9f6b 100644
--- a/erpnext/stock/doctype/warehouse/test_records.json
+++ b/erpnext/stock/doctype/warehouse/test_records.json
@@ -4,67 +4,67 @@
   "create_account_under": "Stock Assets - _TC",
   "doctype": "Warehouse",
   "warehouse_name": "_Test Warehouse",
-  "is_group": "No"
+  "is_group": 0
  },
  {
   "company": "_Test Company",
   "create_account_under": "Stock Assets - _TC",
   "doctype": "Warehouse",
   "warehouse_name": "_Test Warehouse",
-  "is_group": "No"
+  "is_group": 0
  },
  {
   "company": "_Test Company",
   "create_account_under": "Fixed Assets - _TC",
   "doctype": "Warehouse",
   "warehouse_name": "_Test Warehouse 1",
-  "is_group": "No"
+  "is_group": 0
  },
  {
   "company": "_Test Company",
   "create_account_under": "Fixed Assets - _TC",
   "doctype": "Warehouse",
   "warehouse_name": "_Test Warehouse 2",
-  "is_group": "No"
+  "is_group": 0
  },
  {
   "company": "_Test Company",
   "create_account_under": "Stock Assets - _TC",
   "doctype": "Warehouse",
   "warehouse_name": "_Test Rejected Warehouse",
-  "is_group": "No"
+  "is_group": 0
  },
  {
   "company": "_Test Company 1",
   "create_account_under": "Stock Assets - _TC1",
   "doctype": "Warehouse",
   "warehouse_name": "_Test Warehouse 2",
-  "is_group": "No"
+  "is_group": 0
  },
  {
   "company": "_Test Company",
   "doctype": "Warehouse",
   "warehouse_name": "_Test Warehouse No Account",
-  "is_group": "No"
+  "is_group": 0
  },
  {
   "company": "_Test Company",
   "doctype": "Warehouse",
   "warehouse_name": "_Test Warehouse Group",
-  "is_group": "Yes"
+  "is_group": 1
  },
  {
   "company": "_Test Company",
   "doctype": "Warehouse",
   "warehouse_name": "_Test Warehouse Group-C1",
-  "is_group": "No",
+  "is_group": 0,
   "parent_warehouse": "_Test Warehouse Group - _TC"
  },
  {
   "company": "_Test Company",
   "doctype": "Warehouse",
   "warehouse_name": "_Test Warehouse Group-C2",
-  "is_group": "No",
+  "is_group": 0,
   "parent_warehouse": "_Test Warehouse Group - _TC"
  }
 ]
diff --git a/erpnext/stock/doctype/warehouse/test_warehouse.py b/erpnext/stock/doctype/warehouse/test_warehouse.py
index b6eaa13..2232584 100644
--- a/erpnext/stock/doctype/warehouse/test_warehouse.py
+++ b/erpnext/stock/doctype/warehouse/test_warehouse.py
@@ -10,7 +10,7 @@
 class TestWarehouse(unittest.TestCase):
 	def test_parent_warehouse(self):
 		parent_warehouse = frappe.get_doc("Warehouse", "_Test Warehouse Group - _TC")
-		self.assertEquals(parent_warehouse.is_group, "Yes")
+		self.assertEquals(parent_warehouse.is_group, 1)
 		
 	def test_warehouse_hierarchy(self):
 		p_warehouse = frappe.get_doc("Warehouse", "_Test Warehouse Group - _TC")
@@ -20,6 +20,6 @@
 		
 		for child_warehouse in child_warehouses:
 			self.assertEquals(p_warehouse.name, child_warehouse.parent_warehouse)
-			self.assertEquals(child_warehouse.is_group, "No")
+			self.assertEquals(child_warehouse.is_group, 0)
 		
 		
diff --git a/erpnext/stock/doctype/warehouse/warehouse.js b/erpnext/stock/doctype/warehouse/warehouse.js
index b7a3a34..8b1b679 100644
--- a/erpnext/stock/doctype/warehouse/warehouse.js
+++ b/erpnext/stock/doctype/warehouse/warehouse.js
@@ -9,29 +9,37 @@
 		frm.add_custom_button(__("Stock Balance"), function() {
 			frappe.set_route("query-report", "Stock Balance", {"warehouse": frm.doc.name});
 		});
- 		if(frm.doc.__onload && frm.doc.__onload.account) {
-	 		frm.add_custom_button(__("General Ledger"), function() {
-				frappe.route_options = {
-					"account": frm.doc.__onload.account,
-					"company": frm.doc.company
-				}
-				frappe.set_route("query-report", "General Ledger");
-			});
- 		}
+
+		if (cint(frm.doc.is_group) == 1) {
+			frm.add_custom_button(__('Group to Non-Group'),
+				function() { convert_to_group_or_ledger(frm); }, 'icon-retweet', 'btn-default')
+		} else if (cint(frm.doc.is_group) == 0) {
+			if(frm.doc.__onload && frm.doc.__onload.account) {
+				frm.add_custom_button(__("General Ledger"), function() {
+					frappe.route_options = {
+						"account": frm.doc.__onload.account,
+						"company": frm.doc.company
+					}
+					frappe.set_route("query-report", "General Ledger");
+				});
+			}
+
+			frm.add_custom_button(__('Non-Group to Group'),
+				function() { convert_to_group_or_ledger(frm); }, 'icon-retweet', 'btn-default')
+		}
 		
+		cur_frm.toggle_enable(['is_group', 'company'], false);
+
 		frm.fields_dict['parent_warehouse'].get_query = function(doc) {
 			return {
 				filters: {
-					"is_group": "Yes",
+					"is_group": 1,
 				}
 			}
 		}
 	}
 });
 
-
-
-
 cur_frm.set_query("create_account_under", function() {
 	return {
 		filters: {
@@ -40,3 +48,17 @@
 		}
 	}
 })
+
+function convert_to_group_or_ledger(frm){
+	frappe.call({
+		method:"erpnext.stock.doctype.warehouse.warehouse.convert_to_group_or_ledger",
+		args: {
+			docname: frm.doc.name,
+			is_group: frm.doc.is_group
+		},
+		callback: function(){
+			frm.refresh();
+		}
+		
+	})
+}
\ No newline at end of file
diff --git a/erpnext/stock/doctype/warehouse/warehouse.json b/erpnext/stock/doctype/warehouse/warehouse.json
index 1a3a97f..a32ec1f 100644
--- a/erpnext/stock/doctype/warehouse/warehouse.json
+++ b/erpnext/stock/doctype/warehouse/warehouse.json
@@ -39,6 +39,33 @@
    "allow_on_submit": 0, 
    "bold": 0, 
    "collapsible": 0, 
+   "default": "1", 
+   "fieldname": "is_group", 
+   "fieldtype": "Check", 
+   "hidden": 0, 
+   "ignore_user_permissions": 0, 
+   "ignore_xss_filter": 0, 
+   "in_filter": 0, 
+   "in_list_view": 1, 
+   "label": "Is Group", 
+   "length": 0, 
+   "no_copy": 0, 
+   "options": "", 
+   "permlevel": 0, 
+   "precision": "", 
+   "print_hide": 0, 
+   "print_hide_if_no_value": 0, 
+   "read_only": 0, 
+   "report_hide": 0, 
+   "reqd": 0, 
+   "search_index": 0, 
+   "set_only_once": 0, 
+   "unique": 0
+  }, 
+  {
+   "allow_on_submit": 0, 
+   "bold": 0, 
+   "collapsible": 0, 
    "fieldname": "warehouse_name", 
    "fieldtype": "Data", 
    "hidden": 0, 
@@ -477,32 +504,6 @@
    "allow_on_submit": 0, 
    "bold": 0, 
    "collapsible": 0, 
-   "fieldname": "is_group", 
-   "fieldtype": "Select", 
-   "hidden": 0, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 0, 
-   "in_list_view": 1, 
-   "label": "Has Child Node", 
-   "length": 0, 
-   "no_copy": 0, 
-   "options": "\nYes\nNo", 
-   "permlevel": 0, 
-   "precision": "", 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "read_only": 0, 
-   "report_hide": 0, 
-   "reqd": 1, 
-   "search_index": 0, 
-   "set_only_once": 0, 
-   "unique": 0
-  }, 
-  {
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
    "fieldname": "lft", 
    "fieldtype": "Int", 
    "hidden": 1, 
@@ -587,8 +588,8 @@
  "issingle": 0, 
  "istable": 0, 
  "max_attachments": 0, 
- "modified": "2016-06-25 18:21:05.175172", 
- "modified_by": "Administrator", 
+ "modified": "2016-06-26 17:39:16.856800", 
+ "modified_by": "s@s.com", 
  "module": "Stock", 
  "name": "Warehouse", 
  "owner": "Administrator", 
diff --git a/erpnext/stock/doctype/warehouse/warehouse.py b/erpnext/stock/doctype/warehouse/warehouse.py
index ed68065..3b50f30 100644
--- a/erpnext/stock/doctype/warehouse/warehouse.py
+++ b/erpnext/stock/doctype/warehouse/warehouse.py
@@ -50,7 +50,7 @@
 
 	def create_account_head(self):
 		if cint(frappe.defaults.get_global_default("auto_accounting_for_stock")):
-			if not self.get_account(self.name):
+			if not self.get_account():
 				if self.get("__islocal") or not frappe.db.get_value(
 						"Stock Ledger Entry", {"warehouse": self.name}):
 
@@ -60,7 +60,7 @@
 						'account_name': self.warehouse_name,
 						'parent_account': self.parent_warehouse if self.parent_warehouse \
 							else self.create_account_under,
-						'is_group': 1 if self.is_group=="Yes" else 0 ,
+						'is_group': self.is_group,
 						'company':self.company,
 						"account_type": "Stock",
 						"warehouse": self.name,
@@ -113,14 +113,21 @@
 		if warehouse_account:
 			frappe.delete_doc("Account", warehouse_account)
 
-		if frappe.db.sql("""select name from `tabStock Ledger Entry`
-				where warehouse = %s""", self.name):
+		if self.check_sle_exists():
 			throw(_("Warehouse can not be deleted as stock ledger entry exists for this warehouse."))
 
-		if frappe.db.sql("""select name from `tabWarehouse` where parent_warehouse = %s""", self.name):
+		if self.check_if_child_exists():
 			throw(_("Child warehouse exists for this warehouse. You can not delete this warehouse."))
 
 		self.update_nsm_model()
+	
+	def check_if_sle_exists(self):
+		return frappe.db.sql("""select name from `tabStock Ledger Entry`
+			where warehouse = %s""", self.name)
+	
+	def check_if_child_exists(self):
+		return frappe.db.sql("""select name from `tabWarehouse`
+			where parent_warehouse = %s""", self.name)
 
 	def before_rename(self, olddn, newdn, merge=False):
 		# Add company abbr if not provided
@@ -159,9 +166,19 @@
 		from erpnext.setup.doctype.company.company import get_name_with_abbr
 		return get_name_with_abbr(dn, self.company)
 
-	def get_account(self, warehouse):
-		return frappe.db.get_value("Account", {"account_type": "Stock",
-			"warehouse": warehouse, "company": self.company, "is_group": 0})
+	def get_account(self, warehouse=None):
+		filters = {
+			"account_type": "Stock",
+			"company": self.company,
+			"is_group": self.is_group
+		}
+
+		if warehouse:
+			filters.update({"warehouse": warehouse})
+		else:
+			filters.update({"account_name": self.warehouse_name})
+
+		return frappe.db.get_value("Account", filters)
 
 	def after_rename(self, olddn, newdn, merge=False):
 		if merge:
@@ -181,6 +198,42 @@
 
 		frappe.db.set_value("Stock Settings", None, "allow_negative_stock", existing_allow_negative_stock)
 		frappe.db.auto_commit_on_many_writes = 0
+	
+	def convert_to_group_or_ledger(self):
+		if self.is_group:
+			self.convert_to_ledger()
+		else:
+			self.convert_to_group()
+
+	def convert_to_ledger(self):
+		if self.check_if_child_exists():
+			frappe.throw(_("Warehouses with child nodes cannot be converted to ledger"))
+		elif self.check_if_sle_exists():
+			throw(_("Warehouses with existing transaction can not be converted to ledger."))
+		else:
+			account_name = self.get_account()
+			if account_name:
+				doc = frappe.get_doc("Account", account_name)
+				doc.warehouse = self.name
+				doc.convert_group_to_ledger()
+			
+			self.is_group = 0
+			self.save()
+			return 1
+	
+	def convert_to_group(self):
+		if self.check_if_sle_exists():
+			throw(_("Warehouses with existing transaction can not be converted to group."))
+		else:
+			account_name = self.get_account(self.name)
+			if account_name:
+				doc = frappe.get_doc("Account", account_name)
+				doc.flags.exclude_account_type_check = True
+				doc.convert_ledger_to_group()
+
+			self.is_group = 1
+			self.save()
+			return 1
 
 @frappe.whitelist()
 def get_children():
@@ -195,7 +248,7 @@
 		parent = ""
 
 	warehouses = frappe.db.sql("""select name as value,
-		if(is_group='Yes', 1, 0) as expandable
+		is_group as expandable
 		from `tab{doctype}`
 		where docstatus < 2
 		and ifnull(`{parent_field}`,'') = %s and `company` = %s
@@ -229,3 +282,9 @@
 	})
 
 	doc.save()
+
+@frappe.whitelist()
+def convert_to_group_or_ledger():
+	args = frappe.form_dict
+	return frappe.get_doc("Warehouse", args.docname).convert_to_group_or_ledger()
+	
\ No newline at end of file
diff --git a/erpnext/stock/doctype/warehouse/warehouse_tree.js b/erpnext/stock/doctype/warehouse/warehouse_tree.js
index 0361493..9069160 100644
--- a/erpnext/stock/doctype/warehouse/warehouse_tree.js
+++ b/erpnext/stock/doctype/warehouse/warehouse_tree.js
@@ -10,6 +10,12 @@
 		label: __("Company"),
 		default: frappe.defaults.get_default('company') ? frappe.defaults.get_default('company'): ""
 	}],
+	fields:[
+		{fieldtype:'Data', fieldname: 'name_field',
+			label:__('New Warehouse Name'), reqd:true},
+		{fieldtype:'Check', fieldname:'is_group', label:__('Group Node'),
+			description: __("Further nodes can be only created under 'Group' type nodes")}
+	],
 	onrender: function(node) {
 		if (node.data && node.data.balance!==undefined) {
 			$('<span class="balance-area pull-right text-muted small">'
diff --git a/erpnext/stock/report/stock_projected_qty/stock_projected_qty.py b/erpnext/stock/report/stock_projected_qty/stock_projected_qty.py
index 409833a..f90fb49 100644
--- a/erpnext/stock/report/stock_projected_qty/stock_projected_qty.py
+++ b/erpnext/stock/report/stock_projected_qty/stock_projected_qty.py
@@ -66,11 +66,12 @@
 		lft, rgt = frappe.db.get_value("Warehouse", filters.warehouse, ["lft", "rgt"])
 	
 		conditions.append(" exists (select name from `tabWarehouse` wh \
-			where wh.lft >= %s and wh.rgt <= %s and sle.warehouse = wh.name)"%(lft, rgt))
+			where wh.lft >= %s and wh.rgt <= %s and bin.warehouse = wh.name)"%(lft, rgt))
 
 	bin_list = frappe.db.sql("""select item_code, warehouse, actual_qty, planned_qty, indented_qty,
 		ordered_qty, reserved_qty, reserved_qty_for_production, projected_qty
-		from tabBin where %s order by item_code, warehouse """% " and ".join(conditions), as_dict=1,debug=1)
+		from tabBin bin {conditions} order by item_code, warehouse
+		""".format(conditions=" where " + " and ".join(conditions) if conditions else ""), as_dict=1)
 
 	return bin_list
 
diff --git a/erpnext/stock/utils.py b/erpnext/stock/utils.py
index 51d82a6..6797f8e 100644
--- a/erpnext/stock/utils.py
+++ b/erpnext/stock/utils.py
@@ -18,7 +18,7 @@
 		
 		lft, rgt, is_group = frappe.db.get_value("Warehouse", warehouse, ["lft", "rgt", "is_group"])
 		
-		if is_group == "Yes":
+		if is_group:
 			values.extend([lft, rgt])
 			condition += "and exists (\
 				select name from `tabWarehouse` wh where wh.name = sle.warehouse\
@@ -189,6 +189,6 @@
 			InvalidWarehouseCompany)
 
 def is_group_warehouse(warehouse):
-	if frappe.db.get_value("Warehouse", warehouse, "is_group") == "Yes":
+	if frappe.db.get_value("Warehouse", warehouse, "is_group"):
 		frappe.throw(_("Group node warehouse is not allowed to select for transactions"))
 	
\ No newline at end of file
diff --git a/erpnext/utilities/transaction_base.py b/erpnext/utilities/transaction_base.py
index d088f59..3cc79ef 100644
--- a/erpnext/utilities/transaction_base.py
+++ b/erpnext/utilities/transaction_base.py
@@ -107,6 +107,24 @@
 						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 get_link_filters(self, for_doctype):
+		if hasattr(self, "prev_link_mapper") and self.prev_link_mapper.get(for_doctype):
+			fieldname = self.prev_link_mapper[for_doctype]["fieldname"]
+			
+			values = filter(None, tuple([item.as_dict()[fieldname] for item in self.items]))
+
+			if values:
+				ret = {
+					for_doctype : {
+						"filters": [[for_doctype, "name", "in", values]]
+					}
+				}
+			else:
+				ret = None
+		else:
+			ret = None
+		
+		return ret
 
 def delete_events(ref_type, ref_name):
 	frappe.delete_doc("Event", frappe.db.sql_list("""select name from `tabEvent`