Proper way to create a Sales Order in code?

Having spent a lot of time trying to find the “correct” way to create a Sales Order in code, so that it can also be posted as a Sales Invoice seamlessly using Item Tax Templates, I have run into a bug with the cost_center that is set on each tax in the taxes table.

NOTE: I am assigning the Sales Order to a non-default company.

Here’s my process in pseudocode, does anyone know what I’m missing?

New sales_order
Set the fields available, like company, currency, dates, customer...
Run `sales_order.set_missing_values()` !important
For each SO Item:
   Create and set item_code, delivery_date, qty, price_list_rate & append to parent
   sales_order.set_missing_item_details() !important
   set_child_tax_template_and_map(item, so_item, sales_order) !important
   add_taxes_from_tax_template(so_item, sales_order) !important

This works fine and submits, but when creating the Sales Invoice the cost_center on the taxes is set to the default company default cost_center by _set_defaults() in insert() and raises a validation error.

Everything else seems to be set okay, so this is either a bug or I’m missing a function call to update the taxes somewhere.

It’s a long shot, I know…