I'm not able to see an issue with the piece of code that you have pasted here. Maybe you could open a bug report with halcust attached and repeatable situation that I can look at?
Hello!
You can mark it as closed as option. If document is connected with other documents you can not delete it so you will not be able to delete PO, as you will not be able to remove Goods receipt...