Skip to content

Home Information - Your home, your data, organized.

Python

Fix EntityType icon update issue in editing mode (Issue #30) (#69)

cassandra-ai-agentc4f190fd7c73
diff --git a/src/hi/apps/entity/entity_manager.py b/src/hi/apps/entity/entity_manager.py
index 1377da63..d9374be3 100644
--- a/src/hi/apps/entity/entity_manager.py
+++ b/src/hi/apps/entity/entity_manager.py
@@ -1,16 +1,16 @@
from decimal import Decimal
import logging
from threading import local
-from typing import List, Sequence
+from typing import List, Sequence, Tuple
from django.db import transaction
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from hi.apps.common.singleton import Singleton
+from hi.apps.location.path_geometry import PathGeometry
from hi.apps.entity.edit.forms import EntityPositionForm
from hi.apps.location.models import Location, LocationView
-from hi.apps.location.svg_item_factory import SvgItemFactory
from .entity_pairing_manager import EntityPairingManager
from .enums import (
@@ -117,12 +117,12 @@ class EntityManager(Singleton):
with transaction.atomic():
# Need to make sure it has some visible representation in the view if none exists.
- svg_item_type = SvgItemFactory().get_svg_item_type( entity )
- if svg_item_type.is_path:
+ entity_type = entity.entity_type
+ if entity_type.requires_path():
self.add_entity_path_if_needed(
entity = entity,
location_view = location_view,
- is_path_closed = svg_item_type.is_path_closed,
+ is_path_closed = entity_type.requires_closed_path(),
)
else:
self.add_entity_position_if_needed(
@@ -237,10 +237,11 @@ class EntityManager(Singleton):
except EntityPath.DoesNotExist:
pass
- svg_path = SvgItemFactory().get_default_entity_svg_path_str(
- entity = entity,
- location_view = location_view,
- is_path_closed = is_path_closed,
+ # Create default path geometry using utility function
+ svg_path = PathGeometry.create_default_path_string(
+ location_view=location_view,
+ is_path_closed=is_path_closed,
+ entity_type=entity.entity_type,
)
entity_path = EntityPath.objects.create(
entity = entity,
@@ -249,6 +250,213 @@ class EntityManager(Singleton):
)
return entity_path
+ def handle_entity_type_transition( self,
+ entity : Entity,
+ location_view : LocationView = None ) -> Tuple[bool, str]:
+ """
+ Handle transitions between EntityType icon and path representations.
+ Returns (transition_occurred, transition_type)
+ """
+ if not location_view:
+ # If no location view provided, we can't handle position/path transitions
+ return False, "no_location_view"
+
+ # Use EntityType structural methods instead of SvgItemFactory
+ entity_type = entity.entity_type
+
+ # Check current state in database
+ entity_position = EntityPosition.objects.filter(
+ entity = entity,
+ location = location_view.location,
+ ).first()
+ entity_path = EntityPath.objects.filter(
+ entity = entity,
+ location = location_view.location,
+ ).first()
+
+ has_position = bool(entity_position)
+ has_path = bool(entity_path)
+ needs_position = entity_type.requires_position()
+ needs_path = entity_type.requires_path()
+
+ # Check if entity has both representations (from preservation strategy)
+ had_both = has_position and has_path
+
+ # For entities with both, we need to determine the transition type
+ # based on the actual EntityType change, not just database state
+ if had_both:
+ # With preservation strategy, both representations exist
+ # Determine transition type based on what the NEW EntityType needs
+ if needs_position:
+ # Transitioning to position-based type, classify as path->icon
+ # since the entity had both but will now primarily use position
+ pass # Will use path_to_icon transition
+ else:
+ # Transitioning to path-based type, classify as icon->path
+ # since the entity had both but will now primarily use path
+ pass # Will use icon_to_path transition
+
+ # Execute the appropriate transition
+ with transaction.atomic():
+ if needs_position:
+ return self._transition_path_to_icon(
+ entity = entity,
+ location_view = location_view,
+ entity_path = entity_path,
+ )
+ else:
+ return self._transition_icon_to_path(
+ entity = entity,
+ location_view = location_view,
+ entity_position = entity_position,
+ is_path_closed = entity_type.requires_closed_path(),
+ )
+
+ with transaction.atomic():
+ # Handle cases where entity doesn't have both representations
+ if needs_position:
+ # Entity type needs position representation
+ if not has_position:
+ # Need to create position (from path center if path exists)
+ if has_path:
+ return self._transition_path_to_icon(
+ entity = entity,
+ location_view = location_view,
+ entity_path = entity_path,
+ )
+ else:
+ # No existing representation, create new position
+ self.add_entity_position_if_needed(
+ entity = entity,
+ location_view = location_view,
+ )
+ return True, "created_position"
+ else:
+ # Position already exists, just a visual update
+ return True, "icon_to_icon"
+
+ elif needs_path:
+ # Entity type needs path representation
+ if not has_path:
+ # Need to create path (from position if position exists)
+ if has_position:
+ return self._transition_icon_to_path(
+ entity = entity,
+ location_view = location_view,
+ entity_position = entity_position,
+ is_path_closed = entity_type.requires_closed_path(),
+ )
+ else:
+ # No existing representation, create new path
+ self.add_entity_path_if_needed(
+ entity = entity,
+ location_view = location_view,
+ is_path_closed = entity_type.requires_closed_path(),
+ )
+ return True, "created_path"
+ else:
+ # Path already exists, just a visual update
+ return True, "path_to_path"
+
+ return False, "no_transition_needed"
+
+ def _transition_icon_to_path( self,
+ entity : Entity,
+ location_view : LocationView,
+ entity_position : EntityPosition,
+ is_path_closed : bool ) -> Tuple[bool, str]:
+ """Create or update EntityPath based on EntityPosition location, preserving both"""
+
+ # Get center point of the icon for path placement
+ center_x = float(entity_position.svg_x)
+ center_y = float(entity_position.svg_y)
+
+ # Create path centered at icon position with larger size for better UX
+ svg_path = PathGeometry.create_default_path_string(
+ location_view=location_view,
+ is_path_closed=is_path_closed,
+ center_x=center_x,
+ center_y=center_y,
+ entity_type=entity.entity_type,
+ radius_multiplier=2.0, # Double size for better control point visibility
+ )
+
+ # Preserve EntityPosition and create/update EntityPath
+ # This allows easy reversion when users change their mind
+ entity_path, created = EntityPath.objects.get_or_create(
+ entity = entity,
+ location = location_view.location,
+ defaults = {'svg_path': svg_path}
+ )
+
+ if not created:
+ # EntityPath already exists - preserve existing geometry
+ pass # Keep existing path geometry
+
+ return True, "icon_to_path"
+
+ def _transition_path_to_icon( self,
+ entity : Entity,
+ location_view : LocationView,
+ entity_path : EntityPath ) -> Tuple[bool, str]:
+ """Create or update EntityPosition based on EntityPath center, preserving both"""
+
+ # Calculate geometric center of the path
+ center_x, center_y = self._calculate_path_center(entity_path.svg_path)
+
+ # If calculation fails, use location view center
+ if center_x is None or center_y is None:
+ center_x = location_view.svg_view_box.x + (location_view.svg_view_box.width / 2.0)
+ center_y = location_view.svg_view_box.y + (location_view.svg_view_box.height / 2.0)
+
+ # Preserve EntityPath and create/update EntityPosition
+ # This allows easy reversion when users change their mind
+ entity_position, created = EntityPosition.objects.get_or_create(
+ entity = entity,
+ location = location_view.location,
+ defaults = {
+ 'svg_x': Decimal(center_x),
+ 'svg_y': Decimal(center_y),
+ 'svg_scale': Decimal(1.0),
+ 'svg_rotate': Decimal(0.0),
+ }
+ )
+
+ if not created:
+ # EntityPosition already exists - preserve existing position
+ pass # Keep existing position
+
+ return True, "path_to_icon"
+
+ def _calculate_path_center( self, svg_path : str ) -> Tuple[float, float]:
+ """Calculate the geometric center of an SVG path"""
+ try:
+ # Simple path center calculation - find all coordinate pairs and average them
+ import re
+
+ # Extract all numbers from the path (x,y coordinates)
+ numbers = re.findall(r'[-+]?(?:\d*\.\d+|\d+)', svg_path)
+ if len(numbers) < 4: # Need at least 2 points (4 numbers)
+ return None, None
+
+ coords = [float(n) for n in numbers]
+
+ # Group into x,y pairs
+ x_coords = [coords[i] for i in range(0, len(coords), 2)]
+ y_coords = [coords[i] for i in range(1, len(coords), 2)]
+
+ if not x_coords or not y_coords:
+ return None, None
+
+ # Return the average of all points
+ center_x = sum(x_coords) / len(x_coords)
+ center_y = sum(y_coords) / len(y_coords)
+
+ return center_x, center_y
+
+ except (ValueError, IndexError, ZeroDivisionError):
+ return None, None
+
def create_location_entity_view_group_list( self, location_view : LocationView ) -> List[EntityViewGroup]:
existing_entities = [ x.entity
for x in location_view.entity_views.select_related('entity').all() ]
diff --git a/src/hi/apps/entity/enums.py b/src/hi/apps/entity/enums.py
index bdf2128e..64f9fb58 100644
--- a/src/hi/apps/entity/enums.py
+++ b/src/hi/apps/entity/enums.py
@@ -100,6 +100,52 @@ class EntityType(LabeledEnum):
@classmethod
def default(cls):
return cls.OTHER
+
+ # Single source of truth for position vs path classification
+ @classmethod
+ def get_closed_path_types(cls) -> Set['EntityType']:
+ """EntityTypes that require closed paths (areas/regions)"""
+ return {
+ cls.APPLIANCE,
+ cls.AREA,
+ cls.DOOR,
+ cls.FURNITURE,
+ cls.GREENHOUSE,
+ cls.WALL,
+ cls.WINDOW,
+ }
+
+ @classmethod
+ def get_open_path_types(cls) -> Set['EntityType']:
+ """EntityTypes that require open paths (lines/routes)"""
+ return {
+ cls.CONTROL_WIRE,
+ cls.ELECTRIC_WIRE,
+ cls.FENCE,
+ cls.PIPE,
+ cls.SEWER_LINE,
+ cls.SPEAKER_WIRE,
+ cls.SPRINKLER_WIRE,
+ cls.TELECOM_WIRE,
+ cls.WATER_LINE,
+ }
+
+ # Convenience methods for structural decisions
+ def requires_position(self) -> bool:
+ """True if EntityType should be represented as EntityPosition (icon) - DEFAULT"""
+ return not self.requires_path()
+
+ def requires_path(self) -> bool:
+ """True if EntityType should be represented as EntityPath"""
+ return self in (self.get_closed_path_types() | self.get_open_path_types())
+
+ def requires_closed_path(self) -> bool:
+ """True if EntityType requires a closed path"""
+ return self in self.get_closed_path_types()
+
+ def requires_open_path(self) -> bool:
+ """True if EntityType requires an open path"""
+ return self in self.get_open_path_types()
class EntityStateType(LabeledEnum):
diff --git a/src/hi/apps/entity/tests/test_entity_type_transitions.py b/src/hi/apps/entity/tests/test_entity_type_transitions.py
new file mode 100644
index 00000000..0cf6dfce
--- /dev/null
+++ b/src/hi/apps/entity/tests/test_entity_type_transitions.py
@@ -0,0 +1,355 @@
+"""
+Tests for EntityType transition handling functionality.
+Focus on actual behavior and database state changes per testing guidelines.
+"""
+from decimal import Decimal
+
+from django.db import transaction
+from django.test import TransactionTestCase
+
+from hi.apps.entity.entity_manager import EntityManager
+from hi.apps.entity.enums import EntityType
+from hi.apps.entity.models import Entity, EntityPath, EntityPosition
+from hi.apps.location.models import Location, LocationView
+
+
+class TestEntityTypeTransitions(TransactionTestCase):
+ """Test EntityType transition handling with preservation strategy"""
+
+ def setUp(self):
+ super().setUp()
+
+ # Reset singleton state for test isolation
+ EntityManager._instances = {}
+ self.manager = EntityManager()
+
+ # Create test data
+ self.location = Location.objects.create(
+ name = 'Test Location',
+ svg_fragment_filename = 'test.svg',
+ svg_view_box_str = '0 0 1000 1000',
+ )
+ self.location_view = LocationView.objects.create(
+ location = self.location,
+ name = 'Test View',
+ location_view_type_str = 'DEFAULT',
+ svg_view_box_str = '0 0 1000 1000',
+ svg_rotate = Decimal('0'),
+ svg_style_name_str = 'COLOR',
+ )
+ self.entity = Entity.objects.create(
+ name = 'Test Entity',
+ entity_type_str = str(EntityType.LIGHT), # Start with icon type
+ )
+ return
+
+ def test_icon_to_path_transition_preserves_position(self):
+ """Test that icon->path transition preserves EntityPosition"""
+ # Create initial position
+ EntityPosition.objects.create(
+ entity = self.entity,
+ location = self.location,
+ svg_x = Decimal('500'),
+ svg_y = Decimal('300'),
+ svg_scale = Decimal('1.0'),
+ svg_rotate = Decimal('0'),
+ )
+
+ # Change to path type (WALL is a path type)
+ self.entity.entity_type_str = str(EntityType.WALL)
+ self.entity.save()
+
+ # Perform transition
+ transition_occurred, transition_type = self.manager.handle_entity_type_transition(
+ entity = self.entity,
+ location_view = self.location_view,
+ )
+
+ # Verify transition occurred
+ self.assertTrue(transition_occurred)
+ self.assertEqual(transition_type, "icon_to_path")
+
+ # Verify EntityPosition is preserved
+ self.assertTrue(
+ EntityPosition.objects.filter(
+ entity = self.entity,
+ location = self.location,
+ ).exists()
+ )
+
+ # Verify EntityPath was created
+ self.assertTrue(
+ EntityPath.objects.filter(
+ entity = self.entity,
+ location = self.location,
+ ).exists()
+ )
+
+ # Both should coexist
+ self.assertEqual(EntityPosition.objects.filter(entity=self.entity).count(), 1)
+ self.assertEqual(EntityPath.objects.filter(entity=self.entity).count(), 1)
+ return
+
+ def test_path_to_icon_transition_preserves_path(self):
+ """Test that path->icon transition preserves EntityPath"""
+ # Start with path type
+ self.entity.entity_type_str = str(EntityType.WALL)
+ self.entity.save()
+
+ # Create initial path
+ EntityPath.objects.create(
+ entity = self.entity,
+ location = self.location,
+ svg_path = 'M 100,100 L 200,200 L 300,100 Z',
+ )
+
+ # Change to icon type
+ self.entity.entity_type_str = str(EntityType.LIGHT)
+ self.entity.save()
+
+ # Perform transition
+ transition_occurred, transition_type = self.manager.handle_entity_type_transition(
+ entity = self.entity,
+ location_view = self.location_view,
+ )
+
+ # Verify transition occurred
+ self.assertTrue(transition_occurred)
+ self.assertEqual(transition_type, "path_to_icon")
+
+ # Verify EntityPath is preserved
+ self.assertTrue(
+ EntityPath.objects.filter(
+ entity = self.entity,
+ location = self.location,
+ ).exists()
+ )
+
+ # Verify EntityPosition was created
+ self.assertTrue(
+ EntityPosition.objects.filter(
+ entity = self.entity,
+ location = self.location,
+ ).exists()
+ )
+
+ # Both should coexist
+ self.assertEqual(EntityPosition.objects.filter(entity=self.entity).count(), 1)
+ self.assertEqual(EntityPath.objects.filter(entity=self.entity).count(), 1)
+ return
+
+ def test_repeated_transitions_preserve_geometry(self):
+ """Test that switching back and forth preserves original geometry"""
+ # Create initial position
+ original_x = Decimal('123.45')
+ original_y = Decimal('678.90')
+ EntityPosition.objects.create(
+ entity = self.entity,
+ location = self.location,
+ svg_x = original_x,
+ svg_y = original_y,
+ svg_scale = Decimal('1.0'),
+ svg_rotate = Decimal('0'),
+ )
+
+ # Transition icon->path
+ self.entity.entity_type_str = str(EntityType.WALL)
+ self.entity.save()
+ self.manager.handle_entity_type_transition(
+ entity = self.entity,
+ location_view = self.location_view,
+ )
+
+ # Transition path->icon (back to original)
+ self.entity.entity_type_str = str(EntityType.LIGHT)
+ self.entity.save()
+ transition_occurred, transition_type = self.manager.handle_entity_type_transition(
+ entity = self.entity,
+ location_view = self.location_view,
+ )
+
+ # Should be path to icon since both representations now exist
+ self.assertTrue(transition_occurred)
+ self.assertEqual(transition_type, "path_to_icon")
+
+ # Verify original position is preserved
+ entity_position = EntityPosition.objects.get(
+ entity = self.entity,
+ location = self.location,
+ )
+ self.assertEqual(entity_position.svg_x, original_x)
+ self.assertEqual(entity_position.svg_y, original_y)
+ return
+
+ def test_both_exist_edge_case(self):
+ """Test handling when both EntityPosition and EntityPath already exist"""
+ # Create both position and path
+ EntityPosition.objects.create(
+ entity = self.entity,
+ location = self.location,
+ svg_x = Decimal('500'),
+ svg_y = Decimal('500'),
+ svg_scale = Decimal('1.0'),
+ svg_rotate = Decimal('0'),
+ )
+ EntityPath.objects.create(
+ entity = self.entity,
+ location = self.location,
+ svg_path = 'M 0,0 L 100,0',
+ )
+
+ # Transition to icon type
+ transition_occurred, transition_type = self.manager.handle_entity_type_transition(
+ entity = self.entity,
+ location_view = self.location_view,
+ )
+
+ # Should recognize transition from preserved path to icon
+ self.assertTrue(transition_occurred)
+ self.assertEqual(transition_type, "path_to_icon")
+
+ # Transition to path type
+ self.entity.entity_type_str = str(EntityType.WALL)
+ self.entity.save()
+ transition_occurred, transition_type = self.manager.handle_entity_type_transition(
+ entity = self.entity,
+ location_view = self.location_view,
+ )
+
+ # Should recognize transition to path when both exist (icon_to_path)
+ self.assertTrue(transition_occurred)
+ self.assertEqual(transition_type, "icon_to_path")
+
+ # Both should still exist
+ self.assertEqual(EntityPosition.objects.filter(entity=self.entity).count(), 1)
+ self.assertEqual(EntityPath.objects.filter(entity=self.entity).count(), 1)
+ return
+
+ def test_icon_to_icon_transition(self):
+ """Test transition between two icon types"""
+ # Create initial position
+ EntityPosition.objects.create(
+ entity = self.entity,
+ location = self.location,
+ svg_x = Decimal('500'),
+ svg_y = Decimal('500'),
+ svg_scale = Decimal('1.0'),
+ svg_rotate = Decimal('0'),
+ )
+
+ # Change to different icon type
+ self.entity.entity_type_str = str(EntityType.CAMERA)
+ self.entity.save()
+
+ transition_occurred, transition_type = self.manager.handle_entity_type_transition(
+ entity = self.entity,
+ location_view = self.location_view,
+ )
+
+ self.assertTrue(transition_occurred)
+ self.assertEqual(transition_type, "icon_to_icon")
+
+ # Only position should exist
+ self.assertEqual(EntityPosition.objects.filter(entity=self.entity).count(), 1)
+ self.assertEqual(EntityPath.objects.filter(entity=self.entity).count(), 0)
+ return
+
+ def test_path_to_path_transition(self):
+ """Test transition between two path types"""
+ # Start with path type
+ self.entity.entity_type_str = str(EntityType.WALL)
+ self.entity.save()
+
+ # Create initial path
+ EntityPath.objects.create(
+ entity = self.entity,
+ location = self.location,
+ svg_path = 'M 0,0 L 100,100',
+ )
+
+ # Change to different path type
+ self.entity.entity_type_str = str(EntityType.FENCE)
+ self.entity.save()
+
+ transition_occurred, transition_type = self.manager.handle_entity_type_transition(
+ entity = self.entity,
+ location_view = self.location_view,
+ )
+
+ self.assertTrue(transition_occurred)
+ self.assertEqual(transition_type, "path_to_path")
+
+ # Only path should exist
+ self.assertEqual(EntityPosition.objects.filter(entity=self.entity).count(), 0)
+ self.assertEqual(EntityPath.objects.filter(entity=self.entity).count(), 1)
+ return
+
+ def test_no_location_view_returns_false(self):
+ """Test that transition fails gracefully without location view"""
+ transition_occurred, transition_type = self.manager.handle_entity_type_transition(
+ entity = self.entity,
+ location_view = None,
+ )
+
+ self.assertFalse(transition_occurred)
+ self.assertEqual(transition_type, "no_location_view")
+ return
+
+ def test_path_center_calculation(self):
+ """Test geometric center calculation for paths"""
+ # Test simple rectangle path
+ svg_path = 'M 100,100 L 300,100 L 300,200 L 100,200 Z'
+ center_x, center_y = self.manager._calculate_path_center(svg_path)
+
+ # Center should be at (200, 150)
+ self.assertAlmostEqual(center_x, 200.0, places=1)
+ self.assertAlmostEqual(center_y, 150.0, places=1)
+
+ # Test malformed path
+ bad_path = 'invalid path data'
+ center_x, center_y = self.manager._calculate_path_center(bad_path)
+
+ # Should return None for invalid paths
+ self.assertIsNone(center_x)
+ self.assertIsNone(center_y)
+ return
+
+ def test_transaction_rollback_on_transition_failure(self):
+ """Test that database transaction rolls back if transition logic fails"""
+ from unittest.mock import patch
+
+ # Start with valid entity
+ original_name = self.entity.name
+ original_type = self.entity.entity_type_str
+
+ # Mock handle_entity_type_transition to raise an exception
+ with patch.object(EntityManager, 'handle_entity_type_transition') as mock_transition:
+ mock_transition.side_effect = Exception("Simulated transition failure")
+
+ # Attempt entity update with EntityType change
+ try:
+ with transaction.atomic():
+ self.entity.name = "Updated Name"
+ self.entity.entity_type_str = str(EntityType.WALL)
+ self.entity.save()
+
+ # This should raise exception and rollback transaction
+ EntityManager().handle_entity_type_transition(
+ entity = self.entity,
+ location_view = self.location_view,
+ )
+ except Exception:
+ pass # Expected due to mock
+
+ # Reload entity from database
+ self.entity.refresh_from_db()
+
+ # Verify transaction was rolled back - changes should be reverted
+ self.assertEqual(self.entity.name, original_name)
+ self.assertEqual(self.entity.entity_type_str, original_type)
+
+ # Verify no orphaned EntityPosition/EntityPath records created
+ self.assertEqual(EntityPosition.objects.filter(entity=self.entity).count(), 0)
+ self.assertEqual(EntityPath.objects.filter(entity=self.entity).count(), 0)
+ return
+
diff --git a/src/hi/apps/entity/views.py b/src/hi/apps/entity/views.py
index d5d04ba1..15e0286a 100644
--- a/src/hi/apps/entity/views.py
+++ b/src/hi/apps/entity/views.py
@@ -3,6 +3,7 @@ import logging
from django.db import transaction
from django.views.generic import View
+import hi.apps.common.antinode as antinode
from hi.apps.control.controller_history_manager import ControllerHistoryManager
from hi.apps.location.location_manager import LocationManager
from hi.apps.monitor.status_display_manager import StatusDisplayManager
@@ -32,6 +33,9 @@ class EntityEditView( View, EntityViewMixin ):
def post( self, request, *args, **kwargs ):
entity = self.get_entity( request, *args, **kwargs )
+ # Store original entity_type_str to detect changes
+ original_entity_type_str = entity.entity_type_str
+
entity_form = forms.EntityForm( request.POST, instance = entity )
entity_attribute_formset = forms.EntityAttributeFormSet(
request.POST,
@@ -40,10 +44,22 @@ class EntityEditView( View, EntityViewMixin ):
prefix = f'entity-{entity.id}',
)
if entity_form.is_valid() and entity_attribute_formset.is_valid():
+ # Track EntityType change and response needed after transaction
+ entity_type_changed = original_entity_type_str != entity.entity_type_str
+ transition_response = None
+
with transaction.atomic():
entity_form.save()
entity_attribute_formset.save()
+ # Handle transitions within same transaction but defer response
+ if entity_type_changed:
+ transition_response = self._handle_entity_type_change(request, entity)
+
+ # Now that transaction is committed, handle any transition response
+ if transition_response is not None:
+ return transition_response
+
# Recreate to preserve "max" to show new form
entity_attribute_formset = forms.EntityAttributeFormSet(
instance = entity,
@@ -63,6 +79,43 @@ class EntityEditView( View, EntityViewMixin ):
entity_edit_data = entity_edit_data,
status_code = status_code,
)
+
+ def _handle_entity_type_change(self, request, entity):
+ """Handle EntityType changes with appropriate transition logic"""
+ try:
+ # Always attempt advanced transition handling regardless of mode/view
+ current_location_view = LocationManager().get_default_location_view( request = request )
+ transition_occurred, transition_type = EntityManager().handle_entity_type_transition(
+ entity = entity,
+ location_view = current_location_view,
+ )
+
+ if self._needs_full_page_refresh(transition_occurred, transition_type):
+ return antinode.refresh_response()
+
+ # Simple transitions can continue with sidebar-only refresh
+ # (will fall through to normal entity_edit_response)
+ return None
+
+ except Exception as e:
+ logger.warning(f'EntityType transition failed: {e}, falling back to page refresh')
+ return antinode.refresh_response()
+
+ def _needs_full_page_refresh(self, transition_occurred, transition_type):
+ """Determine if EntityType change requires full page refresh"""
+ if not transition_occurred:
+ # Transition failed, use page refresh for safety
+ return True
+
+ if transition_type == "path_to_path":
+ # Path style changes only, sidebar refresh sufficient
+ return False
+
+ # All other transitions need full refresh to show visual changes:
+ # - icon_to_icon: New icon type needs to be visible
+ # - icon_to_path: Database structure changed
+ # - path_to_icon: Database structure changed
+ return True
class EntityAttributeUploadView( View, EntityViewMixin ):
diff --git a/src/hi/apps/location/location_manager.py b/src/hi/apps/location/location_manager.py
index 84dd7f9d..d165cef9 100644
--- a/src/hi/apps/location/location_manager.py
+++ b/src/hi/apps/location/location_manager.py
@@ -165,16 +165,21 @@ class LocationManager(Singleton):
for entity_view in location_view.entity_views.select_related('entity').all():
entity = entity_view.entity
is_visible = False
- entity_position = entity.positions.filter( location = location ).first()
- if entity_position:
- is_visible = True
- entity_positions.append( entity_position )
- displayed_entities.add( entity )
- entity_path = entity.paths.filter( location = location ).first()
- if entity_path:
- is_visible = True
- entity_paths.append( entity_path )
- displayed_entities.add( entity )
+
+ # Only collect position OR path based on EntityType, not both
+ if entity.entity_type.requires_position():
+ entity_position = entity.positions.filter( location = location ).first()
+ if entity_position:
+ is_visible = True
+ entity_positions.append( entity_position )
+ displayed_entities.add( entity )
+ elif entity.entity_type.requires_path():
+ entity_path = entity.paths.filter( location = location ).first()
+ if entity_path:
+ is_visible = True
+ entity_paths.append( entity_path )
+ displayed_entities.add( entity )
+
if not is_visible:
non_displayed_entities.add( entity )
continue
diff --git a/src/hi/apps/location/path_geometry.py b/src/hi/apps/location/path_geometry.py
new file mode 100644
index 00000000..0f1001f1
--- /dev/null
+++ b/src/hi/apps/location/path_geometry.py
@@ -0,0 +1,118 @@
+from typing import Optional
+
+from hi.apps.common.svg_models import SvgRadius
+from hi.apps.entity.enums import EntityType
+from hi.apps.collection.enums import CollectionType
+from hi.apps.location.models import LocationView
+
+
+class PathGeometry:
+ """Pure geometric utility for creating default SVG path strings.
+
+ This utility is independent of SVG items and visual concerns - it only
+ handles the mathematical calculations for generating path geometry.
+ """
+
+ DEFAULT_RADIUS_PERCENT = 5.0 # Match SvgItemFactory.NEW_PATH_RADIUS_PERCENT
+
+ @classmethod
+ def get_entity_radius(cls, entity_type: EntityType) -> SvgRadius:
+ """Get entity-specific radius configuration for path generation.
+
+ This preserves the existing entity-specific sizing configurations
+ that were previously in hi_styles.py EntityTypePathInitialRadius.
+ """
+ entity_radius_configs = {
+ EntityType.APPLIANCE: SvgRadius(x=32, y=32),
+ EntityType.DOOR: SvgRadius(x=None, y=16),
+ EntityType.FURNITURE: SvgRadius(x=64, y=32),
+ EntityType.WALL: SvgRadius(x=16, y=None),
+ EntityType.WINDOW: SvgRadius(x=None, y=16.0),
+ }
+
+ return entity_radius_configs.get(entity_type, SvgRadius(x=None, y=None))
+
+ @classmethod
+ def get_collection_radius(cls, collection_type: CollectionType) -> SvgRadius:
+ """Get collection-specific radius configuration for path generation.
+
+ This preserves the existing collection-specific sizing configurations
+ from hi_styles.py CollectionTypePathInitialRadius for future extensibility.
+ """
+ collection_radius_configs = {
+ # Currently empty but preserved for future collection types
+ # Example: CollectionType.SOME_TYPE: SvgRadius(x=40, y=20),
+ }
+
+ return collection_radius_configs.get(collection_type, SvgRadius(x=None, y=None))
+
+ @classmethod
+ def create_default_path_string(cls,
+ location_view: LocationView,
+ is_path_closed: bool,
+ center_x: Optional[float] = None,
+ center_y: Optional[float] = None,
+ entity_type: Optional[EntityType] = None,
+ collection_type: Optional[CollectionType] = None,
+ radius_multiplier: float = 1.0) -> str:
+ """Create a default SVG path string with configurable positioning and sizing.
+
+ Args:
+ location_view: LocationView for calculating dimensions
+ is_path_closed: Whether to create closed (rectangle) or open (line) path
+ center_x: X position for path center (defaults to view center)
+ center_y: Y position for path center (defaults to view center)
+ entity_type: EntityType for entity-specific radius (optional)
+ collection_type: CollectionType for collection-specific radius (optional)
+ radius_multiplier: Multiplier for radius size (e.g., 2.0 for double size)
+
+ Returns:
+ SVG path string
+ """
+ # Default to view center if no center provided
+ if center_x is None:
+ center_x = location_view.svg_view_box.x + (location_view.svg_view_box.width / 2.0)
+ if center_y is None:
+ center_y = location_view.svg_view_box.y + (location_view.svg_view_box.height / 2.0)
+
+ # Get type-specific radius if provided, otherwise use default calculation
+ radius_x = None
+ radius_y = None
+
+ if entity_type:
+ entity_radius = cls.get_entity_radius(entity_type)
+ radius_x = entity_radius.x
+ radius_y = entity_radius.y
+ elif collection_type:
+ collection_radius = cls.get_collection_radius(collection_type)
+ radius_x = collection_radius.x
+ radius_y = collection_radius.y
+
+ # Apply default calculation for None values
+ if radius_x is None:
+ radius_x = location_view.svg_view_box.width * (cls.DEFAULT_RADIUS_PERCENT / 50.0)
+ if radius_y is None:
+ radius_y = location_view.svg_view_box.height * (cls.DEFAULT_RADIUS_PERCENT / 50.0)
+
+ # Apply radius multiplier
+ radius_x *= radius_multiplier
+ radius_y *= radius_multiplier
+
+ if is_path_closed:
+ # Rectangle for closed paths
+ top_left_x = center_x - radius_x
+ top_left_y = center_y - radius_y
+ top_right_x = center_x + radius_x
+ top_right_y = center_y - radius_y
+ bottom_right_x = center_x + radius_x
+ bottom_right_y = center_y + radius_y
+ bottom_left_x = center_x - radius_x
+ bottom_left_y = center_y + radius_y
+ return f'M {top_left_x},{top_left_y} L {top_right_x},{top_right_y} L {bottom_right_x},{bottom_right_y} L {bottom_left_x},{bottom_left_y} Z'
+ else:
+ # Line for open paths
+ start_x = center_x - radius_x
+ start_y = center_y
+ end_x = center_x + radius_x
+ end_y = center_y
+ return f'M {start_x},{start_y} L {end_x},{end_y}'
diff --git a/src/hi/apps/location/svg_item_factory.py b/src/hi/apps/location/svg_item_factory.py
index 9f043f20..4a208401 100644
--- a/src/hi/apps/location/svg_item_factory.py
+++ b/src/hi/apps/location/svg_item_factory.py
@@ -1,4 +1,5 @@
from hi.apps.common.singleton import Singleton
+from hi.apps.location.path_geometry import PathGeometry
from hi.apps.common.svg_models import SvgIconItem, SvgPathItem, SvgStatusStyle, SvgViewBox
from hi.apps.collection.models import Collection
from hi.apps.entity.models import Entity
@@ -95,10 +96,10 @@ class SvgItemFactory( Singleton ):
if isinstance( obj, Entity ):
entity_type = obj.entity_type
- if entity_type in EntityStyle.EntityTypeOpenPaths:
+ if entity_type.requires_open_path():
return SvgItemType.OPEN_PATH
- if entity_type in EntityStyle.EntityTypeClosedPaths:
+ if entity_type.requires_closed_path():
return SvgItemType.CLOSED_PATH
return SvgItemType.ICON
@@ -114,63 +115,21 @@ class SvgItemFactory( Singleton ):
entity : Entity,
location_view : LocationView,
is_path_closed : bool ) -> str:
- radius = EntityStyle.get_svg_path_initial_radius( entity_type = entity.entity_type )
- return self.get_default_svg_path_str(
- location_view = location_view,
- is_path_closed = is_path_closed,
- radius_x = radius.x,
- radius_y = radius.y,
+ return PathGeometry.create_default_path_string(
+ location_view=location_view,
+ is_path_closed=is_path_closed,
+ entity_type=entity.entity_type,
)
def get_default_collection_svg_path_str( self,
collection : Collection,
location_view : LocationView,
is_path_closed : bool ) -> str:
- radius = CollectionStyle.get_svg_path_initial_radius( collection_type = collection.collection_type )
- return self.get_default_svg_path_str(
- location_view = location_view,
- is_path_closed = is_path_closed,
- radius_x = radius.x,
- radius_y = radius.y,
+ # Use unified PathGeometry approach for collections
+ return PathGeometry.create_default_path_string(
+ location_view=location_view,
+ is_path_closed=is_path_closed,
+ collection_type=collection.collection_type,
)
- def get_default_svg_path_str( self,
- location_view : LocationView,
- is_path_closed : bool,
- radius_x : float = None,
- radius_y : float = None ) -> str:
-
- # Note that this server-side creation of a new path is just one
- # place new paths can be created. During client-side path editing,
- # the Javascript code also uses logic to add new path segments.
- # These do not have to behave identical, but it is preferrable for
- # there to be some consistency.
-
- # Default display a line or rectangle in middle of current view with radius X% of viewbox
- if radius_x is None:
- radius_x = location_view.svg_view_box.width * ( self.NEW_PATH_RADIUS_PERCENT / 50.0 )
- if radius_y is None:
- radius_y = location_view.svg_view_box.height * ( self.NEW_PATH_RADIUS_PERCENT / 50.0 )
-
- center_x = location_view.svg_view_box.x + ( location_view.svg_view_box.width / 2.0 )
- center_y = location_view.svg_view_box.y + ( location_view.svg_view_box.height / 2.0 )
-
- if is_path_closed:
- top_left_x = center_x - radius_x
- top_left_y = center_y - radius_y
- top_right_x = center_x + radius_x
- top_right_y = center_y - radius_y
- bottom_right_x = center_x + radius_x
- bottom_right_y = center_y + radius_y
- bottom_left_x = center_x - radius_x
- bottom_left_y = center_y + radius_y
- svg_path = f'M {top_left_x},{top_left_y} L {top_right_x},{top_right_y} L {bottom_right_x},{bottom_right_y} L {bottom_left_x},{bottom_left_y} Z'
- else:
- start_x = center_x - radius_x
- start_y = center_y
- end_x = start_x + radius_x
- end_y = start_y
- svg_path = f'M {start_x},{start_y} L {end_x},{end_y}'
-
- return svg_path
diff --git a/src/hi/apps/location/tests/test_path_geometry.py b/src/hi/apps/location/tests/test_path_geometry.py
new file mode 100644
index 00000000..d0ec0cb2
--- /dev/null
+++ b/src/hi/apps/location/tests/test_path_geometry.py
@@ -0,0 +1,244 @@
+from django.test import TestCase
+
+from hi.apps.entity.enums import EntityType
+from hi.apps.collection.enums import CollectionType
+from hi.apps.location.models import Location, LocationView
+from hi.apps.location.path_geometry import PathGeometry
+
+
+class TestPathGeometry(TestCase):
+ """Test the PathGeometry utility class for generating default SVG paths."""
+
+ def setUp(self):
+ """Set up test data."""
+ self.location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='test.svg',
+ svg_view_box_str='0 0 200 100',
+ order_id=1
+ )
+
+ self.location_view = LocationView.objects.create(
+ location=self.location,
+ location_view_type_str='DEFAULT',
+ name='Test View',
+ svg_view_box_str='0 0 200 100', # Width=200, Height=100, Center=(100,50)
+ svg_rotate=0,
+ svg_style_name_str='COLOR'
+ )
+
+ def test_get_entity_radius_configured_types(self):
+ """Test entity-specific radius configurations."""
+ # Test configured entity types
+ appliance_radius = PathGeometry.get_entity_radius(EntityType.APPLIANCE)
+ self.assertEqual(appliance_radius.x, 32)
+ self.assertEqual(appliance_radius.y, 32)
+
+ door_radius = PathGeometry.get_entity_radius(EntityType.DOOR)
+ self.assertIsNone(door_radius.x)
+ self.assertEqual(door_radius.y, 16)
+
+ wall_radius = PathGeometry.get_entity_radius(EntityType.WALL)
+ self.assertEqual(wall_radius.x, 16)
+ self.assertIsNone(wall_radius.y)
+
+ window_radius = PathGeometry.get_entity_radius(EntityType.WINDOW)
+ self.assertIsNone(window_radius.x)
+ self.assertEqual(window_radius.y, 16.0)
+
+ furniture_radius = PathGeometry.get_entity_radius(EntityType.FURNITURE)
+ self.assertEqual(furniture_radius.x, 64)
+ self.assertEqual(furniture_radius.y, 32)
+
+ def test_get_entity_radius_default(self):
+ """Test default radius for unconfigured entity types."""
+ other_radius = PathGeometry.get_entity_radius(EntityType.OTHER)
+ self.assertIsNone(other_radius.x)
+ self.assertIsNone(other_radius.y)
+
+ def test_create_default_path_closed_no_entity_type(self):
+ """Test closed path creation with default settings."""
+ svg_path = PathGeometry.create_default_path_string(
+ location_view=self.location_view,
+ is_path_closed=True
+ )
+
+ # Should be a rectangle path
+ self.assertIn('M ', svg_path) # Move command
+ self.assertIn(' L ', svg_path) # Line commands
+ self.assertTrue(svg_path.endswith(' Z')) # Close command
+
+ # Should be centered at view center (100, 50)
+ # Default radius: width=200*5%/50*100 = 20, height=100*5%/50*100 = 10
+ expected_coords = [
+ '80.0,40.0', # top-left (100-20, 50-10)
+ '120.0,40.0', # top-right (100+20, 50-10)
+ '120.0,60.0', # bottom-right (100+20, 50+10)
+ '80.0,60.0' # bottom-left (100-20, 50+10)
+ ]
+
+ for coord in expected_coords:
+ self.assertIn(coord, svg_path)
+
+ def test_create_default_path_open_no_entity_type(self):
+ """Test open path creation with default settings."""
+ svg_path = PathGeometry.create_default_path_string(
+ location_view=self.location_view,
+ is_path_closed=False
+ )
+
+ # Should be a line path
+ self.assertIn('M ', svg_path) # Move command
+ self.assertIn(' L ', svg_path) # Line command
+ self.assertNotIn(' Z', svg_path) # No close command
+
+ # Should be horizontal line centered at (100, 50)
+ # Default radius_x: 200*5%/50*100 = 20
+ self.assertIn('80.0,50.0', svg_path) # start (100-20, 50)
+ self.assertIn('120.0,50.0', svg_path) # end (100+20, 50)
+
+ def test_create_default_path_with_entity_type_door(self):
+ """Test path creation with entity-specific radius (DOOR: y=16)."""
+ svg_path = PathGeometry.create_default_path_string(
+ location_view=self.location_view,
+ is_path_closed=True,
+ entity_type=EntityType.DOOR
+ )
+
+ # DOOR has y=16, x=None (defaults to 20)
+ expected_coords = [
+ '80.0,34.0', # top-left (100-20, 50-16)
+ '120.0,34.0', # top-right (100+20, 50-16)
+ '120.0,66.0', # bottom-right (100+20, 50+16)
+ '80.0,66.0' # bottom-left (100-20, 50+16)
+ ]
+
+ for coord in expected_coords:
+ self.assertIn(coord, svg_path)
+
+ def test_create_default_path_with_entity_type_wall(self):
+ """Test path creation with entity-specific radius (WALL: x=16)."""
+ svg_path = PathGeometry.create_default_path_string(
+ location_view=self.location_view,
+ is_path_closed=True,
+ entity_type=EntityType.WALL
+ )
+
+ # WALL has x=16, y=None (defaults to 10)
+ expected_coords = [
+ '84.0,40.0', # top-left (100-16, 50-10)
+ '116.0,40.0', # top-right (100+16, 50-10)
+ '116.0,60.0', # bottom-right (100+16, 50+10)
+ '84.0,60.0' # bottom-left (100-16, 50+10)
+ ]
+
+ for coord in expected_coords:
+ self.assertIn(coord, svg_path)
+
+ def test_create_default_path_custom_center(self):
+ """Test path creation with custom center position."""
+ svg_path = PathGeometry.create_default_path_string(
+ location_view=self.location_view,
+ is_path_closed=False,
+ center_x=150.0,
+ center_y=25.0
+ )
+
+ # Should be line centered at (150, 25)
+ # Default radius_x: 20
+ self.assertIn('130.0,25.0', svg_path) # start (150-20, 25)
+ self.assertIn('170.0,25.0', svg_path) # end (150+20, 25)
+
+ def test_create_default_path_radius_multiplier(self):
+ """Test path creation with radius multiplier."""
+ svg_path = PathGeometry.create_default_path_string(
+ location_view=self.location_view,
+ is_path_closed=True,
+ radius_multiplier=2.0
+ )
+
+ # Default radius * 2: x=40, y=20
+ expected_coords = [
+ '60.0,30.0', # top-left (100-40, 50-20)
+ '140.0,30.0', # top-right (100+40, 50-20)
+ '140.0,70.0', # bottom-right (100+40, 50+20)
+ '60.0,70.0' # bottom-left (100-40, 50+20)
+ ]
+
+ for coord in expected_coords:
+ self.assertIn(coord, svg_path)
+
+ def test_create_default_path_entity_type_with_multiplier(self):
+ """Test path creation with entity type and radius multiplier."""
+ svg_path = PathGeometry.create_default_path_string(
+ location_view=self.location_view,
+ is_path_closed=True,
+ entity_type=EntityType.APPLIANCE, # x=32, y=32
+ radius_multiplier=0.5
+ )
+
+ # APPLIANCE radius * 0.5: x=16, y=16
+ expected_coords = [
+ '84.0,34.0', # top-left (100-16, 50-16)
+ '116.0,34.0', # top-right (100+16, 50-16)
+ '116.0,66.0', # bottom-right (100+16, 50+16)
+ '84.0,66.0' # bottom-left (100-16, 50+16)
+ ]
+
+ for coord in expected_coords:
+ self.assertIn(coord, svg_path)
+
+ def test_default_radius_percent_constant(self):
+ """Test the DEFAULT_RADIUS_PERCENT constant."""
+ self.assertEqual(PathGeometry.DEFAULT_RADIUS_PERCENT, 5.0)
+ self.assertGreater(PathGeometry.DEFAULT_RADIUS_PERCENT, 0)
+ self.assertLess(PathGeometry.DEFAULT_RADIUS_PERCENT, 50)
+
+ def test_get_collection_radius_default(self):
+ """Test collection radius for types without specific configurations."""
+ # Test default behavior for collection types
+ appliances_radius = PathGeometry.get_collection_radius(CollectionType.APPLIANCES)
+ self.assertIsNone(appliances_radius.x)
+ self.assertIsNone(appliances_radius.y)
+
+ devices_radius = PathGeometry.get_collection_radius(CollectionType.DEVICES)
+ self.assertIsNone(devices_radius.x)
+ self.assertIsNone(devices_radius.y)
+
+ def test_create_default_path_with_collection_type(self):
+ """Test path creation with collection type uses default behavior."""
+ svg_path = PathGeometry.create_default_path_string(
+ location_view=self.location_view,
+ is_path_closed=True,
+ collection_type=CollectionType.APPLIANCES
+ )
+
+ # Should be a rectangle path with default sizing
+ self.assertIn('M ', svg_path) # Move command
+ self.assertIn(' L ', svg_path) # Line commands
+ self.assertTrue(svg_path.endswith(' Z')) # Close command
+
+ # Should use default radius since CollectionTypePathInitialRadius is empty
+ # Default radius: width=200*5%/50*100 = 20, height=100*5%/50*100 = 10
+ expected_coords = [
+ '80.0,40.0', # top-left (100-20, 50-10)
+ '120.0,40.0', # top-right (100+20, 50-10)
+ '120.0,60.0', # bottom-right (100+20, 50+10)
+ '80.0,60.0' # bottom-left (100-20, 50+10)
+ ]
+
+ for coord in expected_coords:
+ self.assertIn(coord, svg_path)
+
+ def test_entity_type_and_collection_type_mutual_exclusion(self):
+ """Test that entity_type takes precedence over collection_type if both provided."""
+ svg_path = PathGeometry.create_default_path_string(
+ location_view=self.location_view,
+ is_path_closed=True,
+ entity_type=EntityType.DOOR, # Has y=16 radius
+ collection_type=CollectionType.APPLIANCES # Should be ignored
+ )
+
+ # Should use entity-specific radius (DOOR has y=16), not collection defaults
+ self.assertIn('34.0', svg_path) # Should have y=50-16=34 (entity radius)
+ self.assertIn('66.0', svg_path) # Should have y=50+16=66 (entity radius)
diff --git a/src/hi/apps/location/tests/test_svg_item_factory.py b/src/hi/apps/location/tests/test_svg_item_factory.py
index c923dfb7..a2d23fc9 100644
--- a/src/hi/apps/location/tests/test_svg_item_factory.py
+++ b/src/hi/apps/location/tests/test_svg_item_factory.py
@@ -139,8 +139,8 @@ class TestSvgItemFactory(BaseTestCase):
self.assertEqual(path_item.fill_color, '#00ff00')
return
- def test_get_default_svg_path_str_closed_path(self):
- """Test default closed path generation - complex geometric calculations."""
+ def test_get_default_entity_svg_path_str_closed_path(self):
+ """Test SvgItemFactory integration with PathGeometry for entity paths."""
factory = SvgItemFactory()
location = Location.objects.create(
@@ -158,25 +158,34 @@ class TestSvgItemFactory(BaseTestCase):
svg_style_name_str='COLOR'
)
- # Generate closed path (rectangle)
- svg_path = factory.get_default_svg_path_str(
+ # Create entity with path-based EntityType
+ from hi.apps.entity.models import Entity
+ from hi.apps.entity.enums import EntityType
+ entity = Entity.objects.create(
+ name='Test Door',
+ entity_type=EntityType.DOOR # Closed path type with y=16 radius
+ )
+
+ # Test SvgItemFactory correctly delegates to PathGeometry
+ svg_path = factory.get_default_entity_svg_path_str(
+ entity=entity,
location_view=location_view,
is_path_closed=True
)
- # Should be a rectangle path centered in viewbox
+ # Should be a rectangle path
self.assertIn('M ', svg_path) # Move to start
self.assertIn(' L ', svg_path) # Line commands
self.assertIn(' Z', svg_path) # Close path
- # Should contain reasonable coordinates
- # Path should be a rectangle with move and line commands
- coordinates = svg_path.replace('M ', '').replace(' L ', ',').replace(' Z', '').split(',')
- self.assertGreater(len(coordinates), 6) # Should have multiple coordinate pairs
+ # Should use entity-specific radius (DOOR has y=16)
+ # This verifies SvgItemFactory passes entity_type to PathGeometry
+ self.assertIn('34.0', svg_path) # Should have y=50-16=34
+ self.assertIn('66.0', svg_path) # Should have y=50+16=66
return
- def test_get_default_svg_path_str_open_path(self):
- """Test default open path generation - geometric calculations."""
+ def test_get_default_entity_svg_path_str_open_path(self):
+ """Test SvgItemFactory integration with PathGeometry for open paths."""
factory = SvgItemFactory()
location = Location.objects.create(
@@ -194,8 +203,17 @@ class TestSvgItemFactory(BaseTestCase):
svg_style_name_str='COLOR'
)
- # Generate open path (line)
- svg_path = factory.get_default_svg_path_str(
+ # Create entity with open path EntityType
+ from hi.apps.entity.models import Entity
+ from hi.apps.entity.enums import EntityType
+ entity = Entity.objects.create(
+ name='Test Wire',
+ entity_type=EntityType.ELECTRIC_WIRE # Open path type, uses defaults
+ )
+
+ # Test SvgItemFactory correctly delegates to PathGeometry
+ svg_path = factory.get_default_entity_svg_path_str(
+ entity=entity,
location_view=location_view,
is_path_closed=False
)
@@ -205,18 +223,16 @@ class TestSvgItemFactory(BaseTestCase):
self.assertIn(' L ', svg_path) # Line command
self.assertNotIn(' Z', svg_path) # No close command
- # Should contain reasonable coordinates
- self.assertIn('50', svg_path) # Should have center Y coordinate
+ # Should be centered horizontally at Y=50
+ self.assertIn('50.0', svg_path) # Should have center Y coordinate
return
- def test_new_path_radius_percent_constant(self):
- """Test NEW_PATH_RADIUS_PERCENT constant - important for UI consistency."""
+ def test_svg_item_factory_delegates_to_path_geometry(self):
+ """Test that SvgItemFactory properly delegates path generation to PathGeometry."""
+ # This test is already covered by the entity path generation tests above
+ # but we keep this as a placeholder to document the architectural relationship
factory = SvgItemFactory()
-
- # Should have reasonable default radius percentage
- self.assertEqual(factory.NEW_PATH_RADIUS_PERCENT, 5.0)
- self.assertGreater(factory.NEW_PATH_RADIUS_PERCENT, 0)
- self.assertLess(factory.NEW_PATH_RADIUS_PERCENT, 50)
+ self.assertTrue(hasattr(factory, 'get_default_entity_svg_path_str'))
return
def test_svg_item_factory_display_only_icon_generation(self):
diff --git a/src/hi/hi_styles.py b/src/hi/hi_styles.py
index 0c914f82..8dbd878b 100644
--- a/src/hi/hi_styles.py
+++ b/src/hi/hi_styles.py
@@ -345,26 +345,6 @@ class EntityStyle:
EntityType.WATER_HEATER: SvgViewBox( x = 0, y = 0, width = 38, height = 64 ),
EntityType.WATER_METER: SvgViewBox( x = 0, y = 0, width = 64, height = 43 ),
}
- EntityTypeClosedPaths = {
- EntityType.APPLIANCE,
- EntityType.AREA,
- EntityType.DOOR,
- EntityType.FURNITURE,
- EntityType.GREENHOUSE,
- EntityType.WALL,
- EntityType.WINDOW,
- }
- EntityTypeOpenPaths = {
- EntityType.CONTROL_WIRE,
- EntityType.ELECTRIC_WIRE,
- EntityType.FENCE,
- EntityType.PIPE,
- EntityType.SEWER_LINE,
- EntityType.SPEAKER_WIRE,
- EntityType.SPRINKLER_WIRE,
- EntityType.TELECOM_WIRE,
- EntityType.WATER_LINE,
- }
PathEntityTypeToSvgStatusStyle = {
EntityType.APPLIANCE: Appliance,
EntityType.AREA: Area,
@@ -383,13 +363,6 @@ class EntityStyle:
EntityType.WATER_LINE: WaterLine,
EntityType.WINDOW: Window,
}
- EntityTypePathInitialRadius = {
- EntityType.APPLIANCE: SvgRadius( x = 32, y = 32 ),
- EntityType.DOOR: SvgRadius( x = None, y = 16 ),
- EntityType.FURNITURE: SvgRadius( x = 64, y = 32 ),
- EntityType.WALL: SvgRadius( x = 16, y = None ),
- EntityType.WINDOW: SvgRadius( x = None, y = 16.0 ),
- }
@classmethod
def get_svg_icon_viewbox( cls, entity_type : EntityType ) -> SvgViewBox:
@@ -409,13 +382,7 @@ class EntityStyle:
return cls.PathEntityTypeToSvgStatusStyle.get( entity_type )
return ItemStyle.get_default_svg_path_status_style()
- @classmethod
- def get_svg_path_initial_radius( cls, entity_type : EntityType ) -> SvgRadius:
- if entity_type in cls.EntityTypePathInitialRadius:
- return cls.EntityTypePathInitialRadius.get( entity_type )
- return SvgRadius( x = None, y = None )
-
class StatusStyle:
DEFAULT_STATUS_VALUE = ''