fix: gl entries for exchange gain loss (#26734)

diff --git a/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
index ca4d009..4bc22a5 100644
--- a/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
+++ b/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
@@ -997,8 +997,8 @@
 
 		expected_gle = [
 			["_Test Account Cost for Goods Sold - _TC", 37500.0],
-			["_Test Payable USD - _TC", -40000.0],
-			["Exchange Gain/Loss - _TC", 2500.0]
+			["_Test Payable USD - _TC", -35000.0],
+			["Exchange Gain/Loss - _TC", -2500.0]
 		]
 
 		gl_entries = frappe.db.sql("""
@@ -1028,8 +1028,8 @@
 
 		expected_gle = [
 			["_Test Account Cost for Goods Sold - _TC", 36500.0],
-			["_Test Payable USD - _TC", -38000.0],
-			["Exchange Gain/Loss - _TC", 1500.0]
+			["_Test Payable USD - _TC", -35000.0],
+			["Exchange Gain/Loss - _TC", -1500.0]
 		]
 
 		gl_entries = frappe.db.sql("""
diff --git a/erpnext/controllers/accounts_controller.py b/erpnext/controllers/accounts_controller.py
index cdd865a..a9b7efb 100644
--- a/erpnext/controllers/accounts_controller.py
+++ b/erpnext/controllers/accounts_controller.py
@@ -674,19 +674,24 @@
 		if self.get('doctype') in ['Purchase Invoice', 'Sales Invoice']:
 			for d in self.get("advances"):
 				if d.exchange_gain_loss:
-					party = self.supplier if self.get('doctype') == 'Purchase Invoice' else self.customer
-					party_account = self.credit_to if self.get('doctype') == 'Purchase Invoice' else self.debit_to
-					party_type = "Supplier" if self.get('doctype') == 'Purchase Invoice' else "Customer"
+					is_purchase_invoice = self.get('doctype') == 'Purchase Invoice'
+					party = self.supplier if is_purchase_invoice else self.customer
+					party_account = self.credit_to if is_purchase_invoice else self.debit_to
+					party_type = "Supplier" if is_purchase_invoice else "Customer"
 
 					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 {}")
+							.format(self.get('company')))
 					account_currency = get_account_currency(gain_loss_account)
 					if account_currency != self.company_currency:
-						frappe.throw(_("Currency for {0} must be {1}").format(d.account, self.company_currency))
+						frappe.throw(_("Currency for {0} must be {1}").format(gain_loss_account, self.company_currency))
 
 					# for purchase
 					dr_or_cr = 'debit' if d.exchange_gain_loss > 0 else 'credit'
-					# just reverse for sales?
-					dr_or_cr = 'debit' if dr_or_cr == 'credit' else 'credit'
+					if not is_purchase_invoice:
+						# just reverse for sales?
+						dr_or_cr = 'debit' if dr_or_cr == 'credit' else 'credit'
 
 					gl_entries.append(
 						self.get_gl_dict({