forked from inventree/InvenTree
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserializers.py
More file actions
2023 lines (1578 loc) · 59.5 KB
/
serializers.py
File metadata and controls
2023 lines (1578 loc) · 59.5 KB
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 serializers for Stock app."""
from datetime import timedelta
from decimal import Decimal
from django.core.exceptions import ValidationError as DjangoValidationError
from django.db import transaction
from django.db.models import BooleanField, Case, Count, Prefetch, Q, Value, When
from django.db.models.functions import Coalesce
from django.utils.translation import gettext_lazy as _
import structlog
from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers
from rest_framework.serializers import ValidationError
from sql_util.utils import SubqueryCount, SubquerySum
import build.models
import common.filters
import company.models
import company.serializers as company_serializers
import InvenTree.helpers
import InvenTree.ready
import InvenTree.serializers
import order.models
import part.filters as part_filters
import part.models as part_models
import part.serializers as part_serializers
import stock.filters
import stock.status_codes
from common.settings import get_global_setting
from generic.states.fields import InvenTreeCustomStatusSerializerMixin
from importer.registry import register_importer
from InvenTree.mixins import DataImportExportSerializerMixin
from InvenTree.serializers import (
FilterableListField,
InvenTreeCurrencySerializer,
InvenTreeDecimalField,
enable_filter,
)
from users.serializers import UserSerializer
from .models import (
StockItem,
StockItemTestResult,
StockItemTracking,
StockLocation,
StockLocationType,
)
logger = structlog.get_logger('inventree')
class GenerateBatchCodeSerializer(serializers.Serializer):
"""Serializer for generating a batch code.
Any of the provided write-only fields can be used for additional context.
"""
class Meta:
"""Metaclass options."""
fields = [
'batch_code',
'build_order',
'item',
'location',
'part',
'purchase_order',
'quantity',
]
read_only_fields = ['batch_code']
write_only_fields = [
'build_order',
'item',
'location',
'part',
'purchase_order',
'quantity',
]
batch_code = serializers.CharField(
read_only=True, help_text=_('Generated batch code'), label=_('Batch Code')
)
build_order = serializers.PrimaryKeyRelatedField(
queryset=build.models.Build.objects.all(),
many=False,
required=False,
allow_null=True,
label=_('Build Order'),
help_text=_('Select build order'),
)
item = serializers.PrimaryKeyRelatedField(
queryset=StockItem.objects.all(),
many=False,
required=False,
allow_null=True,
label=_('Stock Item'),
help_text=_('Select stock item to generate batch code for'),
)
location = serializers.PrimaryKeyRelatedField(
queryset=StockLocation.objects.all(),
many=False,
required=False,
allow_null=True,
label=_('Location'),
help_text=_('Select location to generate batch code for'),
)
part = serializers.PrimaryKeyRelatedField(
queryset=part_models.Part.objects.all(),
many=False,
required=False,
allow_null=True,
label=_('Part'),
help_text=_('Select part to generate batch code for'),
)
purchase_order = serializers.PrimaryKeyRelatedField(
queryset=order.models.PurchaseOrder.objects.all(),
many=False,
required=False,
allow_null=True,
label=_('Purchase Order'),
help_text=_('Select purchase order'),
)
quantity = serializers.FloatField(
required=False,
allow_null=True,
label=_('Quantity'),
help_text=_('Enter quantity for batch code'),
)
class GenerateSerialNumberSerializer(serializers.Serializer):
"""Serializer for generating one or multiple serial numbers.
Any of the provided write-only fields can be used for additional context.
Note that in the case where multiple serial numbers are required,
the "serial_number" field will return a string with multiple serial numbers
separated by a comma.
"""
class Meta:
"""Metaclass options."""
fields = ['serial_number', 'part', 'quantity']
read_only_fields = ['serial_number']
write_only_fields = ['part', 'quantity']
serial_number = serializers.CharField(
read_only=True,
allow_null=True,
help_text=_('Generated serial number'),
label=_('Serial Number'),
)
part = serializers.PrimaryKeyRelatedField(
queryset=part_models.Part.objects.all(),
many=False,
required=False,
allow_null=True,
label=_('Part'),
help_text=_('Select part to generate serial number for'),
)
quantity = serializers.IntegerField(
required=False,
allow_null=False,
default=1,
label=_('Quantity'),
help_text=_('Quantity of serial numbers to generate'),
)
class LocationBriefSerializer(InvenTree.serializers.InvenTreeModelSerializer):
"""Provides a brief serializer for a StockLocation object."""
class Meta:
"""Metaclass options."""
model = StockLocation
fields = ['pk', 'name', 'pathstring']
@register_importer()
class StockItemTestResultSerializer(
InvenTree.serializers.FilterableSerializerMixin,
DataImportExportSerializerMixin,
InvenTree.serializers.InvenTreeModelSerializer,
):
"""Serializer for the StockItemTestResult model."""
class Meta:
"""Metaclass options."""
model = StockItemTestResult
fields = [
'pk',
'stock_item',
'result',
'value',
'attachment',
'notes',
'test_station',
'started_datetime',
'finished_datetime',
'user',
'user_detail',
'date',
'template',
'template_detail',
]
read_only_fields = ['pk', 'user', 'date']
user_detail = enable_filter(
UserSerializer(source='user', read_only=True, allow_null=True),
prefetch_fields=['user'],
)
template = serializers.PrimaryKeyRelatedField(
queryset=part_models.PartTestTemplate.objects.all(),
many=False,
required=False,
allow_null=True,
help_text=_('Template'),
label=_('Test template for this result'),
)
template_detail = enable_filter(
part_serializers.PartTestTemplateSerializer(
source='template', read_only=True, allow_null=True
),
prefetch_fields=['template'],
)
attachment = InvenTree.serializers.InvenTreeAttachmentSerializerField(
required=False,
allow_null=True,
label=_('Attachment'),
help_text=_('Test result attachment'),
)
def validate(self, data):
"""Validate the test result data."""
stock_item = data['stock_item']
template = data.get('template', None)
test_name = None
if not template:
# To support legacy API, we can accept a test name instead of a template
# In such a case, we use the test name to lookup the appropriate template
request_data = self.context['request'].data
if type(request_data) is list and len(request_data) > 0:
request_data = request_data[0]
test_name = request_data.get('test', test_name)
test_key = InvenTree.helpers.generateTestKey(test_name)
ancestors = stock_item.part.get_ancestors(include_self=True)
# Find a template based on name
if template := part_models.PartTestTemplate.objects.filter(
part__tree_id=stock_item.part.tree_id, part__in=ancestors, key=test_key
).first():
data['template'] = template
else:
raise ValidationError({
'test': _('No matching test found for this part')
})
if not template:
raise ValidationError(_('Template ID or test name must be provided'))
data = super().validate(data)
started = data.get('started_datetime')
finished = data.get('finished_datetime')
if started is not None and finished is not None and started > finished:
raise ValidationError({
'finished_datetime': _(
'The test finished time cannot be earlier than the test started time'
)
})
return data
@register_importer()
class StockItemSerializer(
InvenTree.serializers.FilterableSerializerMixin,
DataImportExportSerializerMixin,
InvenTreeCustomStatusSerializerMixin,
InvenTree.serializers.InvenTreeTagModelSerializer,
):
"""Serializer for a StockItem.
- Includes serialization for the linked part
- Includes serialization for the item location
"""
export_exclude_fields = ['tags', 'tracking_items']
export_child_fields = [
'part_detail.name',
'part_detail.description',
'part_detail.IPN',
'part_detail.revision',
'part_detail.pricing_min',
'part_detail.pricing_max',
'location_detail.name',
'location_detail.pathstring',
'supplier_part_detail.SKU',
'supplier_part_detail.MPN',
]
import_exclude_fields = ['location_path', 'serial_numbers', 'use_pack_size']
class Meta:
"""Metaclass options."""
model = StockItem
fields = [
'pk',
'part',
'quantity',
'serial',
'batch',
'location',
'belongs_to',
'build',
'consumed_by',
'customer',
'delete_on_deplete',
'expiry_date',
'in_stock',
'is_building',
'link',
'notes',
'owner',
'packaging',
'parent',
'purchase_order',
'purchase_order_reference',
'sales_order',
'sales_order_reference',
'status',
'status_text',
'status_custom_key',
'supplier_part',
'SKU',
'MPN',
'barcode_hash',
'updated',
'stocktake_date',
'purchase_price',
'purchase_price_currency',
'use_pack_size',
'serial_numbers',
'tests',
# Annotated fields
'allocated',
'expired',
'installed_items',
'child_items',
'location_path',
'stale',
'tracking_items',
'tags',
# Detail fields (FK relationships)
'supplier_part_detail',
'part_detail',
'location_detail',
]
read_only_fields = [
'allocated',
'barcode_hash',
'stocktake_date',
'stocktake_user',
'updated',
]
"""
These fields are read-only in this context.
They can be updated by accessing the appropriate API endpoints
"""
extra_kwargs = {
'use_pack_size': {'write_only': True},
'serial_numbers': {'write_only': True},
}
"""
Fields used when creating a stock item
"""
part = serializers.PrimaryKeyRelatedField(
queryset=part_models.Part.objects.all(),
many=False,
allow_null=False,
help_text=_('Base Part'),
label=_('Part'),
)
parent = serializers.PrimaryKeyRelatedField(
many=False,
read_only=True,
label=_('Parent Item'),
help_text=_('Parent stock item'),
)
location_path = enable_filter(
FilterableListField(
child=serializers.DictField(),
source='location.get_path',
read_only=True,
allow_null=True,
),
filter_name='path_detail',
)
in_stock = serializers.BooleanField(read_only=True, label=_('In Stock'))
"""
Field used when creating a stock item
"""
use_pack_size = serializers.BooleanField(
write_only=True,
required=False,
allow_null=True,
help_text=_(
'Use pack size when adding: the quantity defined is the number of packs'
),
label=_('Use pack size'),
)
serial_numbers = serializers.CharField(
write_only=True,
required=False,
allow_null=True,
help_text=_('Enter serial numbers for new items'),
)
def validate_part(self, part):
"""Ensure the provided Part instance is valid."""
if part.virtual:
raise ValidationError(_('Stock item cannot be created for virtual parts'))
return part
def update(self, instance, validated_data):
"""Custom update method to pass the user information through to the instance."""
instance._user = self.context.get('user', None)
status_custom_key = validated_data.pop('status_custom_key', None)
status = validated_data.pop('status', None)
if status_code := status_custom_key or status:
# avoid a second .save() call and perform both status updates at once (to support `old_status` in tracking event)
# by setting the values in validated_data as computed by set_status()
instance.set_status(status_code)
validated_data['status'] = instance.status
validated_data['status_custom_key'] = (
status_code # for compatibility with custom "leader/follower" concept in super().update()
)
instance = super().update(instance, validated_data=validated_data)
return instance
@staticmethod
def annotate_queryset(queryset):
"""Add some extra annotations to the queryset, performing database queries as efficiently as possible."""
queryset = queryset.prefetch_related(
'location',
'sales_order',
'purchase_order',
Prefetch(
'part',
queryset=part_models.Part.objects.annotate(
category_default_location=part_filters.annotate_default_location(
'category__'
)
).prefetch_related(None),
),
'parent',
'part__category',
'supplier_part',
'supplier_part__manufacturer_part',
'customer',
'belongs_to',
'sales_order',
'consumed_by',
).select_related('part', 'part__pricing_data')
# Annotate the queryset with the total allocated to sales orders
queryset = queryset.annotate(
allocated=Coalesce(
SubquerySum('sales_order_allocations__quantity'), Decimal(0)
)
+ Coalesce(SubquerySum('allocations__quantity'), Decimal(0))
)
# Annotate the queryset with the number of tracking items
queryset = queryset.annotate(tracking_items=SubqueryCount('tracking_info'))
# Add flag to indicate if the StockItem has expired
queryset = queryset.annotate(
expired=Case(
When(
StockItem.EXPIRED_FILTER,
then=Value(True, output_field=BooleanField()),
),
default=Value(False, output_field=BooleanField()),
)
)
# Add flag to indicate if the StockItem is stale
stale_days = get_global_setting('STOCK_STALE_DAYS')
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)
)
queryset = queryset.annotate(
stale=Case(
When(stale_filter, then=Value(True, output_field=BooleanField())),
default=Value(False, output_field=BooleanField()),
)
)
# Annotate with the total number of "installed items"
queryset = queryset.annotate(installed_items=SubqueryCount('installed_parts'))
# Annotate with the total number of "child items" (split stock items)
queryset = queryset.annotate(child_items=SubqueryCount('children'))
return queryset
status_text = serializers.CharField(
source='get_status_display', read_only=True, label=_('Status')
)
SKU = serializers.CharField(
source='supplier_part.SKU',
read_only=True,
label=_('Supplier Part Number'),
allow_null=True,
)
MPN = serializers.CharField(
source='supplier_part.manufacturer_part.MPN',
read_only=True,
label=_('Manufacturer Part Number'),
allow_null=True,
)
# Optional detail fields, which can be appended via query parameters
supplier_part_detail = enable_filter(
company_serializers.SupplierPartSerializer(
label=_('Supplier Part'),
source='supplier_part',
brief=True,
supplier_detail=False,
manufacturer_detail=False,
part_detail=False,
many=False,
read_only=True,
allow_null=True,
),
False,
prefetch_fields=[
'supplier_part__supplier',
'supplier_part__purchase_order_line_items',
'supplier_part__manufacturer_part__manufacturer',
],
)
part_detail = enable_filter(
part_serializers.PartBriefSerializer(
label=_('Part'), source='part', many=False, read_only=True, allow_null=True
),
True,
)
location_detail = enable_filter(
LocationBriefSerializer(
label=_('Location'),
source='location',
many=False,
read_only=True,
allow_null=True,
),
False,
prefetch_fields=['location'],
)
tests = enable_filter(
StockItemTestResultSerializer(
source='test_results', many=True, read_only=True, allow_null=True
),
False,
prefetch_fields=[
'test_results',
'test_results__user',
'test_results__template',
],
)
quantity = InvenTreeDecimalField()
# Annotated fields
allocated = serializers.FloatField(
read_only=True, allow_null=True, label=_('Allocated Quantity')
)
expired = serializers.BooleanField(
read_only=True, allow_null=True, label=_('Expired')
)
installed_items = serializers.IntegerField(
read_only=True, allow_null=True, label=_('Installed Items')
)
child_items = serializers.IntegerField(
read_only=True, allow_null=True, label=_('Child Items')
)
stale = serializers.BooleanField(read_only=True, allow_null=True, label=_('Stale'))
tracking_items = serializers.IntegerField(
read_only=True, allow_null=True, label=_('Tracking Items')
)
purchase_price = InvenTree.serializers.InvenTreeMoneySerializer(
label=_('Purchase Price'),
allow_null=True,
help_text=_('Purchase price of this stock item, per unit or pack'),
)
purchase_price_currency = InvenTreeCurrencySerializer(
help_text=_('Purchase currency of this stock item')
)
purchase_order_reference = serializers.CharField(
source='purchase_order.reference', read_only=True, allow_null=True
)
sales_order_reference = serializers.CharField(
source='sales_order.reference', read_only=True, allow_null=True
)
tags = common.filters.enable_tags_filter()
class SerializeStockItemSerializer(serializers.Serializer):
"""A DRF serializer for "serializing" a StockItem.
(Sorry for the confusing naming...)
Here, "serializing" means splitting out a single StockItem,
into multiple single-quantity items with an assigned serial number
Note: The base StockItem object is provided to the serializer context
"""
class Meta:
"""Metaclass options."""
fields = ['quantity', 'serial_numbers', 'destination', 'notes']
quantity = serializers.IntegerField(
min_value=0,
required=True,
label=_('Quantity'),
help_text=_('Enter number of stock items to serialize'),
)
def validate_quantity(self, quantity):
"""Validate that the quantity value is correct."""
item = self.context.get('item')
if not item:
raise ValidationError(_('No stock item provided'))
if quantity < 0:
raise ValidationError(_('Quantity must be greater than zero'))
if quantity > item.quantity:
q = item.quantity
raise ValidationError(
_(f'Quantity must not exceed available stock quantity ({q})')
)
return quantity
serial_numbers = serializers.CharField(
label=_('Serial Numbers'),
help_text=_('Enter serial numbers for new items'),
allow_blank=False,
required=True,
)
destination = serializers.PrimaryKeyRelatedField(
queryset=StockLocation.objects.all(),
many=False,
required=True,
allow_null=False,
label=_('Location'),
help_text=_('Destination stock location'),
)
notes = serializers.CharField(
required=False,
allow_blank=True,
label=_('Notes'),
help_text=_('Optional note field'),
)
def validate(self, data):
"""Check that the supplied serial numbers are valid."""
data = super().validate(data)
item = self.context.get('item')
if not item:
raise ValidationError(_('No stock item provided'))
if not item.part.trackable:
raise ValidationError(_('Serial numbers cannot be assigned to this part'))
# Ensure the serial numbers are valid!
quantity = data['quantity']
serial_numbers = data['serial_numbers']
try:
serials = InvenTree.helpers.extract_serial_numbers(
serial_numbers,
quantity,
item.part.get_latest_serial_number(),
part=item.part,
)
except DjangoValidationError as e:
raise ValidationError({'serial_numbers': e.messages})
existing = item.part.find_conflicting_serial_numbers(serials)
if len(existing) > 0:
exists = ','.join([str(x) for x in existing])
error = _('Serial numbers already exist') + ': ' + exists
raise ValidationError({'serial_numbers': error})
return data
def save(self) -> list[StockItem]:
"""Serialize the provided StockItem.
Returns:
A list of StockItem objects that were created as a result of the serialization.
"""
item = self.context.get('item')
if not item:
raise ValidationError(_('No stock item provided'))
request = self.context.get('request')
user = request.user if request else None
data = self.validated_data
serials = InvenTree.helpers.extract_serial_numbers(
data['serial_numbers'],
data['quantity'],
item.part.get_latest_serial_number(),
part=item.part,
)
return (
item.serializeStock(
data['quantity'],
serials,
user=user,
notes=data.get('notes', ''),
location=data['destination'],
)
or []
)
class InstallStockItemSerializer(serializers.Serializer):
"""Serializer for installing a stock item into a given part."""
stock_item = serializers.PrimaryKeyRelatedField(
queryset=StockItem.objects.all(),
many=False,
required=True,
allow_null=False,
label=_('Stock Item'),
help_text=_('Select stock item to install'),
)
quantity = serializers.IntegerField(
min_value=1,
default=1,
required=False,
label=_('Quantity to Install'),
help_text=_('Enter the quantity of items to install'),
)
note = serializers.CharField(
label=_('Note'),
help_text=_('Add transaction note (optional)'),
required=False,
allow_blank=True,
)
def validate_quantity(self, quantity):
"""Validate the quantity value."""
if quantity < 1:
raise ValidationError(_('Quantity to install must be at least 1'))
return quantity
def validate_stock_item(self, stock_item):
"""Validate the selected stock item."""
if not stock_item.in_stock:
# StockItem must be in stock to be "installed"
raise ValidationError(_('Stock item is unavailable'))
parent_item = self.context['item']
parent_part = parent_item.part
if get_global_setting(
'STOCK_ENFORCE_BOM_INSTALLATION', backup_value=True, cache=False
):
# Check if the selected part is in the Bill of Materials of the parent item
if not parent_part.check_if_part_in_bom(stock_item.part):
raise ValidationError(
_('Selected part is not in the Bill of Materials')
)
return stock_item
def validate(self, data):
"""Ensure that the provided dataset is valid."""
stock_item = data['stock_item']
quantity = data.get('quantity', stock_item.quantity)
if quantity > stock_item.quantity:
raise ValidationError({
'quantity': _('Quantity to install must not exceed available quantity')
})
return data
def save(self):
"""Install the selected stock item into this one."""
data = self.validated_data
stock_item = data['stock_item']
quantity_to_install = data.get('quantity', stock_item.quantity)
note = data.get('note', '')
parent_item = self.context['item']
request = self.context['request']
parent_item.installStockItem(
stock_item, quantity_to_install, request.user, note
)
class UninstallStockItemSerializer(serializers.Serializer):
"""API serializers for uninstalling an installed item from a stock item."""
class Meta:
"""Metaclass options."""
fields = ['location', 'note']
location = serializers.PrimaryKeyRelatedField(
queryset=StockLocation.objects.all(),
many=False,
required=True,
allow_null=False,
label=_('Location'),
help_text=_('Destination location for uninstalled item'),
)
note = serializers.CharField(
label=_('Notes'),
help_text=_('Add transaction note (optional)'),
required=False,
allow_blank=True,
)
def save(self):
"""Uninstall stock item."""
item = self.context.get('item')
if not item:
raise ValidationError(_('No stock item provided'))
data = self.validated_data
request = self.context['request']
location = data['location']
note = data.get('note', '')
item.uninstall_into_location(location, request.user, note)
class ConvertStockItemSerializer(serializers.Serializer):
"""DRF serializer class for converting a StockItem to a valid variant part."""
class Meta:
"""Metaclass options."""
fields = ['part']
part = serializers.PrimaryKeyRelatedField(
queryset=part_models.Part.objects.all(),
label=_('Part'),
help_text=_('Select part to convert stock item into'),
many=False,
required=True,
allow_null=False,
)
def validate_part(self, part):
"""Ensure that the provided part is a valid option for the stock item."""
stock_item = self.context['item']
valid_options = stock_item.part.get_conversion_options()
if part not in valid_options:
raise ValidationError(
_('Selected part is not a valid option for conversion')
)
return part
def validate(self, data):
"""Ensure that the stock item is valid for conversion.
Rules:
- If a SupplierPart is assigned, we cannot convert!
"""
data = super().validate(data)
stock_item = self.context['item']
if stock_item.supplier_part is not None:
raise ValidationError(
_('Cannot convert stock item with assigned SupplierPart')
)
return data
def save(self):
"""Save the serializer to convert the StockItem to the selected Part."""
data = self.validated_data
part = data['part']
stock_item = self.context['item']
request = self.context['request']
stock_item.convert_to_variant(part, request.user)
@extend_schema_field(
serializers.IntegerField(
help_text='Status key, chosen from the list of StockStatus keys'
)
)
class StockStatusCustomSerializer(serializers.ChoiceField):
"""Serializer to allow annotating the schema to use int where custom values may be entered."""
def __init__(self, *args, **kwargs):
"""Initialize the status selector."""
if 'choices' not in kwargs:
kwargs['choices'] = stock.status_codes.StockStatus.items(custom=True)
if 'label' not in kwargs:
kwargs['label'] = _('Status')
if 'help_text' not in kwargs:
kwargs['help_text'] = _('Stock item status code')
if InvenTree.ready.isGeneratingSchema():
kwargs['help_text'] = (
kwargs['help_text']
+ '\n\n'