Cleanup and fixes on GSTR-2
diff --git a/.travis.yml b/.travis.yml
index 03e75b6..b74289f 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,13 +1,6 @@
 language: python
 dist: trusty
 
-addons:
-  apt:
-    sources:
-      - google-chrome
-    packages:
-      - google-chrome-stable
-
 python:
   - "2.7"
 
@@ -31,15 +24,6 @@
   - cp -r $TRAVIS_BUILD_DIR/test_sites/test_site ~/frappe-bench/sites/
 
 before_script:
-  - wget http://chromedriver.storage.googleapis.com/2.33/chromedriver_linux64.zip
-  - unzip chromedriver_linux64.zip
-  - sudo apt-get install libnss3
-  - sudo apt-get --only-upgrade install google-chrome-stable
-  - sudo cp chromedriver /usr/local/bin/.
-  - sudo chmod +x /usr/local/bin/chromedriver
-  - export DISPLAY=:99.0
-  - sh -e /etc/init.d/xvfb start
-  - sleep 3
   - mysql -u root -ptravis -e 'create database test_frappe'
   - echo "USE mysql;\nCREATE USER 'test_frappe'@'localhost' IDENTIFIED BY 'test_frappe';\nFLUSH PRIVILEGES;\n" | mysql -u root -ptravis
   - echo "USE mysql;\nGRANT ALL PRIVILEGES ON \`test_frappe\`.* TO 'test_frappe'@'localhost';\n" | mysql -u root -ptravis
@@ -62,24 +46,6 @@
       env: Server Side Test
     - # stage
       script:
-        - bench --verbose run-setup-wizard-ui-test
-        - bench execute erpnext.setup.utils.enable_all_roles_and_domains
-        - bench run-ui-tests --app erpnext
-      env: Client Side Test
-    - # stage
-      script:
-        - bench --verbose run-setup-wizard-ui-test
-        - bench execute erpnext.setup.utils.enable_all_roles_and_domains
-        - bench run-ui-tests --app erpnext --test-list erpnext/tests/ui/tests2.txt
-      env: Client Side Test - 2
-    - # stage
-      script:
-        - bench --verbose run-setup-wizard-ui-test
-        - bench execute erpnext.setup.utils.enable_all_roles_and_domains
-        - bench run-ui-tests --app erpnext --test-list erpnext/tests/ui/agriculture.txt
-      env: Agriculture Client Side Test
-    - # stage
-      script:
         - wget http://build.erpnext.com/20171108_190013_955977f8_database.sql.gz
         - bench --force restore ~/frappe-bench/20171108_190013_955977f8_database.sql.gz --mariadb-root-password travis
         - bench migrate
diff --git a/README.md b/README.md
index 74ea7fc..3d11089 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,10 @@
-# ERPNext - ERP made simple
+<div align="center">
+    <img src="https://github.com/frappe/design/blob/master/logos/erpnext-logo.svg" height="128">
+    <h2>ERPNext</h2>
+    <p align="center">
+        <p>ERP made simple</p>
+    </p>
+</div>
 
 [![Build Status](https://travis-ci.org/frappe/erpnext.png)](https://travis-ci.org/frappe/erpnext) [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/frappe/erpnext?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
 
diff --git a/erpnext/__init__.py b/erpnext/__init__.py
index 1b88bdc..76123b1 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.0.17'
+__version__ = '10.0.19'
 
 def get_default_company(user=None):
 	'''Get default company for user'''
diff --git a/erpnext/accounts/doctype/pos_profile/pos_profile.json b/erpnext/accounts/doctype/pos_profile/pos_profile.json
index 2cb8e10..ed3de07 100644
--- a/erpnext/accounts/doctype/pos_profile/pos_profile.json
+++ b/erpnext/accounts/doctype/pos_profile/pos_profile.json
@@ -260,6 +260,36 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
+   "fieldname": "allow_user_to_edit_discount", 
+   "fieldtype": "Check", 
+   "hidden": 0, 
+   "ignore_user_permissions": 0, 
+   "ignore_xss_filter": 0, 
+   "in_filter": 0, 
+   "in_global_search": 0, 
+   "in_list_view": 0, 
+   "in_standard_filter": 0, 
+   "label": "Allow user to edit Discount", 
+   "length": 0, 
+   "no_copy": 0, 
+   "permlevel": 0, 
+   "precision": "", 
+   "print_hide": 0, 
+   "print_hide_if_no_value": 0, 
+   "read_only": 0, 
+   "remember_last_selected_value": 0, 
+   "report_hide": 0, 
+   "reqd": 0, 
+   "search_index": 0, 
+   "set_only_once": 0, 
+   "unique": 0
+  }, 
+  {
+   "allow_bulk_edit": 0, 
+   "allow_on_submit": 0, 
+   "bold": 0, 
+   "collapsible": 0, 
+   "columns": 0, 
    "fieldname": "allow_print_before_pay", 
    "fieldtype": "Check", 
    "hidden": 0, 
@@ -1476,7 +1506,7 @@
  "issingle": 0, 
  "istable": 0, 
  "max_attachments": 0, 
- "modified": "2018-01-03 17:30:45.198147", 
+ "modified": "2018-01-31 19:33:11.765731", 
  "modified_by": "Administrator", 
  "module": "Accounts", 
  "name": "POS Profile", 
diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
index 266e3e1..ed2e3e4 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
@@ -224,12 +224,17 @@
 		from erpnext.selling.doctype.customer.customer import check_credit_limit
 
 		validate_against_credit_limit = False
+		bypass_credit_limit_check_at_sales_order = cint(frappe.db.get_value("Customer", self.customer,
+			"bypass_credit_limit_check_at_sales_order"))
+		if bypass_credit_limit_check_at_sales_order:
+			validate_against_credit_limit = True
+
 		for d in self.get("items"):
 			if not (d.sales_order or d.delivery_note):
 				validate_against_credit_limit = True
 				break
 		if validate_against_credit_limit:
-			check_credit_limit(self.customer, self.company)
+			check_credit_limit(self.customer, self.company, bypass_credit_limit_check_at_sales_order)
 
 	def set_missing_values(self, for_validate=False):
 		pos = self.set_pos_fields(for_validate)
@@ -242,7 +247,11 @@
 		super(SalesInvoice, self).set_missing_values(for_validate)
 
 		if pos:
-			return {"print_format": pos.get("print_format_for_online") }
+			return {
+				"print_format": pos.get("print_format_for_online"),
+				"allow_edit_rate": pos.get("allow_user_to_edit_rate"),
+				"allow_edit_discount": pos.get("allow_user_to_edit_discount")
+			}
 
 	def update_time_sheet(self, sales_invoice):
 		for d in self.timesheets:
diff --git a/erpnext/accounts/doctype/tax_rule/tax_rule.py b/erpnext/accounts/doctype/tax_rule/tax_rule.py
index 9c091e8..2e92e05 100644
--- a/erpnext/accounts/doctype/tax_rule/tax_rule.py
+++ b/erpnext/accounts/doctype/tax_rule/tax_rule.py
@@ -130,8 +130,8 @@
 def get_tax_template(posting_date, args):
 	"""Get matching tax rule"""
 	args = frappe._dict(args)
-	conditions = ["""(from_date is null  or from_date = '' or from_date <= '{0}')
-		and (to_date is null  or to_date = '' or to_date >= '{0}')""".format(posting_date)]
+	conditions = ["""(from_date is null or from_date <= '{0}')
+		and (to_date is null or to_date >= '{0}')""".format(posting_date)]
 
 	for key, value in args.iteritems():
 		if key=="use_for_shopping_cart":
diff --git a/erpnext/accounts/page/pos/pos.js b/erpnext/accounts/page/pos/pos.js
index 558dd8d..a852b76 100644
--- a/erpnext/accounts/page/pos/pos.js
+++ b/erpnext/accounts/page/pos/pos.js
@@ -1620,8 +1620,16 @@
 		var me = this;
 		var invoice_data = {};
 		this.si_docs = this.get_doc_from_localstorage();
+    
 		if (this.frm.doc.offline_pos_name) {
-			this.update_invoice();
+			this.update_invoice()
+			//to retrieve and set the default payment
+			invoice_data[this.frm.doc.offline_pos_name] = this.frm.doc;
+			invoice_data[this.frm.doc.offline_pos_name].payments[0].amount = this.frm.doc.net_total
+			invoice_data[this.frm.doc.offline_pos_name].payments[0].base_amount = this.frm.doc.net_total
+
+			this.frm.doc.paid_amount = this.frm.doc.net_total
+			this.frm.doc.outstanding_amount = 0
 		} else {
 			this.frm.doc.offline_pos_name = $.now();
 			this.frm.doc.posting_date = frappe.datetime.get_today();
diff --git a/erpnext/accounts/report/item_wise_sales_register/item_wise_sales_register.py b/erpnext/accounts/report/item_wise_sales_register/item_wise_sales_register.py
index ab5251f..8917c9f 100644
--- a/erpnext/accounts/report/item_wise_sales_register/item_wise_sales_register.py
+++ b/erpnext/accounts/report/item_wise_sales_register/item_wise_sales_register.py
@@ -168,11 +168,11 @@
 
 	for d in item_list:
 		invoice_item_row.setdefault(d.parent, []).append(d)
-		item_row_map.setdefault(d.parent, {}).setdefault(d.item_code, []).append(d)
+		item_row_map.setdefault(d.parent, {}).setdefault(d.item_code or d.item_name, []).append(d)
 
 	conditions = ""
 	if doctype == "Purchase Invoice":
-		conditions = " and category in ('Total', 'Valuation and Total')"
+		conditions = " and category in ('Total', 'Valuation and Total') and base_tax_amount_after_discount_amount != 0"
 
 	tax_details = frappe.db.sql("""
 		select
diff --git a/erpnext/accounts/report/purchase_register/purchase_register.py b/erpnext/accounts/report/purchase_register/purchase_register.py
index 37848d5..610475a 100644
--- a/erpnext/accounts/report/purchase_register/purchase_register.py
+++ b/erpnext/accounts/report/purchase_register/purchase_register.py
@@ -172,6 +172,7 @@
 		else sum(base_tax_amount_after_discount_amount) * -1 end as tax_amount
 		from `tabPurchase Taxes and Charges`
 		where parent in (%s) and category in ('Total', 'Valuation and Total')
+			and base_tax_amount_after_discount_amount != 0
 		group by parent, account_head, add_deduct_tax
 	""" % ', '.join(['%s']*len(invoice_list)), tuple([inv.name for inv in invoice_list]), as_dict=1)
 
diff --git a/erpnext/accounts/report/trial_balance/trial_balance.py b/erpnext/accounts/report/trial_balance/trial_balance.py
index 5df2a65..7142c69 100644
--- a/erpnext/accounts/report/trial_balance/trial_balance.py
+++ b/erpnext/accounts/report/trial_balance/trial_balance.py
@@ -51,8 +51,8 @@
 		filters.to_date = filters.year_end_date
 
 def get_data(filters):
-	accounts = frappe.db.sql("""select name, parent_account, account_name, root_type, report_type, lft, rgt
-		from `tabAccount` where company=%s order by lft""", filters.company, as_dict=True)
+	accounts = frappe.db.sql("""select name, parent_account, account_name, account_number, root_type, report_type, lft, rgt
+		from `tabAccount` where company=%s order by account_name, lft""", filters.company, as_dict=True)
 	company_currency = erpnext.get_company_currency(filters.company)
 
 	if not accounts:
@@ -175,6 +175,9 @@
 
 def prepare_data(accounts, filters, total_row, parent_children_map, company_currency):
 	data = []
+	tmpaccnt = sorted(accounts)
+	if not (accounts[0].account_number is None):
+		accounts = tmpaccnt
 	
 	for d in accounts:
 		has_value = False
diff --git a/erpnext/buying/doctype/purchase_order/purchase_order.py b/erpnext/buying/doctype/purchase_order/purchase_order.py
index 8075ab3..b448988 100644
--- a/erpnext/buying/doctype/purchase_order/purchase_order.py
+++ b/erpnext/buying/doctype/purchase_order/purchase_order.py
@@ -68,12 +68,16 @@
 			},
 			"Supplier Quotation Item": {
 				"ref_dn_field": "supplier_quotation_item",
-				"compare_fields": [["rate", "="], ["project", "="], ["item_code", "="], 
+				"compare_fields": [["project", "="], ["item_code", "="], 
 					["uom", "="], ["conversion_factor", "="]],
 				"is_child_table": True
 			}
 		})
 
+
+		if cint(frappe.db.get_single_value('Buying Settings', 'maintain_same_rate')):
+			self.validate_rate_with_reference_doc([["Supplier Quotation", "supplier_quotation", "supplier_quotation_item"]])
+
 	def validate_supplier(self):
 		prevent_po = frappe.db.get_value("Supplier", self.supplier, 'prevent_pos')
 		if prevent_po:
diff --git a/erpnext/buying/doctype/supplier/test_records.json b/erpnext/buying/doctype/supplier/test_records.json
index 370ce8d..2536721 100644
--- a/erpnext/buying/doctype/supplier/test_records.json
+++ b/erpnext/buying/doctype/supplier/test_records.json
@@ -8,7 +8,7 @@
  {
   "doctype": "Supplier",
   "supplier_name": "_Test Supplier P",
-  "supplier_type": "_Test Supplier Type",
+  "supplier_type": "_Test Supplier Type"
  },
  {
   "doctype": "Supplier",
diff --git a/erpnext/buying/doctype/supplier_quotation/supplier_quotation.py b/erpnext/buying/doctype/supplier_quotation/supplier_quotation.py
index c395d0c..b221a08 100644
--- a/erpnext/buying/doctype/supplier_quotation/supplier_quotation.py
+++ b/erpnext/buying/doctype/supplier_quotation/supplier_quotation.py
@@ -124,7 +124,8 @@
 				["name", "supplier_quotation_item"],
 				["parent", "supplier_quotation"],
 				["material_request", "material_request"],
-				["material_request_item", "material_request_item"]
+				["material_request_item", "material_request_item"],
+				["sales_order", "sales_order"]
 			],
 			"postprocess": update_item
 		},
