Merge pull request #3374 from nabinhait/develop

Make gl entry for rounded-off amount
diff --git a/erpnext/accounts/doctype/account/account.json b/erpnext/accounts/doctype/account/account.json
index 77eaf65..fa737a7 100644
--- a/erpnext/accounts/doctype/account/account.json
+++ b/erpnext/accounts/doctype/account/account.json
@@ -101,7 +101,7 @@
    "label": "Account Type", 
    "oldfieldname": "account_type", 
    "oldfieldtype": "Select", 
-   "options": "\nBank\nCash\nTax\nChargeable\nWarehouse\nReceivable\nPayable\nEquity\nFixed Asset\nCost of Goods Sold\nExpense Account\nIncome Account\nStock Received But Not Billed\nExpenses Included In Valuation\nStock Adjustment\nStock\nTemporary", 
+   "options": "\nBank\nCash\nTax\nChargeable\nWarehouse\nReceivable\nPayable\nEquity\nFixed Asset\nCost of Goods Sold\nExpense Account\nRound Off\nIncome Account\nStock Received But Not Billed\nExpenses Included In Valuation\nStock Adjustment\nStock\nTemporary", 
    "permlevel": 0, 
    "search_index": 0
   }, 
@@ -171,7 +171,7 @@
  "icon": "icon-money", 
  "idx": 1, 
  "in_create": 0, 
- "modified": "2015-04-27 20:07:37.147184", 
+ "modified": "2015-05-28 14:10:40.606010", 
  "modified_by": "Administrator", 
  "module": "Accounts", 
  "name": "Account", 
diff --git a/erpnext/accounts/doctype/account/chart_of_accounts/verified/standard_chart_of_accounts.py b/erpnext/accounts/doctype/account/chart_of_accounts/verified/standard_chart_of_accounts.py
index dd3c067..481ada8 100644
--- a/erpnext/accounts/doctype/account/chart_of_accounts/verified/standard_chart_of_accounts.py
+++ b/erpnext/accounts/doctype/account/chart_of_accounts/verified/standard_chart_of_accounts.py
@@ -117,8 +117,8 @@
 	            _("Print and Stationary"): {
 	                "account_type": "Expense Account"
 	            },
