Merge branch 'hotfix' into issue-12535-1
diff --git a/.travis.yml b/.travis.yml
index 43b4078..d6fc930 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"
 
@@ -29,15 +22,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
@@ -60,24 +44,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/erpnext/__init__.py b/erpnext/__init__.py
index f4876bd..96ad60f 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.14'
+__version__ = '10.0.18'
 
 def get_default_company(user=None):
 	'''Get default company for user'''
diff --git a/erpnext/accounts/doctype/journal_entry/journal_entry.js b/erpnext/accounts/doctype/journal_entry/journal_entry.js
index 48062a3..60c974f 100644
--- a/erpnext/accounts/doctype/journal_entry/journal_entry.js
+++ b/erpnext/accounts/doctype/journal_entry/journal_entry.js
@@ -82,8 +82,8 @@
 			$.each(this.frm.doc.accounts || [], function(i, jvd) {
 				frappe.model.set_default_values(jvd);
 			});
-
-			if(!this.frm.doc.amended_from) this.frm.doc.posting_date = this.frm.posting_date || frappe.datetime.get_today();
+			var posting_date = this.frm.posting_date;
+			if(!this.frm.doc.amended_from) this.frm.set_value('posting_date', posting_date || frappe.datetime.get_today());
 		}
 	},
 
diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
index 07853d0..28d51ce 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
@@ -96,7 +96,7 @@
 		if not self.credit_to:
 			self.credit_to = get_party_account("Supplier", self.supplier, self.company)
 		if not self.due_date:
-			self.due_date = get_due_date(self.posting_date, "Supplier", self.supplier)
+			self.due_date = get_due_date(self.posting_date, "Supplier", self.supplier, self.company)
 
 		super(PurchaseInvoice, self).set_missing_values(for_validate)
 
diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
index f6d43c7..f37fe61 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)
@@ -237,12 +242,15 @@
 		if not self.debit_to:
 			self.debit_to = get_party_account("Customer", self.customer, self.company)
 		if not self.due_date and self.customer:
-			self.due_date = get_due_date(self.posting_date, "Customer", self.customer)
+			self.due_date = get_due_date(self.posting_date, "Customer", self.customer, self.company)
 
 		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")
+			}
 
 	def update_time_sheet(self, sales_invoice):
 		for d in self.timesheets:
diff --git a/erpnext/accounts/doctype/subscription/subscription.py b/erpnext/accounts/doctype/subscription/subscription.py
index 1103b70..480abd4 100644
--- a/erpnext/accounts/doctype/subscription/subscription.py
+++ b/erpnext/accounts/doctype/subscription/subscription.py
@@ -232,6 +232,8 @@
 def send_notification(new_rv, subscription_doc, print_format='Standard'):
 	"""Notify concerned persons about recurring document generation"""
 	print_format = print_format
+	subject = subscription_doc.subject or ''
+	message = subscription_doc.message or ''
 
 	if not subscription_doc.subject:
 		subject = _("New {0}: #{1}").format(new_rv.doctype, new_rv.name)
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/general_ledger.py b/erpnext/accounts/general_ledger.py
index c575d59..03a06cc 100644
--- a/erpnext/accounts/general_ledger.py
+++ b/erpnext/accounts/general_ledger.py
@@ -191,8 +191,9 @@
 	for entry in gl_entries:
 		validate_frozen_account(entry["account"], adv_adj)
 		validate_balance_type(entry["account"], adv_adj)
-		validate_expense_against_budget(entry)
+		if not adv_adj:
+			validate_expense_against_budget(entry)
 		
-		if entry.get("against_voucher") and update_outstanding == 'Yes':
+		if entry.get("against_voucher") and update_outstanding == 'Yes' and not adv_adj:
 			update_outstanding_amt(entry["account"], entry.get("party_type"), entry.get("party"), entry.get("against_voucher_type"),
 				entry.get("against_voucher"), on_cancel=True)
diff --git a/erpnext/accounts/party.py b/erpnext/accounts/party.py
index 7bccfe8..5237a71 100644
--- a/erpnext/accounts/party.py
+++ b/erpnext/accounts/party.py
@@ -51,7 +51,7 @@
 	set_other_values(out, party, party_type)
 	set_price_list(out, party, party_type, price_list)
 	out["taxes_and_charges"] = set_taxes(party.name, party_type, posting_date, company, out.customer_group, out.supplier_type)
