Codeunit 80 has a HUGE sblock of code that starts with “WITH SalesHeader DO BEGIN”. In there, many pages down, you will find a statement “DELETE”, that’s where the header is deleted. The lines and other related records are deleted elsewhere. Start debugging the process, and when you jump into codeunit 80, set a breakpoint near the statement that says “// Modify/delete sales header and sales lines”, that’s where the process of cleaning starts.
To make things a bit easier you may also follow, in codeunit 80, the adventures of a boolean field called EverythingInvoiced - look at where and when its status is changed and where it is tested.