Problem with Permission for Linked Doc at Script

Following scenario

User A, which has user permissions limited to Company A is triggering a server side script that shall create a Sales Order for Main Company.

@frappe.whitelist()
def make_sales_order_auto(doc, handler=""):  
        so = frappe.new_doc("Sales Order")
        for po_item in doc.items:
            so.append("items", { "item_code":po_item.item_code})
        so.ignore_permissions=True
        so.flags.ignore_permissions = 1        
        so.ignore_linked_doctypes = ['Company']        
        so.update({
                "po_no": doc.name,
                "delivery_date": doc.schedule_date,
				"company": "Main Company",
                "customer": doc.company,
        })
        so.ignore_permissions=True
        so.insert(ignore_permissions=True)
        frappe.db.commit()

(Note: remove some more fields for better reading.)

Good: The Sales Order for “Main Company” is created.

Not Good: User a receives the following message:

Setting the “ignore permission” flag on the company field of the Sales Order would solve this issue, but as a sideeffect User A would be able to create Sales Orders for all other companies. Not good.

Any idea what else I could try?

worked again on this problem.
seems like first inserting (which sets the company to “Company A” somwhere in the background",
and then in a second step changing it back to Main Company and saving with the ignore flag leads to the expcted outcome.

The Sales Order is stored for Main Company, and only visible to users of Main Company. User A does not get error messages, nor does he see the new Sales Order. Everything fine.

@frappe.whitelist()
def make_sales_order_again(doc, handler=""):
        so = frappe.new_doc("Sales Order")
        lots of other stuff.
        so.insert(ignore_permissions=True, ignore_links=True,ignore_mandatory=True)
        so.company="Main Company"
        so.save(ignore_permissions=True)