From f73208a402706e950eeeaea5acedc92df7616f07 Mon Sep 17 00:00:00 2001 From: Miguel Brandt Date: Sat, 21 Nov 2026 19:50:41 -0300 Subject: [PATCH] [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 --- CHANGELOG.md | 2 + docs/docs/stock/index.md | 4 +- .../InvenTree/InvenTree/api_version.py | 5 +- src/backend/InvenTree/common/filters.py | 2 +- src/backend/InvenTree/stock/api.py | 60 +++--- src/backend/InvenTree/stock/models.py | 11 +- src/backend/InvenTree/stock/serializers.py | 19 +- src/backend/InvenTree/stock/test_api.py | 179 +++++++++++++++++- src/frontend/lib/enums/ModelInformation.tsx | 2 + .../components/previews/ModelPreviewShim.ts | 2 + .../models/StockLocationTypePreview.tsx | 16 ++ src/frontend/src/forms/StockForms.tsx | 10 + .../src/pages/stock/LocationTypeDetail.tsx | 142 ++++++++++++++ .../pages/stock/LocationTypeDetailsPanel.tsx | 22 +++ .../pages/stock/StockLocationDetailsPanel.tsx | 27 ++- src/frontend/src/router.tsx | 4 + .../src/tables/general/ParameterTable.tsx | 5 +- .../src/tables/stock/LocationTypesTable.tsx | 18 +- src/frontend/tests/pages/pui_stock.spec.ts | 171 ++++++++++++++++- 19 files changed, 649 insertions(+), 52 deletions(-) create mode 100644 src/frontend/src/components/previews/models/StockLocationTypePreview.tsx create mode 100644 src/frontend/src/pages/stock/LocationTypeDetail.tsx create mode 100644 src/frontend/src/pages/stock/LocationTypeDetailsPanel.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index fb7870ab2b..ff498b4c9a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- [#12121](https://github.com/inventree/InvenTree/issues/12121) adds support for custom parameters on stock location types. + - [#13266](https://github.com/inventree/InvenTree/pull/13266) Adds a "Manufacturer Barcode" plugin, which provides fallback barcode matching against manufacturer part numbers, and a `BARCODE_PRIORITY` attribute which controls the order in which barcode plugins are queried. - [#13208](https://github.com/inventree/InvenTree/pull/13208) Shows the consuming build order in the stock item Child Items table, which includes consumed children by default for users without saved filters. diff --git a/docs/docs/stock/index.md b/docs/docs/stock/index.md index 12916fd9fd..9593697e0e 100644 --- a/docs/docs/stock/index.md +++ b/docs/docs/stock/index.md @@ -62,7 +62,9 @@ If there are some icons missing in the tabler icons package, users can even inst ## Stock Location Type -A stock location type represents a specific type of location (e.g. one specific size of drawer, shelf, ... or box) which can be assigned to multiple stock locations. In the first place, it is used to specify an icon and having the icon in sync for all locations that use this location type, but it also serves as a data field to quickly see what type of location this is. It is planned to add e.g. drawer dimension information to the location type to add a "find a matching, empty stock location" tool. +A stock location type describes a kind of location, such as a drawer, shelf, or box. Multiple stock locations can share a type and use its default icon. + +Open a type from **Admin Center → Location Types** or from the **Location Type** link in a stock location's details. Use the **Parameters** tab to record shared properties such as the internal dimensions of a drawer. Values are stored on the type, so you can update them in one place. Individual locations can also have their own parameters. ## External Stock Location diff --git a/src/backend/InvenTree/InvenTree/api_version.py b/src/backend/InvenTree/InvenTree/api_version.py index 4e3daf267c..fbffb2d1a8 100644 --- a/src/backend/InvenTree/InvenTree/api_version.py +++ b/src/backend/InvenTree/InvenTree/api_version.py @@ -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 diff --git a/src/backend/InvenTree/common/filters.py b/src/backend/InvenTree/common/filters.py index 7f7938d4bd..52a3f46c8a 100644 --- a/src/backend/InvenTree/common/filters.py +++ b/src/backend/InvenTree/common/filters.py @@ -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', ], ) diff --git a/src/backend/InvenTree/stock/api.py b/src/backend/InvenTree/stock/api.py index cb50498f0d..2a23349299 100644 --- a/src/backend/InvenTree/stock/api.py +++ b/src/backend/InvenTree/stock/api.py @@ -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): diff --git a/src/backend/InvenTree/stock/models.py b/src/backend/InvenTree/stock/models.py index af894af38f..be7f7dbfc5 100644 --- a/src/backend/InvenTree/stock/models.py +++ b/src/backend/InvenTree/stock/models.py @@ -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') ) diff --git a/src/backend/InvenTree/stock/serializers.py b/src/backend/InvenTree/stock/serializers.py index 27d7a0468d..1fd387ca23 100644 --- a/src/backend/InvenTree/stock/serializers.py +++ b/src/backend/InvenTree/stock/serializers.py @@ -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 ) diff --git a/src/backend/InvenTree/stock/test_api.py b/src/backend/InvenTree/stock/test_api.py index c701b28476..bb2b58c641 100644 --- a/src/backend/InvenTree/stock/test_api.py +++ b/src/backend/InvenTree/stock/test_api.py @@ -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.""" diff --git a/src/frontend/lib/enums/ModelInformation.tsx b/src/frontend/lib/enums/ModelInformation.tsx index 7e2aebbd60..6bdacb643b 100644 --- a/src/frontend/lib/enums/ModelInformation.tsx +++ b/src/frontend/lib/enums/ModelInformation.tsx @@ -145,7 +145,9 @@ export const ModelInformationDict: ModelDict = { stocklocationtype: { label: () => t`Stock Location Type`, label_multiple: () => t`Stock Location Types`, + url_detail: '/stock/location-type/:pk/', api_endpoint: ApiEndpoints.stock_location_type_list, + admin_url: '/stock/stocklocationtype/', icon: 'location' }, stockhistory: { diff --git a/src/frontend/src/components/previews/ModelPreviewShim.ts b/src/frontend/src/components/previews/ModelPreviewShim.ts index de643ab544..999d25c184 100644 --- a/src/frontend/src/components/previews/ModelPreviewShim.ts +++ b/src/frontend/src/components/previews/ModelPreviewShim.ts @@ -9,6 +9,7 @@ import { ReturnOrderPreviewComponent } from './models/ReturnOrderPreview'; import { SalesOrderPreviewComponent } from './models/SalesOrderPreview'; import { SalesOrderShipmentPreviewComponent } from './models/SalesOrderShipmentPreview'; import { StockLocationPreviewComponent } from './models/StockLocationPreview'; +import { StockLocationTypePreviewComponent } from './models/StockLocationTypePreview'; import { StockPreviewComponent } from './models/StockPreview'; import { SupplierPartPreviewComponent } from './models/SupplierPartPreview'; import { TransferOrderPreviewComponent } from './models/TransferOrderPreview'; @@ -20,6 +21,7 @@ registerModelPreviews({ partcategory: PartCategoryPreviewComponent, stockitem: StockPreviewComponent, stocklocation: StockLocationPreviewComponent, + stocklocationtype: StockLocationTypePreviewComponent, build: BuildOrderPreviewComponent, company: CompanyPreviewComponent, purchaseorder: PurchaseOrderPreviewComponent, diff --git a/src/frontend/src/components/previews/models/StockLocationTypePreview.tsx b/src/frontend/src/components/previews/models/StockLocationTypePreview.tsx new file mode 100644 index 0000000000..b606ef9cc6 --- /dev/null +++ b/src/frontend/src/components/previews/models/StockLocationTypePreview.tsx @@ -0,0 +1,16 @@ +import type { PreviewType } from '@lib/types/Preview'; +import { t } from '@lingui/core/macro'; +import { LocationTypeDetailsPanel } from '../../../pages/stock/LocationTypeDetailsPanel'; + +export function StockLocationTypePreviewComponent({ + instance, + modelId +}: Readonly<{ + instance: any; + modelId: number; +}>): PreviewType { + return { + title: `${t`Stock Location Type`} - ${instance?.name ?? `#${modelId}`}`, + preview: + }; +} diff --git a/src/frontend/src/forms/StockForms.tsx b/src/frontend/src/forms/StockForms.tsx index 10d1788389..ebf88454ec 100644 --- a/src/frontend/src/forms/StockForms.tsx +++ b/src/frontend/src/forms/StockForms.tsx @@ -2211,6 +2211,16 @@ export function useStockLocationFields(): ApiFormFieldSet { return fields; } +export function getStockLocationTypeFields(): ApiFormFieldSet { + return { + name: {}, + description: {}, + icon: { + field_type: 'icon' + } + }; +} + // Construct a set of fields for export function useTestResultFields({ partId, diff --git a/src/frontend/src/pages/stock/LocationTypeDetail.tsx b/src/frontend/src/pages/stock/LocationTypeDetail.tsx new file mode 100644 index 0000000000..44e233944b --- /dev/null +++ b/src/frontend/src/pages/stock/LocationTypeDetail.tsx @@ -0,0 +1,142 @@ +import { ApiEndpoints } from '@lib/enums/ApiEndpoints'; +import { ModelType } from '@lib/enums/ModelType'; +import { getDetailUrl, getOverviewUrl } from '@lib/functions/Navigation'; +import type { PanelType } from '@lib/types/Panel'; +import { t } from '@lingui/core/macro'; +import { Stack } from '@mantine/core'; +import { IconInfoCircle } from '@tabler/icons-react'; +import { useMemo } from 'react'; +import { useNavigate, useParams } from 'react-router-dom'; +import AdminButton from '../../components/buttons/AdminButton'; +import { + DeleteItemAction, + EditItemAction, + OptionsActionDropdown +} from '../../components/items/ActionDropdown'; +import { ApiIcon } from '../../components/items/ApiIcon'; +import InstanceDetail from '../../components/nav/InstanceDetail'; +import { PageDetail } from '../../components/nav/PageDetail'; +import { PanelGroup } from '../../components/panels/PanelGroup'; +import { getStockLocationTypeFields } from '../../forms/StockForms'; +import { + useDeleteApiFormModal, + useEditApiFormModal +} from '../../hooks/UseForm'; +import { useInstance } from '../../hooks/UseInstance'; +import { useUserState } from '../../states/UserState'; +import { LocationTypeDetailsPanel } from './LocationTypeDetailsPanel'; + +export default function LocationTypeDetail() { + const { id } = useParams(); + const navigate = useNavigate(); + const isStaff = useUserState((state) => state.isStaff()); + const canEdit = useUserState((state) => + state.hasChangePermission(ModelType.stocklocationtype) + ); + const canDelete = useUserState((state) => + state.hasDeletePermission(ModelType.stocklocationtype) + ); + const stockOverviewUrl = getOverviewUrl(ModelType.stocklocation); + const locationTypesUrl = '/settings/admin/location-types'; + const { + instance: locationType, + instanceQuery, + refreshInstance + } = useInstance({ + endpoint: ApiEndpoints.stock_location_type_list, + pk: id + }); + + const editLocationType = useEditApiFormModal({ + url: ApiEndpoints.stock_location_type_list, + pk: id, + title: t`Edit Location Type`, + fields: useMemo(getStockLocationTypeFields, []), + onFormSuccess: refreshInstance + }); + + const deleteLocationType = useDeleteApiFormModal({ + url: ApiEndpoints.stock_location_type_list, + pk: id, + title: t`Delete Location Type`, + onFormSuccess: () => + navigate(isStaff ? locationTypesUrl : stockOverviewUrl, { replace: true }) + }); + + const panels = useMemo( + () => [ + { + name: 'details', + label: t`Details`, + icon: , + content: + } + ], + [locationType] + ); + + return ( + + {editLocationType.modal} + {deleteLocationType.modal} + + } + editAction={editLocationType.open} + editEnabled={canEdit} + actions={[ + , + + ]} + breadcrumbs={[ + { name: t`Stock`, url: stockOverviewUrl }, + ...(isStaff + ? [ + { + name: t`Location Types`, + url: locationTypesUrl + } + ] + : []) + ]} + lastCrumb={[ + { + name: locationType.name, + url: getDetailUrl(ModelType.stocklocationtype, locationType.pk) + } + ]} + /> + + + + ); +} diff --git a/src/frontend/src/pages/stock/LocationTypeDetailsPanel.tsx b/src/frontend/src/pages/stock/LocationTypeDetailsPanel.tsx new file mode 100644 index 0000000000..a8dd22e236 --- /dev/null +++ b/src/frontend/src/pages/stock/LocationTypeDetailsPanel.tsx @@ -0,0 +1,22 @@ +import { t } from '@lingui/core/macro'; +import { DetailsTable } from '../../components/details/Details'; + +export function LocationTypeDetailsPanel({ + instance +}: Readonly<{ instance: any }>) { + return ( + + ); +} diff --git a/src/frontend/src/pages/stock/StockLocationDetailsPanel.tsx b/src/frontend/src/pages/stock/StockLocationDetailsPanel.tsx index 8907d5af35..af34e23f80 100644 --- a/src/frontend/src/pages/stock/StockLocationDetailsPanel.tsx +++ b/src/frontend/src/pages/stock/StockLocationDetailsPanel.tsx @@ -1,18 +1,26 @@ import { t } from '@lingui/core/macro'; -import { Group, Skeleton } from '@mantine/core'; +import { Anchor, Group, Skeleton } from '@mantine/core'; import { ModelType } from '@lib/enums/ModelType'; +import { getDetailUrl } from '@lib/functions/Navigation'; +import { Link } from 'react-router-dom'; import type { DetailsField } from '../../components/details/Details'; import { ItemDetailsGrid } from '../../components/details/ItemDetails'; import { useParameterDetailsGrid } from '../../components/details/ParameterDetailsGrid'; import { ApiIcon } from '../../components/items/ApiIcon'; +import { useUserState } from '../../states/UserState'; export function StockLocationDetailsPanel({ instance }: Readonly<{ instance: any; }>) { + const locationTypeName = instance?.location_type_detail?.name; + const canViewLocationType = useUserState((state) => + state.hasViewPermission(ModelType.stocklocationtype) + ); + const left: DetailsField[] = [ { type: 'text', @@ -92,7 +100,22 @@ export function StockLocationDetailsPanel({ name: 'location_type_detail.name', label: t`Location Type`, hidden: !instance?.location_type, - icon: 'packages' + icon: 'packages', + value_formatter: + canViewLocationType && locationTypeName + ? () => ( + + {locationTypeName} + + ) + : undefined } ]; diff --git a/src/frontend/src/router.tsx b/src/frontend/src/router.tsx index ad17df8a19..3c7248d0f0 100644 --- a/src/frontend/src/router.tsx +++ b/src/frontend/src/router.tsx @@ -53,6 +53,9 @@ export const PartDetail = Loadable( export const LocationDetail = Loadable( lazy(() => import('./pages/stock/LocationDetail')) ); +export const LocationTypeDetail = Loadable( + lazy(() => import('./pages/stock/LocationTypeDetail')) +); export const StockDetail = Loadable( lazy(() => import('./pages/stock/StockDetail')) @@ -187,6 +190,7 @@ export const routes = ( } /> } /> + } /> } /> } /> diff --git a/src/frontend/src/tables/general/ParameterTable.tsx b/src/frontend/src/tables/general/ParameterTable.tsx index 4acc4022d4..ed2f0ca7ae 100644 --- a/src/frontend/src/tables/general/ParameterTable.tsx +++ b/src/frontend/src/tables/general/ParameterTable.tsx @@ -46,6 +46,7 @@ export function ParameterTable({ }) { const table = useTable('parameters'); const user = useUserState(); + const canDelete = allowEdit && user.hasDeletePermission(modelType); const tableColumns: TableColumn[] = useMemo(() => { return [ @@ -248,8 +249,8 @@ export function ParameterTable({ columns={tableColumns} props={{ enableDownload: true, - enableBulkDelete: allowEdit != false, - enableSelection: allowEdit != false, + enableBulkDelete: canDelete, + enableSelection: canDelete, rowActions: allowEdit == false ? undefined : rowActions, tableActions: allowEdit == false ? undefined : tableActions, tableFilters: tableFilters, diff --git a/src/frontend/src/tables/stock/LocationTypesTable.tsx b/src/frontend/src/tables/stock/LocationTypesTable.tsx index 88d2e67d78..ebf48d67d1 100644 --- a/src/frontend/src/tables/stock/LocationTypesTable.tsx +++ b/src/frontend/src/tables/stock/LocationTypesTable.tsx @@ -8,14 +8,15 @@ import { RowEditAction } from '@lib/components/RowActions'; import { ApiEndpoints } from '@lib/enums/ApiEndpoints'; +import { ModelType } from '@lib/enums/ModelType'; import { UserRoles } from '@lib/enums/Roles'; import { apiUrl } from '@lib/functions/Api'; import useTable from '@lib/hooks/UseTable'; -import type { ApiFormFieldSet } from '@lib/types/Forms'; import type { TableColumn } from '@lib/types/Tables'; import { ApiIcon } from '../../components/items/ApiIcon'; import { DescriptionColumn } from '../../components/tables/ColumnRenderers'; import { InvenTreeTable } from '../../components/tables/InvenTreeTable'; +import { getStockLocationTypeFields } from '../../forms/StockForms'; import { useCreateApiFormModal, useDeleteApiFormModal, @@ -27,22 +28,12 @@ export default function LocationTypesTable() { const table = useTable('location-types'); const user = useUserState(); - const formFields: ApiFormFieldSet = useMemo(() => { - return { - name: {}, - description: {}, - icon: { - field_type: 'icon' - } - }; - }, []); - const [selectedLocationType, setSelectedLocationType] = useState(0); const newLocationType = useCreateApiFormModal({ url: ApiEndpoints.stock_location_type_list, title: t`Add Location Type`, - fields: useMemo(() => ({ ...formFields }), [formFields]), + fields: useMemo(getStockLocationTypeFields, []), onFormSuccess: table.refreshTable }); @@ -50,7 +41,7 @@ export default function LocationTypesTable() { url: ApiEndpoints.stock_location_type_list, pk: selectedLocationType, title: t`Edit Location Type`, - fields: useMemo(() => ({ ...formFields }), [formFields]), + fields: useMemo(getStockLocationTypeFields, []), onFormSuccess: (record: any) => table.updateRecord(record) }); @@ -125,6 +116,7 @@ export default function LocationTypesTable() { tableState={table} columns={tableColumns} props={{ + modelType: ModelType.stocklocationtype, rowActions: rowActions, tableActions: tableActions }} diff --git a/src/frontend/tests/pages/pui_stock.spec.ts b/src/frontend/tests/pages/pui_stock.spec.ts index 72cfdd04a6..1d1d124a87 100644 --- a/src/frontend/tests/pages/pui_stock.spec.ts +++ b/src/frontend/tests/pages/pui_stock.spec.ts @@ -1,12 +1,14 @@ +import { createApi } from '../api'; import { expect, test } from '../baseFixtures.js'; -import { adminuser, stevenuser } from '../defaults.js'; +import { adminuser, readeruser, stevenuser } from '../defaults.js'; import { clearTableFilters, clickButtonIfVisible, loadTab, navigate, openFilterDrawer, - setTableChoiceFilter + setTableChoiceFilter, + tableSearch } from '../helpers.js'; import { doCachedLogin } from '../login.js'; @@ -89,6 +91,171 @@ test('Stock - Location Tree', async ({ browser }) => { await page.getByText('Storage Room B').first().waitFor(); }); +test('Stock - Location Type Parameters', async ({ browser }) => { + const api = await createApi({}); + const suffix = Date.now(); + const typePrefix = `Small Drawer - ${suffix}`; + const typeName = `${typePrefix} for electronics assembly workbench storage, 120 mm wide and 200 mm deep`; + const typeDescription = `Drawer for electronics storage ${suffix}`; + const updatedDescription = `Drawer for sensitive electronics ${suffix}`; + const templateName = `Internal Width ${suffix}`; + const typeActions = 'action-menu-location-type-actions'; + const adminAction = 'action-button-open-in-admin-interface'; + const locationTypesPage = 'settings/admin/location-types'; + let typeId: number | undefined; + let locationId: number | undefined; + let templateId: number | undefined; + + try { + const typeResponse = await api.post('stock/location-type/', { + data: { name: typeName, description: typeDescription } + }); + await expect(typeResponse).toBeOK(); + typeId = (await typeResponse.json()).pk; + + const locationResponse = await api.post('stock/location/', { + data: { name: `Drawer ${suffix}`, location_type: typeId } + }); + await expect(locationResponse).toBeOK(); + locationId = (await locationResponse.json()).pk; + + const templateResponse = await api.post('parameter/template/', { + data: { + name: templateName, + model_type: 'stock.stocklocationtype', + units: 'mm' + } + }); + await expect(templateResponse).toBeOK(); + templateId = (await templateResponse.json()).pk; + + const page = await doCachedLogin(browser, { user: adminuser }); + let previewEnabled = true; + await page.route('**/api/settings/user/', async (route) => { + const response = await route.fetch(); + const settings: { key: string; value: unknown }[] = await response.json(); + const overrides: Record = { + ENABLE_PREVIEW_PANEL: previewEnabled, + ENABLE_LAST_BREADCRUMB: true + }; + + await route.fulfill({ + response, + json: settings.map((setting) => + setting.key in overrides + ? { ...setting, value: overrides[setting.key] } + : setting + ) + }); + }); + await navigate(page, locationTypesPage); + await tableSearch(page, typePrefix); + const typeCell = page.getByRole('cell', { + name: typeDescription, + exact: true + }); + await typeCell.click(); + const preview = page.getByRole('dialog', { + name: `details-stocklocationtype-${typeId}` + }); + await expect( + preview.getByText(typeDescription, { exact: true }) + ).toBeVisible(); + await preview + .getByRole('link', { name: `details-stocklocationtype-${typeId}` }) + .click(); + const detailUrl = new RegExp(`/stock/location-type/${typeId}/`); + await expect(page).toHaveURL(detailUrl); + + previewEnabled = false; + await navigate(page, locationTypesPage); + await tableSearch(page, typePrefix); + await typeCell.click(); + await expect(page).toHaveURL(detailUrl); + await loadTab(page, 'Details'); + await expect( + page.getByTestId('breadcrumb-list').getByText(typeName, { exact: true }) + ).toBeVisible(); + await expect(page.getByRole('button', { name: adminAction })).toBeVisible(); + + const actionsMenu = page.getByRole('button', { name: typeActions }); + await actionsMenu.click(); + await page.getByRole('menuitem', { name: `${typeActions}-edit` }).click(); + const description = page.getByRole('textbox', { + name: 'text-field-description' + }); + await expect(description).toHaveValue(typeDescription); + await description.fill(updatedDescription); + await page.getByRole('button', { name: 'Submit' }).click(); + await expect( + page.getByText(updatedDescription, { exact: true }) + ).toBeVisible(); + + await loadTab(page, 'Parameters'); + + await page + .getByRole('button', { name: 'action-menu-add-parameters' }) + .click(); + await page + .getByRole('menuitem', { + name: 'action-menu-add-parameters-create-parameter' + }) + .click(); + await page + .getByRole('combobox', { name: 'related-field-template' }) + .fill(templateName); + await page.getByRole('option', { name: templateName }).click(); + await page.getByRole('textbox', { name: 'text-field-data' }).fill('120 mm'); + await page.getByRole('button', { name: 'Submit' }).click(); + await expect( + page.getByRole('cell', { name: '120 mm', exact: true }) + ).toBeVisible(); + const bulkDeleteButton = 'action-button-delete-selected-records'; + await expect( + page.getByRole('button', { name: bulkDeleteButton }) + ).toBeVisible(); + + const reader = await doCachedLogin(browser, { + user: readeruser, + url: `stock/location/${locationId}/details` + }); + await reader.getByRole('link', { name: typeName, exact: true }).click(); + await loadTab(reader, 'Parameters'); + await expect(reader.getByRole('button', { name: adminAction })).toHaveCount( + 0 + ); + await expect(reader.getByRole('button', { name: typeActions })).toHaveCount( + 0 + ); + await expect( + reader.getByRole('cell', { name: '120 mm', exact: true }) + ).toBeVisible(); + await expect( + reader.getByRole('button', { name: bulkDeleteButton }) + ).toHaveCount(0); + await expect(reader.getByLabel('Select all records')).toHaveCount(0); + + await actionsMenu.click(); + await page.getByRole('menuitem', { name: `${typeActions}-delete` }).click(); + await page.getByRole('button', { name: 'Delete', exact: true }).click(); + await expect(page).toHaveURL(/\/settings\/admin\/location-types\/?$/); + const remainingLocation = await api.get(`stock/location/${locationId}/`); + await expect(remainingLocation).toBeOK(); + expect((await remainingLocation.json()).location_type).toBeNull(); + typeId = undefined; + } finally { + if (locationId) { + const response = await api.delete(`stock/location/${locationId}/`, { + data: { delete_stock_items: false, delete_sub_locations: false } + }); + await expect.soft(response).toBeOK(); + } + if (typeId) await api.delete(`stock/location-type/${typeId}/`); + if (templateId) await api.delete(`parameter/template/${templateId}/`); + await api.dispose(); + } +}); + test('Stock - Location Delete', async ({ browser }) => { const page = await doCachedLogin(browser, { url: 'stock/location/38/sublocations'