Checking the balances
The general method of monitoring item balances during document posting is as follows: first, write the register records generated by the document without any checks, and then read the balance values from the database.
If a negative balance value is detected, the document cannot be posted. Instead the applied solution should inform the user about the missing materials and undo the posting.
If no negative balance values are detected, a document can be posted without hesitation.
You are actually half-finished with this task: you implemented the generation and writing of document register records. The only thing you still need to do is monitor the results of real-time posting and undo the posting if a negative balance value is found.