diff --git a/erpnext/buying/doctype/supplier_quotation_item/supplier_quotation_item.json b/erpnext/buying/doctype/supplier_quotation_item/supplier_quotation_item.json
index b3a55b6..da78c12 100644
--- a/erpnext/buying/doctype/supplier_quotation_item/supplier_quotation_item.json
+++ b/erpnext/buying/doctype/supplier_quotation_item/supplier_quotation_item.json
@@ -1332,6 +1332,37 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
+   "fieldname": "sales_order", 
+   "fieldtype": "Link", 
+   "hidden": 0, 
+   "ignore_user_permissions": 0, 
+   "ignore_xss_filter": 0, 
+   "in_filter": 0, 
+   "in_global_search": 0, 
+   "in_list_view": 0, 
+   "in_standard_filter": 0, 
+   "label": "Sales Order", 
+   "length": 0, 
+   "no_copy": 0, 
+   "options": "Sales Order", 
+   "permlevel": 0, 
+   "precision": "", 
+   "print_hide": 1, 
+   "print_hide_if_no_value": 0, 
+   "read_only": 1, 
+   "remember_last_selected_value": 0, 
+   "report_hide": 0, 
+   "reqd": 0, 
+   "search_index": 1, 
+   "set_only_once": 0, 
+   "unique": 0
+  }, 
+  {
+   "allow_bulk_edit": 0, 
+   "allow_on_submit": 0, 
+   "bold": 0, 
+   "collapsible": 0, 
+   "columns": 0, 
    "fieldname": "request_for_quotation", 
    "fieldtype": "Link", 
    "hidden": 0, 
@@ -1614,7 +1645,7 @@
  "issingle": 0, 
  "istable": 1, 
  "max_attachments": 0, 
- "modified": "2017-12-14 09:37:47.427897", 
+ "modified": "2018-01-25 15:04:40.171617", 
  "modified_by": "Administrator", 
  "module": "Buying", 
  "name": "Supplier Quotation Item", 
diff --git a/erpnext/config/desktop.py b/erpnext/config/desktop.py
index ffe9996..18bb36b 100644
--- a/erpnext/config/desktop.py
+++ b/erpnext/config/desktop.py
@@ -283,7 +283,7 @@
 			"label": _("Education"),
 			"hidden": 1
 		},
-        {
+		{
 			"module_name": "Healthcare",
 			"color": "#FF888B",
 			"icon": "fa fa-heartbeat",
@@ -292,29 +292,14 @@
 			"hidden": 1
 		},
         {
-			"module_name": "Lab Test",
-			"color": "#7578f6",
-			"icon": "octicon octicon-beaker",
-			"doctype": "Lab Test",
-			"type": "list",
-			"link": "List/Lab Test",
-			"label": _("Lab Test")
-        },
-        {
-			"module_name": "Consultation",
-			"color": "#2ecc71",
-			"icon": "fa fa-stethoscope",
-			"doctype": "Consultation",
-			"type": "link",
-			"label": _("Consultationt")
-        },
-        {
 			"module_name": "Patient",
 			"color": "#6BE273",
 			"icon": "fa fa-user",
 			"doctype": "Patient",
 			"type": "link",
-			"label": _("Patient")
+			"link": "List/Patient",
+			"label": _("Patient"),
+			"hidden": 1
         },
         {
 			"module_name": "Patient Appointment",
@@ -322,7 +307,29 @@
 			"icon": "fa fa-calendar-plus-o",
 			"doctype": "Patient Appointment",
 			"type": "link",
-			"label": _("Patient Appointment")
+			"link": "List/Patient Appointment",
+			"label": _("Patient Appointment"),
+			"hidden": 1
+        },
+        {
+			"module_name": "Consultation",
+			"color": "#2ecc71",
+			"icon": "fa fa-stethoscope",
+			"doctype": "Consultation",
+			"type": "link",
+			"link": "List/Consultation",
+			"label": _("Consultation"),
+			"hidden": 1
+        },
+        {
+			"module_name": "Lab Test",
+			"color": "#7578f6",
+			"icon": "octicon octicon-beaker",
+			"doctype": "Lab Test",
+			"type": "list",
+			"link": "List/Lab Test",
+			"label": _("Lab Test"),
+			"hidden": 1
         },
 		{
 			"module_name": "Hub",
diff --git a/erpnext/config/projects.py b/erpnext/config/projects.py
index b97e097..ac11c7e 100644
--- a/erpnext/config/projects.py
+++ b/erpnext/config/projects.py
@@ -15,7 +15,7 @@
 				{
 					"type": "doctype",
 					"name": "Task",
-					"route": "Tree/Task",
+					"route": "List/Task",
 					"description": _("Project activity / task."),
 				},
 				{
diff --git a/erpnext/controllers/queries.py b/erpnext/controllers/queries.py
index 158aac0..fd7bdc7 100644
--- a/erpnext/controllers/queries.py
+++ b/erpnext/controllers/queries.py
@@ -257,7 +257,7 @@
 def get_batch_no(doctype, txt, searchfield, start, page_len, filters):
 	cond = ""
 	if filters.get("posting_date"):
-		cond = "and (ifnull(batch.expiry_date, '')='' or batch.expiry_date >= %(posting_date)s)"
+		cond = "and (batch.expiry_date is null or batch.expiry_date >= %(posting_date)s)"
 
 	batch_nos = None
 	args = {
diff --git a/erpnext/docs/assets/img/education/student/student group.gif b/erpnext/docs/assets/img/education/student/student-group.gif
similarity index 100%
rename from erpnext/docs/assets/img/education/student/student group.gif
rename to erpnext/docs/assets/img/education/student/student-group.gif
Binary files differ
diff --git a/erpnext/docs/user/manual/en/education/Assessment/assessment_criteria.md b/erpnext/docs/user/manual/en/education/Assessment/assessment_criteria.md
index b97cfb1..64183ad 100644
--- a/erpnext/docs/user/manual/en/education/Assessment/assessment_criteria.md
+++ b/erpnext/docs/user/manual/en/education/Assessment/assessment_criteria.md
@@ -10,4 +10,17 @@
 
 <img class="screenshot" alt="Assessment Plan Criteria" src="/docs/assets/img/education/assessment/assessment-plan-criteria.png">
 
+#### Video Tutorial on Assessment Criteria
+
+
+
+<div>
+    <style>.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; } .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
+    </style>
+    <div class='embed-container'>
+        <iframe src='https://www.youtube.com/embed/t8ZDDq4qtIk?end=52' frameborder='0' allowfullscreen>
+        </iframe>
+    </div>
+<div>
+
 {next}
\ No newline at end of file
diff --git a/erpnext/docs/user/manual/en/education/Assessment/assessment_criteria_group.md b/erpnext/docs/user/manual/en/education/Assessment/assessment_criteria_group.md
deleted file mode 100644
index 4287ca8..0000000
--- a/erpnext/docs/user/manual/en/education/Assessment/assessment_criteria_group.md
+++ /dev/null
@@ -1 +0,0 @@
-#
\ No newline at end of file
diff --git a/erpnext/docs/user/manual/en/education/Assessment/assessment_group.md b/erpnext/docs/user/manual/en/education/Assessment/assessment_group.md
index ed02a53..35e00ad 100644
--- a/erpnext/docs/user/manual/en/education/Assessment/assessment_group.md
+++ b/erpnext/docs/user/manual/en/education/Assessment/assessment_group.md
@@ -10,4 +10,17 @@
 
 <img class="screenshot" alt="Assessment Group Term" src="/docs/assets/img/education/assessment/assessment-group-details.png">
 
+#### Video Tutorial on Assessment Group
+
+
+
+<div>
+    <style>.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; } .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
+    </style>
+    <div class='embed-container'>
+        <iframe src='https://www.youtube.com/embed/I1T7Z2JbcP4' frameborder='0' allowfullscreen>
+        </iframe>
+    </div>
+<div>
+
 {next}
\ No newline at end of file
diff --git a/erpnext/docs/user/manual/en/education/Assessment/assessment_plan.md b/erpnext/docs/user/manual/en/education/Assessment/assessment_plan.md
index 7272279..8e08535 100644
--- a/erpnext/docs/user/manual/en/education/Assessment/assessment_plan.md
+++ b/erpnext/docs/user/manual/en/education/Assessment/assessment_plan.md
@@ -16,4 +16,17 @@
 
 <img class="screenshot" alt="Assessment Plan Criteria" src="/docs/assets/img/education/assessment/assessment-plan-criteria.png">
 
+#### Video Tutorial on Assessment Plan
+
+
+
+<div>
+    <style>.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; } .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
+    </style>
+    <div class='embed-container'>
+        <iframe src='https://www.youtube.com/embed/Q9CzzoYb_Js' frameborder='0' allowfullscreen>
+        </iframe>
+    </div>
+</div>    
+
 {next}
\ No newline at end of file
diff --git a/erpnext/docs/user/manual/en/education/Assessment/assessment_result.md b/erpnext/docs/user/manual/en/education/Assessment/assessment_result.md
index ed3e5fb..5547f22 100644
--- a/erpnext/docs/user/manual/en/education/Assessment/assessment_result.md
+++ b/erpnext/docs/user/manual/en/education/Assessment/assessment_result.md
@@ -4,4 +4,16 @@
 
 <img class="screenshot" alt="Assessment Result" src="/docs/assets/img/education/assessment/assessment-result.png">
 
+#### Video Tutorial on Assessment Result 
+
+
+<div>
+    <style>.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; } .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
+    </style>
+    <div class='embed-container'>
+        <iframe src='https://www.youtube.com/embed/U8ZRB8CM-UM?end=89' frameborder='0' allowfullscreen>
+        </iframe>
+    </div>
+</div>
+
 {next}
\ No newline at end of file
diff --git a/erpnext/docs/user/manual/en/education/Assessment/assessment_result_tool.md b/erpnext/docs/user/manual/en/education/Assessment/assessment_result_tool.md
index 88b7a7a..1cd0762 100644
--- a/erpnext/docs/user/manual/en/education/Assessment/assessment_result_tool.md
+++ b/erpnext/docs/user/manual/en/education/Assessment/assessment_result_tool.md
@@ -6,4 +6,17 @@
 
 As you go on entering marks for a Student, and switch to next student, in the backend, Student Result record will be auto-created for that Student.
 
+#### Video Tutorial on Assessment Result Tool
+
+
+
+<div>
+    <style>.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; } .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
+    </style>
+    <div class='embed-container'>
+        <iframe src='https://www.youtube.com/embed/U8ZRB8CM-UM?start=80' frameborder='0' allowfullscreen>
+        </iframe>
+    </div>
+</div>    
+
 {next}
diff --git a/erpnext/docs/user/manual/en/education/Assessment/grading_scale.md b/erpnext/docs/user/manual/en/education/Assessment/grading_scale.md
index 0ad610b..c3d8b21 100644
--- a/erpnext/docs/user/manual/en/education/Assessment/grading_scale.md
+++ b/erpnext/docs/user/manual/en/education/Assessment/grading_scale.md
@@ -4,4 +4,17 @@
 
 <img class="screenshot" alt="Grading Scale" src="/docs/assets/img/education/assessment/grading-scale.png">
 
+#### Video Tutorial on Grading Scale
+
+
+
+<div>
+    <style>.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; } .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
+    </style>
+    <div class='embed-container'>
+        <iframe src='https://www.youtube.com/embed/t8ZDDq4qtIk?start=52' frameborder='0' allowfullscreen>
+        </iframe>
+    </div>
+</div>
+
 {next}
\ No newline at end of file
diff --git a/erpnext/docs/user/manual/en/education/Attendance/index.txt b/erpnext/docs/user/manual/en/education/Attendance/index.txt
index 8cd0262..14ecda3 100644
--- a/erpnext/docs/user/manual/en/education/Attendance/index.txt
+++ b/erpnext/docs/user/manual/en/education/Attendance/index.txt
@@ -1,3 +1,3 @@
 student-attendance
-student-leave-application
-student-attendance-tool
\ No newline at end of file
+student-attendance-tool
+student-leave-application
\ No newline at end of file
diff --git a/erpnext/docs/user/manual/en/education/Attendance/student-attendance-tool.md b/erpnext/docs/user/manual/en/education/Attendance/student-attendance-tool.md
index fac9d6e..c68f473 100644
--- a/erpnext/docs/user/manual/en/education/Attendance/student-attendance-tool.md
+++ b/erpnext/docs/user/manual/en/education/Attendance/student-attendance-tool.md
@@ -12,4 +12,17 @@
 
 <img class="screenshot" alt="Student Attendance" src="/docs/assets/img/education/setup/student-attendance-tool.gif">
 
+#### Tutorial Video for Student Attendance Tool
+
+
+
+<div>
+  <style>.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; } .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
+  </style>
+  <div class='embed-container'>
+    <iframe src='https://www.youtube.com/embed//j9pgkPuyiaI?start=63' frameborder='0' allowfullscreen>
+    </iframe>
+  </div>
+<div>
+
 {next}
\ No newline at end of file
diff --git a/erpnext/docs/user/manual/en/education/Attendance/student-attendance.md b/erpnext/docs/user/manual/en/education/Attendance/student-attendance.md
index 4be2831..b931146 100644
--- a/erpnext/docs/user/manual/en/education/Attendance/student-attendance.md
+++ b/erpnext/docs/user/manual/en/education/Attendance/student-attendance.md
@@ -12,4 +12,17 @@
 
 **Student Attendance tool** can be used for bulk updation of the attendance based on **Batch, Course or Activity**.
 
+#### Tutorial Video on Student Attendance
+
+
+
+<div>
+    <style>.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; } .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
+    </style>
+    <div class='embed-container'>
+        <iframe src='https://www.youtube.com/embed//j9pgkPuyiaI' frameborder='0' allowfullscreen>
+        </iframe>
+    </div>
+</div>
+
 {next}
\ No newline at end of file
diff --git a/erpnext/docs/user/manual/en/education/Attendance/student-leave-application.md b/erpnext/docs/user/manual/en/education/Attendance/student-leave-application.md
index e22c6e9..011d07c 100644
--- a/erpnext/docs/user/manual/en/education/Attendance/student-leave-application.md
+++ b/erpnext/docs/user/manual/en/education/Attendance/student-leave-application.md
@@ -10,4 +10,17 @@
 
 Once a Leave Application is recorded for a student it will not be recorded in the absent student report as he has applied for a leave. 
 
+#### Tutorial Video for Student Leave Application
+
+
+
+<div>
+    <style>.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; } .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
+    </style>
+    <div class='embed-container'>
+        <iframe src='https://www.youtube.com/embed/NwwH5t-NKBE' frameborder='0' allowfullscreen>
+        </iframe>
+    </div>
+</div>
+
 {next}
