-
-
Notifications
You must be signed in to change notification settings - Fork 671
/
api.py
1729 lines (1335 loc) · 57.1 KB
/
api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""JSON API for the Stock app."""
from collections import OrderedDict
from datetime import datetime, timedelta
from django.core.exceptions import ValidationError as DjangoValidationError
from django.db import transaction
from django.db.models import F, Q
from django.http import JsonResponse
from django.urls import include, path
from django.utils.translation import gettext_lazy as _
from django_filters import rest_framework as rest_filters
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import extend_schema_field
from rest_framework import status
from rest_framework.response import Response
from rest_framework.serializers import ValidationError
import common.models
import common.settings
import InvenTree.helpers
import stock.serializers as StockSerializers
from build.models import Build
from build.serializers import BuildSerializer
from company.models import Company, SupplierPart
from company.serializers import CompanySerializer
from generic.states.api import StatusView
from InvenTree.api import (
APIDownloadMixin,
AttachmentMixin,
ListCreateDestroyAPIView,
MetadataView,
)
from InvenTree.filters import (
ORDER_FILTER,
SEARCH_ORDER_FILTER,
SEARCH_ORDER_FILTER_ALIAS,
InvenTreeDateFilter,
)
from InvenTree.helpers import (
DownloadFile,
extract_serial_numbers,
generateTestKey,
is_ajax,
isNull,
str2bool,
str2int,
)
from InvenTree.mixins import (
CreateAPI,
CustomRetrieveUpdateDestroyAPI,
ListAPI,
ListCreateAPI,
RetrieveAPI,
RetrieveUpdateDestroyAPI,
)
from InvenTree.status_codes import StockHistoryCode, StockStatus
from order.models import PurchaseOrder, ReturnOrder, SalesOrder, SalesOrderAllocation
from order.serializers import (
PurchaseOrderSerializer,
ReturnOrderSerializer,
SalesOrderSerializer,
)
from part.models import BomItem, Part, PartCategory
from part.serializers import PartBriefSerializer
from stock.admin import LocationResource, StockItemResource
from stock.models import (
StockItem,
StockItemAttachment,
StockItemTestResult,
StockItemTracking,
StockLocation,
StockLocationType,
)
class StockDetail(RetrieveUpdateDestroyAPI):
"""API detail endpoint for Stock object.
get:
Return a single StockItem object
post:
Update a StockItem
delete:
Remove a StockItem
"""
queryset = StockItem.objects.all()
serializer_class = StockSerializers.StockItemSerializer
def get_queryset(self, *args, **kwargs):
"""Annotate queryset."""
queryset = super().get_queryset(*args, **kwargs)
queryset = StockSerializers.StockItemSerializer.annotate_queryset(queryset)
return queryset
def get_serializer_context(self):
"""Extend serializer context."""
ctx = super().get_serializer_context()
ctx['user'] = getattr(self.request, 'user', None)
return ctx
def get_serializer(self, *args, **kwargs):
"""Set context before returning serializer."""
kwargs['context'] = self.get_serializer_context()
try:
params = self.request.query_params
kwargs['part_detail'] = str2bool(params.get('part_detail', True))
kwargs['location_detail'] = str2bool(params.get('location_detail', True))
kwargs['supplier_part_detail'] = str2bool(
params.get('supplier_part_detail', True)
)
kwargs['path_detail'] = str2bool(params.get('path_detail', False))
except AttributeError:
pass
return self.serializer_class(*args, **kwargs)
class StockItemContextMixin:
"""Mixin class for adding StockItem object to serializer context."""
role_required = 'stock.change'
queryset = StockItem.objects.none()
def get_serializer_context(self):
"""Extend serializer context."""
context = super().get_serializer_context()
context['request'] = self.request
try:
context['item'] = StockItem.objects.get(pk=self.kwargs.get('pk', None))
except Exception:
pass
return context
class StockItemSerialize(StockItemContextMixin, CreateAPI):
"""API endpoint for serializing a stock item."""
serializer_class = StockSerializers.SerializeStockItemSerializer
class StockItemInstall(StockItemContextMixin, CreateAPI):
"""API endpoint for installing a particular stock item into this stock item.
- stock_item.part must be in the BOM for this part
- stock_item must currently be "in stock"
- stock_item must be serialized (and not belong to another item)
"""
serializer_class = StockSerializers.InstallStockItemSerializer
class StockItemUninstall(StockItemContextMixin, CreateAPI):
"""API endpoint for removing (uninstalling) items from this item."""
serializer_class = StockSerializers.UninstallStockItemSerializer
class StockItemConvert(StockItemContextMixin, CreateAPI):
"""API endpoint for converting a stock item to a variant part."""
serializer_class = StockSerializers.ConvertStockItemSerializer
class StockItemReturn(StockItemContextMixin, CreateAPI):
"""API endpoint for returning a stock item from a customer."""
serializer_class = StockSerializers.ReturnStockItemSerializer
class StockAdjustView(CreateAPI):
"""A generic class for handling stocktake actions.
Subclasses exist for:
- StockCount: count stock items
- StockAdd: add stock items
- StockRemove: remove stock items
- StockTransfer: transfer stock items
"""
queryset = StockItem.objects.none()
def get_serializer_context(self):
"""Extend serializer context."""
context = super().get_serializer_context()
context['request'] = self.request
return context
class StockChangeStatus(StockAdjustView):
"""API endpoint to change the status code of multiple StockItem objects."""
serializer_class = StockSerializers.StockChangeStatusSerializer
class StockCount(StockAdjustView):
"""Endpoint for counting stock (performing a stocktake)."""
serializer_class = StockSerializers.StockCountSerializer
class StockAdd(StockAdjustView):
"""Endpoint for adding a quantity of stock to an existing StockItem."""
serializer_class = StockSerializers.StockAddSerializer
class StockRemove(StockAdjustView):
"""Endpoint for removing a quantity of stock from an existing StockItem."""
serializer_class = StockSerializers.StockRemoveSerializer
class StockTransfer(StockAdjustView):
"""API endpoint for performing stock movements."""
serializer_class = StockSerializers.StockTransferSerializer
class StockAssign(CreateAPI):
"""API endpoint for assigning stock to a particular customer."""
queryset = StockItem.objects.all()
serializer_class = StockSerializers.StockAssignmentSerializer
def get_serializer_context(self):
"""Extend serializer context."""
ctx = super().get_serializer_context()
ctx['request'] = self.request
return ctx
class StockMerge(CreateAPI):
"""API endpoint for merging multiple stock items."""
queryset = StockItem.objects.none()
serializer_class = StockSerializers.StockMergeSerializer
def get_serializer_context(self):
"""Extend serializer context."""
ctx = super().get_serializer_context()
ctx['request'] = self.request
return ctx
class StockLocationFilter(rest_filters.FilterSet):
"""Base class for custom API filters for the StockLocation endpoint."""
class Meta:
"""Meta class options for this filterset."""
model = StockLocation
fields = ['name', 'structural', 'external']
location_type = rest_filters.ModelChoiceFilter(
queryset=StockLocationType.objects.all(), field_name='location_type'
)
has_location_type = rest_filters.BooleanFilter(
label='has_location_type', method='filter_has_location_type'
)
def filter_has_location_type(self, queryset, name, value):
"""Filter by whether or not the location has a location type."""
if str2bool(value):
return queryset.exclude(location_type=None)
return queryset.filter(location_type=None)
depth = rest_filters.NumberFilter(
label=_('Depth'), method='filter_depth', help_text=_('Filter by location depth')
)
def filter_depth(self, queryset, name, value):
"""Filter by the "depth" of the StockLocation.
- This filter is used to limit the depth of the location tree
- If the "parent" filter is also provided, the depth is calculated from the parent location
"""
parent = self.data.get('parent', None)
# Only filter if the parent filter is *not* provided
if not parent:
queryset = queryset.filter(level__lte=value)
return queryset
cascade = rest_filters.BooleanFilter(
label=_('Cascade'),
method='filter_cascade',
help_text=_('Include sub-locations in filtered results'),
)
def filter_cascade(self, queryset, name, value):
"""Filter by whether to include sub-locations in the filtered results.
Note: If the "parent" filter is provided, we offload the logic to that method.
"""
parent = self.data.get('parent', None)
# If the parent is *not* provided, update the results based on the "cascade" value
if not parent:
if not value:
# If "cascade" is False, only return top-level location
queryset = queryset.filter(parent=None)
return queryset
parent = rest_filters.ModelChoiceFilter(
queryset=StockLocation.objects.all(),
method='filter_parent',
label=_('Parent Location'),
help_text=_('Filter by parent location'),
)
def filter_parent(self, queryset, name, value):
"""Filter by parent location.
Note that the filtering behaviour here varies,
depending on whether the 'cascade' value is set.
So, we have to check the "cascade" value here.
"""
parent = value
depth = self.data.get('depth', None)
cascade = str2bool(self.data.get('cascade', False))
if cascade:
# Return recursive sub-locations
queryset = queryset.filter(
parent__in=parent.get_descendants(include_self=True)
)
else:
# Return only direct children
queryset = queryset.filter(parent=parent)
if depth is not None:
# Filter by depth from parent
depth = int(depth)
queryset = queryset.filter(level__lte=parent.level + depth)
return queryset
class StockLocationList(APIDownloadMixin, ListCreateAPI):
"""API endpoint for list view of StockLocation objects.
- GET: Return list of StockLocation objects
- POST: Create a new StockLocation
"""
queryset = StockLocation.objects.all().prefetch_related('tags')
serializer_class = StockSerializers.LocationSerializer
filterset_class = StockLocationFilter
def download_queryset(self, queryset, export_format):
"""Download the filtered queryset as a data file."""
dataset = LocationResource().export(queryset=queryset)
filedata = dataset.export(export_format)
filename = f'InvenTree_Locations.{export_format}'
return DownloadFile(filedata, filename)
def get_queryset(self, *args, **kwargs):
"""Return annotated queryset for the StockLocationList endpoint."""
queryset = super().get_queryset(*args, **kwargs)
queryset = StockSerializers.LocationSerializer.annotate_queryset(queryset)
return queryset
filter_backends = SEARCH_ORDER_FILTER
search_fields = ['name', 'description', 'tags__name', 'tags__slug']
ordering_fields = ['name', 'pathstring', 'items', 'level', 'tree_id', 'lft']
ordering = ['tree_id', 'lft', 'name']
class StockLocationTree(ListAPI):
"""API endpoint for accessing a list of StockLocation objects, ready for rendering as a tree."""
queryset = StockLocation.objects.all()
serializer_class = StockSerializers.LocationTreeSerializer
filter_backends = ORDER_FILTER
ordering_fields = ['level', 'name', 'sublocations']
# Order by tree level (top levels first) and then name
ordering = ['level', 'name']
def get_queryset(self, *args, **kwargs):
"""Return annotated queryset for the StockLocationTree endpoint."""
queryset = super().get_queryset(*args, **kwargs)
queryset = StockSerializers.LocationTreeSerializer.annotate_queryset(queryset)
return queryset
class StockLocationTypeList(ListCreateAPI):
"""API endpoint for a list of StockLocationType objects.
- GET: Return a list of all StockLocationType objects
- POST: Create a StockLocationType
"""
queryset = StockLocationType.objects.all()
serializer_class = StockSerializers.StockLocationTypeSerializer
filter_backends = SEARCH_ORDER_FILTER
ordering_fields = ['name', 'location_count', 'icon']
ordering = ['-location_count']
search_fields = ['name']
def get_queryset(self):
"""Override the queryset method to include location count."""
queryset = super().get_queryset()
queryset = StockSerializers.StockLocationTypeSerializer.annotate_queryset(
queryset
)
return queryset
class StockLocationTypeDetail(RetrieveUpdateDestroyAPI):
"""API detail endpoint for a StockLocationType object.
- GET: return a single StockLocationType
- PUT: update a StockLocationType
- PATCH: partial update a StockLocationType
- DELETE: delete a StockLocationType
"""
queryset = StockLocationType.objects.all()
serializer_class = StockSerializers.StockLocationTypeSerializer
def get_queryset(self):
"""Override the queryset method to include location count."""
queryset = super().get_queryset()
queryset = StockSerializers.StockLocationTypeSerializer.annotate_queryset(
queryset
)
return queryset
class StockFilter(rest_filters.FilterSet):
"""FilterSet for StockItem LIST API."""
class Meta:
"""Metaclass options for this filterset."""
model = StockItem
# Simple filter filters
fields = [
'supplier_part',
'belongs_to',
'build',
'customer',
'consumed_by',
'sales_order',
'purchase_order',
'tags__name',
'tags__slug',
]
# Relationship filters
manufacturer = rest_filters.ModelChoiceFilter(
label='Manufacturer',
queryset=Company.objects.all(),
method='filter_manufacturer',
)
@extend_schema_field(OpenApiTypes.INT)
def filter_manufacturer(self, queryset, name, company):
"""Filter by manufacturer."""
return queryset.filter(
Q(is_manufacturer=True) & Q(manufacturer_part__manufacturer=company)
)
supplier = rest_filters.ModelChoiceFilter(
label='Supplier',
queryset=Company.objects.filter(is_supplier=True),
field_name='supplier_part__supplier',
)
# Part name filters
name = rest_filters.CharFilter(
label='Part name (case insensitive)',
field_name='part__name',
lookup_expr='iexact',
)
name_contains = rest_filters.CharFilter(
label='Part name contains (case insensitive)',
field_name='part__name',
lookup_expr='icontains',
)
name_regex = rest_filters.CharFilter(
label='Part name (regex)', field_name='part__name', lookup_expr='iregex'
)
# Part IPN filters
IPN = rest_filters.CharFilter(
label='Part IPN (case insensitive)',
field_name='part__IPN',
lookup_expr='iexact',
)
IPN_contains = rest_filters.CharFilter(
label='Part IPN contains (case insensitive)',
field_name='part__IPN',
lookup_expr='icontains',
)
IPN_regex = rest_filters.CharFilter(
label='Part IPN (regex)', field_name='part__IPN', lookup_expr='iregex'
)
# Part attribute filters
assembly = rest_filters.BooleanFilter(label='Assembly', field_name='part__assembly')
active = rest_filters.BooleanFilter(label='Active', field_name='part__active')
salable = rest_filters.BooleanFilter(label='Salable', field_name='part__salable')
min_stock = rest_filters.NumberFilter(
label='Minimum stock', field_name='quantity', lookup_expr='gte'
)
max_stock = rest_filters.NumberFilter(
label='Maximum stock', field_name='quantity', lookup_expr='lte'
)
status = rest_filters.NumberFilter(label='Status Code', method='filter_status')
def filter_status(self, queryset, name, value):
"""Filter by integer status code."""
return queryset.filter(status=value)
allocated = rest_filters.BooleanFilter(
label='Is Allocated', method='filter_allocated'
)
def filter_allocated(self, queryset, name, value):
"""Filter by whether or not the stock item is 'allocated'."""
if str2bool(value):
# Filter StockItem with either build allocations or sales order allocations
return queryset.filter(
Q(sales_order_allocations__isnull=False) | Q(allocations__isnull=False)
).distinct()
# Filter StockItem without build allocations or sales order allocations
return queryset.filter(
Q(sales_order_allocations__isnull=True) & Q(allocations__isnull=True)
)
expired = rest_filters.BooleanFilter(label='Expired', method='filter_expired')
def filter_expired(self, queryset, name, value):
"""Filter by whether or not the stock item has expired."""
if not common.settings.stock_expiry_enabled():
return queryset
if str2bool(value):
return queryset.filter(StockItem.EXPIRED_FILTER)
return queryset.exclude(StockItem.EXPIRED_FILTER)
external = rest_filters.BooleanFilter(
label=_('External Location'), method='filter_external'
)
def filter_external(self, queryset, name, value):
"""Filter by whether or not the stock item is located in an external location."""
if str2bool(value):
return queryset.filter(location__external=True)
return queryset.exclude(location__external=True)
in_stock = rest_filters.BooleanFilter(label='In Stock', method='filter_in_stock')
def filter_in_stock(self, queryset, name, value):
"""Filter by if item is in stock."""
if str2bool(value):
return queryset.filter(StockItem.IN_STOCK_FILTER)
return queryset.exclude(StockItem.IN_STOCK_FILTER)
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
# Note that the item must also be "in stock"
return queryset.filter(StockItem.IN_STOCK_FILTER).filter(
Q(quantity__gt=F('allocated'))
)
# The 'quantity' field is less than (or equal to) the calculated 'allocated' field
return queryset.filter(Q(quantity__lte=F('allocated')))
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'
)
is_building = rest_filters.BooleanFilter(label='In production')
# Serial number filtering
serial_gte = rest_filters.NumberFilter(
label='Serial number GTE', field_name='serial_int', lookup_expr='gte'
)
serial_lte = rest_filters.NumberFilter(
label='Serial number LTE', field_name='serial_int', lookup_expr='lte'
)
serial = rest_filters.CharFilter(
label='Serial number', field_name='serial', lookup_expr='exact'
)
serialized = rest_filters.BooleanFilter(
label='Has serial number', method='filter_serialized'
)
def filter_serialized(self, queryset, name, value):
"""Filter by whether the StockItem has a serial number (or not)."""
q = Q(serial=None) | Q(serial='')
if str2bool(value):
return queryset.exclude(q)
return queryset.filter(q).distinct()
has_batch = rest_filters.BooleanFilter(
label='Has batch code', method='filter_has_batch'
)
def filter_has_batch(self, queryset, name, value):
"""Filter by whether the StockItem has a batch code (or not)."""
q = Q(batch=None) | Q(batch='')
if str2bool(value):
return queryset.exclude(q)
return queryset.filter(q).distinct()
tracked = rest_filters.BooleanFilter(label='Tracked', method='filter_tracked')
def filter_tracked(self, queryset, name, value):
"""Filter by whether this stock item is *tracked*.
Meaning either:
- It has a serial number
- It has a batch code
"""
q_batch = Q(batch=None) | Q(batch='')
q_serial = Q(serial=None) | Q(serial='')
if str2bool(value):
return queryset.exclude(q_batch & q_serial)
return queryset.filter(q_batch).filter(q_serial).distinct()
installed = rest_filters.BooleanFilter(
label='Installed in other stock item', method='filter_installed'
)
def filter_installed(self, queryset, name, value):
"""Filter stock items by "belongs_to" field being empty."""
if str2bool(value):
return queryset.exclude(belongs_to=None)
return queryset.filter(belongs_to=None)
has_installed_items = rest_filters.BooleanFilter(
label='Has installed items', method='filter_has_installed'
)
def filter_has_installed(self, queryset, name, value):
"""Filter stock items by "belongs_to" field being empty."""
if str2bool(value):
return queryset.filter(installed_items__gt=0)
return queryset.filter(installed_items=0)
has_child_items = rest_filters.BooleanFilter(
label='Has child items', method='filter_has_child_items'
)
def filter_has_child_items(self, queryset, name, value):
"""Filter stock items by "belongs_to" field being empty."""
if str2bool(value):
return queryset.filter(child_items__gt=0)
return queryset.filter(child_items=0)
sent_to_customer = rest_filters.BooleanFilter(
label='Sent to customer', method='filter_sent_to_customer'
)
def filter_sent_to_customer(self, queryset, name, value):
"""Filter by sent to customer."""
if str2bool(value):
return queryset.exclude(customer=None)
return queryset.filter(customer=None)
depleted = rest_filters.BooleanFilter(label='Depleted', method='filter_depleted')
def filter_depleted(self, queryset, name, value):
"""Filter by depleted items."""
if str2bool(value):
return queryset.filter(quantity__lte=0)
return queryset.exclude(quantity__lte=0)
has_purchase_price = rest_filters.BooleanFilter(
label='Has purchase price', method='filter_has_purchase_price'
)
def filter_has_purchase_price(self, queryset, name, value):
"""Filter by having a purchase price."""
if str2bool(value):
return queryset.exclude(purchase_price=None)
return queryset.filter(purchase_price=None)
ancestor = rest_filters.ModelChoiceFilter(
label='Ancestor', queryset=StockItem.objects.all(), method='filter_ancestor'
)
@extend_schema_field(OpenApiTypes.INT)
def filter_ancestor(self, queryset, name, ancestor):
"""Filter based on ancestor stock item."""
return queryset.filter(parent__in=ancestor.get_descendants(include_self=True))
category = rest_filters.ModelChoiceFilter(
label=_('Category'),
queryset=PartCategory.objects.all(),
method='filter_category',
)
@extend_schema_field(OpenApiTypes.INT)
def filter_category(self, queryset, name, category):
"""Filter based on part category."""
child_categories = category.get_descendants(include_self=True)
return queryset.filter(part__category__in=child_categories)
bom_item = rest_filters.ModelChoiceFilter(
label=_('BOM Item'), queryset=BomItem.objects.all(), method='filter_bom_item'
)
@extend_schema_field(OpenApiTypes.INT)
def filter_bom_item(self, queryset, name, bom_item):
"""Filter based on BOM item."""
return queryset.filter(bom_item.get_stock_filter())
part_tree = rest_filters.ModelChoiceFilter(
label=_('Part Tree'), queryset=Part.objects.all(), method='filter_part_tree'
)
@extend_schema_field(OpenApiTypes.INT)
def filter_part_tree(self, queryset, name, part_tree):
"""Filter based on part tree."""
return queryset.filter(part__tree_id=part_tree.tree_id)
company = rest_filters.ModelChoiceFilter(
label=_('Company'), queryset=Company.objects.all(), method='filter_company'
)
@extend_schema_field(OpenApiTypes.INT)
def filter_company(self, queryset, name, company):
"""Filter by company (either manufacturer or supplier)."""
return queryset.filter(
Q(supplier_part__supplier=company)
| Q(supplier_part__manufacturer_part__manufacturer=company)
).distinct()
# Update date filters
updated_before = InvenTreeDateFilter(
label='Updated before', field_name='updated', lookup_expr='lte'
)
updated_after = InvenTreeDateFilter(
label='Updated after', field_name='updated', lookup_expr='gte'
)
# Stock "expiry" filters
expiry_date_lte = InvenTreeDateFilter(
label=_('Expiry date before'), field_name='expiry_date', lookup_expr='lte'
)
expiry_date_gte = InvenTreeDateFilter(
label=_('Expiry date after'), field_name='expiry_date', lookup_expr='gte'
)
stale = rest_filters.BooleanFilter(label=_('Stale'), method='filter_stale')
def filter_stale(self, queryset, name, value):
"""Filter by stale stock items."""
stale_days = common.models.InvenTreeSetting.get_setting('STOCK_STALE_DAYS')
if stale_days <= 0:
# No filtering, does not make sense
return queryset
stale_date = InvenTree.helpers.current_date() + timedelta(days=stale_days)
stale_filter = (
StockItem.IN_STOCK_FILTER
& ~Q(expiry_date=None)
& Q(expiry_date__lt=stale_date)
)
if str2bool(value):
return queryset.filter(stale_filter)
else:
return queryset.exclude(stale_filter)
class StockList(APIDownloadMixin, ListCreateDestroyAPIView):
"""API endpoint for list view of Stock objects.
- GET: Return a list of all StockItem objects (with optional query filters)
- POST: Create a new StockItem
- DELETE: Delete multiple StockItem objects
"""
serializer_class = StockSerializers.StockItemSerializer
queryset = StockItem.objects.all()
filterset_class = StockFilter
def get_serializer(self, *args, **kwargs):
"""Set context before returning serializer.
Extra detail may be provided to the serializer via query parameters:
- part_detail: Include detail about the StockItem's part
- location_detail: Include detail about the StockItem's location
- supplier_part_detail: Include detail about the StockItem's supplier_part
- tests: Include detail about the StockItem's test results
"""
try:
params = self.request.query_params
for key in [
'part_detail',
'location_detail',
'supplier_part_detail',
'tests',
]:
kwargs[key] = str2bool(params.get(key, False))
except AttributeError:
pass
kwargs['context'] = self.get_serializer_context()
return self.serializer_class(*args, **kwargs)
def get_serializer_context(self):
"""Extend serializer context."""
ctx = super().get_serializer_context()
ctx['user'] = getattr(self.request, 'user', None)
return ctx
def create(self, request, *args, **kwargs):
"""Create a new StockItem object via the API.
We override the default 'create' implementation.
If a location is *not* specified, but the linked *part* has a default location,
we can pre-fill the location automatically.
"""
user = request.user
# Copy the request data, to side-step "mutability" issues
data = OrderedDict()
# Update with cleaned input data
data.update(self.clean_data(request.data))
quantity = data.get('quantity', None)
if quantity is None:
raise ValidationError({'quantity': _('Quantity is required')})
try:
Part.objects.prefetch_related(None)
part = Part.objects.get(pk=data.get('part', None))
except (ValueError, Part.DoesNotExist):
raise ValidationError({'part': _('Valid part must be supplied')})
# Set default location (if not provided)
if 'location' not in data:
location = part.get_default_location()
if location:
data['location'] = location.pk
expiry_date = data.get('expiry_date', None)
# An expiry date was *not* specified - try to infer it!
if expiry_date is None and part.default_expiry > 0:
data['expiry_date'] = InvenTree.helpers.current_date() + timedelta(
days=part.default_expiry
)
# Attempt to extract serial numbers from submitted data
serials = None
# Check if a set of serial numbers was provided
serial_numbers = data.get('serial_numbers', '')
# Check if the supplier_part has a package size defined, which is not 1
if 'supplier_part' in data and data['supplier_part'] is not None:
try:
supplier_part = SupplierPart.objects.get(
pk=data.get('supplier_part', None)
)
except (ValueError, SupplierPart.DoesNotExist):
raise ValidationError({
'supplier_part': _('The given supplier part does not exist')
})
if supplier_part.base_quantity() != 1:
# Skip this check if pack size is 1 - makes no difference
# use_pack_size = True -> Multiply quantity by pack size
# use_pack_size = False -> Use quantity as is
if 'use_pack_size' not in data:
raise ValidationError({
'use_pack_size': _(
'The supplier part has a pack size defined, but flag use_pack_size not set'
)
})
else:
if bool(data.get('use_pack_size')):
quantity = data['quantity'] = supplier_part.base_quantity(
quantity
)
# Divide purchase price by pack size, to save correct price per stock item
if (
data['purchase_price']
and supplier_part.pack_quantity_native
):
try:
data['purchase_price'] = float(
data['purchase_price']
) / float(supplier_part.pack_quantity_native)
except ValueError:
pass
# Now remove the flag from data, so that it doesn't interfere with saving
# Do this regardless of results above
if 'use_pack_size' in data:
data.pop('use_pack_size')
# Assign serial numbers for a trackable part
if serial_numbers:
if not part.trackable:
raise ValidationError({
'serial_numbers': [
_('Serial numbers cannot be supplied for a non-trackable part')
]
})
# If serial numbers are specified, check that they match!
try:
serials = extract_serial_numbers(
serial_numbers, quantity, part.get_latest_serial_number()
)
# Determine if any of the specified serial numbers are invalid
# Note "invalid" means either they already exist, or do not pass custom rules
invalid = []
errors = []
for serial in serials:
try:
part.validate_serial_number(serial, raise_error=True)
except DjangoValidationError as exc:
# Catch raised error to extract specific error information
invalid.append(serial)
if exc.message not in errors:
errors.append(exc.message)
if len(errors) > 0:
msg = _('The following serial numbers already exist or are invalid')
msg += ' : '
msg += ','.join([str(e) for e in invalid])
raise ValidationError({'serial_numbers': errors + [msg]})