[Fix] Error in sales invoice and POS if customer group not defined in the customer (#10160)

diff --git a/erpnext/accounts/doctype/pos_profile/pos_profile.json b/erpnext/accounts/doctype/pos_profile/pos_profile.json
index 93aca1b..6991da2 100644
--- a/erpnext/accounts/doctype/pos_profile/pos_profile.json
+++ b/erpnext/accounts/doctype/pos_profile/pos_profile.json
@@ -727,38 +727,6 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
-   "fieldname": "tc_name", 
-   "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": "Terms and Conditions", 
-   "length": 0, 
-   "no_copy": 0, 
-   "oldfieldname": "tc_name", 
-   "oldfieldtype": "Link", 
-   "options": "Terms and Conditions", 
-   "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, 
    "fieldname": "column_break0", 
    "fieldtype": "Column Break", 
    "hidden": 0, 
@@ -788,39 +756,6 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
-   "description": "", 
-   "fieldname": "territory", 
-   "fieldtype": "Link", 
-   "hidden": 0, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 0, 
-   "in_global_search": 0, 
-   "in_list_view": 1, 
-   "in_standard_filter": 0, 
-   "label": "Territory", 
-   "length": 0, 
-   "no_copy": 0, 
-   "oldfieldname": "territory", 
-   "oldfieldtype": "Link", 
-   "options": "Territory", 
-   "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, 
    "fieldname": "selling_price_list", 
    "fieldtype": "Link", 
    "hidden": 0, 
@@ -853,6 +788,38 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
+   "fieldname": "tc_name", 
+   "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": "Terms and Conditions", 
+   "length": 0, 
+   "no_copy": 0, 
+   "oldfieldname": "tc_name", 
+   "oldfieldtype": "Link", 
+   "options": "Terms and Conditions", 
+   "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, 
    "fieldname": "apply_discount", 
    "fieldtype": "Check", 
    "hidden": 0, 
@@ -916,6 +883,129 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
+   "fieldname": "customer_details", 
+   "fieldtype": "Section 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, 
+   "label": "New Customer Details", 
+   "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, 
+   "description": "", 
+   "fieldname": "territory", 
+   "fieldtype": "Link", 
+   "hidden": 0, 
+   "ignore_user_permissions": 0, 
+   "ignore_xss_filter": 0, 
+   "in_filter": 0, 
+   "in_global_search": 0, 
+   "in_list_view": 1, 
+   "in_standard_filter": 0, 
+   "label": "Territory", 
+   "length": 0, 
+   "no_copy": 0, 
+   "oldfieldname": "territory", 
+   "oldfieldtype": "Link", 
+   "options": "Territory", 
+   "permlevel": 0, 
+   "print_hide": 0, 
+   "print_hide_if_no_value": 0, 
+   "read_only": 0, 
+   "remember_last_selected_value": 0, 
+   "report_hide": 0, 
+   "reqd": 1, 
+   "search_index": 0, 
+   "set_only_once": 0, 
+   "unique": 0
+  }, 
+  {
+   "allow_bulk_edit": 0, 
+   "allow_on_submit": 0, 
+   "bold": 0, 
+   "collapsible": 0, 
+   "columns": 0, 
+   "fieldname": "column_break_31", 
+   "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, 
+   "fieldname": "customer_group", 
+   "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": "Customer Group", 
+   "length": 0, 
+   "no_copy": 0, 
+   "options": "Customer Group", 
+   "permlevel": 0, 
+   "precision": "", 
+   "print_hide": 0, 
+   "print_hide_if_no_value": 0, 
+   "read_only": 0, 
+   "remember_last_selected_value": 0, 
+   "report_hide": 0, 
+   "reqd": 1, 
+   "search_index": 0, 
+   "set_only_once": 0, 
+   "unique": 0
+  }, 
+  {
+   "allow_bulk_edit": 0, 
+   "allow_on_submit": 0, 
+   "bold": 0, 
+   "collapsible": 0, 
+   "columns": 0, 
    "fieldname": "section_break_19", 
    "fieldtype": "Section Break", 
    "hidden": 0, 
@@ -1201,7 +1291,7 @@
  "issingle": 0, 
  "istable": 0, 
  "max_attachments": 0, 
- "modified": "2017-06-16 17:04:33.165676", 
+ "modified": "2017-07-28 03:40:03.253088", 
  "modified_by": "Administrator", 
  "module": "Accounts", 
  "name": "POS Profile", 
diff --git a/erpnext/accounts/doctype/pos_profile/pos_profile.py b/erpnext/accounts/doctype/pos_profile/pos_profile.py
index ef497bf..86682d3 100644
--- a/erpnext/accounts/doctype/pos_profile/pos_profile.py
+++ b/erpnext/accounts/doctype/pos_profile/pos_profile.py
@@ -14,6 +14,7 @@
 		self.check_for_duplicate()
 		self.validate_all_link_fields()
 		self.validate_duplicate_groups()
+		self.validate_customer_territory_group()
 
 	def check_for_duplicate(self):
 		res = frappe.db.sql("""select name, user from `tabPOS Profile`
@@ -48,6 +49,13 @@
 		if len(customer_groups) != len(set(customer_groups)):
 			frappe.throw(_("Duplicate customer group found in the cutomer group table"), title = "Duplicate Customer Group")
 
+	def validate_customer_territory_group(self):
+		if not self.territory:
+			frappe.throw(_("Territory is Required in POS Profile"), title="Mandatory Field")
+
+		if not self.customer_group:
+			frappe.throw(_("Customer Group is Required in POS Profile"), title="Mandatory Field")
+
 	def before_save(self):
 		set_account_for_mode_of_payment(self)
 
diff --git a/erpnext/accounts/doctype/pos_profile/test_pos_profile.js b/erpnext/accounts/doctype/pos_profile/test_pos_profile.js
new file mode 100644
index 0000000..42e5b7f
--- /dev/null
+++ b/erpnext/accounts/doctype/pos_profile/test_pos_profile.js
@@ -0,0 +1,23 @@
+/* eslint-disable */
+// rename this file from _test_[name] to test_[name] to activate
+// and remove above this line
+
+QUnit.test("test: POS Profile", function (assert) {
+	let done = assert.async();
+
+	// number of asserts
+	assert.expect(1);
+
+	frappe.run_serially('POS Profile', [
+		// insert a new POS Profile
+		() => frappe.tests.make([
+			// values to be set
+			{key: 'value'}
+		]),
+		() => {
+			assert.equal(cur_frm.doc.key, 'value');
+		},
+		() => done()
+	]);
+
+});
diff --git a/erpnext/accounts/doctype/pos_profile/test_pos_profile.py b/erpnext/accounts/doctype/pos_profile/test_pos_profile.py
index 9c6a114..534abb6 100644
--- a/erpnext/accounts/doctype/pos_profile/test_pos_profile.py
+++ b/erpnext/accounts/doctype/pos_profile/test_pos_profile.py
@@ -42,6 +42,7 @@
 		"naming_series": "_T-POS Profile-",
 		"selling_price_list": "_Test Price List",
 		"territory": "_Test Territory",
+		"customer_group": frappe.db.get_value('Customer Group', {'is_group': 0}, 'name'),
 		"warehouse": "_Test Warehouse - _TC",
 		"write_off_account": "_Test Write Off - _TC",
 		"write_off_cost_center": "_Test Write Off Cost Center - _TC"
diff --git a/erpnext/accounts/doctype/sales_invoice/pos.py b/erpnext/accounts/doctype/sales_invoice/pos.py
index f61931a..3c9de12 100644
--- a/erpnext/accounts/doctype/sales_invoice/pos.py
+++ b/erpnext/accounts/doctype/sales_invoice/pos.py
@@ -3,6 +3,7 @@
 
 from __future__ import unicode_literals
 import frappe, json
+from frappe import _
 from frappe.utils import nowdate
 from erpnext.setup.utils import get_exchange_rate
 from frappe.core.doctype.communication.email import make
@@ -20,6 +21,7 @@
 
 	if pos_profile.get('name'):
 		pos_profile = frappe.get_doc('POS Profile', pos_profile.get('name'))
+		pos_profile.validate()
 
 	company_data = get_company_data(doc.company)
 	update_pos_profile_data(doc, pos_profile, company_data)
@@ -378,13 +380,27 @@
 	customer_doc.customer_name = data.get('full_name') or data.get('customer')
 	customer_doc.customer_pos_id = data.get('customer_pos_id')
 	customer_doc.customer_type = 'Company'
-	customer_doc.customer_group = frappe.db.get_single_value('Selling Settings', 'customer_group')
-	customer_doc.territory = frappe.db.get_single_value('Selling Settings', 'territory')
+	customer_doc.customer_group = get_customer_group(data)
+	customer_doc.territory = get_territory(data)
 	customer_doc.flags.ignore_mandatory = True
 	customer_doc.save(ignore_permissions = True)
 	frappe.db.commit()
 	return customer_doc.name
 
+def get_territory(data):
+	if data.get('territory'):
+		return data.get('territory')
+
+	return frappe.db.get_single_value('Selling Settings',
+		'territory') or _('All Territories')
+
+def get_customer_group(data):
+	if data.get('customer_group'):
+		return data.get('customer_group')
+
+	return frappe.db.get_single_value('Selling Settings',
+		'customer_group') or frappe.db.get_value('Customer Group', {'is_group': 0}, 'name')
+
 def make_contact(args,customer):
 	if args.get('email_id') or args.get('phone'):
 		name = frappe.db.get_value('Dynamic Link',
diff --git a/erpnext/accounts/page/pos/pos.js b/erpnext/accounts/page/pos/pos.js
index a5f9b3c..d69a306 100644
--- a/erpnext/accounts/page/pos/pos.js
+++ b/erpnext/accounts/page/pos/pos.js
@@ -979,6 +979,8 @@
 	get_prompt_details: function() {
 		this.prompt_details = this.customer_doc.get_values();
 		this.prompt_details['country'] = this.pos_profile_data.country;
+		this.prompt_details['territory'] = this.pos_profile_data["territory"];
+		this.prompt_details['customer_group'] = this.pos_profile_data["customer_group"];
 		this.prompt_details['customer_pos_id'] = this.customer_doc.fields_dict.customer_pos_id.value;
 		return JSON.stringify(this.prompt_details)
 	},
diff --git a/erpnext/accounts/party.py b/erpnext/accounts/party.py
index 005abe6..0f8b92f 100644
--- a/erpnext/accounts/party.py
+++ b/erpnext/accounts/party.py
@@ -273,6 +273,7 @@
 	return due_date
 
 def get_credit_days(party_type, party, company):
+	credit_days = 0
 	if party_type and party:
 		if party_type == "Customer":
 			credit_days_based_on, credit_days, customer_group = \
@@ -282,10 +283,10 @@
 				frappe.db.get_value(party_type, party, ["credit_days_based_on", "credit_days", "supplier_type"])
 
 	if not credit_days_based_on:
-		if party_type == "Customer":
+		if party_type == "Customer" and customer_group:
 			credit_days_based_on, credit_days = \
 				frappe.db.get_value("Customer Group", customer_group, ["credit_days_based_on", "credit_days"])
-		else:
+		elif party_type == "Supplier" and supplier_type:
 			credit_days_based_on, credit_days = \
 				frappe.db.get_value("Supplier Type", supplier_type, ["credit_days_based_on", "credit_days"])
 
diff --git a/erpnext/patches.txt b/erpnext/patches.txt
index fb8f02e..e3a2e58 100644
--- a/erpnext/patches.txt
+++ b/erpnext/patches.txt
@@ -423,4 +423,5 @@
 erpnext.patches.v8_1.update_expense_claim_status
 erpnext.patches.v8_3.update_company_total_sales
 erpnext.patches.v8_1.set_delivery_date_in_so_item
-erpnext.patches.v8_5.fix_tax_breakup_for_non_invoice_docs
\ No newline at end of file
+erpnext.patches.v8_5.fix_tax_breakup_for_non_invoice_docs
+erpnext.patches.v8_5.update_customer_group_in_POS_profile
\ No newline at end of file
diff --git a/erpnext/patches/v8_5/update_customer_group_in_POS_profile.py b/erpnext/patches/v8_5/update_customer_group_in_POS_profile.py
new file mode 100644
index 0000000..9a5fef9
--- /dev/null
+++ b/erpnext/patches/v8_5/update_customer_group_in_POS_profile.py
@@ -0,0 +1,8 @@
+import frappe
+
+def execute():
+	frappe.reload_doctype('POS Profile')
+	customer_group = frappe.db.get_single_value('Selling Settings', 'customer_group')
+	if customer_group:
+		frappe.db.sql(""" update `tabPOS Profile`
+			set customer_group = %s where customer_group is null """, (customer_group))
\ No newline at end of file