From 123aab89bcb5d0c6ca9f074f7af2161991abdd6b Mon Sep 17 00:00:00 2001
From: Oliver <oliver.henry.walters@gmail.com>
Date: Thu, 2 Dec 2021 21:39:49 +1100
Subject: [PATCH] Adds an "available" filter for stock item API

---
 InvenTree/stock/api.py                        | 20 ++++++++++++++++++-
 .../templates/js/translated/table_filters.js  |  5 +++++
 2 files changed, 24 insertions(+), 1 deletion(-)

diff --git a/InvenTree/stock/api.py b/InvenTree/stock/api.py
index 8385041209..760a18c72c 100644
--- a/InvenTree/stock/api.py
+++ b/InvenTree/stock/api.py
@@ -10,7 +10,7 @@ from datetime import datetime, timedelta
 from django.core.exceptions import ValidationError as DjangoValidationError
 from django.conf.urls import url, include
 from django.http import JsonResponse
-from django.db.models import Q
+from django.db.models import Q, F
 from django.db import transaction
 from django.utils.translation import ugettext_lazy as _
 
@@ -304,6 +304,24 @@ class StockFilter(rest_filters.FilterSet):
 
         return queryset
 
+    available = rest_filters.BooleanFilter(label='Available', method='filter_available')
+
+    def filter_available(self, queryset, name, value):
+        """
+        Filter by whether the StockItem is "available" or not.
+
+        Here, "available" means that the allocated quantity is less than the total quantity
+        """
+
+        if str2bool(value):
+            # The 'quantity' field is greater than the calculated 'allocated' field
+            queryset = queryset.filter(Q(quantity__gt=F('allocated')))
+        else:
+            # The 'quantity' field is less than (or equal to) the calculated 'allocated' field
+            queryset = queryset.filter(Q(quantity__lte=F('allocated')))
+
+        return queryset
+
     batch = rest_filters.CharFilter(label="Batch code filter (case insensitive)", lookup_expr='iexact')
 
     batch_regex = rest_filters.CharFilter(label="Batch code filter (regex)", field_name='batch', lookup_expr='iregex')
diff --git a/InvenTree/templates/js/translated/table_filters.js b/InvenTree/templates/js/translated/table_filters.js
index 409192f74d..e7f5dc2a4d 100644
--- a/InvenTree/templates/js/translated/table_filters.js
+++ b/InvenTree/templates/js/translated/table_filters.js
@@ -173,6 +173,11 @@ function getAvailableTableFilters(tableKey) {
                 title: '{% trans "Is allocated" %}',
                 description: '{% trans "Item has been allocated" %}',
             },
+            available: {
+                type: 'bool',
+                title: '{% trans "Available" %}',
+                description: '{% trans "Stock is available for use" %}',
+            },
             cascade: {
                 type: 'bool',
                 title: '{% trans "Include sublocations" %}',