-	            _("Rounded Off"): {
-	                "account_type": "Expense Account"
+	            _("Round Off"): {
+	                "account_type": "Round Off"
 	            },
 	            _("Salary"): {
 	                "account_type": "Expense Account"
diff --git a/erpnext/accounts/doctype/gl_entry/test_gl_entry.py b/erpnext/accounts/doctype/gl_entry/test_gl_entry.py
new file mode 100644
index 0000000..383409c
--- /dev/null
+++ b/erpnext/accounts/doctype/gl_entry/test_gl_entry.py
@@ -0,0 +1,25 @@
+# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
+# License: GNU General Public License v3. See license.txt
+
+from __future__ import unicode_literals
+import frappe, unittest
+from erpnext.accounts.doctype.journal_entry.test_journal_entry import make_journal_entry
+
+class TestGLEntry(unittest.TestCase):
+	def test_round_off_entry(self):
+		frappe.db.set_value("Company", "_Test Company", "round_off_account", "_Test Write Off - _TC")
+		frappe.db.set_value("Company", "_Test Company", "round_off_cost_center", "_Test Cost Center - _TC")
+		
+		jv = make_journal_entry("_Test Account Cost for Goods Sold - _TC", 
+			"_Test Account Bank Account - _TC", 100, "_Test Cost Center - _TC", submit=False)
+			
+		jv.get("accounts")[0].debit = 100.01
+		jv.flags.ignore_validate = True
+		jv.submit()
+		
+		round_off_entry = frappe.db.sql("""select name from `tabGL Entry`
+			where voucher_type='Journal Entry' and voucher_no = %s 
+			and account='_Test Write Off - _TC' and cost_center='_Test Cost Center - _TC'
+			and ifnull(debit, 0) = 0 and ifnull(credit, 0) = '.01'""", jv.name)
+			
+		self.assertTrue(round_off_entry)
\ No newline at end of file
diff --git a/erpnext/accounts/general_ledger.py b/erpnext/accounts/general_ledger.py
index 9b97e4b..76b5309 100644
--- a/erpnext/accounts/general_ledger.py
+++ b/erpnext/accounts/general_ledger.py
@@ -5,6 +5,7 @@
 import frappe
 from frappe.utils import flt, cstr
 from frappe import _
+from frappe.model.meta import get_field_precision
 from erpnext.accounts.utils import validate_expense_against_budget
 
 
@@ -64,19 +65,13 @@
 
 def save_entries(gl_map, adv_adj, update_outstanding):
 	validate_account_for_auto_accounting_for_stock(gl_map)
-
-	total_debit = total_credit = 0.0
+	round_off_debit_credit(gl_map)
+	
 	for entry in gl_map:
 		make_entry(entry, adv_adj, update_outstanding)
 		# check against budget
 		validate_expense_against_budget(entry)
 
-		# update total debit / credit
-		total_debit += flt(entry.debit)
-		total_credit += flt(entry.credit)
-
-	validate_total_debit_credit(total_debit, total_credit, gl_map)
-
 def make_entry(args, adv_adj, update_outstanding):
 	args.update({"doctype": "GL Entry"})
 	gle = frappe.get_doc(args)
@@ -85,10 +80,6 @@
 	gle.run_method("on_update_with_args", adv_adj, update_outstanding)
 	gle.submit()
 
-def validate_total_debit_credit(total_debit, total_credit, gl_map):
-	if abs(total_debit - total_credit) > 0.005:
-		frappe.throw(_("Debit and Credit not equal for {0} #{1}. Difference is {2}.").format(gl_map[0].voucher_type, gl_map[0].voucher_no, total_debit - total_credit))
-
 def validate_account_for_auto_accounting_for_stock(gl_map):
 	if gl_map[0].voucher_type=="Journal Entry":
 		aii_accounts = [d[0] for d in frappe.db.sql("""select name from tabAccount
@@ -96,7 +87,55 @@
 
 		for entry in gl_map:
 			if entry.account in aii_accounts:
-				frappe.throw(_("Account: {0} can only be updated via Stock Transactions").format(entry.account), StockAccountInvalidTransaction)
+				frappe.throw(_("Account: {0} can only be updated via Stock Transactions")
+					.format(entry.account), StockAccountInvalidTransaction)
+
+def round_off_debit_credit(gl_map):
+	precision = get_field_precision(frappe.get_meta("GL Entry").get_field("debit"),
+		currency=frappe.db.get_value("Company", gl_map[0].company, "default_currency", cache=True))
+	
+	debit_credit_diff = 0.0
+	for entry in gl_map:
+		entry.debit = flt(entry.debit, precision)
+		entry.credit = flt(entry.credit, precision)
+		debit_credit_diff += entry.debit - entry.credit
+	
+	debit_credit_diff = flt(debit_credit_diff, precision)
+	print debit_credit_diff, 1.0 / (10**precision)
+	if abs(debit_credit_diff) >= (2.0 / (10**precision)):
+		frappe.throw(_("Debit and Credit not equal for {0} #{1}. Difference is {2}.")
+			.format(gl_map[0].voucher_type, gl_map[0].voucher_no, debit_credit_diff))
+		
+	elif abs(debit_credit_diff) >= (1.0 / (10**precision)):
+		make_round_off_gle(gl_map, debit_credit_diff)
+		
+def make_round_off_gle(gl_map, debit_credit_diff):
+	round_off_account, round_off_cost_center = frappe.db.get_value("Company", gl_map[0].company, 
+		["round_off_account", "round_off_cost_center"]) or [None, None]
+	if not round_off_account:
+		frappe.throw(_("Please mention Round Off Account in Company"))
+		
+	if not round_off_cost_center:
+		frappe.throw(_("Please mention Round Off Cost Center in Company"))
+		
+	
+	round_off_gle = frappe._dict()
+	for k in ["voucher_type", "voucher_no", "company", 
+		"posting_date", "remarks", "fiscal_year", "is_opening"]:
+			round_off_gle[k] = gl_map[0][k]
+	
+	round_off_gle.update({
+		"account": round_off_account,
+		"debit": abs(debit_credit_diff) if debit_credit_diff < 0 else 0,
+		"credit": debit_credit_diff if debit_credit_diff > 0 else 0,
+		"cost_center": round_off_cost_center,
+		"party_type": None,
+		"party": None,
+		"against_voucher_type": None,
+		"against_voucher": None
+	})
+	
+	gl_map.append(round_off_gle)
 
 
 def delete_gl_entries(gl_entries=None, voucher_type=None, voucher_no=None,
diff --git a/erpnext/accounts/report/gross_profit/gross_profit.py b/erpnext/accounts/report/gross_profit/gross_profit.py
index 618c9cf..98a121a 100644
--- a/erpnext/accounts/report/gross_profit/gross_profit.py
+++ b/erpnext/accounts/report/gross_profit/gross_profit.py
@@ -14,7 +14,7 @@
 	source = gross_profit_data.grouped_data if filters.get("group_by") != "Invoice" else gross_profit_data.data
 
 	group_wise_columns = frappe._dict({
-		"invoice": ["name", "posting_date", "posting_time", "item_code", "item_name", "brand", "description", \
+		"invoice": ["parent", "posting_date", "posting_time", "item_code", "item_name", "brand", "description", \
 			"warehouse", "qty", "base_rate", "buying_rate", "base_amount",
 			"buying_amount", "gross_profit", "gross_profit_percent", "project"],
 		"item_code": ["item_code", "item_name", "brand", "description", "warehouse", "qty", "base_rate",
@@ -50,7 +50,7 @@
 def get_columns(group_wise_columns, filters):
 	columns = []
 	column_map = frappe._dict({
-		"name": _("Sales Invoice") + ":Link/Sales Invoice:120",
+		"parent": _("Sales Invoice") + ":Link/Sales Invoice:120",
 		"posting_date": _("Posting Date") + ":Date",
 		"posting_time": _("Posting Time"),
 		"item_code": _("Item Code") + ":Link/Item",
diff --git a/erpnext/change_log/current/round_off_gl_entry.md b/erpnext/change_log/current/round_off_gl_entry.md
new file mode 100644
index 0000000..9d865c3
--- /dev/null
+++ b/erpnext/change_log/current/round_off_gl_entry.md
@@ -0,0 +1,2 @@
+- Introduce `Round Off` account to book rounding loss automatically 
+- Added 2 new fields 'Round Off Account' and 'Round Off Cost Center' in Company
diff --git a/erpnext/hr/doctype/leave_application/leave_application.json b/erpnext/hr/doctype/leave_application/leave_application.json
index cd32b9c..de1c2b0 100644
--- a/erpnext/hr/doctype/leave_application/leave_application.json
+++ b/erpnext/hr/doctype/leave_application/leave_application.json
@@ -130,6 +130,7 @@
    "description": "", 
    "fieldname": "leave_approver", 
    "fieldtype": "Link", 
+   "ignore_user_permissions": 1, 
    "label": "Leave Approver", 
    "options": "User", 
    "permlevel": 0
@@ -216,7 +217,7 @@
  "idx": 1, 
  "is_submittable": 1, 
  "max_attachments": 3, 
- "modified": "2015-04-30 02:19:39.330689", 
+ "modified": "2015-05-27 18:44:36.708614", 
  "modified_by": "Administrator", 
  "module": "HR", 
  "name": "Leave Application", 
diff --git a/erpnext/manufacturing/doctype/bom/bom.py b/erpnext/manufacturing/doctype/bom/bom.py
index 4c87dc7..d4fa02c 100644
--- a/erpnext/manufacturing/doctype/bom/bom.py
+++ b/erpnext/manufacturing/doctype/bom/bom.py
@@ -424,6 +424,6 @@
 	if bom.docstatus != 1:
 		if not getattr(frappe.flags, "in_test", False):
 			frappe.throw(_("BOM {0} must be submitted").format(bom_no))
-	if item and not (bom.item == item or \
-		bom.item == frappe.db.get_value("Item", item, "variant_of")):
+	if item and not (bom.item.lower() == item.lower() or \
+		bom.item.lower() == frappe.db.get_value("Item", item, "variant_of").lower()):
 		frappe.throw(_("BOM {0} does not belong to Item {1}").format(bom_no, item))
diff --git a/erpnext/patches/v5_0/replace_renamed_fields_in_custom_scripts_and_print_formats.py b/erpnext/patches/v5_0/replace_renamed_fields_in_custom_scripts_and_print_formats.py
index 5ab150d..ef3f1d6 100644
--- a/erpnext/patches/v5_0/replace_renamed_fields_in_custom_scripts_and_print_formats.py
+++ b/erpnext/patches/v5_0/replace_renamed_fields_in_custom_scripts_and_print_formats.py
@@ -9,13 +9,13 @@
 	# NOTE: sequence is important
 	renamed_fields = get_all_renamed_fields()
 
-	for dt, script_field in (("Custom Script", "script"), ("Print Format", "html")):
+	for dt, script_field, ref_dt_field in (("Custom Script", "script", "dt"), ("Print Format", "html", "doc_type")):
 
 		cond1 = " or ".join("""{0} like "%%{1}%%" """.format(script_field, d[0].replace("_", "\\_")) for d in renamed_fields)
 		cond2 = " and standard = 'No'" if dt == "Print Format" else ""
 
-		for name, script in frappe.db.sql("select name, {0} as script from `tab{1}` where ({2}) {3}".format(script_field, dt, cond1, cond2)):
-			update_script(dt, name, script_field, script, renamed_fields)
+		for name, script, ref_dt in frappe.db.sql("select name, {0} as script, {1} as ref_dt from `tab{2}` where ({3}) {4}".format(script_field, ref_dt_field, dt, cond1, cond2)):
+			update_script(dt, name, ref_dt, script_field, script, renamed_fields)
 
 def get_all_renamed_fields():
 	from erpnext.patches.v5_0.rename_table_fieldnames import rename_map
@@ -46,20 +46,20 @@
 	)
 
 	for fields in rename_map.values():
-		valid_fields = [d for d in fields if d[0] != "entries"]
-		renamed_fields += tuple(valid_fields)
+		renamed_fields += tuple(fields)
 	
 	return renamed_fields
 
-def update_script(dt, name, script_field, script, renamed_fields):
+def update_script(dt, name, ref_dt, script_field, script, renamed_fields):
 	for from_field, to_field in renamed_fields:
-		script = re.sub(r"\b{}\b".format(from_field), to_field, script)
-		
-	if dt == "Journal Entry":
+		if from_field != "entries":
+			script = re.sub(r"\b{}\b".format(from_field), to_field, script)
+			
+	if ref_dt == "Journal Entry":
 		script = re.sub(r"\bentries\b", "accounts", script)
-	elif dt == "Bank Reconciliation":
+	elif ref_dt == "Bank Reconciliation":
 		script = re.sub(r"\bentries\b", "journal_entries", script)
-	elif dt in ("Sales Invoice", "Purchase Invoice"):
+	elif ref_dt in ("Sales Invoice", "Purchase Invoice"):
 		script = re.sub(r"\bentries\b", "items", script)
 
 	frappe.db.set_value(dt, name, script_field, script)
\ No newline at end of file
diff --git a/erpnext/setup/doctype/company/company.js b/erpnext/setup/doctype/company/company.js
index 8f28310..2c9d4f5 100644
--- a/erpnext/setup/doctype/company/company.js
+++ b/erpnext/setup/doctype/company/company.js
@@ -4,6 +4,10 @@
 frappe.provide("erpnext.company");
 
 frappe.ui.form.on("Company", {
+	onload: function(frm) {
+		erpnext.company.setup_queries(frm);
+	}, 
+	
 	onload_post_render: function(frm) {
 		frm.get_field("delete_company_transactions").$input.addClass("btn-danger");
 	},
@@ -114,98 +118,44 @@
 	dialog.show();
 }
 
-cur_frm.fields_dict.default_bank_account.get_query = function(doc) {
-	return{
-		filters: [
-			['Account', 'account_type', '=', 'Bank'],
-			['Account', 'is_group', '=', 0],
-			['Account', 'company', '=', doc.name]
-		]
+erpnext.company.setup_queries = function(frm) {
+	$.each([
+		["default_bank_account", {"account_type": "Bank"}], 
+		["default_cash_account", {"account_type": "Cash"}], 
+		["default_receivable_account", {"account_type": "Receivable"}], 
+		["default_payable_account", {"account_type": "Payable"}], 
+		["default_expense_account", {"report_type": "Profit and Loss"}], 
+		["default_income_account", {"report_type": "Profit and Loss"}], 
+		["round_off_account", {"account_type": "Profit and Loss"}],
+		["cost_center", {}],
+		["round_off_cost_center", {}]
+	], function(i, v) {
+		erpnext.company.set_custom_query(frm, v);
+	});
+	
+	if (sys_defaults.auto_accounting_for_stock) {
+		$.each([
+			["stock_adjustment_account", {"report_type": "Profit and Loss"}], 
+			["expenses_included_in_valuation", {"report_type": "Profit and Loss"}],
+			["stock_received_but_not_billed", {"report_type": "Balance Sheet"}]
+		], function(i, v) {
+			erpnext.company.set_custom_query(frm, v);
+		});
 	}
 }
 
-cur_frm.fields_dict.default_cash_account.get_query = function(doc) {
-	return{
-		filters: [
-			['Account', 'account_type', '=', 'Cash'],
-			['Account', 'is_group', '=', 0],
-			['Account', 'company', '=', doc.name]
-		]
-	}
-}
-
-cur_frm.fields_dict.default_receivable_account.get_query = function(doc) {
-	return{
-		filters:{
-			'company': doc.name,
-			"is_group": 0,
-			"account_type": "Receivable"
-		}
-	}
-}
-
-cur_frm.fields_dict.default_payable_account.get_query = function(doc) {
-	return{
-		filters:{
-			'company': doc.name,
-			"is_group": 0,
-			"account_type": "Payable"
-		}
-	}
-}
-
-
-
-cur_frm.fields_dict.default_expense_account.get_query = function(doc) {
-	return{
-		filters:{
-			'company': doc.name,
-			"is_group": 0,
-			"report_type": "Profit and Loss"
-		}
-	}
-}
-
-cur_frm.fields_dict.default_income_account.get_query = function(doc) {
-	return{
-		filters:{
-			'company': doc.name,
-			"is_group": 0,
-			"report_type": "Profit and Loss"
-		}
-	}
-}
-
-cur_frm.fields_dict.cost_center.get_query = function(doc) {
-	return{
-		filters:{
-			'company': doc.name,
-			"is_group": 0,
-		}
-	}
-}
-
-if (sys_defaults.auto_accounting_for_stock) {
-	cur_frm.fields_dict["stock_adjustment_account"].get_query = function(doc) {
+erpnext.company.set_custom_query = function(frm, v) {
+	var filters = {
+		"company": frm.doc.company,
+		"is_group": 0
+	};
+	
+	for (var key in v[1]) 
+		filters[key] = v[1][key];
+	
+	frm.set_query(v[0], function() {
 		return {
-			"filters": {
-				"report_type": "Profit and Loss",
-				"company": doc.name,
-				"is_group": 0
-			}
-		}
-	}
-
-	cur_frm.fields_dict["expenses_included_in_valuation"].get_query =
-		cur_frm.fields_dict["stock_adjustment_account"].get_query;
-
-	cur_frm.fields_dict["stock_received_but_not_billed"].get_query = function(doc) {
-		return {
-			"filters": {
-				"report_type": "Balance Sheet",
-				"company": doc.name,
-				"is_group": 0
-			}
-		}
-	}
-}
+			filters: filters
+		};
+	});
+}
\ No newline at end of file
diff --git a/erpnext/setup/doctype/company/company.json b/erpnext/setup/doctype/company/company.json
index db71d0f..c2d7073 100644
--- a/erpnext/setup/doctype/company/company.json
+++ b/erpnext/setup/doctype/company/company.json
@@ -171,6 +171,15 @@
    "read_only": 0
   }, 
   {
+   "fieldname": "round_off_account", 
+   "fieldtype": "Link", 
+   "ignore_user_permissions": 0, 
+   "label": "Round Off Account", 
+   "options": "Account", 
+   "permlevel": 0, 
+   "precision": ""
+  }, 
+  {
    "fieldname": "column_break0", 
    "fieldtype": "Column Break", 
    "oldfieldtype": "Column Break", 
@@ -212,6 +221,15 @@
    "permlevel": 0
   }, 
   {
+   "fieldname": "round_off_cost_center", 
+   "fieldtype": "Link", 
+   "ignore_user_permissions": 0, 
+   "label": "Round Off Cost Center", 
+   "options": "Cost Center", 
+   "permlevel": 0, 
+   "precision": ""
+  }, 
+  {
    "fieldname": "section_break_22", 
    "fieldtype": "Section Break", 
    "permlevel": 0, 
@@ -414,7 +432,7 @@
  ], 
  "icon": "icon-building", 
  "idx": 1, 
- "modified": "2015-05-19 02:00:41.055138", 
+ "modified": "2015-05-28 12:56:18.175509", 
  "modified_by": "Administrator", 
  "module": "Setup", 
  "name": "Company", 
diff --git a/erpnext/setup/doctype/company/company.py b/erpnext/setup/doctype/company/company.py
index 6c67e60..f1f7cc4 100644
--- a/erpnext/setup/doctype/company/company.py
+++ b/erpnext/setup/doctype/company/company.py
@@ -114,6 +114,7 @@
 	def set_default_accounts(self):
 		self._set_default_account("default_cash_account", "Cash")
 		self._set_default_account("default_bank_account", "Bank")
+		self._set_default_account("round_off_account", "Round Off")
 
 		if cint(frappe.db.get_single_value("Accounts Settings", "auto_accounting_for_stock")):
 			self._set_default_account("stock_received_but_not_billed", "Stock Received But Not Billed")
@@ -161,6 +162,7 @@
 			cc_doc.insert()
 
 		frappe.db.set(self, "cost_center", _("Main") + " - " + self.abbr)
+		frappe.db.set(self, "round_off_cost_center", _("Main") + " - " + self.abbr)
 
 	def before_rename(self, olddn, newdn, merge=False):
 		if merge: