mirror of
https://github.com/inventree/InvenTree.git
synced 2026-11-28 10:34:34 +00:00
[bug] check before deleting parts from category (#13403)
This commit is contained in:
1 parent
6ec28a09e2
commit
fd3dfc8517
6 files changed
+216
-9
No files matched your search
@@ -97,6 +97,11 @@ class InvenTreeTree(ContentTypeMixin, MPTTModel):
|
||||
'Object %s of type %s no longer exists', str(self), str(self.__class__)
|
||||
)
|
||||
|
||||
# If items are to be deleted, ensure that *all* of them can be deleted,
|
||||
# before any changes are made to the database
|
||||
if delete_items:
|
||||
self.validate_delete_items(cascade=delete_children)
|
||||
|
||||
tree_id = self.tree_id
|
||||
parent = getattr(self, self.NODE_PARENT_KEY, None)
|
||||
|
||||
@@ -351,11 +356,58 @@ class InvenTreeTree(ContentTypeMixin, MPTTModel):
|
||||
)
|
||||
return False
|
||||
|
||||
# Maximum number of blocking items to list in a validation error message
|
||||
MAX_DELETE_ERRORS = 10
|
||||
|
||||
def validate_delete_items(self, cascade: bool = False):
|
||||
"""Ensure that all 'items' under this node can be deleted.
|
||||
|
||||
Each item is checked using its own 'check_delete' method (if it has one),
|
||||
which applies the same rules as deleting that item individually.
|
||||
|
||||
Arguments:
|
||||
cascade: If True, also check items under all child nodes
|
||||
|
||||
Raises:
|
||||
ValidationError: If any item cannot be deleted. No changes are made.
|
||||
"""
|
||||
items = self.get_items(cascade=cascade)
|
||||
|
||||
if not items:
|
||||
return
|
||||
|
||||
errors = []
|
||||
n_blocked = 0
|
||||
|
||||
for item in items:
|
||||
check_delete = getattr(item, 'check_delete', None)
|
||||
|
||||
if not check_delete:
|
||||
continue
|
||||
|
||||
try:
|
||||
check_delete()
|
||||
except ValidationError as exc:
|
||||
n_blocked += 1
|
||||
|
||||
if len(errors) < self.MAX_DELETE_ERRORS:
|
||||
errors.append(f'{item}: {"; ".join(exc.messages)}')
|
||||
|
||||
if n_blocked > 0:
|
||||
msg = _('{n} item(s) cannot be deleted').format(n=n_blocked)
|
||||
|
||||
if n_blocked > len(errors):
|
||||
errors.append('...')
|
||||
|
||||
raise ValidationError([msg, *errors])
|
||||
|
||||
def delete_items(self, cascade: bool = False):
|
||||
"""Delete any 'items' which exist under this node in the tree.
|
||||
|
||||
- Note that an 'item' is an instance of a different model class.
|
||||
- Not all tree structures will have items associated with them.
|
||||
- Items are deleted in bulk (for performance). The items must first be
|
||||
checked with validate_delete_items, which is performed by delete().
|
||||
"""
|
||||
if items := self.get_items(cascade=cascade):
|
||||
items.delete()
|
||||
|
||||
@@ -609,10 +609,24 @@ class Part(
|
||||
def delete(self, **kwargs):
|
||||
"""Custom delete method for the Part model.
|
||||
|
||||
Raises:
|
||||
ValidationError: If the part cannot be deleted (see check_delete)
|
||||
"""
|
||||
self.check_delete()
|
||||
|
||||
super().delete()
|
||||
|
||||
def check_delete(self):
|
||||
"""Check whether this Part can be deleted.
|
||||
|
||||
Prevents deletion of a Part if any of the following conditions are met:
|
||||
|
||||
- The part is locked
|
||||
- The part is still active
|
||||
- The part is used in a BOM for a different part.
|
||||
|
||||
Raises:
|
||||
ValidationError: If the part cannot be deleted
|
||||
"""
|
||||
if self.locked and get_global_setting('PART_ENABLE_LOCKING'):
|
||||
raise ValidationError(_('Cannot delete this part as it is locked'))
|
||||
@@ -626,8 +640,6 @@ class Part(
|
||||
_('Cannot delete this part as it is used in an assembly')
|
||||
)
|
||||
|
||||
super().delete()
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
"""Overrides the save function for the Part model.
|
||||
|
||||
|
||||
@@ -404,6 +404,87 @@ class PartCategoryAPITest(InvenTreeAPITestCase):
|
||||
|
||||
self.assertEqual(response.data['description'], 'A part category')
|
||||
|
||||
def test_category_delete_blocked(self):
|
||||
"""A category cannot be deleted (with its parts) if any part cannot be deleted."""
|
||||
from common.settings import set_global_setting
|
||||
|
||||
def setup_category():
|
||||
"""Create a category, with a child category, each with an inactive part."""
|
||||
cat = PartCategory.objects.create(name='To delete', description='Delete me')
|
||||
child = PartCategory.objects.create(
|
||||
name='Child', description='Child category', parent=cat
|
||||
)
|
||||
parts = [
|
||||
Part.objects.create(
|
||||
name=f'Part {c.pk}', description='A part', category=c, active=False
|
||||
)
|
||||
for c in [cat, child]
|
||||
]
|
||||
return cat, child, parts
|
||||
|
||||
def check_blocked(cat, child, parts, msg, cascade=True):
|
||||
"""Attempt to delete the category, and check that nothing was changed."""
|
||||
url = reverse('api-part-category-detail', kwargs={'pk': cat.pk})
|
||||
response = self.delete(
|
||||
url,
|
||||
{'delete_parts': True, 'delete_child_categories': cascade},
|
||||
expected_code=400,
|
||||
)
|
||||
self.assertIn('cannot be deleted', str(response.data))
|
||||
self.assertIn(msg, str(response.data))
|
||||
|
||||
# Nothing has been deleted or moved
|
||||
for obj in [cat, child, *parts]:
|
||||
obj.refresh_from_db()
|
||||
|
||||
self.assertEqual(child.parent, cat)
|
||||
for p in parts:
|
||||
self.assertIn(p.category, [cat, child])
|
||||
|
||||
set_global_setting('PART_ENABLE_LOCKING', True)
|
||||
set_global_setting('PART_ALLOW_DELETE_FROM_ASSEMBLY', False)
|
||||
|
||||
# 1. An active part (in a child category) blocks deletion
|
||||
cat, child, parts = setup_category()
|
||||
Part.objects.filter(pk=parts[1].pk).update(active=True)
|
||||
check_blocked(cat, child, parts, 'still active')
|
||||
|
||||
# ... unless the child category is not deleted (only direct parts are deleted)
|
||||
self.delete(
|
||||
reverse('api-part-category-detail', kwargs={'pk': cat.pk}),
|
||||
{'delete_parts': True, 'delete_child_categories': False},
|
||||
expected_code=204,
|
||||
)
|
||||
with self.assertRaises(Part.DoesNotExist):
|
||||
parts[0].refresh_from_db()
|
||||
parts[1].refresh_from_db()
|
||||
|
||||
# 2. A locked part blocks deletion
|
||||
cat, child, parts = setup_category()
|
||||
Part.objects.filter(pk=parts[0].pk).update(locked=True)
|
||||
check_blocked(cat, child, parts, 'locked')
|
||||
|
||||
# 3. A part which is used in an assembly blocks deletion
|
||||
cat, child, parts = setup_category()
|
||||
assembly = Part.objects.create(
|
||||
name='Assembly', description='An assembly', assembly=True
|
||||
)
|
||||
BomItem.objects.create(part=assembly, sub_part=parts[1], quantity=1)
|
||||
check_blocked(cat, child, parts, 'used in an assembly')
|
||||
|
||||
# Once the assembly restriction is lifted, the category can be deleted
|
||||
set_global_setting('PART_ALLOW_DELETE_FROM_ASSEMBLY', True)
|
||||
|
||||
self.delete(
|
||||
reverse('api-part-category-detail', kwargs={'pk': cat.pk}),
|
||||
{'delete_parts': True, 'delete_child_categories': True},
|
||||
expected_code=204,
|
||||
)
|
||||
|
||||
for obj in [cat, child, *parts]:
|
||||
with self.assertRaises(obj.__class__.DoesNotExist):
|
||||
obj.refresh_from_db()
|
||||
|
||||
def test_category_delete(self):
|
||||
"""Test category deletion with different parameters."""
|
||||
for delete_child_categories in [False, True]:
|
||||
@@ -436,6 +517,7 @@ class PartCategoryAPITest(InvenTreeAPITestCase):
|
||||
name=f'Part {"A" if delete_child_categories else "B"}{"C" if delete_parts else "D"}-{jj}',
|
||||
description='Child part of the deleted category',
|
||||
category=cat_to_delete,
|
||||
active=False,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -457,6 +539,7 @@ class PartCategoryAPITest(InvenTreeAPITestCase):
|
||||
name=f'Part xyz {jj}_{ii}-{"E" if delete_child_categories else "F"}{"G" if delete_parts else "H"}',
|
||||
description='Child part in the child category of the deleted category',
|
||||
category=child,
|
||||
active=False,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -449,7 +449,15 @@ class CategoryTest(TestCase):
|
||||
# All parts should have been deleted
|
||||
self.assertEqual(Part.objects.filter(category=C32).count(), 10)
|
||||
|
||||
# Now, delete C32 and delete all parts underneath
|
||||
# Active parts cannot be deleted - so neither can the category (with its parts)
|
||||
with self.assertRaises(ValidationError):
|
||||
C32.delete(delete_parts=True)
|
||||
|
||||
C32.refresh_from_db()
|
||||
self.assertEqual(Part.objects.filter(category=C32).count(), 10)
|
||||
|
||||
# Now, deactivate the parts, delete C32 and delete all parts underneath
|
||||
Part.objects.filter(category=C32).update(active=False)
|
||||
C32.delete(delete_parts=True)
|
||||
|
||||
# 10 parts should have been deleted from the database
|
||||
|
||||
@@ -589,13 +589,11 @@ class StockItem(
|
||||
|
||||
Arguments:
|
||||
ignore_serial_check: If True, allow deletion of serialized stock items regardless of global setting
|
||||
|
||||
Raises:
|
||||
ValidationError: If the stock item cannot be deleted (see check_delete)
|
||||
"""
|
||||
if (
|
||||
not ignore_serial_check
|
||||
and not get_global_setting('STOCK_ALLOW_DELETE_SERIALIZED', cache=False)
|
||||
and self.serialized
|
||||
):
|
||||
raise ValidationError(_('Serialized stock items cannot be deleted'))
|
||||
self.check_delete(ignore_serial_check=ignore_serial_check)
|
||||
|
||||
with transaction.atomic():
|
||||
# Re-link any child items to the parent of this item,
|
||||
@@ -612,6 +610,22 @@ class StockItem(
|
||||
|
||||
super().delete(**kwargs)
|
||||
|
||||
def check_delete(self, ignore_serial_check: bool = False):
|
||||
"""Check whether this StockItem can be deleted.
|
||||
|
||||
Arguments:
|
||||
ignore_serial_check: If True, allow deletion of serialized stock items regardless of global setting
|
||||
|
||||
Raises:
|
||||
ValidationError: If the stock item cannot be deleted
|
||||
"""
|
||||
if (
|
||||
not ignore_serial_check
|
||||
and not get_global_setting('STOCK_ALLOW_DELETE_SERIALIZED', cache=False)
|
||||
and self.serialized
|
||||
):
|
||||
raise ValidationError(_('Serialized stock items cannot be deleted'))
|
||||
|
||||
@staticmethod
|
||||
def get_api_url():
|
||||
"""Return API url."""
|
||||
|
||||
@@ -237,6 +237,44 @@ class StockLocationTest(StockAPITestCase):
|
||||
|
||||
self.post(self.list_url, data, expected_code=201)
|
||||
|
||||
def test_stock_location_delete_blocked(self):
|
||||
"""A location cannot be deleted (with its stock) if any stock item cannot be deleted."""
|
||||
part = Part.objects.filter(trackable=True).first()
|
||||
|
||||
location = StockLocation.objects.create(name='To delete', description='Gone')
|
||||
child = StockLocation.objects.create(
|
||||
name='Child', description='Child location', parent=location
|
||||
)
|
||||
|
||||
plain = StockItem.objects.create(part=part, location=location, quantity=5)
|
||||
serialized = StockItem.objects.create(
|
||||
part=part, location=child, quantity=1, serial='DEL-001'
|
||||
)
|
||||
|
||||
url = reverse('api-location-detail', kwargs={'pk': location.pk})
|
||||
params = {'delete_stock_items': True, 'delete_sub_locations': True}
|
||||
|
||||
# Serialized stock cannot be deleted - so neither can the location
|
||||
set_global_setting('STOCK_ALLOW_DELETE_SERIALIZED', False)
|
||||
|
||||
response = self.delete(url, params, expected_code=400)
|
||||
self.assertIn('Serialized stock items cannot be deleted', str(response.data))
|
||||
|
||||
# Nothing has been deleted
|
||||
for obj in [location, child, plain, serialized]:
|
||||
obj.refresh_from_db()
|
||||
|
||||
self.assertEqual(child.parent, location)
|
||||
self.assertEqual(serialized.location, child)
|
||||
|
||||
# Once the setting allows it, the location can be deleted
|
||||
set_global_setting('STOCK_ALLOW_DELETE_SERIALIZED', True)
|
||||
self.delete(url, params, expected_code=204)
|
||||
|
||||
for obj in [location, child, plain, serialized]:
|
||||
with self.assertRaises(obj.__class__.DoesNotExist):
|
||||
obj.refresh_from_db()
|
||||
|
||||
def test_stock_location_delete(self):
|
||||
"""Test stock location deletion with different parameters."""
|
||||
# First, construct a set of template / variant parts
|
||||
|
||||
Reference in new issue
Block a user