fix: Validation for parent cost center (#19664)
* fix: Validation for parent cost center
* fix: Minor modification in condition
* fix: Update test cases for invalid cost center creation
diff --git a/erpnext/accounts/doctype/cost_center/cost_center.py b/erpnext/accounts/doctype/cost_center/cost_center.py
index 584e11c..0294e78 100644
--- a/erpnext/accounts/doctype/cost_center/cost_center.py
+++ b/erpnext/accounts/doctype/cost_center/cost_center.py
@@ -18,6 +18,7 @@
def validate(self):
self.validate_mandatory()
+ self.validate_parent_cost_center()
def validate_mandatory(self):
if self.cost_center_name != self.company and not self.parent_cost_center:
@@ -25,6 +26,12 @@
elif self.cost_center_name == self.company and self.parent_cost_center:
frappe.throw(_("Root cannot have a parent cost center"))
+ def validate_parent_cost_center(self):
+ if self.parent_cost_center:
+ if not frappe.db.get_value('Cost Center', self.parent_cost_center, 'is_group'):
+ frappe.throw(_("{0} is not a group node. Please select a group node as parent cost center").format(
+ frappe.bold(self.parent_cost_center)))
+
def convert_group_to_ledger(self):
if self.check_if_child_exists():
frappe.throw(_("Cannot convert Cost Center to ledger as it has child nodes"))
diff --git a/erpnext/accounts/doctype/cost_center/test_cost_center.py b/erpnext/accounts/doctype/cost_center/test_cost_center.py
index c4fad75..8f23d90 100644
--- a/erpnext/accounts/doctype/cost_center/test_cost_center.py
+++ b/erpnext/accounts/doctype/cost_center/test_cost_center.py
@@ -1,12 +1,26 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
-
-
+import unittest
import frappe
+
test_records = frappe.get_test_records('Cost Center')
+class TestCostCenter(unittest.TestCase):
+ def test_cost_center_creation_against_child_node(self):
+ if not frappe.db.get_value('Cost Center', {'name': '_Test Cost Center 2 - _TC'}):
+ frappe.get_doc(test_records[1]).insert()
+
+ cost_center = frappe.get_doc({
+ 'doctype': 'Cost Center',
+ 'cost_center_name': '_Test Cost Center 3',
+ 'parent_cost_center': '_Test Cost Center 2 - _TC',
+ 'is_group': 0,
+ 'company': '_Test Company'
+ })
+
+ self.assertRaises(frappe.ValidationError, cost_center.save)
def create_cost_center(**args):
args = frappe._dict(args)