Custom Script: Discount %

Hi,

I am trying to calculate total qty and cash discount in the Sales Invoice. The cash discount will be 1% of the total net_amount. Though, the qty is calculating correctly, the cash discount is not getting refreshed. Can you please help? When my net_amount changes from 6000 to 8000, it shows 60, whereas it should be showing 80.

var calculate_total_qty = function(frm) {
var total_qty = frappe.utils.sum(
(frm.doc.items || []).map(function(i) { return i.qty; })
);

    frm.set_value("total_qty", total_qty);
    refresh_field("total_qty");
    refresh_field("net_amount");
   
    var total_amount = frappe.utils.sum(
           (frm.doc.items || []).map(function(i) { return i.net_amount; })
);
    frm.set_value("cash_discount", total_amount * 0.01);
    refresh_field("cash_discount");

}

frappe.ui.form.on(“Sales Invoice Item”, “qty”, function(frm, cdt, cdn) {
calculate_total_qty(frm, cdt, cdn);
})

@uma13 don’t change standard totals field directly,
Add your 1% discount to standard discount field, then it will be auto calculated in net total.
ERPNext recalculate all calculation on save/submits event.

Thanks a lot for the prompt response. Actually, I wish to give 1% additional cash discount on the Net Amount. I have tried to write this script. Though, it is working, it is recalculating the discount amount again and adding the cash discount again to the field. When I add Msgprint command in between to debug, I could see that the script is executing twice. Can you please see why my script is running twice? Thanks a ton for your support.

frappe.ui.form.on(“Sales Invoice”, “additional_discount_percentage”, function(frm) {
frappe.model.set_value(frm.doctype, frm.docname, “cash_discount”, frm.doc.net_total*0.01);
frappe.model.set_value(frm.doctype, frm.docname, “discount_amount”, frm.doc.discount_amount + (frm.doc.cash_discount));

});