Negative invoice Quantity on converting sales order to invoice Dynamics GP

Solving why the sales order created a negative invoice quantity in Dynamics GP.

Finance team reported an invoice with Qty To Invoice of -8750
The originating sales order that had been converted to invoice had zero to invoice for that line.

After some deep investigations utilsing lots of sales order logging tables I concluded it is due to a corrupt sale order line record.

For that sales line the quantity figures looked like this:
QTYONPO = 11800
QtyToInvoice of 3050

QtyToInvoice had been taken down to zero before invoicing.
11800-3050=8750

So it looked like the QTYONPO field was involved. This led to noticing that the PURCHSTAT field had a value of 3. That normally is the case where the sales line has a purchase order commitment in table SOP60100.

Running the following query showwed this record was the only one that had purchasing status of 3 (3 – Purchased).

SELECT *
FROM SOP10200 WHERE  PURCHSTAT=3
AND 
NOT EXISTS
(
	SELECT 1 FROM SOP60100
	WHERE SOPTYPE = SOP10200.SOPTYPE
		AND SOPNUMBE = SOP10200.SOPNUMBE
		AND LNITMSEQ = SOP10200.LNITMSEQ
		AND CMPNTSEQ = SOP10200.CMPNTSEQ
)

So it has no purchase order committed, even though the line has values in the fields relating to that function.

I assume this caused the invoice to try and invoice the about purchased but as the quantity to invoice was zero it had gone to a negative value.

The above SQL check is now added as a step before invoicing to check for any other corrupt records. I assume at some point in the past this order line had a purchase order committed that was later removed, but left the sales order line in this inconsitent state.