diff --git a/InvenTree/part/models.py b/InvenTree/part/models.py index 1400abd225..5f29c8cf80 100644 --- a/InvenTree/part/models.py +++ b/InvenTree/part/models.py @@ -784,12 +784,13 @@ class Part(MPTTModel): """ Return the current number of parts currently being built """ - quantity = self.active_builds.aggregate(quantity=Sum('quantity'))['quantity'] + stock_items = self.stock_items.filter(is_building=True) - if quantity is None: - quantity = 0 + query = stock_items.aggregate( + quantity=Coalesce(Sum('quantity'), Decimal(0)) + ) - return quantity + return query['quantity'] def build_order_allocations(self): """ diff --git a/InvenTree/stock/models.py b/InvenTree/stock/models.py index 3277137a25..fbdc1654f3 100644 --- a/InvenTree/stock/models.py +++ b/InvenTree/stock/models.py @@ -721,6 +721,10 @@ class StockItem(MPTTModel): if self.customer is not None: return False + # Not 'in stock' if it is building + if self.is_building: + return False + # Not 'in stock' if the status code makes it unavailable if self.status in StockStatus.UNAVAILABLE_CODES: return False diff --git a/InvenTree/stock/tests.py b/InvenTree/stock/tests.py index 23cf6b3d02..135cb48f8b 100644 --- a/InvenTree/stock/tests.py +++ b/InvenTree/stock/tests.py @@ -47,6 +47,30 @@ class StockTest(TestCase): Part.objects.rebuild() StockItem.objects.rebuild() + def test_is_building(self): + """ + Test that the is_building flag does not count towards stock. + """ + + part = Part.objects.get(pk=1) + + # Record the total stock count + n = part.total_stock + + StockItem.objects.create(part=part, quantity=5) + + # And there should be *no* items being build + self.assertEqual(part.quantity_being_built, 0) + + # Add some stock items which are "building" + for i in range(10): + item = StockItem.objects.create(part=part, quantity=10, is_building=True) + + # The "is_building" quantity should not be counted here + self.assertEqual(part.total_stock, n + 5) + + self.assertEqual(part.quantity_being_built, 100) + def test_loc_count(self): self.assertEqual(StockLocation.objects.count(), 7)