Order with both negative and positive lines. How is the OnHand calculated?

I’m having a hard time trying to understand this. My users need to post an invoice from a SalesOrder with, for the same item, both negative and positive lines (negative lines should add quantity to the inventLocation and positive should consume that quantity).

For example:
Order 001
item A, qty -2
item A, qty +2
item B, qty -2
item B, qty +2

Somehow they way Ax calculates the available qty for these items seems to be random… most of the time looks like it depends on the order you insert them on the order (e.g if i first insert the negative qty, then I find enogh onHand to consume the positive one). But now I’m stuck in an order where it keeps saying there is not enough qty to post the invoice even if the sum of the qty for each item is exactly 0 and I put in first the negative lines and then the positive ones.

Any clue?