Calculate backorder quantity on Delivery Notes

We would like to use ERPNext for creating Delivery Notes from a Sales Order. Sometimes we sell for example 10 boards, but can only deliver for example 6 boards. This means the quantity on the Sales Order is 10 and the delivered quantity for the first Delivery Note will be 6. I know ERPNext tracks the already delivered quantity. Since we would like to display backorder quantity on the Delivery Note, I have to calculate the already delivered quantity. I tried it using the following way:

  • Find the Sales Order which is related to the current Delivery Note.
  • Get the delivered quantity (delivered_qty)
  • Calculate the quantity to deliver

The only problem is that when you press Submit, the ‘delivered_qty’ is updated immediately. This means, I can’t save a correct Delivery Note, since the backorder quantity will be calculated with the latest ‘delivered_qty’.

So I would like to calculate the already delivered quantity myself. What I think I need to do when creating a Delivery Note is the following:

  • Check if there are more Delivery Notes linked to the same Sales Order. Just check Delivery Notes which are created before the current Delivery Note.
  • Count the quantities for the previously created Delivery Notes.
  • Calculate the backorder quantity.

I tried a lot, but I can’t figure out how I can do this inside the Jinja templates. I struggled a few days with this, but I don’t know the right query/Jinja code.

Could someone help me with this? Thanks!