[patch] Update billing status in Delivery Note and Purchase Receipt
diff --git a/erpnext/change_log/current/billing_status_in_dn_and_pr.md b/erpnext/change_log/current/billing_status_in_dn_and_pr.md
new file mode 100644
index 0000000..b504020
--- /dev/null
+++ b/erpnext/change_log/current/billing_status_in_dn_and_pr.md
@@ -0,0 +1,4 @@
+- Billing Status in Delivery Note (DN) and Purchase Receipt (PR)
+	- If Invoice made directly against DN/PR, calculate based on actual billed amount
+	- If Invoice made via Sales Order/Purchase Order, allocate billed amount in DN/PR based on FIFO
+	- Billing status updated in existing DN/PR
\ No newline at end of file
diff --git a/erpnext/patches/v6_16/__init__.py b/erpnext/patches/v6_16/__init__.py
new file mode 100644
index 0000000..baffc48
--- /dev/null
+++ b/erpnext/patches/v6_16/__init__.py
@@ -0,0 +1 @@
+from __future__ import unicode_literals
diff --git a/erpnext/patches/v6_16/update_billing_status_in_dn_and_pr.py b/erpnext/patches/v6_16/update_billing_status_in_dn_and_pr.py
new file mode 100644
index 0000000..34770e5
--- /dev/null
+++ b/erpnext/patches/v6_16/update_billing_status_in_dn_and_pr.py
@@ -0,0 +1,33 @@
+# Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and Contributors
+# License: GNU General Public License v3. See license.txt
+
+from __future__ import unicode_literals
+import frappe
+
+def execute():
+	for dt in ("Delivery Note", "Purchase Receipt"):
+		frappe.reload_doctype(dt)
+		frappe.reload_doctype(dt + " Item")
+		
+	# Update billed_amt in DN and PR which are not against any order
+	for d in frappe.db.sql("""select name from `tabDelivery Note Item` 
+		where (so_detail is null or so_detail = '') and docstatus=1""", as_dict=1):
+			billed_amt = frappe.db.sql("""select sum(amount) from `tabSales Invoice Item` 
+				where dn_detail=%s and docstatus=1""", d.name)
+			billed_amt = billed_amt and billed_amt[0][0] or 0
+			frappe.db.set_value("Delivery Note Item", d.name, "billed_amt", billed_amt)
+			
+	# Update billed_amt in DN and PR which are not against any order
+	for d in frappe.db.sql("""select name from `tabPurchase Receipt Item` 
+		where (prevdoc_detail_docname is null or prevdoc_detail_docname = '') and docstatus=1""", as_dict=1):
+			billed_amt = frappe.db.sql("""select sum(amount) from `tabPurchase Invoice Item` 
+				where pr_detail=%s and docstatus=1""", d.name)
+			billed_amt = billed_amt and billed_amt[0][0] or 0
+			frappe.db.set_value("Purchase Receipt Item", d.name, "billed_amt", billed_amt)
+		
+	# Update billed amt which are against order or invoice
+	# Update billing status for all
+	for d in frappe.db.sql("select name from `tab{0}` where docstatus=1".format(dt), as_dict=1):
+		doc = frappe.get_doc(dt, d.name)
+		doc.update_billing_status(set_modified=False)
+		doc.set_status(update=True, update_modified=False)
\ No newline at end of file