Merge pull request #3209 from rmehta/email-threading

[email] changes in email_account api
diff --git a/erpnext/patches/v4_2/party_model.py b/erpnext/patches/v4_2/party_model.py
index ac9a141..d105349 100644
--- a/erpnext/patches/v4_2/party_model.py
+++ b/erpnext/patches/v4_2/party_model.py
@@ -19,15 +19,17 @@
 	receivable_payable_accounts = frappe._dict()
 
 	def _create_account(args):
-		account = frappe.new_doc("Account")
-		account.is_group = 0
-		account.update(args)
-		account.insert()
+		if not frappe.db.get_value("Account", 
+				{"account_name": args["account_name"], "company": args["company"]}):
+			account = frappe.new_doc("Account")
+			account.is_group = 0
+			account.update(args)
+			account.insert()
 
-		frappe.db.set_value("Company", args["company"], ("default_receivable_account"
-			if args["account_type"]=="Receivable" else "default_payable_account"), account.name)
+			frappe.db.set_value("Company", args["company"], ("default_receivable_account"
+				if args["account_type"]=="Receivable" else "default_payable_account"), account.name)
 
-		receivable_payable_accounts.setdefault(args["company"], {}).setdefault(args["account_type"], account.name)
+			receivable_payable_accounts.setdefault(args["company"], {}).setdefault(args["account_type"], account.name)
 
 	for company in frappe.db.sql_list("select name from tabCompany"):
 		_create_account({
@@ -47,8 +49,11 @@
 	return receivable_payable_accounts
 
 def get_parent_account(company, master_type):
-	parent_account = frappe.db.get_value("Company", company,
-		"receivables_group" if master_type=="Customer" else "payables_group")
+	parent_account = None
+	
+	if "receivables_group" in frappe.db.get_table_columns("Company"):
+		parent_account = frappe.db.get_value("Company", company,
+			"receivables_group" if master_type=="Customer" else "payables_group")
 	if not parent_account:
 		parent_account = frappe.db.get_value("Account", {"company": company,
 			"account_name": "Accounts Receivable" if master_type=="Customer" else "Accounts Payable"})
@@ -73,7 +78,8 @@
 		return
 
 	for dt in ["Journal Entry Account", "GL Entry"]:
-		records = frappe.db.sql("""select name, account from `tab%s` where account in (%s)""" %
+		records = frappe.db.sql("""select name, account from `tab%s` 
+			where account in (%s) and ifnull(party, '') = ''""" % 
 			(dt, ", ".join(['%s']*len(account_map))), tuple(account_map.keys()), as_dict=1)
 		for i, d in enumerate(records):
 			account_details = account_map.get(d.account, {})
diff --git a/erpnext/public/js/controllers/accounts.js b/erpnext/public/js/controllers/accounts.js
index 15e043b..212d2ae 100644
--- a/erpnext/public/js/controllers/accounts.js
+++ b/erpnext/public/js/controllers/accounts.js
@@ -40,7 +40,7 @@
 		frm.get_docfield("taxes", "rate").reqd = 0;
 		frm.get_docfield("taxes", "tax_amount").reqd = 0;
 
-		$.each(frm.doc.taxes, function(i, d) {
+		$.each(frm.doc.taxes || [], function(i, d) {
 			if(d.charge_type==="Actual") {
 				d.rate = 0;
 				if(!d.tax_amount) {
diff --git a/erpnext/setup/doctype/company/company.js b/erpnext/setup/doctype/company/company.js
index 115fdfa..817fdb6 100644
--- a/erpnext/setup/doctype/company/company.js
+++ b/erpnext/setup/doctype/company/company.js
@@ -5,37 +5,35 @@
 
 frappe.ui.form.on("Company", {
 	onload_post_render: function(frm) {
-		frm.get_field("delete_company").$input.addClass("btn-danger");
+		frm.get_field("delete_company_transactions").$input.addClass("btn-danger");
 	},
 	country: function(frm) {
 		erpnext.company.set_chart_of_accounts_options(frm.doc);
 	},
-	delete_company: function(frm) {
+	delete_company_transactions: function(frm) {
 		var d = frappe.prompt({
 			fieldtype:"Data",
 			fieldname: "company_name",
 			label: __("Please re-type company name to confirm"),
 			reqd: 1,
-			description: __("Please make sure you really want to delete this company and all its transactions. Your master data will remain as it is. This action cannot be undone.")},
+			description: __("Please make sure you really want to delete all the transactions for this company. Your master data will remain as it is. This action cannot be undone.")},
 				function(data) {
 					if(data.company_name !== frm.doc.name) {
 						frappe.msgprint("Company name not same");
 						return;
 					}
 					frappe.call({
-						method: "erpnext.setup.doctype.company.delete_company.delete_company",
+						method: "erpnext.setup.doctype.company.delete_company_transactions.delete_company_transactions",
 						args: {
 							company_name: data.company_name
 						},
 						freeze: true,
-						callback: function(r) {
-							if(!r.exc) {
-								frappe.model.clear_doc("Company", data.company_name);
-								window.history.back();
-							}
+						callback: function(r, rt) {
+							if(!r.exc) 
+								frappe.msgprint(__("Successfully deleted all transactions related to this company!"));
 						}
 					});
-				}, __("Delete Comany and all Related Transactions"), __("Delete"));
+				}, __("Delete all the Transactions for this Company"), __("Delete"));
 
 			d.get_primary_btn().addClass("btn-danger");
 	}
diff --git a/erpnext/setup/doctype/company/company.json b/erpnext/setup/doctype/company/company.json
index f7faf96..0e7b17a 100644
--- a/erpnext/setup/doctype/company/company.json
+++ b/erpnext/setup/doctype/company/company.json
@@ -397,16 +397,16 @@
    "read_only": 0
   }, 
   {
-   "fieldname": "delete_company", 
+   "fieldname": "delete_company_transactions", 
    "fieldtype": "Button", 
-   "label": "Delete Company", 
+   "label": "Delete Company Transactions", 
    "permlevel": 0, 
    "precision": ""
   }
  ], 
  "icon": "icon-building", 
  "idx": 1, 
- "modified": "2015-04-17 01:37:32.304374", 
+ "modified": "2015-05-04 11:22:42.116328", 
  "modified_by": "Administrator", 
  "module": "Setup", 
  "name": "Company", 
diff --git a/erpnext/setup/doctype/company/company.py b/erpnext/setup/doctype/company/company.py
index 26a2797..ad89114 100644
--- a/erpnext/setup/doctype/company/company.py
+++ b/erpnext/setup/doctype/company/company.py
@@ -167,6 +167,33 @@
 			where defkey='Company' and defvalue=%s""", (newdn, olddn))
 
 		frappe.defaults.clear_cache()
+		
+	def on_trash(self):
+		"""
+			Trash accounts and cost centers for this company if no gl entry exists
+		"""
+		rec = frappe.db.sql("SELECT name from `tabGL Entry` where company = %s", self.name)
+		if not rec:
+			# delete Account
+			frappe.db.sql("delete from `tabAccount` where company = %s", self.name)
+
+			# delete cost center child table - budget detail
+			frappe.db.sql("""delete bd.* from `tabBudget Detail` bd, `tabCost Center` cc 
+				where bd.parent = cc.name and cc.company = %s""", self.name)
+			#delete cost center
+			frappe.db.sql("delete from `tabCost Center` WHERE company = %s", self.name)
+
+			# delete account from customer and supplier
+			frappe.db.sql("delete from `tabParty Account` where company=%s", self.name)
+
+		if not frappe.db.get_value("Stock Ledger Entry", {"company": self.name}):
+			frappe.db.sql("""delete from `tabWarehouse` where company=%s""", self.name)
+
+		frappe.defaults.clear_default("company", value=self.name)
+
+		frappe.db.sql("""update `tabSingles` set value=""
+			where doctype='Global Defaults' and field='default_company'
+			and value=%s""", self.name)
 
 @frappe.whitelist()
 def replace_abbr(company, old, new):
diff --git a/erpnext/setup/doctype/company/delete_company.py b/erpnext/setup/doctype/company/delete_company_transactions.py
similarity index 82%
rename from erpnext/setup/doctype/company/delete_company.py
rename to erpnext/setup/doctype/company/delete_company_transactions.py
index 92b6c52..f27ba86 100644
--- a/erpnext/setup/doctype/company/delete_company.py
+++ b/erpnext/setup/doctype/company/delete_company_transactions.py
@@ -8,26 +8,19 @@
 from frappe import _
 
 @frappe.whitelist()
-def delete_company(company_name):
+def delete_company_transactions(company_name):
 	frappe.only_for("System Manager")
 	doc = frappe.get_doc("Company", company_name)
 
 	if frappe.session.user != doc.owner:
-		frappe.throw(_("Company can only be deleted by the creator"), frappe.PermissionError)
+		frappe.throw(_("Transactions can only be deleted by the creator of the Company"), frappe.PermissionError)
 
 	delete_bins(company_name)
 
 	for doctype in frappe.db.sql_list("""select parent from
 		tabDocField where fieldtype='Link' and options='Company'"""):
-		delete_for_doctype(doctype, company_name)
-
-	frappe.delete_doc("Company", company_name)
-
-	frappe.defaults.clear_default("company", value=doc.name)
-
-	frappe.db.sql("""update `tabSingles` set value=""
-		where doctype='Global Defaults' and field='default_company'
-		and value=%s""", doc.name)
+		if doctype not in ("Account", "Cost Center", "Warehouse", "Budget Detail", "Party Account"):
+			delete_for_doctype(doctype, company_name)
 
 def delete_for_doctype(doctype, company_name):
 	meta = frappe.get_meta(doctype)
diff --git a/erpnext/stock/doctype/item/item.json b/erpnext/stock/doctype/item/item.json
index b34983d..282d182 100644
--- a/erpnext/stock/doctype/item/item.json
+++ b/erpnext/stock/doctype/item/item.json
@@ -428,6 +428,7 @@
    "reqd": 1
   }, 
   {
+   "depends_on": "eval:doc.is_purchase_item==\"Yes\"", 
    "fieldname": "default_supplier", 
    "fieldtype": "Link", 
    "ignore_user_permissions": 1, 
@@ -448,7 +449,7 @@
    "read_only": 0
   }, 
   {
-   "depends_on": "eval:doc.is_purchase_item==\"Yes\"", 
+   "depends_on": "", 
    "description": "Default Purchase Account in which cost of the item will be debited.", 
    "fieldname": "expense_account", 
    "fieldtype": "Link", 
@@ -461,7 +462,7 @@
    "read_only": 0
   }, 
   {
-   "depends_on": "eval:doc.is_purchase_item==\"Yes\"", 
+   "depends_on": "", 
    "description": "", 
    "fieldname": "buying_cost_center", 
    "fieldtype": "Link", 
@@ -877,7 +878,7 @@
  "icon": "icon-tag", 
  "idx": 1, 
  "max_attachments": 1, 
- "modified": "2015-03-03 06:18:35.717586", 
+ "modified": "2015-05-04 18:44:46.090445", 
  "modified_by": "Administrator", 
  "module": "Stock", 
  "name": "Item", 
diff --git a/erpnext/stock/doctype/item/item_list.js b/erpnext/stock/doctype/item/item_list.js
index 168252e..c6beeff 100644
--- a/erpnext/stock/doctype/item/item_list.js
+++ b/erpnext/stock/doctype/item/item_list.js
@@ -3,7 +3,7 @@
 		"has_variants", "end_of_life", "is_sales_item"],
 
 	get_indicator: function(doc) {
-		if(doc.end_of_life < frappe.datetime.get_today()) {
+		if(doc.end_of_life && doc.end_of_life < frappe.datetime.get_today()) {
 			return [__("Expired"), "grey", "end_of_life,<,Today"]
 		} else if(doc.has_variants) {
 			return [__("Template"), "blue", "has_variant,=,1"]