\ No newline at end of file
diff --git a/erpnext/docs/user/manual/en/education/admission/program-enrollment-tool.md b/erpnext/docs/user/manual/en/education/admission/program-enrollment-tool.md
index 97a26c7..5727bc2 100644
--- a/erpnext/docs/user/manual/en/education/admission/program-enrollment-tool.md
+++ b/erpnext/docs/user/manual/en/education/admission/program-enrollment-tool.md
@@ -18,4 +18,16 @@
 
 For promoting the students, the new academic year, academic term and program can also be selected for the enrollment of the fetched students list.
 
+#### Video Tutorial for Program Enrollment Tool
+
+
+<div>
+    <style>.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; } .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
+    </style>
+    <div class='embed-container'>
+        <iframe src='https://www.youtube.com/embed//5nxWYBRHY_o?start=82' frameborder='0' allowfullscreen>
+        </iframe>
+    </div>
+</div>    
+
 {next}
\ No newline at end of file
diff --git a/erpnext/docs/user/manual/en/education/admission/program-enrollment.md b/erpnext/docs/user/manual/en/education/admission/program-enrollment.md
index 6fe9692..36af3f2 100644
--- a/erpnext/docs/user/manual/en/education/admission/program-enrollment.md
+++ b/erpnext/docs/user/manual/en/education/admission/program-enrollment.md
@@ -17,5 +17,15 @@
 
 Student Category: For the Institutions having multiple Fees Structure, this field can be used to differentiate the student enrollment in a given fee category. 
 
+#### Video Tutorial For Program Enrollment
 
-{next}
\ No newline at end of file
+
+<div>
+    <style>.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; } .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }</style>
+    <div class='embed-container'>
+        <iframe src='https://www.youtube.com/embed//5nxWYBRHY_o?start=0&end=88' frameborder='0' allowfullscreen>
+        </iframe>
+    </div>
+</div>
+
+{next}
diff --git a/erpnext/docs/user/manual/en/education/admission/student-applicant.md b/erpnext/docs/user/manual/en/education/admission/student-applicant.md
index 121844c..fa1b4c2 100644
--- a/erpnext/docs/user/manual/en/education/admission/student-applicant.md
+++ b/erpnext/docs/user/manual/en/education/admission/student-applicant.md
@@ -27,4 +27,16 @@
 
 <img class="screenshot" alt="Student Applicant Enrollment" src="/docs/assets/img/education/admission/student-applicant-enroll.png">
 
+#### Video Tutorial for Student Application
+
+
+
+<div>
+	<style>.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; } .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }</style>
+	<div class='embed-container'>
+		<iframe src='https://www.youtube.com/embed/l8PUACusN3E' frameborder='0' allowfullscreen>
+		</iframe>
+	</div>
+</div>
+
 {next}
diff --git a/erpnext/docs/user/manual/en/education/fees/fee-structure.md b/erpnext/docs/user/manual/en/education/fees/fee-structure.md
index 2131c4a..76d43a4 100644
--- a/erpnext/docs/user/manual/en/education/fees/fee-structure.md
+++ b/erpnext/docs/user/manual/en/education/fees/fee-structure.md
@@ -20,4 +20,16 @@
 
 If you are going to use this in the Fee Schedule, you must select the Accounts carefully as Fee Schedule updates the respected Accounts in bulk. 
 
+#### Video Tutorial for Fee Structure
+
+
+<div>
+    <style>.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; } .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
+    </style>
+    <div class='embed-container'>
+        <iframe src='https://www.youtube.com/embed//_ZkvyVnWgYk' frameborder='0' allowfullscreen>
+        </iframe>
+    </div>
+</div>
+
 {next}
\ No newline at end of file
diff --git a/erpnext/docs/user/manual/en/education/schedule/course-schedule.md b/erpnext/docs/user/manual/en/education/schedule/course-schedule.md
index f5134d5..8b8a36e 100644
--- a/erpnext/docs/user/manual/en/education/schedule/course-schedule.md
+++ b/erpnext/docs/user/manual/en/education/schedule/course-schedule.md
@@ -5,6 +5,18 @@
 
 <img class="screenshot" alt="Course Schedule" src="/docs/assets/img/education/schedule/course-schedule.png">
 
+#### Video Tutorial on Course Scheduling
+
+
+<div>
+    <style>.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; } .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
+    </style>
+    <div class='embed-container'>
+        <iframe src='https://www.youtube.com/embed/iy-DBV9jI-A?start=0&end=114' frameborder='0' allowfullscreen>
+        </iframe>
+    </div>
+</div>
+
 ### Marking Attendance
 
 You can mark attendance for a Student Group against a Course Schedule.
diff --git a/erpnext/docs/user/manual/en/education/schedule/scheduling-tool.md b/erpnext/docs/user/manual/en/education/schedule/scheduling-tool.md
index 08a7fa9..087c933 100644
--- a/erpnext/docs/user/manual/en/education/schedule/scheduling-tool.md
+++ b/erpnext/docs/user/manual/en/education/schedule/scheduling-tool.md
@@ -20,4 +20,14 @@
 - Check the 'Reschedule' checkbox and then click 'Schedule Course' button.
 - System will delete existing Course Schedules for specified Course within the mentioned Course Start Date and Course End Date and crate new Course Schedules.
 
+#### Video Tutorial on Scheduling Tool
+
+<div>
+    <style>.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; } .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }</style>
+    <div class='embed-container'>
+        <iframe src='https://www.youtube.com/embed/iy-DBV9jI-A?start=114' frameborder='0' allowfullscreen>
+        </iframe>
+    </div>
+</div>    
+
 {next}
diff --git a/erpnext/docs/user/manual/en/education/setup/course.md b/erpnext/docs/user/manual/en/education/setup/course.md
index 0d6e5ac..ec7d813 100644
--- a/erpnext/docs/user/manual/en/education/setup/course.md
+++ b/erpnext/docs/user/manual/en/education/setup/course.md
@@ -12,4 +12,18 @@
 
 The Course form is further linked to **Program, Student Group and Assessment Plan** doctypes. The links allow to view/create the related documents for a **Course**.
 
+#### Video Tutorial for Course
+
+
+
+<div>
+    <style>.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; } .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
+    </style>   
+    <div class='embed-container'>
+        <iframe src='https://www.youtube.com/embed//1ueE4seFTp8?start=66' frameborder='0' allowfullscreen>
+        </iframe>
+    </div>
+</div>    
+
+
 {next}
\ No newline at end of file
diff --git a/erpnext/docs/user/manual/en/education/setup/instructor.md b/erpnext/docs/user/manual/en/education/setup/instructor.md
index 219413d..5af4cc0 100644
--- a/erpnext/docs/user/manual/en/education/setup/instructor.md
+++ b/erpnext/docs/user/manual/en/education/setup/instructor.md
@@ -16,5 +16,16 @@
 
 Further, the log for the Instructor can be entered in the Instructor Log table which can be used for keeping the records of subjects taught by that Instructor.
 
+#### Video Tutorial for Instructor
+
+
+<div>
+    <style>.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; } .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
+    </style>
+    <div class='embed-container'>
+        <iframe src='https://www.youtube.com/embed//rVqQYS1_02k' frameborder='0' allowfullscreen>
+        </iframe>
+    </div>
+</div>
 
 {next}
\ No newline at end of file
diff --git a/erpnext/docs/user/manual/en/education/setup/program.md b/erpnext/docs/user/manual/en/education/setup/program.md
index 25e390e..0d2a4d2 100644
--- a/erpnext/docs/user/manual/en/education/setup/program.md
+++ b/erpnext/docs/user/manual/en/education/setup/program.md
@@ -4,7 +4,7 @@
 
 To create a Program go to :
 
-###education >> Setup >> Program >> New Program
+> Education > Setup > Program > New Program
 
 Enter a unique code for every **Program**. You can also link the **Program** to the department under which it is conducted.
 
@@ -16,4 +16,16 @@
 
 The Program Doctype is further linked to the **Student applicant**, **Program enrollment, Student group, Fee structre and Fee**. The links allow to view or create the related document for a Program.
 
+#### Video Tutorial on Program and Courses
+
+
+<div>
+    <style>.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; } .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
+    </style>   
+    <div class='embed-container'>
+        <iframe src='https://www.youtube.com/embed//1ueE4seFTp8?end=70' frameborder='0' allowfullscreen>
+        </iframe>
+    </div>
+</div>    
+
 {next}
\ No newline at end of file
diff --git a/erpnext/docs/user/manual/en/education/setup/school-settings.md b/erpnext/docs/user/manual/en/education/setup/school-settings.md
index 44f9c44..74e5ed5 100644
--- a/erpnext/docs/user/manual/en/education/setup/school-settings.md
+++ b/erpnext/docs/user/manual/en/education/setup/school-settings.md
@@ -2,7 +2,7 @@
 
 The Education Settings page allow you to setup basic settings like **Academic Year and Term** for the educational setup. 
 
-<img class="screenshot" alt="Student" src="/docs/assets/img/education/student/education.png">
+<img class="screenshot" alt="Student" src="/docs/assets/img/education/student/schools-settings.png">
 
 The checkbox to Validate Batch for Students in Student Group enables the Student Batch validation for every Student from the Program Enrollment for the **Batch** based on **Student Group** 
 
diff --git a/erpnext/docs/user/manual/en/education/student/student-group-creation-tool.md b/erpnext/docs/user/manual/en/education/student/student-group-creation-tool.md
index aeedd97..d27f4f7 100644
--- a/erpnext/docs/user/manual/en/education/student/student-group-creation-tool.md
+++ b/erpnext/docs/user/manual/en/education/student/student-group-creation-tool.md
@@ -4,7 +4,7 @@
 
 To create Student group using this tool go to 
 
-##education >>Student >> Student Group creation tool
+> Education > Student > Student Group creation tool
 
 Select the **Academic Term** and the **Program** for which a student group is to be created. 
 
@@ -14,4 +14,16 @@
 
 You can leave it unchecked if you don't want to consider batch while making course based groups.
 
+#### Tutorial Video on Student Group Creation Tool
+
+
+<div>
+    <style>.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; } .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
+    </style> 
+    <div class='embed-container'>
+        <iframe src='https://www.youtube.com/embed/5K_smeeE1Q4?start=108' frameborder='0' allowfullscreen>
+        </iframe>
+    </div>
+</div>
+
 {next}
\ No newline at end of file
diff --git a/erpnext/docs/user/manual/en/education/student/student-group.md b/erpnext/docs/user/manual/en/education/student/student-group.md
index 467fb3e..be68df1 100644
--- a/erpnext/docs/user/manual/en/education/student/student-group.md
+++ b/erpnext/docs/user/manual/en/education/student/student-group.md
@@ -6,9 +6,9 @@
 
 To create a Student Group go to:
 
-education >> Student >> New Student Group 
+> Education > Student > New Student Group 
 
-<img class="screenshot" alt="Student Group" src="/docs/assets/img/education/student/Student-group.gif">
+<img class="screenshot" alt="Student Group" src="/docs/assets/img/education/student/student-group.gif">
 
 To create a Student group based on **Batch**, select the **Progam** and **Batch**, where as to create a Student group based on **Course**, you will only have to select the Course Code. Creating a student group based on activity allows you to group of student for events and activities happening in the institute. 
 
@@ -18,5 +18,18 @@
 
 You can also update the **Email Group** for the Student Group. Click on Update Email Group to add all the email ids of the gaurdians in the respective email group and **Newsletter** can be created and sent to the Email group.
 
+#### Tutorial Video on Student Groups
+
+
+
+<div>
+    <style>.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; } .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
+    </style>
+    <div class='embed-container'>       
+        <iframe src='https://www.youtube.com/embed/QILiHiTD3uc'
+        frameborder='0' allowfullscreen>
+        </iframe>
+    </div> 
+</div>
 
 {next}
\ No newline at end of file
diff --git a/erpnext/docs/user/manual/en/education/student/student.md b/erpnext/docs/user/manual/en/education/student/student.md
index fce5d7b..9799e80 100644
--- a/erpnext/docs/user/manual/en/education/student/student.md
+++ b/erpnext/docs/user/manual/en/education/student/student.md
@@ -4,9 +4,21 @@
 The Student doctype maintains detials like personal information, date of birth, address etc. It also records the **Guardian** and sibling details. 
 
 <img class="screenshot" alt="Student" src="/docs/assets/img/education/student/student.png">
+
 The student is enrolled in a **Program** when the application is approved. Once the enrollement is done the **Student Applicant** status is update to Admitted.
 
 You can view every doctype created for a particular student. Eg : Fees, Student Group, etc
 
+#### Video Tutorial on Student Management
+
+
+<div>
+    <style>.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; } .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
+    </style>
+    <div class='embed-container'>
+        <iframe src='https://www.youtube.com/embed//nIUsbl0rEE0' frameborder='0' allowfullscreen>
+        </iframe>
+    </div>
+</div>    
 
 {next}
\ No newline at end of file
diff --git a/erpnext/education/doctype/guardian/guardian.py b/erpnext/education/doctype/guardian/guardian.py
index 3741a06..e82cc54 100644
--- a/erpnext/education/doctype/guardian/guardian.py
+++ b/erpnext/education/doctype/guardian/guardian.py
@@ -37,7 +37,6 @@
 		frappe.throw(_("Please set Email Address"))
 	else:
 		guardian_as_user = frappe.get_value('User', dict(email=guardian_doc.email_address))
-		print guardian_as_user
 		if guardian_as_user:
 			frappe.msgprint(_("User {0} already exists").format(getlink("User", guardian_as_user)))
 			return guardian_as_user
diff --git a/erpnext/healthcare/doctype/healthcare_settings/healthcare_settings.py b/erpnext/healthcare/doctype/healthcare_settings/healthcare_settings.py
index 7206e4b..0d3d6e7 100644
--- a/erpnext/healthcare/doctype/healthcare_settings/healthcare_settings.py
+++ b/erpnext/healthcare/doctype/healthcare_settings/healthcare_settings.py
@@ -9,60 +9,60 @@
 import json
 
 class HealthcareSettings(Document):
