import frappe

def execute():
	frappe.reload_doctype("Purchase Order Item")
	for po in frappe.get_all("Purchase Order", filters={"delivered_by_supplier": 1}, fields=["name"]):
		purchase_order = frappe.get_doc("Purchase Order", po)
		
		for item in purchase_order.items:
			if item.prevdoc_doctype == "Sales Order":
				delivered_by_supplier = frappe.get_value("Sales Order Item", item.prevdoc_detail_docname, 
					"delivered_by_supplier")
				
				if delivered_by_supplier:
					frappe.db.sql("""update `tabPurchase Order Item` 
						set delivered_by_supplier=1, billed_amt=amount, received_qty=qty
						where name=%s """, item.name)
						
		update_per_received(purchase_order)
		update_per_billed(purchase_order)
	
def update_per_received(po):
	frappe.db.sql(""" update `tabPurchase Order` 
				set per_received = round((select sum(if(qty > ifnull(received_qty, 0), 
					ifnull(received_qty, 0), qty)) / sum(qty) *100 
				from `tabPurchase Order Item` 
				where parent = %(name)s), 2) 
			where name = %(name)s """, {"name": po.name})

def update_per_billed(po):
	frappe.db.sql(""" update `tabPurchase Order` 
				set per_billed = round((select sum( if(amount > ifnull(billed_amt, 0), 
					ifnull(billed_amt, 0), amount)) / sum(amount) *100 
				from `tabPurchase Order Item` 
				where parent = %(name)s), 2) 
			where name = %(name)s """, {"name": po.name})

				

@@ -23,16 +23,57 @@
 cute():%0A
+%09frappe.reload_doctype(%22Purchase Order%22)%0A
 %09frappe.
@@ -110,16 +110,17 @@
  Item%22)%0A
+%0A
 %09for po 
@@ -267,18 +267,16 @@
 r%22, po)%0A
-%09%09
 %0A%09%09for i
@@ -442,17 +442,16 @@
 docname,
- 
 %0A%09%09%09%09%09%22d
@@ -473,20 +473,16 @@
 plier%22)%0A
-%09%09%09%09
 %0A%09%09%09%09if 
@@ -553,25 +553,24 @@
  Order Item%60
- 
 %0A%09%09%09%09%09%09set d
@@ -665,22 +665,16 @@
 m.name)%0A
-%09%09%09%09%09%09
 %0A%09%09updat
@@ -740,17 +740,16 @@
 _order)%0A
-%09
 %0Adef upd
@@ -807,33 +807,32 @@
 bPurchase Order%60
- 
 %0A%09%09%09%09set per_rec
@@ -886,25 +886,24 @@
 ved_qty, 0),
- 
 %0A%09%09%09%09%09ifnull
@@ -938,25 +938,24 @@
 um(qty) *100
- 
 %0A%09%09%09%09from %60t
@@ -968,33 +968,32 @@
 hase Order Item%60
- 
 %0A%09%09%09%09where paren
@@ -1001,33 +1001,32 @@
  = %25(name)s), 2)
- 
 %0A%09%09%09where name =
@@ -1132,17 +1132,16 @@
 e Order%60
- 
 %0A%09%09%09%09set
@@ -1207,17 +1207,16 @@
 amt, 0),
- 
 %0A%09%09%09%09%09if
@@ -1263,17 +1263,16 @@
 nt) *100
- 
 %0A%09%09%09%09fro
@@ -1297,17 +1297,16 @@
 er Item%60
- 
 %0A%09%09%09%09whe
@@ -1330,17 +1330,16 @@
 e)s), 2)
- 
 %0A%09%09%09wher
@@ -1381,13 +1381,9 @@
 name%7D)%0A%0A
-%09%09%09%09
 %0A

drop ship patch