Merge pull request #27659 from nextchamp-saqib/fix-32644

fix: setting of gain/loss if party account is in company currency
diff --git a/erpnext/accounts/doctype/payment_entry_reference/payment_entry_reference.json b/erpnext/accounts/doctype/payment_entry_reference/payment_entry_reference.json
index 43eb0b6..8961167 100644
--- a/erpnext/accounts/doctype/payment_entry_reference/payment_entry_reference.json
+++ b/erpnext/accounts/doctype/payment_entry_reference/payment_entry_reference.json
@@ -93,6 +93,7 @@
    "options": "Payment Term"
   },
   {
+   "depends_on": "exchange_gain_loss",
    "fieldname": "exchange_gain_loss",
    "fieldtype": "Currency",
    "label": "Exchange Gain/Loss",
@@ -103,7 +104,7 @@
  "index_web_pages_for_search": 1,
  "istable": 1,
  "links": [],
- "modified": "2021-04-21 13:30:11.605388",
+ "modified": "2021-09-26 17:06:55.597389",
  "modified_by": "Administrator",
  "module": "Accounts",
  "name": "Payment Entry Reference",
diff --git a/erpnext/accounts/doctype/purchase_invoice_advance/purchase_invoice_advance.json b/erpnext/accounts/doctype/purchase_invoice_advance/purchase_invoice_advance.json
index 63dfff8..9fcbf5c 100644
--- a/erpnext/accounts/doctype/purchase_invoice_advance/purchase_invoice_advance.json
+++ b/erpnext/accounts/doctype/purchase_invoice_advance/purchase_invoice_advance.json
@@ -97,6 +97,7 @@
    "width": "100px"
   },
   {
+   "depends_on": "exchange_gain_loss",
    "fieldname": "exchange_gain_loss",
    "fieldtype": "Currency",
    "label": "Exchange Gain/Loss",
@@ -104,6 +105,7 @@
    "read_only": 1
   },
   {
+   "depends_on": "exchange_gain_loss",
    "fieldname": "ref_exchange_rate",
    "fieldtype": "Float",
    "label": "Reference Exchange Rate",
@@ -115,7 +117,7 @@
  "index_web_pages_for_search": 1,
  "istable": 1,
  "links": [],
- "modified": "2021-04-20 16:26:53.820530",
+ "modified": "2021-09-26 15:47:28.167371",
  "modified_by": "Administrator",
  "module": "Accounts",
  "name": "Purchase Invoice Advance",
diff --git a/erpnext/accounts/doctype/sales_invoice_advance/sales_invoice_advance.json b/erpnext/accounts/doctype/sales_invoice_advance/sales_invoice_advance.json
index 29422d6..f92b57a 100644
--- a/erpnext/accounts/doctype/sales_invoice_advance/sales_invoice_advance.json
+++ b/erpnext/accounts/doctype/sales_invoice_advance/sales_invoice_advance.json
@@ -98,6 +98,7 @@
    "width": "120px"
   },
   {
+   "depends_on": "exchange_gain_loss",
    "fieldname": "exchange_gain_loss",
    "fieldtype": "Currency",
    "label": "Exchange Gain/Loss",
@@ -105,6 +106,7 @@
    "read_only": 1
   },
   {
+   "depends_on": "exchange_gain_loss",
    "fieldname": "ref_exchange_rate",
    "fieldtype": "Float",
    "label": "Reference Exchange Rate",
@@ -116,7 +118,7 @@
  "index_web_pages_for_search": 1,
  "istable": 1,
  "links": [],
- "modified": "2021-06-04 20:25:49.832052",
+ "modified": "2021-09-26 15:47:46.911595",
  "modified_by": "Administrator",
  "module": "Accounts",
  "name": "Sales Invoice Advance",
diff --git a/erpnext/controllers/accounts_controller.py b/erpnext/controllers/accounts_controller.py
index 87d5648..e9b531e 100644
--- a/erpnext/controllers/accounts_controller.py
+++ b/erpnext/controllers/accounts_controller.py
@@ -685,13 +685,17 @@
 							.format(d.reference_name, d.against_order))
 
 	def set_advance_gain_or_loss(self):
