Home Information - Your home, your data, organized.
Python
import json
import logging
from typing import Any, List, Optional, Tuple
from django.core.files.storage import default_storage
from django.db import models
from hi.apps.attribute.value_ranges import PredefinedValueRanges
from hi.apps.common.file_utils import generate_unique_filename
from hi.integrations.transient_models import IntegrationKey
from .enums import (
AttributeValueType,
AttributeType,
)
from .managers import ActiveAttributeModelManager, DeletedAttributeModelManager
from .thumbnail import AttributeThumbnail, AttributeThumbnailRules
logger = logging.getLogger(__name__)
class AttributeModel(models.Model):
supports_soft_delete = False
class Meta:
abstract = True
ordering = ['order_id', 'id']
name = models.CharField(
'Name',
max_length = 64,
)
value = models.TextField(
'Value',
blank = True, null = True,
)
file_value = models.FileField(
upload_to = 'attributes/', # Subclasses override via get_upload_to()
blank = True, null = True,
)
file_mime_type = models.CharField(
'Mime Type',
max_length = 128,
null = True, blank = True,
)
value_type_str = models.CharField(
'Value Type',
max_length = 32,
null = False, blank = False,
)
value_range_str = models.TextField(
'Value Range',
null = True, blank = True,
)
integration_key_str = models.CharField(
'Integration Key',
max_length = 128,
null = True, blank = True,
)
attribute_type_str = models.CharField(
'Attribute Type',
max_length = 32,
null = False, blank = False,
)
is_editable = models.BooleanField(
'Editable?',
default = True,
)
is_required = models.BooleanField(
'Required?',
default = False,
)
created_datetime = models.DateTimeField(
'Created',
auto_now_add = True,
)
updated_datetime = models.DateTimeField(
'Updated',
auto_now=True,
blank = True,
)
order_id = models.PositiveIntegerField(
'Ordering Index',
default = 0,
)
def get_upload_to(self):
raise NotImplementedError('Subclasses should override this method.' )
def get_attribute_default_value(self):
return None
@property
def display_description( self ):
return None
def __str__(self):
return f'Attr: {self.name}={self.value} [{self.value_type_str}] [{self.attribute_type_str}]'
def __repr__(self):
return self.__str__()
@property
def value_type(self) -> AttributeValueType:
return AttributeValueType.from_name_safe( self.value_type_str )
@value_type.setter
def value_type( self, value_type : AttributeValueType ):
self.value_type_str = str(value_type)
return
@property
def integration_key(self) -> IntegrationKey:
if not self.integration_key_str:
return None
return IntegrationKey.from_string( self.integration_key_str )
@integration_key.setter
def integration_key( self, integration_key : IntegrationKey ):
if integration_key:
self.integration_key_str = str(integration_key)
else:
self.integration_key_str = None
return
@property
def attribute_type(self) -> AttributeType:
return AttributeType.from_name_safe( self.attribute_type_str )
@attribute_type.setter
def attribute_type( self, attribute_type : AttributeType ):
self.attribute_type_str = str(attribute_type)
return
@property
def is_predefined(self):
return bool( self.attribute_type == AttributeType.PREDEFINED )
def choices(self) -> List[ Tuple[ str, str ] ]:
# First check predefined ids
choice_list = PredefinedValueRanges.get_choices( self.value_range_str )
if choice_list:
return choice_list
if not self.value_range_str:
return list()
try:
value_range = json.loads( self.value_range_str )
if isinstance( value_range, dict ):
return [ ( k, v ) for k, v in value_range.items() ]
if isinstance( value_range, list ):
return [ ( x, x ) for x in value_range ]
except json.JSONDecodeError as e:
logger.error( f'Bad value range for attribute {self.name}: {e}' )
pass
return list()
def _parse_value_range_raw(self) -> Optional[ Tuple[ Any, Any ] ]:
"""Shared parser for ``value_range`` / ``value_range_int``.
Returns the ``(min, max)`` pair as the raw JSON-decoded
values without type coercion, so each typed wrapper can apply
its own validation policy. Returns ``None`` for missing,
unparseable, or unrecognized-shape data.
Recognized shapes (parallel to ``choices()`` so authors can
declare numeric ranges in either form):
* Two-element list: ``"[5, 86400]"``
* Object with min/max keys: ``'{"min": 5, "max": 86400}'``"""
if not self.value_range_str:
return None
try:
value_range = json.loads( self.value_range_str )
except (json.JSONDecodeError, TypeError):
return None
if isinstance( value_range, list ) and len( value_range ) == 2:
return ( value_range[0], value_range[1] )
if ( isinstance( value_range, dict )
and 'min' in value_range and 'max' in value_range ):
return ( value_range['min'], value_range['max'] )
return None
def value_range(self) -> Optional[ Tuple[ float, float ] ]:
"""Parse ``value_range_str`` as a numeric ``(min, max)`` range
for FLOAT-typed attributes (also serves callers that just need
either-int-or-float bounds as floats). Returns ``None`` when
the field is missing, malformed, or has the bounds reversed.
Integer-typed call sites should prefer ``value_range_int()`` --
this method coerces both bounds via ``float()`` and will
therefore accept declarations like ``"[5.7, 10.2]"`` that an
integer caller shouldn't honor."""
raw = self._parse_value_range_raw()
if raw is None:
return None
low_raw, high_raw = raw
try:
low = float( low_raw )
high = float( high_raw )
except (ValueError, TypeError):
return None
if low > high:
return None
return ( low, high )
def value_range_int(self) -> Optional[ Tuple[ int, int ] ]:
"""Integer-typed variant of ``value_range()``. Accepts the same
list / dict shapes but requires both bounds to be JSON
integers (so ``"[5, 10]"`` is honored and ``"[5.0, 10.0]"`` is
rejected -- the author declared floats and ``int(5.0)`` would
silently coerce). Returns ``None`` on any failure mode of the
underlying parse or on a non-int bound.
``bool`` is excluded explicitly because Python's
``isinstance(True, int)`` is True; allowing it would silently
coerce a misplaced ``"[true, 100]"`` into ``(1, 100)``."""
raw = self._parse_value_range_raw()
if raw is None:
return None
low_raw, high_raw = raw
for bound in ( low_raw, high_raw ):
if isinstance( bound, bool ) or not isinstance( bound, int ):
return None
if low_raw > high_raw:
return None
return ( low_raw, high_raw )
@property
def supports_thumbnail_generation(self):
return AttributeThumbnailRules.supports_thumbnail_generation(
file_value=self.file_value,
file_mime_type=self.file_mime_type,
)
@property
def thumbnail_relative_path(self):
return AttributeThumbnailRules.thumbnail_relative_path(
file_value=self.file_value,
file_mime_type=self.file_mime_type,
)
def _thumbnail_exists(self):
if hasattr(self, '_thumbnail_exists_cache'):
return self._thumbnail_exists_cache
thumbnail_path = self.thumbnail_relative_path
self._thumbnail_exists_cache = bool( thumbnail_path and default_storage.exists(thumbnail_path) )
return self._thumbnail_exists_cache
def set_thumbnail_exists_cache(self, exists):
self._thumbnail_exists_cache = bool(exists)
return self._thumbnail_exists_cache
def clear_thumbnail_exists_cache(self):
if hasattr(self, '_thumbnail_exists_cache'):
del self._thumbnail_exists_cache
return
@property
def has_thumbnail(self):
return self._thumbnail_exists()
def ensure_thumbnail(self):
"""Generate a thumbnail synchronously if one is missing for this
file attribute. Intended as a lazy-generation hook invoked from
display templates via the ``{% ensure_thumbnail %}`` tag.
Spreads thumbnail-generation cost across actual usage (each file
attribute pays once, on first view) instead of forcing an upfront
pass at startup. No-op for unsupported file types or already-
generated thumbnails. Generation failures are swallowed by the
best-effort helper; the template falls back to its icon
placeholder in that case."""
if not self.supports_thumbnail_generation:
return
if self._thumbnail_exists():
return
AttributeThumbnail( self ).generate_thumbnail_best_effort()
self.clear_thumbnail_exists_cache()
return
@property
def thumbnail_url(self):
if not self._thumbnail_exists():
return None
return default_storage.url(self.thumbnail_relative_path)
@property
def preview_state(self):
if self.has_thumbnail:
return 'thumbnail'
return 'placeholder'
def save(self, *args, **kwargs):
# Skip history tracking for kwargs that disable it
track_history = kwargs.pop('track_history', True)
if self.file_value and self.file_value.name:
self.file_value.field.upload_to = self.get_upload_to()
if not self.value:
self.value = self.file_value.name
all_manager = getattr( self.__class__, 'all_objects', self.__class__.objects )
if not self.pk or not all_manager.filter( pk = self.pk ).exists():
self.file_value.name = generate_unique_filename( self.file_value.name )
# Save the attribute first
super().save(*args, **kwargs)
# Track history for value-based attributes only AFTER saving
if track_history and not self.value_type.is_file:
self._create_history_record()
return
def _create_history_record(self):
"""Create a history record for this attribute's value change."""
# Get the history model class for this concrete attribute type
history_model_class = self._get_history_model_class()
if not history_model_class:
return
# Create history record
history_model_class.objects.create(
attribute=self,
value=self.value
)
def _get_history_model_class(self):
"""
Get the corresponding history model class for this attribute type.
Must be implemented by all concrete subclasses.
"""
raise NotImplementedError(
f"{self.__class__.__name__} must implement _get_history_model_class() "
"to provide history tracking support."
)
def delete( self, *args, **kwargs ):
""" Deleting file from MEDIA_ROOT on best effort basis. Ignore if fails. """
thumbnail_path = self.thumbnail_relative_path
if self.file_value:
try:
if default_storage.exists( self.file_value.name ):
default_storage.delete( self.file_value.name )
logger.debug( f'Deleted Attribute file: {self.file_value.name}' )
else:
logger.warn( f'Attribute file not found: {self.file_value.name}' )
except Exception as e:
# Log the error or handle it accordingly
logger.warn( f'Error deleting Attribute file {self.file_value.name}: {e}' )
if thumbnail_path:
try:
if default_storage.exists(thumbnail_path):
default_storage.delete(thumbnail_path)
logger.debug(f'Deleted Attribute thumbnail: {thumbnail_path}')
except Exception as e:
logger.warn(f'Error deleting Attribute thumbnail {thumbnail_path}: {e}')
self.set_thumbnail_exists_cache(False)
super().delete( *args, **kwargs )
return
class SoftDeleteAttributeModel(AttributeModel):
"""Base class for attribute models that support soft delete."""
supports_soft_delete = True
is_deleted = models.BooleanField(
'Deleted?',
default = False,
db_index = True,
)
objects = ActiveAttributeModelManager()
all_objects = models.Manager()
deleted_objects = DeletedAttributeModelManager()
class Meta(AttributeModel.Meta):
abstract = True
def soft_delete( self ):
self.is_deleted = True
self.save(
update_fields = ['is_deleted', 'updated_datetime'],
track_history = False,
)
def restore_from_deleted( self ):
self.is_deleted = False
self.save(
update_fields = ['is_deleted', 'updated_datetime'],
track_history = False,
)
def delete( self, *args, **kwargs ):
hard_delete = kwargs.pop( 'hard_delete', False )
if hard_delete:
return super().delete(*args, **kwargs)
self.soft_delete()
return (1, {self.__class__.__name__: 1})
class AttributeValueHistoryModel(models.Model):
"""
Abstract base class for tracking attribute value changes.
Each concrete attribute subclass should have its own history model
that defines the foreign key to its specific attribute type.
Only tracks value-based attributes (Text, Boolean, Integer, Float, etc.).
File attributes are excluded and will be handled separately.
"""
class Meta:
abstract = True
ordering = ['-changed_datetime']
value = models.TextField(
'Value',
blank=True, null=True,
)
changed_datetime = models.DateTimeField(
'Changed',
auto_now_add=True,
db_index=True,
)
def __str__(self):
return f'Changed at {self.changed_datetime}'