Sum of item qty in sales invoice

Hello @nabinhait

See below a code you wrote last year for calculating and displaying item qty in a sales invoice

frappe.ui.form.on(“Sales Invoice Item”, “qty”, function(frm, cdt, cdn) {
// code for calculate total and set on parent field.
total_qty = 0;
$.each(frm.doc.items || [], function(i, d) {
total_qty += flt(d.qty);
});
frm.set_value(“net_weight”, total_qty);
});

I have used this code in a custom script, it does not work well for the following reasons

it does not add up the qty unless you change the item qty from 1 to another qty (2 3 etc) so you may have 10 different items in the item grid, but the total will be zero, if however you change the qty of just 1 of the item to 2 or above the total qty becomes accurate. You must change the qty of at least 1 of the items.

if you delete an item, the item qty does not reduce but stays the same, but if you reduce the qty by keying in a new qty, it works

Please how do I address this two issues? They make the code useless for me.

Regards

can you try the following code?
total function fires when item add and remove.

frappe.ui.form.on("Sales Invoice Item", {
	items_add: function(doc,cdt,cdn){
	    cur_frm.cscript.total(doc.doc,cdt,cdn);
	},
    items_remove: function(doc,cdt,cdn){
	    cur_frm.cscript.total(doc.doc,cdt,cdn);
	}
});

cur_frm.cscript.total = function(doc,cdt,cdn) {
	var total_qty = 0;
    $.each(doc.items || [], function(i, d) {
        total_qty += flt(d.qty);
    });
    cur_frm.set_value(“net_weight”, total_qty);
};

edit:
you can also set event on qty:

qty: function(doc,cdt,cdn){
    cur_frm.cscript.total(doc.doc,cdt,cdn);
}
2 Likes

Best would be to trigger calculation on before_save/validate event something like below:

frappe.ui.form.on("Sales Invoice", {
	validate: function(frm) {
		total_qty = 0;
		$.each(frm.doc.items || [], function(i, d) {
			total_qty += flt(d.qty);
		});
		frm.set_value("net_weight", total_qty);
	}
});
5 Likes

Thank you all

I am good now

Much appreciated

1 Like