Help with custom script to show total gross profit in quotation

Hi, I’m trying to get the total sum of the gross_profit column in the doctype Quotation Item to show up in the Quotation doctype. Like so:

I used this in custom script:

frappe.ui.form.on(“Quotation Item”, {
items_add: function (frm, cdt, cdn) {
var d = locals[cdt][cdn];
var total = 0;
frm.doc.items.forEach(function (d) {
total += d.gross_profit;
});
frm.set_value(“total_gross_profit”, total);
refresh_field(“total_gross_profit”);
},
items_remove: function (frm, cdt, cdn) {
var d = locals[cdt][cdn];
var total = 0;
frm.doc.items.forEach(function (d) {
total += d.gross_profit;
});
frm.set_value(“total_gross_profit”, total);
refresh_field(“total_gross_profit”);
}
});

It works when I delete a row but when I add a row I get NaN and then when I save the quotation, I get a 0.

Can anyone help me with this please?

Try using validate trigger