How to subtract 2 fields and store their values

I have written a client script in which I have created a custom field “Buy Back” and if a value is input in it then the value of the “amount” field should be reduced.
Till now everything is working perfect but after saving it is showing its previous value.
My code :point_down:

frappe.ui.form.on('Sales Invoice Item', {
custom_buy_back: function(frm, cdt, cdn) {
    var item = locals[cdt][cdn];
    if (item.custom_buy_back) {
        frappe.model.set_value(cdt, cdn, 'amount', item.amount - item.custom_buy_back);
        calculate_total(frm);
    }
},
amount: function(frm) {
    calculate_total(frm);
}
});

function calculate_total(frm) {
var total_amount = frm.doc.items.reduce((total, item) => total + item.amount, 0);
frm.set_value('total', total_amount);
}

Output Screen-shot :point_down:
Before Save

After Save

Please help me in this.
Thank You.

1 Like

Please read the comment regarding Total and amount.

Thanks for your reply,
I have seen this post taking reference from here and wrote this code but I am not able to understand how to solve this issue,
I just have to subtract the amount from buy back and further process which is follow by ERPNext.
Can you help? Why is it showing the previous value after saving?

Hello,
Even if you change the value of Amount. Eventually it runs the code of ERPNext to Calculate the Amount = Rate * Qty. So you can not directly change the value of Amount. You will have to follow another logic for this.

Can anyone help me to solve this please?