From 8052a1989c3cbed8b7d2cd2cbbcb2994dddd6664 Mon Sep 17 00:00:00 2001
From: Oliver Walters <oliver.henry.walters@gmail.com>
Date: Tue, 21 Apr 2020 11:41:08 +1000
Subject: [PATCH] Serialize the allocated quantity for a purchase-order line
 item

---
 InvenTree/order/api.py         |  1 +
 InvenTree/order/models.py      | 14 +++++++++++++-
 InvenTree/order/serializers.py |  4 ++++
 3 files changed, 18 insertions(+), 1 deletion(-)

diff --git a/InvenTree/order/api.py b/InvenTree/order/api.py
index 6dfcfb6077..6599d1a209 100644
--- a/InvenTree/order/api.py
+++ b/InvenTree/order/api.py
@@ -335,6 +335,7 @@ class SOLineItemList(generics.ListCreateAPIView):
         return queryset.prefetch_related(
             'part',
             'part__stock_items',
+            'stock_items',
             'order',
         )
 
diff --git a/InvenTree/order/models.py b/InvenTree/order/models.py
index 1490b45d98..7a694fbc8d 100644
--- a/InvenTree/order/models.py
+++ b/InvenTree/order/models.py
@@ -5,7 +5,8 @@ Order model definitions
 # -*- coding: utf-8 -*-
 
 from django.db import models, transaction
-from django.db.models import F
+from django.db.models import F, Sum
+from django.db.models.functions import Coalesce
 from django.core.validators import MinValueValidator
 from django.core.exceptions import ValidationError
 from django.contrib.auth.models import User
@@ -16,6 +17,7 @@ from markdownx.models import MarkdownxField
 
 import os
 from datetime import datetime
+from decimal import Decimal
 
 from stock.models import StockItem
 from company.models import Company, SupplierPart
@@ -372,6 +374,16 @@ class SalesOrderLineItem(OrderLineItem):
 
     part = models.ForeignKey(Part, on_delete=models.SET_NULL, related_name='sales_order_line_items', null=True, help_text=_('Part'), limit_choices_to={'salable': True})
 
+    def allocated_quantity(self):
+        """ Return the total stock quantity allocated to this LineItem.
+
+        This is a summation of the quantity of each attached StockItem
+        """
+
+        query = self.stock_items.aggregate(allocated=Coalesce(Sum('stock_item__quantity'), Decimal(0)))
+
+        return query['allocated']
+
 
 class SalesOrderLineItemStockAssociation(models.Model):
     """
diff --git a/InvenTree/order/serializers.py b/InvenTree/order/serializers.py
index 6e482d019e..deb470baab 100644
--- a/InvenTree/order/serializers.py
+++ b/InvenTree/order/serializers.py
@@ -162,11 +162,15 @@ class SOLineItemSerializer(InvenTreeModelSerializer):
     order_detail = SalesOrderSerializer(source='order', many=False, read_only=True)
     part_detail = PartBriefSerializer(source='part', many=False, read_only=True)
 
+    quantity = serializers.FloatField()
+    allocated = serializers.FloatField(source='allocated_quantity', read_only=True)
+
     class Meta:
         model = SalesOrderLineItem
 
         fields = [
             'pk',
+            'allocated',
             'quantity',
             'reference',
             'notes',