-		if not self.get("advances"):
+		if self.get('conversion_rate') == 1 or not self.get("advances"):
+			return
+
+		is_purchase_invoice = self.doctype == 'Purchase Invoice'
+		party_account = self.credit_to if is_purchase_invoice else self.debit_to
+		if get_account_currency(party_account) != self.currency:
 			return
 
 		for d in self.get("advances"):
 			advance_exchange_rate = d.ref_exchange_rate
-			if (d.allocated_amount and self.conversion_rate != 1
-				and self.conversion_rate != advance_exchange_rate):
+			if (d.allocated_amount and self.conversion_rate != advance_exchange_rate):
 
 				base_allocated_amount_in_ref_rate = advance_exchange_rate * d.allocated_amount
 				base_allocated_amount_in_inv_rate = self.conversion_rate * d.allocated_amount
@@ -710,7 +714,7 @@
 
 					gain_loss_account = frappe.db.get_value('Company', self.company, 'exchange_gain_loss_account')
 					if not gain_loss_account:
-						frappe.throw(_("Please set Default Exchange Gain/Loss Account in Company {}")
+						frappe.throw(_("Please set default Exchange Gain/Loss Account in Company {}")
 							.format(self.get('company')))
 					account_currency = get_account_currency(gain_loss_account)
 					if account_currency != self.company_currency:
@@ -729,7 +733,7 @@
 							"against": party,
 							dr_or_cr + "_in_account_currency": abs(d.exchange_gain_loss),
 							dr_or_cr: abs(d.exchange_gain_loss),
-							"cost_center": self.cost_center,
+							"cost_center": self.cost_center or erpnext.get_default_cost_center(self.company),
 							"project": self.project
 						}, item=d)
 					)
diff --git a/erpnext/patches.txt b/erpnext/patches.txt
index cee796e..d26c92e 100644
--- a/erpnext/patches.txt
+++ b/erpnext/patches.txt
@@ -309,3 +309,4 @@
 erpnext.patches.v14_0.update_opportunity_currency_fields
 erpnext.patches.v13_0.gst_fields_for_pos_invoice
 erpnext.patches.v13_0.create_accounting_dimensions_in_pos_doctypes
+erpnext.patches.v13_0.modify_invalid_gain_loss_gl_entries
\ No newline at end of file
diff --git a/erpnext/patches/v13_0/modify_invalid_gain_loss_gl_entries.py b/erpnext/patches/v13_0/modify_invalid_gain_loss_gl_entries.py
new file mode 100644
index 0000000..fa8a864
--- /dev/null
+++ b/erpnext/patches/v13_0/modify_invalid_gain_loss_gl_entries.py
@@ -0,0 +1,49 @@
+from __future__ import unicode_literals
+
+import json
+
+import frappe
+
+
+def execute():
+	frappe.reload_doc('accounts', 'doctype', 'purchase_invoice_advance')
+	frappe.reload_doc('accounts', 'doctype', 'sales_invoice_advance')
+
+	purchase_invoices = frappe.db.sql("""
+		select
+			parenttype as type, parent as name
+		from
+			`tabPurchase Invoice Advance`
+		where
+			ref_exchange_rate = 1
+			and docstatus = 1
+			and ifnull(exchange_gain_loss, '') != ''
+		group by
+			parent
+	""", as_dict=1)
+
+	sales_invoices = frappe.db.sql("""
+		select
+			parenttype as type, parent as name
+		from
+			`tabSales Invoice Advance`
+		where
+			ref_exchange_rate = 1
+			and docstatus = 1
+			and ifnull(exchange_gain_loss, '') != ''
+		group by
+			parent
+	""", as_dict=1)
+
+	if purchase_invoices + sales_invoices:
+		frappe.log_error(json.dumps(purchase_invoices + sales_invoices, indent=2), title="Patch Log")
+
+	for invoice in purchase_invoices + sales_invoices:
+		doc = frappe.get_doc(invoice.type, invoice.name)
+		doc.docstatus = 2
+		doc.make_gl_entries()
+		for advance in doc.advances:
+			if advance.ref_exchange_rate == 1:
+				advance.db_set('exchange_gain_loss', 0, False)
+		doc.docstatus = 1
+		doc.make_gl_entries()
\ No newline at end of file