-	out["payment_terms_template"] = get_pyt_term_template(party.name, party_type)
+	out["payment_terms_template"] = get_pyt_term_template(party.name, party_type, company)
 
 	if not out.get("currency"):
 		out["currency"] = currency
@@ -164,7 +164,7 @@
 	out = {
 		party_type.lower(): party,
 		account_fieldname : account,
-		"due_date": get_due_date(posting_date, party_type, party)
+		"due_date": get_due_date(posting_date, party_type, party, company)
 	}
 	return out
 
@@ -267,12 +267,12 @@
 
 
 @frappe.whitelist()
-def get_due_date(posting_date, party_type, party):
+def get_due_date(posting_date, party_type, party, company=None):
 	"""Get due date from `Payment Terms Template`"""
 	due_date = None
 	if posting_date and party:
 		due_date = posting_date
-		template_name = get_pyt_term_template(party, party_type)
+		template_name = get_pyt_term_template(party, party_type, company)
 		if template_name:
 			due_date = get_due_date_from_template(template_name, posting_date).strftime("%Y-%m-%d")
 		else:
@@ -305,12 +305,11 @@
 
 	return due_date
 
-
-def validate_due_date(posting_date, due_date, party_type, party):
+def validate_due_date(posting_date, due_date, party_type, party, company=None):
 	if getdate(due_date) < getdate(posting_date):
 		frappe.throw(_("Due Date cannot be before Posting Date"))
 	else:
-		default_due_date = get_due_date(posting_date, party_type, party)
+		default_due_date = get_due_date(posting_date, party_type, party, company)
 		if not default_due_date:
 			return
 
@@ -360,14 +359,32 @@
 
 
 @frappe.whitelist()
-def get_pyt_term_template(party_name, party_type):
+def get_pyt_term_template(party_name, party_type, company=None):
+	if party_type not in ("Customer", "Supplier"):
+		return
+
 	template = None
-	if party_type in ('Customer', 'Supplier'):
-		template = frappe.db.get_value(party_type, party_name, fieldname='payment_terms')
+	if party_type == 'Customer':
+		customer = frappe.db.get_value("Customer", party_name,
+			fieldname=['payment_terms', "customer_group"], as_dict=1)
+		template = customer.payment_terms
+
+		if not template and customer.customer_group:
+			template = frappe.db.get_value("Customer Group",
+				customer.customer_group, fieldname='payment_terms')
+	else:
+		supplier = frappe.db.get_value("Supplier", party_name,
+			fieldname=['payment_terms', "supplier_type"], as_dict=1)
+		template = supplier.payment_terms
+
+		if not template and supplier.supplier_type:
+			template = frappe.db.get_value("Supplier Type", supplier.supplier_type, fieldname='payment_terms')
+
+	if not template and company:
+		template = frappe.db.get_value("Company", company, fieldname='payment_terms')
 
 	return template
 
