Doctype linkage and reference when created via server scripts

First of all sorry in advance if this is posted in the wrong section since i’m new to the Frappe community

Hi. i am trying to accomplish some form of automation task between sales order and delivery note using server script. On submission of a sales order a new delivery note is created automatically. So far my script has successfully executed and a new delivery note is automatically created but this new document fails to link or refer from which sales order it is created and vice versa.

Server Script for On Submit Event:

items_to_load = []
for item in doc.items:
items_to_load.append({‘item_code’: item.item_code, ‘rate’: item.rate, ‘qty’: item.qty, ‘uom’: item.uom})

frappe.get_doc(dict(
doctype = ‘Delivery Note’,
title = doc.customer,
customer = doc.customer_name,
company = doc.company,
docstatus = 0,
items = items_to_load,
)).insert(ignore_permissions=True)

frappe.msgprint(msg=(f"Delivery Note for {doc.customer_name} has been created"),title=(“Automation Success”), indicator=“green”)

Any help would be greatly appreciated.

i just learned that i could use doc.name in the script to retrieve sales order document name and pass it to a custom field in delivery note. But this still doesn’t solve the problem of linkage and reference to each other.

please add this
‘against_sales_order’:doc.name, ‘so_detail’:item.name

“Against Sales Order” only is not enough for Sales Order and Delivery Note linkage. Child item table should be considered too. This should solve your problem

While the automation will work, you should also relook into your workflow. Instead of creating docs automatically, just use Sales Invoice with “Update Stock” instead?

Also this function maps order SO to Delivery Note when you click Create > Delivery Note on frontend: https://github.com/frappe/erpnext/blob/96db5b9aedd55fd5502ae593cca91addd2bab9bf/erpnext/selling/doctype/sales_order/sales_order.py#L560