-	def validate(self):
-		for key in ["collect_registration_fee","manage_customer","patient_master_name",
-		"require_test_result_approval","require_sample_collection", "default_medical_code_standard"]:
-			frappe.db.set_default(key, self.get(key, ""))
-		if(self.collect_registration_fee):
-			if self.registration_fee <= 0 :
-				frappe.throw("Registration fee can not be Zero")
+    def validate(self):
+        for key in ["collect_registration_fee","manage_customer","patient_master_name",
+        "require_test_result_approval","require_sample_collection", "default_medical_code_standard"]:
+            frappe.db.set_default(key, self.get(key, ""))
+        if(self.collect_registration_fee):
+            if self.registration_fee <= 0 :
+                frappe.throw("Registration fee can not be Zero")
 
 @frappe.whitelist()
 def get_sms_text(doc):
-	sms_text = {}
-	doc = frappe.get_doc("Lab Test",doc)
-	#doc = json.loads(doc)
-	context = {"doc": doc, "alert": doc, "comments": None}
-	emailed = frappe.db.get_value("Healthcare Settings", None, "sms_emailed")
-	sms_text['emailed'] = frappe.render_template(emailed, context)
- 	printed = frappe.db.get_value("Healthcare Settings", None, "sms_printed")
-	sms_text['printed'] = frappe.render_template(printed, context)
-	return sms_text
+    sms_text = {}
+    doc = frappe.get_doc("Lab Test",doc)
+    #doc = json.loads(doc)
+    context = {"doc": doc, "alert": doc, "comments": None}
+    emailed = frappe.db.get_value("Healthcare Settings", None, "sms_emailed")
+    sms_text['emailed'] = frappe.render_template(emailed, context)
+    printed = frappe.db.get_value("Healthcare Settings", None, "sms_printed")
+    sms_text['printed'] = frappe.render_template(printed, context)
+    return sms_text
 
 def send_registration_sms(doc):
-	if (frappe.db.get_value("Healthcare Settings", None, "reg_sms")=='1'):
-		if doc.mobile:
-			context = {"doc": doc, "alert": doc, "comments": None}
-			if doc.get("_comments"):
-				context["comments"] = json.loads(doc.get("_comments"))
-			messages = frappe.db.get_value("Healthcare Settings", None, "reg_msg")
-			messages = frappe.render_template(messages, context)
-			number = [doc.mobile]
-			send_sms(number,messages)
-		else:
-			frappe.msgprint(doc.name + " Has no mobile number to send registration SMS", alert=True)
+    if (frappe.db.get_value("Healthcare Settings", None, "reg_sms")=='1'):
+        if doc.mobile:
+            context = {"doc": doc, "alert": doc, "comments": None}
+            if doc.get("_comments"):
+                context["comments"] = json.loads(doc.get("_comments"))
+            messages = frappe.db.get_value("Healthcare Settings", None, "reg_msg")
+            messages = frappe.render_template(messages, context)
+            number = [doc.mobile]
+            send_sms(number,messages)
+        else:
+            frappe.msgprint(doc.name + " Has no mobile number to send registration SMS", alert=True)
 
 
 def get_receivable_account(company):
-	receivable_account = get_account(None, "receivable_account", "Healthcare Settings", company)
-	if receivable_account:
-		return receivable_account
-	return frappe.db.get_value("Company", company, "default_receivable_account")
+    receivable_account = get_account(None, "receivable_account", "Healthcare Settings", company)
+    if receivable_account:
+        return receivable_account
+    return frappe.db.get_value("Company", company, "default_receivable_account")
 
 def get_income_account(physician, company):
-	if(physician):
-		income_account = get_account("Physician", None, physician, company)
-		if income_account:
-			return income_account
-	income_account = get_account(None, "income_account", "Healthcare Settings", company)
-	if income_account:
-		return income_account
-	return frappe.db.get_value("Company", company, "default_income_account")
+    if(physician):
+        income_account = get_account("Physician", None, physician, company)
+        if income_account:
+            return income_account
+    income_account = get_account(None, "income_account", "Healthcare Settings", company)
+    if income_account:
+        return income_account
+    return frappe.db.get_value("Company", company, "default_income_account")
 
 def get_account(parent_type, parent_field, parent, company):
-	if(parent_type):
-		return frappe.db.get_value("Party Account",
-			{"parenttype": parent_type, "parent": parent, "company": company}, "account")
-	if(parent_field):
-		return frappe.db.get_value("Party Account",
-			{"parentfield": parent_field, "parent": parent, "company": company}, "account")
+    if(parent_type):
+        return frappe.db.get_value("Party Account",
+            {"parenttype": parent_type, "parent": parent, "company": company}, "account")
+    if(parent_field):
+        return frappe.db.get_value("Party Account",
+            {"parentfield": parent_field, "parent": parent, "company": company}, "account")
diff --git a/erpnext/hooks.py b/erpnext/hooks.py
index ebc1921..45abbdb 100644
--- a/erpnext/hooks.py
+++ b/erpnext/hooks.py
@@ -204,7 +204,7 @@
 	'Address': {
 		'validate': 'erpnext.regional.india.utils.validate_gstin_for_india'
 	},
-	'Sales Invoice': {
+	('Sales Invoice', 'Purchase Invoice'): {
 		'validate': 'erpnext.regional.india.utils.set_place_of_supply'
 	}
 }
diff --git a/erpnext/manufacturing/doctype/bom/bom.py b/erpnext/manufacturing/doctype/bom/bom.py
index a06645a..2e69475 100644
--- a/erpnext/manufacturing/doctype/bom/bom.py
+++ b/erpnext/manufacturing/doctype/bom/bom.py
@@ -544,7 +544,7 @@
 				group by item_code, stock_uom
 				order by idx"""
 
-	if fetch_exploded:
+	if cint(fetch_exploded):
 		query = query.format(table="BOM Explosion Item",
 			where_conditions="",
 			select_columns = ", bom_item.source_warehouse, (Select idx from `tabBOM Item` where item_code = bom_item.item_code and parent = %(parent)s ) as idx")
@@ -592,7 +592,7 @@
 
 @frappe.whitelist()
 def get_children(doctype, parent=None, is_root=False, **filters):
-	if not parent:
+	if not parent or parent=="BOM":
 		frappe.msgprint(_('Please select a BOM'))
 		return
 
diff --git a/erpnext/manufacturing/doctype/bom/bom_tree.js b/erpnext/manufacturing/doctype/bom/bom_tree.js
index 854f633..6cbd7a2 100644
--- a/erpnext/manufacturing/doctype/bom/bom_tree.js
+++ b/erpnext/manufacturing/doctype/bom/bom_tree.js
@@ -11,7 +11,8 @@
 	title: "BOM",
 	breadcrumb: "Manufacturing",
 	disable_add_node: true,
-	root_label: "All Bill of Materials", //fieldname from filters
+	root_label: "BOM", //fieldname from filters
+	get_tree_root: false,
 	get_label: function(node) {
 		if(node.data.qty) {
 			return node.data.qty + " x " + node.data.item_code;
@@ -19,6 +20,23 @@
 			return node.data.item_code || node.data.value;
 		}
 	},
+	onload: function(me) {
+		var label = frappe.get_route()[0] + "/" + frappe.get_route()[1];
+		if(frappe.pages[label]) {
+			delete frappe.pages[label];
+		}
+
+		var filter = me.opts.filters[0];
+		if(frappe.route_options && frappe.route_options[filter.fieldname]) {
+			var val = frappe.route_options[filter.fieldname];
+			delete frappe.route_options[filter.fieldname];
+			filter.default = "";
+			me.args[filter.fieldname] = val;
+			me.root_label = val;
+			me.page.set_title(val);
+		}
+		me.make_tree();
+	},
 	toolbar: [
 		{ toggle_btn: true },
 		{
diff --git a/erpnext/manufacturing/doctype/production_order/production_order.py b/erpnext/manufacturing/doctype/production_order/production_order.py
index 7cfbab0..d3b7c5a 100644
--- a/erpnext/manufacturing/doctype/production_order/production_order.py
+++ b/erpnext/manufacturing/doctype/production_order/production_order.py
@@ -490,7 +490,7 @@
 					and detail.parent = entry.name
 					and detail.item_code = %s''', (self.name, d.item_code))[0][0]
 
-			d.db_set('transferred_qty', transferred_qty, update_modified = False)
+			d.db_set('transferred_qty', flt(transferred_qty), update_modified = False)
 
 
 @frappe.whitelist()
diff --git a/erpnext/patches.txt b/erpnext/patches.txt
index 74f90a8..6f4c63e 100644
--- a/erpnext/patches.txt
+++ b/erpnext/patches.txt
@@ -345,7 +345,7 @@
 erpnext.patches.v7_1.set_prefered_contact_email
 execute:frappe.reload_doc('accounts', 'doctype', 'accounts_settings')
 execute:frappe.db.set_value("Accounts Settings", "Accounts Settings", "unlink_payment_on_cancellation_of_invoice", 0)
-execute:frappe.db.sql("update `tabStock Entry` set total_amount = null where purpose in('Repack', 'Manufacture')")
+execute:frappe.db.sql("update `tabStock Entry` set total_amount = 0 where purpose in('Repack', 'Manufacture')")
 erpnext.patches.v7_1.save_stock_settings
 erpnext.patches.v7_0.repost_gle_for_pi_with_update_stock #2016-11-01
 erpnext.patches.v7_1.add_account_user_role_for_timesheet
@@ -491,4 +491,5 @@
 erpnext.patches.v10_0.added_extra_gst_custom_field
 erpnext.patches.v10_0.workflow_leave_application #2018-01-24
 erpnext.patches.v10_0.set_default_payment_terms_based_on_company
+erpnext.patches.v10_0.update_sales_order_link_to_purchase_order
 erpnext.patches.v10_0.added_extra_gst_custom_field_in_gstr2
diff --git a/erpnext/patches/v10_0/update_sales_order_link_to_purchase_order.py b/erpnext/patches/v10_0/update_sales_order_link_to_purchase_order.py
new file mode 100644
index 0000000..b4f5838
--- /dev/null
+++ b/erpnext/patches/v10_0/update_sales_order_link_to_purchase_order.py
@@ -0,0 +1,18 @@
+# License: GNU General Public License v3. See license.txt
+
+from __future__ import unicode_literals
+import frappe
+
+def execute():
+	frappe.reload_doc("buying", "doctype", "supplier_quotation_item")
+
+	for doctype in ['Purchase Order','Supplier Quotation']:
+		frappe.db.sql("""
+			Update
+				`tab{doctype} Item`, `tabMaterial Request Item`
+			set
+				`tab{doctype} Item`.sales_order = `tabMaterial Request Item`.sales_order
+			where
+				`tab{doctype} Item`.material_request= `tabMaterial Request Item`.parent
+				and `tab{doctype} Item`.material_request_item = `tabMaterial Request Item`.name
+				and `tabMaterial Request Item`.sales_order is not null""".format(doctype=doctype))
\ No newline at end of file
diff --git a/erpnext/patches/v7_0/update_status_of_po_so.py b/erpnext/patches/v7_0/update_status_of_po_so.py
index c0b6f59..d630e8f 100644
--- a/erpnext/patches/v7_0/update_status_of_po_so.py
+++ b/erpnext/patches/v7_0/update_status_of_po_so.py
@@ -20,7 +20,10 @@
 					where parent = `tabPurchase Order`.name), 2),
 			`tabPurchase Order`.per_billed = ifnull(round((select sum( if(amount > ifnull(billed_amt, 0),
 					ifnull(billed_amt, 0), amount)) / sum(amount) *100 from `tabPurchase Order Item`
-					where parent = `tabPurchase Order`.name), 2), 0)""")
+					where parent = `tabPurchase Order`.name), 2), 0)
+		where
+			net_total > 0
+	""")
 
 def update_so_per_delivered_per_billed():
 	frappe.db.sql(""" 
@@ -32,7 +35,10 @@
 					where parent = `tabSales Order`.name), 2), 
 			`tabSales Order`.per_billed = ifnull(round((select sum( if(amount > ifnull(billed_amt, 0),
 					ifnull(billed_amt, 0), amount)) / sum(amount) *100 from `tabSales Order Item`
-					where parent = `tabSales Order`.name), 2), 0)""")
+					where parent = `tabSales Order`.name), 2), 0)
+		where
+			net_total > 0
+	""")
 
 def update_status():
 	frappe.db.sql("""
diff --git a/erpnext/patches/v7_1/set_currency_exchange_date.py b/erpnext/patches/v7_1/set_currency_exchange_date.py
index 7d8e4f0..630b7d4 100644
--- a/erpnext/patches/v7_1/set_currency_exchange_date.py
+++ b/erpnext/patches/v7_1/set_currency_exchange_date.py
@@ -5,5 +5,5 @@
 	frappe.db.sql("""
 		update `tabCurrency Exchange` 
 		set `date` = '2010-01-01' 
-		where date is null or date = '' or date = '0000-00-00'
+		where date is null or date = '0000-00-00'
 	""")
\ No newline at end of file
diff --git a/erpnext/patches/v7_2/rename_att_date_attendance.py b/erpnext/patches/v7_2/rename_att_date_attendance.py
index f7caf70..b2658ba 100644
--- a/erpnext/patches/v7_2/rename_att_date_attendance.py
+++ b/erpnext/patches/v7_2/rename_att_date_attendance.py
@@ -7,7 +7,7 @@
 	frappe.reload_doc("hr", "doctype", "attendance")
 	frappe.db.sql("""update `tabAttendance` 
 	 		set attendance_date = att_date
-			where attendance_date is null or attendance_date = '' or attendance_date = '0000-00-00'""")
+			where attendance_date is null or attendance_date = '0000-00-00'""")
 	
 	update_reports("Attendance", "att_date", "attendance_date")
 	update_users_report_view_settings("Attendance", "att_date", "attendance_date")
diff --git a/erpnext/patches/v7_2/update_salary_slips.py b/erpnext/patches/v7_2/update_salary_slips.py
index 22bb1d8..c6bca8e 100644
--- a/erpnext/patches/v7_2/update_salary_slips.py
+++ b/erpnext/patches/v7_2/update_salary_slips.py
@@ -9,8 +9,7 @@
 
 	salary_slips = frappe.db.sql("""select month, name, fiscal_year from `tabSalary Slip`
 				where (month is not null and month != '') and
-				(start_date is null  or start_date = '') and
-				(end_date is null  or end_date = '') and docstatus != 2""", as_dict=True)
+				start_date is null and end_date is null and docstatus != 2""", as_dict=True)
 
 	for salary_slip in salary_slips:
 		if not cint(salary_slip.month):
diff --git a/erpnext/patches/v8_1/set_delivery_date_in_so_item.py b/erpnext/patches/v8_1/set_delivery_date_in_so_item.py
index aa5cbc5..2e81571 100644
--- a/erpnext/patches/v8_1/set_delivery_date_in_so_item.py
+++ b/erpnext/patches/v8_1/set_delivery_date_in_so_item.py
@@ -8,7 +8,7 @@
 		frappe.db.sql("""
 			update `tabSales Order`
 			set delivery_date = final_delivery_date
-			where (delivery_date is null or delivery_date = '' or delivery_date = '0000-00-00')
+			where (delivery_date is null or delivery_date = '0000-00-00')
 				and order_type = 'Sales'""")
 
 	frappe.db.sql("""
@@ -16,8 +16,6 @@
 		set so_item.delivery_date = so.delivery_date
 		where so.name = so_item.parent
 			and so.order_type = 'Sales'
-			and (so_item.delivery_date is null or so_item.delivery_date = ''
-				or so_item.delivery_date = '0000-00-00')
-			and (so.delivery_date is not null and so.delivery_date != ''
-				and so.delivery_date != '0000-00-00')
-	""")
+			and (so_item.delivery_date is null or so_item.delivery_date = '0000-00-00')
+			and (so.delivery_date is not null and so.delivery_date != '0000-00-00')
+	""")
\ No newline at end of file
diff --git a/erpnext/public/js/payment/payments.js b/erpnext/public/js/payment/payments.js
index 77209e0..0d656bc 100644
--- a/erpnext/public/js/payment/payments.js
+++ b/erpnext/public/js/payment/payments.js
@@ -27,8 +27,14 @@
 		var me = this;
 	
 		this.dialog.set_primary_action(__("Submit"), function() {
-			me.dialog.hide()
-			me.submit_invoice()
+			// Allow no ZERO payment
+			$.each(me.frm.doc.payments, function (index, data) {
+				if (data.amount != 0) {
+					me.dialog.hide();
+					me.submit_invoice();
+					return;
+				}
+			});
 		})
 	},
 
diff --git a/erpnext/regional/india/setup.py b/erpnext/regional/india/setup.py
index 9243859..fa0a448 100644
--- a/erpnext/regional/india/setup.py
+++ b/erpnext/regional/india/setup.py
@@ -94,7 +94,6 @@
 		dict(fieldname='reverse_charge', label='Reverse Charge',
 			fieldtype='Select', insert_after='invoice_copy', print_hide=1,
 			options='Y\nN', default='N'),
-		dict(fieldname='gst_col_break', fieldtype='Column Break', insert_after='reverse_charge'),
 		dict(fieldname='invoice_type', label='Invoice Type',
 			fieldtype='Select', insert_after='gst_col_break', print_hide=1,
 			options='Regular\nSEZ\nExport\nDeemed Export', default='Regular'),
@@ -104,10 +103,11 @@
 			options='\nWith Payment of Tax\nWithout Payment of Tax'),
 		dict(fieldname='ecommerce_gstin', label='E-commerce GSTIN',
 			fieldtype='Data', insert_after='export_type', print_hide=1),
+		dict(fieldname='gst_col_break', fieldtype='Column Break', insert_after='reason_for_issuing_document'),
 		dict(fieldname='reason_for_issuing_document', label='Reason For Issuing document',
-			fieldtype='Select', insert_after='ecommerce_gstin', print_hide=1,
-			depends_on='eval:doc.is_return==1',
-			options='\n01-Sales Return\n02-Post Sale Discount\n03-Deficiency in services\n04-Correction in Invoice\n05-Change in POS\n06-Finalization of Provisional assessment\n07-Others')
+			fieldtype='Select', insert_after='gst_col_break', print_hide=1,
+			depends_on='eval:doc.is_return==1', reqd=1,
+			options='\n01-Sales Return\n02-Post Sale Discount\n03-Deficiency in services\n04-Correction in Invoice\n05-Change in POS\n06-Finalization of Provisional assessment\n07-Others', default='01-Sales Return')
 	]
 
 	purchase_invoice_gst_fields = [
@@ -117,6 +117,9 @@
 			dict(fieldname='company_gstin', label='Company GSTIN',
 				fieldtype='Data', insert_after='shipping_address',
 				options='shipping_address.gstin', print_hide=1),
+			dict(fieldname='place_of_supply', label='Place of Supply',
+				fieldtype='Data', insert_after='shipping_address',
+				print_hide=1, read_only=0),
 			dict(fieldname='eligibility_for_itc', label='Eligibility For ITC',
 				fieldtype='Select', insert_after='reason_for_issuing_document', print_hide=1,
 				options='input\ninput service\ncapital goods\nineligible', default="ineligible"),
@@ -163,8 +166,8 @@
 			dict(fieldname='gst_state_number', label='GST State Number',
 				fieldtype='Int', insert_after='gst_state', read_only=1),
 		],
-		'Purchase Invoice': purchase_invoice_gst_fields + invoice_gst_fields,
-		'Sales Invoice': sales_invoice_gst_fields + invoice_gst_fields,
+		'Purchase Invoice': invoice_gst_fields + purchase_invoice_gst_fields,
+		'Sales Invoice': invoice_gst_fields + sales_invoice_gst_fields,
 		"Delivery Note": sales_invoice_gst_fields,
 		'Item': [
 			dict(fieldname='gst_hsn_code', label='HSN/SAC',
diff --git a/erpnext/regional/india/utils.py b/erpnext/regional/india/utils.py
index fb421fb..1b91218 100644
--- a/erpnext/regional/india/utils.py
+++ b/erpnext/regional/india/utils.py
@@ -64,7 +64,11 @@
 def set_place_of_supply(doc, method):
 	if not frappe.get_meta('Address').has_field('gst_state'): return
 
-	address_name = doc.shipping_address_name or doc.customer_address
+	if doc.doctype == "Sales Invoice":
+		address_name = doc.shipping_address_name or doc.customer_address
+	elif doc.doctype == "Purchase Invoice":
+		address_name = doc.shipping_address or doc.supplier_address
+
 	if address_name:
 		address = frappe.db.get_value("Address", address_name, ["gst_state", "gst_state_number"], as_dict=1)
 		doc.place_of_supply = cstr(address.gst_state_number) + "-" + cstr(address.gst_state)
diff --git a/erpnext/regional/report/gstr_1/gstr_1.py b/erpnext/regional/report/gstr_1/gstr_1.py
index b6df878..1ad673f 100644
--- a/erpnext/regional/report/gstr_1/gstr_1.py
+++ b/erpnext/regional/report/gstr_1/gstr_1.py
@@ -12,15 +12,32 @@
 class Gstr1Report(object):
 	def __init__(self, filters=None):
 		self.filters = frappe._dict(filters or {})
+		self.doctype = "Sales Invoice"
+		self.tax_doctype = "Sales Taxes and Charges"
+		self.select_columns = """
+			name as invoice_number,
+			customer_name,
+			posting_date,
+			base_grand_total,
+			base_rounded_total,
+			customer_gstin,
+			place_of_supply,
+			ecommerce_gstin,
+			reverse_charge,
+			invoice_type,
+			return_against,
+			is_return,
+			invoice_type,
+			export_type,
+			port_code,
+			shipping_bill_number,
+			shipping_bill_date,
+			reason_for_issuing_document
+		"""
 		self.customer_type = "Company" if self.filters.get("type_of_business") ==  "B2B" else "Individual"
 
 	def run(self):
 		self.get_columns()
-		self.get_data()
-		return self.columns, self.data
-
-	def get_data(self):
-		self.data = []
 		self.get_gst_accounts()
 		self.get_invoice_data()
 
@@ -28,27 +45,16 @@
 
 		self.get_invoice_items()
 		self.get_items_based_on_tax_rate()
-		invoice_fields = [d["fieldname"] for d in self.invoice_columns]
+		self.invoice_fields = [d["fieldname"] for d in self.invoice_columns]
+		self.get_data()
+		return self.columns, self.data
 
-
+	def get_data(self):
+		self.data = []
 		for inv, items_based_on_rate in self.items_based_on_tax_rate.items():
 			invoice_details = self.invoices.get(inv)
 			for rate, items in items_based_on_rate.items():
-				row = []
-				for fieldname in invoice_fields:
-					if self.filters.get("type_of_business") ==  "CDNR" and fieldname == "invoice_value":
-						row.append(abs(invoice_details.base_rounded_total) or abs(invoice_details.base_grand_total))
-					elif fieldname == "invoice_value":
-						row.append(invoice_details.base_rounded_total or invoice_details.base_grand_total)
-					else:
-						row.append(invoice_details.get(fieldname))
-
-				row += [rate,
-					sum([abs(net_amount) for item_code, net_amount in self.invoice_items.get(inv).items()
-						if item_code in items]),
-					self.invoice_cess.get(inv)
-				]
-
+				row, taxable_value = self.get_row_data_for_invoice(inv, invoice_details, rate, items)
 				if self.filters.get("type_of_business") ==  "B2C Small":
 					row.append("E" if invoice_details.ecommerce_gstin else "OE")
 
@@ -58,34 +64,33 @@
 
 				self.data.append(row)
 
+	def get_row_data_for_invoice(self, invoice, invoice_details, tax_rate, items):
+		row = []
+		for fieldname in self.invoice_fields:
+			if self.filters.get("type_of_business") ==  "CDNR" and fieldname == "invoice_value":
+				row.append(abs(invoice_details.base_rounded_total) or abs(invoice_details.base_grand_total))
+			elif fieldname == "invoice_value":
+				row.append(invoice_details.base_rounded_total or invoice_details.base_grand_total)
+			else:
+				row.append(invoice_details.get(fieldname))
+
+		taxable_value = sum([abs(net_amount)
+			for item_code, net_amount in self.invoice_items.get(invoice).items() if item_code in items])
+		row += [tax_rate, taxable_value]
+
+		return row, taxable_value
+
 	def get_invoice_data(self):
 		self.invoices = frappe._dict()
 		conditions = self.get_conditions()
-
 		invoice_data = frappe.db.sql("""
 			select
-				name as invoice_number,
-				customer_name,
-				posting_date,
-				base_grand_total,
-				base_rounded_total,
-				customer_gstin,
-				place_of_supply,
-				ecommerce_gstin,
-				reverse_charge,
-				invoice_type,
-				return_against,
-				is_return,
-				invoice_type,
-				export_type,
-				port_code,
-				shipping_bill_number,
-				shipping_bill_date,
-				reason_for_issuing_document
-			from `tabSales Invoice`
-			where docstatus = 1 %s
+				{select_columns}
+			from `tab{doctype}`
+			where docstatus = 1 {where_conditions}
 			order by posting_date desc
-			""" % (conditions), self.filters, as_dict=1)
+			""".format(select_columns=self.select_columns, doctype=self.doctype,
+				where_conditions=conditions), self.filters, as_dict=1)
 
 		for d in invoice_data:
 			self.invoices.setdefault(d.invoice_number, d)
@@ -127,30 +132,29 @@
 		self.invoice_items = frappe._dict()
 		items = frappe.db.sql("""
 			select item_code, parent, base_net_amount
-			from `tabSales Invoice Item`
+			from `tab%s Item`
 			where parent in (%s)
-		""" % (', '.join(['%s']*len(self.invoices))), tuple(self.invoices), as_dict=1)
+		""" % (self.doctype, ', '.join(['%s']*len(self.invoices))), tuple(self.invoices), as_dict=1)
 
 		for d in items:
 			self.invoice_items.setdefault(d.parent, {}).setdefault(d.item_code, d.base_net_amount)
 
 	def get_items_based_on_tax_rate(self):
-		tax_details = frappe.db.sql("""
+		self.tax_details = frappe.db.sql("""
 			select
 				parent, account_head, item_wise_tax_detail, base_tax_amount_after_discount_amount
-			from `tabSales Taxes and Charges`
+			from `tab%s`
 			where
-				parenttype = 'Sales Invoice' and docstatus = 1
+				parenttype = %s and docstatus = 1
 				and parent in (%s)
-
 			order by account_head
-		""" % (', '.join(['%s']*len(self.invoices.keys()))), tuple(self.invoices.keys()))
+		""" % (self.tax_doctype, '%s', ', '.join(['%s']*len(self.invoices.keys()))),
+			tuple([self.doctype] + self.invoices.keys()))
 
 		self.items_based_on_tax_rate = {}
 		self.invoice_cess = frappe._dict()
 		unidentified_gst_accounts = []
-
-		for parent, account, item_wise_tax_detail, tax_amount in tax_details:
+		for parent, account, item_wise_tax_detail, tax_amount in self.tax_details:
 			if account in self.gst_accounts.cess_account:
 				self.invoice_cess.setdefault(parent, tax_amount)
 			else:
@@ -172,8 +176,8 @@
 							if cgst_or_sgst:
 								tax_rate *= 2
 
-							rate_based_dict = self.items_based_on_tax_rate.setdefault(parent, {})\
-								.setdefault(tax_rate, [])
+							rate_based_dict = self.items_based_on_tax_rate\
+								.setdefault(parent, {}).setdefault(tax_rate, [])
 							if item_code not in rate_based_dict:
 								rate_based_dict.append(item_code)
 					except ValueError:
diff --git a/erpnext/regional/report/gstr_2/gstr_2.py b/erpnext/regional/report/gstr_2/gstr_2.py
index 2aa0386..a69a67f 100644
--- a/erpnext/regional/report/gstr_2/gstr_2.py
+++ b/erpnext/regional/report/gstr_2/gstr_2.py
@@ -2,110 +2,76 @@
 # For license information, please see license.txt
 
 from __future__ import unicode_literals
-import frappe, json
-from frappe import _
+import frappe
 from datetime import date
+from erpnext.regional.report.gstr_1.gstr_1 import Gstr1Report
 
 def execute(filters=None):
 	return Gstr2Report(filters).run()
 
-class Gstr2Report(object):
+class Gstr2Report(Gstr1Report):
 	def __init__(self, filters=None):
 		self.filters = frappe._dict(filters or {})
-
-	def run(self):
-		self.get_columns()
-		self.get_data()
-		return self.columns, self.data
+		self.doctype = "Purchase Invoice"
+		self.tax_doctype = "Purchase Taxes and Charges"
+		self.select_columns = """
+			name as invoice_number,
+			supplier_name,
+			posting_date,
+			base_grand_total,
+			base_rounded_total,
+			supplier_gstin,
+			place_of_supply,
+			ecommerce_gstin,
+			reverse_charge,
+			invoice_type,
+			return_against,
+			is_return,
+			invoice_type,
+			export_type,
+			reason_for_issuing_document,
+			eligibility_for_itc,
+			itc_integrated_tax,
+			itc_central_tax,
+			itc_state_tax,
+			itc_cess_amount
+		"""
 
 	def get_data(self):
+		self.get_igst_invoices()
 		self.data = []
-		self.get_gst_accounts()
-		self.get_invoice_data()
-
-		if not self.invoices: return
-
-		self.get_invoice_items()
-		self.get_items_based_on_tax_rate()
-		invoice_fields = [d["fieldname"] for d in self.invoice_columns]
-
-
 		for inv, items_based_on_rate in self.items_based_on_tax_rate.items():
 			invoice_details = self.invoices.get(inv)
-			
 			for rate, items in items_based_on_rate.items():
-				# for is_igst, items in account.items():
-				row = []
-				for fieldname in invoice_fields:
-					if self.filters.get("type_of_business") ==  "CDNR" and fieldname == "invoice_value":
-						row.append(abs(invoice_details.base_rounded_total) or abs(invoice_details.base_grand_total))
-					elif fieldname == "invoice_value":
-						row.append(invoice_details.base_rounded_total or invoice_details.base_grand_total)
-					else:
-						row.append(invoice_details.get(fieldname))
+				row, taxable_value = self.get_row_data_for_invoice(inv, invoice_details, rate, items)
+				tax_amount = taxable_value * rate / 100
+				if inv in self.igst_invoices:
+					row += [tax_amount, 0, 0]
+				else:
+					row += [0, tax_amount / 2, tax_amount / 2]
 
-				print("items", items.items())
-
-				
-				row += [rate,
-					sum([abs(net_amount) for item_code, net_amount in self.invoice_items.get(inv).items()
-						if item_code in [v[0] for k, v in items.items()]]),
-					[abs(v[1]) if k == True else 0.00 for k, v in items.items()],
-					[abs(v[1]) if k == False else 0.00 for k, v in items.items()],
-					[abs(v[1]) if k == False else 0.00 for k, v in items.items()],
+				row += [
 					self.invoice_cess.get(inv),
 					invoice_details.get('eligibility_for_itc'),
 					invoice_details.get('itc_integrated_tax'),
 					invoice_details.get('itc_central_tax'),
 					invoice_details.get('itc_state_tax'),
-					invoice_details.get('itc_cess_amount'),
+					invoice_details.get('itc_cess_amount')
 				]
-
-
-
-
 				if self.filters.get("type_of_business") ==  "CDNR":
 					row.append("Y" if invoice_details.posting_date <= date(2017, 7, 1) else "N")
 					row.append("C" if invoice_details.return_against else "R")
 
 				self.data.append(row)
 
-	def get_invoice_data(self):
-		self.invoices = frappe._dict()
-		conditions = self.get_conditions()
-
-		invoice_data = frappe.db.sql("""
-			select
-				name as invoice_number,
-				supplier_name,
-				posting_date,
-				base_grand_total,
-				base_rounded_total,
-				supplier_gstin,
-				place_of_supply,
-				ecommerce_gstin,
-				reverse_charge,
-				invoice_type,
-				return_against,
-				is_return,
-				invoice_type,
-				export_type,
-				port_code,
-				shipping_bill_number,
-				shipping_bill_date,
-				reason_for_issuing_document,
-				eligibility_for_itc,
-				itc_integrated_tax,
-				itc_central_tax,
-				itc_state_tax,
-				itc_cess_amount
-			from `tabPurchase Invoice`
-			where docstatus = 1 %s
-			order by posting_date desc
-			""" % (conditions), self.filters, as_dict=1)
-
-		for d in invoice_data:
-			self.invoices.setdefault(d.invoice_number, d)
+	def get_igst_invoices(self):
+		self.igst_invoices = []
+		for d in self.tax_details:
+			is_igst = True if d[1] in self.gst_accounts.igst_account else False
+			if is_igst and d[0] not in self.igst_invoices:
+				self.igst_invoices.append(d[0])
+			if is_igst:
+				break
 
 	def get_conditions(self):
 		conditions = ""
@@ -124,86 +90,6 @@
 
 		return conditions
 
-	def get_invoice_items(self):
-		self.invoice_items = frappe._dict()
-		items = frappe.db.sql("""
-			select item_code, parent, base_net_amount
-			from `tabPurchase Invoice Item`
-			where parent in (%s)
-		""" % (', '.join(['%s']*len(self.invoices))), tuple(self.invoices), as_dict=1)
-
-		for d in items:
-			self.invoice_items.setdefault(d.parent, {}).setdefault(d.item_code, d.base_net_amount)
-
-	def get_items_based_on_tax_rate(self):
-		tax_details = frappe.db.sql("""
-			select
-				parent, account_head, item_wise_tax_detail, base_tax_amount_after_discount_amount
-			from `tabPurchase Taxes and Charges`
-			where
-				parenttype = 'Purchase Invoice' and docstatus = 1
-				and parent in (%s)
-
-			order by account_head
-		""" % (', '.join(['%s']*len(self.invoices.keys()))), tuple(self.invoices.keys()))
-
-		self.items_based_on_tax_rate = {}
-		self.invoice_cess = frappe._dict()
-		unidentified_gst_accounts = []
-
-		for parent, account, item_wise_tax_detail, tax_amount in tax_details:
-			if account in self.gst_accounts.cess_account:
-				self.invoice_cess.setdefault(parent, tax_amount)
-			else:
-				if item_wise_tax_detail:
-					try:
-						item_wise_tax_detail = json.loads(item_wise_tax_detail)
-						cgst_or_sgst = False
-						if account in self.gst_accounts.cgst_account \
-							or account in self.gst_accounts.sgst_account:
-							cgst_or_sgst = True
-
-						if not (cgst_or_sgst or account in self.gst_accounts.igst_account):
-							if "gst" in account.lower() and account not in unidentified_gst_accounts:
-								unidentified_gst_accounts.append(account)
-							continue
-						is_igst = False
-						for item_code, tax_amounts in item_wise_tax_detail.items():
-							tax_rate = tax_amounts[0]
-							tax_amt = tax_amounts[1]
-							if cgst_or_sgst:
-								tax_rate *= 2
-								tax_amt *= 2
-
-							else:
-								is_igst =True
-								
-
-							rate_based_dict = self.items_based_on_tax_rate.setdefault(parent, {})\
-								.setdefault(tax_rate, {}).setdefault(is_igst, [])
-							print("rate_base_dict", rate_based_dict)
-							if item_code not in rate_based_dict:
-								rate_based_dict.append(item_code)
-								rate_based_dict.append(tax_amt if is_igst else tax_amt / 2 )
-					except ValueError:
-						continue
-		if unidentified_gst_accounts:
-			frappe.msgprint(_("Following accounts might be selected in GST Settings:")
-				+ "<br>" + "<br>".join(unidentified_gst_accounts), alert=True)
-
-	def get_gst_accounts(self):
-		self.gst_accounts = frappe._dict()
-		gst_settings_accounts = frappe.get_list("GST Account",
-			filters={"parent": "GST Settings", "company": self.filters.company},
-			fields=["cgst_account", "sgst_account", "igst_account", "cess_account"])
-
-		if not gst_settings_accounts:
-			frappe.throw(_("Please set GST Accounts in GST Settings"))
-
-		for d in gst_settings_accounts:
-			for acc, val in d.items():
-				self.gst_accounts.setdefault(acc, []).append(val)
-
 	def get_columns(self):
 		self.tax_columns = [
 			{
diff --git a/erpnext/selling/doctype/customer/customer.json b/erpnext/selling/doctype/customer/customer.json
index b618bf3..b2577d5 100644
--- a/erpnext/selling/doctype/customer/customer.json
+++ b/erpnext/selling/doctype/customer/customer.json
@@ -1002,9 +1002,9 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
-   "depends_on": "", 
-   "fieldname": "payment_terms", 
-   "fieldtype": "Link", 
+   "default": "0", 
+   "fieldname": "bypass_credit_limit_check_at_sales_order", 
+   "fieldtype": "Check", 
    "hidden": 0, 
    "ignore_user_permissions": 0, 
    "ignore_xss_filter": 0, 
@@ -1012,10 +1012,9 @@
    "in_global_search": 0, 
    "in_list_view": 0, 
    "in_standard_filter": 0, 
-   "label": "Default Payment Terms Template", 
+   "label": "Bypass credit limit check at Sales Order", 
    "length": 0, 
    "no_copy": 0, 
-   "options": "Payment Terms Template", 
    "permlevel": 0, 
    "precision": "", 
    "print_hide": 0, 
@@ -1034,9 +1033,8 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
-   "default": "0", 
-   "fieldname": "bypass_credit_limit_check_at_sales_order", 
-   "fieldtype": "Check", 
+   "fieldname": "column_break_34", 
+   "fieldtype": "Column Break", 
    "hidden": 0, 
    "ignore_user_permissions": 0, 
    "ignore_xss_filter": 0, 
@@ -1044,7 +1042,6 @@
    "in_global_search": 0, 
    "in_list_view": 0, 
    "in_standard_filter": 0, 
-   "label": "Bypass credit limit check at Sales Order", 
    "length": 0, 
    "no_copy": 0, 
    "permlevel": 0, 
@@ -1063,6 +1060,38 @@
    "allow_bulk_edit": 0, 
    "allow_on_submit": 0, 
    "bold": 0, 
+   "collapsible": 0, 
+   "columns": 0, 
+   "depends_on": "", 
+   "fieldname": "payment_terms", 
+   "fieldtype": "Link", 
+   "hidden": 0, 
+   "ignore_user_permissions": 0, 
+   "ignore_xss_filter": 0, 
+   "in_filter": 0, 
+   "in_global_search": 0, 
+   "in_list_view": 0, 
+   "in_standard_filter": 0, 
+   "label": "Default Payment Terms Template", 
+   "length": 0, 
+   "no_copy": 0, 
+   "options": "Payment Terms Template", 
+   "permlevel": 0, 
+   "precision": "", 
+   "print_hide": 0, 
+   "print_hide_if_no_value": 0, 
+   "read_only": 0, 
+   "remember_last_selected_value": 0, 
+   "report_hide": 0, 
+   "reqd": 0, 
+   "search_index": 0, 
+   "set_only_once": 0, 
+   "unique": 0
+  }, 
+  {
+   "allow_bulk_edit": 0, 
+   "allow_on_submit": 0, 
+   "bold": 0, 
    "collapsible": 1, 
    "collapsible_depends_on": "customer_details", 
    "columns": 0, 
@@ -1354,7 +1383,7 @@
  "issingle": 0, 
  "istable": 0, 
  "max_attachments": 0, 
- "modified": "2017-12-13 18:17:19.894331", 
+ "modified": "2018-01-30 11:52:05.497363", 
  "modified_by": "Administrator", 
  "module": "Selling", 
  "name": "Customer", 
diff --git a/erpnext/selling/doctype/customer/customer.py b/erpnext/selling/doctype/customer/customer.py
index eaa82b3..2284f85 100644
--- a/erpnext/selling/doctype/customer/customer.py
+++ b/erpnext/selling/doctype/customer/customer.py
@@ -185,12 +185,14 @@
 		("%%%s%%" % txt, "%%%s%%" % txt, "%%%s%%" % txt, "%%%s%%" % txt, start, page_len))
 
 
-def check_credit_limit(customer, company):
-	customer_outstanding = get_customer_outstanding(customer, company)
+def check_credit_limit(customer, company, ignore_outstanding_sales_order=False, extra_amount=0):
+	customer_outstanding = get_customer_outstanding(customer, company, ignore_outstanding_sales_order)
+	if extra_amount > 0:
+		customer_outstanding += flt(extra_amount)
 
 	credit_limit = get_credit_limit(customer, company)
 	if credit_limit > 0 and flt(customer_outstanding) > credit_limit:
-		msgprint(_("Credit limit has been crossed for customer {0} {1}/{2}")
+		msgprint(_("Credit limit has been crossed for customer {0} ({1}/{2})")
 			.format(customer, customer_outstanding, credit_limit))
 
 		# If not authorized person raise exception
@@ -231,7 +233,8 @@
 			and dn.customer=%s and dn.company=%s
 			and dn.docstatus = 1 and dn.status not in ('Closed', 'Stopped')
 			and ifnull(dn_item.against_sales_order, '') = ''
-			and ifnull(dn_item.against_sales_invoice, '') = ''""", (customer, company), as_dict=True)
+			and ifnull(dn_item.against_sales_invoice, '') = ''
+		""", (customer, company), as_dict=True)
 
 	outstanding_based_on_dn = 0.0
 
diff --git a/erpnext/selling/doctype/sales_order/sales_order.py b/erpnext/selling/doctype/sales_order/sales_order.py
index 5bacf28..60046c8 100644
--- a/erpnext/selling/doctype/sales_order/sales_order.py
+++ b/erpnext/selling/doctype/sales_order/sales_order.py
@@ -484,11 +484,6 @@
 			else:
 				target.po_no = source.po_no
 
-		# Since the credit limit check is bypassed at sales order level,
-		# we need to check it at delivery note
-		if cint(frappe.db.get_value("Customer", source.customer, "bypass_credit_limit_check_at_sales_order")):
-			check_credit_limit(source.customer, source.company)
-
 		target.ignore_pricing_rule = 1
 		target.run_method("set_missing_values")
 		target.run_method("calculate_taxes_and_totals")
@@ -553,10 +548,6 @@
 		target.run_method("set_missing_values")
 		target.run_method("calculate_taxes_and_totals")
 
-		# Since the credit limit check is bypassed at sales order level, we need to check it at sales invoice
-		if cint(frappe.db.get_value("Customer", source.customer, "bypass_credit_limit_check_at_sales_order")):
-			check_credit_limit(source.customer, source.company)
-
 		# set company address
 		target.update(get_company_address(target.company))
 		if target.company_address:
diff --git a/erpnext/selling/page/point_of_sale/point_of_sale.js b/erpnext/selling/page/point_of_sale/point_of_sale.js
index 29238ea..5c2662c 100644
--- a/erpnext/selling/page/point_of_sale/point_of_sale.js
+++ b/erpnext/selling/page/point_of_sale/point_of_sale.js
@@ -468,6 +468,8 @@
 
 					if (r.message) {
 						this.frm.meta.default_print_format = r.message.print_format || 'POS Invoice';
+						this.frm.allow_edit_rate = r.message.allow_edit_rate;
+						this.frm.allow_edit_discount = r.message.allow_edit_discount;
 					}
 				}
 
@@ -564,9 +566,9 @@
 						<div class="taxes-and-totals">
 							${this.get_taxes_and_totals()}
 						</div>
-						<div class="discount-amount">
-							${this.get_discount_amount()}
-						</div>
+						<div class="discount-amount">`+
+						(!this.frm.allow_edit_discount ? `` : `${this.get_discount_amount()}`)+
+						`</div>
 						<div class="grand-total">
 							${this.get_grand_total()}
 						</div>
@@ -595,6 +597,7 @@
 		this.numpad && this.numpad.reset_value();
 		this.customer_field.set_value("");
 
+		this.$discount_amount.find('input:text').val('');
 		this.wrapper.find('.grand-total-value').text(
 			format_currency(this.frm.doc.grand_total, this.frm.currency));
 		this.wrapper.find('.rounded-total-value').text(
@@ -725,6 +728,17 @@
 		this.customer_field.set_value(this.frm.doc.customer);
 	}
 
+	disable_numpad_control() {
+		let disabled_btns = [];
+		if(!this.frm.allow_edit_rate) {
+			disabled_btns.push('Rate');
+		}
+		if(!this.frm.allow_edit_discount) {
+			disabled_btns.push('Disc');
+		}
+		return disabled_btns;
+	}
+
 	make_numpad() {
 		this.numpad = new NumberPad({
 			button_array: [
@@ -739,6 +753,7 @@
 			disable_highlight: ['Qty', 'Disc', 'Rate', 'Pay'],
 			reset_btns: ['Qty', 'Disc', 'Rate', 'Pay'],
 			del_btn: 'Del',
+			disable_btns: this.disable_numpad_control(),
 			wrapper: this.wrapper.find('.number-pad-container'),
 			onclick: (btn_value) => {
 				// on click
@@ -1269,7 +1284,7 @@
 	constructor({
 		wrapper, onclick, button_array,
 		add_class={}, disable_highlight=[],
-		reset_btns=[], del_btn='',
+		reset_btns=[], del_btn='', disable_btns
 	}) {
 		this.wrapper = wrapper;
 		this.onclick = onclick;
@@ -1278,6 +1293,7 @@
 		this.disable_highlight = disable_highlight;
 		this.reset_btns = reset_btns;
 		this.del_btn = del_btn;
+		this.disable_btns = disable_btns || [];
 		this.make_dom();
 		this.bind_events();
 		this.value = '';
@@ -1308,6 +1324,16 @@
 		}
 
 		this.set_class();
+
+		if(this.disable_btns) {
+			this.disable_btns.forEach((btn) => {
+				const $btn = this.get_btn(btn);
+				$btn.prop("disabled", true)
+				$btn.hover(() => {
+					$btn.css('cursor','not-allowed');
+				})
+			})
+		}
 	}
 
 	set_class() {
diff --git a/erpnext/setup/doctype/item_group/item_group.py b/erpnext/setup/doctype/item_group/item_group.py
index 39172d7..14a478d 100644
--- a/erpnext/setup/doctype/item_group/item_group.py
+++ b/erpnext/setup/doctype/item_group/item_group.py
@@ -9,6 +9,7 @@
 from frappe.website.website_generator import WebsiteGenerator
 from frappe.website.render import clear_cache
 from frappe.website.doctype.website_slideshow.website_slideshow import get_slideshow
+from erpnext.utilities.product import get_qty_in_stock
 
 
 class ItemGroup(NestedSet, WebsiteGenerator):
@@ -83,7 +84,8 @@
 	# base query
 	query = """select I.name, I.item_name, I.item_code, I.route, I.image, I.website_image, I.thumbnail, I.item_group,
 			I.description, I.web_long_description as website_description, I.is_stock_item,
-			case when (S.actual_qty - S.reserved_qty) > 0 then 1 else 0 end as in_stock
+			case when (S.actual_qty - S.reserved_qty) > 0 then 1 else 0 end as in_stock, I.website_warehouse,
+			I.has_batch_no
 		from `tabItem` I
 		left join tabBin S on I.item_code = S.item_code and I.website_warehouse = S.warehouse
 		where I.show_in_website = 1
@@ -104,8 +106,26 @@
 
 	data = frappe.db.sql(query, {"product_group": product_group,"search": search, "today": nowdate()}, as_dict=1)
 
+	data = adjust_qty_for_expired_items(data)
+
 	return [get_item_for_list_in_html(r) for r in data]
 
+
+def adjust_qty_for_expired_items(data):
+	adjusted_data = []
+
+	for item in data:
+		if item.get('has_batch_no') and item.get('website_warehouse'):
+			stock_qty_dict = get_qty_in_stock(
+				item.get('name'), 'website_warehouse', item.get('website_warehouse'))
+			qty = stock_qty_dict.stock_qty[0][0]
+			item['in_stock'] = 1 if qty else 0
+		adjusted_data.append(item)
+
+	return adjusted_data
+
+
+
 def get_child_groups(item_group_name):
 	item_group = frappe.get_doc("Item Group", item_group_name)
 	return frappe.db.sql("""select name
diff --git a/erpnext/setup/setup_wizard/setup_wizard.py b/erpnext/setup/setup_wizard/setup_wizard.py
index 2c5f7e8..d6491a8 100644
--- a/erpnext/setup/setup_wizard/setup_wizard.py
+++ b/erpnext/setup/setup_wizard/setup_wizard.py
@@ -5,7 +5,7 @@
 
 import frappe
 from frappe import _
-from operations import install_fixtures, taxes_setup, defaults_setup, company_setup, sample_data
+from .operations import install_fixtures, taxes_setup, defaults_setup, company_setup, sample_data
 
 def get_setup_stages(args=None):
 	if frappe.db.sql("select name from tabCompany"):
diff --git a/erpnext/setup/utils.py b/erpnext/setup/utils.py
index 5fcc3a2..8d9bba3 100644
--- a/erpnext/setup/utils.py
+++ b/erpnext/setup/utils.py
@@ -128,7 +128,7 @@
 		doc.update(r)
 		try:
 			doc.insert(ignore_permissions=True)
-		except frappe.DuplicateEntryError, e:
+		except frappe.DuplicateEntryError as e:
 			# pass DuplicateEntryError and continue
 			if e.args and e.args[0]==doc.doctype and e.args[1]==doc.name:
 				# make sure DuplicateEntryError is for the exact same doc and not a related doc
diff --git a/erpnext/stock/doctype/batch/batch.py b/erpnext/stock/doctype/batch/batch.py
index bcbc35e..b5674d3 100644
--- a/erpnext/stock/doctype/batch/batch.py
+++ b/erpnext/stock/doctype/batch/batch.py
@@ -131,7 +131,7 @@
 	:param batch_no: Optional - give qty for this batch no
 	:param warehouse: Optional - give qty for this warehouse
 	:param item_code: Optional - give qty for this item"""
-	frappe.has_permission('Batch', throw=True)
+
 	out = 0
 	if batch_no and warehouse:
 		out = float(frappe.db.sql("""select sum(actual_qty)
@@ -203,7 +203,7 @@
 			else:
 				batch_qty = get_batch_qty(batch_no=d.batch_no, warehouse=warehouse)
 				if flt(batch_qty, d.precision("qty")) < flt(qty, d.precision("qty")):
-					frappe.throw(_("Row #{0}: The batch {1} has only {2} qty. Please select another batch which has {3} qty available or split the row into multiple rows, to deliver/issue from multiple batches").format(d.idx, d.batch_no, batch_qty, d.stock_qty))
+					frappe.throw(_("Row #{0}: The batch {1} has only {2} qty. Please select another batch which has {3} qty available or split the row into multiple rows, to deliver/issue from multiple batches").format(d.idx, d.batch_no, batch_qty, qty))
 
 
 @frappe.whitelist()
diff --git a/erpnext/stock/doctype/delivery_note/delivery_note.py b/erpnext/stock/doctype/delivery_note/delivery_note.py
index dd00398..65f384f 100644
--- a/erpnext/stock/doctype/delivery_note/delivery_note.py
+++ b/erpnext/stock/doctype/delivery_note/delivery_note.py
@@ -235,13 +235,22 @@
 	def check_credit_limit(self):
 		from erpnext.selling.doctype.customer.customer import check_credit_limit
 
+		extra_amount = 0
 		validate_against_credit_limit = False
-		for d in self.get("items"):
-			if not (d.against_sales_order or d.against_sales_invoice):
-				validate_against_credit_limit = True
-				break
+		bypass_credit_limit_check_at_sales_order = cint(frappe.db.get_value("Customer", self.customer,
+			"bypass_credit_limit_check_at_sales_order"))
+		if bypass_credit_limit_check_at_sales_order:
+			validate_against_credit_limit = True
+			extra_amount = self.base_grand_total
+		else:
+			for d in self.get("items"):
+				if not (d.against_sales_order or d.against_sales_invoice):
+					validate_against_credit_limit = True
+					break
+
 		if validate_against_credit_limit:
-			check_credit_limit(self.customer, self.company)
+			check_credit_limit(self.customer, self.company,
+				bypass_credit_limit_check_at_sales_order, extra_amount)
 
 	def validate_packed_qty(self):
 		"""
diff --git a/erpnext/stock/doctype/item/item.js b/erpnext/stock/doctype/item/item.js
index c7719e4..104eeb8 100644
--- a/erpnext/stock/doctype/item/item.js
+++ b/erpnext/stock/doctype/item/item.js
@@ -317,11 +317,6 @@
 	show_multiple_variants_dialog: function(frm) {
 		var me = this;
 
-		if(me.multiple_variant_dialog) {
-			me.multiple_variant_dialog.show();
-			return;
-		}
-
 		let promises = [];
 		let attr_val_fields = {};
 
diff --git a/erpnext/stock/doctype/item/test_item.py b/erpnext/stock/doctype/item/test_item.py
index d065b09..fb3182e 100644
--- a/erpnext/stock/doctype/item/test_item.py
+++ b/erpnext/stock/doctype/item/test_item.py
@@ -80,7 +80,6 @@
 		}
 
 		make_test_objects("Item Price")
-		print(frappe.get_all("Item Price"))
 
 		details = get_item_details({
 			"item_code": "_Test Item",
diff --git a/erpnext/stock/doctype/material_request/material_request.py b/erpnext/stock/doctype/material_request/material_request.py
index da310aa..defce62 100644
--- a/erpnext/stock/doctype/material_request/material_request.py
+++ b/erpnext/stock/doctype/material_request/material_request.py
@@ -65,7 +65,7 @@
 			self.status = "Draft"
 
 		from erpnext.controllers.status_updater import validate_status
-		validate_status(self.status, 
+		validate_status(self.status,
 			["Draft", "Submitted", "Stopped", "Cancelled", "Pending",
 			"Partially Ordered", "Ordered", "Issued", "Transferred"])
 
@@ -240,7 +240,8 @@
 				["name", "material_request_item"],
 				["parent", "material_request"],
 				["uom", "stock_uom"],
-				["uom", "uom"]
+				["uom", "uom"],
+				["sales_order", "sales_order"]
 			],
 			"postprocess": update_item,
 			"condition": lambda doc: doc.ordered_qty < doc.stock_qty
@@ -344,7 +345,8 @@
 			"doctype": "Supplier Quotation Item",
 			"field_map": {
 				"name": "material_request_item",
-				"parent": "material_request"
+				"parent": "material_request",
+				"sales_order": "sales_order"
 			}
 		}
 	}, target_doc, postprocess)
diff --git a/erpnext/stock/doctype/stock_entry/stock_entry.py b/erpnext/stock/doctype/stock_entry/stock_entry.py
index 80afd49..7560e8a 100644
--- a/erpnext/stock/doctype/stock_entry/stock_entry.py
+++ b/erpnext/stock/doctype/stock_entry/stock_entry.py
@@ -274,14 +274,15 @@
 		self.set_actual_qty()
 		self.calculate_rate_and_amount()
 
-	def calculate_rate_and_amount(self, force=False, update_finished_item_rate=True):
+	def calculate_rate_and_amount(self, force=False,
+			update_finished_item_rate=True, raise_error_if_no_rate=True):
 		self.set_basic_rate(force, update_finished_item_rate)
 		self.distribute_additional_costs()
 		self.update_valuation_rate()
 		self.set_total_incoming_outgoing_value()
 		self.set_total_amount()
 
-	def set_basic_rate(self, force=False, update_finished_item_rate=True):
+	def set_basic_rate(self, force=False, update_finished_item_rate=True, raise_error_if_no_rate=True):
 		"""get stock and incoming rate on posting date"""
 		raw_material_cost = 0.0
 		scrap_material_cost = 0.0
@@ -294,7 +295,7 @@
 			# get basic rate
 			if not d.bom_no:
 				if (not flt(d.basic_rate) and not d.allow_zero_valuation_rate) or d.s_warehouse or force:
-					basic_rate = flt(get_incoming_rate(args), self.precision("basic_rate", d))
+					basic_rate = flt(get_incoming_rate(args, raise_error_if_no_rate), self.precision("basic_rate", d))
 					if basic_rate > 0:
 						d.basic_rate = basic_rate
 
@@ -306,7 +307,8 @@
 			if d.bom_no:
 				if not flt(d.basic_rate) and not d.allow_zero_valuation_rate and \
 					getattr(self, "pro_doc", frappe._dict()).scrap_warehouse == d.t_warehouse:
-					basic_rate = flt(get_incoming_rate(args), self.precision("basic_rate", d))
+					basic_rate = flt(get_incoming_rate(args, raise_error_if_no_rate),
+						self.precision("basic_rate", d))
 					if basic_rate > 0:
 						d.basic_rate = basic_rate
 					d.basic_amount = flt(flt(d.transfer_qty) * flt(d.basic_rate), d.precision("basic_amount"))
@@ -600,7 +602,8 @@
 						if self.pro_doc and not self.pro_doc.skip_transfer:
 							item["from_warehouse"] = self.pro_doc.wip_warehouse
 						#Get Reserve Warehouse from PO
-						item["from_warehouse"] = item_wh.get(item.item_code) if self.purchase_order and self.purpose=="Subcontract" else ""
+						if self.purchase_order and self.purpose=="Subcontract":
+							item["from_warehouse"] = item_wh.get(item.item_code)
 						item["to_warehouse"] = self.to_warehouse if self.purpose=="Subcontract" else ""
 
 					self.add_to_stock_entry_detail(item_dict)
@@ -622,7 +625,7 @@
 				self.load_items_from_bom()
 
 		self.set_actual_qty()
-		self.calculate_rate_and_amount()
+		self.calculate_rate_and_amount(raise_error_if_no_rate=False)
 
 	def set_production_order_details(self):
 		if not getattr(self, "pro_doc", None):
diff --git a/erpnext/stock/doctype/stock_entry/test_stock_entry.py b/erpnext/stock/doctype/stock_entry/test_stock_entry.py
index b590822..b2f85d0 100644
--- a/erpnext/stock/doctype/stock_entry/test_stock_entry.py
+++ b/erpnext/stock/doctype/stock_entry/test_stock_entry.py
@@ -557,12 +557,13 @@
 		production_order.submit()
 
 		make_stock_entry(item_code="_Test Item", target="_Test Warehouse - _TC", qty=50, basic_rate=100)
+		make_stock_entry(item_code="_Test Item 2", target="_Test Warehouse - _TC", qty=50, basic_rate=20)
 
 		stock_entry = _make_stock_entry(production_order.name, "Manufacture", 1)
 
 		rm_cost = 0
 		for d in stock_entry.get("items"):
-			if d.s_warehouse:
+			if d.item_code != "_Test FG Item 2":
 				rm_cost += flt(d.amount)
 
 		fg_cost = filter(lambda x: x.item_code=="_Test FG Item 2", stock_entry.get("items"))[0].amount
diff --git a/erpnext/stock/get_item_details.py b/erpnext/stock/get_item_details.py
index a7638b4..6b67233 100644
--- a/erpnext/stock/get_item_details.py
+++ b/erpnext/stock/get_item_details.py
@@ -472,8 +472,8 @@
 @frappe.whitelist()
 def get_bin_details(item_code, warehouse):
 	return frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse},
-			["projected_qty", "actual_qty"], as_dict=True) \
-			or {"projected_qty": 0, "actual_qty": 0}
+			["projected_qty", "actual_qty", "ordered_qty"], as_dict=True) \
+			or {"projected_qty": 0, "actual_qty": 0, "ordered_qty": 0}
 
 @frappe.whitelist()
 def get_serial_no_details(item_code, warehouse, stock_qty, serial_no):
diff --git a/erpnext/stock/report/stock_ledger/stock_ledger.py b/erpnext/stock/report/stock_ledger/stock_ledger.py
index 8377f59..e436132 100644
--- a/erpnext/stock/report/stock_ledger/stock_ledger.py
+++ b/erpnext/stock/report/stock_ledger/stock_ledger.py
@@ -106,11 +106,10 @@
 	from erpnext.stock.stock_ledger import get_previous_sle
 	last_entry = get_previous_sle({
 		"item_code": filters.item_code,
-		"warehouse": get_warehouse_condition(filters.warehouse),
+		"warehouse_condition": get_warehouse_condition(filters.warehouse),
 		"posting_date": filters.from_date,
 		"posting_time": "00:00:00"
 	})
-
 	row = [""]*len(columns)
 	row[1] = _("'Opening'")
 	for i, v in ((9, 'qty_after_transaction'), (11, 'valuation_rate'), (12, 'stock_value')):
@@ -122,7 +121,7 @@
 	warehouse_details = frappe.db.get_value("Warehouse", warehouse, ["lft", "rgt"], as_dict=1)
 	if warehouse_details:
 		return " exists (select name from `tabWarehouse` wh \
-			where wh.lft >= %s and wh.rgt <= %s and sle.warehouse = wh.name)"%(warehouse_details.lft,
+			where wh.lft >= %s and wh.rgt <= %s and warehouse = wh.name)"%(warehouse_details.lft,
 			warehouse_details.rgt)
 
 	return ''
diff --git a/erpnext/stock/stock_ledger.py b/erpnext/stock/stock_ledger.py
index 647c9fa..956f976 100644
--- a/erpnext/stock/stock_ledger.py
+++ b/erpnext/stock/stock_ledger.py
@@ -407,7 +407,12 @@
 
 def get_stock_ledger_entries(previous_sle, operator=None, order="desc", limit=None, for_update=False, debug=False):
 	"""get stock ledger entries filtered by specific posting datetime conditions"""
-	conditions = "timestamp(posting_date, posting_time) {0} timestamp(%(posting_date)s, %(posting_time)s)".format(operator)
+	conditions = " and timestamp(posting_date, posting_time) {0} timestamp(%(posting_date)s, %(posting_time)s)".format(operator)
+	if previous_sle.get("warehouse"):
+		conditions += " and warehouse = %(warehouse)s"
+	elif previous_sle.get("warehouse_condition"):
+		conditions += " and " + previous_sle.get("warehouse_condition")
+
 	if not previous_sle.get("posting_date"):
 		previous_sle["posting_date"] = "1900-01-01"
 	if not previous_sle.get("posting_time"):
@@ -418,9 +423,8 @@
 
 	return frappe.db.sql("""select *, timestamp(posting_date, posting_time) as "timestamp" from `tabStock Ledger Entry`
 		where item_code = %%(item_code)s
-		and warehouse = %%(warehouse)s
 		and ifnull(is_cancelled, 'No')='No'
-		and %(conditions)s
+		%(conditions)s
 		order by timestamp(posting_date, posting_time) %(order)s, name %(order)s
 		%(limit)s %(for_update)s""" % {
 			"conditions": conditions,
@@ -430,7 +434,7 @@
 		}, previous_sle, as_dict=1, debug=debug)
 
 def get_valuation_rate(item_code, warehouse, voucher_type, voucher_no,
-	allow_zero_rate=False, currency=None, company=None):
+	allow_zero_rate=False, currency=None, company=None, raise_error_if_no_rate=True):
 	# Get valuation rate from last sle for the same item and warehouse
 	if not company:
 		company = erpnext.get_default_company()
@@ -465,7 +469,7 @@
 					dict(item_code=item_code, buying=1, currency=currency),
 					'price_list_rate')
 
-	if not allow_zero_rate and not valuation_rate \
+	if not allow_zero_rate and not valuation_rate and raise_error_if_no_rate \
 			and cint(erpnext.is_perpetual_inventory_enabled(company)):
 		frappe.local.message_log = []
 		frappe.throw(_("Valuation rate not found for the Item {0}, which is required to do accounting entries for {1} {2}. If the item is transacting as a zero valuation rate item in the {1}, please mention that in the {1} Item table. Otherwise, please create an incoming stock transaction for the item or mention valuation rate in the Item record, and then try submiting/cancelling this entry").format(item_code, voucher_type, voucher_no))
diff --git a/erpnext/stock/utils.py b/erpnext/stock/utils.py
index 9b2fcb7..49d0ec6 100644
--- a/erpnext/stock/utils.py
+++ b/erpnext/stock/utils.py
@@ -123,7 +123,7 @@
 		frappe.msgprint(_("Item {0} ignored since it is not a stock item").format(args.get("item_code")))
 
 @frappe.whitelist()
-def get_incoming_rate(args):
+def get_incoming_rate(args, raise_error_if_no_rate=True):
 	"""Get Incoming Rate based on valuation method"""
 	from erpnext.stock.stock_ledger import get_previous_sle, get_valuation_rate
 	if isinstance(args, basestring):
@@ -146,7 +146,8 @@
 		voucher_no = args.get('voucher_no') or args.get('name')
 		in_rate = get_valuation_rate(args.get('item_code'), args.get('warehouse'),
 			args.get('voucher_type'), voucher_no, args.get('allow_zero_valuation'),
-			currency=erpnext.get_company_currency(args.get('company')), company=args.get('company'))
+			currency=erpnext.get_company_currency(args.get('company')), company=args.get('company'),
+			raise_error_if_no_rate=True)
 
 	return in_rate
 
diff --git a/erpnext/templates/generators/item.html b/erpnext/templates/generators/item.html
index de54493..6fec94e 100644
--- a/erpnext/templates/generators/item.html
+++ b/erpnext/templates/generators/item.html
@@ -57,6 +57,21 @@
 						<div class="item-stock" itemprop="availability"></div>
 					</div>
 					<div class="item-cart hide">
+						<div id="item-spinner">
+							<span style="display: inline-block">
+								<div class="input-group number-spinner">
+									<span class="input-group-btn">
+										<button class="btn btn-default cart-btn" data-dir="dwn">
+											–</button>
+									</span>
+									<input class="form-control text-right cart-qty"	value="1">
+									<span class="input-group-btn">
+										<button class="btn btn-default cart-btn" data-dir="up" style="margin-left:-2px;">
+											+</button>
+									</span>
+								</div>
+							</span>
+						</div>
 						<div id="item-add-to-cart">
 							<button class="btn btn-primary btn-sm">
 								{{ _("Add to Cart") }}</button>
diff --git a/erpnext/templates/includes/product_page.js b/erpnext/templates/includes/product_page.js
index 9f9d6ac..722283e 100644
--- a/erpnext/templates/includes/product_page.js
+++ b/erpnext/templates/includes/product_page.js
@@ -15,7 +15,7 @@
 			$(".item-cart").toggleClass("hide", (!!!r.message.price || !!!r.message.in_stock));
 			if(r.message && r.message.price) {
 				$(".item-price")
-					.html(r.message.price.formatted_price + " {{ _("per") }} " + r.message.uom);
+					.html(r.message.price.formatted_price + " / " + r.message.uom);
 
 				if(r.message.in_stock==0) {
 					$(".item-stock").html("<div style='color: red'> <i class='fa fa-close'></i> {{ _("Not in stock") }}</div>");
@@ -44,7 +44,7 @@
 
 		erpnext.shopping_cart.update_cart({
 			item_code: get_item_code(),
-			qty: 1,
+			qty: $("#item-spinner .cart-qty").val(),
 			callback: function(r) {
 				if(!r.exc) {
 					toggle_update_cart(1);
@@ -55,6 +55,25 @@
 		});
 	});
 
+	$("#item-spinner").on('click', '.number-spinner button', function () {
+		var btn = $(this),
+			input = btn.closest('.number-spinner').find('input'),
+			oldValue = input.val().trim(),
+			newVal = 0;
+
+		if (btn.attr('data-dir') == 'up') {
+			newVal = parseInt(oldValue) + 1;
+		} else if (btn.attr('data-dir') == 'dwn')  {
+			if (parseInt(oldValue) > 1) {
+				newVal = parseInt(oldValue) - 1;
+			}
+			else {
+				newVal = parseInt(oldValue);
+			}
+		}
+		input.val(newVal);
+	});
+
 	$("[itemscope] .item-view-attribute .form-control").on("change", function() {
 		try {
 			var item_code = encodeURIComponent(get_item_code());
@@ -86,6 +105,7 @@
 	$("#item-update-cart")
 		.toggle(qty ? true : false)
 		.find("input").val(qty);
+	$("#item-spinner").toggle(qty ? false : true);
 }
 
 function get_item_code() {
diff --git a/erpnext/utilities/product.py b/erpnext/utilities/product.py
index 9d5c056..415056d 100644
--- a/erpnext/utilities/product.py
+++ b/erpnext/utilities/product.py
@@ -4,25 +4,70 @@
 from __future__ import unicode_literals
 
 import frappe
-from frappe.utils import cint, fmt_money, flt
+from frappe.utils import cint, fmt_money, flt, nowdate, getdate
 from erpnext.accounts.doctype.pricing_rule.pricing_rule import get_pricing_rule_for_item
+from erpnext.stock.doctype.batch.batch import get_batch_qty
 
-def get_qty_in_stock(item_code, item_warehouse_field):
+def get_qty_in_stock(item_code, item_warehouse_field, warehouse=None):
 	in_stock, stock_qty = 0, ''
 	template_item_code, is_stock_item = frappe.db.get_value("Item", item_code, ["variant_of", "is_stock_item"])
 
-	warehouse = frappe.db.get_value("Item", item_code, item_warehouse_field)
+	if not warehouse:
+		warehouse = frappe.db.get_value("Item", item_code, item_warehouse_field)
+
 	if not warehouse and template_item_code and template_item_code != item_code:
 		warehouse = frappe.db.get_value("Item", template_item_code, item_warehouse_field)
 
 	if warehouse:
 		stock_qty = frappe.db.sql("""select GREATEST(actual_qty - reserved_qty, 0) from tabBin where
 			item_code=%s and warehouse=%s""", (item_code, warehouse))
-		if stock_qty:
+
+	if stock_qty:
+		stock_qty = adjust_qty_for_expired_items(item_code, stock_qty, warehouse)
+
+	if stock_qty:
+		in_stock = stock_qty[0][0] > 0 and 1 or 0
+
+	if stock_qty:
 			in_stock = stock_qty[0][0] > 0 and 1 or 0
 
 	return frappe._dict({"in_stock": in_stock, "stock_qty": stock_qty, "is_stock_item": is_stock_item})
 
+
+def adjust_qty_for_expired_items(item_code, stock_qty, warehouse):
+	batches = frappe.get_all('Batch', filters=[{'item': item_code}], fields=['expiry_date', 'name'])
+	expired_batches = get_expired_batches(batches)
+	stock_qty = [list(item) for item in stock_qty]
+	
+	for batch in expired_batches:
+		if warehouse:
+			stock_qty[0][0] = max(0, stock_qty[0][0] - get_batch_qty(batch, warehouse))
+		else:
+			stock_qty[0][0] = max(0, stock_qty[0][0] - qty_from_all_warehouses(get_batch_qty(batch)))
+
+		if not stock_qty[0][0]:
+			break
+
+	return stock_qty
+
+
+def get_expired_batches(batches):
+	"""
+	:param batches: A list of dict in the form [{'expiry_date': datetime.date(20XX, 1, 1), 'name': 'batch_id'}, ...]
+	"""
+	return [b.name for b in batches if b.expiry_date and b.expiry_date <= getdate(nowdate())]
+
+
+def qty_from_all_warehouses(batch_info):
+	"""
+	:param batch_info: A list of dict in the form [{u'warehouse': u'Stores - I', u'qty': 0.8}, ...]
+	"""
+	qty = 0
+	for batch in batch_info:
+		qty = qty + batch.qty
+
+	return qty
+
 def get_price(item_code, price_list, customer_group, company, qty=1):
 	template_item_code = frappe.db.get_value("Item", item_code, "variant_of")