refactor: make locks / locked generic (#13356)

* pass ids to notes

* ammend api

* add generic model mixin

* stop editing locked notes

* make frontend generic

* add tests

* update instance info when refreshing instace info

* update test

* update test

* fix test

* fix link
This commit is contained in:
Matthias Mair authored and GitHub committed 2026-11-29 10:43:44 +11:00
1 parent 767cdc9ec1
commit 1655c1d0b3
20 files changed
+181 -88

No files matched your search

@@ -1,11 +1,14 @@
"""InvenTree API version information."""
# InvenTree API version
INVENTREE_API_VERSION = 584
INVENTREE_API_VERSION = 585
"""Increment this API version number whenever there is a significant change to the API that any clients need to know about."""
INVENTREE_API_TEXT = """
v585 -> 2026-11-23 : https://github.com/inventree/InvenTree/pull/13356
- Adds "locked" field to the instance-info API endpoint as a new generic model mixin is added for lockable models
v584 -> 2026-11-23 : https://github.com/inventree/InvenTree/pull/13346
- Adds "search_fields" query parameter to list endpoints, to limit a search to a subset of the searchable fields
- Adds "search_fields" information to the OPTIONS response for list endpoints
+23 -6
View File
@@ -546,7 +546,10 @@ class NotesImageList(ListCreateAPI):
note = serializer.validated_data['note']
common.serializers.check_note_change_permission(
self.request.user, template=note.template, model_type=note.model_type
self.request.user,
template=note.template,
model_type=note.model_type,
model_id=note.model_id,
)
serializer.save(user=self.request.user)
@@ -1106,6 +1109,7 @@ class NoteDetail(NoteMixin, RetrieveUpdateDestroyAPI):
self.request.user,
template=instance.template,
model_type=instance.model_type,
model_id=instance.model_id,
)
super().perform_destroy(instance)
@@ -1519,9 +1523,11 @@ class InstanceInfoView(APIView):
"""Return counts of attachments, notes and parameters for the given instance."""
from generic.models.modelmixins import (
InvenTreeAttachmentMixin,
InvenTreeLockableMixin,
InvenTreeNoteMixin,
InvenTreeParameterMixin,
)
from users.permissions import check_user_permission
model_type = request.query_params.get('model_type')
model_id = request.query_params.get('model_id')
@@ -1540,11 +1546,16 @@ class InstanceInfoView(APIView):
content_type = common.filters.determine_content_type(model_type)
model_class = content_type.model_class() if content_type else None
counts = {'attachment_count': 0, 'note_count': 0, 'parameter_count': 0}
data = {
'attachment_count': 0,
'note_count': 0,
'parameter_count': 0,
'locked': None,
}
if model_class:
if issubclass(model_class, InvenTreeAttachmentMixin):
counts['attachment_count'] = common.models.Attachment.objects.filter(
data['attachment_count'] = common.models.Attachment.objects.filter(
model_type=model_class.__name__.lower(), model_id=model_id
).count()
@@ -1553,7 +1564,7 @@ class InstanceInfoView(APIView):
# re-deriving the view-permission check here) so this count can
# never drift from what the Notes list endpoint actually shows.
note_list_view = NoteList(request=request, format_kwarg=None)
counts['note_count'] = (
data['note_count'] = (
note_list_view
.get_queryset()
.filter(model_type=content_type, model_id=model_id, template=False)
@@ -1561,11 +1572,17 @@ class InstanceInfoView(APIView):
)
if issubclass(model_class, InvenTreeParameterMixin):
counts['parameter_count'] = common.models.Parameter.objects.filter(
data['parameter_count'] = common.models.Parameter.objects.filter(
model_type=content_type, model_id=model_id
).count()
serializer = common.serializers.InstanceInfoSerializer(counts)
if issubclass(
model_class, InvenTreeLockableMixin
) and check_user_permission(request.user, model_class, 'view'):
mdl_cls_instance = model_class()
data['locked'] = mdl_cls_instance.check_pk_locked(model_id)
serializer = common.serializers.InstanceInfoSerializer(data)
return Response(serializer.data)
+19 -2
View File
@@ -24,6 +24,7 @@ import generic.states.custom
from generic.modelfeatures import get_model_features
from generic.models.modelmixins import (
InvenTreeAttachmentMixin,
InvenTreeLockableMixin,
InvenTreeNoteMixin,
InvenTreeParameterMixin,
)
@@ -947,7 +948,7 @@ def check_model_change_permission(
raise PermissionDenied(permission_error_msg)
def check_note_change_permission(user, *, template, model_type):
def check_note_change_permission(user, *, template, model_type, model_id=None):
"""Check whether a user is permitted to create, edit or delete a note.
Shared between NoteSerializer.save() (create/update) and NoteDetail's
@@ -973,6 +974,13 @@ def check_note_change_permission(user, *, template, model_type):
_('User does not have permission to create or edit notes for this model'),
)
if issubclass(target_model_class, InvenTreeLockableMixin) and (
target_model_class.check_pk_locked(model_id)
):
raise PermissionDenied(
_('Notes cannot be changed, as the linked item is locked')
)
class NoteSerializer(FilterableSerializerMixin, InvenTreeModelSerializer):
"""Serializer for the Note model."""
@@ -1033,7 +1041,12 @@ class NoteSerializer(FilterableSerializerMixin, InvenTreeModelSerializer):
self.instance and self.instance.model_type
)
check_note_change_permission(user, template=is_template, model_type=model_type)
model_id = self.validated_data.get(
'model_id', getattr(self.instance, 'model_id', None)
)
check_note_change_permission(
user, template=is_template, model_type=model_type, model_id=model_id
)
return super().save(updated_by=user, **kwargs)
@@ -1359,6 +1372,10 @@ class InstanceInfoSerializer(serializers.Serializer):
read_only=True,
)
locked = serializers.BooleanField(
label=_('Locked'), read_only=True, allow_null=True
)
class OAuth2ApplicationSerializer(serializers.ModelSerializer):
"""Serializer for OAuth2 application records."""
+25
View File
@@ -1593,6 +1593,31 @@ class NoteAPITests(InvenTreeAPITestCase):
self.assertTrue(Note.objects.filter(pk=note.pk).exists())
self.assertEqual(len(attempts), 1)
def test_locked_instance(self):
"""Notes cannot be changed while the linked instance is locked."""
self.assignRole('part.view')
self.assignRole('part.change')
info = {'model_type': 'part', 'model_id': self.part.pk}
note = self._create_note('Note').data
url = self._note_url(note['pk'])
self.part.locked = True
self.part.save()
# Part locking is disabled - part is not locked
set_global_setting('PART_ENABLE_LOCKING', False)
self.assertFalse(self.get(reverse('api-instance-info'), info).data['locked'])
self.patch(url, {'title': 'Edited'}, expected_code=200)
# Part locking is enabled - part is locked
set_global_setting('PART_ENABLE_LOCKING', True)
self.assertTrue(self.get(reverse('api-instance-info'), info).data['locked'])
self._create_note('Another', expected_code=403)
self.patch(url, {'title': 'Edited again'}, expected_code=403)
self.delete(url, expected_code=403)
self.get(url, expected_code=200)
class NoteModelTypeValidationTests(InvenTreeAPITestCase):
"""Tests that Note.model_type is restricted to models which support notes.
@@ -659,6 +659,42 @@ class InvenTreeParameterMixin(
return True
class InvenTreeLockableMixin(ModelFeatureMixin):
"""Mixin for models which can be 'locked'.
A model declares its locking rule by overriding check_locked().
"""
MODEL_FEATURE = 'org.inventree.i.modelfeatures.lockable'
def check_locked(self, db: bool = False) -> bool:
"""Return True if this instance is locked."""
return False
@classmethod
def check_pk_locked(cls, pk) -> bool:
"""Return True if the instance with the given primary key exists and is locked."""
if pk is None:
return False
instance = cls.objects.filter(pk=pk).first()
return bool(instance and instance.check_locked())
# overrides of parameter checks for lockable models
def check_parameter_delete(self, parameter) -> bool:
"""Run a check to determine if the provided parameter can be deleted."""
if self.check_locked():
raise ValidationError(_('Cannot delete parameters of a locked item'))
return super().check_parameter_delete(parameter)
def check_parameter_save(self, parameter) -> bool:
"""Run a check to determine if the provided parameter can be saved."""
if self.check_locked():
raise ValidationError(_('Cannot modify parameters of a locked item'))
return super().check_parameter_save(parameter)
class InvenTreeNoteMixin(
ModelFeatureMixin, InvenTreePermissionCheckMixin, models.Model
):
+2
View File
@@ -55,6 +55,7 @@ from generic.models.modelmixins import (
InvenTreeAttachmentMixin,
InvenTreeAuditMixin,
InvenTreeBarcodeMixin,
InvenTreeLockableMixin,
InvenTreeNoteMixin,
InvenTreeParameterMixin,
InvenTreeReferenceIndexingMixin,
@@ -364,6 +365,7 @@ class TransferOrderReportContext(BaseOrderReportContext, TypedDict):
class Order(
InvenTreeLockableMixin,
StatusCodeMixin,
StateTransitionMixin,
InvenTreeParameterMixin,
+9 -12
View File
@@ -51,6 +51,7 @@ from generic.models.modelmixins import (
InvenTreeAuditMixin,
InvenTreeBarcodeMixin,
InvenTreeImageMixin,
InvenTreeLockableMixin,
InvenTreeMetadataMixin,
InvenTreeNoteMixin,
InvenTreeParameterMixin,
@@ -474,6 +475,7 @@ class PartReportContext(report.mixins.BaseReportContext, TypedDict):
@cleanup.ignore
class Part(
InvenTreeLockableMixin,
InvenTreeAuditMixin,
InvenTreePluginValidationMixin,
InvenTreeParameterMixin,
@@ -596,15 +598,10 @@ class Part(
'test_templates': self.getTestTemplateMap(),
}
def check_parameter_delete(self, parameter):
"""Custom delete check for Parameter instances associated with this Part."""
if self.locked and get_global_setting('PART_ENABLE_LOCKING'):
raise ValidationError(_('Cannot delete parameters of a locked part'))
def check_parameter_save(self, parameter):
"""Custom save check for Parameter instances associated with this Part."""
if self.locked and get_global_setting('PART_ENABLE_LOCKING'):
raise ValidationError(_('Cannot modify parameters of a locked part'))
def check_locked(self, db: bool = False) -> bool:
"""Check if this part is 'locked' (and part locking is enabled)."""
instance = (self.get_db_instance() if db else None) or self
return bool(instance.locked and get_global_setting('PART_ENABLE_LOCKING'))
def delete(self, **kwargs):
"""Custom delete method for the Part model.
@@ -628,7 +625,7 @@ class Part(
Raises:
ValidationError: If the part cannot be deleted
"""
if self.locked and get_global_setting('PART_ENABLE_LOCKING'):
if self.check_locked():
raise ValidationError(_('Cannot delete this part as it is locked'))
if self.active:
@@ -3201,13 +3198,13 @@ class BomItem(InvenTreeAuditMixin, InvenTreeMetadataModel):
if not get_global_setting('PART_ENABLE_LOCKING'):
return
if assembly.locked:
if assembly.check_locked():
raise ValidationError(_('BOM item cannot be modified - assembly is locked'))
# If this BOM item is inherited, check all variants of the assembly
if self.inherited:
for part in assembly.get_descendants(include_self=False):
if part.locked:
if part.check_locked():
raise ValidationError(
_('BOM item cannot be modified - variant assembly is locked')
)
+2 -1
View File
@@ -10,5 +10,6 @@ export enum ModelFeature {
image = 'org.inventree.i.modelfeatures.image',
report = 'org.inventree.i.modelfeatures.report',
label = 'org.inventree.i.modelfeatures.label', // for now this is frontend only for overrides
history = 'org.inventree.i.modelfeatures.history'
history = 'org.inventree.i.modelfeatures.history',
lockable = 'org.inventree.i.modelfeatures.lockable'
}
+2 -2
View File
@@ -26,12 +26,12 @@ export type PanelType = {
*
* @param model - The model type (e.g. 'part', or a plugin defined model)
* @param id - The primary key of the model instance
* @param instanceInfo - Aggregated counts for the instance (e.g. attachment_count)
* @param instanceInfo - Aggregated counts and states for the instance
*/
export type ModelFeaturePanelProps = {
model: string;
id: number;
instanceInfo: Record<string, number | undefined>;
instanceInfo: Record<string, (number | boolean) | undefined>;
userSettings: SettingsStateProps;
globalSettings: SettingsStateProps;
};
@@ -68,6 +68,7 @@ import {
EditItemAction,
OptionsActionDropdown
} from '../items/ActionDropdown';
import { LockedItemMessage } from '../items/LockedItemMessage';
import { RenderUser } from '../render/User';
function NoteInfoHover({ note }: { note: any }) {
@@ -108,11 +109,13 @@ export default function NotesEditor({
modelType,
modelId,
templateMode = false,
locked = false,
setDirtyCallback
}: Readonly<{
modelType?: ModelType;
modelId?: number;
templateMode?: boolean;
locked?: boolean;
setDirtyCallback?: (dirty: boolean) => void;
}>) {
const api = useApi();
@@ -267,14 +270,14 @@ export default function NotesEditor({
if (templateMode) {
return user.isStaff();
}
if (!modelType) {
if (!modelType || locked) {
return false;
}
return action === 'change'
? user.hasChangePermission(modelType)
: user.hasDeletePermission(modelType);
},
[user, modelType, templateMode]
[user, modelType, templateMode, locked]
);
const canEdit: boolean = useMemo(
@@ -447,6 +450,7 @@ export default function NotesEditor({
<Flex align='left' gap={5}>
<Box style={{ flex: 1 }}>
<Stack gap={5}>
{locked && !templateMode && <LockedItemMessage />}
{selectedNote && (
<Paper p='xs' shadow='sm' withBorder>
<Group justify='space-between'>
@@ -0,0 +1,11 @@
import { t } from '@lingui/core/macro';
import { Alert } from '@mantine/core';
import { IconLock } from '@tabler/icons-react';
export function LockedItemMessage() {
return (
<Alert color='yellow' icon={<IconLock />}>
{t`This item is locked`}
</Alert>
);
}
@@ -14,7 +14,8 @@ export const ModelFeaturePanelLookup: Record<string, ModelFeaturePanelFactory> =
return ParametersPanel({
model_type: model as ModelType,
model_id: id,
parameter_count: instanceInfo.parameter_count
parameter_count: instanceInfo.parameter_count as number,
locked: instanceInfo.locked as boolean
});
},
[ModelFeature.attachments]: async ({ model, id, instanceInfo }) => {
@@ -22,7 +23,7 @@ export const ModelFeaturePanelLookup: Record<string, ModelFeaturePanelFactory> =
return AttachmentPanel({
model_type: model as ModelType,
model_id: id,
attachment_count: instanceInfo.attachment_count
attachment_count: instanceInfo.attachment_count as number
});
},
[ModelFeature.notes]: async ({ model, id, instanceInfo }) => {
@@ -30,7 +31,8 @@ export const ModelFeaturePanelLookup: Record<string, ModelFeaturePanelFactory> =
return NotesPanel({
model_type: model as ModelType,
model_id: id,
note_count: instanceInfo.note_count
note_count: instanceInfo.note_count as number,
locked: instanceInfo.locked as boolean
});
},
[ModelFeature.history]: async ({
@@ -11,12 +11,12 @@ import NotesEditor from '../editors/NotesEditor';
export default function NotesPanel({
model_type,
model_id,
editable,
locked,
note_count
}: {
model_type: ModelType;
model_id: number | undefined;
editable?: boolean;
locked?: boolean;
note_count?: number;
}): PanelType {
return {
@@ -27,7 +27,11 @@ export default function NotesPanel({
notification_dot: note_count ? 'info' : null,
content:
model_type && model_id ? (
<NotesEditor modelType={model_type} modelId={model_id} />
<NotesEditor
modelType={model_type}
modelId={model_id}
locked={locked}
/>
) : (
<Skeleton />
),
@@ -1,21 +1,24 @@
import type { ModelType } from '@lib/enums/ModelType';
import type { PanelType } from '@lib/types/Panel';
import { t } from '@lingui/core/macro';
import { Skeleton } from '@mantine/core';
import { Skeleton, Stack } from '@mantine/core';
import { IconListDetails } from '@tabler/icons-react';
import { ParameterTable } from '../../tables/general/ParameterTable';
import { LockedItemMessage } from '../items/LockedItemMessage';
export default function ParametersPanel({
model_type,
model_id,
hidden,
allowEdit = true,
locked = false,
parameter_count
}: {
model_type: ModelType;
model_id: number | undefined;
hidden?: boolean;
allowEdit?: boolean;
locked?: boolean;
parameter_count?: number;
}): PanelType {
return {
@@ -27,11 +30,14 @@ export default function ParametersPanel({
notification_dot: parameter_count ? 'info' : null,
content:
model_type && model_id ? (
<ParameterTable
allowEdit={allowEdit}
modelType={model_type}
modelId={model_id}
/>
<Stack gap='xs'>
{locked && <LockedItemMessage />}
<ParameterTable
allowEdit={allowEdit && !locked}
modelType={model_type}
modelId={model_id}
/>
</Stack>
) : (
<Skeleton />
)
+8 -1
View File
@@ -1,6 +1,6 @@
import { apiUrl } from '@lib/functions/Api';
import type { UseInstanceResult, useInstanceProps } from '@lib/types/Rendering';
import { useQuery } from '@tanstack/react-query';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useCallback, useMemo, useState } from 'react';
import { useApi } from '../contexts/ApiContext';
@@ -27,6 +27,7 @@ export function useInstance<T = any>({
updateInterval
}: useInstanceProps): UseInstanceResult {
const api = useApi();
const queryClient = useQueryClient();
const [instance, setInstance] = useState<T | undefined>(defaultValue);
@@ -95,11 +96,17 @@ export function useInstance<T = any>({
);
}, [instanceQuery]);
const refetechInfo = useCallback(() => {
queryClient.invalidateQueries({ queryKey: ['instance-info'] });
}, [queryClient]);
const refreshInstance = useCallback(() => {
refetechInfo();
instanceQuery.refetch();
}, []);
const refreshInstancePromise = useCallback(() => {
refetechInfo();
return instanceQuery.refetch();
}, []);
+3 -1
View File
@@ -8,12 +8,14 @@ export interface InstanceInfo {
attachment_count: number;
note_count: number;
parameter_count: number;
locked: boolean;
}
const emptyInstanceInfo: InstanceInfo = {
attachment_count: 0,
note_count: 0,
parameter_count: 0
parameter_count: 0,
locked: false
};
/**
+3 -36
View File
@@ -20,7 +20,6 @@ import {
IconExclamationCircle,
IconInfoCircle,
IconLayersLinked,
IconListDetails,
IconListTree,
IconLock,
IconLockOpen,
@@ -85,7 +84,6 @@ import { useUserState } from '../../states/UserState';
import { BomTable } from '../../tables/bom/BomTable';
import { UsedInTable } from '../../tables/bom/UsedInTable';
import { BuildOrderTable } from '../../tables/build/BuildOrderTable';
import { ParameterTable } from '../../tables/general/ParameterTable';
import PartPurchaseOrdersTable from '../../tables/part/PartPurchaseOrdersTable';
import PartSalesOrdersTable from '../../tables/part/PartSalesOrdersTable';
import PartTestResultTable from '../../tables/part/PartTestResultTable';
@@ -349,10 +347,7 @@ export default function PartDetail() {
<Text>{t`The Bill of Materials for this assembly has not been validated.`}</Text>
</Alert>
)}
<BomTable
partId={part.pk ?? -1}
partLocked={part?.locked == true}
/>
<BomTable partId={part.pk ?? -1} partLocked={instanceInfo.locked} />
</Stack>
) : (
<Skeleton />
@@ -456,9 +451,7 @@ export default function PartDetail() {
content: part?.pk ? (
<PartTestTemplateTable
partId={part?.pk}
partLocked={
globalSettings.isSet('PART_ENABLE_LOCKING') && part?.locked
}
partLocked={instanceInfo.locked}
/>
) : (
<Skeleton />
@@ -480,32 +473,6 @@ export default function PartDetail() {
label: t`Related Parts`,
icon: <IconLayersLinked />,
content: <RelatedPartTable partId={part.pk} />
},
// TODO: remove this panel once generic model locking is available
{
name: 'parameters',
label: t`Parameters`,
icon: <IconListDetails />,
notification_dot: instanceInfo.parameter_count ? 'info' : null,
content: (
<>
{lockingEnabled && part.locked && (
<Alert
title={t`Part is Locked`}
color='orange'
icon={<IconLock />}
p='xs'
>
<Text>{t`Part parameters cannot be edited, as the part is locked`}</Text>
</Alert>
)}
<ParameterTable
modelType={ModelType.part}
modelId={part?.pk}
allowEdit={!lockingEnabled || part?.locked != true}
/>
</>
)
}
];
}, [
@@ -813,7 +780,7 @@ export default function PartDetail() {
variant='transparent'
disabled={!user.hasChangeRole(UserRoles.part)}
onClick={() => {
const locking = !part.locked;
const locking = instanceInfo.locked;
api
.patch(apiUrl(ApiEndpoints.part_list, part.pk), {
locked: locking
+2 -10
View File
@@ -58,10 +58,7 @@ import {
useEditApiFormModal
} from '../../hooks/UseForm';
import { useImporterState } from '../../states/ImporterState';
import {
useGlobalSettingsState,
useUserSettingsState
} from '../../states/SettingsStates';
import { useUserSettingsState } from '../../states/SettingsStates';
import { useUserState } from '../../states/UserState';
// Calculate the total stock quantity available for a given BomItem
@@ -125,12 +122,7 @@ export function BomTable({
const [isEditing, setIsEditing] = useState<boolean>(false);
const globalSettings = useGlobalSettingsState();
const isLocked = useMemo(
() => globalSettings.isSet('PART_ENABLE_LOCKING') && (partLocked ?? false),
[globalSettings, partLocked]
);
const isLocked = partLocked ?? false;
const userSettings = useUserSettingsState();
+1 -1
View File
@@ -659,7 +659,7 @@ test('Parts - Locking', async ({ browser }) => {
// Check the "parameters" tab also
await loadTab(page, 'Parameters');
await page.getByText('Part parameters cannot be').waitFor();
await page.getByText('This item is locked').waitFor();
});
test('Parts - Details', async ({ browser }) => {
@@ -86,7 +86,7 @@ test('Purchasing - Index', async ({ browser }) => {
test('Purchasing - Parameters', async ({ browser }) => {
const page = await doCachedLogin(browser, {
url: 'purchasing/purchase-order/11/parameters',
url: 'purchasing/purchase-order/12/parameters',
user: stevenuser
});