mirror of
https://github.com/inventree/InvenTree.git
synced 2026-11-24 16:57:30 +00:00
refactor: use generic model insights for frontend features (#13072)
* feat:generic model insights inspired by https://github.com/inventree/InvenTree/pull/13069 this adds a more general approach to generic features like attachments, notes some tests and functions written with assistance of AI * lazy load panels * add pr version * fix snapshot issue * move history panel to new generic mechanism * Update api_version.py * move to generic * remove duplicate * clean up import * fix test * add ignore for broken contract in test
This commit is contained in:
1 parent
016f965ac8
commit
a87489ca44
32 files changed
+533
-477
No files matched your search
@@ -1,11 +1,14 @@
|
||||
"""InvenTree API version information."""
|
||||
|
||||
# InvenTree API version
|
||||
INVENTREE_API_VERSION = 579
|
||||
INVENTREE_API_VERSION = 580
|
||||
"""Increment this API version number whenever there is a significant change to the API that any clients need to know about."""
|
||||
|
||||
INVENTREE_API_TEXT = """
|
||||
|
||||
v580 -> 2026-11-14 : https://github.com/inventree/InvenTree/pull/13072
|
||||
- Adds feature info to contenttype endpoint
|
||||
|
||||
v579 -> 2026-11-14 : https://github.com/inventree/InvenTree/pull/13271
|
||||
- The "consumed" field on the BuildLine API is now read-only - stock must be consumed via the build order endpoints
|
||||
- The "received_date" field on the ReturnOrderLineItem API is now read-only - line items must be received via the return order "receive" endpoint
|
||||
|
||||
@@ -17,6 +17,7 @@ from allauth.socialaccount.signals import social_account_updated
|
||||
import InvenTree.conversion
|
||||
import InvenTree.ready
|
||||
import InvenTree.tasks
|
||||
from generic.modelfeatures import build_model_features_cache
|
||||
from InvenTree.config import get_setting
|
||||
from InvenTree.ready import ignore_ready_warning
|
||||
|
||||
@@ -102,6 +103,7 @@ class InvenTreeConfig(AppConfig):
|
||||
|
||||
self.update_site_url()
|
||||
self.load_unit_registry()
|
||||
build_model_features_cache()
|
||||
|
||||
if InvenTree.ready.canAppAccessDatabase() or settings.TESTING_ENV:
|
||||
self.add_user_on_startup()
|
||||
|
||||
@@ -35,6 +35,7 @@ import InvenTree.helpers
|
||||
import InvenTree.helpers_model
|
||||
import InvenTree.sentry
|
||||
import report.mixins
|
||||
from generic.modelfeatures import ModelFeatureMixin
|
||||
|
||||
logger = structlog.get_logger('inventree')
|
||||
|
||||
@@ -532,7 +533,7 @@ class InvenTreePermissionCheckMixin:
|
||||
return user.has_perm(perm)
|
||||
|
||||
|
||||
class InvenTreeAuditMixin:
|
||||
class InvenTreeAuditMixin(ModelFeatureMixin):
|
||||
"""Opt a model in to the audit log (field-level change history).
|
||||
|
||||
Any concrete model which inherits from this mixin is registered with django-auditlog
|
||||
@@ -551,6 +552,8 @@ class InvenTreeAuditMixin:
|
||||
(e.g. StockHistoryCode) - see audit.helpers.audit_event
|
||||
"""
|
||||
|
||||
MODEL_FEATURE = 'org.inventree.i.modelfeatures.history'
|
||||
|
||||
AUDIT_INCLUDE_FIELDS: tuple[str, ...] = ()
|
||||
AUDIT_EXCLUDE_FIELDS: tuple[str, ...] = ()
|
||||
AUDIT_MASK_FIELDS: tuple[str, ...] = ()
|
||||
@@ -622,13 +625,17 @@ class InvenTreeAuditMixin:
|
||||
return False
|
||||
|
||||
|
||||
class InvenTreeParameterMixin(InvenTreePermissionCheckMixin, models.Model):
|
||||
class InvenTreeParameterMixin(
|
||||
ModelFeatureMixin, InvenTreePermissionCheckMixin, models.Model
|
||||
):
|
||||
"""Provides an abstracted class for managing parameters.
|
||||
|
||||
Links the implementing model to the common.models.Parameter table,
|
||||
and provides the following methods:
|
||||
"""
|
||||
|
||||
MODEL_FEATURE = 'org.inventree.i.modelfeatures.parameters'
|
||||
|
||||
class Meta:
|
||||
"""Metaclass options for InvenTreeParameterMixin."""
|
||||
|
||||
@@ -774,13 +781,17 @@ class InvenTreeParameterMixin(InvenTreePermissionCheckMixin, models.Model):
|
||||
return True
|
||||
|
||||
|
||||
class InvenTreeNoteMixin(InvenTreePermissionCheckMixin, models.Model):
|
||||
class InvenTreeNoteMixin(
|
||||
ModelFeatureMixin, InvenTreePermissionCheckMixin, models.Model
|
||||
):
|
||||
"""Provides an abstracted class for managing notes.
|
||||
|
||||
Links the implementing model to the common.models.Note table,
|
||||
and provides multiple accessor / helper methods.
|
||||
"""
|
||||
|
||||
MODEL_FEATURE = 'org.inventree.i.modelfeatures.notes'
|
||||
|
||||
class Meta:
|
||||
"""Metaclass options for InvenTreeNoteMixin."""
|
||||
|
||||
@@ -927,7 +938,7 @@ class InvenTreeNoteMixin(InvenTreePermissionCheckMixin, models.Model):
|
||||
return True
|
||||
|
||||
|
||||
class InvenTreeAttachmentMixin(InvenTreePermissionCheckMixin):
|
||||
class InvenTreeAttachmentMixin(ModelFeatureMixin, InvenTreePermissionCheckMixin):
|
||||
"""Provides an abstracted class for managing file attachments.
|
||||
|
||||
Links the implementing model to the common.models.Attachment table,
|
||||
@@ -936,6 +947,8 @@ class InvenTreeAttachmentMixin(InvenTreePermissionCheckMixin):
|
||||
- attachments: Return a queryset containing all attachments for this model
|
||||
"""
|
||||
|
||||
MODEL_FEATURE = 'org.inventree.i.modelfeatures.attachments'
|
||||
|
||||
def delete(self, *args, **kwargs):
|
||||
"""Handle the deletion of a model instance.
|
||||
|
||||
@@ -1571,7 +1584,7 @@ class PathStringMixin(models.Model):
|
||||
]
|
||||
|
||||
|
||||
class InvenTreeTagsMixin(models.Model):
|
||||
class InvenTreeTagsMixin(ModelFeatureMixin, models.Model):
|
||||
"""A mixin class for adding tag functionality to a model class.
|
||||
|
||||
The following fields are added to any model which implements this mixin:
|
||||
@@ -1579,6 +1592,8 @@ class InvenTreeTagsMixin(models.Model):
|
||||
- tags : A text field for storing comma-separated tags
|
||||
"""
|
||||
|
||||
MODEL_FEATURE = 'org.inventree.i.modelfeatures.tags'
|
||||
|
||||
class Meta:
|
||||
"""Metaclass options for this mixin.
|
||||
|
||||
@@ -1590,7 +1605,7 @@ class InvenTreeTagsMixin(models.Model):
|
||||
tags = TaggableManager(blank=True)
|
||||
|
||||
|
||||
class InvenTreeBarcodeMixin(models.Model):
|
||||
class InvenTreeBarcodeMixin(ModelFeatureMixin, models.Model):
|
||||
"""A mixin class for adding barcode functionality to a model class.
|
||||
|
||||
Two types of barcodes are supported:
|
||||
@@ -1606,6 +1621,8 @@ class InvenTreeBarcodeMixin(models.Model):
|
||||
The barcode_model_type_code() classmethod must be implemented in the model class.
|
||||
"""
|
||||
|
||||
MODEL_FEATURE = 'org.inventree.i.modelfeatures.barcode'
|
||||
|
||||
class Meta:
|
||||
"""Metaclass options for this mixin.
|
||||
|
||||
@@ -1862,7 +1879,7 @@ def after_error_logged(sender, instance: Error, created: bool, **kwargs):
|
||||
)
|
||||
|
||||
|
||||
class InvenTreeImageMixin(models.Model):
|
||||
class InvenTreeImageMixin(ModelFeatureMixin, models.Model):
|
||||
"""A mixin class for adding image functionality to a model class.
|
||||
|
||||
The following fields are added to any model which implements this mixin:
|
||||
@@ -1870,6 +1887,8 @@ class InvenTreeImageMixin(models.Model):
|
||||
- image : An image field for storing an image
|
||||
"""
|
||||
|
||||
MODEL_FEATURE = 'org.inventree.i.modelfeatures.image'
|
||||
|
||||
IMAGE_RENAME: Callable | None = None
|
||||
|
||||
class Meta:
|
||||
|
||||
@@ -21,6 +21,7 @@ import common.filters
|
||||
import common.models as common_models
|
||||
import common.validators
|
||||
import generic.states.custom
|
||||
from generic.modelfeatures import get_model_features
|
||||
from importer.registry import register_importer
|
||||
from InvenTree.apps import DEFAULT_OIDC_APP_ID
|
||||
from InvenTree.helpers import get_objectreference
|
||||
@@ -554,7 +555,7 @@ class FlagSerializer(serializers.Serializer):
|
||||
return data
|
||||
|
||||
|
||||
class ContentTypeSerializer(serializers.Serializer):
|
||||
class ContentTypeSerializer(FilterableSerializerMixin, serializers.ModelSerializer):
|
||||
"""Serializer for ContentType models."""
|
||||
|
||||
pk = serializers.IntegerField(read_only=True)
|
||||
@@ -563,16 +564,34 @@ class ContentTypeSerializer(serializers.Serializer):
|
||||
app_labeled_name = serializers.CharField(read_only=True)
|
||||
is_plugin = serializers.SerializerMethodField('get_is_plugin', read_only=True)
|
||||
|
||||
features = OptionalField(
|
||||
serializer_class=serializers.SerializerMethodField,
|
||||
serializer_kwargs={'read_only': True},
|
||||
default_include=False,
|
||||
filter_name='features',
|
||||
)
|
||||
|
||||
class Meta:
|
||||
"""Meta options for ContentTypeSerializer."""
|
||||
|
||||
model = ContentType
|
||||
fields = ['pk', 'app_label', 'model', 'app_labeled_name', 'is_plugin']
|
||||
fields = [
|
||||
'pk',
|
||||
'app_label',
|
||||
'model',
|
||||
'app_labeled_name',
|
||||
'is_plugin',
|
||||
'features',
|
||||
]
|
||||
|
||||
def get_is_plugin(self, obj) -> bool:
|
||||
"""Return True if the model is a plugin model."""
|
||||
return obj.app_label in plugin_registry.installed_apps
|
||||
|
||||
def get_features(self, obj) -> list[str]:
|
||||
"""Return the list of generic features supported by this model type."""
|
||||
return get_model_features(obj.model_class())
|
||||
|
||||
|
||||
@register_importer()
|
||||
class CustomUnitSerializer(DataImportExportSerializerMixin, InvenTreeModelSerializer):
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
"""Generic model features package."""
|
||||
|
||||
from .func import (
|
||||
ModelFeatureMixin,
|
||||
build_model_features_cache,
|
||||
clear_model_features_cache,
|
||||
get_model_features,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
'ModelFeatureMixin',
|
||||
'build_model_features_cache',
|
||||
'clear_model_features_cache',
|
||||
'get_model_features',
|
||||
]
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Generic model features, declared by model mixin classes."""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from django.apps import apps
|
||||
|
||||
import structlog
|
||||
|
||||
logger = structlog.get_logger('inventree')
|
||||
|
||||
|
||||
class ModelFeatureMixin:
|
||||
"""Base class for mixins which provide a generic 'feature' to a model.
|
||||
|
||||
Identified with the MODEL_FEATURE attribute. Builtin start with 'org.inventree.i.modelfeatures.', do not use that space in a plugin.
|
||||
|
||||
Example:
|
||||
class MyPluginMixin(ModelFeatureMixin, models.Model):
|
||||
MODEL_FEATURE = 'com.example.myplugin.my_feature'
|
||||
"""
|
||||
|
||||
MODEL_FEATURE: Optional[str] = None
|
||||
|
||||
|
||||
_model_features_cache: Optional[dict[str, list[str]]] = None
|
||||
|
||||
|
||||
def collect_model_features(model_class):
|
||||
"""Collect the generic features declared in the class hierarchy of a model."""
|
||||
features = []
|
||||
|
||||
for base in model_class.__mro__:
|
||||
feature = base.__dict__.get('MODEL_FEATURE')
|
||||
if feature and feature not in features:
|
||||
features.append(feature)
|
||||
|
||||
return features
|
||||
|
||||
|
||||
def build_model_features_cache():
|
||||
"""Build cache of features for all registered models."""
|
||||
global _model_features_cache
|
||||
|
||||
_model_features_cache = {
|
||||
model._meta.label_lower: collect_model_features(model)
|
||||
for model in apps.get_models()
|
||||
if issubclass(model, ModelFeatureMixin)
|
||||
}
|
||||
logger.debug('Built model feature cache for %s models', len(_model_features_cache))
|
||||
return _model_features_cache
|
||||
|
||||
|
||||
def clear_model_features_cache():
|
||||
"""Clear feature cache."""
|
||||
global _model_features_cache
|
||||
_model_features_cache = None
|
||||
|
||||
|
||||
def get_model_features(model_class) -> list[str]:
|
||||
"""Return the features supported by model class."""
|
||||
if model_class is None or not issubclass(model_class, ModelFeatureMixin):
|
||||
return []
|
||||
|
||||
cache = _model_features_cache
|
||||
if cache is None:
|
||||
cache = build_model_features_cache()
|
||||
|
||||
meta = getattr(model_class, '_meta', None)
|
||||
features = cache.get(meta.label_lower) if meta else None
|
||||
|
||||
if features is None:
|
||||
# Not a registered model - e.g. an abstract class
|
||||
return collect_model_features(model_class)
|
||||
return features
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Tests for the model features functionality."""
|
||||
|
||||
from django.urls import reverse
|
||||
|
||||
from taggit.models import Tag
|
||||
|
||||
import InvenTree.models
|
||||
from InvenTree.unit_test import InvenTreeAPITestCase
|
||||
from part.models import Part
|
||||
|
||||
from . import func
|
||||
from .func import ModelFeatureMixin, clear_model_features_cache, get_model_features
|
||||
|
||||
|
||||
class ContentTypeFeatureAPITests(InvenTreeAPITestCase):
|
||||
"""Tests for the 'features' field on the ContentType API."""
|
||||
|
||||
def test_features(self):
|
||||
"""Test that the list endpoint reports features per model type."""
|
||||
url = reverse('api-contenttype-list')
|
||||
|
||||
# The 'features' field is not included by default
|
||||
data = self.get(url, expected_code=200).data
|
||||
self.assertNotIn('features', data[0])
|
||||
|
||||
data = self.get(url, {'features': True}, expected_code=200).data
|
||||
features = {item['model']: item['features'] for item in data}
|
||||
for f in ['attachments', 'notes', 'parameters', 'barcode']:
|
||||
self.assertIn(f'org.inventree.i.modelfeatures.{f}', features['part'])
|
||||
|
||||
self.assertIn(
|
||||
'org.inventree.i.modelfeatures.attachments', features['salesorder']
|
||||
)
|
||||
self.assertIn('org.inventree.i.modelfeatures.notes', features['stockitem'])
|
||||
self.assertEqual(features['contenttype'], [])
|
||||
|
||||
def test_model_features(self):
|
||||
"""Test that features are declared by the model mixins, and cached per application."""
|
||||
clear_model_features_cache()
|
||||
|
||||
features = get_model_features(Part)
|
||||
|
||||
self.assertIn('org.inventree.i.modelfeatures.attachments', features)
|
||||
self.assertIn('org.inventree.i.modelfeatures.report', features)
|
||||
|
||||
# The cache is built for all models on first access, and reused afterwards
|
||||
self.assertIsNotNone(func._model_features_cache)
|
||||
self.assertIs(features, get_model_features(Part))
|
||||
|
||||
# Clearing the cache (e.g. after a plugin reload) rebuilds it
|
||||
clear_model_features_cache()
|
||||
self.assertIsNone(func._model_features_cache)
|
||||
self.assertEqual(features, get_model_features(Part))
|
||||
self.assertIsNotNone(func._model_features_cache)
|
||||
|
||||
self.assertEqual(get_model_features(None), [])
|
||||
self.assertEqual(get_model_features(Tag), [])
|
||||
|
||||
# A custom mixin (e.g. provided by a plugin) can declare a new feature
|
||||
class CustomFeatureMixin(ModelFeatureMixin):
|
||||
MODEL_FEATURE = 'custom'
|
||||
|
||||
class CustomModel(CustomFeatureMixin, InvenTree.models.InvenTreeNoteMixin):
|
||||
class Meta:
|
||||
abstract = True
|
||||
|
||||
self.assertEqual(
|
||||
get_model_features(CustomModel),
|
||||
['custom', 'org.inventree.i.modelfeatures.notes'],
|
||||
)
|
||||
self.assertNotIn('custom', get_model_features(Part))
|
||||
@@ -30,6 +30,7 @@ import structlog
|
||||
import InvenTree.cache
|
||||
import InvenTree.ready
|
||||
from common.settings import get_global_setting, set_global_setting
|
||||
from generic.modelfeatures import clear_model_features_cache
|
||||
from InvenTree.config import get_plugin_dir
|
||||
from InvenTree.exceptions import log_error
|
||||
|
||||
@@ -1170,6 +1171,8 @@ class PluginsRegistry:
|
||||
else:
|
||||
self._try_reload(apps.set_installed_apps, loadable_apps)
|
||||
|
||||
clear_model_features_cache()
|
||||
|
||||
def _clean_installed_apps(self):
|
||||
for plugin in self.installed_apps:
|
||||
if plugin in settings.INSTALLED_APPS:
|
||||
|
||||
@@ -5,6 +5,8 @@ from typing import Generic, Optional, TypedDict, TypeVar
|
||||
|
||||
from django.db import models
|
||||
|
||||
from generic.modelfeatures import ModelFeatureMixin
|
||||
|
||||
_Model = TypeVar('_Model', bound=models.Model, covariant=True)
|
||||
|
||||
REPORT_ATTRIBUTE_MARKER = '_report_attribute_description'
|
||||
@@ -54,13 +56,15 @@ class BaseReportContext(TypedDict):
|
||||
"""Base context for a report model."""
|
||||
|
||||
|
||||
class InvenTreeReportMixin(models.Model):
|
||||
class InvenTreeReportMixin(ModelFeatureMixin, models.Model):
|
||||
"""A mixin class for adding report generation functionality to a model class.
|
||||
|
||||
In addition to exposing the model to the report generation interface,
|
||||
this mixin provides a hook for providing extra context information to the reports.
|
||||
"""
|
||||
|
||||
MODEL_FEATURE = 'org.inventree.i.modelfeatures.report'
|
||||
|
||||
class Meta:
|
||||
"""Metaclass options for this mixin."""
|
||||
|
||||
|
||||
Reference in new issue
Block a user