fix: On change of currency, set margin amount based on exchange rate (#17712)

diff --git a/erpnext/public/js/controllers/transaction.js b/erpnext/public/js/controllers/transaction.js
index 7de0e62..329695e 100644
--- a/erpnext/public/js/controllers/transaction.js
+++ b/erpnext/public/js/controllers/transaction.js
@@ -756,7 +756,11 @@
 
 			this.get_exchange_rate(transaction_date, this.frm.doc.currency, company_currency,
 				function(exchange_rate) {
-					me.frm.set_value("conversion_rate", exchange_rate);
+					if(exchange_rate != me.frm.doc.conversion_rate) {
+						me.set_margin_amount_based_on_currency(exchange_rate);
+						me.set_actual_charges_based_on_currency(exchange_rate);
+						me.frm.set_value("conversion_rate", exchange_rate);
+					}
 				});
 		} else {
 			this.conversion_rate();
@@ -777,7 +781,6 @@
 			if(this.frm.doc.ignore_pricing_rule) {
 				this.calculate_taxes_and_totals();
 			} else if (!this.in_apply_price_list){
-				this.set_actual_charges_based_on_currency();
 				this.apply_price_list();
 			}
 
@@ -804,12 +807,24 @@
 		}
 	},
 
-	set_actual_charges_based_on_currency: function() {
+	set_margin_amount_based_on_currency: function(exchange_rate) {
+		if (in_list(["Quotation", "Sales Order", "Delivery Note", "Sales Invoice"]), this.frm.doc.doctype) {
+			var me = this;
+			$.each(this.frm.doc.items || [], function(i, d) {
+				if(d.margin_type == "Amount") {
+					frappe.model.set_value(d.doctype, d.name, "margin_rate_or_amount",
+						flt(d.margin_rate_or_amount) / flt(exchange_rate));
+				}
+			});
+		}
+	},
+
+	set_actual_charges_based_on_currency: function(exchange_rate) {
 		var me = this;
 		$.each(this.frm.doc.taxes || [], function(i, d) {
 			if(d.charge_type == "Actual") {
 				frappe.model.set_value(d.doctype, d.name, "tax_amount",
-					flt(d.tax_amount) / flt(me.frm.doc.conversion_rate));
+					flt(d.tax_amount) / flt(exchange_rate));
 			}
 		});
 	},