-
 def validate_party_frozen_disabled(party_type, party_name):
 	if party_type and party_name:
 		if party_type in ("Customer", "Supplier"):
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/buying/doctype/purchase_order/purchase_order.py b/erpnext/buying/doctype/purchase_order/purchase_order.py
index db13bd5..e879f40 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 7479f55..2536721 100644
--- a/erpnext/buying/doctype/supplier/test_records.json
+++ b/erpnext/buying/doctype/supplier/test_records.json
@@ -8,8 +8,7 @@
  {
   "doctype": "Supplier",
   "supplier_name": "_Test Supplier P",
-  "supplier_type": "_Test Supplier Type",
-  "credit_days_based_on": "Fixed Days"
+  "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/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/accounts_controller.py b/erpnext/controllers/accounts_controller.py
index c7b5206..b3672cb 100644
--- a/erpnext/controllers/accounts_controller.py
+++ b/erpnext/controllers/accounts_controller.py
@@ -135,9 +135,9 @@
 			if not self.due_date:
 				frappe.throw(_("Due Date is mandatory"))
 
-			validate_due_date(self.posting_date, self.due_date, "Customer", self.customer)
+			validate_due_date(self.posting_date, self.due_date, "Customer", self.customer, self.company)
 		elif self.doctype == "Purchase Invoice":
-			validate_due_date(self.posting_date, self.due_date, "Supplier", self.supplier)
+			validate_due_date(self.posting_date, self.due_date, "Supplier", self.supplier, self.company)
 
 	def set_price_list_currency(self, buying_or_selling):
 		if self.meta.get_field("posting_date"):
diff --git a/erpnext/controllers/queries.py b/erpnext/controllers/queries.py
index 53f9ecb..139586f 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/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 8fa382c..9474a94 100644
--- a/erpnext/patches.txt
+++ b/erpnext/patches.txt
@@ -183,7 +183,6 @@
 execute:frappe.db.sql("""delete from `tabProject Task`""")
 erpnext.patches.v5_0.update_item_desc_in_invoice
 erpnext.patches.v5_1.fix_against_account
-erpnext.patches.v5_1.fix_credit_days_based_on
 execute:frappe.rename_doc("DocType", "Salary Manager", "Process Payroll", force=True)
 erpnext.patches.v5_1.rename_roles
 erpnext.patches.v5_1.default_bom
@@ -346,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
@@ -487,3 +486,5 @@
 erpnext.patches.v10_0.set_numeric_ranges_in_template_if_blank
 erpnext.patches.v10_0.update_assessment_plan
 erpnext.patches.v10_0.update_assessment_result
+erpnext.patches.v10_0.set_default_payment_terms_based_on_company
+erpnext.patches.v10_0.update_sales_order_link_to_purchase_order
\ No newline at end of file
diff --git a/erpnext/patches/v10_0/set_default_payment_terms_based_on_company.py b/erpnext/patches/v10_0/set_default_payment_terms_based_on_company.py
new file mode 100644
index 0000000..a90e096
--- /dev/null
+++ b/erpnext/patches/v10_0/set_default_payment_terms_based_on_company.py
@@ -0,0 +1,37 @@
+from __future__ import unicode_literals
+import frappe
+from erpnext.patches.v8_10.change_default_customer_credit_days import make_payment_term, make_template
+
+def execute():
+	for dt in ("Company", "Customer Group"):
+		frappe.reload_doc("setup", "doctype", frappe.scrub(dt))
+
+		credit_records = frappe.db.sql("""
+			SELECT DISTINCT `credit_days`, `credit_days_based_on`, `name`
+			from `tab{0}`
+			where
+				((credit_days_based_on='Fixed Days' or credit_days_based_on is null) and credit_days is not null)
+				or credit_days_based_on='Last Day of the Next Month'
+		""".format(dt), as_dict=1)
+
+		for d in credit_records:
+			template = create_payment_terms_template(d)
+
+			frappe.db.sql("""
+				update `tab{0}`
+				set `payment_terms` = %s
+				where name = %s
+			""".format(dt), (template.name, d.name))
+
+def create_payment_terms_template(data):
+	if data.credit_days_based_on == "Fixed Days":
+		pyt_template_name = 'Default Payment Term - N{0}'.format(data.credit_days)
+	else:
+		pyt_template_name = 'Default Payment Term - EO2M'
+
+	if not frappe.db.exists("Payment Terms Template", pyt_template_name):
+		payment_term = make_payment_term(data.credit_days, data.credit_days_based_on)
+		template = make_template(payment_term)
+	else:
+		template = frappe.get_doc("Payment Terms Template", pyt_template_name)
+	return template
\ No newline at end of file
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/v5_1/fix_credit_days_based_on.py b/erpnext/patches/v5_1/fix_credit_days_based_on.py
deleted file mode 100644
index 6df19f2..0000000
--- a/erpnext/patches/v5_1/fix_credit_days_based_on.py
+++ /dev/null
@@ -1,9 +0,0 @@
-from __future__ import unicode_literals
-
-import frappe
-
-def execute():
-	for dt in ("Customer", "Customer Group", "Company"):
-		frappe.reload_doctype(dt, force=True)
-		frappe.db.sql("""update `tab{0}` set credit_days_based_on='Fixed Days'
-			where ifnull(credit_days, 0) > 0""".format(dt))
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/patches/v8_10/change_default_customer_credit_days.py b/erpnext/patches/v8_10/change_default_customer_credit_days.py
index 640c8aa..eddafb5 100644
--- a/erpnext/patches/v8_10/change_default_customer_credit_days.py
+++ b/erpnext/patches/v8_10/change_default_customer_credit_days.py
@@ -17,7 +17,8 @@
 			SELECT DISTINCT `credit_days`, `credit_days_based_on`, `name`
 			from `tab{0}`
 			where
-				(credit_days_based_on='Fixed Days' and credit_days is not null)
+				((credit_days_based_on='Fixed Days' or credit_days_based_on is null)
+					and credit_days is not null)
 				or credit_days_based_on='Last Day of the Next Month'
 		""".format(doctype))
 
diff --git a/erpnext/public/js/controllers/transaction.js b/erpnext/public/js/controllers/transaction.js
index d06a76a..eb333af 100644
--- a/erpnext/public/js/controllers/transaction.js
+++ b/erpnext/public/js/controllers/transaction.js
@@ -523,7 +523,8 @@
 					},
 					callback: function(r, rt) {
 						if(r.message) {
-							me.frm.set_value("due_date", r.message);
+							me.frm.doc.due_date = r.message;
+							refresh_field("due_date");
 							frappe.ui.form.trigger(me.frm.doc.doctype, "currency");
 							me.recalculate_terms();
 						}
@@ -538,7 +539,7 @@
 	due_date: function() {
 		// due_date is to be changed, payment terms template and/or payment schedule must
 		// be removed as due_date is automatically changed based on payment terms
-		if (this.frm.doc.due_date) {
+		if (this.frm.doc.due_date && !this.frm.updating_party_details && !this.frm.doc.is_pos) {
 			if (this.frm.doc.payment_terms_template ||
 				(this.frm.doc.payment_schedule && this.frm.doc.payment_schedule.length)) {
 				var message1 = "";
@@ -555,11 +556,9 @@
 					if (message1.length !== 0) message2 = " and " + message2;
 					final_message = final_message + message2;
 				}
-
 				frappe.msgprint(final_message);
 			}
-
-	    }
+		}
 	},
 
 	recalculate_terms: function() {
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 1c3354c..42cde9f 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 0876228..357475d 100644
--- a/erpnext/selling/page/point_of_sale/point_of_sale.js
+++ b/erpnext/selling/page/point_of_sale/point_of_sale.js
@@ -463,6 +463,7 @@
 
 					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;
 					}
 				}
 
@@ -727,6 +728,7 @@
 			disable_highlight: ['Qty', 'Disc', 'Rate', 'Pay'],
 			reset_btns: ['Qty', 'Disc', 'Rate', 'Pay'],
 			del_btn: 'Del',
+			disable_btns: !this.frm.allow_edit_rate ? ['Rate']: [],
 			wrapper: this.wrapper.find('.number-pad-container'),
 			onclick: (btn_value) => {
 				// on click
@@ -1257,7 +1259,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;
@@ -1266,6 +1268,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 = '';
@@ -1296,6 +1299,14 @@
 		}
 
 		this.set_class();
+
+		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/company/company.json b/erpnext/setup/doctype/company/company.json
index 9824c70..d444417 100644
--- a/erpnext/setup/doctype/company/company.json
+++ b/erpnext/setup/doctype/company/company.json
@@ -1186,6 +1186,35 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
+   "fieldname": "column_break_26", 
+   "fieldtype": "Column Break", 
+   "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, 
+   "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, 
    "depends_on": "eval:!doc.__islocal", 
    "fieldname": "credit_limit", 
    "fieldtype": "Currency", 
@@ -1219,8 +1248,9 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
-   "fieldname": "column_break_26", 
-   "fieldtype": "Column Break", 
+   "depends_on": "", 
+   "fieldname": "payment_terms", 
+   "fieldtype": "Link", 
    "hidden": 0, 
    "ignore_user_permissions": 0, 
    "ignore_xss_filter": 0, 
@@ -1228,8 +1258,10 @@
    "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, 
@@ -1248,69 +1280,6 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
-   "fieldname": "credit_days_based_on", 
-   "fieldtype": "Select", 
-   "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": "Credit Days Based On", 
-   "length": 0, 
-   "no_copy": 0, 
-   "options": "\nFixed Days\nLast Day of the Next Month", 
-   "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, 
-   "depends_on": "eval:(!doc.__islocal && doc.credit_days_based_on=='Fixed Days')", 
-   "fieldname": "credit_days", 
-   "fieldtype": "Int", 
-   "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": "Credit Days", 
-   "length": 0, 
-   "no_copy": 0, 
-   "oldfieldname": "credit_days", 
-   "oldfieldtype": "Int", 
-   "permlevel": 0, 
-   "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, 
    "depends_on": "eval:!doc.__islocal", 
    "fieldname": "auto_accounting_for_stock_settings", 
    "fieldtype": "Section Break", 
@@ -2052,7 +2021,7 @@
  "istable": 0, 
  "max_attachments": 0, 
  "menu_index": 0, 
- "modified": "2017-12-07 18:40:24.646920", 
+ "modified": "2018-01-29 12:40:24.646920", 
  "modified_by": "Administrator", 
  "module": "Setup", 
  "name": "Company", 
diff --git a/erpnext/setup/doctype/customer_group/customer_group.json b/erpnext/setup/doctype/customer_group/customer_group.json
index 316f11b..062a49a 100644
--- a/erpnext/setup/doctype/customer_group/customer_group.json
+++ b/erpnext/setup/doctype/customer_group/customer_group.json
@@ -162,12 +162,14 @@
    "unique": 0
   }, 
   {
+   "allow_bulk_edit": 0, 
    "allow_on_submit": 0, 
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
-   "fieldname": "credit_days_based_on", 
-   "fieldtype": "Select", 
+   "depends_on": "", 
+   "fieldname": "payment_terms", 
+   "fieldtype": "Link", 
    "hidden": 0, 
    "ignore_user_permissions": 0, 
    "ignore_xss_filter": 0, 
@@ -175,10 +177,10 @@
    "in_global_search": 0, 
    "in_list_view": 0, 
    "in_standard_filter": 0, 
-   "label": "Credit Days Based On", 
+   "label": "Default Payment Terms Template", 
    "length": 0, 
    "no_copy": 0, 
-   "options": "\nFixed Days\nLast Day of the Next Month", 
+   "options": "Payment Terms Template", 
    "permlevel": 0, 
    "precision": "", 
    "print_hide": 0, 
@@ -196,35 +198,6 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
-   "depends_on": "eval:doc.credit_days_based_on=='Fixed Days'", 
-   "fieldname": "credit_days", 
-   "fieldtype": "Int", 
-   "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": "Credit Days", 
-   "length": 0, 
-   "no_copy": 0, 
-   "permlevel": 1, 
-   "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_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
    "fieldname": "credit_limit", 
    "fieldtype": "Currency", 
    "hidden": 0, 
@@ -411,7 +384,7 @@
  "issingle": 0, 
  "istable": 0, 
  "max_attachments": 0, 
- "modified": "2017-02-20 13:25:31.549874", 
+ "modified": "2018-01-29 13:25:31.549874", 
  "modified_by": "Administrator", 
  "module": "Setup", 
  "name": "Customer Group", 
diff --git a/erpnext/stock/doctype/batch/batch.py b/erpnext/stock/doctype/batch/batch.py
index 3e5d351..41bc7b4 100644
--- a/erpnext/stock/doctype/batch/batch.py
+++ b/erpnext/stock/doctype/batch/batch.py
@@ -114,8 +114,8 @@
 				d.batch_no = get_batch_no(d.item_code, warehouse, qty, throw)
 			else:
 				batch_qty = get_batch_qty(batch_no=d.batch_no, warehouse=warehouse)
-				if flt(batch_qty) < flt(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.qty))
+				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, qty))
 
 @frappe.whitelist()
 def get_batch_no(item_code, warehouse, qty=1, throw=False):
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 4e61bd9..f7250e4 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/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/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..874a382 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,