Bug fix: Update child/parent relationship when a StockItem is deleted

- Pass the child items up to the parent of the deleted item
- Fix unit tests
This commit is contained in:
Oliver Walters 2020-02-18 08:42:55 +11:00
parent 9e456f5a11
commit 49d5573f8b
2 changed files with 31 additions and 6 deletions

View File

@ -552,7 +552,13 @@ class StockItem(MPTTModel):
new_stock.pk = None
new_stock.parent = self
new_stock.quantity = quantity
new_stock.location = location
# Move to the new location if specified, otherwise use current location
if location:
new_stock.location = location
else:
new_stock.location = self.location
new_stock.save()
# Copy the transaction history of this part into the new one
@ -606,7 +612,7 @@ class StockItem(MPTTModel):
# Split the existing StockItem in two
self.splitStock(quantity, location, user)
return
return True
msg = "Moved to {loc}".format(loc=str(location))
@ -757,6 +763,23 @@ class StockItem(MPTTModel):
return s
@receiver(pre_delete, sender=StockItem, dispatch_uid='stock_item_pre_delete_log')
def before_delete_stock_item(sender, instance, using, **kwargs):
""" Receives pre_delete signal from StockItem object.
Before a StockItem is deleted, ensure that each child object is updated,
to point to the new parent item.
"""
# Update each StockItem parent field
for child in instance.children.all():
child.parent = instance.parent
child.save()
# Rebuild the MPTT tree
StockItem.objects.rebuild()
class StockItemTracking(models.Model):
""" Stock tracking entry - breacrumb for keeping track of automated stock transactions

View File

@ -156,7 +156,9 @@ class StockTest(TestCase):
# Move 6 of the units
self.assertTrue(w1.move(self.diningroom, 'Moved', None, quantity=6))
self.assertEqual(w1.quantity, 6)
# There should be 4 remaining
self.assertEqual(w1.quantity, 4)
# There should also be a new object still in drawer3
self.assertEqual(StockItem.objects.filter(part=25).count(), 4)
@ -175,17 +177,17 @@ class StockTest(TestCase):
N = StockItem.objects.filter(part=3).count()
stock = StockItem.objects.get(id=1234)
stock.splitStock(1000, None)
stock.splitStock(1000, None, self.user)
self.assertEqual(stock.quantity, 234)
# There should be a new stock item too!
self.assertEqual(StockItem.objects.filter(part=3).count(), N + 1)
# Try to split a negative quantity
stock.splitStock(-10, None)
stock.splitStock(-10, None, self.user)
self.assertEqual(StockItem.objects.filter(part=3).count(), N + 1)
stock.splitStock(stock.quantity, None)
stock.splitStock(stock.quantity, None, self.user)
self.assertEqual(StockItem.objects.filter(part=3).count(), N + 1)
def test_stocktake(self):