/
api.py
2377 lines (1810 loc) · 76.5 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
"""Provides a JSON API for the Part app."""
import functools
import re
from django.db.models import Count, F, Q
from django.http import JsonResponse
from django.urls import include, path, re_path
from django.utils.translation import gettext_lazy as _
from django_filters import rest_framework as rest_filters
from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import extend_schema_field
from rest_framework import permissions, serializers, status
from rest_framework.exceptions import ValidationError
from rest_framework.response import Response
import order.models
import part.filters
from build.models import Build, BuildItem
from InvenTree.api import (
APIDownloadMixin,
AttachmentMixin,
ListCreateDestroyAPIView,
MetadataView,
)
from InvenTree.filters import (
ORDER_FILTER,
SEARCH_ORDER_FILTER,
SEARCH_ORDER_FILTER_ALIAS,
InvenTreeDateFilter,
InvenTreeSearchFilter,
)
from InvenTree.helpers import (
DownloadFile,
increment_serial_number,
is_ajax,
isNull,
str2bool,
)
from InvenTree.mixins import (
CreateAPI,
CustomRetrieveUpdateDestroyAPI,
ListAPI,
ListCreateAPI,
RetrieveAPI,
RetrieveUpdateAPI,
RetrieveUpdateDestroyAPI,
UpdateAPI,
)
from InvenTree.permissions import RolePermission
from InvenTree.serializers import EmptySerializer
from InvenTree.status_codes import (
BuildStatusGroups,
PurchaseOrderStatusGroups,
SalesOrderStatusGroups,
)
from part.admin import PartCategoryResource, PartResource
from stock.models import StockLocation
from . import serializers as part_serializers
from . import views
from .models import (
BomItem,
BomItemSubstitute,
Part,
PartAttachment,
PartCategory,
PartCategoryParameterTemplate,
PartInternalPriceBreak,
PartParameter,
PartParameterTemplate,
PartRelated,
PartSellPriceBreak,
PartStocktake,
PartStocktakeReport,
PartTestTemplate,
)
class CategoryMixin:
"""Mixin class for PartCategory endpoints."""
serializer_class = part_serializers.CategorySerializer
queryset = PartCategory.objects.all()
def get_queryset(self, *args, **kwargs):
"""Return an annotated queryset for the CategoryDetail endpoint."""
queryset = super().get_queryset(*args, **kwargs)
queryset = part_serializers.CategorySerializer.annotate_queryset(queryset)
return queryset
def get_serializer_context(self):
"""Add extra context to the serializer for the CategoryDetail endpoint."""
ctx = super().get_serializer_context()
try:
ctx['starred_categories'] = [
star.category for star in self.request.user.starred_categories.all()
]
except AttributeError:
# Error is thrown if the view does not have an associated request
ctx['starred_categories'] = []
return ctx
class CategoryFilter(rest_filters.FilterSet):
"""Custom filterset class for the PartCategoryList endpoint."""
class Meta:
"""Metaclass options for this filterset."""
model = PartCategory
fields = ['name', 'structural']
starred = rest_filters.BooleanFilter(
label=_('Starred'),
method='filter_starred',
help_text=_('Filter by starred categories'),
)
def filter_starred(self, queryset, name, value):
"""Filter by whether the PartCategory is starred by the current user."""
user = self.request.user
starred_categories = [
star.category.pk for star in user.starred_categories.all()
]
if str2bool(value):
return queryset.filter(pk__in=starred_categories)
return queryset.exclude(pk__in=starred_categories)
depth = rest_filters.NumberFilter(
label=_('Depth'), method='filter_depth', help_text=_('Filter by category depth')
)
def filter_depth(self, queryset, name, value):
"""Filter by the "depth" of the PartCategory.
- This filter is used to limit the depth of the category tree
- If the "parent" filter is also provided, the depth is calculated from the parent category
"""
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-categories in filtered results'),
)
def filter_cascade(self, queryset, name, value):
"""Filter by whether to include sub-categories 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 categories
queryset = queryset.filter(parent=None)
return queryset
parent = rest_filters.ModelChoiceFilter(
queryset=PartCategory.objects.all(),
label=_('Parent'),
method='filter_parent',
help_text=_('Filter by parent category'),
)
def filter_parent(self, queryset, name, value):
"""Filter by parent category.
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 subcategories
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
exclude_tree = rest_filters.ModelChoiceFilter(
queryset=PartCategory.objects.all(),
label=_('Exclude Tree'),
method='filter_exclude_tree',
help_text=_('Exclude sub-categories under the specified category'),
)
@extend_schema_field(OpenApiTypes.INT)
def filter_exclude_tree(self, queryset, name, value):
"""Exclude all sub-categories under the specified category."""
# Exclude the specified category
queryset = queryset.exclude(pk=value.pk)
# Exclude any sub-categories also
queryset = queryset.exclude(parent__in=value.get_descendants(include_self=True))
return queryset
class CategoryList(CategoryMixin, APIDownloadMixin, ListCreateAPI):
"""API endpoint for accessing a list of PartCategory objects.
- GET: Return a list of PartCategory objects
- POST: Create a new PartCategory object
"""
filterset_class = CategoryFilter
def download_queryset(self, queryset, export_format):
"""Download the filtered queryset as a data file."""
dataset = PartCategoryResource().export(queryset=queryset)
filedata = dataset.export(export_format)
filename = f'InvenTree_Categories.{export_format}'
return DownloadFile(filedata, filename)
filter_backends = SEARCH_ORDER_FILTER
ordering_fields = ['name', 'pathstring', 'level', 'tree_id', 'lft', 'part_count']
# Use hierarchical ordering by default
ordering = ['tree_id', 'lft', 'name']
search_fields = ['name', 'description']
class CategoryDetail(CategoryMixin, CustomRetrieveUpdateDestroyAPI):
"""API endpoint for detail view of a single PartCategory object."""
def get_serializer(self, *args, **kwargs):
"""Add additional context based on query parameters."""
try:
params = self.request.query_params
kwargs['path_detail'] = str2bool(params.get('path_detail', False))
except AttributeError:
pass
kwargs.setdefault('context', self.get_serializer_context())
return self.serializer_class(*args, **kwargs)
def update(self, request, *args, **kwargs):
"""Perform 'update' function and mark this part as 'starred' (or not)."""
# Clean up input data
data = self.clean_data(request.data)
if 'starred' in data:
starred = str2bool(data.get('starred', False))
self.get_object().set_starred(request.user, starred)
response = super().update(request, *args, **kwargs)
return response
def destroy(self, request, *args, **kwargs):
"""Delete a Part category instance via the API."""
delete_parts = (
'delete_parts' in request.data and request.data['delete_parts'] == '1'
)
delete_child_categories = (
'delete_child_categories' in request.data
and request.data['delete_child_categories'] == '1'
)
return super().destroy(
request,
*args,
**dict(
kwargs,
delete_parts=delete_parts,
delete_child_categories=delete_child_categories,
),
)
class CategoryTree(ListAPI):
"""API endpoint for accessing a list of PartCategory objects ready for rendering a tree."""
queryset = PartCategory.objects.all()
serializer_class = part_serializers.CategoryTree
filter_backends = ORDER_FILTER
ordering_fields = ['level', 'name', 'subcategories']
# Order by tree level (top levels first) and then name
ordering = ['level', 'name']
def get_queryset(self, *args, **kwargs):
"""Return an annotated queryset for the CategoryTree endpoint."""
queryset = super().get_queryset(*args, **kwargs)
queryset = part_serializers.CategoryTree.annotate_queryset(queryset)
return queryset
class CategoryParameterList(ListCreateAPI):
"""API endpoint for accessing a list of PartCategoryParameterTemplate objects.
- GET: Return a list of PartCategoryParameterTemplate objects
"""
queryset = PartCategoryParameterTemplate.objects.all()
serializer_class = part_serializers.CategoryParameterTemplateSerializer
def get_queryset(self):
"""Custom filtering.
Rules:
- Allow filtering by "null" parent to retrieve all categories parameter templates
- Allow filtering by category
- Allow traversing all parent categories
"""
queryset = super().get_queryset()
params = self.request.query_params
category = params.get('category', None)
if category is not None:
try:
category = PartCategory.objects.get(pk=category)
fetch_parent = str2bool(params.get('fetch_parent', True))
if fetch_parent:
parents = category.get_ancestors(include_self=True)
queryset = queryset.filter(category__in=[cat.pk for cat in parents])
else:
queryset = queryset.filter(category=category)
except (ValueError, PartCategory.DoesNotExist):
pass
return queryset
class CategoryParameterDetail(RetrieveUpdateDestroyAPI):
"""Detail endpoint for the PartCategoryParameterTemplate model."""
queryset = PartCategoryParameterTemplate.objects.all()
serializer_class = part_serializers.CategoryParameterTemplateSerializer
class PartSalePriceDetail(RetrieveUpdateDestroyAPI):
"""Detail endpoint for PartSellPriceBreak model."""
queryset = PartSellPriceBreak.objects.all()
serializer_class = part_serializers.PartSalePriceSerializer
class PartSalePriceList(ListCreateAPI):
"""API endpoint for list view of PartSalePriceBreak model."""
queryset = PartSellPriceBreak.objects.all()
serializer_class = part_serializers.PartSalePriceSerializer
filter_backends = SEARCH_ORDER_FILTER
filterset_fields = ['part']
ordering_fields = ['quantity', 'price']
ordering = 'quantity'
class PartInternalPriceDetail(RetrieveUpdateDestroyAPI):
"""Detail endpoint for PartInternalPriceBreak model."""
queryset = PartInternalPriceBreak.objects.all()
serializer_class = part_serializers.PartInternalPriceSerializer
class PartInternalPriceList(ListCreateAPI):
"""API endpoint for list view of PartInternalPriceBreak model."""
queryset = PartInternalPriceBreak.objects.all()
serializer_class = part_serializers.PartInternalPriceSerializer
permission_required = 'roles.sales_order.show'
filter_backends = SEARCH_ORDER_FILTER
filterset_fields = ['part']
ordering_fields = ['quantity', 'price']
ordering = 'quantity'
class PartAttachmentList(AttachmentMixin, ListCreateDestroyAPIView):
"""API endpoint for listing, creating and bulk deleting a PartAttachment (file upload)."""
queryset = PartAttachment.objects.all()
serializer_class = part_serializers.PartAttachmentSerializer
filterset_fields = ['part']
class PartAttachmentDetail(AttachmentMixin, RetrieveUpdateDestroyAPI):
"""Detail endpoint for PartAttachment model."""
queryset = PartAttachment.objects.all()
serializer_class = part_serializers.PartAttachmentSerializer
class PartTestTemplateFilter(rest_filters.FilterSet):
"""Custom filterset class for the PartTestTemplateList endpoint."""
class Meta:
"""Metaclass options for this filterset."""
model = PartTestTemplate
fields = ['enabled', 'key', 'required', 'requires_attachment', 'requires_value']
part = rest_filters.ModelChoiceFilter(
queryset=Part.objects.filter(trackable=True),
label='Part',
field_name='part',
method='filter_part',
)
def filter_part(self, queryset, name, part):
"""Filter by the 'part' field.
Note that for the 'part' field, we also include any parts "above" the specified part.
"""
include_inherited = str2bool(
self.request.query_params.get('include_inherited', True)
)
if include_inherited:
return queryset.filter(part__in=part.get_ancestors(include_self=True))
else:
return queryset.filter(part=part)
has_results = rest_filters.BooleanFilter(
label=_('Has Results'), method='filter_has_results'
)
def filter_has_results(self, queryset, name, value):
"""Filter by whether the PartTestTemplate has any associated test results."""
if str2bool(value):
return queryset.exclude(results=0)
return queryset.filter(results=0)
class PartTestTemplateMixin:
"""Mixin class for the PartTestTemplate API endpoints."""
queryset = PartTestTemplate.objects.all()
serializer_class = part_serializers.PartTestTemplateSerializer
def get_queryset(self, *args, **kwargs):
"""Return an annotated queryset for the PartTestTemplateDetail endpoints."""
queryset = super().get_queryset(*args, **kwargs)
queryset = part_serializers.PartTestTemplateSerializer.annotate_queryset(
queryset
)
return queryset
class PartTestTemplateDetail(PartTestTemplateMixin, RetrieveUpdateDestroyAPI):
"""Detail endpoint for PartTestTemplate model."""
pass
class PartTestTemplateList(PartTestTemplateMixin, ListCreateAPI):
"""API endpoint for listing (and creating) a PartTestTemplate."""
filterset_class = PartTestTemplateFilter
filter_backends = SEARCH_ORDER_FILTER
search_fields = ['test_name', 'description']
ordering_fields = [
'enabled',
'required',
'requires_value',
'requires_attachment',
'results',
'test_name',
]
ordering = 'test_name'
class PartThumbs(ListAPI):
"""API endpoint for retrieving information on available Part thumbnails."""
queryset = Part.objects.all()
serializer_class = part_serializers.PartThumbSerializer
def get_queryset(self):
"""Return a queryset which excludes any parts without images."""
queryset = super().get_queryset()
# Get all Parts which have an associated image
queryset = queryset.exclude(image='')
return queryset
def list(self, request, *args, **kwargs):
"""Serialize the available Part images.
- Images may be used for multiple parts!
"""
queryset = self.filter_queryset(self.get_queryset())
# Return the most popular parts first
data = (
queryset.values('image').annotate(count=Count('image')).order_by('-count')
)
page = self.paginate_queryset(data)
if page is not None:
serializer = self.get_serializer(page, many=True)
else:
serializer = self.get_serializer(data, many=True)
data = serializer.data
return Response(data)
filter_backends = [InvenTreeSearchFilter]
search_fields = [
'name',
'description',
'IPN',
'revision',
'keywords',
'category__name',
]
class PartThumbsUpdate(RetrieveUpdateAPI):
"""API endpoint for updating Part thumbnails."""
queryset = Part.objects.all()
serializer_class = part_serializers.PartThumbSerializerUpdate
filter_backends = [DjangoFilterBackend]
class PartScheduling(RetrieveAPI):
"""API endpoint for delivering "scheduling" information about a given part via the API.
Returns a chronologically ordered list about future "scheduled" events,
concerning stock levels for the part:
- Purchase Orders (incoming stock)
- Sales Orders (outgoing stock)
- Build Orders (incoming completed stock)
- Build Orders (outgoing allocated stock)
"""
queryset = Part.objects.all()
serializer_class = EmptySerializer
def retrieve(self, request, *args, **kwargs):
"""Return scheduling information for the referenced Part instance."""
part = self.get_object()
schedule = []
def add_schedule_entry(
date, quantity, title, label, url, speculative_quantity=0
):
"""Check if a scheduled entry should be added.
Rules:
- date must be non-null
- date cannot be in the "past"
- quantity must not be zero
"""
schedule.append({
'date': date,
'quantity': quantity,
'speculative_quantity': speculative_quantity,
'title': title,
'label': label,
'url': url,
})
# Add purchase order (incoming stock) information
po_lines = order.models.PurchaseOrderLineItem.objects.filter(
part__part=part, order__status__in=PurchaseOrderStatusGroups.OPEN
)
for line in po_lines:
target_date = line.target_date or line.order.target_date
line_quantity = max(line.quantity - line.received, 0)
# Multiply by the pack quantity of the SupplierPart
quantity = line.part.base_quantity(line_quantity)
add_schedule_entry(
target_date,
quantity,
_('Incoming Purchase Order'),
str(line.order),
line.order.get_absolute_url(),
)
# Add sales order (outgoing stock) information
so_lines = order.models.SalesOrderLineItem.objects.filter(
part=part, order__status__in=SalesOrderStatusGroups.OPEN
)
for line in so_lines:
target_date = line.target_date or line.order.target_date
quantity = max(line.quantity - line.shipped, 0)
add_schedule_entry(
target_date,
-quantity,
_('Outgoing Sales Order'),
str(line.order),
line.order.get_absolute_url(),
)
# Add build orders (incoming stock) information
build_orders = Build.objects.filter(
part=part, status__in=BuildStatusGroups.ACTIVE_CODES
)
for build in build_orders:
quantity = max(build.quantity - build.completed, 0)
add_schedule_entry(
build.target_date,
quantity,
_('Stock produced by Build Order'),
str(build),
build.get_absolute_url(),
)
"""
Add build order allocation (outgoing stock) information.
Here we need some careful consideration:
- 'Tracked' stock items are removed from stock when the individual Build Output is completed
- 'Untracked' stock items are removed from stock when the Build Order is completed
The 'simplest' approach here is to look at existing BuildItem allocations which reference this part,
and "schedule" them for removal at the time of build order completion.
This assumes that the user is responsible for correctly allocating parts.
However, it has the added benefit of side-stepping the various BOM substitution options,
and just looking at what stock items the user has actually allocated against the Build.
"""
# Grab a list of BomItem objects that this part might be used in
bom_items = BomItem.objects.filter(part.get_used_in_bom_item_filter())
# Track all outstanding build orders
seen_builds = set()
for bom_item in bom_items:
# Find a list of active builds for this BomItem
if bom_item.inherited:
# An "inherited" BOM item filters down to variant parts also
children = bom_item.part.get_descendants(include_self=True)
builds = Build.objects.filter(
status__in=BuildStatusGroups.ACTIVE_CODES, part__in=children
)
else:
builds = Build.objects.filter(
status__in=BuildStatusGroups.ACTIVE_CODES, part=bom_item.part
)
for build in builds:
# Ensure we don't double-count any builds
if build in seen_builds:
continue
seen_builds.add(build)
if bom_item.sub_part.trackable:
# Trackable parts are allocated against the outputs
required_quantity = build.remaining * bom_item.quantity
else:
# Non-trackable parts are allocated against the build itself
required_quantity = build.quantity * bom_item.quantity
# Grab all allocations against the specified BomItem
allocations = BuildItem.objects.filter(
build_line__bom_item=bom_item, build_line__build=build
)
# Total allocated for *this* part
part_allocated_quantity = 0
# Total allocated for *any* part
total_allocated_quantity = 0
for allocation in allocations:
total_allocated_quantity += allocation.quantity
if allocation.stock_item.part == part:
part_allocated_quantity += allocation.quantity
speculative_quantity = 0
# Consider the case where the build order is *not* fully allocated
if required_quantity > total_allocated_quantity:
speculative_quantity = -1 * (
required_quantity - total_allocated_quantity
)
add_schedule_entry(
build.target_date,
-part_allocated_quantity,
_('Stock required for Build Order'),
str(build),
build.get_absolute_url(),
speculative_quantity=speculative_quantity,
)
def compare(entry_1, entry_2):
"""Comparison function for sorting entries by date.
Account for the fact that either date might be None
"""
date_1 = entry_1['date']
date_2 = entry_2['date']
if date_1 is None:
return -1
elif date_2 is None:
return 1
return -1 if date_1 < date_2 else 1
# Sort by incrementing date values
schedule = sorted(schedule, key=functools.cmp_to_key(compare))
return Response(schedule)
class PartRequirements(RetrieveAPI):
"""API endpoint detailing 'requirements' information for a particular part.
This endpoint returns information on upcoming requirements for:
- Sales Orders
- Build Orders
- Total requirements
As this data is somewhat complex to calculate, is it not included in the default API
"""
queryset = Part.objects.all()
serializer_class = EmptySerializer
def retrieve(self, request, *args, **kwargs):
"""Construct a response detailing Part requirements."""
part = self.get_object()
data = {
'available_stock': part.available_stock,
'on_order': part.on_order,
'required_build_order_quantity': part.required_build_order_quantity(),
'allocated_build_order_quantity': part.build_order_allocation_count(),
'required_sales_order_quantity': part.required_sales_order_quantity(),
'allocated_sales_order_quantity': part.sales_order_allocation_count(
pending=True
),
}
data['allocated'] = (
data['allocated_build_order_quantity']
+ data['allocated_sales_order_quantity']
)
data['required'] = (
data['required_build_order_quantity']
+ data['required_sales_order_quantity']
)
return Response(data)
class PartPricingDetail(RetrieveUpdateAPI):
"""API endpoint for viewing part pricing data."""
serializer_class = part_serializers.PartPricingSerializer
queryset = Part.objects.all()
def get_object(self):
"""Return the PartPricing object associated with the linked Part."""
part = super().get_object()
return part.pricing
def _get_serializer(self, *args, **kwargs):
"""Return a part pricing serializer object."""
part = self.get_object()
kwargs['instance'] = part.pricing
return self.serializer_class(**kwargs)
class PartSerialNumberDetail(RetrieveAPI):
"""API endpoint for returning extra serial number information about a particular part."""
queryset = Part.objects.all()
serializer_class = EmptySerializer
def retrieve(self, request, *args, **kwargs):
"""Return serial number information for the referenced Part instance."""
part = self.get_object()
# Calculate the "latest" serial number
latest = part.get_latest_serial_number()
data = {'latest': latest}
if latest is not None:
next_serial = increment_serial_number(latest)
if next_serial != latest:
data['next'] = next_serial
return Response(data)
class PartCopyBOM(CreateAPI):
"""API endpoint for duplicating a BOM."""
queryset = Part.objects.all()
serializer_class = part_serializers.PartCopyBOMSerializer
def get_serializer_context(self):
"""Add custom information to the serializer context for this endpoint."""
ctx = super().get_serializer_context()
try:
ctx['part'] = Part.objects.get(pk=self.kwargs.get('pk', None))
except Exception:
pass
return ctx
class PartValidateBOM(RetrieveUpdateAPI):
"""API endpoint for 'validating' the BOM for a given Part."""
class BOMValidateSerializer(serializers.ModelSerializer):
"""Simple serializer class for validating a single BomItem instance."""
class Meta:
"""Metaclass defines serializer fields."""
model = Part
fields = ['checksum', 'valid']
checksum = serializers.CharField(read_only=True, source='bom_checksum')
valid = serializers.BooleanField(
write_only=True,
default=False,
label=_('Valid'),
help_text=_('Validate entire Bill of Materials'),
)
def validate_valid(self, valid):
"""Check that the 'valid' input was flagged."""
if not valid:
raise ValidationError(_('This option must be selected'))
queryset = Part.objects.all()
serializer_class = BOMValidateSerializer
def update(self, request, *args, **kwargs):
"""Validate the referenced BomItem instance."""
part = self.get_object()
partial = kwargs.pop('partial', False)
# Clean up input data before using it
data = self.clean_data(request.data)
serializer = self.get_serializer(part, data=data, partial=partial)
serializer.is_valid(raise_exception=True)
part.validate_bom(request.user)
return Response({'checksum': part.bom_checksum})
class PartFilter(rest_filters.FilterSet):
"""Custom filters for the PartList endpoint.
Uses the django_filters extension framework
"""
class Meta:
"""Metaclass options for this filter set."""
model = Part
fields = []
has_units = rest_filters.BooleanFilter(label='Has units', method='filter_has_units')
def filter_has_units(self, queryset, name, value):
"""Filter by whether the Part has units or not."""
if str2bool(value):
return queryset.exclude(Q(units=None) | Q(units=''))
return queryset.filter(Q(units=None) | Q(units='')).distinct()
# Filter by parts which have (or not) an IPN value
has_ipn = rest_filters.BooleanFilter(label='Has IPN', method='filter_has_ipn')
def filter_has_ipn(self, queryset, name, value):
"""Filter by whether the Part has an IPN (internal part number) or not."""
if str2bool(value):
return queryset.exclude(IPN='')
return queryset.filter(IPN='')
# Regex filter for name
name_regex = rest_filters.CharFilter(
label='Filter by name (regex)', field_name='name', lookup_expr='iregex'
)
# Exact match for IPN
IPN = rest_filters.CharFilter(
label='Filter by exact IPN (internal part number)',
field_name='IPN',
lookup_expr='iexact',
)
# Regex match for IPN
IPN_regex = rest_filters.CharFilter(
label='Filter by regex on IPN (internal part number)',
field_name='IPN',
lookup_expr='iregex',
)
# low_stock filter
low_stock = rest_filters.BooleanFilter(label='Low stock', method='filter_low_stock')
def filter_low_stock(self, queryset, name, value):
"""Filter by "low stock" status."""
if str2bool(value):
# Ignore any parts which do not have a specified 'minimum_stock' level
# Filter items which have an 'in_stock' level lower than 'minimum_stock'
return queryset.exclude(minimum_stock=0).filter(
Q(total_in_stock__lt=F('minimum_stock'))
)
# Filter items which have an 'in_stock' level higher than 'minimum_stock'
return queryset.filter(Q(total_in_stock__gte=F('minimum_stock')))
# has_stock filter
has_stock = rest_filters.BooleanFilter(label='Has stock', method='filter_has_stock')
def filter_has_stock(self, queryset, name, value):
"""Filter by whether the Part has any stock."""
if str2bool(value):
return queryset.filter(Q(in_stock__gt=0))
return queryset.filter(Q(in_stock__lte=0))
# unallocated_stock filter
unallocated_stock = rest_filters.BooleanFilter(
label='Unallocated stock', method='filter_unallocated_stock'
)
def filter_unallocated_stock(self, queryset, name, value):