fix: update the project after task deletion so that the % completed s… (#22591)

* fix: update the project after task deletion so that the % completed shows correct value

* fix: patch to correct % complete of previous projects

* fix: for version-13

* fix: removed patch from v13

Co-authored-by: Marica <maricadsouza221197@gmail.com>
Co-authored-by: Anurag Mishra <32095923+Anurag810@users.noreply.github.com>
Co-authored-by: Nabin Hait <nabinhait@gmail.com>
diff --git a/erpnext/patches.txt b/erpnext/patches.txt
index 2fb9d7f..a24f5f7 100644
--- a/erpnext/patches.txt
+++ b/erpnext/patches.txt
@@ -713,6 +713,7 @@
 erpnext.patches.v13_0.check_is_income_tax_component #22-06-2020
 erpnext.patches.v13_0.loyalty_points_entry_for_pos_invoice #22-07-2020
 erpnext.patches.v12_0.add_taxjar_integration_field
+erpnext.patches.v12_0.fix_percent_complete_for_projects
 erpnext.patches.v13_0.delete_report_requested_items_to_order
 erpnext.patches.v12_0.update_item_tax_template_company
 erpnext.patches.v13_0.move_branch_code_to_bank_account
diff --git a/erpnext/patches/v12_0/fix_percent_complete_for_projects.py b/erpnext/patches/v12_0/fix_percent_complete_for_projects.py
new file mode 100644
index 0000000..3622df6
--- /dev/null
+++ b/erpnext/patches/v12_0/fix_percent_complete_for_projects.py
@@ -0,0 +1,14 @@
+import frappe
+from frappe.utils import flt
+
+def execute():
+	for project in frappe.get_all("Project", fields=["name", "percent_complete_method"]):
+		total = frappe.db.count('Task', dict(project=project.name))
+		if project.percent_complete_method == "Task Completion" and total > 0:
+			completed = frappe.db.sql("""select count(name) from tabTask where
+					project=%s and status in ('Cancelled', 'Completed')""", project.name)[0][0]
+			percent_complete = flt(flt(completed) / total * 100, 2)
+			if project.percent_complete != percent_complete:
+				frappe.db.set_value("Project", project.name, "percent_complete", percent_complete)
+				if percent_complete == 100:
+					frappe.db.set_value("Project", project.name, "status", "Completed")
diff --git a/erpnext/projects/doctype/task/task.py b/erpnext/projects/doctype/task/task.py
index 4bdda68..cf2fd26 100755
--- a/erpnext/projects/doctype/task/task.py
+++ b/erpnext/projects/doctype/task/task.py
@@ -175,6 +175,9 @@
 
 		self.update_nsm_model()
 
+	def after_delete(self):
+		self.update_project()
+
 	def update_status(self):
 		if self.status not in ('Cancelled', 'Completed') and self.exp_end_date:
 			from datetime import datetime