mirror of
https://github.com/inventree/InvenTree.git
synced 2026-11-24 16:57:30 +00:00
[Feature] Add parameters to stock location types (#13339)
* Support parameters on stock location types * Add stock location type details page * Bump API version and document location type parameters * Fix location type write queries and deletion rollback * Preserve location type names and gate parameter actions * Use standard navigation and actions for location types * Add location type preview and detail page shortcuts
This commit is contained in:
1 parent
6c5cb2910a
commit
f73208a402
19 files changed
+649
-52
No files matched your search
@@ -1,11 +1,14 @@
|
||||
"""InvenTree API version information."""
|
||||
|
||||
# InvenTree API version
|
||||
INVENTREE_API_VERSION = 582
|
||||
INVENTREE_API_VERSION = 583
|
||||
"""Increment this API version number whenever there is a significant change to the API that any clients need to know about."""
|
||||
|
||||
INVENTREE_API_TEXT = """
|
||||
|
||||
v583 -> 2026-11-20 : https://github.com/inventree/InvenTree/issues/12121
|
||||
- Adds parameter support to the StockLocationType model and API endpoints
|
||||
|
||||
v582 -> 2026-11-19 : https://github.com/inventree/InvenTree/pull/13329
|
||||
- The title tag of the part's override_min/max_currency had been moved by the API generator generating diff in the schema, no functional changes
|
||||
|
||||
|
||||
@@ -443,7 +443,7 @@ def enable_parameters_filter():
|
||||
'parameters_list',
|
||||
'parameters_list__model_type',
|
||||
'parameters_list__updated_by',
|
||||
'parameters_list__template',
|
||||
'parameters_list__template__model_type',
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ from drf_spectacular.utils import extend_schema, extend_schema_field
|
||||
from rest_framework import status
|
||||
from rest_framework.exceptions import PermissionDenied
|
||||
from rest_framework.generics import GenericAPIView
|
||||
from rest_framework.permissions import SAFE_METHODS
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.serializers import ValidationError
|
||||
|
||||
@@ -540,17 +541,43 @@ class StockLocationTree(TreeMixin, ListAPI):
|
||||
return queryset
|
||||
|
||||
|
||||
class StockLocationTypeList(ListCreateAPI):
|
||||
class StockLocationTypeOutputOptions(OutputConfiguration):
|
||||
"""Output options for the stock location type endpoints."""
|
||||
|
||||
OPTIONS = [
|
||||
InvenTreeOutputOption(
|
||||
flag='parameters', description='Include parameters for each location type'
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
class StockLocationTypeMixin:
|
||||
"""Shared configuration for the stock location type endpoints."""
|
||||
|
||||
queryset = StockLocationType.objects.all()
|
||||
serializer_class = StockSerializers.StockLocationTypeSerializer
|
||||
|
||||
def get_serializer_class(self):
|
||||
"""Include optional parameter data only on read requests."""
|
||||
request = getattr(self, 'request', None)
|
||||
if request is not None and request.method not in SAFE_METHODS:
|
||||
return StockSerializers.StockLocationTypeBriefSerializer
|
||||
return super().get_serializer_class()
|
||||
|
||||
def get_queryset(self):
|
||||
"""Include the number of locations assigned to each type."""
|
||||
return self.serializer_class.annotate_queryset(super().get_queryset())
|
||||
|
||||
|
||||
class StockLocationTypeList(StockLocationTypeMixin, OutputOptionsMixin, 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
|
||||
output_options = StockLocationTypeOutputOptions
|
||||
|
||||
ordering_fields = ['name', 'location_count', 'icon']
|
||||
|
||||
@@ -558,17 +585,10 @@ class StockLocationTypeList(ListCreateAPI):
|
||||
|
||||
search_fields = ['name', 'description']
|
||||
|
||||
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):
|
||||
class StockLocationTypeDetail(
|
||||
StockLocationTypeMixin, OutputOptionsMixin, RetrieveUpdateDestroyAPI
|
||||
):
|
||||
"""API detail endpoint for a StockLocationType object.
|
||||
|
||||
- GET: return a single StockLocationType
|
||||
@@ -577,17 +597,7 @@ class StockLocationTypeDetail(RetrieveUpdateDestroyAPI):
|
||||
- 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
|
||||
output_options = StockLocationTypeOutputOptions
|
||||
|
||||
|
||||
class StockFilter(FilterSet):
|
||||
|
||||
@@ -56,7 +56,11 @@ from users.models import Owner
|
||||
logger = structlog.get_logger('inventree')
|
||||
|
||||
|
||||
class StockLocationType(InvenTree.models.MetadataMixin, models.Model):
|
||||
class StockLocationType(
|
||||
InvenTree.models.InvenTreeParameterMixin,
|
||||
InvenTree.models.MetadataMixin,
|
||||
models.Model,
|
||||
):
|
||||
"""A type of stock location like Warehouse, room, shelf, drawer.
|
||||
|
||||
Attributes:
|
||||
@@ -82,6 +86,11 @@ class StockLocationType(InvenTree.models.MetadataMixin, models.Model):
|
||||
"""String representation of a StockLocationType."""
|
||||
return self.name
|
||||
|
||||
@transaction.atomic
|
||||
def delete(self, *args, **kwargs):
|
||||
"""Delete this type and its parameters in a single transaction."""
|
||||
super().delete(*args, **kwargs)
|
||||
|
||||
name = models.CharField(
|
||||
blank=False, max_length=100, verbose_name=_('Name'), help_text=_('Name')
|
||||
)
|
||||
|
||||
@@ -1396,8 +1396,8 @@ class StockChangeStatusSerializer(serializers.Serializer):
|
||||
item.save(add_note=False)
|
||||
|
||||
|
||||
class StockLocationTypeSerializer(InvenTree.serializers.InvenTreeModelSerializer):
|
||||
"""Serializer for StockLocationType model."""
|
||||
class StockLocationTypeBriefSerializer(InvenTree.serializers.InvenTreeModelSerializer):
|
||||
"""Serializer for location type writes and embedded stock location details."""
|
||||
|
||||
class Meta:
|
||||
"""Serializer metaclass."""
|
||||
@@ -1409,6 +1409,19 @@ class StockLocationTypeSerializer(InvenTree.serializers.InvenTreeModelSerializer
|
||||
|
||||
location_count = serializers.IntegerField(read_only=True, allow_null=True)
|
||||
|
||||
|
||||
class StockLocationTypeSerializer(
|
||||
InvenTree.serializers.FilterableSerializerMixin, StockLocationTypeBriefSerializer
|
||||
):
|
||||
"""Serializer for the location type endpoints, with optional parameter data."""
|
||||
|
||||
class Meta(StockLocationTypeBriefSerializer.Meta):
|
||||
"""Metaclass options."""
|
||||
|
||||
fields = [*StockLocationTypeBriefSerializer.Meta.fields, 'parameters']
|
||||
|
||||
parameters = common.filters.enable_parameters_filter()
|
||||
|
||||
@staticmethod
|
||||
def annotate_queryset(queryset):
|
||||
"""Add location count to each location type."""
|
||||
@@ -1556,7 +1569,7 @@ class LocationSerializer(
|
||||
icon = serializers.CharField(read_only=True)
|
||||
|
||||
# Detail for location type
|
||||
location_type_detail = StockLocationTypeSerializer(
|
||||
location_type_detail = StockLocationTypeBriefSerializer(
|
||||
source='location_type', read_only=True, allow_null=True, many=False
|
||||
)
|
||||
|
||||
|
||||
@@ -3,9 +3,11 @@
|
||||
import os
|
||||
from datetime import datetime, timedelta
|
||||
from decimal import Decimal
|
||||
from unittest.mock import patch
|
||||
|
||||
from django.contrib.contenttypes.models import ContentType
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.db.models import Model
|
||||
from django.test.utils import override_settings
|
||||
from django.urls import reverse
|
||||
|
||||
@@ -17,7 +19,13 @@ import build.models
|
||||
import company.models
|
||||
import order.models
|
||||
import part.models
|
||||
from common.models import InvenTreeCustomUserStateModel, InvenTreeSetting, Note
|
||||
from common.models import (
|
||||
InvenTreeCustomUserStateModel,
|
||||
InvenTreeSetting,
|
||||
Note,
|
||||
Parameter,
|
||||
ParameterTemplate,
|
||||
)
|
||||
from common.settings import set_global_setting
|
||||
from InvenTree.unit_test import (
|
||||
InvenTreeAPIPerformanceTestCase,
|
||||
@@ -575,6 +583,30 @@ class StockLocationTypeTest(StockAPITestCase):
|
||||
)
|
||||
self.assertEqual(StockLocationType.objects.count(), 0)
|
||||
|
||||
def test_delete_rolls_back_parameters(self):
|
||||
"""A failed location type deletion preserves its parameters and assignments."""
|
||||
location_type = StockLocationType.objects.create(name='Drawer')
|
||||
location = StockLocation.objects.create(
|
||||
name='Drawer A3', location_type=location_type
|
||||
)
|
||||
template = ParameterTemplate.objects.create(name='Internal width')
|
||||
parameter = Parameter.objects.create(
|
||||
model_type=ContentType.objects.get_for_model(StockLocationType),
|
||||
model_id=location_type.pk,
|
||||
template=template,
|
||||
data='120',
|
||||
)
|
||||
|
||||
with (
|
||||
patch.object(Model, 'delete', side_effect=RuntimeError('Delete failed')),
|
||||
self.assertRaisesMessage(RuntimeError, 'Delete failed'),
|
||||
):
|
||||
location_type.delete()
|
||||
|
||||
location.refresh_from_db()
|
||||
self.assertEqual(location.location_type_id, location_type.pk)
|
||||
self.assertTrue(Parameter.objects.filter(pk=parameter.pk).exists())
|
||||
|
||||
def test_create(self):
|
||||
"""Test that we can create a location type via API."""
|
||||
self.post(
|
||||
@@ -615,6 +647,151 @@ class StockLocationTypeTest(StockAPITestCase):
|
||||
).json()
|
||||
self.assertEqual(res['icon'], 'ti:tag:outline')
|
||||
|
||||
def test_update_does_not_load_parameters(self):
|
||||
"""Editing a location type does not query or return its parameters."""
|
||||
location_type = StockLocationType.objects.create(name='Drawer')
|
||||
url = reverse('api-location-type-detail', kwargs={'pk': location_type.pk})
|
||||
self.patch(url, {'description': 'Initial description'})
|
||||
with self.assertNumQueriesLessThan(self.MAX_QUERY_COUNT) as queries:
|
||||
self.patch(url, {'description': 'Empty drawer type'})
|
||||
|
||||
model_type = ContentType.objects.get_for_model(StockLocationType)
|
||||
for index in range(10):
|
||||
template = ParameterTemplate.objects.create(
|
||||
name=f'Width {index}', model_type=model_type
|
||||
)
|
||||
Parameter.objects.create(
|
||||
model_type=model_type,
|
||||
model_id=location_type.pk,
|
||||
template=template,
|
||||
data='120',
|
||||
updated_by=self.user,
|
||||
)
|
||||
|
||||
for suffix in ['', '?parameters=true']:
|
||||
response = self.patch(
|
||||
url + suffix,
|
||||
{'description': 'Updated drawer type'},
|
||||
max_query_count=len(queries.captured_queries) + 1,
|
||||
)
|
||||
self.assertEqual(response.data['description'], 'Updated drawer type')
|
||||
self.assertNotIn('parameters', response.data)
|
||||
|
||||
def test_parameters(self):
|
||||
"""Type parameters are opt-in and independent of location parameters."""
|
||||
location_type = StockLocationType.objects.create(name='Drawer')
|
||||
location = StockLocation.objects.create(
|
||||
name='Drawer A3', location_type=location_type
|
||||
)
|
||||
template = ParameterTemplate.objects.create(name='Internal width', units='mm')
|
||||
location_parameter = Parameter.objects.create(
|
||||
model_type=ContentType.objects.get_for_model(StockLocation),
|
||||
model_id=location.pk,
|
||||
template=template,
|
||||
data='125 mm',
|
||||
)
|
||||
parameter = self.post(
|
||||
reverse('api-parameter-list'),
|
||||
{
|
||||
'model_type': 'stock.stocklocationtype',
|
||||
'model_id': location_type.pk,
|
||||
'template': template.pk,
|
||||
'data': '120 mm',
|
||||
},
|
||||
).data
|
||||
|
||||
detail_url = reverse(
|
||||
'api-location-type-detail', kwargs={'pk': location_type.pk}
|
||||
)
|
||||
for options in [{}, {'parameters': False}]:
|
||||
self.assertNotIn('parameters', self.get(self.list_url, options).data[0])
|
||||
self.assertNotIn('parameters', self.get(detail_url, options).data)
|
||||
|
||||
options = {'parameters': True}
|
||||
for record in [
|
||||
self.get(self.list_url, options).data[0],
|
||||
self.get(detail_url, options).data,
|
||||
]:
|
||||
self.assertEqual(record['location_count'], 1)
|
||||
self.assertEqual([p['pk'] for p in record['parameters']], [parameter['pk']])
|
||||
|
||||
stock_location = self.get(
|
||||
reverse('api-location-detail', kwargs={'pk': location.pk}), options
|
||||
).data
|
||||
self.assertEqual(
|
||||
[p['pk'] for p in stock_location['parameters']], [location_parameter.pk]
|
||||
)
|
||||
self.assertNotIn('parameters', stock_location['location_type_detail'])
|
||||
|
||||
self.delete(detail_url, expected_code=204)
|
||||
location.refresh_from_db()
|
||||
self.assertIsNone(location.location_type_id)
|
||||
self.assertFalse(Parameter.objects.filter(pk=parameter['pk']).exists())
|
||||
self.assertTrue(Parameter.objects.filter(pk=location_parameter.pk).exists())
|
||||
|
||||
def test_parameter_permissions(self):
|
||||
"""Reading and changing a type's parameters uses stock location permissions."""
|
||||
location_type = StockLocationType.objects.create(name='Drawer')
|
||||
model_type = ContentType.objects.get_for_model(StockLocationType)
|
||||
template = ParameterTemplate.objects.create(
|
||||
name='Internal width', model_type=model_type
|
||||
)
|
||||
parameter = Parameter.objects.create(
|
||||
model_type=model_type,
|
||||
model_id=location_type.pk,
|
||||
template=template,
|
||||
data='120',
|
||||
)
|
||||
params = {'model_type': model_type.model, 'model_id': location_type.pk}
|
||||
parameter_list = reverse('api-parameter-list')
|
||||
type_detail = reverse(
|
||||
'api-location-type-detail', kwargs={'pk': location_type.pk}
|
||||
)
|
||||
|
||||
self.clearRoles()
|
||||
self.assertEqual(self.get(parameter_list, params).data, [])
|
||||
self.get(type_detail, {'parameters': True}, expected_code=403)
|
||||
|
||||
self.assignRole('stock_location.view')
|
||||
self.assertEqual(self.get(parameter_list, params).data[0]['pk'], parameter.pk)
|
||||
self.assertEqual(
|
||||
self.get(type_detail, {'parameters': True}).data['parameters'][0]['pk'],
|
||||
parameter.pk,
|
||||
)
|
||||
self.patch(
|
||||
reverse('api-parameter-detail', kwargs={'pk': parameter.pk}),
|
||||
{'data': '150'},
|
||||
expected_code=403,
|
||||
)
|
||||
|
||||
def test_parameters_prefetch(self):
|
||||
"""Including parameters does not add per-type or per-template queries."""
|
||||
model_type = ContentType.objects.get_for_model(StockLocationType)
|
||||
for index in range(5):
|
||||
location_type = StockLocationType.objects.create(name=f'Drawer {index}')
|
||||
template = ParameterTemplate.objects.create(
|
||||
name=f'Width {index}', model_type=model_type
|
||||
)
|
||||
Parameter.objects.create(
|
||||
model_type=model_type,
|
||||
model_id=location_type.pk,
|
||||
template=template,
|
||||
data='120',
|
||||
)
|
||||
|
||||
options = {'parameters': True, 'search': 'Drawer 0'}
|
||||
self.get(self.list_url, options)
|
||||
with self.assertNumQueriesLessThan(self.MAX_QUERY_COUNT) as queries:
|
||||
self.assertEqual(len(self.get(self.list_url, options).data), 1)
|
||||
|
||||
records = self.get(
|
||||
self.list_url,
|
||||
{'parameters': True, 'search': 'Drawer'},
|
||||
max_query_count=len(queries.captured_queries) + 1,
|
||||
).data
|
||||
self.assertEqual(len(records), 5)
|
||||
self.assertTrue(all(len(record['parameters']) == 1 for record in records))
|
||||
|
||||
|
||||
class StockItemListTest(StockAPITestCase):
|
||||
"""Tests for the StockItem API LIST endpoint."""
|
||||
|
||||
Reference in new issue
Block a user