From afc88f56e8f0e3547deac972c7bde93906cdbfb6 Mon Sep 17 00:00:00 2001 From: Matthias Mair Date: Sun, 22 Nov 2026 23:44:54 +0100 Subject: [PATCH] refactor(backend): move mixins to generic (#13293) * move mixins to generic * fix imports * fix import * move InvenTreePermissionCheckMixin * move base models * move InvenTreeAuditMixin * move PathStringMixin * move ContentTypeMixin * move MetadataMixin, PluginValidationMixin * move ReferenceIndexingMixin * fix import paths * update doc paths * fix imports * internalize diff base * add legacy imports * rename metadata mixin * rename PathStringMixin * rename PluginValidationMixin * rename ReferenceIndexingMixin * add changelog entry * document base clases * add docs for model mixins * add the rest of doc strings --- CHANGELOG.md | 1 + docs/docs/plugins/mixins/barcode.md | 2 +- docs/docs/plugins/models.md | 68 +- src/backend/InvenTree/InvenTree/filters.py | 2 +- .../commands/export_audited_models.py | 2 +- src/backend/InvenTree/InvenTree/models.py | 1833 +---------------- src/backend/InvenTree/InvenTree/tasks.py | 7 +- src/backend/InvenTree/InvenTree/tests.py | 2 +- src/backend/InvenTree/audit/registry.py | 2 +- src/backend/InvenTree/build/models.py | 37 +- src/backend/InvenTree/common/api.py | 8 +- ..._squashed_0039_emailthread_emailmessage.py | 11 +- .../0040_parametertemplate_parameter.py | 12 +- .../InvenTree/common/migrations/0050_note.py | 7 +- src/backend/InvenTree/common/models.py | 61 +- src/backend/InvenTree/common/serializers.py | 8 +- src/backend/InvenTree/common/validators.py | 24 +- .../migrations/0076_alter_company_image.py | 4 +- src/backend/InvenTree/company/models.py | 64 +- .../InvenTree/generic/modelfeatures/tests.py | 4 +- src/backend/InvenTree/generic/models/base.py | 394 ++++ .../InvenTree/generic/models/internal.py | 91 + .../InvenTree/generic/models/modelmixins.py | 1347 ++++++++++++ .../order/migrations/0118_transferorder.py | 16 +- src/backend/InvenTree/order/models.py | 47 +- .../part/migrations/0143_alter_part_image.py | 4 +- src/backend/InvenTree/part/models.py | 62 +- .../InvenTree/plugin/base/barcodes/helper.py | 2 +- .../InvenTree/plugin/base/barcodes/mixins.py | 2 +- .../builtin/barcodes/inventree_barcode.py | 2 +- .../builtin/exporter/parameter_exporter.py | 4 +- src/backend/InvenTree/plugin/models.py | 4 +- src/backend/InvenTree/pricing/models.py | 12 +- .../report/migrations/0022_reporttemplate.py | 5 +- .../report/migrations/0025_labeltemplate.py | 5 +- src/backend/InvenTree/report/models.py | 7 +- .../migrations/0036_stockitemattachment.py | 1 - src/backend/InvenTree/stock/models.py | 48 +- src/backend/InvenTree/users/models.py | 8 +- 39 files changed, 2172 insertions(+), 2048 deletions(-) create mode 100644 src/backend/InvenTree/generic/models/base.py create mode 100644 src/backend/InvenTree/generic/models/internal.py create mode 100644 src/backend/InvenTree/generic/models/modelmixins.py diff --git a/CHANGELOG.md b/CHANGELOG.md index ff498b4c9a..32774e2965 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Breaking Changes - [#13271](https://github.com/inventree/InvenTree/pull/13271) makes a number of API fields read-only, as they are managed by dedicated endpoints and must not be edited directly: `consumed` (BuildLine), `received_date` (ReturnOrderLineItem), `barcode_hash` (ManufacturerPart, SalesOrderShipment), `issue_date` (SalesOrder, ReturnOrder, TransferOrder) and `complete_date` (ReturnOrder, TransferOrder). Values provided for these fields are now ignored. +- [#13293](https://github.com/inventree/InvenTree/pull/13293) moves various (internal) model base classes, if your plugin uses InvenTree base classes update your imports from InvenTree.models to generic.models before the next major release. ### Added diff --git a/docs/docs/plugins/mixins/barcode.md b/docs/docs/plugins/mixins/barcode.md index 8ff4a3eca9..8b1176237d 100644 --- a/docs/docs/plugins/mixins/barcode.md +++ b/docs/docs/plugins/mixins/barcode.md @@ -86,7 +86,7 @@ To try it just copy the file to src/InvenTree/plugins and restart the server. Op To implement a custom internal barcode format, the `generate(...)` method from the Barcode Mixin needs to be overridden. Then the plugin can be selected at `System Settings > Barcodes > Barcode Generation Plugin`. ```python -from InvenTree.models import InvenTreeBarcodeMixin +from generic.models.modelmixins import InvenTreeBarcodeMixin from plugin import InvenTreePlugin from plugin.mixins import BarcodeMixin diff --git a/docs/docs/plugins/models.md b/docs/docs/plugins/models.md index 6a6d8f26dd..af4f617af8 100644 --- a/docs/docs/plugins/models.md +++ b/docs/docs/plugins/models.md @@ -23,14 +23,78 @@ This configuration ensures that Django recognizes the plugin as a valid applicat ## Base classes -A typical Django model class is based on `django.db.models.Model`, which provides the core functionality for defining database models in Django. Alternatively, `InvenTree.models.InvenTreeModel` comes with a few additional core integrations (content type association, [plugin validation](./mixins/validation.md)) or `InvenTree.models.InvenTreeMetadataModel` which also includes [model metadata](./metadata.md) support for the model instances. +A typical Django model class is based on `django.db.models.Model`, which provides the core functionality for defining database models in Django. + + +Alternatively, `generic.models.base`contains a few base classes that plugins can also use. + +### InvenTreeModel + +Add support for content type association and [plugin validation](./mixins/validation.md). + +### InvenTreeMetadataModel + +Adds everything in InvenTreeModel, and adds support for [model metadata](./metadata.md). + +### InvenTreeTree + +For Tree models using django-mptt for hierarchies, also include content type association. ## Generic Model Mixins -### MetadataMixin +Most common mechanisms contained in InvenTree's own models are exposed in the `generic.models` module as a set of mixins that often also have detection for frontend components to provide functions automatically. + +### InvenTreeAttachmentMixin + +Adds support for use of [generic attachments](../concepts/attachments.md) with a models instances. + + +### InvenTreeAuditMixin + +Adds support for [audit tracking](../concepts/audit.md) of model instances, including API and user interface generation. + +### InvenTreeBarcodeMixin + +Adds fields and functions for linking a [barcode](../barcodes/index.md) against model instances including lookup, assignment, and validation of barcodes against the API. + +### InvenTreeImageMixin + +Adds a `image` field to the model and automatic thumbnail generation for the uploaded images. This image can also be referenced in [reports](../report/report.md). + +You must define a constant `IMAGE_RENAME` on the model class pointing to the function in your model that handles renaming uploaded images. + +### InvenTreeMetadataMixin Adds support for [model metadata](./metadata.md) support, allowing additional information to be attached to model instances. This metadata can be accessed and manipulated through the InvenTree API or by other plugins. +### InvenTreeNoteMixin + +Adds support for defining and managing [notes](../concepts/notes.md) against model instances. + ### InvenTreeParameterMixin Adds support for [parameters](../concepts/parameters.md), allowing your models to use the parameter mechanism including proper permission checks and integration with the InvenTree API. + + +### InvenTreePathStringMixin + +Adds a number of fields to support having hierarchical path strings persisted on model instances automatically. Used by parts and stock item. + +!!! warning "Warning" + Use only after understanding the added computational and database load overhead. + + +### InvenTreePluginValidationMixin + +Adds functions that extend save and delete operations of the model to call [plugins for validation](./mixins/validation.md) before committing changes to the database. + +### InvenTreeReferenceIndexingMixin + + +Adds support for generating, validating and parsing [instance references](../settings/reference.md). Also adds a `reference_int` field that stores a converted value for the reference for use in ordering and indexing operations. + +An optional constant `REFERENCE_PATTERN_SETTING` on the model class can be pointed to a settings name that will be used to control the [reference pattern](../settings/reference.md). + +### InvenTreeTagsMixin + +Adds the required mechanism for defining [tags](../concepts/tags.md) for model instances. diff --git a/src/backend/InvenTree/InvenTree/filters.py b/src/backend/InvenTree/InvenTree/filters.py index 0e175849ab..51e9063b95 100644 --- a/src/backend/InvenTree/InvenTree/filters.py +++ b/src/backend/InvenTree/InvenTree/filters.py @@ -37,7 +37,7 @@ class InvenTreeSearchFilter(filters.SearchFilter): - search_notes: If True, 'notes' is added to the search_fields if it isn't already present - search_regex: If True, search is performed on 'regex' comparison """ - from InvenTree.models import InvenTreeNoteMixin + from generic.models.modelmixins import InvenTreeNoteMixin # Set (and read, in filter_queryset) on self rather than returned some other # way, since get_search_fields() only returns the field list, not the diff --git a/src/backend/InvenTree/InvenTree/management/commands/export_audited_models.py b/src/backend/InvenTree/InvenTree/management/commands/export_audited_models.py index 3ea70841ab..58364790da 100644 --- a/src/backend/InvenTree/InvenTree/management/commands/export_audited_models.py +++ b/src/backend/InvenTree/InvenTree/management/commands/export_audited_models.py @@ -42,7 +42,7 @@ def audit_parent(model) -> tuple[str, str]: - If the parent is a foreign key field, the name of the related model is returned - If the parent reference is resolved by a custom method, the method docstring summary is returned as a note """ - from InvenTree.models import InvenTreeAuditMixin + from generic.models.modelmixins import InvenTreeAuditMixin if model.AUDIT_PARENT_FIELD: field = model._meta.get_field(model.AUDIT_PARENT_FIELD) diff --git a/src/backend/InvenTree/InvenTree/models.py b/src/backend/InvenTree/InvenTree/models.py index 42706cd070..88d336978b 100644 --- a/src/backend/InvenTree/InvenTree/models.py +++ b/src/backend/InvenTree/InvenTree/models.py @@ -1,20 +1,9 @@ """Generic models which provide extra functionality over base Django model types.""" -from collections.abc import Callable -from datetime import datetime -from string import Formatter -from typing import Any, Optional - from django.contrib.auth import get_user_model -from django.contrib.contenttypes.fields import GenericRelation -from django.contrib.contenttypes.models import ContentType -from django.core.exceptions import ValidationError -from django.db import models, transaction -from django.db.models import QuerySet from django.db.models.signals import post_save -from django.db.transaction import TransactionManagementError from django.dispatch import receiver -from django.urls import resolve, reverse +from django.urls import reverse from django.urls.exceptions import NoReverseMatch from django.utils.translation import gettext_lazy as _ @@ -22,1738 +11,40 @@ import structlog from django_q.models import Task from django_q.signals import post_execute from error_report.models import Error -from mptt.exceptions import InvalidMove -from mptt.models import MPTTModel, TreeForeignKey -from rest_framework.exceptions import PermissionDenied -from stdimage.models import StdImageField -from taggit.managers import TaggableManager -import common.settings -import InvenTree.exceptions -import InvenTree.format -import InvenTree.helpers import InvenTree.helpers_model -import InvenTree.sentry -import report.mixins -from generic.modelfeatures import ModelFeatureMixin + +# legacy imports +from generic.models.base import ( # noqa: F401 + InvenTreeMetadataModel, + InvenTreeModel, + InvenTreeTree, +) +from generic.models.modelmixins import ( # noqa: F401 + InvenTreeAttachmentMixin, + InvenTreeAuditMixin, + InvenTreeBarcodeMixin, + InvenTreeImageMixin, + InvenTreeNoteMixin, + InvenTreeParameterMixin, + InvenTreeTagsMixin, +) +from generic.models.modelmixins import ( + InvenTreeMetadataMixin as MetadataMixin, # noqa: F401 +) +from generic.models.modelmixins import ( + InvenTreePathStringMixin as PathStringMixin, # noqa: F401 +) +from generic.models.modelmixins import ( + InvenTreePluginValidationMixin as PluginValidationMixin, # noqa: F401 +) +from generic.models.modelmixins import ( + InvenTreeReferenceIndexingMixin as ReferenceIndexingMixin, # noqa: F401 +) logger = structlog.get_logger('inventree') -class DiffMixin: - """Mixin which can be used to determine which fields have changed, compared to the instance saved to the database.""" - - def get_db_instance(self): - """Return the instance of the object saved in the database. - - Returns: - object: Instance of the object saved in the database - """ - if self.pk: - try: - return self.__class__.objects.get(pk=self.pk) - except self.__class__.DoesNotExist: - pass - - return None - - def get_field_deltas(self): - """Return a dict of field deltas. - - Compares the current instance with the instance saved in the database, - and returns a dict of fields which have changed. - - Returns: - dict: Dict of field deltas - """ - db_instance = self.get_db_instance() - - if db_instance is None: - return {} - - deltas = {} - - for field in self._meta.fields: - if field.name == 'id': - continue - - if field.is_relation: - # Compare the raw FK id first (no query) - only dereference to the - # full related object (one query each side) if it actually differs. - # In the common case (unchanged FK) this avoids two full-object - # fetches per relational field for every single save() call. - if getattr(self, field.attname) == getattr(db_instance, field.attname): - continue - - if getattr(self, field.name) != getattr(db_instance, field.name): - deltas[field.name] = { - 'old': getattr(db_instance, field.name), - 'new': getattr(self, field.name), - } - - return deltas - - def has_field_changed(self, field_name): - """Determine if a particular field has changed.""" - return field_name in self.get_field_deltas() - - -class PluginValidationMixin(DiffMixin): - """Mixin class which exposes the model instance to plugin validation. - - Any model class which inherits from this mixin will be exposed to the plugin validation system. - """ - - def should_plugin_validate(self): - """Return True if this model instance should be validated by plugins. - - The default implementation returns True, but this can be overridden in the implementing class if required. - """ - from InvenTree.ready import isReadOnlyCommand - - # Prevent plugin validation when importing or exporting data - return not isReadOnlyCommand() - - def run_plugin_validation(self): - """Throw this model against the plugin validation interface.""" - from plugin import PluginMixinEnum, registry - - if not self.should_plugin_validate(): - return - - deltas = self.get_field_deltas() - - for plugin in registry.with_mixin(PluginMixinEnum.VALIDATION): - try: - if plugin.validate_model_instance(self, deltas=deltas) is True: - return - except ValidationError as exc: - raise exc - except Exception: - # Log the exception to the database - import InvenTree.exceptions - - InvenTree.exceptions.log_error( - 'validate_model_instance', plugin=plugin.slug - ) - raise ValidationError(_('Error running plugin validation')) - - def full_clean(self, *args, **kwargs): - """Run plugin validation on full model clean. - - Note that plugin validation is performed *after* super.full_clean() - """ - super().full_clean(*args, **kwargs) - self.run_plugin_validation() - - def save(self, *args, **kwargs): - """Run plugin validation on model save. - - Note that plugin validation is performed *before* super.save() - """ - self.run_plugin_validation() - super().save(*args, **kwargs) - - def delete(self, *args, **kwargs): - """Run plugin validation on model delete. - - Allows plugins to prevent model instances from being deleted. - - Note: Each plugin may raise a ValidationError to prevent deletion. - """ - from InvenTree.exceptions import log_error - from plugin import PluginMixinEnum, registry - - if self.should_plugin_validate(): - for plugin in registry.with_mixin(PluginMixinEnum.VALIDATION): - try: - plugin.validate_model_deletion(self) - except ValidationError as e: - # Plugin might raise a ValidationError to prevent deletion - raise e - except Exception: - log_error('validate_model_deletion', plugin=plugin.slug) - continue - - super().delete(*args, **kwargs) - - -class MetadataMixin(models.Model): - """Model mixin class which adds a JSON metadata field to a model, for use by any (and all) plugins. - - The intent of this mixin is to provide a metadata field on a model instance, - for plugins to read / modify as required, to store any extra information. - - The assumptions for models implementing this mixin are: - - - The internal InvenTree business logic will make no use of this field - - Multiple plugins may read / write to this metadata field, and not assume they have sole rights - """ - - class Meta: - """Meta for MetadataMixin.""" - - abstract = True - - def save(self, force_insert=False, force_update=False, *args, **kwargs): - """Save the model instance, and perform validation on the metadata field.""" - self.validate_metadata() - if len(args) > 0: - raise TypeError( - 'save() takes no positional arguments anymore' - ) # pragma: no cover - super().save(force_insert=force_insert, force_update=force_update, **kwargs) - - def clean(self, *args, **kwargs): - """Perform model validation on the metadata field.""" - super().clean() - - self.validate_metadata() - - def validate_metadata(self): - """Validate the metadata field.""" - # Ensure that the 'metadata' field is a valid dict object - if self.metadata is None: - self.metadata = {} - - if type(self.metadata) is not dict: - raise ValidationError({ - 'metadata': _('Metadata must be a python dict object') - }) - - metadata = models.JSONField( - blank=True, - null=True, - verbose_name=_('Plugin Metadata'), - help_text=_('JSON metadata field, for use by external plugins'), - ) - - def get_metadata(self, key: str, backup_value=None): - """Finds metadata for this model instance, using the provided key for lookup. - - Args: - key: String key for requesting metadata. e.g. if a plugin is accessing the metadata, the plugin slug should be used - backup_value: Value that should be used if no value is found - - Returns: - Python dict object containing requested metadata. If no matching metadata is found, returns None - """ - if self.metadata is None: - return backup_value - - return self.metadata.get(key, backup_value) - - def set_metadata( - self, key: str, data, commit: bool = True, overwrite: bool = False - ): - """Save the provided metadata under the provided key. - - Args: - key (str): Key for saving metadata - data (Any): Data object to save - must be able to be rendered as a JSON string - commit (bool, optional): If true, existing metadata with the provided key will be overwritten. If false, a merge will be attempted. Defaults to True. - overwrite (bool): If true, delete existing metadata before adding new value - """ - if overwrite or self.metadata is None: - self.metadata = {} - - self.metadata[key] = data - - if commit: - self.save() - - -class ReferenceIndexingMixin(models.Model): - """A mixin for keeping track of numerical copies of the "reference" field. - - Here, we attempt to convert a "reference" field value (char) to an integer, - for performing fast natural sorting. - - This requires extra database space (due to the extra table column), - but is required as not all supported database backends provide equivalent casting. - - This mixin adds a field named 'reference_int'. - - - If the 'reference' field can be cast to an integer, it is stored here - - If the 'reference' field *starts* with an integer, it is stored here - - Otherwise, we store zero - """ - - # Name of the global setting which defines the required reference pattern for this model - REFERENCE_PATTERN_SETTING = None - - class Meta: - """Metaclass options. Abstract ensures no database table is created.""" - - abstract = True - - @classmethod - def get_reference_pattern(cls): - """Returns the reference pattern associated with this model. - - This is defined by a global setting object, specified by the REFERENCE_PATTERN_SETTING attribute - """ - # By default, we return an empty string - if cls.REFERENCE_PATTERN_SETTING is None: - return '' - - return common.settings.get_global_setting( - cls.REFERENCE_PATTERN_SETTING, create=False - ).strip() - - @classmethod - def get_reference_context(cls): - """Generate context data for generating the 'reference' field for this class. - - - Returns a python dict object which contains the context data for formatting the reference string. - - The default implementation provides some default context information - - The '?' key is required to accept our wildcard-with-default syntax {?:default} - """ - return {'ref': cls.get_next_reference(), 'date': datetime.now(), '?': '?'} - - @classmethod - def get_most_recent_item(cls): - """Return the item which is 'most recent'. - - In practice, this means the item with the highest reference value - """ - query = cls.objects.all().order_by('-reference_int', '-pk') - - if query.exists(): - return query.first() - return None - - @classmethod - def get_next_reference(cls): - """Return the next available reference value for this particular class.""" - # Find the "most recent" item - latest = cls.get_most_recent_item() - - if not latest: - # No existing items - return 1 - - reference = latest.reference.strip() - - try: - reference = InvenTree.format.extract_named_group( - 'ref', reference, cls.get_reference_pattern() - ) - except Exception: - # If reference cannot be extracted using the pattern, try just the integer value - reference = str(latest.reference_int) - - # Attempt to perform 'intelligent' incrementing of the reference field - incremented = InvenTree.helpers.increment(reference) - - try: - incremented = int(incremented) - except ValueError: - pass - - return incremented - - @classmethod - def generate_reference(cls): - """Generate the next 'reference' field based on specified pattern.""" - - # Based on https://stackoverflow.com/a/57570269/14488558 - class ReferenceFormatter(Formatter): - def format_field(self, value, format_spec): - if isinstance(value, str) and value == '?': - value = format_spec - format_spec = '' - return super().format_field(value, format_spec) - - ref_ptn = cls.get_reference_pattern() - ctx = cls.get_reference_context() - fmt = ReferenceFormatter() - - reference = None - - attempts = set() - - while reference is None: - try: - ref = fmt.format(ref_ptn, **ctx) - - if ref in attempts: - # We are stuck in a loop! - reference = ref - break - else: - attempts.add(ref) - - if cls.objects.filter(reference=ref).exists(): - # Handle case where we have duplicated an existing reference - ctx['ref'] = InvenTree.helpers.increment(ctx['ref']) - else: - # We have found an 'unused' reference - reference = ref - break - - except Exception: - # If anything goes wrong, return the most recent reference - recent = cls.get_most_recent_item() - reference = recent.reference if recent else '' - - return reference - - @classmethod - def validate_reference_pattern(cls, pattern): - """Ensure that the provided pattern is valid.""" - ctx = cls.get_reference_context() - - try: - info = InvenTree.format.parse_format_string(pattern) - except Exception as exc: - raise ValidationError({ - 'value': _('Improperly formatted pattern') + ': ' + str(exc) - }) - - # Check that only 'allowed' keys are provided - for key in info: - if key not in ctx: - raise ValidationError({ - 'value': _('Unknown format key specified') + f": '{key}'" - }) - - # Check that the 'ref' variable is specified - if 'ref' not in info: - raise ValidationError({ - 'value': _('Missing required format key') + ": 'ref'" - }) - - @classmethod - def validate_reference_field(cls, value): - """Check that the provided 'reference' value matches the requisite pattern.""" - pattern = cls.get_reference_pattern() - - value = str(value).strip() - - if len(value) == 0: - raise ValidationError(_('Reference field cannot be empty')) - - # An 'empty' pattern means no further validation is required - if not pattern: - return - - if not InvenTree.format.validate_string(value, pattern): - raise ValidationError( - _('Reference must match required pattern') + ': ' + pattern - ) - - # Check that the reference field can be rebuild - return cls.rebuild_reference_field(value, validate=True) - - @classmethod - def rebuild_reference_field(cls, reference, validate=False): - """Extract integer out of reference for sorting. - - If the 'integer' portion is buried somewhere 'within' the reference, - we can first try to extract it using the pattern. - - Example: - reference - BO-123-ABC - pattern - BO-{ref}-??? - extracted - 123 - - If we cannot extract using the pattern for some reason, fallback to the entire reference - """ - try: - # Extract named group based on provided pattern - reference = InvenTree.format.extract_named_group( - 'ref', reference, cls.get_reference_pattern() - ) - except Exception: - pass - - reference_int = InvenTree.helpers.extract_int(reference) - - if validate and reference_int > models.BigIntegerField.MAX_BIGINT: - raise ValidationError({'reference': _('Reference number is too large')}) - - return reference_int - - reference_int = models.BigIntegerField(default=0) - - -class ContentTypeMixin: - """Mixin class which supports retrieval of the ContentType for a model instance.""" - - @classmethod - def get_content_type(cls): - """Return the ContentType object associated with this model.""" - from django.contrib.contenttypes.models import ContentType - - return ContentType.objects.get_for_model(cls) - - -class InvenTreeModel(ContentTypeMixin, PluginValidationMixin, models.Model): - """Base class for InvenTree models, which provides some common functionality. - - Includes the following mixins by default: - - - PluginValidationMixin: Provides a hook for plugins to validate model instances - """ - - class Meta: - """Metaclass options.""" - - abstract = True - - -class InvenTreeMetadataModel(MetadataMixin, InvenTreeModel): - """Base class for an InvenTree model which includes a metadata field.""" - - class Meta: - """Metaclass options.""" - - abstract = True - - -class InvenTreePermissionCheckMixin: - """Provides an abstracted class for managing permissions against related fields.""" - - @classmethod - def check_related_permission(cls, permission, user) -> bool: - """Check if the user has permission to perform the specified action on the attachment. - - The default implementation runs a permission check against *this* model class, - but this can be overridden in the implementing class if required. - - Arguments: - permission: The permission to check (add / change / view / delete) - user: The user to check against - - Returns: - bool: True if the user has permission, False otherwise - """ - perm = f'{cls._meta.app_label}.{permission}_{cls._meta.model_name}' - return user.has_perm(perm) - - -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 - when the 'audit' app is loaded (see audit.registry). - - Attributes: - AUDIT_INCLUDE_FIELDS: If specified, *only* these fields are recorded (e.g. user-editable fields of a cache model) - AUDIT_EXCLUDE_FIELDS: Fields which are never recorded (merged with a base set, see audit.registry) - AUDIT_MASK_FIELDS: Fields whose values are masked (the change is recorded, the value is not) - AUDIT_M2M_FIELDS: Many-to-many fields which are tracked - AUDIT_PARENT_FIELD: Name of the field which links to the "parent" object (e.g. 'order' for a line item) - AUDIT_VIEW_RESTRICTION: Restrict reading audit history to 'staff' or 'superuser' users (or None) - AUDIT_REQUIRE_PARENT_PERMISSION: Entries are only visible to users who can view the *parent* model - (for models whose access is determined by the linked object, e.g. attachments) - AUDIT_EVENT_TYPES: Enumeration of named event types which can be recorded against this model - (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, ...] = () - AUDIT_M2M_FIELDS: tuple[str, ...] = () - AUDIT_PARENT_FIELD: Optional[str] = None - AUDIT_VIEW_RESTRICTION: Optional[str] = None - AUDIT_REQUIRE_PARENT_PERMISSION: bool = False - AUDIT_EVENT_TYPES: Optional[type] = None - - def get_audit_parent(self): - """Return the "parent" object for audit log entries against this instance. - - Audit entries linked to a parent are included in the history of that parent - (e.g. changes to line items are shown against the order). - """ - if self.AUDIT_PARENT_FIELD: - return getattr(self, self.AUDIT_PARENT_FIELD, None) - - return None - - def get_audit_parent_reference(self) -> Optional[tuple[Any, str]]: - """Return a (ContentType, pk) reference to the "parent" object (or None). - - Override this (rather than get_audit_parent) where the parent can be identified - without fetching it from the database (e.g. generic model_type / model_id links). - """ - from django.contrib.contenttypes.models import ContentType - - # Resolve a foreign key parent from its ID, without fetching the related object - if self.AUDIT_PARENT_FIELD: - field = self._meta.get_field(self.AUDIT_PARENT_FIELD) - - if field.many_to_one or field.one_to_one: - parent_id = getattr(self, field.attname) - - if parent_id is None: - return None - - return ContentType.objects.get_for_model(field.related_model), str( - parent_id - ) - - if parent := self.get_audit_parent(): - return ContentType.objects.get_for_model(parent), str(parent.pk) - - return None - - def should_audit(self) -> bool: - """Return False to skip recording audit entries for this instance. - - Used where only some rows of a model are of interest - (e.g. settings which are written automatically by the system). - """ - return True - - def audit_always(self) -> bool: - """Return True to record audit entries for this instance, even if the audit log is disabled. - - Used for changes which must always be recorded (e.g. disabling the audit log itself). - """ - return False - - def is_audit_masked(self) -> bool: - """Return True if *all* values recorded against this instance must be masked. - - Used where sensitivity depends on the row rather than the field - (e.g. a 'protected' setting value). - """ - return False - - -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.""" - - abstract = True - - # Define a reverse relation to the Parameter model - parameters_list = GenericRelation( - 'common.Parameter', content_type_field='model_type', object_id_field='model_id' - ) - - @staticmethod - def annotate_parameters(queryset: QuerySet) -> QuerySet: - """Annotate a queryset with pre-fetched parameters. - - Args: - queryset: Queryset to annotate - - Returns: - Annotated queryset - """ - return queryset.prefetch_related( - 'parameters_list', - 'parameters_list__model_type', - 'parameters_list__updated_by', - 'parameters_list__template', - 'parameters_list__template__model_type', - ) - - @property - @report.mixins.report_attribute() - def parameters(self) -> report.mixins.QuerySet: - """Return a QuerySet containing all the Parameter instances for this model. - - This will return pre-fetched data if available (i.e. in a serializer context). - """ - # Check the query cache for pre-fetched parameters - if cache := getattr(self, '_prefetched_objects_cache', None): - if 'parameters_list' in cache: - return cache['parameters_list'] - - return self.parameters_list.all().prefetch_related('template') - - def delete(self, *args, **kwargs): - """Handle the deletion of a model instance. - - Before deleting the model instance, delete any associated parameters. - """ - self.parameters_list.all().delete() - super().delete(*args, **kwargs) - - @transaction.atomic - def copy_parameters_from(self, other, clear=True, **kwargs): - """Copy all parameters from another model instance. - - Arguments: - other: The other model instance to copy parameters from - clear: If True, clear existing parameters before copying - **kwargs: Additional keyword arguments to pass to the Parameter constructor - """ - import common.models - - if clear: - self.parameters_list.all().delete() - - parameters = [] - - content_type = ContentType.objects.get_for_model(self.__class__) - - # Skip any parameters which are linked to a template with a uniqueness requirement, - # as copying these values would create conflicting (duplicate) values - copyable_parameters = [ - parameter - for parameter in other.parameters.all().select_related('template') - if parameter.template.unique - == common.models.ParameterTemplate.UniqueOptions.NONE - ] - - template_ids = [parameter.template.pk for parameter in copyable_parameters] - - # Remove all conflicting parameters first - self.parameters_list.filter(template__pk__in=template_ids).delete() - - for parameter in copyable_parameters: - parameter.pk = None - parameter.model_id = self.pk - parameter.model_type = content_type - - parameters.append(parameter) - - if len(parameters) > 0: - from audit.helpers import audited_bulk_create - - audited_bulk_create(common.models.Parameter, parameters) - - def get_parameter(self, name: str): - """Return a Parameter instance for the given parameter name. - - Args: - name: Name of the parameter template - - Returns: - Parameter instance if found, else None - """ - return self.parameters_list.filter(template__name=name).first() - - def get_parameters(self) -> QuerySet: - """Return all Parameter instances for this model.""" - return ( - self.parameters_list - .all() - .prefetch_related('template', 'model_type') - .order_by('template__name') - ) - - def parameters_map(self) -> dict: - """Return a map (dict) of parameter values associated with this Part instance, of the form. - - Example: - { - "name_1": "value_1", - "name_2": "value_2", - } - """ - params = {} - - for parameter in self.parameters.all().prefetch_related('template'): - params[parameter.template.name] = parameter.data - - return params - - def check_parameter_delete(self, parameter) -> bool: - """Run a check to determine if the provided parameter can be deleted. - - The default implementation always returns True, but this can be overridden in the implementing class. - """ - return True - - def check_parameter_save(self, parameter) -> bool: - """Run a check to determine if the provided parameter can be saved. - - The default implementation always returns True, but this can be overridden in the implementing class. - """ - return True - - -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.""" - - abstract = True - - # Define a reverse relation to the Note model - notes_list = GenericRelation( - 'common.Note', content_type_field='model_type', object_id_field='model_id' - ) - - @property - def notes(self) -> QuerySet: - """Return a queryset containing all notes for this model.""" - # Check the query cache for pre-fetched parameters - if cache := getattr(self, '_prefetched_objects_cache', None): - if 'notes_list' in cache: - return cache['notes_list'] - - return self.notes_list.all() - - def delete(self, *args, **kwargs): - """Handle the deletion of a model instance. - - Before deleting the model instance, delete any associated notes. - """ - self.notes_list.all().delete() - super().delete(*args, **kwargs) - - @transaction.atomic - def copy_notes_from(self, other, **kwargs): - """Copy all notes from another model instance. - - Arguments: - other: The other model instance to copy notes from - """ - import os - - from django.core.files.base import ContentFile - - import common.models - - content_type = ContentType.objects.get_for_model(self.__class__) - - # Prefetch each note's images in a single extra query, rather than - # one 'images.all()' query per note. - # - # Sort so primary note is saved last — Note.save() promotes the last - # note saved with primary=True, which correctly mirrors the source. - # This (and the resulting demotion of sibling notes) is real business - # logic in Note.save(), so notes must still be saved one at a time, - # in this order - unlike common.migrations.0051's data migration, - # which bulk_create()s notes directly, this can't do the same: that - # migration operates on a historical model with no custom - # save()/clean() methods at all, so there's no primary-flag logic to - # preserve there in the first place. - source_notes = sorted( - other.notes.all().prefetch_related('images'), key=lambda n: n.primary - ) - - for source_note in source_notes: - new_note = common.models.Note( - model_type=content_type, - model_id=self.pk, - primary=source_note.primary, - title=source_note.title, - description=source_note.description, - content=source_note.content, - ) - new_note.save() - - # Read each source image's file data and write it to storage up front, - # then bulk_create() all of this note's NotesImage rows in one INSERT - # instead of one save() per image - unlike Note, NotesImage has no - # save()-time business logic, so this is safe to batch. - new_images = [] - - for img in source_note.images.all(): - if not img.image: - continue - - old_url = img.image.url - filename = os.path.basename(img.image.name) - - try: - img.image.open('rb') - data = img.image.read() - finally: - img.image.close() - - new_img = common.models.NotesImage(note=new_note, user=img.user) - # save=False: still writes the file to storage (and assigns the - # resulting name/url), but defers the NotesImage row itself to - # the bulk_create() below - new_img.image.save(filename, ContentFile(data), save=False) - new_images.append((old_url, new_img)) - - if new_images: - common.models.NotesImage.objects.bulk_create([ - new_img for _, new_img in new_images - ]) - - content_updated = False - - for old_url, new_img in new_images: - if old_url in new_note.content: - new_note.content = new_note.content.replace( - old_url, new_img.image.url - ) - content_updated = True - - if content_updated: - new_note.save() - - @property - def primary_note(self): - """Return the primary note for this model instance, if it exists.""" - return self.notes_list.all().order_by('-primary').first() - - def get_note(self, title: Optional[str] = None): - """Return a Note instance for the given note title. - - Arguments: - title: Title of the note to retrieve. If None, returns the primary note (if it exists) - """ - notes = self.notes_list.all().order_by('-primary') - - if title: - notes = notes.filter(title=title) - - return notes.first() - - def check_note_delete(self, note) -> bool: - """Run a check to determine if the provided note can be deleted. - - The default implementation always returns True, but this can be overridden in the implementing class. - """ - return True - - def check_note_save(self, note) -> bool: - """Run a check to determine if the provided note can be saved. - - The default implementation always returns True, but this can be overridden in the implementing class. - """ - return True - - -class InvenTreeAttachmentMixin(ModelFeatureMixin, InvenTreePermissionCheckMixin): - """Provides an abstracted class for managing file attachments. - - Links the implementing model to the common.models.Attachment table, - and provides the following methods: - - - 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. - - Before deleting the model instance, delete any associated attachments. - """ - for attachment in list(self.attachments.all()): - attachment.delete() - - super().delete(*args, **kwargs) - - @property - @report.mixins.report_attribute() - def attachments(self) -> report.mixins.QuerySet: - """Return a queryset containing all attachments for this model.""" - return self.attachments_for_model().filter(model_id=self.pk) - - def attachments_for_model(self) -> QuerySet: - """Return all attachments for this model class.""" - from common.models import Attachment - - model_type = self.__class__.__name__.lower() - return Attachment.objects.filter(model_type=model_type) - - def create_attachment(self, attachment=None, link=None, comment='', **kwargs): - """Create an attachment / link for this model.""" - from common.models import Attachment - - kwargs['attachment'] = attachment - kwargs['link'] = link - kwargs['comment'] = comment - kwargs['model_type'] = self.__class__.__name__.lower() - kwargs['model_id'] = self.pk - - Attachment.objects.create(**kwargs) - - -class InvenTreeTree(ContentTypeMixin, MPTTModel): - """Provides an abstracted self-referencing tree model, based on the MPTTModel class. - - Our implementation provides the following key improvements: - - - Allow tracking of separate concepts of "nodes" and "items" - - Better handling of deletion of nodes and items - - Ensure tree is correctly rebuilt after deletion and other operations - - Improved protection against recursive tree structures - """ - - # How each node reference its parent object - NODE_PARENT_KEY = 'parent' - - # How items (not nodes) are hooked into the tree - # e.g. for StockLocation, this value is 'location' - ITEM_PARENT_KEY = None - - class Meta: - """Metaclass defines extra model properties.""" - - abstract = True - - class MPTTMeta: - """MPTT metaclass options.""" - - order_insertion_by = ['name'] - - @transaction.atomic - def delete(self, *args, **kwargs): - """Handle the deletion of a tree node. - - kwargs: - delete_children: If True, delete all child nodes (otherwise, point to the parent of this node) - delete_items: If True, delete all items associated with this node (otherwise, point to the parent of this node) - - Order of operations: - 1. Update nodes and items under the current node - 2. Delete this node - 3. Rebuild the model tree - """ - delete_children = kwargs.pop('delete_children', False) - delete_items = kwargs.pop('delete_items', False) - - # Ensure that we have the latest version of the database object - try: - self.refresh_from_db() - except self.__class__.DoesNotExist: - # If the object no longer exists, raise a ValidationError - raise ValidationError( - 'Object %s of type %s no longer exists', str(self), str(self.__class__) - ) - - tree_id = self.tree_id - parent = getattr(self, self.NODE_PARENT_KEY, None) - - # When deleting a top level node with multiple children, - # we need to assign a new tree_id to each child node - # otherwise they will all have the same tree_id (which is not allowed) - lower_trees = [] - - if not parent: # No parent, which means this is a top-level node - for child in self.get_children(): - # Store a flattened list of node IDs for each of the lower trees - nodes = list( - child - .get_descendants(include_self=True) - .values_list('pk', flat=True) - .distinct() - ) - lower_trees.append(nodes) - - # 1. Update nodes and items under the current node - self.handle_tree_delete( - delete_children=delete_children, delete_items=delete_items - ) - - # 2. Delete *this* node - super().delete(*args, **kwargs) - - # A set of tree_id values which need to be rebuilt - trees = set() - - if tree_id: - # If this node had a tree_id, we need to rebuild that tree - trees.add(tree_id) - - # Did we delete a top-level node? - next_tree_id = self.getNextTreeID() - - # If there is only one sub-tree, it can retain the same tree_id value - for tree in lower_trees[1:]: - # Bulk update the tree_id for all lower nodes - lower_nodes = self.__class__.objects.filter(pk__in=tree) - lower_nodes.update(tree_id=next_tree_id) - trees.add(next_tree_id) - next_tree_id += 1 - - # 3. Rebuild the model tree(s) as required - self.__class__.rebuild_trees(trees) - - def handle_tree_delete(self, delete_children=False, delete_items=False): - """Delete a single instance of the tree, based on provided kwargs. - - Removing a tree "node" from the database must be considered carefully, - based on what the user intends for any items which exist *under* that node. - - - "children" are any nodes (of the same type) which exist *under* this node (e.g. PartCategory) - - "items" are any items (of a different type) which exist *under* this node (e.g. Part) - - Arguments: - delete_children: If True, delete all child items - delete_items: If True, delete all items associated with this node - - There are multiple scenarios we can consider here: - - A) delete_children = True and delete_items = True - B) delete_children = True and delete_items = False - C) delete_children = False and delete_items = True - D) delete_children = False and delete_items = False - - Note: re-parenting uses audited_update(), so that the change is recorded - for audited models (it falls back to a plain update() otherwise). - """ - from audit.helpers import audited_update - - child_nodes = self.get_descendants(include_self=False) - - # Case A: Delete all child items, and all child nodes. - # - Delete all items at any lower level - # - Delete all descendant nodes - if delete_children and delete_items: - self.delete_items(cascade=True) - self.delete_nodes(child_nodes) - - # Case B: Delete all child nodes, but move all child items up to the parent - # - Move all items at any lower level to the parent of this item - # - Delete all descendant nodes - elif delete_children and not delete_items: - if items := self.get_items(cascade=True): - parent = getattr(self, self.NODE_PARENT_KEY, None) - audited_update(items, **{self.ITEM_PARENT_KEY: parent}) - self.delete_nodes(child_nodes) - - # Case C: Delete all child items, but keep all child nodes - # - Remove all items directly associated with this node - # - Move any direct child nodes up one level - elif not delete_children and delete_items: - self.delete_items(cascade=False) - parent = getattr(self, self.NODE_PARENT_KEY, None) - audited_update(self.get_children(), **{self.NODE_PARENT_KEY: parent}) - - # Case D: Keep all child items, and keep all child nodes - # - Move all items directly associated with this node up one level - # - Move any direct child nodes up one level - elif not delete_children and not delete_items: - parent = getattr(self, self.NODE_PARENT_KEY, None) - if items := self.get_items(cascade=False): - audited_update(items, **{self.ITEM_PARENT_KEY: parent}) - audited_update(self.get_children(), **{self.NODE_PARENT_KEY: parent}) - - def delete_nodes(self, nodes): - """Delete a set of nodes from the tree. - - 1. First, set the "parent" value for selected nodes to None - 2. Then, perform bulk deletion of selected nodes - - Step 1. is required because we cannot guarantee the order-of-operations in the db backend - - Arguments: - nodes: A queryset of nodes to delete - """ - nodes.update(**{self.NODE_PARENT_KEY: None}) - nodes.delete() - - def api_instance_filters(self): - """Instance filters for InvenTreeTree models.""" - return {self.NODE_PARENT_KEY: {'exclude_tree': self.pk}} - - def save(self, *args, **kwargs): - """Custom save method for InvenTreeTree abstract model.""" - db_instance = None - - parent = getattr(self, self.NODE_PARENT_KEY, None) - - if not self.tree_id: - if parent: - # If we have a parent, use the parent's tree_id - self.tree_id = parent.tree_id - self.level = parent.level + 1 - else: - # Otherwise, we need to generate a new tree_id - self.tree_id = self.getNextTreeID() - - if self.pk: - try: - db_instance = self.get_db_instance() - except self.__class__.DoesNotExist: - # If the instance does not exist, we cannot get the db instance - db_instance = None - try: - super().save(*args, **kwargs) - except InvalidMove: - # Provide better error for parent selection - raise ValidationError({self.NODE_PARENT_KEY: _('Invalid choice')}) - - trees = set() - - parent = getattr(self, self.NODE_PARENT_KEY, None) - - if db_instance: - # If the tree_id or parent has changed, we need to rebuild the tree - if getattr(db_instance, self.NODE_PARENT_KEY) != parent: - trees.add(db_instance.tree_id) - if db_instance.tree_id != self.tree_id: - trees.add(self.tree_id) - trees.add(db_instance.tree_id) - elif parent: - # New instance, so we need to rebuild the tree (if it has a parent) - trees.add(self.tree_id) - - # Flag to indicate that a tree rebuild task was triggered by this save - self._tree_rebuild_offloaded = False - - if len(trees) > 0: - # Offload the tree rebuild(s) to the background worker. - # Note that repeated calls are de-duplicated (per tree), - # so a bulk operation results in a single rebuild per affected tree. - ran_sync = self.__class__.offload_tree_rebuild(trees) - self._tree_rebuild_offloaded = True - - if ran_sync: - # The tree was rebuilt synchronously, so refresh the instance - try: - self.refresh_from_db() - except TransactionManagementError: - # If we are inside a transaction block, we cannot refresh from db - pass - except Exception as e: - # Any other error is unexpected - InvenTree.sentry.report_exception(e) - InvenTree.exceptions.log_error(f'{self.__class__.__name__}.save') - - @classmethod - def offload_tree_rebuild(cls, tree_ids) -> bool: - """Offload a rebuild of the specified trees to the background worker. - - - The tree structure (and pathstring values, where applicable) are rebuilt for each tree - - If the background worker is not running, the rebuild is performed synchronously - - Identical pending tasks are skipped, so repeated calls (e.g. during a bulk - operation) result in (at most) a single queued rebuild per affected tree - - Returns: - bool: True if any rebuild was performed synchronously (in the calling thread) - """ - from InvenTree.tasks import offload_task - - ran_sync = False - - for tree_id in tree_ids: - if tree_id: - result = offload_task( - 'InvenTree.tasks.rebuild_model_tree', cls._meta.label_lower, tree_id - ) - - if result is True: - # offload_task returns True if the task ran synchronously - ran_sync = True - - return ran_sync - - @classmethod - def rebuild_trees(cls, tree_ids) -> None: - """Rebuild the specified trees, with fallback to a full rebuild. - - - Perform a partial rebuild for each provided tree_id - - If any partial rebuild fails, rebuild the entire tree (expensive!!!) - """ - result = True - - for tree_id in tree_ids: - if tree_id and not cls.partial_rebuild(tree_id): - result = False - - if not result: - # Rebuild the entire tree (expensive!!!) - cls.objects.rebuild() - - @classmethod - def partial_rebuild(cls, tree_id: int) -> bool: - """Perform a partial rebuild of the tree structure. - - If a failure occurs, log the error and return False. - """ - try: - cls.objects.partial_rebuild(tree_id) - return True - except Exception as e: - # This is a critical error, explicitly report to sentry - InvenTree.sentry.report_exception(e) - - InvenTree.exceptions.log_error(f'{cls.__name__}.partial_rebuild') - logger.exception( - 'Failed to rebuild tree <%s> for %s: %s', tree_id, cls.__name__, e - ) - return False - - def delete_items(self, cascade: bool = False): - """Delete any 'items' which exist under this node in the tree. - - - Note that an 'item' is an instance of a different model class. - - Not all tree structures will have items associated with them. - """ - if items := self.get_items(cascade=cascade): - items.delete() - - def get_items(self, cascade: bool = False): - """Return a queryset of items which exist *under* this node in the tree. - - - For a StockLocation instance, this would be a queryset of StockItem objects - - For a PartCategory instance, this would be a queryset of Part objects - - The default implementation returns None, indicating that no items exist under this node. - """ - return None - - def getUniqueParents(self) -> QuerySet: - """Return a flat set of all parent items that exist above this node.""" - return self.get_ancestors() - - def getUniqueChildren(self, include_self=True) -> QuerySet: - """Return a flat set of all child items that exist under this node.""" - return self.get_descendants(include_self=include_self) - - @property - def has_children(self) -> bool: - """True if there are any children under this item.""" - return self.getUniqueChildren(include_self=False).count() > 0 - - @classmethod - def getNextTreeID(cls) -> int: - """Return the next available tree_id for this model class.""" - instance = cls.objects.order_by('-tree_id').first() - - if instance: - return instance.tree_id + 1 - else: - return 1 - - -class PathStringMixin(models.Model): - """Mixin class for adding a 'pathstring' field to a model class. - - The pathstring is a string representation of the path to this model instance, - which can be used for display purposes. - - The pathstring is automatically generated when the model instance is saved. - """ - - # Field to use for constructing a "pathstring" for the tree - PATH_FIELD = 'name' - - # Extra fields to include in the get_path result. E.g. icon - EXTRA_PATH_FIELDS = [] - - class Meta: - """Metaclass options for this mixin. - - Note: abstract must be true, as this is only a mixin, not a separate table - """ - - abstract = True - - name = models.CharField( - blank=False, max_length=100, verbose_name=_('Name'), help_text=_('Name') - ) - - description = models.CharField( - blank=True, - max_length=250, - verbose_name=_('Description'), - help_text=_('Description (optional)'), - ) - - # When a category is deleted, graft the children onto its parent - parent = TreeForeignKey( - 'self', - on_delete=models.DO_NOTHING, - blank=True, - null=True, - verbose_name='parent', - related_name='children', - ) - - # The 'pathstring' field is calculated each time the model is saved - pathstring = models.CharField( - blank=True, max_length=250, verbose_name=_('Path'), help_text=_('Path') - ) - - def save(self, *args, **kwargs): - """Update the pathstring field when saving the model instance.""" - old_pathstring = self.pathstring - - # Rebuild upper first, to ensure the lower nodes are updated correctly - super().save(*args, **kwargs) - - # Determine if a tree rebuild task was already triggered by this save - # (e.g. if the node was re-parented) - if so, the pathstring values - # for any lower nodes are updated by that task - rebuild_offloaded = getattr(self, '_tree_rebuild_offloaded', False) - - # Ensure that the pathstring is correctly constructed - pathstring = self.construct_pathstring(refresh=True) - - if pathstring != old_pathstring: - kwargs.pop('force_insert', None) - kwargs['force_update'] = True - - self.pathstring = pathstring - super().save(*args, **kwargs) - - # Update the pathstring values for any lower nodes, - # by offloading the update to the background worker - if not rebuild_offloaded and self.get_descendant_count() > 0: - self.__class__.offload_tree_rebuild([self.tree_id]) # ty: ignore[invalid-attribute-access] - - def delete(self, *args, **kwargs): - """Custom delete method for PathStringMixin. - - - Before deleting the object, update the pathstring for any child nodes. - - Then, delete the object. - """ - # Ensure that we have the latest version of the database object - try: - self.refresh_from_db() - except self.__class__.DoesNotExist: - # If the object no longer exists, raise a ValidationError - raise ValidationError( - 'Object %s of type %s no longer exists', str(self), str(self.__class__) - ) - - # Store the node ID values for lower nodes, before we delete this one - lower_nodes = self.get_lower_nodes() - - # Delete this node - after which we expect the tree structure will be updated - super().delete(*args, **kwargs) - - # Rebuild the pathstring for lower nodes - self.rebuild_lower_nodes(lower_nodes) - - def __str__(self): - """String representation of a category is the full path to that category.""" - return f'{self.pathstring} - {self.description}' - - def get_lower_nodes(self) -> list[int]: - """Return a list of all lower nodes in the tree.""" - return list( - self.get_descendants(include_self=False).values_list('pk', flat=True) - ) - - def rebuild_lower_nodes(self, lower_nodes: list[int]): - """Rebuild the pathstring for lower nodes in the tree. - - - This is used when the pathstring for this node is updated, and we need to update all lower nodes. - - We use a bulk-update to update the pathstring for all lower nodes in the tree. - """ - nodes = self.__class__.objects.filter(pk__in=lower_nodes) - - nodes_to_update = [] - - for node in nodes: - new_path = node.construct_pathstring() - - if new_path != node.pathstring: - node.pathstring = new_path - nodes_to_update.append(node) - - if len(nodes_to_update) > 0: - self.__class__.objects.bulk_update(nodes_to_update, ['pathstring']) - - @classmethod - def rebuild_tree_pathstring_values(cls, tree_ids) -> None: - """Rebuild the 'pathstring' values for all nodes in the specified trees. - - Each tree is processed in a single pass: - the pathstring for each node is constructed from its parent node, - and any changed values are written back in a single bulk update. - """ - tree_nodes = list(cls.objects.filter(tree_id__in=tree_ids)) - node_map = {node.pk: node for node in tree_nodes} - - # Cache of node ID -> list of path elements (from the top level down) - path_cache: dict[int, list[str]] = {} - - def path_names(node) -> list[str]: - """Construct the path (list of names) for a node, via its parent chain.""" - if node.pk in path_cache: - return path_cache[node.pk] - - names = [str(getattr(node, cls.PATH_FIELD, node.pk))] - - if node.parent_id: - parent = node_map.get(node.parent_id) - - if parent is None: - # Parent node exists outside the selected trees - parent = cls.objects.get(pk=node.parent_id) - node_map[node.parent_id] = parent - - names = [*path_names(parent), *names] - - path_cache[node.pk] = names - return names - - nodes_to_update = [] - - for node in tree_nodes: - pathstring = InvenTree.helpers.constructPathString(path_names(node)) - - if pathstring != node.pathstring: - node.pathstring = pathstring - nodes_to_update.append(node) - - if len(nodes_to_update) > 0: - cls.objects.bulk_update(nodes_to_update, ['pathstring'], batch_size=250) - - def construct_pathstring(self, refresh: bool = False) -> str: - """Construct the pathstring for this tree node. - - Arguments: - refresh: If True, force a refresh of the model instance - """ - if refresh: - # Refresh the model instance from the database - self.refresh_from_db() - - return InvenTree.helpers.constructPathString([ - getattr(item, self.PATH_FIELD, item.pk) for item in self.path - ]) - - def validate_unique(self, exclude=None): - """Validate that this tree instance satisfies our uniqueness requirements. - - Note that a 'unique_together' requirement for ('name', 'parent') is insufficient, - as it ignores cases where parent=None (i.e. top-level items) - """ - super().validate_unique(exclude) - - results = self.__class__.objects.filter( - name=self.name, parent=self.parent - ).exclude(pk=self.pk) - - if results.exists(): - raise ValidationError( - _('Duplicate names cannot exist under the same parent') - ) - - @property - @report.mixins.report_attribute() - def parentpath(self) -> list: - """Construct the parent path of this tree node. - - Returns: - List of category names from the top level to the parent of this category - """ - return list(self.get_ancestors()) - - @property - @report.mixins.report_attribute() - def path(self) -> list: - """Construct the complete part of this tree node. - - e.g. ["Top", "Second", "Third", "This"] - - Returns: - List of category names from the top level to this category - """ - return [*self.parentpath, self] - - def get_path(self) -> list: - """Return a list of element in the item tree. - - Contains the full path to this item, with each entry containing the following data: - - { - pk: , - name: , - } - """ - return [ - { - 'pk': item.pk, - 'name': getattr(item, self.PATH_FIELD, item.pk), - **{k: getattr(item, k, None) for k in self.EXTRA_PATH_FIELDS}, - } - for item in self.path - ] - - -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: - - - tags : A text field for storing comma-separated tags - """ - - MODEL_FEATURE = 'org.inventree.i.modelfeatures.tags' - - class Meta: - """Metaclass options for this mixin. - - Note: abstract must be true, as this is only a mixin, not a separate table - """ - - abstract = True - - tags = TaggableManager(blank=True) - - -class InvenTreeBarcodeMixin(ModelFeatureMixin, models.Model): - """A mixin class for adding barcode functionality to a model class. - - Two types of barcodes are supported: - - - Internal barcodes (QR codes using a strictly defined format) - - External barcodes (assign third party barcode data to a model instance) - - The following fields are added to any model which implements this mixin: - - - barcode_data : Raw data associated with an assigned barcode - - barcode_hash : A 'hash' of the assigned barcode data used to improve matching - - 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. - - Note: abstract must be true, as this is only a mixin, not a separate table - """ - - abstract = True - - barcode_data = models.CharField( - blank=True, - max_length=500, - verbose_name=_('Barcode Data'), - help_text=_('Third party barcode data'), - ) - - barcode_hash = models.CharField( - blank=True, - max_length=128, - verbose_name=_('Barcode Hash'), - help_text=_('Unique hash of barcode data'), - ) - - @classmethod - def barcode_model_type(cls): - """Return the model 'type' for creating a custom QR code.""" - # By default, use the name of the class - return cls.__name__.lower() - - @classmethod - def barcode_model_type_code(cls): - r"""Return a 'short' code for the model type. - - This is used to generate a efficient QR code for the model type. - It is expected to match this pattern: [0-9A-Z $%*+-.\/:]{2} - - Note: Due to the shape constraints (45**2=2025 different allowed codes) - this needs to be explicitly implemented in the model class to avoid collisions. - """ - raise NotImplementedError( - 'barcode_model_type_code() must be implemented in the model class' - ) - - def format_barcode(self, **kwargs): - """Return a string for formatting a QR code for this model instance.""" - from plugin.base.barcodes.helper import generate_barcode - - return generate_barcode(self) - - def format_matched_response(self, user, **kwargs): - """Format a standard response for a matched barcode.""" - # Check permission for this object - from users.permissions import check_user_permission - - if not check_user_permission(user, self, 'view'): - raise PermissionDenied( - _('User does not have permission to view this model') - ) - - data = {'pk': self.pk} - - if hasattr(self, 'get_api_url'): - api_url = self.get_api_url() - data['api_url'] = api_url = f'{api_url}{self.pk}/' - - # Attempt to serialize the object too - try: - match = resolve(api_url) - view_class = match.func.view_class - serializer_class = view_class.serializer_class - serializer = serializer_class(self) - data['instance'] = serializer.data - except Exception: - pass - - if hasattr(self, 'get_absolute_url'): - data['web_url'] = self.get_absolute_url() - - return data - - @property - @report.mixins.report_attribute() - def barcode(self) -> str: - """Format a minimal barcode string (e.g. for label printing).""" - return self.format_barcode() - - @classmethod - def lookup_barcode(cls, barcode_hash: str) -> models.Model: - """Check if a model instance exists with the specified third-party barcode hash.""" - return cls.objects.filter(barcode_hash=barcode_hash).first() - - def assign_barcode( - self, - barcode_hash: Optional[str] = None, - barcode_data: Optional[str] = None, - raise_error: bool = True, - save: bool = True, - ): - """Assign an external (third-party) barcode to this object.""" - # Must provide either barcode_hash or barcode_data - if barcode_hash is None and barcode_data is None: - raise ValueError("Provide either 'barcode_hash' or 'barcode_data'") - - # If barcode_hash is not provided, create from supplier barcode_data - if barcode_hash is None and barcode_data is not None: - barcode_hash = InvenTree.helpers.hash_barcode(barcode_data) - - # Check for existing item - if self.__class__.lookup_barcode(barcode_hash) is not None: - if raise_error: - raise ValidationError(_('Existing barcode found')) - else: - return False - - if barcode_data is not None: - self.barcode_data = barcode_data - - self.barcode_hash = barcode_hash - - if save: - self.save() - - return True - - def unassign_barcode(self): - """Unassign custom barcode from this model.""" - self.barcode_data = '' - self.barcode_hash = '' - - self.save() - - def notify_staff_users_of_error(instance, label: str, context: dict): """Helper function to notify staff users of an error.""" import common.models @@ -1877,69 +168,3 @@ def after_error_logged(sender, instance: Error, created: bool, **kwargs): 'link': url, }, ) - - -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: - - - image : An image field for storing an image - """ - - MODEL_FEATURE = 'org.inventree.i.modelfeatures.image' - - IMAGE_RENAME: Callable | None = None - - class Meta: - """Metaclass options for this mixin. - - Note: abstract must be true, as this is only a mixin, not a separate table - """ - - abstract = True - - def __init__(self, *args: Any, **kwargs: Any) -> None: - """Custom init method for InvenTreeImageMixin to ensure IMAGE_RENAME is implemented.""" - if self.IMAGE_RENAME is None: - raise NotImplementedError( - 'IMAGE_RENAME must be implemented in the model class' - ) - super().__init__(*args, **kwargs) - - def rename_image(self, filename): - """Rename the uploaded image file using the IMAGE_RENAME function.""" - return self.IMAGE_RENAME(filename) - - image = StdImageField( - upload_to=rename_image, - null=True, - blank=True, - variations={'thumbnail': (128, 128), 'preview': (256, 256)}, - delete_orphans=False, - verbose_name=_('Image'), - ) - - def get_image_url(self) -> str: - """Return the URL of the image for this object.""" - if self.image: - return InvenTree.helpers.getMediaUrl(self.image) - return InvenTree.helpers.getBlankImage() - - @property - @report.mixins.report_attribute() - def image_url(self) -> str: - """Return the URL of the image for this object.""" - return self.get_image_url() - - def get_thumbnail_url(self) -> str: - """Return the URL of the image thumbnail for this object.""" - if self.image: - return InvenTree.helpers.getMediaUrl(self.image, 'thumbnail') - return InvenTree.helpers.getBlankThumbnail() - - @property - @report.mixins.report_attribute() - def thumbnail_url(self) -> str: - """Return the URL of the image thumbnail for this object.""" - return self.get_thumbnail_url() diff --git a/src/backend/InvenTree/InvenTree/tasks.py b/src/backend/InvenTree/InvenTree/tasks.py index 40ef965de5..fd96533e9d 100644 --- a/src/backend/InvenTree/InvenTree/tasks.py +++ b/src/backend/InvenTree/InvenTree/tasks.py @@ -771,7 +771,8 @@ def rebuild_model_tree(model: str, tree_id: int) -> None: """ from django.apps import apps - import InvenTree.models + from generic.models.base import InvenTreeTree + from generic.models.modelmixins import InvenTreePathStringMixin try: model_class = apps.get_model(model) @@ -779,7 +780,7 @@ def rebuild_model_tree(model: str, tree_id: int) -> None: logger.warning("rebuild_model_tree: Model '%s' does not exist", model) return - if not issubclass(model_class, InvenTree.models.InvenTreeTree): + if not issubclass(model_class, InvenTreeTree): logger.warning("rebuild_model_tree: Model '%s' is not a tree model", model) return @@ -787,7 +788,7 @@ def rebuild_model_tree(model: str, tree_id: int) -> None: model_class.rebuild_trees([tree_id]) # Rebuild the 'pathstring' values for the entire tree (if applicable) - if issubclass(model_class, InvenTree.models.PathStringMixin): + if issubclass(model_class, InvenTreePathStringMixin): model_class.rebuild_tree_pathstring_values([tree_id]) # ty: ignore[invalid-attribute-access] diff --git a/src/backend/InvenTree/InvenTree/tests.py b/src/backend/InvenTree/InvenTree/tests.py index 298cddb3ef..e4024c49fa 100644 --- a/src/backend/InvenTree/InvenTree/tests.py +++ b/src/backend/InvenTree/InvenTree/tests.py @@ -861,7 +861,7 @@ class TestHelpers(TestCase): def test_model_mixin(self): """Test the getModelsWithMixin function.""" - from InvenTree.models import InvenTreeBarcodeMixin + from generic.models.modelmixins import InvenTreeBarcodeMixin models = InvenTree.helpers_model.getModelsWithMixin(InvenTreeBarcodeMixin) diff --git a/src/backend/InvenTree/audit/registry.py b/src/backend/InvenTree/audit/registry.py index 92ffae4d5e..75578f2484 100644 --- a/src/backend/InvenTree/audit/registry.py +++ b/src/backend/InvenTree/audit/registry.py @@ -45,7 +45,7 @@ def audited_models() -> list: Uses the app registry rather than ContentTypes, so that no database access is required. """ - from InvenTree.models import InvenTreeAuditMixin + from generic.models.modelmixins import InvenTreeAuditMixin return sorted( ( diff --git a/src/backend/InvenTree/build/models.py b/src/backend/InvenTree/build/models.py index cd165e7693..79363784e3 100644 --- a/src/backend/InvenTree/build/models.py +++ b/src/backend/InvenTree/build/models.py @@ -25,7 +25,6 @@ import generic.states import InvenTree.fields import InvenTree.helpers import InvenTree.helpers_model -import InvenTree.models import InvenTree.ready import InvenTree.tasks import part.models @@ -49,6 +48,18 @@ from build.validators import ( from common.models import ProjectCode from common.settings import get_global_setting from generic.enums import StringEnum +from generic.models.base import InvenTreeMetadataModel, InvenTreeModel, InvenTreeTree +from generic.models.modelmixins import ( + InvenTreeAttachmentMixin, + InvenTreeAuditMixin, + InvenTreeBarcodeMixin, + InvenTreeMetadataMixin, + InvenTreeNoteMixin, + InvenTreeParameterMixin, + InvenTreePluginValidationMixin, + InvenTreeReferenceIndexingMixin, + InvenTreeTagsMixin, +) from generic.states import ( DEFERRABLE, Deprecations, @@ -92,19 +103,19 @@ class BuildReportContext(report.mixins.BaseReportContext, TypedDict): class Build( - InvenTree.models.InvenTreeAuditMixin, - InvenTree.models.PluginValidationMixin, + InvenTreeAuditMixin, + InvenTreePluginValidationMixin, report.mixins.InvenTreeReportMixin, - InvenTree.models.InvenTreeParameterMixin, - InvenTree.models.InvenTreeAttachmentMixin, - InvenTree.models.InvenTreeBarcodeMixin, - InvenTree.models.InvenTreeNoteMixin, - InvenTree.models.InvenTreeTagsMixin, - InvenTree.models.ReferenceIndexingMixin, + InvenTreeParameterMixin, + InvenTreeAttachmentMixin, + InvenTreeBarcodeMixin, + InvenTreeNoteMixin, + InvenTreeTagsMixin, + InvenTreeReferenceIndexingMixin, StateTransitionMixin, StatusCodeMixin, - InvenTree.models.MetadataMixin, - InvenTree.models.InvenTreeTree, + InvenTreeMetadataMixin, + InvenTreeTree, ): """A Build object organizes the creation of new StockItem objects from other existing StockItem objects. @@ -2190,7 +2201,7 @@ class BuildLineReportContext(report.mixins.BaseReportContext, TypedDict): quantity: decimal.Decimal -class BuildLine(report.mixins.InvenTreeReportMixin, InvenTree.models.InvenTreeModel): +class BuildLine(report.mixins.InvenTreeReportMixin, InvenTreeModel): """A BuildLine object links a BOMItem to a Build. When a new Build is created, the BuildLine objects are created automatically. @@ -2310,7 +2321,7 @@ class BuildLine(report.mixins.InvenTreeReportMixin, InvenTree.models.InvenTreeMo return self.consumed >= self.quantity -class BuildItem(InvenTree.models.InvenTreeMetadataModel): +class BuildItem(InvenTreeMetadataModel): """A BuildItem links multiple StockItem objects to a Build. These are used to allocate part stock to a build. Once the Build is completed, the parts are removed from stock and the BuildItemAllocation objects are removed. diff --git a/src/backend/InvenTree/common/api.py b/src/backend/InvenTree/common/api.py index eb3a23a644..cdd86dac84 100644 --- a/src/backend/InvenTree/common/api.py +++ b/src/backend/InvenTree/common/api.py @@ -47,12 +47,12 @@ import common.filters import common.models import common.serializers import InvenTree.conversion -import InvenTree.models import InvenTree.ready from common.icons import get_icon_packs from common.serializers import OAuth2ApplicationSerializer from common.settings import get_global_setting from data_exporter.mixins import DataExportViewMixin +from generic.models.base import InvenTreeTree from generic.states.api import urlpattern as generic_states_api_urls from InvenTree.api import ( BulkCreateMixin, @@ -1226,7 +1226,7 @@ class ParameterTemplateFilter(FilterSet): }) # If the provided model is a "tree" structure, then we should also include any child objects in the filter - if isinstance(instance, InvenTree.models.InvenTreeTree): + if isinstance(instance, InvenTreeTree): id_values = list( instance.get_descendants(include_self=True).values_list('pk', flat=True) ) @@ -1315,7 +1315,7 @@ class ParameterTemplateFilter(FilterSet): return queryset.none() # Account for potential tree structure in the related model - if isinstance(related_instance, InvenTree.models.InvenTreeTree): + if isinstance(related_instance, InvenTreeTree): related_instances = list( related_instance.get_descendants(include_self=True).values_list( 'pk', flat=True @@ -1517,7 +1517,7 @@ class InstanceInfoView(APIView): ) def get(self, request, *args, **kwargs): """Return counts of attachments, notes and parameters for the given instance.""" - from InvenTree.models import ( + from generic.models.modelmixins import ( InvenTreeAttachmentMixin, InvenTreeNoteMixin, InvenTreeParameterMixin, diff --git a/src/backend/InvenTree/common/migrations/0008_remove_inventreesetting_description_squashed_0039_emailthread_emailmessage.py b/src/backend/InvenTree/common/migrations/0008_remove_inventreesetting_description_squashed_0039_emailthread_emailmessage.py index 5dc2d7e1f8..96a4739821 100644 --- a/src/backend/InvenTree/common/migrations/0008_remove_inventreesetting_description_squashed_0039_emailthread_emailmessage.py +++ b/src/backend/InvenTree/common/migrations/0008_remove_inventreesetting_description_squashed_0039_emailthread_emailmessage.py @@ -2,7 +2,6 @@ import InvenTree.config import InvenTree.fields -import InvenTree.models import common.models import common.validators import django.db.models.deletion @@ -11,7 +10,7 @@ import uuid from django.conf import settings from django.db import migrations, models, transaction from moneyed import CURRENCIES - +import generic.models.modelmixins def set_default_currency(apps, schema_editor): """Migrate the currency setting from config.yml to db.""" @@ -235,7 +234,7 @@ class Migration(migrations.Migration): options={ 'verbose_name': 'Attachment', }, - bases=(InvenTree.models.PluginValidationMixin, models.Model), + bases=(generic.models.modelmixins.InvenTreePluginValidationMixin, models.Model), ), migrations.AlterField( model_name='customunit', @@ -280,7 +279,7 @@ class Migration(migrations.Migration): options={ 'verbose_name': 'Barcode Scan', }, - bases=(InvenTree.models.PluginValidationMixin, models.Model), + bases=(generic.models.modelmixins.InvenTreePluginValidationMixin, models.Model), ), migrations.CreateModel( name='SelectionList', @@ -299,7 +298,7 @@ class Migration(migrations.Migration): 'verbose_name': 'Selection List', 'verbose_name_plural': 'Selection Lists', }, - bases=(InvenTree.models.PluginValidationMixin, models.Model), + bases=(generic.models.modelmixins.InvenTreePluginValidationMixin, models.Model), ), migrations.CreateModel( name='SelectionListEntry', @@ -372,7 +371,7 @@ class Migration(migrations.Migration): 'ordering': ['-updated'], 'unique_together': {('key', 'global_id')}, }, - bases=(InvenTree.models.PluginValidationMixin, models.Model), + bases=(generic.models.modelmixins.InvenTreePluginValidationMixin, models.Model), ), migrations.CreateModel( name='EmailMessage', diff --git a/src/backend/InvenTree/common/migrations/0040_parametertemplate_parameter.py b/src/backend/InvenTree/common/migrations/0040_parametertemplate_parameter.py index 5bfce74256..a22b198358 100644 --- a/src/backend/InvenTree/common/migrations/0040_parametertemplate_parameter.py +++ b/src/backend/InvenTree/common/migrations/0040_parametertemplate_parameter.py @@ -1,12 +1,12 @@ # Generated by Django 5.2.8 on 2025-12-03 12:39 -import InvenTree.models +import generic.models.modelmixins import InvenTree.validators import django.core.validators import django.db.models.deletion from django.conf import settings from django.db import migrations, models - +import generic.models.internal class Migration(migrations.Migration): @@ -124,8 +124,8 @@ class Migration(migrations.Migration): "db_table": "part_partparametertemplate", }, bases=( - InvenTree.models.ContentTypeMixin, - InvenTree.models.PluginValidationMixin, + generic.models.internal.ContentTypeMixin, + generic.models.modelmixins.InvenTreePluginValidationMixin, models.Model, ), ), @@ -237,8 +237,8 @@ class Migration(migrations.Migration): "unique_together": {("model_type", "model_id", "template")}, }, bases=( - InvenTree.models.ContentTypeMixin, - InvenTree.models.PluginValidationMixin, + generic.models.internal.ContentTypeMixin, + generic.models.modelmixins.InvenTreePluginValidationMixin, models.Model, ), ), diff --git a/src/backend/InvenTree/common/migrations/0050_note.py b/src/backend/InvenTree/common/migrations/0050_note.py index c5382e7a60..94b61746a2 100644 --- a/src/backend/InvenTree/common/migrations/0050_note.py +++ b/src/backend/InvenTree/common/migrations/0050_note.py @@ -1,10 +1,11 @@ # Generated by Django 5.2.14 on 2026-05-18 14:16 import common.validators -import InvenTree.models +import generic.models.modelmixins import django.db.models.deletion from django.conf import settings from django.db import migrations, models +import generic.models.internal class Migration(migrations.Migration): @@ -118,8 +119,8 @@ class Migration(migrations.Migration): "verbose_name_plural": "Notes", }, bases=( - InvenTree.models.ContentTypeMixin, - InvenTree.models.PluginValidationMixin, + generic.models.internal.ContentTypeMixin, + generic.models.modelmixins.InvenTreePluginValidationMixin, models.Model, ), ), diff --git a/src/backend/InvenTree/common/models.py b/src/backend/InvenTree/common/models.py index 35f33743ac..3a1f11855f 100644 --- a/src/backend/InvenTree/common/models.py +++ b/src/backend/InvenTree/common/models.py @@ -59,7 +59,6 @@ import InvenTree.conversion import InvenTree.exceptions import InvenTree.fields import InvenTree.helpers -import InvenTree.models import InvenTree.ready import InvenTree.tasks import InvenTree.validators @@ -67,6 +66,14 @@ import users.models from common.setting.type import InvenTreeSettingsKeyType, SettingsKeyType from common.settings import get_global_setting, global_setting_overrides from generic.enums import StringEnum +from generic.models.base import InvenTreeMetadataModel, InvenTreeModel +from generic.models.modelmixins import ( + InvenTreeAttachmentMixin, + InvenTreeAuditMixin, + InvenTreeNoteMixin, + InvenTreeParameterMixin, + InvenTreeTagsMixin, +) from generic.states import ColorEnum from generic.states.custom import state_color_mappings from InvenTree.cache import get_session_cache, set_session_cache @@ -151,9 +158,7 @@ class UpdatedUserMixin(models.Model): ) -class ProjectCode( - InvenTree.models.InvenTreeAuditMixin, InvenTree.models.InvenTreeMetadataModel -): +class ProjectCode(InvenTreeAuditMixin, InvenTreeMetadataModel): """A ProjectCode is a unique identifier for a project.""" IMPORT_ID_FIELDS = ['code'] @@ -1279,7 +1284,7 @@ class BaseInvenTreeSetting(UpdatedUserMixin, models.Model): return self.__class__.is_required(self.key, **self.get_filters_for_instance()) -class InvenTreeSetting(InvenTree.models.InvenTreeAuditMixin, BaseInvenTreeSetting): +class InvenTreeSetting(InvenTreeAuditMixin, BaseInvenTreeSetting): """An InvenTreeSetting object is a key:value pair used for storing single values (e.g. one-off settings values). The class provides a way of retrieving the value for a particular key, @@ -1871,7 +1876,7 @@ class NewsFeedEntry(models.Model): ) -class CustomUnit(InvenTree.models.InvenTreeAuditMixin, models.Model): +class CustomUnit(InvenTreeAuditMixin, models.Model): """Model for storing custom physical unit definitions. Model Attributes: @@ -2032,12 +2037,7 @@ def rename_attachment(instance, filename: str): ) -class Attachment( - InvenTree.models.InvenTreeAuditMixin, - InvenTree.models.MetadataMixin, - InvenTree.models.InvenTreeTagsMixin, - InvenTree.models.InvenTreeModel, -): +class Attachment(InvenTreeAuditMixin, InvenTreeTagsMixin, InvenTreeMetadataModel): """Class which represents an uploaded file attachment. An attachment can be either an uploaded file, or an external URL. @@ -2322,8 +2322,6 @@ class Attachment( def check_permission(self, permission, user): """Check if the user has the required permission for this attachment.""" - from InvenTree.models import InvenTreeAttachmentMixin - model_class = common.validators.attachment_model_class_from_label( self.model_type ) @@ -2544,7 +2542,7 @@ class InvenTreeCustomUserStateModel(models.Model): return cls -class SelectionList(InvenTree.models.MetadataMixin, InvenTree.models.InvenTreeModel): +class SelectionList(InvenTreeMetadataModel): """Class which represents a list of selectable items for parameters. A lists selection options can be either manually defined, or sourced from a plugin. @@ -2743,11 +2741,7 @@ class SelectionListEntry(models.Model): return self.label -class ParameterTemplate( - InvenTree.models.InvenTreeAuditMixin, - InvenTree.models.MetadataMixin, - InvenTree.models.InvenTreeModel, -): +class ParameterTemplate(InvenTreeAuditMixin, InvenTreeMetadataModel): """A ParameterTemplate provides a template for defining parameter values against various models. This allow for assigning arbitrary data fields against existing models, @@ -2977,12 +2971,7 @@ def post_save_parameter_template(sender, instance, created, **kwargs): ) -class Parameter( - InvenTree.models.InvenTreeAuditMixin, - UpdatedUserMixin, - InvenTree.models.MetadataMixin, - InvenTree.models.InvenTreeModel, -): +class Parameter(InvenTreeAuditMixin, UpdatedUserMixin, InvenTreeMetadataModel): """Class which represents a parameter value assigned to a particular model instance. Attributes: @@ -3183,8 +3172,6 @@ class Parameter( def check_permission(self, permission, user): """Check if the user has the required permission for this parameter.""" - from InvenTree.models import InvenTreeParameterMixin - model_class = self.model_type.model_class() if not issubclass(model_class, InvenTreeParameterMixin): @@ -3198,8 +3185,6 @@ class Parameter( The linked content_object can implement custom checks by overriding the 'check_parameter_edit' method. """ - from InvenTree.models import InvenTreeParameterMixin - # content_object is None (rather than raising) if the target row is # missing - GenericForeignKey.__get__ catches ObjectDoesNotExist # internally, it never propagates it. @@ -3210,8 +3195,6 @@ class Parameter( def check_delete(self): """Check if this parameter can be deleted.""" - from InvenTree.models import InvenTreeParameterMixin - instance = self.content_object if instance and isinstance(instance, InvenTreeParameterMixin): @@ -3266,9 +3249,7 @@ class Parameter( return self.template.description -class Note( - UpdatedUserMixin, InvenTree.models.MetadataMixin, InvenTree.models.InvenTreeModel -): +class Note(UpdatedUserMixin, InvenTreeMetadataModel): """Class which represents a note assigned to a particular model instance. Attributes: @@ -3475,8 +3456,6 @@ class Note( def check_save(self): """Check if this note can be saved.""" - from InvenTree.models import InvenTreeNoteMixin - if self.template or not self.model_type: return @@ -3490,8 +3469,6 @@ class Note( def check_delete(self): """Check if this note can be deleted.""" - from InvenTree.models import InvenTreeNoteMixin - if self.template or not self.model_type: return @@ -3507,8 +3484,6 @@ class Note( def check_permission(self, permission, user): """Check if the user has the required permission for this note.""" - from InvenTree.models import InvenTreeNoteMixin - if self.template: return user.is_staff @@ -3615,7 +3590,7 @@ def after_notesimage_deleted(sender, instance, **kwargs): ) -class BarcodeScanResult(InvenTree.models.InvenTreeModel): +class BarcodeScanResult(InvenTreeModel): """Model for storing barcode scans results.""" BARCODE_SCAN_MAX_LEN = 250 @@ -3948,7 +3923,7 @@ class EmailMessage(models.Model): return super().delete(*args, **kwargs) -class EmailThread(InvenTree.models.InvenTreeMetadataModel): +class EmailThread(InvenTreeMetadataModel): """Model for storing email threads.""" class Meta: diff --git a/src/backend/InvenTree/common/serializers.py b/src/backend/InvenTree/common/serializers.py index 446b3c123a..dbc63f7f24 100644 --- a/src/backend/InvenTree/common/serializers.py +++ b/src/backend/InvenTree/common/serializers.py @@ -22,12 +22,16 @@ import common.models as common_models import common.validators import generic.states.custom from generic.modelfeatures import get_model_features +from generic.models.modelmixins import ( + InvenTreeAttachmentMixin, + InvenTreeNoteMixin, + InvenTreeParameterMixin, +) from importer.registry import register_importer from InvenTree.apps import DEFAULT_OIDC_APP_ID from InvenTree.helpers import get_objectreference from InvenTree.helpers_model import construct_absolute_url from InvenTree.mixins import DataImportExportSerializerMixin -from InvenTree.models import InvenTreeNoteMixin, InvenTreeParameterMixin from InvenTree.serializers import ( ContentTypeField, FilterableSerializerMixin, @@ -892,8 +896,6 @@ class AttachmentSerializer( def save(self, **kwargs): """Override the save method to handle the model_type field.""" - from InvenTree.models import InvenTreeAttachmentMixin - model_type = self.validated_data.get('model_type', None) if model_type is None and self.instance: diff --git a/src/backend/InvenTree/common/validators.py b/src/backend/InvenTree/common/validators.py index db536f6b94..7af400333a 100644 --- a/src/backend/InvenTree/common/validators.py +++ b/src/backend/InvenTree/common/validators.py @@ -28,16 +28,16 @@ def model_options_for_mixin(mixin_class) -> list: def note_model_types(): """Return a list of valid note model choices.""" - import InvenTree.models + from generic.models.modelmixins import InvenTreeNoteMixin - return models_with_mixin(InvenTree.models.InvenTreeNoteMixin) + return models_with_mixin(InvenTreeNoteMixin) def note_model_options(): """Return a list of options for models which support notes.""" - import InvenTree.models + from generic.models.modelmixins import InvenTreeNoteMixin - return model_options_for_mixin(InvenTree.models.InvenTreeNoteMixin) + return model_options_for_mixin(InvenTreeNoteMixin) def validate_note_model_type(value): @@ -65,16 +65,16 @@ def validate_note_model_type(value): def parameter_model_types(): """Return a list of valid parameter model choices.""" - import InvenTree.models + from generic.models.modelmixins import InvenTreeParameterMixin - return models_with_mixin(InvenTree.models.InvenTreeParameterMixin) + return models_with_mixin(InvenTreeParameterMixin) def parameter_model_options(): """Return a list of options for models which support parameters.""" - import InvenTree.models + from generic.models.modelmixins import InvenTreeParameterMixin - return model_options_for_mixin(InvenTree.models.InvenTreeParameterMixin) + return model_options_for_mixin(InvenTreeParameterMixin) def parameter_template_model_options(): @@ -84,16 +84,16 @@ def parameter_template_model_options(): def attachment_model_types(): """Return a list of valid attachment model choices.""" - import InvenTree.models + from generic.models.modelmixins import InvenTreeAttachmentMixin - return models_with_mixin(InvenTree.models.InvenTreeAttachmentMixin) + return models_with_mixin(InvenTreeAttachmentMixin) def attachment_model_options(): """Return a list of options for models which support attachments.""" - import InvenTree.models + from generic.models.modelmixins import InvenTreeAttachmentMixin - return model_options_for_mixin(InvenTree.models.InvenTreeAttachmentMixin) + return model_options_for_mixin(InvenTreeAttachmentMixin) def attachment_model_class_from_label(label: str): diff --git a/src/backend/InvenTree/company/migrations/0076_alter_company_image.py b/src/backend/InvenTree/company/migrations/0076_alter_company_image.py index dc59cf677d..bdc4672b78 100644 --- a/src/backend/InvenTree/company/migrations/0076_alter_company_image.py +++ b/src/backend/InvenTree/company/migrations/0076_alter_company_image.py @@ -1,9 +1,9 @@ # Generated by Django 5.2.7 on 2025-11-04 20:59 -import InvenTree.models import stdimage.models from django.db import migrations +import generic.models.modelmixins class Migration(migrations.Migration): @@ -15,6 +15,6 @@ class Migration(migrations.Migration): migrations.AlterField( model_name='company', name='image', - field=stdimage.models.StdImageField(blank=True, force_min_size=False, null=True, upload_to=InvenTree.models.InvenTreeImageMixin.rename_image, variations={'preview': (256, 256), 'thumbnail': (128, 128)}, verbose_name='Image'), + field=stdimage.models.StdImageField(blank=True, force_min_size=False, null=True, upload_to=generic.models.modelmixins.InvenTreeImageMixin.rename_image, variations={'preview': (256, 256), 'thumbnail': (128, 128)}, verbose_name='Image'), ), ] diff --git a/src/backend/InvenTree/company/models.py b/src/backend/InvenTree/company/models.py index e9cbc25213..5f75521122 100644 --- a/src/backend/InvenTree/company/models.py +++ b/src/backend/InvenTree/company/models.py @@ -22,13 +22,22 @@ import common.currency import common.models import InvenTree.conversion import InvenTree.helpers -import InvenTree.models import InvenTree.ready import InvenTree.validators import report.mixins from audit.helpers import audited_update from common.currency import currency_code_default from common.settings import get_global_setting +from generic.models.base import InvenTreeMetadataModel, InvenTreeModel +from generic.models.modelmixins import ( + InvenTreeAttachmentMixin, + InvenTreeAuditMixin, + InvenTreeBarcodeMixin, + InvenTreeImageMixin, + InvenTreeNoteMixin, + InvenTreeParameterMixin, + InvenTreeTagsMixin, +) from InvenTree.fields import InvenTreeURLField, RoundingDecimalField from order.status_codes import PurchaseOrderStatusGroups @@ -87,14 +96,14 @@ def default_internal_company() -> Optional[int]: class Company( - InvenTree.models.InvenTreeAuditMixin, - InvenTree.models.InvenTreeAttachmentMixin, - InvenTree.models.InvenTreeParameterMixin, - InvenTree.models.InvenTreeNoteMixin, - InvenTree.models.InvenTreeTagsMixin, + InvenTreeAuditMixin, + InvenTreeAttachmentMixin, + InvenTreeParameterMixin, + InvenTreeNoteMixin, + InvenTreeTagsMixin, report.mixins.InvenTreeReportMixin, - InvenTree.models.InvenTreeImageMixin, - InvenTree.models.InvenTreeMetadataModel, + InvenTreeImageMixin, + InvenTreeMetadataModel, ): """A Company object represents an external company. @@ -339,9 +348,7 @@ class Company( ).distinct() -class Contact( - InvenTree.models.InvenTreeAuditMixin, InvenTree.models.InvenTreeMetadataModel -): +class Contact(InvenTreeAuditMixin, InvenTreeMetadataModel): """A Contact represents a person who works at a particular company. A Company may have zero or more associated Contact objects. Attributes: @@ -384,7 +391,7 @@ class Contact( return self.name -class Address(InvenTree.models.InvenTreeAuditMixin, InvenTree.models.InvenTreeModel): +class Address(InvenTreeAuditMixin, InvenTreeModel): """An address represents a physical location where the company is located. It is possible for a company to have multiple locations. Attributes: @@ -561,13 +568,13 @@ class Address(InvenTree.models.InvenTreeAuditMixin, InvenTree.models.InvenTreeMo class ManufacturerPart( - InvenTree.models.InvenTreeAuditMixin, - InvenTree.models.InvenTreeAttachmentMixin, - InvenTree.models.InvenTreeParameterMixin, - InvenTree.models.InvenTreeBarcodeMixin, - InvenTree.models.InvenTreeNoteMixin, - InvenTree.models.InvenTreeTagsMixin, - InvenTree.models.InvenTreeMetadataModel, + InvenTreeAuditMixin, + InvenTreeAttachmentMixin, + InvenTreeParameterMixin, + InvenTreeBarcodeMixin, + InvenTreeNoteMixin, + InvenTreeTagsMixin, + InvenTreeMetadataModel, ): """Represents a unique part as provided by a Manufacturer Each ManufacturerPart is identified by a MPN (Manufacturer Part Number) Each ManufacturerPart is also linked to a Part object. A Part may be available from multiple manufacturers. @@ -680,15 +687,14 @@ class ManufacturerPart( class SupplierPart( - InvenTree.models.InvenTreeAuditMixin, - InvenTree.models.InvenTreeAttachmentMixin, - InvenTree.models.InvenTreeParameterMixin, - InvenTree.models.MetadataMixin, - InvenTree.models.InvenTreeBarcodeMixin, - InvenTree.models.InvenTreeNoteMixin, - InvenTree.models.InvenTreeTagsMixin, + InvenTreeAuditMixin, + InvenTreeAttachmentMixin, + InvenTreeParameterMixin, + InvenTreeBarcodeMixin, + InvenTreeNoteMixin, + InvenTreeTagsMixin, common.models.MetaMixin, - InvenTree.models.InvenTreeModel, + InvenTreeMetadataModel, ): """Represents a unique part as provided by a Supplier Each SupplierPart is identified by a SKU (Supplier Part Number) Each SupplierPart is also linked to a Part or ManufacturerPart object. A Part may be available from multiple suppliers. @@ -1093,9 +1099,7 @@ class SupplierPart( return s -class SupplierPriceBreak( - InvenTree.models.InvenTreeAuditMixin, common.models.PriceBreak -): +class SupplierPriceBreak(InvenTreeAuditMixin, common.models.PriceBreak): """Represents a quantity price break for a SupplierPart. - Suppliers can offer discounts at larger quantities diff --git a/src/backend/InvenTree/generic/modelfeatures/tests.py b/src/backend/InvenTree/generic/modelfeatures/tests.py index 0568a5b501..0378808ee4 100644 --- a/src/backend/InvenTree/generic/modelfeatures/tests.py +++ b/src/backend/InvenTree/generic/modelfeatures/tests.py @@ -4,7 +4,7 @@ from django.urls import reverse from taggit.models import Tag -import InvenTree.models +from generic.models.modelmixins import InvenTreeNoteMixin from InvenTree.unit_test import InvenTreeAPITestCase from part.models import Part @@ -60,7 +60,7 @@ class ContentTypeFeatureAPITests(InvenTreeAPITestCase): class CustomFeatureMixin(ModelFeatureMixin): MODEL_FEATURE = 'custom' - class CustomModel(CustomFeatureMixin, InvenTree.models.InvenTreeNoteMixin): + class CustomModel(CustomFeatureMixin, InvenTreeNoteMixin): class Meta: abstract = True diff --git a/src/backend/InvenTree/generic/models/base.py b/src/backend/InvenTree/generic/models/base.py new file mode 100644 index 0000000000..8ba326d48c --- /dev/null +++ b/src/backend/InvenTree/generic/models/base.py @@ -0,0 +1,394 @@ +"""Base classes for building models.""" + +from django.core.exceptions import ValidationError +from django.db import models, transaction +from django.db.models import QuerySet +from django.db.transaction import TransactionManagementError +from django.utils.translation import gettext_lazy as _ + +import structlog +from mptt.exceptions import InvalidMove +from mptt.models import MPTTModel + +import InvenTree.exceptions +import InvenTree.sentry +from generic.models.internal import ContentTypeMixin +from generic.models.modelmixins import ( + InvenTreeMetadataMixin, + InvenTreePluginValidationMixin, +) + +logger = structlog.get_logger('inventree') + + +class InvenTreeModel(ContentTypeMixin, InvenTreePluginValidationMixin, models.Model): + """Base class for InvenTree models, which provides some common functionality. + + Includes the following mixins by default: + + - PluginValidationMixin: Provides a hook for plugins to validate model instances + """ + + class Meta: + """Metaclass options.""" + + abstract = True + + +class InvenTreeMetadataModel(InvenTreeMetadataMixin, InvenTreeModel): + """Base class for an InvenTree model which includes a metadata field.""" + + class Meta: + """Metaclass options.""" + + abstract = True + + +class InvenTreeTree(ContentTypeMixin, MPTTModel): + """Provides an abstracted self-referencing tree model, based on the MPTTModel class. + + Our implementation provides the following key improvements: + + - Allow tracking of separate concepts of "nodes" and "items" + - Better handling of deletion of nodes and items + - Ensure tree is correctly rebuilt after deletion and other operations + - Improved protection against recursive tree structures + """ + + # How each node reference its parent object + NODE_PARENT_KEY = 'parent' + + # How items (not nodes) are hooked into the tree + # e.g. for StockLocation, this value is 'location' + ITEM_PARENT_KEY = None + + class Meta: + """Metaclass defines extra model properties.""" + + abstract = True + + class MPTTMeta: + """MPTT metaclass options.""" + + order_insertion_by = ['name'] + + @transaction.atomic + def delete(self, *args, **kwargs): + """Handle the deletion of a tree node. + + kwargs: + delete_children: If True, delete all child nodes (otherwise, point to the parent of this node) + delete_items: If True, delete all items associated with this node (otherwise, point to the parent of this node) + + Order of operations: + 1. Update nodes and items under the current node + 2. Delete this node + 3. Rebuild the model tree + """ + delete_children = kwargs.pop('delete_children', False) + delete_items = kwargs.pop('delete_items', False) + + # Ensure that we have the latest version of the database object + try: + self.refresh_from_db() + except self.__class__.DoesNotExist: + # If the object no longer exists, raise a ValidationError + raise ValidationError( + 'Object %s of type %s no longer exists', str(self), str(self.__class__) + ) + + tree_id = self.tree_id + parent = getattr(self, self.NODE_PARENT_KEY, None) + + # When deleting a top level node with multiple children, + # we need to assign a new tree_id to each child node + # otherwise they will all have the same tree_id (which is not allowed) + lower_trees = [] + + if not parent: # No parent, which means this is a top-level node + for child in self.get_children(): + # Store a flattened list of node IDs for each of the lower trees + nodes = list( + child + .get_descendants(include_self=True) + .values_list('pk', flat=True) + .distinct() + ) + lower_trees.append(nodes) + + # 1. Update nodes and items under the current node + self.handle_tree_delete( + delete_children=delete_children, delete_items=delete_items + ) + + # 2. Delete *this* node + super().delete(*args, **kwargs) + + # A set of tree_id values which need to be rebuilt + trees = set() + + if tree_id: + # If this node had a tree_id, we need to rebuild that tree + trees.add(tree_id) + + # Did we delete a top-level node? + next_tree_id = self.getNextTreeID() + + # If there is only one sub-tree, it can retain the same tree_id value + for tree in lower_trees[1:]: + # Bulk update the tree_id for all lower nodes + lower_nodes = self.__class__.objects.filter(pk__in=tree) + lower_nodes.update(tree_id=next_tree_id) + trees.add(next_tree_id) + next_tree_id += 1 + + # 3. Rebuild the model tree(s) as required + self.__class__.rebuild_trees(trees) + + def handle_tree_delete(self, delete_children=False, delete_items=False): + """Delete a single instance of the tree, based on provided kwargs. + + Removing a tree "node" from the database must be considered carefully, + based on what the user intends for any items which exist *under* that node. + + - "children" are any nodes (of the same type) which exist *under* this node (e.g. PartCategory) + - "items" are any items (of a different type) which exist *under* this node (e.g. Part) + + Arguments: + delete_children: If True, delete all child items + delete_items: If True, delete all items associated with this node + + There are multiple scenarios we can consider here: + + A) delete_children = True and delete_items = True + B) delete_children = True and delete_items = False + C) delete_children = False and delete_items = True + D) delete_children = False and delete_items = False + + Note: re-parenting uses audited_update(), so that the change is recorded + for audited models (it falls back to a plain update() otherwise). + """ + from audit.helpers import audited_update + + child_nodes = self.get_descendants(include_self=False) + + # Case A: Delete all child items, and all child nodes. + # - Delete all items at any lower level + # - Delete all descendant nodes + if delete_children and delete_items: + self.delete_items(cascade=True) + self.delete_nodes(child_nodes) + + # Case B: Delete all child nodes, but move all child items up to the parent + # - Move all items at any lower level to the parent of this item + # - Delete all descendant nodes + elif delete_children and not delete_items: + if items := self.get_items(cascade=True): + parent = getattr(self, self.NODE_PARENT_KEY, None) + audited_update(items, **{self.ITEM_PARENT_KEY: parent}) + self.delete_nodes(child_nodes) + + # Case C: Delete all child items, but keep all child nodes + # - Remove all items directly associated with this node + # - Move any direct child nodes up one level + elif not delete_children and delete_items: + self.delete_items(cascade=False) + parent = getattr(self, self.NODE_PARENT_KEY, None) + audited_update(self.get_children(), **{self.NODE_PARENT_KEY: parent}) + + # Case D: Keep all child items, and keep all child nodes + # - Move all items directly associated with this node up one level + # - Move any direct child nodes up one level + elif not delete_children and not delete_items: + parent = getattr(self, self.NODE_PARENT_KEY, None) + if items := self.get_items(cascade=False): + audited_update(items, **{self.ITEM_PARENT_KEY: parent}) + audited_update(self.get_children(), **{self.NODE_PARENT_KEY: parent}) + + def delete_nodes(self, nodes): + """Delete a set of nodes from the tree. + + 1. First, set the "parent" value for selected nodes to None + 2. Then, perform bulk deletion of selected nodes + + Step 1. is required because we cannot guarantee the order-of-operations in the db backend + + Arguments: + nodes: A queryset of nodes to delete + """ + nodes.update(**{self.NODE_PARENT_KEY: None}) + nodes.delete() + + def api_instance_filters(self): + """Instance filters for InvenTreeTree models.""" + return {self.NODE_PARENT_KEY: {'exclude_tree': self.pk}} + + def save(self, *args, **kwargs): + """Custom save method for InvenTreeTree abstract model.""" + db_instance = None + + parent = getattr(self, self.NODE_PARENT_KEY, None) + + if not self.tree_id: + if parent: + # If we have a parent, use the parent's tree_id + self.tree_id = parent.tree_id + self.level = parent.level + 1 + else: + # Otherwise, we need to generate a new tree_id + self.tree_id = self.getNextTreeID() + + if self.pk: + try: + db_instance = self.get_db_instance() + except self.__class__.DoesNotExist: + # If the instance does not exist, we cannot get the db instance + db_instance = None + try: + super().save(*args, **kwargs) + except InvalidMove: + # Provide better error for parent selection + raise ValidationError({self.NODE_PARENT_KEY: _('Invalid choice')}) + + trees = set() + + parent = getattr(self, self.NODE_PARENT_KEY, None) + + if db_instance: + # If the tree_id or parent has changed, we need to rebuild the tree + if getattr(db_instance, self.NODE_PARENT_KEY) != parent: + trees.add(db_instance.tree_id) + if db_instance.tree_id != self.tree_id: + trees.add(self.tree_id) + trees.add(db_instance.tree_id) + elif parent: + # New instance, so we need to rebuild the tree (if it has a parent) + trees.add(self.tree_id) + + # Flag to indicate that a tree rebuild task was triggered by this save + self._tree_rebuild_offloaded = False + + if len(trees) > 0: + # Offload the tree rebuild(s) to the background worker. + # Note that repeated calls are de-duplicated (per tree), + # so a bulk operation results in a single rebuild per affected tree. + ran_sync = self.__class__.offload_tree_rebuild(trees) + self._tree_rebuild_offloaded = True + + if ran_sync: + # The tree was rebuilt synchronously, so refresh the instance + try: + self.refresh_from_db() + except TransactionManagementError: + # If we are inside a transaction block, we cannot refresh from db + pass + except Exception as e: + # Any other error is unexpected + InvenTree.sentry.report_exception(e) + InvenTree.exceptions.log_error(f'{self.__class__.__name__}.save') + + @classmethod + def offload_tree_rebuild(cls, tree_ids) -> bool: + """Offload a rebuild of the specified trees to the background worker. + + - The tree structure (and pathstring values, where applicable) are rebuilt for each tree + - If the background worker is not running, the rebuild is performed synchronously + - Identical pending tasks are skipped, so repeated calls (e.g. during a bulk + operation) result in (at most) a single queued rebuild per affected tree + + Returns: + bool: True if any rebuild was performed synchronously (in the calling thread) + """ + from InvenTree.tasks import offload_task + + ran_sync = False + + for tree_id in tree_ids: + if tree_id: + result = offload_task( + 'InvenTree.tasks.rebuild_model_tree', cls._meta.label_lower, tree_id + ) + + if result is True: + # offload_task returns True if the task ran synchronously + ran_sync = True + + return ran_sync + + @classmethod + def rebuild_trees(cls, tree_ids) -> None: + """Rebuild the specified trees, with fallback to a full rebuild. + + - Perform a partial rebuild for each provided tree_id + - If any partial rebuild fails, rebuild the entire tree (expensive!!!) + """ + result = True + + for tree_id in tree_ids: + if tree_id and not cls.partial_rebuild(tree_id): + result = False + + if not result: + # Rebuild the entire tree (expensive!!!) + cls.objects.rebuild() + + @classmethod + def partial_rebuild(cls, tree_id: int) -> bool: + """Perform a partial rebuild of the tree structure. + + If a failure occurs, log the error and return False. + """ + try: + cls.objects.partial_rebuild(tree_id) + return True + except Exception as e: + # This is a critical error, explicitly report to sentry + InvenTree.sentry.report_exception(e) + + InvenTree.exceptions.log_error(f'{cls.__name__}.partial_rebuild') + logger.exception( + 'Failed to rebuild tree <%s> for %s: %s', tree_id, cls.__name__, e + ) + return False + + def delete_items(self, cascade: bool = False): + """Delete any 'items' which exist under this node in the tree. + + - Note that an 'item' is an instance of a different model class. + - Not all tree structures will have items associated with them. + """ + if items := self.get_items(cascade=cascade): + items.delete() + + def get_items(self, cascade: bool = False): + """Return a queryset of items which exist *under* this node in the tree. + + - For a StockLocation instance, this would be a queryset of StockItem objects + - For a PartCategory instance, this would be a queryset of Part objects + + The default implementation returns None, indicating that no items exist under this node. + """ + return None + + def getUniqueParents(self) -> QuerySet: + """Return a flat set of all parent items that exist above this node.""" + return self.get_ancestors() + + def getUniqueChildren(self, include_self=True) -> QuerySet: + """Return a flat set of all child items that exist under this node.""" + return self.get_descendants(include_self=include_self) + + @property + def has_children(self) -> bool: + """True if there are any children under this item.""" + return self.getUniqueChildren(include_self=False).count() > 0 + + @classmethod + def getNextTreeID(cls) -> int: + """Return the next available tree_id for this model class.""" + instance = cls.objects.order_by('-tree_id').first() + + if instance: + return instance.tree_id + 1 + else: + return 1 diff --git a/src/backend/InvenTree/generic/models/internal.py b/src/backend/InvenTree/generic/models/internal.py new file mode 100644 index 0000000000..e14ef7a789 --- /dev/null +++ b/src/backend/InvenTree/generic/models/internal.py @@ -0,0 +1,91 @@ +"""Internal model mixins for building InvenTree models.""" + + +class InvenTreePermissionCheckMixin: + """Provides an abstracted class for managing permissions against related fields.""" + + @classmethod + def check_related_permission(cls, permission, user) -> bool: + """Check if the user has permission to perform the specified action on the attachment. + + The default implementation runs a permission check against *this* model class, + but this can be overridden in the implementing class if required. + + Arguments: + permission: The permission to check (add / change / view / delete) + user: The user to check against + + Returns: + bool: True if the user has permission, False otherwise + """ + perm = f'{cls._meta.app_label}.{permission}_{cls._meta.model_name}' + return user.has_perm(perm) + + +class ContentTypeMixin: + """Mixin class which supports retrieval of the ContentType for a model instance.""" + + @classmethod + def get_content_type(cls): + """Return the ContentType object associated with this model.""" + from django.contrib.contenttypes.models import ContentType + + return ContentType.objects.get_for_model(cls) + + +class DiffMixin: + """Mixin which can be used to determine which fields have changed, compared to the instance saved to the database.""" + + def get_db_instance(self): + """Return the instance of the object saved in the database. + + Returns: + object: Instance of the object saved in the database + """ + if self.pk: + try: + return self.__class__.objects.get(pk=self.pk) + except self.__class__.DoesNotExist: + pass + + return None + + def get_field_deltas(self): + """Return a dict of field deltas. + + Compares the current instance with the instance saved in the database, + and returns a dict of fields which have changed. + + Returns: + dict: Dict of field deltas + """ + db_instance = self.get_db_instance() + + if db_instance is None: + return {} + + deltas = {} + + for field in self._meta.fields: + if field.name == 'id': + continue + + if field.is_relation: + # Compare the raw FK id first (no query) - only dereference to the + # full related object (one query each side) if it actually differs. + # In the common case (unchanged FK) this avoids two full-object + # fetches per relational field for every single save() call. + if getattr(self, field.attname) == getattr(db_instance, field.attname): + continue + + if getattr(self, field.name) != getattr(db_instance, field.name): + deltas[field.name] = { + 'old': getattr(db_instance, field.name), + 'new': getattr(self, field.name), + } + + return deltas + + def has_field_changed(self, field_name): + """Determine if a particular field has changed.""" + return field_name in self.get_field_deltas() diff --git a/src/backend/InvenTree/generic/models/modelmixins.py b/src/backend/InvenTree/generic/models/modelmixins.py new file mode 100644 index 0000000000..1c070955ae --- /dev/null +++ b/src/backend/InvenTree/generic/models/modelmixins.py @@ -0,0 +1,1347 @@ +"""Generic models which provide extra functionality over base Django model types.""" + +from collections.abc import Callable +from datetime import datetime +from string import Formatter +from typing import Any, Optional + +from django.contrib.contenttypes.fields import GenericRelation +from django.contrib.contenttypes.models import ContentType +from django.core.exceptions import ValidationError +from django.db import models, transaction +from django.db.models import QuerySet +from django.urls import resolve +from django.utils.translation import gettext_lazy as _ + +import structlog +from mptt.models import TreeForeignKey +from rest_framework.exceptions import PermissionDenied +from stdimage.models import StdImageField +from taggit.managers import TaggableManager + +import common.settings +import InvenTree.format +import InvenTree.helpers +import report.mixins +from generic.modelfeatures import ModelFeatureMixin + +from .internal import DiffMixin, InvenTreePermissionCheckMixin + +logger = structlog.get_logger('inventree') + + +class InvenTreePluginValidationMixin(DiffMixin): + """Mixin class which exposes the model instance to plugin validation. + + Any model class which inherits from this mixin will be exposed to the plugin validation system. + """ + + def should_plugin_validate(self): + """Return True if this model instance should be validated by plugins. + + The default implementation returns True, but this can be overridden in the implementing class if required. + """ + from InvenTree.ready import isReadOnlyCommand + + # Prevent plugin validation when importing or exporting data + return not isReadOnlyCommand() + + def run_plugin_validation(self): + """Throw this model against the plugin validation interface.""" + from plugin import PluginMixinEnum, registry + + if not self.should_plugin_validate(): + return + + deltas = self.get_field_deltas() + + for plugin in registry.with_mixin(PluginMixinEnum.VALIDATION): + try: + if plugin.validate_model_instance(self, deltas=deltas) is True: + return + except ValidationError as exc: + raise exc + except Exception: + # Log the exception to the database + import InvenTree.exceptions + + InvenTree.exceptions.log_error( + 'validate_model_instance', plugin=plugin.slug + ) + raise ValidationError(_('Error running plugin validation')) + + def full_clean(self, *args, **kwargs): + """Run plugin validation on full model clean. + + Note that plugin validation is performed *after* super.full_clean() + """ + super().full_clean(*args, **kwargs) + self.run_plugin_validation() + + def save(self, *args, **kwargs): + """Run plugin validation on model save. + + Note that plugin validation is performed *before* super.save() + """ + self.run_plugin_validation() + super().save(*args, **kwargs) + + def delete(self, *args, **kwargs): + """Run plugin validation on model delete. + + Allows plugins to prevent model instances from being deleted. + + Note: Each plugin may raise a ValidationError to prevent deletion. + """ + from InvenTree.exceptions import log_error + from plugin import PluginMixinEnum, registry + + if self.should_plugin_validate(): + for plugin in registry.with_mixin(PluginMixinEnum.VALIDATION): + try: + plugin.validate_model_deletion(self) + except ValidationError as e: + # Plugin might raise a ValidationError to prevent deletion + raise e + except Exception: + log_error('validate_model_deletion', plugin=plugin.slug) + continue + + super().delete(*args, **kwargs) + + +class InvenTreeMetadataMixin(models.Model): + """Model mixin class which adds a JSON metadata field to a model, for use by any (and all) plugins. + + The intent of this mixin is to provide a metadata field on a model instance, + for plugins to read / modify as required, to store any extra information. + + The assumptions for models implementing this mixin are: + + - The internal InvenTree business logic will make no use of this field + - Multiple plugins may read / write to this metadata field, and not assume they have sole rights + """ + + class Meta: + """Meta for MetadataMixin.""" + + abstract = True + + def save(self, force_insert=False, force_update=False, *args, **kwargs): + """Save the model instance, and perform validation on the metadata field.""" + self.validate_metadata() + if len(args) > 0: + raise TypeError( + 'save() takes no positional arguments anymore' + ) # pragma: no cover + super().save(force_insert=force_insert, force_update=force_update, **kwargs) + + def clean(self, *args, **kwargs): + """Perform model validation on the metadata field.""" + super().clean() + + self.validate_metadata() + + def validate_metadata(self): + """Validate the metadata field.""" + # Ensure that the 'metadata' field is a valid dict object + if self.metadata is None: + self.metadata = {} + + if type(self.metadata) is not dict: + raise ValidationError({ + 'metadata': _('Metadata must be a python dict object') + }) + + metadata = models.JSONField( + blank=True, + null=True, + verbose_name=_('Plugin Metadata'), + help_text=_('JSON metadata field, for use by external plugins'), + ) + + def get_metadata(self, key: str, backup_value=None): + """Finds metadata for this model instance, using the provided key for lookup. + + Args: + key: String key for requesting metadata. e.g. if a plugin is accessing the metadata, the plugin slug should be used + backup_value: Value that should be used if no value is found + + Returns: + Python dict object containing requested metadata. If no matching metadata is found, returns None + """ + if self.metadata is None: + return backup_value + + return self.metadata.get(key, backup_value) + + def set_metadata( + self, key: str, data, commit: bool = True, overwrite: bool = False + ): + """Save the provided metadata under the provided key. + + Args: + key (str): Key for saving metadata + data (Any): Data object to save - must be able to be rendered as a JSON string + commit (bool, optional): If true, existing metadata with the provided key will be overwritten. If false, a merge will be attempted. Defaults to True. + overwrite (bool): If true, delete existing metadata before adding new value + """ + if overwrite or self.metadata is None: + self.metadata = {} + + self.metadata[key] = data + + if commit: + self.save() + + +class InvenTreeReferenceIndexingMixin(models.Model): + """A mixin for keeping track of numerical copies of the "reference" field. + + Here, we attempt to convert a "reference" field value (char) to an integer, + for performing fast natural sorting. + + This requires extra database space (due to the extra table column), + but is required as not all supported database backends provide equivalent casting. + + This mixin adds a field named 'reference_int'. + + - If the 'reference' field can be cast to an integer, it is stored here + - If the 'reference' field *starts* with an integer, it is stored here + - Otherwise, we store zero + """ + + # Name of the global setting which defines the required reference pattern for this model + REFERENCE_PATTERN_SETTING = None + + class Meta: + """Metaclass options. Abstract ensures no database table is created.""" + + abstract = True + + @classmethod + def get_reference_pattern(cls): + """Returns the reference pattern associated with this model. + + This is defined by a global setting object, specified by the REFERENCE_PATTERN_SETTING attribute + """ + # By default, we return an empty string + if cls.REFERENCE_PATTERN_SETTING is None: + return '' + + return common.settings.get_global_setting( + cls.REFERENCE_PATTERN_SETTING, create=False + ).strip() + + @classmethod + def get_reference_context(cls): + """Generate context data for generating the 'reference' field for this class. + + - Returns a python dict object which contains the context data for formatting the reference string. + - The default implementation provides some default context information + - The '?' key is required to accept our wildcard-with-default syntax {?:default} + """ + return {'ref': cls.get_next_reference(), 'date': datetime.now(), '?': '?'} + + @classmethod + def get_most_recent_item(cls): + """Return the item which is 'most recent'. + + In practice, this means the item with the highest reference value + """ + query = cls.objects.all().order_by('-reference_int', '-pk') + + if query.exists(): + return query.first() + return None + + @classmethod + def get_next_reference(cls): + """Return the next available reference value for this particular class.""" + # Find the "most recent" item + latest = cls.get_most_recent_item() + + if not latest: + # No existing items + return 1 + + reference = latest.reference.strip() + + try: + reference = InvenTree.format.extract_named_group( + 'ref', reference, cls.get_reference_pattern() + ) + except Exception: + # If reference cannot be extracted using the pattern, try just the integer value + reference = str(latest.reference_int) + + # Attempt to perform 'intelligent' incrementing of the reference field + incremented = InvenTree.helpers.increment(reference) + + try: + incremented = int(incremented) + except ValueError: + pass + + return incremented + + @classmethod + def generate_reference(cls): + """Generate the next 'reference' field based on specified pattern.""" + + # Based on https://stackoverflow.com/a/57570269/14488558 + class ReferenceFormatter(Formatter): + def format_field(self, value, format_spec): + if isinstance(value, str) and value == '?': + value = format_spec + format_spec = '' + return super().format_field(value, format_spec) + + ref_ptn = cls.get_reference_pattern() + ctx = cls.get_reference_context() + fmt = ReferenceFormatter() + + reference = None + + attempts = set() + + while reference is None: + try: + ref = fmt.format(ref_ptn, **ctx) + + if ref in attempts: + # We are stuck in a loop! + reference = ref + break + else: + attempts.add(ref) + + if cls.objects.filter(reference=ref).exists(): + # Handle case where we have duplicated an existing reference + ctx['ref'] = InvenTree.helpers.increment(ctx['ref']) + else: + # We have found an 'unused' reference + reference = ref + break + + except Exception: + # If anything goes wrong, return the most recent reference + recent = cls.get_most_recent_item() + reference = recent.reference if recent else '' + + return reference + + @classmethod + def validate_reference_pattern(cls, pattern): + """Ensure that the provided pattern is valid.""" + ctx = cls.get_reference_context() + + try: + info = InvenTree.format.parse_format_string(pattern) + except Exception as exc: + raise ValidationError({ + 'value': _('Improperly formatted pattern') + ': ' + str(exc) + }) + + # Check that only 'allowed' keys are provided + for key in info: + if key not in ctx: + raise ValidationError({ + 'value': _('Unknown format key specified') + f": '{key}'" + }) + + # Check that the 'ref' variable is specified + if 'ref' not in info: + raise ValidationError({ + 'value': _('Missing required format key') + ": 'ref'" + }) + + @classmethod + def validate_reference_field(cls, value): + """Check that the provided 'reference' value matches the requisite pattern.""" + pattern = cls.get_reference_pattern() + + value = str(value).strip() + + if len(value) == 0: + raise ValidationError(_('Reference field cannot be empty')) + + # An 'empty' pattern means no further validation is required + if not pattern: + return + + if not InvenTree.format.validate_string(value, pattern): + raise ValidationError( + _('Reference must match required pattern') + ': ' + pattern + ) + + # Check that the reference field can be rebuild + return cls.rebuild_reference_field(value, validate=True) + + @classmethod + def rebuild_reference_field(cls, reference, validate=False): + """Extract integer out of reference for sorting. + + If the 'integer' portion is buried somewhere 'within' the reference, + we can first try to extract it using the pattern. + + Example: + reference - BO-123-ABC + pattern - BO-{ref}-??? + extracted - 123 + + If we cannot extract using the pattern for some reason, fallback to the entire reference + """ + try: + # Extract named group based on provided pattern + reference = InvenTree.format.extract_named_group( + 'ref', reference, cls.get_reference_pattern() + ) + except Exception: + pass + + reference_int = InvenTree.helpers.extract_int(reference) + + if validate and reference_int > models.BigIntegerField.MAX_BIGINT: + raise ValidationError({'reference': _('Reference number is too large')}) + + return reference_int + + reference_int = models.BigIntegerField(default=0) + + +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 + when the 'audit' app is loaded (see audit.registry). + + Attributes: + AUDIT_INCLUDE_FIELDS: If specified, *only* these fields are recorded (e.g. user-editable fields of a cache model) + AUDIT_EXCLUDE_FIELDS: Fields which are never recorded (merged with a base set, see audit.registry) + AUDIT_MASK_FIELDS: Fields whose values are masked (the change is recorded, the value is not) + AUDIT_M2M_FIELDS: Many-to-many fields which are tracked + AUDIT_PARENT_FIELD: Name of the field which links to the "parent" object (e.g. 'order' for a line item) + AUDIT_VIEW_RESTRICTION: Restrict reading audit history to 'staff' or 'superuser' users (or None) + AUDIT_REQUIRE_PARENT_PERMISSION: Entries are only visible to users who can view the *parent* model + (for models whose access is determined by the linked object, e.g. attachments) + AUDIT_EVENT_TYPES: Enumeration of named event types which can be recorded against this model + (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, ...] = () + AUDIT_M2M_FIELDS: tuple[str, ...] = () + AUDIT_PARENT_FIELD: Optional[str] = None + AUDIT_VIEW_RESTRICTION: Optional[str] = None + AUDIT_REQUIRE_PARENT_PERMISSION: bool = False + AUDIT_EVENT_TYPES: Optional[type] = None + + def get_audit_parent(self): + """Return the "parent" object for audit log entries against this instance. + + Audit entries linked to a parent are included in the history of that parent + (e.g. changes to line items are shown against the order). + """ + if self.AUDIT_PARENT_FIELD: + return getattr(self, self.AUDIT_PARENT_FIELD, None) + + return None + + def get_audit_parent_reference(self) -> Optional[tuple[Any, str]]: + """Return a (ContentType, pk) reference to the "parent" object (or None). + + Override this (rather than get_audit_parent) where the parent can be identified + without fetching it from the database (e.g. generic model_type / model_id links). + """ + from django.contrib.contenttypes.models import ContentType + + # Resolve a foreign key parent from its ID, without fetching the related object + if self.AUDIT_PARENT_FIELD: + field = self._meta.get_field(self.AUDIT_PARENT_FIELD) + + if field.many_to_one or field.one_to_one: + parent_id = getattr(self, field.attname) + + if parent_id is None: + return None + + return ContentType.objects.get_for_model(field.related_model), str( + parent_id + ) + + if parent := self.get_audit_parent(): + return ContentType.objects.get_for_model(parent), str(parent.pk) + + return None + + def should_audit(self) -> bool: + """Return False to skip recording audit entries for this instance. + + Used where only some rows of a model are of interest + (e.g. settings which are written automatically by the system). + """ + return True + + def audit_always(self) -> bool: + """Return True to record audit entries for this instance, even if the audit log is disabled. + + Used for changes which must always be recorded (e.g. disabling the audit log itself). + """ + return False + + def is_audit_masked(self) -> bool: + """Return True if *all* values recorded against this instance must be masked. + + Used where sensitivity depends on the row rather than the field + (e.g. a 'protected' setting value). + """ + return False + + +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.""" + + abstract = True + + # Define a reverse relation to the Parameter model + parameters_list = GenericRelation( + 'common.Parameter', content_type_field='model_type', object_id_field='model_id' + ) + + @staticmethod + def annotate_parameters(queryset: QuerySet) -> QuerySet: + """Annotate a queryset with pre-fetched parameters. + + Args: + queryset: Queryset to annotate + + Returns: + Annotated queryset + """ + return queryset.prefetch_related( + 'parameters_list', + 'parameters_list__model_type', + 'parameters_list__updated_by', + 'parameters_list__template', + 'parameters_list__template__model_type', + ) + + @property + @report.mixins.report_attribute() + def parameters(self) -> report.mixins.QuerySet: + """Return a QuerySet containing all the Parameter instances for this model. + + This will return pre-fetched data if available (i.e. in a serializer context). + """ + # Check the query cache for pre-fetched parameters + if cache := getattr(self, '_prefetched_objects_cache', None): + if 'parameters_list' in cache: + return cache['parameters_list'] + + return self.parameters_list.all().prefetch_related('template') + + def delete(self, *args, **kwargs): + """Handle the deletion of a model instance. + + Before deleting the model instance, delete any associated parameters. + """ + self.parameters_list.all().delete() + super().delete(*args, **kwargs) + + @transaction.atomic + def copy_parameters_from(self, other, clear=True, **kwargs): + """Copy all parameters from another model instance. + + Arguments: + other: The other model instance to copy parameters from + clear: If True, clear existing parameters before copying + **kwargs: Additional keyword arguments to pass to the Parameter constructor + """ + import common.models + + if clear: + self.parameters_list.all().delete() + + parameters = [] + + content_type = ContentType.objects.get_for_model(self.__class__) + + # Skip any parameters which are linked to a template with a uniqueness requirement, + # as copying these values would create conflicting (duplicate) values + copyable_parameters = [ + parameter + for parameter in other.parameters.all().select_related('template') + if parameter.template.unique + == common.models.ParameterTemplate.UniqueOptions.NONE + ] + + template_ids = [parameter.template.pk for parameter in copyable_parameters] + + # Remove all conflicting parameters first + self.parameters_list.filter(template__pk__in=template_ids).delete() + + for parameter in copyable_parameters: + parameter.pk = None + parameter.model_id = self.pk + parameter.model_type = content_type + + parameters.append(parameter) + + if len(parameters) > 0: + from audit.helpers import audited_bulk_create + + audited_bulk_create(common.models.Parameter, parameters) + + def get_parameter(self, name: str): + """Return a Parameter instance for the given parameter name. + + Args: + name: Name of the parameter template + + Returns: + Parameter instance if found, else None + """ + return self.parameters_list.filter(template__name=name).first() + + def get_parameters(self) -> QuerySet: + """Return all Parameter instances for this model.""" + return ( + self.parameters_list + .all() + .prefetch_related('template', 'model_type') + .order_by('template__name') + ) + + def parameters_map(self) -> dict: + """Return a map (dict) of parameter values associated with this Part instance, of the form. + + Example: + { + "name_1": "value_1", + "name_2": "value_2", + } + """ + params = {} + + for parameter in self.parameters.all().prefetch_related('template'): + params[parameter.template.name] = parameter.data + + return params + + def check_parameter_delete(self, parameter) -> bool: + """Run a check to determine if the provided parameter can be deleted. + + The default implementation always returns True, but this can be overridden in the implementing class. + """ + return True + + def check_parameter_save(self, parameter) -> bool: + """Run a check to determine if the provided parameter can be saved. + + The default implementation always returns True, but this can be overridden in the implementing class. + """ + return True + + +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.""" + + abstract = True + + # Define a reverse relation to the Note model + notes_list = GenericRelation( + 'common.Note', content_type_field='model_type', object_id_field='model_id' + ) + + @property + def notes(self) -> QuerySet: + """Return a queryset containing all notes for this model.""" + # Check the query cache for pre-fetched parameters + if cache := getattr(self, '_prefetched_objects_cache', None): + if 'notes_list' in cache: + return cache['notes_list'] + + return self.notes_list.all() + + def delete(self, *args, **kwargs): + """Handle the deletion of a model instance. + + Before deleting the model instance, delete any associated notes. + """ + self.notes_list.all().delete() + super().delete(*args, **kwargs) + + @transaction.atomic + def copy_notes_from(self, other, **kwargs): + """Copy all notes from another model instance. + + Arguments: + other: The other model instance to copy notes from + """ + import os + + from django.core.files.base import ContentFile + + import common.models + + content_type = ContentType.objects.get_for_model(self.__class__) + + # Prefetch each note's images in a single extra query, rather than + # one 'images.all()' query per note. + # + # Sort so primary note is saved last — Note.save() promotes the last + # note saved with primary=True, which correctly mirrors the source. + # This (and the resulting demotion of sibling notes) is real business + # logic in Note.save(), so notes must still be saved one at a time, + # in this order - unlike common.migrations.0051's data migration, + # which bulk_create()s notes directly, this can't do the same: that + # migration operates on a historical model with no custom + # save()/clean() methods at all, so there's no primary-flag logic to + # preserve there in the first place. + source_notes = sorted( + other.notes.all().prefetch_related('images'), key=lambda n: n.primary + ) + + for source_note in source_notes: + new_note = common.models.Note( + model_type=content_type, + model_id=self.pk, + primary=source_note.primary, + title=source_note.title, + description=source_note.description, + content=source_note.content, + ) + new_note.save() + + # Read each source image's file data and write it to storage up front, + # then bulk_create() all of this note's NotesImage rows in one INSERT + # instead of one save() per image - unlike Note, NotesImage has no + # save()-time business logic, so this is safe to batch. + new_images = [] + + for img in source_note.images.all(): + if not img.image: + continue + + old_url = img.image.url + filename = os.path.basename(img.image.name) + + try: + img.image.open('rb') + data = img.image.read() + finally: + img.image.close() + + new_img = common.models.NotesImage(note=new_note, user=img.user) + # save=False: still writes the file to storage (and assigns the + # resulting name/url), but defers the NotesImage row itself to + # the bulk_create() below + new_img.image.save(filename, ContentFile(data), save=False) + new_images.append((old_url, new_img)) + + if new_images: + common.models.NotesImage.objects.bulk_create([ + new_img for _, new_img in new_images + ]) + + content_updated = False + + for old_url, new_img in new_images: + if old_url in new_note.content: + new_note.content = new_note.content.replace( + old_url, new_img.image.url + ) + content_updated = True + + if content_updated: + new_note.save() + + @property + def primary_note(self): + """Return the primary note for this model instance, if it exists.""" + return self.notes_list.all().order_by('-primary').first() + + def get_note(self, title: Optional[str] = None): + """Return a Note instance for the given note title. + + Arguments: + title: Title of the note to retrieve. If None, returns the primary note (if it exists) + """ + notes = self.notes_list.all().order_by('-primary') + + if title: + notes = notes.filter(title=title) + + return notes.first() + + def check_note_delete(self, note) -> bool: + """Run a check to determine if the provided note can be deleted. + + The default implementation always returns True, but this can be overridden in the implementing class. + """ + return True + + def check_note_save(self, note) -> bool: + """Run a check to determine if the provided note can be saved. + + The default implementation always returns True, but this can be overridden in the implementing class. + """ + return True + + +class InvenTreeAttachmentMixin(ModelFeatureMixin, InvenTreePermissionCheckMixin): + """Provides an abstracted class for managing file attachments. + + Links the implementing model to the common.models.Attachment table, + and provides the following methods: + + - 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. + + Before deleting the model instance, delete any associated attachments. + """ + for attachment in list(self.attachments.all()): + attachment.delete() + + super().delete(*args, **kwargs) + + @property + @report.mixins.report_attribute() + def attachments(self) -> report.mixins.QuerySet: + """Return a queryset containing all attachments for this model.""" + return self.attachments_for_model().filter(model_id=self.pk) + + def attachments_for_model(self) -> QuerySet: + """Return all attachments for this model class.""" + from common.models import Attachment + + model_type = self.__class__.__name__.lower() + return Attachment.objects.filter(model_type=model_type) + + def create_attachment(self, attachment=None, link=None, comment='', **kwargs): + """Create an attachment / link for this model.""" + from common.models import Attachment + + kwargs['attachment'] = attachment + kwargs['link'] = link + kwargs['comment'] = comment + kwargs['model_type'] = self.__class__.__name__.lower() + kwargs['model_id'] = self.pk + + Attachment.objects.create(**kwargs) + + +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: + + - image : An image field for storing an image + """ + + MODEL_FEATURE = 'org.inventree.i.modelfeatures.image' + + IMAGE_RENAME: Callable | None = None + + class Meta: + """Metaclass options for this mixin. + + Note: abstract must be true, as this is only a mixin, not a separate table + """ + + abstract = True + + def __init__(self, *args: Any, **kwargs: Any) -> None: + """Custom init method for InvenTreeImageMixin to ensure IMAGE_RENAME is implemented.""" + if self.IMAGE_RENAME is None: + raise NotImplementedError( + 'IMAGE_RENAME must be implemented in the model class' + ) + super().__init__(*args, **kwargs) + + def rename_image(self, filename): + """Rename the uploaded image file using the IMAGE_RENAME function.""" + return self.IMAGE_RENAME(filename) + + image = StdImageField( + upload_to=rename_image, + null=True, + blank=True, + variations={'thumbnail': (128, 128), 'preview': (256, 256)}, + delete_orphans=False, + verbose_name=_('Image'), + ) + + def get_image_url(self) -> str: + """Return the URL of the image for this object.""" + if self.image: + return InvenTree.helpers.getMediaUrl(self.image) + return InvenTree.helpers.getBlankImage() + + @property + @report.mixins.report_attribute() + def image_url(self) -> str: + """Return the URL of the image for this object.""" + return self.get_image_url() + + def get_thumbnail_url(self) -> str: + """Return the URL of the image thumbnail for this object.""" + if self.image: + return InvenTree.helpers.getMediaUrl(self.image, 'thumbnail') + return InvenTree.helpers.getBlankThumbnail() + + @property + @report.mixins.report_attribute() + def thumbnail_url(self) -> str: + """Return the URL of the image thumbnail for this object.""" + return self.get_thumbnail_url() + + +class InvenTreePathStringMixin(models.Model): + """Mixin class for adding a 'pathstring' field to a model class. + + The pathstring is a string representation of the path to this model instance, + which can be used for display purposes. + + The pathstring is automatically generated when the model instance is saved. + """ + + # Field to use for constructing a "pathstring" for the tree + PATH_FIELD = 'name' + + # Extra fields to include in the get_path result. E.g. icon + EXTRA_PATH_FIELDS = [] + + class Meta: + """Metaclass options for this mixin. + + Note: abstract must be true, as this is only a mixin, not a separate table + """ + + abstract = True + + name = models.CharField( + blank=False, max_length=100, verbose_name=_('Name'), help_text=_('Name') + ) + + description = models.CharField( + blank=True, + max_length=250, + verbose_name=_('Description'), + help_text=_('Description (optional)'), + ) + + # When a category is deleted, graft the children onto its parent + parent = TreeForeignKey( + 'self', + on_delete=models.DO_NOTHING, + blank=True, + null=True, + verbose_name='parent', + related_name='children', + ) + + # The 'pathstring' field is calculated each time the model is saved + pathstring = models.CharField( + blank=True, max_length=250, verbose_name=_('Path'), help_text=_('Path') + ) + + def save(self, *args, **kwargs): + """Update the pathstring field when saving the model instance.""" + old_pathstring = self.pathstring + + # Rebuild upper first, to ensure the lower nodes are updated correctly + super().save(*args, **kwargs) + + # Determine if a tree rebuild task was already triggered by this save + # (e.g. if the node was re-parented) - if so, the pathstring values + # for any lower nodes are updated by that task + rebuild_offloaded = getattr(self, '_tree_rebuild_offloaded', False) + + # Ensure that the pathstring is correctly constructed + pathstring = self.construct_pathstring(refresh=True) + + if pathstring != old_pathstring: + kwargs.pop('force_insert', None) + kwargs['force_update'] = True + + self.pathstring = pathstring + super().save(*args, **kwargs) + + # Update the pathstring values for any lower nodes, + # by offloading the update to the background worker + if not rebuild_offloaded and self.get_descendant_count() > 0: + self.__class__.offload_tree_rebuild([self.tree_id]) # ty: ignore[invalid-attribute-access] + + def delete(self, *args, **kwargs): + """Custom delete method for PathStringMixin. + + - Before deleting the object, update the pathstring for any child nodes. + - Then, delete the object. + """ + # Ensure that we have the latest version of the database object + try: + self.refresh_from_db() + except self.__class__.DoesNotExist: + # If the object no longer exists, raise a ValidationError + raise ValidationError( + 'Object %s of type %s no longer exists', str(self), str(self.__class__) + ) + + # Store the node ID values for lower nodes, before we delete this one + lower_nodes = self.get_lower_nodes() + + # Delete this node - after which we expect the tree structure will be updated + super().delete(*args, **kwargs) + + # Rebuild the pathstring for lower nodes + self.rebuild_lower_nodes(lower_nodes) + + def __str__(self): + """String representation of a category is the full path to that category.""" + return f'{self.pathstring} - {self.description}' + + def get_lower_nodes(self) -> list[int]: + """Return a list of all lower nodes in the tree.""" + return list( + self.get_descendants(include_self=False).values_list('pk', flat=True) + ) + + def rebuild_lower_nodes(self, lower_nodes: list[int]): + """Rebuild the pathstring for lower nodes in the tree. + + - This is used when the pathstring for this node is updated, and we need to update all lower nodes. + - We use a bulk-update to update the pathstring for all lower nodes in the tree. + """ + nodes = self.__class__.objects.filter(pk__in=lower_nodes) + + nodes_to_update = [] + + for node in nodes: + new_path = node.construct_pathstring() + + if new_path != node.pathstring: + node.pathstring = new_path + nodes_to_update.append(node) + + if len(nodes_to_update) > 0: + self.__class__.objects.bulk_update(nodes_to_update, ['pathstring']) + + @classmethod + def rebuild_tree_pathstring_values(cls, tree_ids) -> None: + """Rebuild the 'pathstring' values for all nodes in the specified trees. + + Each tree is processed in a single pass: + the pathstring for each node is constructed from its parent node, + and any changed values are written back in a single bulk update. + """ + tree_nodes = list(cls.objects.filter(tree_id__in=tree_ids)) + node_map = {node.pk: node for node in tree_nodes} + + # Cache of node ID -> list of path elements (from the top level down) + path_cache: dict[int, list[str]] = {} + + def path_names(node) -> list[str]: + """Construct the path (list of names) for a node, via its parent chain.""" + if node.pk in path_cache: + return path_cache[node.pk] + + names = [str(getattr(node, cls.PATH_FIELD, node.pk))] + + if node.parent_id: + parent = node_map.get(node.parent_id) + + if parent is None: + # Parent node exists outside the selected trees + parent = cls.objects.get(pk=node.parent_id) + node_map[node.parent_id] = parent + + names = [*path_names(parent), *names] + + path_cache[node.pk] = names + return names + + nodes_to_update = [] + + for node in tree_nodes: + pathstring = InvenTree.helpers.constructPathString(path_names(node)) + + if pathstring != node.pathstring: + node.pathstring = pathstring + nodes_to_update.append(node) + + if len(nodes_to_update) > 0: + cls.objects.bulk_update(nodes_to_update, ['pathstring'], batch_size=250) + + def construct_pathstring(self, refresh: bool = False) -> str: + """Construct the pathstring for this tree node. + + Arguments: + refresh: If True, force a refresh of the model instance + """ + if refresh: + # Refresh the model instance from the database + self.refresh_from_db() + + return InvenTree.helpers.constructPathString([ + getattr(item, self.PATH_FIELD, item.pk) for item in self.path + ]) + + def validate_unique(self, exclude=None): + """Validate that this tree instance satisfies our uniqueness requirements. + + Note that a 'unique_together' requirement for ('name', 'parent') is insufficient, + as it ignores cases where parent=None (i.e. top-level items) + """ + super().validate_unique(exclude) + + results = self.__class__.objects.filter( + name=self.name, parent=self.parent + ).exclude(pk=self.pk) + + if results.exists(): + raise ValidationError( + _('Duplicate names cannot exist under the same parent') + ) + + @property + @report.mixins.report_attribute() + def parentpath(self) -> list: + """Construct the parent path of this tree node. + + Returns: + List of category names from the top level to the parent of this category + """ + return list(self.get_ancestors()) + + @property + @report.mixins.report_attribute() + def path(self) -> list: + """Construct the complete part of this tree node. + + e.g. ["Top", "Second", "Third", "This"] + + Returns: + List of category names from the top level to this category + """ + return [*self.parentpath, self] + + def get_path(self) -> list: + """Return a list of element in the item tree. + + Contains the full path to this item, with each entry containing the following data: + + { + pk: , + name: , + } + """ + return [ + { + 'pk': item.pk, + 'name': getattr(item, self.PATH_FIELD, item.pk), + **{k: getattr(item, k, None) for k in self.EXTRA_PATH_FIELDS}, + } + for item in self.path + ] + + +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: + + - tags : A text field for storing comma-separated tags + """ + + MODEL_FEATURE = 'org.inventree.i.modelfeatures.tags' + + class Meta: + """Metaclass options for this mixin. + + Note: abstract must be true, as this is only a mixin, not a separate table + """ + + abstract = True + + tags = TaggableManager(blank=True) + + +class InvenTreeBarcodeMixin(ModelFeatureMixin, models.Model): + """A mixin class for adding barcode functionality to a model class. + + Two types of barcodes are supported: + + - Internal barcodes (QR codes using a strictly defined format) + - External barcodes (assign third party barcode data to a model instance) + + The following fields are added to any model which implements this mixin: + + - barcode_data : Raw data associated with an assigned barcode + - barcode_hash : A 'hash' of the assigned barcode data used to improve matching + + 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. + + Note: abstract must be true, as this is only a mixin, not a separate table + """ + + abstract = True + + barcode_data = models.CharField( + blank=True, + max_length=500, + verbose_name=_('Barcode Data'), + help_text=_('Third party barcode data'), + ) + + barcode_hash = models.CharField( + blank=True, + max_length=128, + verbose_name=_('Barcode Hash'), + help_text=_('Unique hash of barcode data'), + ) + + @classmethod + def barcode_model_type(cls): + """Return the model 'type' for creating a custom QR code.""" + # By default, use the name of the class + return cls.__name__.lower() + + @classmethod + def barcode_model_type_code(cls): + r"""Return a 'short' code for the model type. + + This is used to generate a efficient QR code for the model type. + It is expected to match this pattern: [0-9A-Z $%*+-.\/:]{2} + + Note: Due to the shape constraints (45**2=2025 different allowed codes) + this needs to be explicitly implemented in the model class to avoid collisions. + """ + raise NotImplementedError( + 'barcode_model_type_code() must be implemented in the model class' + ) + + def format_barcode(self, **kwargs): + """Return a string for formatting a QR code for this model instance.""" + from plugin.base.barcodes.helper import generate_barcode + + return generate_barcode(self) + + def format_matched_response(self, user, **kwargs): + """Format a standard response for a matched barcode.""" + # Check permission for this object + from users.permissions import check_user_permission + + if not check_user_permission(user, self, 'view'): + raise PermissionDenied( + _('User does not have permission to view this model') + ) + + data = {'pk': self.pk} + + if hasattr(self, 'get_api_url'): + api_url = self.get_api_url() + data['api_url'] = api_url = f'{api_url}{self.pk}/' + + # Attempt to serialize the object too + try: + match = resolve(api_url) + view_class = match.func.view_class + serializer_class = view_class.serializer_class + serializer = serializer_class(self) + data['instance'] = serializer.data + except Exception: + pass + + if hasattr(self, 'get_absolute_url'): + data['web_url'] = self.get_absolute_url() + + return data + + @property + @report.mixins.report_attribute() + def barcode(self) -> str: + """Format a minimal barcode string (e.g. for label printing).""" + return self.format_barcode() + + @classmethod + def lookup_barcode(cls, barcode_hash: str) -> models.Model: + """Check if a model instance exists with the specified third-party barcode hash.""" + return cls.objects.filter(barcode_hash=barcode_hash).first() + + def assign_barcode( + self, + barcode_hash: Optional[str] = None, + barcode_data: Optional[str] = None, + raise_error: bool = True, + save: bool = True, + ): + """Assign an external (third-party) barcode to this object.""" + # Must provide either barcode_hash or barcode_data + if barcode_hash is None and barcode_data is None: + raise ValueError("Provide either 'barcode_hash' or 'barcode_data'") + + # If barcode_hash is not provided, create from supplier barcode_data + if barcode_hash is None and barcode_data is not None: + barcode_hash = InvenTree.helpers.hash_barcode(barcode_data) + + # Check for existing item + if self.__class__.lookup_barcode(barcode_hash) is not None: + if raise_error: + raise ValidationError(_('Existing barcode found')) + else: + return False + + if barcode_data is not None: + self.barcode_data = barcode_data + + self.barcode_hash = barcode_hash + + if save: + self.save() + + return True + + def unassign_barcode(self): + """Unassign custom barcode from this model.""" + self.barcode_data = '' + self.barcode_hash = '' + + self.save() diff --git a/src/backend/InvenTree/order/migrations/0118_transferorder.py b/src/backend/InvenTree/order/migrations/0118_transferorder.py index ddaf02c8c6..e39ccba6fa 100644 --- a/src/backend/InvenTree/order/migrations/0118_transferorder.py +++ b/src/backend/InvenTree/order/migrations/0118_transferorder.py @@ -1,7 +1,6 @@ # Generated by Django 5.2.11 on 2026-02-27 22:00 import InvenTree.fields -import InvenTree.models import django.core.validators import django.db.models.deletion import generic.states.fields @@ -12,7 +11,8 @@ import order.status_codes import order.validators from django.conf import settings from django.db import migrations, models - +import generic.models.modelmixins +import generic.models.internal class Migration(migrations.Migration): @@ -289,10 +289,10 @@ class Migration(migrations.Migration): bases=( generic.states.states.StatusCodeMixin, generic.states.transition.StateTransitionMixin, - InvenTree.models.InvenTreeAttachmentMixin, - InvenTree.models.InvenTreePermissionCheckMixin, - InvenTree.models.ContentTypeMixin, - InvenTree.models.PluginValidationMixin, + generic.models.modelmixins.InvenTreeAttachmentMixin, + generic.models.internal.InvenTreePermissionCheckMixin, + generic.models.internal.ContentTypeMixin, + generic.models.modelmixins.InvenTreePluginValidationMixin, models.Model, ), ), @@ -422,8 +422,8 @@ class Migration(migrations.Migration): "verbose_name": "Transfer Order Line Item", }, bases=( - InvenTree.models.ContentTypeMixin, - InvenTree.models.PluginValidationMixin, + generic.models.internal.ContentTypeMixin, + generic.models.modelmixins.InvenTreePluginValidationMixin, models.Model, ), ), diff --git a/src/backend/InvenTree/order/models.py b/src/backend/InvenTree/order/models.py index f3209eb227..f81d59853a 100644 --- a/src/backend/InvenTree/order/models.py +++ b/src/backend/InvenTree/order/models.py @@ -25,7 +25,6 @@ from mptt.models import TreeForeignKey import common.models as common_models import InvenTree.helpers -import InvenTree.models import InvenTree.ready import InvenTree.tasks import InvenTree.validators @@ -51,6 +50,16 @@ from company.models import ( SupplierPart, default_internal_company, ) +from generic.models.base import InvenTreeMetadataModel +from generic.models.modelmixins import ( + InvenTreeAttachmentMixin, + InvenTreeAuditMixin, + InvenTreeBarcodeMixin, + InvenTreeNoteMixin, + InvenTreeParameterMixin, + InvenTreeReferenceIndexingMixin, + InvenTreeTagsMixin, +) from generic.states import ( RETURN_VALUE, Deprecations, @@ -96,7 +105,7 @@ from stock.status_codes import StockHistoryCode, StockStatus logger = structlog.get_logger('inventree') -class AuditedOrderMixin(InvenTree.models.InvenTreeAuditMixin): +class AuditedOrderMixin(InvenTreeAuditMixin): """Audit log configuration for order models.""" AUDIT_EXCLUDE_FIELDS = ( @@ -108,7 +117,7 @@ class AuditedOrderMixin(InvenTree.models.InvenTreeAuditMixin): ) -class AuditedLineItemMixin(InvenTree.models.InvenTreeAuditMixin): +class AuditedLineItemMixin(InvenTreeAuditMixin): """Audit log configuration for order line item models. Changes to line items are included in the history of the order. @@ -357,15 +366,14 @@ class TransferOrderReportContext(BaseOrderReportContext, TypedDict): class Order( StatusCodeMixin, StateTransitionMixin, - InvenTree.models.InvenTreeParameterMixin, - InvenTree.models.InvenTreeAttachmentMixin, - InvenTree.models.InvenTreeBarcodeMixin, - InvenTree.models.InvenTreeNoteMixin, - InvenTree.models.InvenTreeTagsMixin, + InvenTreeParameterMixin, + InvenTreeAttachmentMixin, + InvenTreeBarcodeMixin, + InvenTreeNoteMixin, + InvenTreeTagsMixin, report.mixins.InvenTreeReportMixin, - InvenTree.models.MetadataMixin, - InvenTree.models.ReferenceIndexingMixin, - InvenTree.models.InvenTreeModel, + InvenTreeReferenceIndexingMixin, + InvenTreeMetadataModel, ): """Abstract model for an order. @@ -2185,7 +2193,7 @@ def after_save_sales_order(sender, instance: SalesOrder, created: bool, **kwargs SalesOrderShipment.objects.create(order=instance, reference='1') -class OrderLineItem(InvenTree.models.InvenTreeMetadataModel): +class OrderLineItem(InvenTreeMetadataModel): """Abstract model for an order line item. Attributes: @@ -2747,15 +2755,14 @@ class SalesOrderShipmentReportContext(report.mixins.BaseReportContext, TypedDict class SalesOrderShipment( - InvenTree.models.InvenTreeAuditMixin, - InvenTree.models.InvenTreeParameterMixin, - InvenTree.models.InvenTreeAttachmentMixin, - InvenTree.models.InvenTreeBarcodeMixin, - InvenTree.models.InvenTreeNoteMixin, - InvenTree.models.InvenTreeTagsMixin, + InvenTreeAuditMixin, + InvenTreeParameterMixin, + InvenTreeAttachmentMixin, + InvenTreeBarcodeMixin, + InvenTreeNoteMixin, + InvenTreeTagsMixin, report.mixins.InvenTreeReportMixin, - InvenTree.models.MetadataMixin, - InvenTree.models.InvenTreeModel, + InvenTreeMetadataModel, ): """The SalesOrderShipment model represents a physical shipment made against a SalesOrder. diff --git a/src/backend/InvenTree/part/migrations/0143_alter_part_image.py b/src/backend/InvenTree/part/migrations/0143_alter_part_image.py index 89565df62a..84e5066673 100644 --- a/src/backend/InvenTree/part/migrations/0143_alter_part_image.py +++ b/src/backend/InvenTree/part/migrations/0143_alter_part_image.py @@ -1,8 +1,8 @@ # Generated by Django 5.2.7 on 2025-11-04 20:59 -import InvenTree.models import stdimage.models from django.db import migrations +import generic.models.modelmixins class Migration(migrations.Migration): @@ -15,6 +15,6 @@ class Migration(migrations.Migration): migrations.AlterField( model_name='part', name='image', - field=stdimage.models.StdImageField(blank=True, force_min_size=False, null=True, upload_to=InvenTree.models.InvenTreeImageMixin.rename_image, variations={'preview': (256, 256), 'thumbnail': (128, 128)}, verbose_name='Image'), + field=stdimage.models.StdImageField(blank=True, force_min_size=False, null=True, upload_to=generic.models.modelmixins.InvenTreeImageMixin.rename_image, variations={'preview': (256, 256), 'thumbnail': (128, 128)}, verbose_name='Image'), ), ] diff --git a/src/backend/InvenTree/part/models.py b/src/backend/InvenTree/part/models.py index 3a2854f76b..ede4c29e47 100644 --- a/src/backend/InvenTree/part/models.py +++ b/src/backend/InvenTree/part/models.py @@ -34,7 +34,6 @@ import company.models import InvenTree.conversion import InvenTree.fields import InvenTree.helpers -import InvenTree.models import InvenTree.ready import InvenTree.tasks import part.helpers as part_helpers @@ -46,6 +45,19 @@ from build import models as BuildModels from build.status_codes import BuildStatusGroups from common.icons import validate_icon from common.settings import get_global_setting +from generic.models.base import InvenTreeMetadataModel, InvenTreeTree +from generic.models.modelmixins import ( + InvenTreeAttachmentMixin, + InvenTreeAuditMixin, + InvenTreeBarcodeMixin, + InvenTreeImageMixin, + InvenTreeMetadataMixin, + InvenTreeNoteMixin, + InvenTreeParameterMixin, + InvenTreePathStringMixin, + InvenTreePluginValidationMixin, + InvenTreeTagsMixin, +) from InvenTree import helpers, validators from InvenTree.exceptions import log_error from InvenTree.fields import InvenTreeURLField @@ -62,12 +74,12 @@ logger = structlog.get_logger('inventree') class PartCategory( - InvenTree.models.InvenTreeAuditMixin, - InvenTree.models.PluginValidationMixin, - InvenTree.models.InvenTreeParameterMixin, - InvenTree.models.MetadataMixin, - InvenTree.models.PathStringMixin, - InvenTree.models.InvenTreeTree, + InvenTreeAuditMixin, + InvenTreePluginValidationMixin, + InvenTreeParameterMixin, + InvenTreeMetadataMixin, + InvenTreePathStringMixin, + InvenTreeTree, ): """PartCategory provides hierarchical organization of Part objects. @@ -348,7 +360,7 @@ def rename_part_image(instance, filename): return os.path.join(base, fname) -class PartCategoryParameterTemplate(InvenTree.models.InvenTreeMetadataModel): +class PartCategoryParameterTemplate(InvenTreeMetadataModel): """A PartCategoryParameterTemplate creates a unique relationship between a PartCategory and a ParameterTemplate. Multiple ParameterTemplate instances can be associated to a PartCategory to drive a default list of parameter templates attached to a Part instance upon creation. @@ -462,17 +474,17 @@ class PartReportContext(report.mixins.BaseReportContext, TypedDict): @cleanup.ignore class Part( - InvenTree.models.InvenTreeAuditMixin, - InvenTree.models.PluginValidationMixin, - InvenTree.models.InvenTreeParameterMixin, - InvenTree.models.InvenTreeAttachmentMixin, - InvenTree.models.InvenTreeBarcodeMixin, - InvenTree.models.InvenTreeNoteMixin, - InvenTree.models.InvenTreeTagsMixin, + InvenTreeAuditMixin, + InvenTreePluginValidationMixin, + InvenTreeParameterMixin, + InvenTreeAttachmentMixin, + InvenTreeBarcodeMixin, + InvenTreeNoteMixin, + InvenTreeTagsMixin, report.mixins.InvenTreeReportMixin, - InvenTree.models.InvenTreeImageMixin, - InvenTree.models.MetadataMixin, - InvenTree.models.InvenTreeTree, + InvenTreeImageMixin, + InvenTreeMetadataMixin, + InvenTreeTree, ): """The Part object represents an abstract part, the 'concept' of an actual entity. @@ -2737,7 +2749,7 @@ class PartCategoryStar(models.Model): ) -class PartTestTemplate(InvenTree.models.InvenTreeMetadataModel): +class PartTestTemplate(InvenTreeMetadataModel): """A PartTestTemplate defines a 'template' for a test which is required to be run against a StockItem (an instance of the Part). The test template applies "recursively" to part variants, allowing tests to be @@ -2902,11 +2914,7 @@ class PartTestTemplate(InvenTree.models.InvenTreeMetadataModel): return [x.strip() for x in self.choices.split(',') if x.strip()] -class BomItem( - InvenTree.models.InvenTreeAuditMixin, - InvenTree.models.MetadataMixin, - InvenTree.models.InvenTreeModel, -): +class BomItem(InvenTreeAuditMixin, InvenTreeMetadataModel): """A BomItem links a part to its component items. A part can have a BOM (bill of materials) which defines @@ -3595,9 +3603,7 @@ def update_pricing_after_delete(sender, instance, **kwargs): pass -class BomItemSubstitute( - InvenTree.models.InvenTreeAuditMixin, InvenTree.models.InvenTreeMetadataModel -): +class BomItemSubstitute(InvenTreeAuditMixin, InvenTreeMetadataModel): """A BomItemSubstitute provides a specification for alternative parts, which can be used in a bill of materials. Attributes: @@ -3684,7 +3690,7 @@ class BomItemSubstitute( ) -class PartRelated(InvenTree.models.InvenTreeMetadataModel): +class PartRelated(InvenTreeMetadataModel): """Store and handle related parts (eg. mating connector, crimps, etc.).""" class Meta: diff --git a/src/backend/InvenTree/plugin/base/barcodes/helper.py b/src/backend/InvenTree/plugin/base/barcodes/helper.py index fcddfcf327..aaff9f511b 100644 --- a/src/backend/InvenTree/plugin/base/barcodes/helper.py +++ b/src/backend/InvenTree/plugin/base/barcodes/helper.py @@ -5,7 +5,7 @@ from typing import cast import structlog import InvenTree.helpers_model -from InvenTree.models import InvenTreeBarcodeMixin +from generic.models.modelmixins import InvenTreeBarcodeMixin logger = structlog.get_logger('inventree') diff --git a/src/backend/InvenTree/plugin/base/barcodes/mixins.py b/src/backend/InvenTree/plugin/base/barcodes/mixins.py index 1e3b84a61d..5f781bf884 100644 --- a/src/backend/InvenTree/plugin/base/barcodes/mixins.py +++ b/src/backend/InvenTree/plugin/base/barcodes/mixins.py @@ -9,8 +9,8 @@ from django.utils.translation import gettext_lazy as _ import structlog from company.models import Company, ManufacturerPart, SupplierPart +from generic.models.modelmixins import InvenTreeBarcodeMixin from InvenTree.exceptions import log_error -from InvenTree.models import InvenTreeBarcodeMixin from order.models import PurchaseOrder from part.models import Part from plugin import PluginMixinEnum diff --git a/src/backend/InvenTree/plugin/builtin/barcodes/inventree_barcode.py b/src/backend/InvenTree/plugin/builtin/barcodes/inventree_barcode.py index 4027344db0..a5366b255f 100644 --- a/src/backend/InvenTree/plugin/builtin/barcodes/inventree_barcode.py +++ b/src/backend/InvenTree/plugin/builtin/barcodes/inventree_barcode.py @@ -13,8 +13,8 @@ from typing import cast from django.utils.translation import gettext_lazy as _ +from generic.models.modelmixins import InvenTreeBarcodeMixin from InvenTree.helpers import hash_barcode -from InvenTree.models import InvenTreeBarcodeMixin from plugin import InvenTreePlugin from plugin.mixins import ( BarcodeMixin, diff --git a/src/backend/InvenTree/plugin/builtin/exporter/parameter_exporter.py b/src/backend/InvenTree/plugin/builtin/exporter/parameter_exporter.py index 0c890d8a8b..8ff0c59399 100644 --- a/src/backend/InvenTree/plugin/builtin/exporter/parameter_exporter.py +++ b/src/backend/InvenTree/plugin/builtin/exporter/parameter_exporter.py @@ -43,7 +43,7 @@ class ParameterExporter(DataExportMixin, InvenTreePlugin): **kwargs, ) -> bool: """Supported if the base model implements the InvenTreeParameterMixin.""" - from InvenTree.models import InvenTreeParameterMixin + from generic.models.modelmixins import InvenTreeParameterMixin return issubclass(model_class, InvenTreeParameterMixin) @@ -57,7 +57,7 @@ class ParameterExporter(DataExportMixin, InvenTreePlugin): def prefetch_queryset(self, queryset): """Ensure that the associated parameters are prefetched.""" - from InvenTree.models import InvenTreeParameterMixin + from generic.models.modelmixins import InvenTreeParameterMixin queryset = InvenTreeParameterMixin.annotate_parameters(queryset) return queryset diff --git a/src/backend/InvenTree/plugin/models.py b/src/backend/InvenTree/plugin/models.py index ced9834ca5..f97c78d738 100644 --- a/src/backend/InvenTree/plugin/models.py +++ b/src/backend/InvenTree/plugin/models.py @@ -12,13 +12,13 @@ from django.urls import reverse from django.utils.translation import gettext_lazy as _ import common.models -import InvenTree.models import plugin.staticfiles +from generic.models.modelmixins import InvenTreeMetadataMixin from plugin import InvenTreePlugin, registry from plugin.events import PluginEvents, trigger_event -class PluginConfig(InvenTree.models.MetadataMixin, models.Model): +class PluginConfig(InvenTreeMetadataMixin, models.Model): """A PluginConfig object holds settings for plugins. Attributes: diff --git a/src/backend/InvenTree/pricing/models.py b/src/backend/InvenTree/pricing/models.py index 72f41a6b0d..56091d6f07 100644 --- a/src/backend/InvenTree/pricing/models.py +++ b/src/backend/InvenTree/pricing/models.py @@ -19,11 +19,11 @@ import common.currency import common.models import InvenTree.fields import InvenTree.helpers -import InvenTree.models import InvenTree.ready import InvenTree.tasks from common.currency import currency_code_default from common.settings import get_global_setting +from generic.models.modelmixins import InvenTreeAuditMixin from InvenTree import validators from InvenTree.cache import get_session_cache, set_session_cache from InvenTree.exceptions import log_error @@ -34,7 +34,7 @@ from part.models import Part logger = structlog.get_logger('inventree') -class PartPricing(InvenTree.models.InvenTreeAuditMixin, common.models.MetaMixin): +class PartPricing(InvenTreeAuditMixin, common.models.MetaMixin): """Model for caching min/max pricing information for a particular Part. It is prohibitively expensive to calculate min/max pricing for a part "on the fly". @@ -851,9 +851,7 @@ class PartPricing(InvenTree.models.InvenTreeAuditMixin, common.models.MetaMixin) ) -class PartSellPriceBreak( - InvenTree.models.InvenTreeAuditMixin, common.models.PriceBreak -): +class PartSellPriceBreak(InvenTreeAuditMixin, common.models.PriceBreak): """Represents a price break for selling this part.""" # Changes to a price break are included in the history of the part @@ -881,9 +879,7 @@ class PartSellPriceBreak( ) -class PartInternalPriceBreak( - InvenTree.models.InvenTreeAuditMixin, common.models.PriceBreak -): +class PartInternalPriceBreak(InvenTreeAuditMixin, common.models.PriceBreak): """Represents a price break for internally selling this part.""" # Changes to a price break are included in the history of the part diff --git a/src/backend/InvenTree/report/migrations/0022_reporttemplate.py b/src/backend/InvenTree/report/migrations/0022_reporttemplate.py index c0c4c01b3f..3a6fbde8e5 100644 --- a/src/backend/InvenTree/report/migrations/0022_reporttemplate.py +++ b/src/backend/InvenTree/report/migrations/0022_reporttemplate.py @@ -1,10 +1,9 @@ # Generated by Django 4.2.11 on 2024-04-21 03:11 -import InvenTree.models +import generic.models.modelmixins import django.core.validators from django.db import migrations, models import report.helpers -import report.models import report.validators @@ -35,6 +34,6 @@ class Migration(migrations.Migration): 'abstract': False, 'unique_together': [('name', 'model_type')] }, - bases=(InvenTree.models.PluginValidationMixin, models.Model), + bases=(generic.models.modelmixins.InvenTreePluginValidationMixin, models.Model), ), ] diff --git a/src/backend/InvenTree/report/migrations/0025_labeltemplate.py b/src/backend/InvenTree/report/migrations/0025_labeltemplate.py index 4ce2babc9f..dd409cef20 100644 --- a/src/backend/InvenTree/report/migrations/0025_labeltemplate.py +++ b/src/backend/InvenTree/report/migrations/0025_labeltemplate.py @@ -1,9 +1,8 @@ # Generated by Django 4.2.11 on 2024-04-22 12:48 -import InvenTree.models +import generic.models.modelmixins import django.core.validators from django.db import migrations, models -import report.models import report.validators @@ -34,6 +33,6 @@ class Migration(migrations.Migration): 'abstract': False, 'unique_together': {('name', 'model_type')}, }, - bases=(InvenTree.models.PluginValidationMixin, models.Model), + bases=(generic.models.modelmixins.InvenTreePluginValidationMixin, models.Model), ), ] diff --git a/src/backend/InvenTree/report/models.py b/src/backend/InvenTree/report/models.py index 8b6bd54d65..adcefc5dc2 100644 --- a/src/backend/InvenTree/report/models.py +++ b/src/backend/InvenTree/report/models.py @@ -24,15 +24,14 @@ from pypdf import PdfWriter import InvenTree.exceptions import InvenTree.helpers -import InvenTree.models import InvenTree.ready import report.helpers import report.validators from common.models import DataOutput, RenderChoices, UpdatedUserMixin from common.settings import get_global_setting from company.models import Company +from generic.models.base import InvenTreeMetadataModel from InvenTree.helpers_model import get_base_url -from InvenTree.models import MetadataMixin from plugin import InvenTreePlugin, PluginMixinEnum, registry from report.security import restricted_db_access @@ -203,9 +202,7 @@ class ReportContextExtension(TypedDict): merge: bool -class ReportTemplateBase( - MetadataMixin, UpdatedUserMixin, InvenTree.models.InvenTreeModel -): +class ReportTemplateBase(UpdatedUserMixin, InvenTreeMetadataModel): """Base class for reports, labels.""" class ModelChoices(RenderChoices): diff --git a/src/backend/InvenTree/stock/migrations/0036_stockitemattachment.py b/src/backend/InvenTree/stock/migrations/0036_stockitemattachment.py index 1ffc87b1e2..fb26b891ed 100644 --- a/src/backend/InvenTree/stock/migrations/0036_stockitemattachment.py +++ b/src/backend/InvenTree/stock/migrations/0036_stockitemattachment.py @@ -1,6 +1,5 @@ # Generated by Django 3.0.5 on 2020-05-06 23:36 -import InvenTree.models from django.db import migrations, models import django.db.models.deletion diff --git a/src/backend/InvenTree/stock/models.py b/src/backend/InvenTree/stock/models.py index be7f7dbfc5..dfc66916ad 100644 --- a/src/backend/InvenTree/stock/models.py +++ b/src/backend/InvenTree/stock/models.py @@ -31,7 +31,6 @@ import build.models import common.models import InvenTree.exceptions import InvenTree.helpers -import InvenTree.models import InvenTree.ready import InvenTree.tasks import order.models @@ -41,6 +40,18 @@ from common.icons import validate_icon from common.settings import get_global_setting from company import models as CompanyModels from generic.enums import StringEnum +from generic.models.base import InvenTreeMetadataModel, InvenTreeTree +from generic.models.modelmixins import ( + InvenTreeAttachmentMixin, + InvenTreeAuditMixin, + InvenTreeBarcodeMixin, + InvenTreeMetadataMixin, + InvenTreeNoteMixin, + InvenTreeParameterMixin, + InvenTreePathStringMixin, + InvenTreePluginValidationMixin, + InvenTreeTagsMixin, +) from generic.states import StatusCodeMixin from generic.states.fields import InvenTreeCustomStatusModelField from InvenTree.fields import InvenTreeModelMoneyField, InvenTreeURLField @@ -56,11 +67,7 @@ from users.models import Owner logger = structlog.get_logger('inventree') -class StockLocationType( - InvenTree.models.InvenTreeParameterMixin, - InvenTree.models.MetadataMixin, - models.Model, -): +class StockLocationType(InvenTreeParameterMixin, InvenTreeMetadataMixin, models.Model): """A type of stock location like Warehouse, room, shelf, drawer. Attributes: @@ -130,14 +137,14 @@ class StockLocationReportContext(report.mixins.BaseReportContext): class StockLocation( - InvenTree.models.PluginValidationMixin, - InvenTree.models.InvenTreeParameterMixin, - InvenTree.models.InvenTreeBarcodeMixin, - InvenTree.models.InvenTreeTagsMixin, + InvenTreePluginValidationMixin, + InvenTreeParameterMixin, + InvenTreeBarcodeMixin, + InvenTreeTagsMixin, report.mixins.InvenTreeReportMixin, - InvenTree.models.PathStringMixin, - InvenTree.models.MetadataMixin, - InvenTree.models.InvenTreeTree, + InvenTreePathStringMixin, + InvenTreeMetadataMixin, + InvenTreeTree, ): """Organization tree for StockItem objects. @@ -438,16 +445,15 @@ STOCK_SORT_DEFAULT = StockSortOrder.DATE_OLDEST class StockItem( - InvenTree.models.InvenTreeAuditMixin, - InvenTree.models.InvenTreeAttachmentMixin, - InvenTree.models.InvenTreeBarcodeMixin, - InvenTree.models.InvenTreeNoteMixin, - InvenTree.models.InvenTreeTagsMixin, + InvenTreeAuditMixin, + InvenTreeAttachmentMixin, + InvenTreeBarcodeMixin, + InvenTreeNoteMixin, + InvenTreeTagsMixin, StatusCodeMixin, report.mixins.InvenTreeReportMixin, common.models.MetaMixin, - InvenTree.models.MetadataMixin, - InvenTree.models.InvenTreeModel, + InvenTreeMetadataModel, ): """A StockItem object represents a quantity of physical instances of a part. @@ -3720,7 +3726,7 @@ def rename_stock_item_test_result_attachment(instance, filename): ) -class StockItemTestResult(InvenTree.models.InvenTreeMetadataModel): +class StockItemTestResult(InvenTreeMetadataModel): """A StockItemTestResult records results of custom tests against individual StockItem objects. This is useful for tracking unit acceptance tests, and particularly useful when integrated diff --git a/src/backend/InvenTree/users/models.py b/src/backend/InvenTree/users/models.py index 5d1981fe7f..f4949f319a 100644 --- a/src/backend/InvenTree/users/models.py +++ b/src/backend/InvenTree/users/models.py @@ -27,8 +27,8 @@ from allauth.account.signals import password_reset from rest_framework.authtoken.models import Token as AuthToken import InvenTree.helpers -import InvenTree.models from common.settings import get_global_setting +from generic.models.modelmixins import InvenTreeMetadataMixin from InvenTree.ready import isImportingData, isReadOnlyCommand from web.tips import KNOWN_IDS @@ -90,7 +90,7 @@ def default_token_expiry(): return InvenTree.helpers.current_date() + datetime.timedelta(days=365) -class ApiToken(AuthToken, InvenTree.models.MetadataMixin): +class ApiToken(AuthToken, InvenTreeMetadataMixin): """Extends the default token model provided by djangorestframework.authtoken. Extensions: @@ -731,7 +731,7 @@ def create_missing_rule_sets(sender, instance, **kwargs): update_group_roles(instance) -class UserProfile(InvenTree.models.MetadataMixin): +class UserProfile(InvenTreeMetadataMixin): """Model to store additional user profile information.""" class UserType(models.TextChoices): @@ -863,7 +863,7 @@ def create_or_update_user_profile(sender, instance, created, **kwargs): instance.profile.save() -class TipResult(InvenTree.models.MetadataMixin): +class TipResult(InvenTreeMetadataMixin): """Model representing a tip result.""" class Meta: