Need help on a custom script for Sales Invoice


I have added a custom field in my Sales Invoice Item table, named ‘vat_rate’. And I have added a custom script which actually set the Sales Invoice Items ‘rate, amount’ based on the ‘vat_rate’. The script works fine, but the ‘total’ field in the parent document [ Sales Invoice] is not getting updated in real time but gets updated after save.

The ‘total’ field gets updated when we change ‘qty, rate’ manually, but why it’s not working when the ‘rate’ is getting set by a custom script? And how can I do this? Here’s the code.

 function vat_tax(frm, cdt, cdn) {
        for ( let i in frm.doc.items){
        	if (frm.doc.items[i].item_tax_template == "VAT 5") { 
                frm.doc.items[i].rate =  (frm.doc.items[i].vat_rate - ((frm.doc.items[i].vat_rate * 5)/(105)));
                frm.doc.items[i].amount =  (frm.doc.items[i].rate * frm.doc.items[i].qty);
    frappe.ui.form.on("Sales Invoice Item", "vat_rate", vat_tax);
    frappe.ui.form.on("Sales Invoice Item", "sales_invoice_item_remove", vat_tax);