Skip to content

Home Information - Your home, your data, organized.

Python

Issue #199: Pre-sync placement modal for integration sync (#286)

Tony C4504cd9616a1
diff --git a/src/hi/apps/collection/collection_manager.py b/src/hi/apps/collection/collection_manager.py
index 9e145684..ef3a179a 100644
--- a/src/hi/apps/collection/collection_manager.py
+++ b/src/hi/apps/collection/collection_manager.py
@@ -72,6 +72,50 @@ class CollectionManager(Singleton):
entity_status_data_list = entity_status_data_list,
)
+ def create_collection( self, name : str ) -> Collection:
+ """Create a new ``Collection`` with sensible defaults
+ (default collection_type, default collection_view_type,
+ next available order_id). The ``name`` is auto-disambiguated
+ against existing collections by appending ``(2)``, ``(3)``,
+ etc. — same pattern as ``LocationManager.create_location_view``.
+ Used by the dispatcher's '+ New collection' option."""
+ from .enums import CollectionType, CollectionViewType
+
+ last_collection = Collection.objects.order_by( '-order_id' ).first()
+ if last_collection:
+ order_id = last_collection.order_id + 1
+ else:
+ order_id = 0
+
+ resolved_name = self.resolve_unique_collection_name(
+ requested_name = name,
+ )
+
+ collection = Collection(
+ name = resolved_name,
+ order_id = order_id,
+ )
+ collection.collection_type = CollectionType.default()
+ collection.collection_view_type = CollectionViewType.default()
+ collection.save()
+ return collection
+
+ def resolve_unique_collection_name( self, requested_name : str ) -> str:
+ """Return ``requested_name`` if no Collection uses it;
+ otherwise append ``(2)``, ``(3)``, ... until a free name is
+ found. Collection names are global (unlike LocationView
+ names which are per-Location), so the namespace is the full
+ ``Collection.objects.all()`` set."""
+ existing_names = set( Collection.objects.values_list('name', flat=True) )
+ if requested_name not in existing_names:
+ return requested_name
+ suffix = 2
+ while True:
+ candidate = f'{requested_name} ({suffix})'
+ if candidate not in existing_names:
+ return candidate
+ suffix += 1
+
def create_collection_entity( self,
entity : Entity,
collection : Collection ) -> CollectionEntity:
diff --git a/src/hi/apps/collection/edit/views.py b/src/hi/apps/collection/edit/views.py
index d3a267bf..64139841 100644
--- a/src/hi/apps/collection/edit/views.py
+++ b/src/hi/apps/collection/edit/views.py
@@ -273,7 +273,7 @@ class CollectionReorderEntitiesView( View, CollectionViewMixin ):
raise BadRequest( str(e) )
if not entity_id_list:
- raise BadRequest( 'Missing entity ids.' )
+ raise BadRequest( 'Missing item ids.' )
CollectionManager().set_collection_entity_order(
collection = collection,
diff --git a/src/hi/apps/collection/tests/test_collection_manager.py b/src/hi/apps/collection/tests/test_collection_manager.py
index 84a4da67..c997524b 100644
--- a/src/hi/apps/collection/tests/test_collection_manager.py
+++ b/src/hi/apps/collection/tests/test_collection_manager.py
@@ -656,3 +656,30 @@ class TestCollectionManager(BaseTestCase):
return
+
+class TestCollectionManagerCreateCollection(BaseTestCase):
+ """create_collection auto-disambiguates duplicate names. Used by
+ the dispatcher's '+ New collection: "<integration label>"'
+ option (when the operator already has a Collection with that
+ name)."""
+
+ def test_unique_name_passes_through_unchanged(self):
+ collection = CollectionManager().create_collection(name='Tools')
+ self.assertEqual(collection.name, 'Tools')
+ self.assertIsNotNone(collection.collection_type)
+ self.assertIsNotNone(collection.collection_view_type)
+
+ def test_first_collision_gets_suffix_2(self):
+ manager = CollectionManager()
+ first = manager.create_collection(name='HomeBox')
+ second = manager.create_collection(name='HomeBox')
+ self.assertEqual(first.name, 'HomeBox')
+ self.assertEqual(second.name, 'HomeBox (2)')
+
+ def test_subsequent_collisions_increment_suffix(self):
+ manager = CollectionManager()
+ manager.create_collection(name='Inventory')
+ manager.create_collection(name='Inventory')
+ third = manager.create_collection(name='Inventory')
+ self.assertEqual(third.name, 'Inventory (3)')
+
diff --git a/src/hi/apps/config/signals.py b/src/hi/apps/config/signals.py
index 87144464..dda10c5c 100644
--- a/src/hi/apps/config/signals.py
+++ b/src/hi/apps/config/signals.py
@@ -60,6 +60,10 @@ class SettingsInitializer:
name = app_settings.label,
subsystem_key = app_settings.app_name,
)
+ else:
+ if subsystem.name != app_settings.label:
+ subsystem.name = app_settings.label
+ subsystem.save( update_fields = ['name'] )
self._create_attributes_if_needed(
subsystem = subsystem,
app_settings = app_settings,
@@ -101,4 +105,11 @@ class SettingsInitializer:
is_editable = setting_definition.is_editable,
is_required = setting_definition.is_required,
)
+ else:
+ if attribute.name != setting_definition.label:
+ attribute.name = setting_definition.label
+ attribute.save(
+ update_fields = ['name'],
+ track_history = False,
+ )
return attribute
diff --git a/src/hi/apps/entity/edit/entity_type_transition_handler.py b/src/hi/apps/entity/edit/entity_type_transition_handler.py
index 671f8fd4..13132bb8 100644
--- a/src/hi/apps/entity/edit/entity_type_transition_handler.py
+++ b/src/hi/apps/entity/edit/entity_type_transition_handler.py
@@ -12,7 +12,7 @@ from django.http import HttpRequest, HttpResponse
import hi.apps.common.antinode as antinode
from hi.apps.location.location_manager import LocationManager
from hi.apps.location.models import LocationView
-from hi.apps.entity.entity_manager import EntityManager
+from hi.apps.entity.entity_placement import EntityPlacer
from hi.apps.entity.enums import EntityTransitionType
from hi.apps.entity.models import Entity
from hi.apps.entity.forms import EntityForm, EntityAttributeRegularFormSet
@@ -83,7 +83,7 @@ class EntityTypeTransitionHandler:
current_location_view: Optional['LocationView'] = LocationManager().get_default_location_view(request=request)
transition_occurred: bool
transition_type: EntityTransitionType
- transition_occurred, transition_type = EntityManager().handle_entity_type_transition(
+ transition_occurred, transition_type = EntityPlacer().handle_entity_type_transition(
entity=entity,
location_view=current_location_view,
)
diff --git a/src/hi/apps/entity/edit/tests/test_entity_type_transition_handler.py b/src/hi/apps/entity/edit/tests/test_entity_type_transition_handler.py
index d6208ba0..7f63fd46 100644
--- a/src/hi/apps/entity/edit/tests/test_entity_type_transition_handler.py
+++ b/src/hi/apps/entity/edit/tests/test_entity_type_transition_handler.py
@@ -163,7 +163,7 @@ class TestEntityTypeTransitionHandlerTransitionLogic(BaseTestCase):
# Set the cached location_view so it doesn't need to query the DB
self.request.view_parameters._location_view = self.location_view
- @patch('hi.apps.entity.edit.entity_type_transition_handler.EntityManager')
+ @patch('hi.apps.entity.edit.entity_type_transition_handler.EntityPlacer')
def test_handle_entity_type_change_successful_transition(self, mock_entity_manager):
"""Test successful entity type change with transition using real location data."""
# Only mock the EntityManager's transition method since that's the complex business logic
@@ -181,7 +181,7 @@ class TestEntityTypeTransitionHandlerTransitionLogic(BaseTestCase):
self.assertIsNotNone(result)
self.assertIsInstance(result, HttpResponse)
- @patch('hi.apps.entity.edit.entity_type_transition_handler.EntityManager')
+ @patch('hi.apps.entity.edit.entity_type_transition_handler.EntityPlacer')
def test_handle_entity_type_change_failed_transition(self, mock_entity_manager):
"""Test entity type change when transition fails using real location data."""
# Mock failed transition
@@ -199,7 +199,7 @@ class TestEntityTypeTransitionHandlerTransitionLogic(BaseTestCase):
self.assertIsNotNone(result)
self.assertIsInstance(result, HttpResponse)
- @patch('hi.apps.entity.edit.entity_type_transition_handler.EntityManager')
+ @patch('hi.apps.entity.edit.entity_type_transition_handler.EntityPlacer')
def test_handle_entity_type_change_exception_handling(self, mock_entity_manager):
"""Test entity type change exception handling with real location data."""
# Mock entity manager to raise exception during transition
@@ -217,7 +217,7 @@ class TestEntityTypeTransitionHandlerTransitionLogic(BaseTestCase):
self.assertIsNotNone(result)
self.assertIsInstance(result, HttpResponse)
- @patch('hi.apps.entity.edit.entity_type_transition_handler.EntityManager')
+ @patch('hi.apps.entity.edit.entity_type_transition_handler.EntityPlacer')
def test_handle_entity_type_change_path_to_path_transition(self, mock_entity_manager):
"""Test path_to_path transition returns None (sidebar refresh only) with real location data."""
# Mock successful path_to_path transition
@@ -326,7 +326,7 @@ class TestEntityTypeTransitionHandlerIntegration(BaseTestCase):
# Set the cached location_view so it doesn't need to query the DB
self.request.view_parameters._location_view = self.location_view
- @patch('hi.apps.entity.edit.entity_type_transition_handler.EntityManager')
+ @patch('hi.apps.entity.edit.entity_type_transition_handler.EntityPlacer')
def test_complete_entity_type_change_scenario(self, mock_entity_mgr):
"""Test complete entity type change from LIGHT to WALL_SWITCH using real objects."""
entity = EntityAttributeSyntheticData.create_test_entity(entity_type_str=str(EntityType.LIGHT))
@@ -365,7 +365,7 @@ class TestEntityTypeTransitionHandlerIntegration(BaseTestCase):
self.assertIsNotNone(result)
self.assertIsInstance(result, HttpResponse)
- @patch('hi.apps.entity.edit.entity_type_transition_handler.EntityManager')
+ @patch('hi.apps.entity.edit.entity_type_transition_handler.EntityPlacer')
def test_transaction_rollback_on_transition_failure(self, mock_entity_mgr):
"""Test that transaction is properly managed even if transition fails using real objects."""
entity = EntityAttributeSyntheticData.create_test_entity(entity_type_str=str(EntityType.LIGHT))
diff --git a/src/hi/apps/entity/edit/tests/test_entity_type_transitions.py b/src/hi/apps/entity/edit/tests/test_entity_type_transitions.py
index f606ddd9..1d982b48 100644
--- a/src/hi/apps/entity/edit/tests/test_entity_type_transitions.py
+++ b/src/hi/apps/entity/edit/tests/test_entity_type_transitions.py
@@ -9,6 +9,7 @@ from django.db import transaction
from django.test import TransactionTestCase
from hi.apps.entity.entity_manager import EntityManager
+from hi.apps.entity.entity_placement import EntityPlacer
from hi.apps.entity.enums import EntityType, EntityTransitionType
from hi.apps.entity.models import Entity, EntityPath, EntityPosition
from hi.apps.location.models import Location, LocationView
@@ -24,7 +25,7 @@ class TestEntityTypeTransitions(TransactionTestCase):
# Reset singleton state for test isolation
EntityManager._instances = {}
- self.manager = EntityManager()
+ self.placer = EntityPlacer()
# Create test data
self.location = Location.objects.create(
@@ -63,7 +64,7 @@ class TestEntityTypeTransitions(TransactionTestCase):
self.entity.save()
# Perform transition
- transition_occurred, transition_type = self.manager.handle_entity_type_transition(
+ transition_occurred, transition_type = self.placer.handle_entity_type_transition(
entity = self.entity,
location_view = self.location_view,
)
@@ -111,7 +112,7 @@ class TestEntityTypeTransitions(TransactionTestCase):
self.entity.save()
# Perform transition
- transition_occurred, transition_type = self.manager.handle_entity_type_transition(
+ transition_occurred, transition_type = self.placer.handle_entity_type_transition(
entity = self.entity,
location_view = self.location_view,
)
@@ -158,7 +159,7 @@ class TestEntityTypeTransitions(TransactionTestCase):
# Transition icon->path
self.entity.entity_type_str = str(EntityType.WALL)
self.entity.save()
- self.manager.handle_entity_type_transition(
+ self.placer.handle_entity_type_transition(
entity = self.entity,
location_view = self.location_view,
)
@@ -166,7 +167,7 @@ class TestEntityTypeTransitions(TransactionTestCase):
# 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(
+ transition_occurred, transition_type = self.placer.handle_entity_type_transition(
entity = self.entity,
location_view = self.location_view,
)
@@ -202,7 +203,7 @@ class TestEntityTypeTransitions(TransactionTestCase):
)
# Transition to icon type
- transition_occurred, transition_type = self.manager.handle_entity_type_transition(
+ transition_occurred, transition_type = self.placer.handle_entity_type_transition(
entity = self.entity,
location_view = self.location_view,
)
@@ -214,7 +215,7 @@ class TestEntityTypeTransitions(TransactionTestCase):
# 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(
+ transition_occurred, transition_type = self.placer.handle_entity_type_transition(
entity = self.entity,
location_view = self.location_view,
)
@@ -244,7 +245,7 @@ class TestEntityTypeTransitions(TransactionTestCase):
self.entity.entity_type_str = str(EntityType.CAMERA)
self.entity.save()
- transition_occurred, transition_type = self.manager.handle_entity_type_transition(
+ transition_occurred, transition_type = self.placer.handle_entity_type_transition(
entity = self.entity,
location_view = self.location_view,
)
@@ -274,7 +275,7 @@ class TestEntityTypeTransitions(TransactionTestCase):
self.entity.entity_type_str = str(EntityType.FENCE)
self.entity.save()
- transition_occurred, transition_type = self.manager.handle_entity_type_transition(
+ transition_occurred, transition_type = self.placer.handle_entity_type_transition(
entity = self.entity,
location_view = self.location_view,
)
@@ -289,7 +290,7 @@ class TestEntityTypeTransitions(TransactionTestCase):
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(
+ transition_occurred, transition_type = self.placer.handle_entity_type_transition(
entity = self.entity,
location_view = None,
)
@@ -298,25 +299,6 @@ class TestEntityTypeTransitions(TransactionTestCase):
self.assertEqual(transition_type, EntityTransitionType.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
@@ -326,18 +308,18 @@ class TestEntityTypeTransitions(TransactionTestCase):
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:
+ with patch.object(EntityPlacer, '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(
+ EntityPlacer().handle_entity_type_transition(
entity = self.entity,
location_view = self.location_view,
)
diff --git a/src/hi/apps/entity/edit/views.py b/src/hi/apps/entity/edit/views.py
index d3cfa68c..9a90729c 100644
--- a/src/hi/apps/entity/edit/views.py
+++ b/src/hi/apps/entity/edit/views.py
@@ -14,6 +14,7 @@ from hi.apps.collection.collection_manager import CollectionManager
import hi.apps.common.antinode as antinode
from hi.apps.entity.entity_manager import EntityManager
from hi.apps.entity.entity_pairing_manager import EntityPairingManager, EntityPairingError
+from hi.apps.entity.entity_placement import EntityPlacer
from hi.apps.entity.edit.entity_type_transition_handler import EntityTypeTransitionHandler
from hi.apps.entity.forms import EntityAddForm, EntityForm
from hi.apps.entity.models import (
@@ -126,7 +127,7 @@ class EntityAddView( HiModalView ):
if request.view_parameters.view_type.is_location_view:
try:
current_location_view = LocationManager().get_default_location_view( request = request )
- EntityManager().add_entity_to_view(
+ EntityPlacer().place_entity_in_view(
entity = entity,
location_view = current_location_view,
bulk_grid_index = bulk_grid_index,
@@ -161,7 +162,7 @@ class EntityDeleteView( HiModalView, EntityViewMixin ):
entity = self.get_entity( request, *args, **kwargs )
if not entity.can_user_delete:
- raise PermissionDenied( 'This entity cannot be deleted.' )
+ raise PermissionDenied( 'This item cannot be deleted.' )
context = {
'entity': entity,
@@ -176,7 +177,7 @@ class EntityDeleteView( HiModalView, EntityViewMixin ):
raise BadRequest( 'Missing confirmation value.' )
if not entity.can_user_delete:
- raise PermissionDenied( 'This entity cannot be deleted.' )
+ raise PermissionDenied( 'This item cannot be deleted.' )
entity.delete()
@@ -344,7 +345,7 @@ class EntityArchiveView( HiModalView, EntityViewMixin ):
entity = self.get_entity( request, *args, **kwargs )
if entity.integration_id:
- raise PermissionDenied( 'Integration entities cannot be archived.' )
+ raise PermissionDenied( 'Integration items cannot be archived.' )
context = {
'entity': entity,
@@ -359,7 +360,7 @@ class EntityArchiveView( HiModalView, EntityViewMixin ):
raise BadRequest( 'Missing confirmation value.' )
if entity.integration_id:
- raise PermissionDenied( 'Integration entities cannot be archived.' )
+ raise PermissionDenied( 'Integration items cannot be archived.' )
with transaction.atomic():
archived_entity = ArchivedEntity.objects.create(
@@ -416,7 +417,7 @@ class EntityArchiveDetailView( HiModalView ):
try:
archived_entity = ArchivedEntity.objects.get( pk = archived_entity_id )
except ArchivedEntity.DoesNotExist:
- raise Http404( 'Archived entity not found.' )
+ raise Http404( 'Archived item not found.' )
context = {
'archived_entity': archived_entity,
diff --git a/src/hi/apps/entity/entity_manager.py b/src/hi/apps/entity/entity_manager.py
index acd57f46..28a386c7 100644
--- a/src/hi/apps/entity/entity_manager.py
+++ b/src/hi/apps/entity/entity_manager.py
@@ -1,23 +1,17 @@
-from decimal import Decimal
import logging
from threading import local
-from typing import List, Optional, Sequence, Tuple
+from typing import List, Sequence
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.hi_styles import EntityStyle
+from hi.apps.location.models import LocationView
from .entity_pairing_manager import EntityPairingManager
-from .enums import (
- EntityGroupType,
- EntityTransitionType,
-)
+from .entity_placement import EntityPlacer
+from .enums import EntityGroupType
from .models import (
Entity,
EntityAttribute,
@@ -37,11 +31,12 @@ logger = logging.getLogger(__name__)
class EntityManager(Singleton):
+ """Entity-domain coordination: edit-mode data assembly, view-group
+ rendering, capability listings, and the change-listener registry.
- DEFAULT_ICON_SIZE_PERCENT_OF_VIEWBOX = 10.0
- DEFAULT_INITIAL_POSITION_GRID_COLUMNS = 4
- DEFAULT_INITIAL_POSITION_GRID_SPACING_FRACTION = 0.18
- DEFAULT_INITIAL_POSITION_VIEWBOX_MARGIN_FRACTION = 0.05
+ Initial entity placement, persistence of EntityPosition /
+ EntityPath rows, and entity-type transitions all live in
+ ``hi.apps.entity.entity_placement``."""
def __init_singleton__(self):
self._change_listeners = list()
@@ -51,12 +46,12 @@ class EntityManager(Singleton):
def reload(self):
self._notify_change_listeners()
return
-
+
def register_change_listener( self, callback ):
logger.debug( f'Adding EntityManager change listener from {callback.__module__}' )
self._change_listeners.append( callback )
return
-
+
def _notify_change_listeners(self):
for callback in self._change_listeners:
try:
@@ -72,494 +67,20 @@ class EntityManager(Singleton):
is_editing : bool ) -> EntityEditModeData:
entity_position_form = None
- if is_editing and location_view:
- entity_position = EntityPosition.objects.filter(
+ if is_editing:
+ entity_position_form = EntityPlacer().get_entity_position_form(
entity = entity,
- location = location_view.location,
- ).first()
- if entity_position:
- entity_position_form = EntityPositionForm(
- location_view.location.svg_position_bounds,
- instance = entity_position,
- )
+ location_view = location_view,
+ )
entity_pairing_list = EntityPairingManager().get_entity_pairing_list( entity = entity )
-
+
return EntityEditModeData(
entity = entity,
entity_position_form = entity_position_form,
entity_pairing_list = entity_pairing_list,
)
- def set_entity_path( self,
- entity_id : int,
- location : Location,
- svg_path_str : str ) -> EntityPath:
-
- with transaction.atomic():
- try:
- entity_path = EntityPath.objects.get(
- location = location,
- entity_id = entity_id,
- )
- entity_path.svg_path = svg_path_str
- entity_path.save()
- return entity_path
-
- except EntityPath.DoesNotExist:
- pass
-
- entity = Entity.objects.get( id = entity_id )
- return EntityPath.objects.create(
- entity = entity,
- location = location,
- svg_path = svg_path_str,
- )
-
- def create_entity_view( self,
- entity : Entity,
- location_view : LocationView,
- bulk_grid_index : Optional[int] = None,
- bulk_grid_total : Optional[int] = None ):
-
- with transaction.atomic():
-
- # Need to make sure it has some visible representation in the view if none exists.
- 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 = entity_type.requires_closed_path(),
- )
- else:
- self.add_entity_position_if_needed(
- entity = entity,
- location_view = location_view,
- bulk_grid_index = bulk_grid_index,
- bulk_grid_total = bulk_grid_total,
- )
- try:
- entity_view = EntityView.objects.get(
- entity = entity,
- location_view = location_view,
- )
- except EntityView.DoesNotExist:
- entity_view = EntityView.objects.create(
- entity = entity,
- location_view = location_view,
- )
- return entity_view
-
- def remove_entity_view( self, entity : Entity, location_view : LocationView ):
-
- with transaction.atomic():
- entity_view = EntityView.objects.get(
- entity = entity,
- location_view = location_view,
- )
- entity_view.delete()
- return
-
- def add_entity_to_view( self,
- entity : Entity,
- location_view : LocationView,
- bulk_grid_index : Optional[int] = None,
- bulk_grid_total : Optional[int] = None ):
-
- with transaction.atomic():
- # Only create delegate entities the first time an entity is added to a view.
- if not entity.entity_views.all().exists():
- delegate_entity_list = EntityPairingManager().get_delegate_entities_with_defaults(
- entity = entity,
- )
- else:
- delegate_entity_list = EntityPairingManager().get_delegate_entities(
- entity = entity,
- )
-
- _ = self.create_entity_view(
- entity = entity,
- location_view = location_view,
- bulk_grid_index = bulk_grid_index,
- bulk_grid_total = bulk_grid_total,
- )
- for delegate_entity in delegate_entity_list:
- _ = self.create_entity_view(
- entity = delegate_entity,
- location_view = location_view,
- )
- continue
- return
-
- def toggle_entity_in_view( self, entity : Entity, location_view : LocationView ) -> bool:
-
- try:
- self.remove_entity_from_view( entity = entity, location_view = location_view )
- return False
- except EntityView.DoesNotExist:
- self.add_entity_to_view( entity = entity, location_view = location_view )
- return True
-
- def remove_entity_from_view( self, entity : Entity, location_view : LocationView ):
-
- with transaction.atomic():
- self.remove_entity_view(
- entity = entity,
- location_view = location_view,
- )
- EntityPairingManager().remove_delegate_entities_from_view_if_needed(
- entity = entity,
- location_view = location_view,
- )
- return
-
- def add_entity_position_if_needed( self,
- entity : Entity,
- location_view : LocationView,
- bulk_grid_index : Optional[int] = None,
- bulk_grid_total : Optional[int] = None ) -> EntityPosition:
- try:
- _ = EntityPosition.objects.get(
- location = location_view.location,
- entity = entity,
- )
- return
- except EntityPosition.DoesNotExist:
- pass
-
- if bulk_grid_total is not None and bulk_grid_total > 1 and bulk_grid_index is not None:
- svg_x, svg_y = self._get_bulk_initial_entity_position(
- location_view = location_view,
- bulk_grid_index = bulk_grid_index,
- bulk_grid_total = bulk_grid_total,
- )
- else:
- # Default display in middle of current view
- svg_x = location_view.svg_view_box.x + ( location_view.svg_view_box.width / 2.0 )
- svg_y = location_view.svg_view_box.y + ( location_view.svg_view_box.height / 2.0 )
-
- svg_scale = self._get_default_icon_scale( entity = entity, location_view = location_view )
-
- entity_position = EntityPosition.objects.create(
- entity = entity,
- location = location_view.location,
- svg_x = Decimal( svg_x ),
- svg_y = Decimal( svg_y ),
- svg_scale = svg_scale,
- svg_rotate = Decimal( 0.0 ),
- )
- return entity_position
-
- def _get_bulk_initial_entity_position( self,
- location_view : LocationView,
- bulk_grid_index : int,
- bulk_grid_total : int ) -> Tuple[float, float]:
- view_box = location_view.svg_view_box
- center_x = view_box.x + ( view_box.width / 2.0 )
- center_y = view_box.y + ( view_box.height / 2.0 )
-
- if bulk_grid_total <= 1:
- return center_x, center_y
-
- columns = min( max( 2, self.DEFAULT_INITIAL_POSITION_GRID_COLUMNS ), bulk_grid_total )
- rows = ( bulk_grid_total + columns - 1 ) // columns
-
- column_index = bulk_grid_index % columns
- row_index = bulk_grid_index // columns
-
- column_offset = column_index - ( ( columns - 1 ) / 2.0 )
- row_offset = row_index - ( ( rows - 1 ) / 2.0 )
-
- spacing_x = view_box.width * self.DEFAULT_INITIAL_POSITION_GRID_SPACING_FRACTION
- spacing_y = view_box.height * self.DEFAULT_INITIAL_POSITION_GRID_SPACING_FRACTION
-
- svg_x = center_x + ( column_offset * spacing_x )
- svg_y = center_y + ( row_offset * spacing_y )
-
- return self._clamp_point_to_viewbox(
- svg_x = svg_x,
- svg_y = svg_y,
- view_box = view_box,
- )
-
- def _clamp_point_to_viewbox( self,
- svg_x : float,
- svg_y : float,
- view_box ) -> Tuple[float, float]:
- margin_x = view_box.width * self.DEFAULT_INITIAL_POSITION_VIEWBOX_MARGIN_FRACTION
- margin_y = view_box.height * self.DEFAULT_INITIAL_POSITION_VIEWBOX_MARGIN_FRACTION
-
- min_x = view_box.x + margin_x
- max_x = ( view_box.x + view_box.width ) - margin_x
- min_y = view_box.y + margin_y
- max_y = ( view_box.y + view_box.height ) - margin_y
-
- if min_x > max_x:
- min_x = max_x = view_box.x + ( view_box.width / 2.0 )
- if min_y > max_y:
- min_y = max_y = view_box.y + ( view_box.height / 2.0 )
-
- clamped_x = max( min_x, min( svg_x, max_x ) )
- clamped_y = max( min_y, min( svg_y, max_y ) )
- return clamped_x, clamped_y
-
- def _get_default_icon_scale( self,
- entity : Entity,
- location_view : LocationView ) -> Decimal:
- view_box = location_view.svg_view_box
- icon_view_box = EntityStyle.get_svg_icon_viewbox( entity.entity_type )
-
- icon_max_dimension = max( icon_view_box.width, icon_view_box.height )
- if icon_max_dimension <= 0:
- return Decimal( '1.0' )
-
- viewbox_min_dimension = min( view_box.width, view_box.height )
- size_fraction = self.DEFAULT_ICON_SIZE_PERCENT_OF_VIEWBOX / 100.0
- target_icon_size = viewbox_min_dimension * size_fraction
- scale = target_icon_size / icon_max_dimension
-
- position_bounds = location_view.location.svg_position_bounds
- scale = max( position_bounds.min_scale, min( scale, position_bounds.max_scale ) )
-
- return Decimal( str(scale) )
-
- def add_entity_path_if_needed( self,
- entity : Entity,
- location_view : LocationView,
- is_path_closed : bool ) -> EntityPath:
- try:
- _ = EntityPath.objects.get(
- location = location_view.location,
- entity = entity,
- )
- return
- except EntityPath.DoesNotExist:
- pass
-
- # 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,
- location = location_view.location,
- svg_path = svg_path,
- )
- return entity_path
-
- def handle_entity_type_transition(
- self,
- entity : Entity,
- location_view : LocationView = None ) -> Tuple[bool, EntityTransitionType]:
- """
- 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, EntityTransitionType.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, EntityTransitionType.CREATED_POSITION
- else:
- # Position already exists, just a visual update
- return True, EntityTransitionType.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, EntityTransitionType.CREATED_PATH
- else:
- # Path already exists, just a visual update
- return True, EntityTransitionType.PATH_TO_PATH
-
- return False, EntityTransitionType.NO_TRANSITION_NEEDED
-
- def _transition_icon_to_path( self,
- entity : Entity,
- location_view : LocationView,
- entity_position : EntityPosition,
- is_path_closed : bool ) -> Tuple[bool, EntityTransitionType]:
- """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, EntityTransitionType.ICON_TO_PATH
-
- def _transition_path_to_icon( self,
- entity : Entity,
- location_view : LocationView,
- entity_path : EntityPath ) -> Tuple[bool, EntityTransitionType]:
- """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
- svg_scale = self._get_default_icon_scale( entity, location_view )
- 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': svg_scale,
- 'svg_rotate': Decimal(0.0),
- }
- )
-
- if not created:
- # EntityPosition already exists - preserve existing position
- pass # Keep existing position
-
- return True, EntityTransitionType.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,
unused_entity_ids : set = None ) -> List[EntityViewGroup]:
@@ -599,11 +120,11 @@ class EntityManager(Singleton):
for entity_group_type, entity_view_group in entity_view_group_dict.items():
entity_view_group.item_list.sort( key = lambda item : item.entity.name )
continue
-
+
entity_view_group_list = list( entity_view_group_dict.values() )
entity_view_group_list.sort( key = lambda item : item.entity_group_type.label )
return entity_view_group_list
-
+
def get_view_stream_entities(self) -> List[ Entity ]:
"""
Return all entities that have a video-stream capability AND are
@@ -618,7 +139,7 @@ class EntityManager(Singleton):
is_disabled = False,
))
-
+
_thread_local = local()
@@ -653,11 +174,10 @@ def entity_manager_model_changed( sender, instance, **kwargs ):
_thread_local.reload_registered = False
logger.debug( 'EntityManager model change detected.')
-
+
if not _thread_local.reload_registered:
logger.debug( 'Queuing EntityManager reload on model change.')
_thread_local.reload_registered = True
transaction.on_commit( do_entity_manager_reload )
-
+
return
-
diff --git a/src/hi/apps/entity/entity_placement.py b/src/hi/apps/entity/entity_placement.py
new file mode 100644
index 00000000..ba3d7cef
--- /dev/null
+++ b/src/hi/apps/entity/entity_placement.py
@@ -0,0 +1,864 @@
+"""
+Entity placement: putting entities into LocationViews.
+
+"Placement" is the union of (a) deciding what an entity should look
+like in a view (a centered icon, a default path), (b) persisting the
+chosen ``EntityPosition`` / ``EntityPath`` row, and (c) linking the
+entity to the ``LocationView`` via an ``EntityView``. All three are
+the responsibility of this module.
+
+Two collaborating classes:
+
+* ``EntityPlacementCalculator`` — orchestrates per-entity shape
+ selection (Point vs Path), delegating "where in the SVG" to
+ ``PositionGeometry`` and "how a path looks" to ``PathGeometry``.
+ Performs no DB writes.
+
+* ``EntityPlacer`` — DB-touching placer. Accepts either a
+ pre-computed ``PlacementShape`` (e.g., from Phase 3's dispatcher
+ modal that lays out an entire sync result group at once) or
+ derives one via the calculator. Persists the result, links the
+ entity to the view, manages delegates, owns un-place / toggle
+ counterparts, and runs entity-type transitions.
+
+Known limitation (carried over from earlier code, not introduced by
+this module): when an entity carrying delegate entities is placed
+into a view, the delegates are placed at the viewbox center
+without any spread. Multiple delegates therefore overlap. Phase 3
+inherits this behavior; revisit when it bites.
+"""
+
+from dataclasses import dataclass, field
+from decimal import Decimal
+import logging
+from typing import List, Optional, Tuple, Union
+
+from django.db import transaction
+
+from hi.apps.entity.edit.forms import EntityPositionForm
+from hi.apps.entity.enums import EntityTransitionType
+from hi.apps.location.models import Location, LocationView
+from hi.apps.location.path_geometry import PathGeometry
+from hi.apps.location.position_geometry import PositionGeometry
+
+from .entity_pairing_manager import EntityPairingManager
+from .models import (
+ Entity,
+ EntityPath,
+ EntityPosition,
+ EntityView,
+)
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass(frozen=True)
+class PlacementPoint:
+ """SVG icon placement: center-of-icon coordinates plus scale."""
+ svg_x: float
+ svg_y: float
+ svg_scale: Decimal
+
+
+@dataclass(frozen=True)
+class PlacementPath:
+ """SVG path placement: a fully-formed path string already centered
+ and sized for the chosen view."""
+ svg_path: str
+
+
+PlacementShape = Union[PlacementPoint, PlacementPath]
+
+
+@dataclass
+class EntityPlacementItem:
+ """A single entity destined for placement.
+
+ ``key`` is a stable identifier the dispatcher modal uses to
+ address this item across form turns; suppliers typically derive
+ it from a per-entity integration_key, but the placement layer
+ only requires uniqueness within a placement input.
+ """
+ key: str
+ label: str
+ entity: Entity
+
+
+@dataclass
+class EntityPlacementGroup:
+ """A supplier-defined grouping of items for the dispatcher modal.
+
+ Suppliers create groups when their domain has a meaningful
+ grouping notion (HASS by entity_type, ZM monitors). The
+ dispatcher presents groups verbatim.
+ """
+ label: str
+ items: List[EntityPlacementItem] = field(default_factory=list)
+
+
+@dataclass
+class EntityPlacementInput:
+ """The shape the dispatcher modal needs: groups and ungrouped
+ items to choose placements for.
+
+ Producible from any source — a freshly-run integration sync, a
+ "place unplaced items" recovery feature, or any future bulk-
+ placement flow. The placement layer does not know what produced
+ its input; suppliers do not know how the dispatcher renders or
+ applies the result.
+ """
+ groups: List[EntityPlacementGroup] = field(default_factory=list)
+ ungrouped_items: List[EntityPlacementItem] = field(default_factory=list)
+
+ def is_empty(self) -> bool:
+ if self.ungrouped_items:
+ return False
+ return not any( group.items for group in self.groups )
+
+ def all_entity_ids(self) -> 'List[int]':
+ """Flatten the entity ids from groups + ungrouped items.
+ Used by callers that need to thread the placement scope
+ through a URL or session — e.g., the sync-result CTA
+ passing the just-imported entity ids to the dispatcher
+ view so it scopes to those entities rather than all
+ unplaced ones for the integration."""
+ ids = []
+ for group in self.groups:
+ for item in group.items:
+ ids.append( item.entity.id )
+ for item in self.ungrouped_items:
+ ids.append( item.entity.id )
+ return ids
+
+
+@dataclass(frozen=True)
+class PlacementDecision:
+ """One entity → placement-target assignment chosen by the operator.
+
+ Targets are mutually exclusive: at most one of ``location_view``
+ and ``collection`` is set. Both None means the operator skipped
+ placement for this entity; skipped decisions are filtered out
+ before placement and counted toward the placement outcome's
+ ``skipped_entity_count``.
+ """
+ entity: Entity
+ location_view: Optional[LocationView] = None
+ collection: 'Optional[object]' = None # Collection; forward-decl
+
+ @property
+ def is_skip(self) -> bool:
+ return self.location_view is None and self.collection is None
+
+ @property
+ def is_view(self) -> bool:
+ return self.location_view is not None
+
+ @property
+ def is_collection(self) -> bool:
+ return self.collection is not None
+
+
+@dataclass(frozen=True)
+class PlacementSummary:
+ """One affected target + how many entities the bulk placer
+ placed into it. Targets are mutually exclusive: exactly one of
+ ``location_view`` or ``collection`` is set."""
+ placed_entity_count: int
+ location_view: Optional[LocationView] = None
+ collection: 'Optional[object]' = None # Collection; forward-decl
+
+ @property
+ def is_view(self) -> bool:
+ return self.location_view is not None
+
+ @property
+ def is_collection(self) -> bool:
+ return self.collection is not None
+
+ @property
+ def target_name(self) -> str:
+ if self.location_view is not None:
+ return self.location_view.name
+ return self.collection.name
+
+
+@dataclass
+class PlacementOutcome:
+ """Result of one bulk placement. Drives the post-dispatch modal:
+ per-target summary lines, primary 'Refine'/'Review' button
+ selection, the skipped count when present.
+
+ Lives in the placement layer rather than an integration layer
+ because the shape is supplier-agnostic — any future bulk-
+ placement flow that accepts placement decisions and applies
+ them produces this outcome.
+ """
+ summaries: List[PlacementSummary] = field(default_factory=list)
+ skipped_entity_count: int = 0
+
+ @property
+ def total_placed(self) -> int:
+ return sum(s.placed_entity_count for s in self.summaries)
+
+ @property
+ def primary_summary(self) -> Optional[PlacementSummary]:
+ """Highest-count summary, with view-targeted summaries
+ preferred over collection-targeted ones. The post-dispatch
+ modal's primary action is REFINE for views (drag entities
+ into spatial position) — meaningless for collections — so
+ when any view target was used, that's the primary slot.
+ Only when every placement landed in a Collection does the
+ primary become a Collection (with a REVIEW link instead of
+ REFINE)."""
+ view_summaries = [s for s in self.summaries if s.is_view]
+ if view_summaries:
+ return max(view_summaries, key=lambda s: s.placed_entity_count)
+ if self.summaries:
+ return max(self.summaries, key=lambda s: s.placed_entity_count)
+ return None
+
+ @property
+ def secondary_summaries(self) -> List[PlacementSummary]:
+ """All summaries except the primary, in input order."""
+ primary = self.primary_summary
+ if primary is None:
+ return []
+ result = []
+ skipped = False
+ for summary in self.summaries:
+ if not skipped and summary is primary:
+ skipped = True
+ continue
+ result.append(summary)
+ return result
+
+
+class EntityPlacementService:
+ """Bulk-placement operations: query candidate entities and apply
+ a list of operator placement decisions. Supplier-agnostic; the
+ integration sync flow and any future bulk-placement entry point
+ (e.g., a 'place unplaced items' recovery feature) call into this.
+ """
+
+ @classmethod
+ def query_unplaced_entities( cls,
+ integration_id : Optional[str] = None,
+ ) -> 'List[Entity]':
+ """Entities that have neither an EntityView nor a
+ CollectionEntity row — fully unplaced in the app. Optionally
+ filtered to a single integration. Used by the dispatcher
+ GET endpoint to seed the modal with what's left to place."""
+ queryset = Entity.objects.filter(
+ entity_views__isnull = True,
+ collections__isnull = True,
+ )
+ if integration_id is not None:
+ queryset = queryset.filter( integration_id = integration_id )
+ return list( queryset.distinct() )
+
+ @classmethod
+ def apply_decisions(
+ cls,
+ decisions : 'List[PlacementDecision]',
+ ) -> PlacementOutcome:
+ """Partition decisions by target (preserving first-seen
+ order so the post-dispatch summary lists targets in the
+ order the operator's choices produced them), invoke the
+ right placement op per target type, and aggregate per-
+ target counts into a PlacementOutcome.
+
+ View targets go through ``EntityPlacer.place_entities_in_view``;
+ Collection targets go through
+ ``CollectionManager.add_entity_to_collection``."""
+ from collections import OrderedDict
+ from hi.apps.collection.collection_manager import CollectionManager
+
+ outcome = PlacementOutcome()
+ # Key by (kind, id) so views and collections occupy distinct
+ # buckets even if their numeric ids overlap.
+ by_target = OrderedDict()
+ for decision in decisions:
+ if decision.is_skip:
+ outcome.skipped_entity_count += 1
+ continue
+ if decision.is_view:
+ key = ('view', decision.location_view.id)
+ else:
+ key = ('collection', decision.collection.id)
+ by_target.setdefault( key, [] ).append( decision )
+ continue
+ for (kind, _target_id), decision_list in by_target.items():
+ entities = [ d.entity for d in decision_list ]
+ if kind == 'view':
+ location_view = decision_list[0].location_view
+ EntityPlacer().place_entities_in_view(
+ entities = entities, location_view = location_view,
+ )
+ outcome.summaries.append( PlacementSummary(
+ placed_entity_count = len( entities ),
+ location_view = location_view,
+ ) )
+ else: # collection
+ collection = decision_list[0].collection
+ for entity in entities:
+ CollectionManager().add_entity_to_collection(
+ entity = entity, collection = collection,
+ )
+ outcome.summaries.append( PlacementSummary(
+ placed_entity_count = len( entities ),
+ collection = collection,
+ ) )
+ continue
+ return outcome
+
+
+class EntityPlacementCalculator:
+ """Orchestrates per-entity shape selection. Pure-functional;
+ performs no DB writes. The geometry math lives in
+ ``PositionGeometry`` (where) and ``PathGeometry`` (how a path
+ looks); this class branches on entity_type to decide which
+ output shape applies.
+ """
+
+ def shape_for_entity( self,
+ entity : Entity,
+ location_view : LocationView ) -> PlacementShape:
+ """Return the placement shape for a single entity centered on
+ the current viewbox."""
+ svg_x, svg_y = PositionGeometry.view_center( location_view )
+ return self._shape_at_point(
+ entity = entity,
+ location_view = location_view,
+ svg_x = svg_x,
+ svg_y = svg_y,
+ )
+
+ def shapes_for_entities( self,
+ entities : List[Entity],
+ location_view : LocationView ) -> List[PlacementShape]:
+ """Return one shape per entity in input order. Single-entity
+ input degenerates to ``shape_for_entity``. Larger groups get
+ a centered grid; each entity's slot becomes either a Point
+ (icon entities) or a Path centered on that slot (path
+ entities)."""
+ total = len( entities )
+ if total == 0:
+ return []
+ if total == 1:
+ return [ self.shape_for_entity(
+ entity = entities[0], location_view = location_view ) ]
+
+ return [
+ self._shape_at_grid_slot(
+ entity = entity,
+ location_view = location_view,
+ grid_index = index,
+ grid_total = total,
+ )
+ for index, entity in enumerate( entities )
+ ]
+
+ def default_icon_scale( self,
+ entity : Entity,
+ location_view : LocationView ) -> Decimal:
+ """Default scale for an icon entity. Delegates to
+ ``PositionGeometry.default_icon_scale``."""
+ return PositionGeometry.default_icon_scale(
+ entity = entity, location_view = location_view )
+
+ # ----- internal shape routing (no DB) -----
+
+ def _shape_at_grid_slot( self,
+ entity : Entity,
+ location_view : LocationView,
+ grid_index : int,
+ grid_total : int ) -> PlacementShape:
+ svg_x, svg_y = PositionGeometry.grid_slot(
+ location_view = location_view,
+ grid_index = grid_index,
+ grid_total = grid_total,
+ )
+ return self._shape_at_point(
+ entity = entity,
+ location_view = location_view,
+ svg_x = svg_x,
+ svg_y = svg_y,
+ )
+
+ def _shape_at_point( self,
+ entity : Entity,
+ location_view : LocationView,
+ svg_x : float,
+ svg_y : float ) -> PlacementShape:
+ entity_type = entity.entity_type
+ if entity_type.requires_path():
+ svg_path = PathGeometry.create_default_path_string(
+ location_view = location_view,
+ is_path_closed = entity_type.requires_closed_path(),
+ center_x = svg_x,
+ center_y = svg_y,
+ entity_type = entity_type,
+ )
+ return PlacementPath( svg_path = svg_path )
+
+ return PlacementPoint(
+ svg_x = svg_x,
+ svg_y = svg_y,
+ svg_scale = self.default_icon_scale(
+ entity = entity, location_view = location_view ),
+ )
+
+
+class EntityPlacer:
+ """DB-touching placement operations. Persists shapes computed by
+ EntityPlacementCalculator and links entities into LocationViews.
+ Pulls in delegate entities so callers don't have to. Also owns
+ user-drawn-path persistence, edit-form construction, and
+ entity-type transitions (icon ↔ path)."""
+
+ def __init__( self ):
+ self._calculator = EntityPlacementCalculator()
+ return
+
+ @property
+ def calculator(self) -> EntityPlacementCalculator:
+ return self._calculator
+
+ def place_entity_in_view( self,
+ entity : Entity,
+ location_view : LocationView,
+ placement_shape : Optional[PlacementShape] = None,
+ bulk_grid_index : Optional[int] = None,
+ bulk_grid_total : Optional[int] = None ):
+ """Place a single entity into a location view, including its
+ delegate entities. Idempotent: existing position/path/view rows
+ are preserved.
+
+ Three input modes for shape selection (in priority order):
+
+ 1. Caller provides ``placement_shape`` directly — used.
+ 2. Caller provides ``bulk_grid_index`` + ``bulk_grid_total``
+ (legacy form-driven flow) — calculator picks the slot.
+ 3. Otherwise — calculator centers the shape on the viewbox.
+
+ Delegates always go through mode (3): each delegate is placed
+ at the viewbox center. See module docstring on the
+ delegate-overlap limitation.
+ """
+ with transaction.atomic():
+ if not entity.entity_views.all().exists():
+ delegate_entity_list = (
+ EntityPairingManager().get_delegate_entities_with_defaults(
+ entity = entity )
+ )
+ else:
+ delegate_entity_list = (
+ EntityPairingManager().get_delegate_entities( entity = entity )
+ )
+
+ if placement_shape is None:
+ placement_shape = self._derive_placement_shape(
+ entity = entity,
+ location_view = location_view,
+ bulk_grid_index = bulk_grid_index,
+ bulk_grid_total = bulk_grid_total,
+ )
+ self._create_entity_view(
+ entity = entity,
+ location_view = location_view,
+ placement_shape = placement_shape,
+ )
+ for delegate_entity in delegate_entity_list:
+ delegate_shape = self._calculator.shape_for_entity(
+ entity = delegate_entity,
+ location_view = location_view,
+ )
+ self._create_entity_view(
+ entity = delegate_entity,
+ location_view = location_view,
+ placement_shape = delegate_shape,
+ )
+ continue
+ return
+
+ def place_entities_in_view( self,
+ entities : List[Entity],
+ location_view : LocationView ):
+ """Place a group of entities into a location view in a single
+ layout pass. Used by the post-sync dispatcher to position all
+ items in a result group together. The grid is computed once
+ across the entire group; per-entity delegates are placed by
+ the single-entity flow."""
+ shapes = self._calculator.shapes_for_entities(
+ entities = entities,
+ location_view = location_view,
+ )
+ with transaction.atomic():
+ for entity, shape in zip( entities, shapes ):
+ self.place_entity_in_view(
+ entity = entity,
+ location_view = location_view,
+ placement_shape = shape,
+ )
+ continue
+ return
+
+ def toggle_entity_in_view( self,
+ entity : Entity,
+ location_view : LocationView ) -> bool:
+ """Add the entity to the view if absent, or remove it if
+ present. Returns True if the entity is now in the view, False
+ otherwise."""
+ try:
+ self.unplace_entity_from_view(
+ entity = entity, location_view = location_view )
+ return False
+ except EntityView.DoesNotExist:
+ self.place_entity_in_view(
+ entity = entity, location_view = location_view )
+ return True
+
+ def ensure_default_shape_persisted( self,
+ entity : Entity,
+ location_view : LocationView ):
+ """Ensure the entity has either an EntityPosition or
+ EntityPath row for the location, creating it with default
+ placement if missing. Does NOT create an EntityView link.
+
+ Used by entity-type transition flows that already have an
+ EntityView and just need a shape row to exist (e.g., a type
+ change to a path-based type when no path row exists yet)."""
+ shape = self._calculator.shape_for_entity(
+ entity = entity,
+ location_view = location_view,
+ )
+ self._persist_placement_shape(
+ entity = entity,
+ location_view = location_view,
+ placement_shape = shape,
+ )
+ return
+
+ def unplace_entity_from_view( self,
+ entity : Entity,
+ location_view : LocationView ):
+ """Remove an entity (and its no-longer-needed delegates) from a
+ location view. Raises ``EntityView.DoesNotExist`` if the entity
+ is not in the view."""
+ with transaction.atomic():
+ self._delete_entity_view(
+ entity = entity,
+ location_view = location_view,
+ )
+ EntityPairingManager().remove_delegate_entities_from_view_if_needed(
+ entity = entity,
+ location_view = location_view,
+ )
+ return
+
+ def set_entity_path( self,
+ entity_id : int,
+ location : Location,
+ svg_path_str : str ) -> EntityPath:
+ """Persist a user-drawn path string into an ``EntityPath``
+ row, creating one if absent or updating in place if
+ present."""
+ with transaction.atomic():
+ try:
+ entity_path = EntityPath.objects.get(
+ location = location,
+ entity_id = entity_id,
+ )
+ entity_path.svg_path = svg_path_str
+ entity_path.save()
+ return entity_path
+
+ except EntityPath.DoesNotExist:
+ pass
+
+ entity = Entity.objects.get( id = entity_id )
+ return EntityPath.objects.create(
+ entity = entity,
+ location = location,
+ svg_path = svg_path_str,
+ )
+
+ def get_entity_position_form( self,
+ entity : Entity,
+ location_view : LocationView ) -> Optional[EntityPositionForm]:
+ """Return an ``EntityPositionForm`` bound to the entity's
+ existing position in this location, or None if the entity has
+ no position row. Used by the entity edit-mode UI."""
+ if not location_view:
+ return None
+ entity_position = EntityPosition.objects.filter(
+ entity = entity,
+ location = location_view.location,
+ ).first()
+ if not entity_position:
+ return None
+ return EntityPositionForm(
+ location_view.location.svg_position_bounds,
+ instance = entity_position,
+ )
+
+ def handle_entity_type_transition(
+ self,
+ entity : Entity,
+ location_view : LocationView = None ) -> Tuple[bool, EntityTransitionType]:
+ """Transition an entity's persisted geometry between icon
+ (EntityPosition) and path (EntityPath) representations
+ following an entity_type change.
+
+ Preservation strategy: when both representations already
+ exist, leave both rows in place and just classify the
+ transition for the caller. When only one exists and the new
+ type needs the other, build the missing one from the
+ existing one's center (path → icon uses path geometric
+ center; icon → path uses position center) so the visual
+ location is preserved across the type change. When neither
+ exists, create a default-placement shape.
+
+ Returns (transition_occurred, transition_type)."""
+ if not location_view:
+ return False, EntityTransitionType.NO_LOCATION_VIEW
+
+ entity_type = entity.entity_type
+
+ 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()
+
+ had_both = has_position and has_path
+
+ if had_both:
+ 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():
+ if needs_position:
+ if not has_position:
+ if has_path:
+ return self._transition_path_to_icon(
+ entity = entity,
+ location_view = location_view,
+ entity_path = entity_path,
+ )
+ self.ensure_default_shape_persisted(
+ entity = entity,
+ location_view = location_view,
+ )
+ return True, EntityTransitionType.CREATED_POSITION
+ return True, EntityTransitionType.ICON_TO_ICON
+
+ elif needs_path:
+ if not has_path:
+ 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(),
+ )
+ self.ensure_default_shape_persisted(
+ entity = entity,
+ location_view = location_view,
+ )
+ return True, EntityTransitionType.CREATED_PATH
+ return True, EntityTransitionType.PATH_TO_PATH
+
+ return False, EntityTransitionType.NO_TRANSITION_NEEDED
+
+ # ----- internal helpers -----
+
+ def _derive_placement_shape( self,
+ entity : Entity,
+ location_view : LocationView,
+ bulk_grid_index : Optional[int],
+ bulk_grid_total : Optional[int] ) -> PlacementShape:
+ if (
+ bulk_grid_total is not None
+ and bulk_grid_total > 1
+ and bulk_grid_index is not None
+ ):
+ return self._calculator._shape_at_grid_slot(
+ entity = entity,
+ location_view = location_view,
+ grid_index = bulk_grid_index,
+ grid_total = bulk_grid_total,
+ )
+ return self._calculator.shape_for_entity(
+ entity = entity, location_view = location_view )
+
+ def _create_entity_view( self,
+ entity : Entity,
+ location_view : LocationView,
+ placement_shape : PlacementShape ) -> EntityView:
+ with transaction.atomic():
+ self._persist_placement_shape(
+ entity = entity,
+ location_view = location_view,
+ placement_shape = placement_shape,
+ )
+ try:
+ entity_view = EntityView.objects.get(
+ entity = entity,
+ location_view = location_view,
+ )
+ except EntityView.DoesNotExist:
+ entity_view = EntityView.objects.create(
+ entity = entity,
+ location_view = location_view,
+ )
+ return entity_view
+
+ def _delete_entity_view( self,
+ entity : Entity,
+ location_view : LocationView ):
+ entity_view = EntityView.objects.get(
+ entity = entity,
+ location_view = location_view,
+ )
+ entity_view.delete()
+ return
+
+ def _persist_placement_shape( self,
+ entity : Entity,
+ location_view : LocationView,
+ placement_shape : PlacementShape ):
+ if isinstance( placement_shape, PlacementPoint ):
+ self._persist_position_if_needed(
+ entity = entity,
+ location_view = location_view,
+ placement_point = placement_shape,
+ )
+ elif isinstance( placement_shape, PlacementPath ):
+ self._persist_path_if_needed(
+ entity = entity,
+ location_view = location_view,
+ placement_path = placement_shape,
+ )
+ else:
+ raise TypeError(
+ f'Unrecognized placement shape: {type(placement_shape).__name__}'
+ )
+ return
+
+ def _persist_position_if_needed(
+ self,
+ entity : Entity,
+ location_view : LocationView,
+ placement_point : PlacementPoint ) -> Optional[EntityPosition]:
+ try:
+ return EntityPosition.objects.get(
+ location = location_view.location,
+ entity = entity,
+ )
+ except EntityPosition.DoesNotExist:
+ pass
+
+ return EntityPosition.objects.create(
+ entity = entity,
+ location = location_view.location,
+ svg_x = Decimal( str( placement_point.svg_x ) ),
+ svg_y = Decimal( str( placement_point.svg_y ) ),
+ svg_scale = placement_point.svg_scale,
+ svg_rotate = Decimal( '0.0' ),
+ )
+
+ def _persist_path_if_needed(
+ self,
+ entity : Entity,
+ location_view : LocationView,
+ placement_path : PlacementPath ) -> Optional[EntityPath]:
+ try:
+ return EntityPath.objects.get(
+ location = location_view.location,
+ entity = entity,
+ )
+ except EntityPath.DoesNotExist:
+ pass
+
+ return EntityPath.objects.create(
+ entity = entity,
+ location = location_view.location,
+ svg_path = placement_path.svg_path,
+ )
+
+ def _transition_icon_to_path(
+ self,
+ entity : Entity,
+ location_view : LocationView,
+ entity_position : EntityPosition,
+ is_path_closed : bool ) -> Tuple[bool, EntityTransitionType]:
+ """Create an EntityPath centered on the existing position so
+ the visual location is preserved. Existing EntityPath rows
+ (if any) are preserved verbatim (preservation strategy
+ allows easy reversion)."""
+ center_x = float( entity_position.svg_x )
+ center_y = float( entity_position.svg_y )
+
+ 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, # Larger for control-point visibility.
+ )
+ EntityPath.objects.get_or_create(
+ entity = entity,
+ location = location_view.location,
+ defaults = { 'svg_path': svg_path },
+ )
+ return True, EntityTransitionType.ICON_TO_PATH
+
+ def _transition_path_to_icon(
+ self,
+ entity : Entity,
+ location_view : LocationView,
+ entity_path : EntityPath ) -> Tuple[bool, EntityTransitionType]:
+ """Create an EntityPosition at the existing path's geometric
+ center so the visual location is preserved. Falls back to
+ the viewbox center when path-center extraction fails.
+ Existing EntityPosition rows (if any) are preserved
+ verbatim."""
+ center_x, center_y = PositionGeometry.path_center( entity_path.svg_path )
+ if center_x is None or center_y is None:
+ center_x, center_y = PositionGeometry.view_center( location_view )
+
+ svg_scale = self._calculator.default_icon_scale(
+ entity = entity, location_view = location_view )
+ EntityPosition.objects.get_or_create(
+ entity = entity,
+ location = location_view.location,
+ defaults = {
+ 'svg_x': Decimal( str( center_x ) ),
+ 'svg_y': Decimal( str( center_y ) ),
+ 'svg_scale': svg_scale,
+ 'svg_rotate': Decimal( '0.0' ),
+ },
+ )
+ return True, EntityTransitionType.PATH_TO_ICON
diff --git a/src/hi/apps/entity/forms.py b/src/hi/apps/entity/forms.py
index 4bddd016..c3eb75d2 100644
--- a/src/hi/apps/entity/forms.py
+++ b/src/hi/apps/entity/forms.py
@@ -75,7 +75,7 @@ class EntityAttributeRegularFormSet(RegularAttributeBaseFormSet):
)
if has_new_data:
raise forms.ValidationError(
- 'New attributes cannot be added for this entity because attributes are managed externally.'
+ 'New attributes cannot be added for this item because attributes are managed externally.'
)
diff --git a/src/hi/apps/entity/tests/test_entity_manager.py b/src/hi/apps/entity/tests/test_entity_manager.py
index 4b4c6d7f..ecf5f301 100644
--- a/src/hi/apps/entity/tests/test_entity_manager.py
+++ b/src/hi/apps/entity/tests/test_entity_manager.py
@@ -1,9 +1,7 @@
import logging
-from decimal import Decimal
-from unittest.mock import Mock
from hi.apps.entity.entity_manager import EntityManager
-from hi.apps.entity.models import Entity, EntityPath, EntityPosition
+from hi.apps.entity.models import Entity
from hi.apps.entity.enums import EntityGroupType, EntityType
from hi.testing.base_test_case import BaseTestCase
@@ -76,89 +74,6 @@ class TestEntityManager(BaseTestCase):
self.assertEqual(len(normal_callback_called), 1)
return
- def test_set_entity_path_create_new(self):
- """Test set_entity_path creation logic - complex business logic with transactions."""
- manager = EntityManager()
-
- # Create test entity
- entity = Entity.objects.create(
- name='Test Entity',
- entity_type_str=str(EntityType.LIGHT),
- integration_id='test_entity_001',
- integration_name='test_integration',
- )
-
- # Create minimal location (this may need adjustment based on actual Location model)
- # For now, testing the core logic without full location setup
- try:
- from hi.apps.location.models import Location
- location = Location.objects.create(name='Test Location')
-
- # Test creating new path
- svg_path_str = 'M 10 10 L 20 20'
- entity_path = manager.set_entity_path(
- entity_id=entity.id,
- location=location,
- svg_path_str=svg_path_str
- )
-
- self.assertEqual(entity_path.entity, entity)
- self.assertEqual(entity_path.location, location)
- self.assertEqual(entity_path.svg_path, svg_path_str)
-
- except ImportError:
- # Skip if Location model not available in test environment
- self.skipTest("Location model not available for testing")
- return
-
- def test_set_entity_path_update_existing(self):
- """Test set_entity_path update logic - should update existing rather than create duplicate."""
- manager = EntityManager()
-
- try:
- from hi.apps.location.models import Location
- from hi.apps.entity.models import EntityPath
-
- # Create test data
- entity = Entity.objects.create(
- name='Test Entity',
- entity_type_str=str(EntityType.LIGHT),
- integration_id='test_entity_001',
- integration_name='test_integration',
- )
-
- location = Location.objects.create(name='Test Location')
-
- # Create initial path
- initial_path = 'M 10 10 L 20 20'
- entity_path = EntityPath.objects.create(
- entity=entity,
- location=location,
- svg_path=initial_path
- )
-
- initial_id = entity_path.id
-
- # Update path
- updated_path = 'M 30 30 L 40 40'
- updated_entity_path = manager.set_entity_path(
- entity_id=entity.id,
- location=location,
- svg_path_str=updated_path
- )
-
- # Should update existing, not create new
- self.assertEqual(updated_entity_path.id, initial_id)
- self.assertEqual(updated_entity_path.svg_path, updated_path)
-
- # Should only be one EntityPath for this entity/location
- path_count = EntityPath.objects.filter(entity=entity, location=location).count()
- self.assertEqual(path_count, 1)
-
- except ImportError:
- self.skipTest("Required models not available for testing")
- return
-
def test_get_entity_edit_mode_data_returns_complete_data_structure(self):
"""Test get_entity_edit_mode_data business logic - complex method integrating multiple systems."""
manager = EntityManager()
@@ -277,274 +192,4 @@ class TestEntityManager(BaseTestCase):
return
- def test_set_entity_path_update_vs_create_logic(self):
- """Test set_entity_path business logic - should update existing or create new appropriately."""
- manager = EntityManager()
-
- try:
- from hi.apps.location.models import Location
-
- # Create test data
- entity = Entity.objects.create(
- name='Wire Entity',
- entity_type_str=str(EntityType.ELECTRIC_WIRE),
- integration_id='wire_001',
- integration_name='test_integration',
- )
-
- location = Location.objects.create(name='Test Location')
-
- # Test creating new path
- initial_path = 'M 10 10 L 20 20'
- entity_path = manager.set_entity_path(
- entity_id=entity.id,
- location=location,
- svg_path_str=initial_path
- )
-
- # Verify creation
- self.assertEqual(entity_path.entity, entity)
- self.assertEqual(entity_path.location, location)
- self.assertEqual(entity_path.svg_path, initial_path)
- initial_id = entity_path.id
-
- # Test updating existing path
- updated_path = 'M 30 30 L 40 40 L 50 50'
- updated_entity_path = manager.set_entity_path(
- entity_id=entity.id,
- location=location,
- svg_path_str=updated_path
- )
-
- # Should update existing, not create new
- self.assertEqual(updated_entity_path.id, initial_id)
- self.assertEqual(updated_entity_path.svg_path, updated_path)
-
- # Verify only one EntityPath exists for this entity/location
- path_count = EntityPath.objects.filter(entity=entity, location=location).count()
- self.assertEqual(path_count, 1)
-
- except ImportError:
- self.skipTest("Location model not available for testing")
- return
-
- def test_add_entity_position_if_needed_centers_in_view(self):
- """Test entity position creation - should center entity in location view by default."""
- manager = EntityManager()
-
- try:
- from hi.apps.location.models import Location
- from hi.apps.common.svg_models import SvgViewBox
-
- # Create test data
- entity = Entity.objects.create(
- name='Position Test Entity',
- entity_type_str=str(EntityType.CAMERA),
- integration_id='pos_test_001',
- integration_name='test_integration',
- )
-
- location = Location.objects.create(
- name = 'Test Location',
- svg_view_box_str = '100 200 400 300',
- )
-
- # Create a mock location view with known view box
- view_box = SvgViewBox(x=100, y=200, width=400, height=300)
- location_view = Mock()
- location_view.location = location
- location_view.svg_view_box = view_box
-
- # Test position creation
- entity_position = manager.add_entity_position_if_needed(
- entity=entity,
- location_view=location_view
- )
-
- # Should center in view box
- expected_x = Decimal('300') # 100 + 400/2
- expected_y = Decimal('350') # 200 + 300/2
-
- self.assertEqual(entity_position.entity, entity)
- self.assertEqual(entity_position.location, location)
- self.assertEqual(entity_position.svg_x, expected_x)
- self.assertEqual(entity_position.svg_y, expected_y)
- # Default icon size should be a percentage of the viewBox's smaller dimension.
- expected_scale = (
- Decimal('300')
- * Decimal(str(manager.DEFAULT_ICON_SIZE_PERCENT_OF_VIEWBOX))
- / Decimal('100')
- / Decimal('64')
- )
- self.assertEqual(entity_position.svg_scale, expected_scale)
- self.assertEqual(entity_position.svg_rotate, Decimal('0.0'))
-
- # Test that calling again doesn't create duplicate
- manager.add_entity_position_if_needed(
- entity=entity,
- location_view=location_view
- )
-
- position_count = EntityPosition.objects.filter(
- entity=entity,
- location=location
- ).count()
- self.assertEqual(position_count, 1)
-
- except ImportError:
- self.skipTest("Location models not available for testing")
- return
-
- def _create_scale_test_fixtures( self, viewbox_width, viewbox_height ):
- from hi.apps.common.svg_models import SvgViewBox
- from hi.apps.location.models import Location
-
- entity = Entity.objects.create(
- name = 'Scale Test Entity',
- entity_type_str = str( EntityType.CAMERA ),
- )
- location = Location.objects.create(
- name = 'Test Location',
- svg_view_box_str = f'0 0 {viewbox_width} {viewbox_height}',
- )
- location_view = Mock()
- location_view.location = location
- location_view.svg_view_box = SvgViewBox(
- x = 0, y = 0, width = viewbox_width, height = viewbox_height,
- )
- return entity, location, location_view
-
- def test_get_default_icon_scale_zero_viewbox(self):
- """Scale should clamp to min_scale when viewbox has zero dimension."""
- manager = EntityManager()
- entity, location, location_view = self._create_scale_test_fixtures( 0, 0 )
-
- scale = manager._get_default_icon_scale( entity, location_view )
- self.assertEqual( scale, Decimal( str( location.svg_position_bounds.min_scale ) ) )
- return
-
- def test_get_default_icon_scale_very_large_viewbox(self):
- """Scale should clamp to max_scale for extremely large viewboxes."""
- manager = EntityManager()
- entity, location, location_view = self._create_scale_test_fixtures( 100000, 100000 )
-
- scale = manager._get_default_icon_scale( entity, location_view )
- self.assertEqual( scale, Decimal( str( location.svg_position_bounds.max_scale ) ) )
- return
-
- def test_get_default_icon_scale_very_small_viewbox(self):
- """Scale should clamp to min_scale for tiny viewboxes."""
- manager = EntityManager()
- entity, location, location_view = self._create_scale_test_fixtures( 10, 10 )
-
- scale = manager._get_default_icon_scale( entity, location_view )
- self.assertEqual( scale, Decimal( str( location.svg_position_bounds.min_scale ) ) )
- return
-
- def _create_bulk_position_location_view( self, x, y, width, height ):
- from hi.apps.common.svg_models import SvgViewBox
-
- location_view = Mock()
- location_view.svg_view_box = SvgViewBox(
- x = x, y = y, width = width, height = height,
- )
- return location_view
-
- def test_bulk_position_single_entity_returns_center(self):
- """Single entity in a bulk add should be centered in the view."""
- manager = EntityManager()
- location_view = self._create_bulk_position_location_view( 0, 0, 1000, 1000 )
-
- svg_x, svg_y = manager._get_bulk_initial_entity_position(
- location_view = location_view,
- bulk_grid_index = 0,
- bulk_grid_total = 1,
- )
- self.assertAlmostEqual( svg_x, 500.0 )
- self.assertAlmostEqual( svg_y, 500.0 )
- return
-
- def test_bulk_position_multiple_entities_distributed_around_center(self):
- """Multiple entities should be placed symmetrically around the view center."""
- manager = EntityManager()
- location_view = self._create_bulk_position_location_view( 0, 0, 1000, 1000 )
-
- # For 4 entities in a 4-column grid, one row, columns centered at indices
- # 0..3 with offset from center at (-1.5, -0.5, 0.5, 1.5) * spacing.
- positions = [
- manager._get_bulk_initial_entity_position(
- location_view = location_view,
- bulk_grid_index = i,
- bulk_grid_total = 4,
- )
- for i in range( 4 )
- ]
- x_values = [ p[0] for p in positions ]
- y_values = [ p[1] for p in positions ]
-
- # Symmetric around center x=500: first and last should mirror, middle two mirror.
- self.assertAlmostEqual( x_values[0] + x_values[3], 1000.0 )
- self.assertAlmostEqual( x_values[1] + x_values[2], 1000.0 )
- # All in the same row, so y is identical.
- self.assertEqual( len( set( round( y, 6 ) for y in y_values ) ), 1 )
- # Single row means y sits at center.
- self.assertAlmostEqual( y_values[0], 500.0 )
- return
-
- def test_bulk_position_viewbox_offset_respects_origin(self):
- """Grid positioning should be centered on the viewbox center, not origin."""
- manager = EntityManager()
- location_view = self._create_bulk_position_location_view( 200, 300, 1000, 1000 )
-
- svg_x, svg_y = manager._get_bulk_initial_entity_position(
- location_view = location_view,
- bulk_grid_index = 0,
- bulk_grid_total = 1,
- )
- # Viewbox center is (200 + 500, 300 + 500) = (700, 800).
- self.assertAlmostEqual( svg_x, 700.0 )
- self.assertAlmostEqual( svg_y, 800.0 )
- return
-
- def test_bulk_position_grid_wraps_to_multiple_rows(self):
- """With more entities than columns, indices should wrap into additional rows."""
- manager = EntityManager()
- location_view = self._create_bulk_position_location_view( 0, 0, 1000, 1000 )
-
- # 8 entities with 4-column default = 2 rows. Index 0 is top-left, index 4
- # is first of second row (same column as index 0).
- x_0, y_0 = manager._get_bulk_initial_entity_position(
- location_view = location_view,
- bulk_grid_index = 0,
- bulk_grid_total = 8,
- )
- x_4, y_4 = manager._get_bulk_initial_entity_position(
- location_view = location_view,
- bulk_grid_index = 4,
- bulk_grid_total = 8,
- )
- self.assertAlmostEqual( x_0, x_4 )
- self.assertLess( y_0, y_4 )
- return
-
- def test_bulk_position_clamps_to_viewbox_margin(self):
- """Grid positions that would exceed viewbox bounds should clamp inside margin."""
- manager = EntityManager()
- # Very small viewbox so spacing would push grid cells outside.
- location_view = self._create_bulk_position_location_view( 0, 0, 100, 100 )
-
- svg_x, svg_y = manager._get_bulk_initial_entity_position(
- location_view = location_view,
- bulk_grid_index = 0,
- bulk_grid_total = 16,
- )
- margin_fraction = manager.DEFAULT_INITIAL_POSITION_VIEWBOX_MARGIN_FRACTION
- margin_x = 100 * margin_fraction
- margin_y = 100 * margin_fraction
-
- self.assertGreaterEqual( svg_x, margin_x )
- self.assertLessEqual( svg_x, 100 - margin_x )
- self.assertGreaterEqual( svg_y, margin_y )
- self.assertLessEqual( svg_y, 100 - margin_y )
- return
diff --git a/src/hi/apps/entity/tests/test_entity_placement.py b/src/hi/apps/entity/tests/test_entity_placement.py
new file mode 100644
index 00000000..508e8ffc
--- /dev/null
+++ b/src/hi/apps/entity/tests/test_entity_placement.py
@@ -0,0 +1,451 @@
+"""
+Tests for EntityPlacementCalculator and EntityPlacer.
+
+The pure layout math (grid slots, viewbox margin clamping, default
+icon scale) is owned by ``PositionGeometry`` and exercised in
+``hi/apps/location/tests/test_position_geometry.py``. This file
+exercises the placement-layer responsibilities:
+
+* Calculator entity-routing: deciding shape kind per entity, single
+ vs. bulk dispatch.
+* Placer persistence: idempotent EntityPosition creation via the
+ shape-dispatching path.
+"""
+
+import logging
+from decimal import Decimal
+from unittest.mock import Mock
+
+from hi.apps.entity.entity_placement import (
+ EntityPlacementCalculator,
+ EntityPlacer,
+ PlacementPoint,
+)
+from hi.apps.entity.models import Entity, EntityPosition
+from hi.apps.entity.enums import EntityType
+from hi.apps.location.position_geometry import PositionGeometry
+from hi.testing.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestEntityPlacerPersistence(BaseTestCase):
+ """Persistence behavior: persisting a PlacementPoint creates an
+ EntityPosition centered on the viewbox and is idempotent on
+ re-call."""
+
+ def test_persists_centered_position(self):
+ from hi.apps.location.models import Location
+ from hi.apps.common.svg_models import SvgViewBox
+
+ entity = Entity.objects.create(
+ name='Position Test Entity',
+ entity_type_str=str(EntityType.CAMERA),
+ integration_id='pos_test_001',
+ integration_name='test_integration',
+ )
+ location = Location.objects.create(
+ name='Test Location',
+ svg_view_box_str='100 200 400 300',
+ )
+ view_box = SvgViewBox(x=100, y=200, width=400, height=300)
+ location_view = Mock()
+ location_view.location = location
+ location_view.svg_view_box = view_box
+
+ placer = EntityPlacer()
+ # Compute the shape via the calculator, then persist directly
+ # (skipping place_entity_in_view to avoid delegate-pairing
+ # side effects that need a real EntityView).
+ placement_shape = placer.calculator.shape_for_entity(
+ entity=entity, location_view=location_view,
+ )
+ self.assertIsInstance(placement_shape, PlacementPoint)
+ placer._persist_placement_shape(
+ entity=entity,
+ location_view=location_view,
+ placement_shape=placement_shape,
+ )
+
+ entity_position = EntityPosition.objects.get(
+ entity=entity, location=location,
+ )
+ # Centered on the viewbox: 100 + 400/2 = 300, 200 + 300/2 = 350.
+ self.assertEqual(entity_position.svg_x, Decimal('300'))
+ self.assertEqual(entity_position.svg_y, Decimal('350'))
+ # Default icon size is a percentage of the viewbox's smaller dimension.
+ expected_scale = (
+ Decimal('300')
+ * Decimal(str(PositionGeometry.DEFAULT_ICON_SIZE_PERCENT_OF_VIEWBOX))
+ / Decimal('100')
+ / Decimal('64')
+ )
+ self.assertEqual(entity_position.svg_scale, expected_scale)
+ self.assertEqual(entity_position.svg_rotate, Decimal('0.0'))
+
+ # Re-call must not create a duplicate row.
+ placer._persist_placement_shape(
+ entity=entity,
+ location_view=location_view,
+ placement_shape=placement_shape,
+ )
+ position_count = EntityPosition.objects.filter(
+ entity=entity, location=location,
+ ).count()
+ self.assertEqual(position_count, 1)
+
+
+class TestEntityPlacementCalculatorBulkShapes(BaseTestCase):
+ """shapes_for_entities returns one shape per entity in input
+ order, computed against a single grid pass over the whole group.
+ The grid math itself is tested in test_position_geometry; this
+ class verifies the calculator's entity-routing wrapper."""
+
+ def _make_location_view(self):
+ from hi.apps.common.svg_models import SvgViewBox
+ from hi.apps.location.models import Location
+
+ location = Location.objects.create(
+ name='Bulk Test Location',
+ svg_view_box_str='0 0 1000 1000',
+ )
+ location_view = Mock()
+ location_view.location = location
+ location_view.svg_view_box = SvgViewBox(x=0, y=0, width=1000, height=1000)
+ return location_view
+
+ def test_empty_input_yields_empty_shapes(self):
+ calculator = EntityPlacementCalculator()
+ location_view = self._make_location_view()
+ self.assertEqual(
+ calculator.shapes_for_entities(entities=[], location_view=location_view),
+ [],
+ )
+
+ def test_single_entity_falls_back_to_single_shape(self):
+ calculator = EntityPlacementCalculator()
+ location_view = self._make_location_view()
+ entity = Entity.objects.create(
+ name='Single Camera',
+ entity_type_str=str(EntityType.CAMERA),
+ )
+ shapes = calculator.shapes_for_entities(
+ entities=[entity], location_view=location_view,
+ )
+ self.assertEqual(len(shapes), 1)
+ self.assertIsInstance(shapes[0], PlacementPoint)
+ # Centered on viewbox.
+ self.assertAlmostEqual(shapes[0].svg_x, 500.0)
+ self.assertAlmostEqual(shapes[0].svg_y, 500.0)
+
+ def test_multiple_icon_entities_each_get_a_grid_slot(self):
+ calculator = EntityPlacementCalculator()
+ location_view = self._make_location_view()
+ entities = [
+ Entity.objects.create(
+ name=f'Cam {i}',
+ entity_type_str=str(EntityType.CAMERA),
+ integration_id=f'cam_{i}',
+ integration_name='test',
+ )
+ for i in range(4)
+ ]
+ shapes = calculator.shapes_for_entities(
+ entities=entities, location_view=location_view,
+ )
+ self.assertEqual(len(shapes), len(entities))
+ for shape in shapes:
+ self.assertIsInstance(shape, PlacementPoint)
+ # Distinct x positions in a single row.
+ xs = [s.svg_x for s in shapes]
+ self.assertEqual(len(set(xs)), 4)
+
+
+class TestEntityPlacerSetEntityPath(BaseTestCase):
+ """User-drawn-path persistence: creates a new EntityPath row when
+ none exists, updates in place when one does."""
+
+ def _entity_and_location(self):
+ from hi.apps.location.models import Location
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str=str(EntityType.ELECTRIC_WIRE),
+ integration_id='wire_001',
+ integration_name='test_integration',
+ )
+ location = Location.objects.create(name='Test Location')
+ return entity, location
+
+ def test_set_entity_path_creates_new_when_absent(self):
+ from hi.apps.entity.models import EntityPath
+ entity, location = self._entity_and_location()
+
+ svg_path_str = 'M 10 10 L 20 20'
+ entity_path = EntityPlacer().set_entity_path(
+ entity_id=entity.id,
+ location=location,
+ svg_path_str=svg_path_str,
+ )
+
+ self.assertEqual(entity_path.entity, entity)
+ self.assertEqual(entity_path.location, location)
+ self.assertEqual(entity_path.svg_path, svg_path_str)
+ self.assertEqual(
+ EntityPath.objects.filter(entity=entity, location=location).count(),
+ 1,
+ )
+
+ def test_set_entity_path_updates_existing_in_place(self):
+ from hi.apps.entity.models import EntityPath
+ entity, location = self._entity_and_location()
+
+ initial = EntityPath.objects.create(
+ entity=entity, location=location, svg_path='M 10 10 L 20 20',
+ )
+ initial_id = initial.id
+
+ updated_path = 'M 30 30 L 40 40 L 50 50'
+ updated = EntityPlacer().set_entity_path(
+ entity_id=entity.id,
+ location=location,
+ svg_path_str=updated_path,
+ )
+
+ # Same row, new svg_path; no duplicate row created.
+ self.assertEqual(updated.id, initial_id)
+ self.assertEqual(updated.svg_path, updated_path)
+ self.assertEqual(
+ EntityPath.objects.filter(entity=entity, location=location).count(),
+ 1,
+ )
+
+
+class PlacementOutcomeTests(BaseTestCase):
+ """PlacementOutcome shape: primary/secondary helpers, total
+ counts, tie-breaking. Pure data, no DB."""
+
+ def _named_view(self, name):
+ from unittest.mock import Mock
+ view = Mock()
+ view.name = name
+ view.id = 0
+ return view
+
+ def _summary(self, name, count):
+ from hi.apps.entity.entity_placement import PlacementSummary
+ return PlacementSummary(
+ location_view=self._named_view(name), placed_entity_count=count,
+ )
+
+ def test_empty_outcome_has_no_primary(self):
+ from hi.apps.entity.entity_placement import PlacementOutcome
+ outcome = PlacementOutcome()
+ self.assertIsNone(outcome.primary_summary)
+ self.assertEqual(outcome.secondary_summaries, [])
+ self.assertEqual(outcome.total_placed, 0)
+ self.assertEqual(outcome.summaries, [])
+
+ def test_primary_picks_highest_count(self):
+ from hi.apps.entity.entity_placement import PlacementOutcome
+ a = self._summary('A', 1)
+ b = self._summary('B', 5)
+ c = self._summary('C', 3)
+ outcome = PlacementOutcome(summaries=[a, b, c])
+ self.assertIs(outcome.primary_summary, b)
+ self.assertEqual(outcome.secondary_summaries, [a, c])
+
+ def test_primary_breaks_ties_by_first_seen(self):
+ from hi.apps.entity.entity_placement import PlacementOutcome
+ first = self._summary('First', 4)
+ second = self._summary('Second', 4)
+ outcome = PlacementOutcome(summaries=[first, second])
+ self.assertIs(outcome.primary_summary, first)
+ self.assertEqual(outcome.secondary_summaries, [second])
+
+ def test_total_placed_sums_counts(self):
+ from hi.apps.entity.entity_placement import PlacementOutcome
+ outcome = PlacementOutcome(summaries=[
+ self._summary('A', 2),
+ self._summary('B', 5),
+ ])
+ self.assertEqual(outcome.total_placed, 7)
+
+ def test_skipped_count_is_independent_of_summaries(self):
+ from hi.apps.entity.entity_placement import PlacementOutcome
+ outcome = PlacementOutcome(
+ summaries=[self._summary('A', 1)],
+ skipped_entity_count=3,
+ )
+ self.assertEqual(outcome.skipped_entity_count, 3)
+ self.assertEqual(outcome.total_placed, 1)
+
+
+class EntityPlacementServiceTests(BaseTestCase):
+ """EntityPlacementService: query candidates and apply decisions."""
+
+ def setUp(self):
+ from hi.apps.common.svg_models import SvgViewBox
+ from hi.apps.entity.enums import EntityType
+ from hi.apps.entity.models import Entity, EntityView
+ from hi.apps.location.models import Location, LocationView
+
+ self.location = Location.objects.create(
+ name='Test Location', svg_view_box_str='0 0 100 100',
+ )
+ self.view_a = LocationView.objects.create(
+ location=self.location, name='Kitchen', order_id=1,
+ svg_view_box_str='0 0 100 100', svg_rotate=0,
+ svg_style_name_str='COLOR', location_view_type_str='DEFAULT',
+ )
+ self.view_b = LocationView.objects.create(
+ location=self.location, name='Living Room', order_id=2,
+ svg_view_box_str='0 0 100 100', svg_rotate=0,
+ svg_style_name_str='COLOR', location_view_type_str='DEFAULT',
+ )
+
+ # Two unplaced for 'svc_a', one already placed; one unplaced
+ # for 'svc_b' (cross-integration filter test).
+ self.unplaced_a1 = Entity.objects.create(
+ name='A1', entity_type_str=str(EntityType.CAMERA),
+ integration_id='svc_a', integration_name='a1',
+ )
+ self.unplaced_a2 = Entity.objects.create(
+ name='A2', entity_type_str=str(EntityType.CAMERA),
+ integration_id='svc_a', integration_name='a2',
+ )
+ already_placed = Entity.objects.create(
+ name='Placed', entity_type_str=str(EntityType.CAMERA),
+ integration_id='svc_a', integration_name='placed',
+ )
+ EntityView.objects.create(
+ entity=already_placed, location_view=self.view_a,
+ )
+ self.unplaced_b = Entity.objects.create(
+ name='B1', entity_type_str=str(EntityType.CAMERA),
+ integration_id='svc_b', integration_name='b1',
+ )
+ # Reference SvgViewBox to avoid lint noise; the helper above
+ # is exercised indirectly through LocationView's str field.
+ _ = SvgViewBox
+
+ def test_query_unplaced_entities_filters_to_integration(self):
+ from hi.apps.entity.entity_placement import EntityPlacementService
+ result = EntityPlacementService.query_unplaced_entities(
+ integration_id='svc_a',
+ )
+ result_ids = {e.id for e in result}
+ self.assertEqual(
+ result_ids,
+ {self.unplaced_a1.id, self.unplaced_a2.id},
+ )
+
+ def test_query_unplaced_entities_with_no_filter_returns_all(self):
+ from hi.apps.entity.entity_placement import EntityPlacementService
+ result = EntityPlacementService.query_unplaced_entities()
+ result_ids = {e.id for e in result}
+ self.assertEqual(
+ result_ids,
+ {self.unplaced_a1.id, self.unplaced_a2.id, self.unplaced_b.id},
+ )
+
+ def test_apply_decisions_partitions_by_view_and_skips_none(self):
+ from hi.apps.entity.entity_placement import (
+ EntityPlacementService, PlacementDecision,
+ )
+ decisions = [
+ PlacementDecision(entity=self.unplaced_a1, location_view=self.view_a),
+ PlacementDecision(entity=self.unplaced_a2, location_view=self.view_a),
+ PlacementDecision(entity=self.unplaced_b, location_view=self.view_b),
+ # Skip decision contributes to skipped_entity_count.
+ PlacementDecision(
+ entity=Entity.objects.create(
+ name='Skipped',
+ entity_type_str='CAMERA',
+ integration_id='svc_a',
+ integration_name='skipped',
+ ),
+ ),
+ ]
+ outcome = EntityPlacementService.apply_decisions(decisions=decisions)
+ self.assertEqual(outcome.skipped_entity_count, 1)
+ self.assertEqual(outcome.total_placed, 3)
+ # Two summaries, in input order: view_a (2), view_b (1).
+ self.assertEqual(len(outcome.summaries), 2)
+ self.assertEqual(outcome.summaries[0].location_view, self.view_a)
+ self.assertEqual(outcome.summaries[0].placed_entity_count, 2)
+ self.assertEqual(outcome.summaries[1].location_view, self.view_b)
+ self.assertEqual(outcome.summaries[1].placed_entity_count, 1)
+
+ def test_apply_decisions_handles_collection_targets(self):
+ """Collection-targeted decisions go through CollectionManager
+ and produce a collection-flavored PlacementSummary. The
+ outcome's primary_summary still prefers the view-targeted
+ summary when one exists."""
+ from hi.apps.collection.enums import CollectionType, CollectionViewType
+ from hi.apps.collection.models import Collection, CollectionEntity
+ from hi.apps.entity.entity_placement import (
+ EntityPlacementService, PlacementDecision,
+ )
+ collection = Collection(name='Tools', order_id=0)
+ collection.collection_type = CollectionType.default()
+ collection.collection_view_type = CollectionViewType.default()
+ collection.save()
+
+ decisions = [
+ # 2 view-targeted, 1 collection-targeted.
+ PlacementDecision(entity=self.unplaced_a1, location_view=self.view_a),
+ PlacementDecision(entity=self.unplaced_a2, location_view=self.view_a),
+ PlacementDecision(entity=self.unplaced_b, collection=collection),
+ ]
+ outcome = EntityPlacementService.apply_decisions(decisions=decisions)
+ self.assertEqual(outcome.skipped_entity_count, 0)
+ self.assertEqual(outcome.total_placed, 3)
+ self.assertEqual(len(outcome.summaries), 2)
+
+ # View summary first, collection summary second (input order).
+ view_summary, collection_summary = outcome.summaries
+ self.assertTrue(view_summary.is_view)
+ self.assertEqual(view_summary.placed_entity_count, 2)
+ self.assertTrue(collection_summary.is_collection)
+ self.assertEqual(collection_summary.collection, collection)
+ self.assertEqual(collection_summary.placed_entity_count, 1)
+
+ # Primary prefers view-targeted summaries.
+ self.assertIs(outcome.primary_summary, view_summary)
+
+ # The collection placement actually persisted as a CollectionEntity.
+ self.assertEqual(
+ CollectionEntity.objects.filter(
+ collection=collection, entity=self.unplaced_b,
+ ).count(),
+ 1,
+ )
+
+ def test_apply_decisions_all_collections_promotes_collection_to_primary(self):
+ """When every placement targets a Collection, the highest-
+ count collection is the primary summary (the post-dispatch
+ modal renders REVIEW for it instead of REFINE)."""
+ from hi.apps.collection.enums import CollectionType, CollectionViewType
+ from hi.apps.collection.models import Collection
+ from hi.apps.entity.entity_placement import (
+ EntityPlacementService, PlacementDecision,
+ )
+ tools = Collection(name='Tools', order_id=0)
+ tools.collection_type = CollectionType.default()
+ tools.collection_view_type = CollectionViewType.default()
+ tools.save()
+ recipes = Collection(name='Recipes', order_id=1)
+ recipes.collection_type = CollectionType.default()
+ recipes.collection_view_type = CollectionViewType.default()
+ recipes.save()
+
+ decisions = [
+ PlacementDecision(entity=self.unplaced_a1, collection=tools),
+ PlacementDecision(entity=self.unplaced_a2, collection=tools),
+ PlacementDecision(entity=self.unplaced_b, collection=recipes),
+ ]
+ outcome = EntityPlacementService.apply_decisions(decisions=decisions)
+ self.assertEqual(len(outcome.summaries), 2)
+ self.assertTrue(outcome.primary_summary.is_collection)
+ # Highest-count is Tools (2 entities).
+ self.assertEqual(outcome.primary_summary.collection, tools)
diff --git a/src/hi/apps/entity/tests/test_views.py b/src/hi/apps/entity/tests/test_views.py
index f407cd67..68147f31 100644
--- a/src/hi/apps/entity/tests/test_views.py
+++ b/src/hi/apps/entity/tests/test_views.py
@@ -370,7 +370,7 @@ class TestEntityEditView(DualModeViewTestCase):
self.assertFalse(self.entity.attributes.filter(name='blocked_property').exists())
content = response.content.decode('utf-8')
- self.assertIn('New attributes cannot be added for this entity because attributes are managed externally.', content)
+ self.assertIn('New attributes cannot be added for this item because attributes are managed externally.', content)
def test_entity_with_complex_attribute_mix(self):
"""Test editing entity with mixed attribute types (text, file, secret)."""
diff --git a/src/hi/apps/entity/view_mixins.py b/src/hi/apps/entity/view_mixins.py
index b50a26ec..4087c10d 100644
--- a/src/hi/apps/entity/view_mixins.py
+++ b/src/hi/apps/entity/view_mixins.py
@@ -11,7 +11,7 @@ class EntityViewMixin:
try:
entity_id = int( kwargs.get( 'entity_id' ))
except (TypeError, ValueError):
- raise BadRequest( 'Invalid entity id.' )
+ raise BadRequest( 'Invalid item id.' )
try:
return Entity.objects.get( id = entity_id )
except Entity.DoesNotExist:
diff --git a/src/hi/apps/location/edit/views.py b/src/hi/apps/location/edit/views.py
index 8527d264..95872aa8 100644
--- a/src/hi/apps/location/edit/views.py
+++ b/src/hi/apps/location/edit/views.py
@@ -20,6 +20,7 @@ import hi.apps.common.antinode as antinode
from hi.apps.common.svg_models import SvgViewBox
from hi.apps.entity.edit.views import EntityPositionEditView
from hi.apps.entity.entity_manager import EntityManager
+from hi.apps.entity.entity_placement import EntityPlacer
from hi.apps.entity.models import Entity
from hi.apps.location.location_manager import LocationManager
from hi.apps.location.models import Location
@@ -459,13 +460,13 @@ class LocationViewEntityToggleView( View, LocationViewMixin ):
try:
entity_id = int( kwargs.get('entity_id'))
except (TypeError, ValueError):
- raise BadRequest( 'Invalid entity id.' )
+ raise BadRequest( 'Invalid item id.' )
try:
entity = Entity.objects.get( id = entity_id )
except Entity.DoesNotExist:
raise Http404( request )
- exists_in_view = EntityManager().toggle_entity_in_view(
+ exists_in_view = EntityPlacer().toggle_entity_in_view(
entity = entity,
location_view = location_view,
)
@@ -591,7 +592,7 @@ class LocationItemPathView( View ):
location = LocationManager().get_default_location( request = request )
if item_type == ItemType.ENTITY:
- EntityManager().set_entity_path(
+ EntityPlacer().set_entity_path(
entity_id = item_id,
location = location,
svg_path_str = svg_path_str,
diff --git a/src/hi/apps/location/location_manager.py b/src/hi/apps/location/location_manager.py
index 445650e5..db2c36d7 100644
--- a/src/hi/apps/location/location_manager.py
+++ b/src/hi/apps/location/location_manager.py
@@ -209,22 +209,51 @@ class LocationManager(Singleton):
location_view_type = LocationViewType.default()
if svg_style_name is None:
svg_style_name = SvgStyleName.default()
-
+
last_location_view = location.views.order_by( '-order_id' ).first()
if last_location_view:
order_id = last_location_view.order_id + 1
else:
order_id = 0
-
+
+ resolved_name = self.resolve_unique_view_name(
+ location = location, requested_name = name,
+ )
+
return LocationView.objects.create(
location = location,
location_view_type_str = str(location_view_type),
- name = name,
+ name = resolved_name,
svg_style_name_str = str( svg_style_name ),
svg_view_box_str = str( location.svg_view_box ),
svg_rotate = Decimal( 0.0 ),
order_id = order_id,
)
+
+ def resolve_unique_view_name( self,
+ location : Location,
+ requested_name : str ) -> str:
+ """Return ``requested_name`` if no LocationView in this
+ Location uses it; otherwise append ``(2)``, ``(3)``, ... until
+ a free name is found.
+
+ LocationView.name is not unique-per-location at the DB level —
+ anyone could create duplicates by direct ORM use — so this
+ helper is the single point that all callers go through to
+ avoid surprise duplicates. Used by the dispatcher's
+ ``+ New view: "<integration label>"`` option (where the
+ operator already has a view with that name) and by the
+ manage-page Add View form (where the operator typed a
+ duplicate by accident)."""
+ existing_names = set( location.views.values_list('name', flat=True) )
+ if requested_name not in existing_names:
+ return requested_name
+ suffix = 2
+ while True:
+ candidate = f'{requested_name} ({suffix})'
+ if candidate not in existing_names:
+ return candidate
+ suffix += 1
def get_location_view( self, request : HttpRequest, location_view_id : int ) -> LocationView:
"""
diff --git a/src/hi/apps/location/position_geometry.py b/src/hi/apps/location/position_geometry.py
new file mode 100644
index 00000000..d370d719
--- /dev/null
+++ b/src/hi/apps/location/position_geometry.py
@@ -0,0 +1,151 @@
+"""
+Position geometry: "where in the SVG" math.
+
+Pure-functional helpers that answer the question "where, in a
+Location's SVG coordinate space, should something go?" — siblings
+to ``PathGeometry`` (which answers "what does the path string look
+like once you've decided where").
+
+* ``view_center`` — the center of the current viewbox.
+* ``grid_slot`` — one slot of a centered grid laid over the
+ viewbox; used to lay out a group of entities arriving together.
+* ``clamp_to_viewbox`` — keep a point inside the viewbox margin.
+* ``default_icon_scale`` — entity-aware icon scale: ~10% of the
+ viewbox's smaller dimension, clamped to the location's
+ svg_position_bounds.
+* ``path_center`` — geometric center of an existing SVG path
+ string. Lives here because the *output* is a position even
+ though the input is a path string.
+
+Performs no DB writes and has no opinions about Entity vs
+Collection: callers in either domain pass in a ``LocationView`` (or
+view box) and receive geometry. Constants for the placement
+heuristic live here as the canonical home.
+"""
+
+from decimal import Decimal
+import re
+from typing import Optional, Tuple
+
+from hi.apps.location.models import LocationView
+from hi.hi_styles import EntityStyle
+
+
+class PositionGeometry:
+
+ DEFAULT_ICON_SIZE_PERCENT_OF_VIEWBOX = 10.0
+ DEFAULT_GRID_COLUMNS = 4
+ DEFAULT_GRID_SPACING_FRACTION = 0.18
+ DEFAULT_VIEWBOX_MARGIN_FRACTION = 0.05
+
+ @classmethod
+ def view_center( cls, location_view : LocationView ) -> Tuple[float, float]:
+ view_box = location_view.svg_view_box
+ return (
+ view_box.x + ( view_box.width / 2.0 ),
+ view_box.y + ( view_box.height / 2.0 ),
+ )
+
+ @classmethod
+ def grid_slot( cls,
+ location_view : LocationView,
+ grid_index : int,
+ grid_total : int ) -> Tuple[float, float]:
+ view_box = location_view.svg_view_box
+ center_x, center_y = cls.view_center( location_view )
+
+ if grid_total <= 1:
+ return center_x, center_y
+
+ columns = min( max( 2, cls.DEFAULT_GRID_COLUMNS ), grid_total )
+ rows = ( grid_total + columns - 1 ) // columns
+
+ column_index = grid_index % columns
+ row_index = grid_index // columns
+
+ column_offset = column_index - ( ( columns - 1 ) / 2.0 )
+ row_offset = row_index - ( ( rows - 1 ) / 2.0 )
+
+ spacing_x = view_box.width * cls.DEFAULT_GRID_SPACING_FRACTION
+ spacing_y = view_box.height * cls.DEFAULT_GRID_SPACING_FRACTION
+
+ svg_x = center_x + ( column_offset * spacing_x )
+ svg_y = center_y + ( row_offset * spacing_y )
+
+ return cls.clamp_to_viewbox(
+ svg_x = svg_x,
+ svg_y = svg_y,
+ view_box = view_box,
+ )
+
+ @classmethod
+ def clamp_to_viewbox( cls,
+ svg_x : float,
+ svg_y : float,
+ view_box ) -> Tuple[float, float]:
+ margin_x = view_box.width * cls.DEFAULT_VIEWBOX_MARGIN_FRACTION
+ margin_y = view_box.height * cls.DEFAULT_VIEWBOX_MARGIN_FRACTION
+
+ min_x = view_box.x + margin_x
+ max_x = ( view_box.x + view_box.width ) - margin_x
+ min_y = view_box.y + margin_y
+ max_y = ( view_box.y + view_box.height ) - margin_y
+
+ if min_x > max_x:
+ min_x = max_x = view_box.x + ( view_box.width / 2.0 )
+ if min_y > max_y:
+ min_y = max_y = view_box.y + ( view_box.height / 2.0 )
+
+ clamped_x = max( min_x, min( svg_x, max_x ) )
+ clamped_y = max( min_y, min( svg_y, max_y ) )
+ return clamped_x, clamped_y
+
+ @classmethod
+ def default_icon_scale( cls,
+ entity,
+ location_view : LocationView ) -> Decimal:
+ """Default scale for an icon entity: ~10% of the viewbox's
+ smaller dimension, clamped to the location's
+ svg_position_bounds.min_scale / max_scale."""
+ view_box = location_view.svg_view_box
+ icon_view_box = EntityStyle.get_svg_icon_viewbox( entity.entity_type )
+
+ icon_max_dimension = max( icon_view_box.width, icon_view_box.height )
+ if icon_max_dimension <= 0:
+ return Decimal( str( location_view.location.svg_position_bounds.min_scale ) )
+
+ viewbox_min_dimension = min( view_box.width, view_box.height )
+ size_fraction = cls.DEFAULT_ICON_SIZE_PERCENT_OF_VIEWBOX / 100.0
+ target_icon_size = viewbox_min_dimension * size_fraction
+ scale = target_icon_size / icon_max_dimension
+
+ position_bounds = location_view.location.svg_position_bounds
+ scale = max( position_bounds.min_scale,
+ min( scale, position_bounds.max_scale ) )
+
+ return Decimal( str( scale ) )
+
+ @classmethod
+ def path_center( cls, svg_path : str ) -> Tuple[Optional[float], Optional[float]]:
+ """Geometric center of an SVG path: average of all extracted
+ coordinate pairs. Returns ``(None, None)`` for malformed or
+ too-short input."""
+ try:
+ numbers = re.findall( r'[-+]?(?:\d*\.\d+|\d+)', svg_path )
+ if len( numbers ) < 4:
+ return None, None
+
+ coords = [ float( n ) for n in numbers ]
+ 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 (
+ sum( x_coords ) / len( x_coords ),
+ sum( y_coords ) / len( y_coords ),
+ )
+
+ except (ValueError, IndexError, ZeroDivisionError):
+ return None, None
diff --git a/src/hi/apps/location/tests/test_location_manager_draft.py b/src/hi/apps/location/tests/test_location_manager_draft.py
index b7a5b2f1..9d8ded5a 100644
--- a/src/hi/apps/location/tests/test_location_manager_draft.py
+++ b/src/hi/apps/location/tests/test_location_manager_draft.py
@@ -215,3 +215,93 @@ class TestLocationManagerDraftSvgHelpers(BaseTestCase):
with default_storage.open(self.location.svg_fragment_filename, 'r') as f:
live_content = f.read()
self.assertEqual(live_content, self.live_svg_content)
+
+
+class TestLocationManagerCreateLocationView(BaseTestCase):
+ """create_location_view auto-disambiguates duplicate names within
+ a Location by appending a numeric suffix. Used both by the
+ dispatcher's '+ New view: "<integration label>"' option (when
+ the operator already has a view with that name) and by the
+ manage-page Add View form (when the operator types a
+ duplicate)."""
+
+ def setUp(self):
+ super().setUp()
+ from hi.apps.location.models import Location
+ self.location = Location.objects.create(
+ name='Test Location', svg_view_box_str='0 0 100 100',
+ )
+ self.manager = LocationManager()
+
+ def test_unique_name_passes_through_unchanged(self):
+ view = self.manager.create_location_view(
+ location=self.location, name='Kitchen',
+ )
+ self.assertEqual(view.name, 'Kitchen')
+
+ def test_first_collision_gets_suffix_2(self):
+ first = self.manager.create_location_view(
+ location=self.location, name='Home Assistant',
+ )
+ second = self.manager.create_location_view(
+ location=self.location, name='Home Assistant',
+ )
+ self.assertEqual(first.name, 'Home Assistant')
+ self.assertEqual(second.name, 'Home Assistant (2)')
+
+ def test_subsequent_collisions_increment_suffix(self):
+ self.manager.create_location_view(
+ location=self.location, name='Cameras',
+ )
+ self.manager.create_location_view(
+ location=self.location, name='Cameras',
+ )
+ third = self.manager.create_location_view(
+ location=self.location, name='Cameras',
+ )
+ fourth = self.manager.create_location_view(
+ location=self.location, name='Cameras',
+ )
+ self.assertEqual(third.name, 'Cameras (3)')
+ self.assertEqual(fourth.name, 'Cameras (4)')
+
+ def test_collision_isolated_per_location(self):
+ """Disambiguation looks at views in the *same* location only;
+ a different location with the same view name does not affect
+ suffix selection."""
+ from hi.apps.location.models import Location
+ other_location = Location.objects.create(
+ name='Other', svg_view_box_str='0 0 100 100',
+ )
+ self.manager.create_location_view(
+ location=other_location, name='Home Assistant',
+ )
+ # First call here is unique relative to self.location.
+ view = self.manager.create_location_view(
+ location=self.location, name='Home Assistant',
+ )
+ self.assertEqual(view.name, 'Home Assistant')
+
+ def test_skips_taken_suffix_in_sequence(self):
+ """Pre-existing '(2)' name still leaves room for an unsuffixed
+ first creation, then suffix-2 collision should advance to
+ suffix 3."""
+ from hi.apps.location.models import LocationView
+ # Pre-create a manually-named '(2)' to simulate a deployment
+ # where someone already used that exact name.
+ LocationView.objects.create(
+ location=self.location, name='Lights (2)', order_id=0,
+ svg_view_box_str='0 0 100 100', svg_rotate=0,
+ svg_style_name_str='COLOR', location_view_type_str='DEFAULT',
+ )
+ # First 'Lights' creation is unique.
+ first = self.manager.create_location_view(
+ location=self.location, name='Lights',
+ )
+ self.assertEqual(first.name, 'Lights')
+ # Second collides with both 'Lights' and 'Lights (2)' →
+ # advances to (3).
+ second = self.manager.create_location_view(
+ location=self.location, name='Lights',
+ )
+ self.assertEqual(second.name, 'Lights (3)')
diff --git a/src/hi/apps/location/tests/test_position_geometry.py b/src/hi/apps/location/tests/test_position_geometry.py
new file mode 100644
index 00000000..22cfd774
--- /dev/null
+++ b/src/hi/apps/location/tests/test_position_geometry.py
@@ -0,0 +1,140 @@
+"""
+Tests for PositionGeometry.
+
+Pure-functional layout math. No DB writes; some methods take a
+``LocationView`` (mockable) or a Location row.
+"""
+
+import logging
+from decimal import Decimal
+from unittest.mock import Mock
+
+from hi.apps.entity.models import Entity
+from hi.apps.entity.enums import EntityType
+from hi.apps.location.position_geometry import PositionGeometry
+from hi.testing.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestPositionGeometryViewCenter(BaseTestCase):
+
+ def test_view_center_respects_origin(self):
+ from hi.apps.common.svg_models import SvgViewBox
+
+ location_view = Mock()
+ location_view.svg_view_box = SvgViewBox(x=200, y=300, width=1000, height=1000)
+
+ x, y = PositionGeometry.view_center(location_view)
+ self.assertAlmostEqual(x, 700.0)
+ self.assertAlmostEqual(y, 800.0)
+
+
+class TestPositionGeometryGridSlot(BaseTestCase):
+
+ def _make_view(self, x, y, width, height):
+ from hi.apps.common.svg_models import SvgViewBox
+
+ location_view = Mock()
+ location_view.svg_view_box = SvgViewBox(x=x, y=y, width=width, height=height)
+ return location_view
+
+ def test_single_entity_returns_center(self):
+ view = self._make_view(0, 0, 1000, 1000)
+ x, y = PositionGeometry.grid_slot(location_view=view, grid_index=0, grid_total=1)
+ self.assertAlmostEqual(x, 500.0)
+ self.assertAlmostEqual(y, 500.0)
+
+ def test_multiple_entities_distributed_around_center(self):
+ view = self._make_view(0, 0, 1000, 1000)
+ positions = [
+ PositionGeometry.grid_slot(location_view=view, grid_index=i, grid_total=4)
+ for i in range(4)
+ ]
+ xs = [p[0] for p in positions]
+ ys = [p[1] for p in positions]
+ self.assertAlmostEqual(xs[0] + xs[3], 1000.0)
+ self.assertAlmostEqual(xs[1] + xs[2], 1000.0)
+ self.assertEqual(len(set(round(y, 6) for y in ys)), 1)
+ self.assertAlmostEqual(ys[0], 500.0)
+
+ def test_grid_wraps_to_multiple_rows(self):
+ view = self._make_view(0, 0, 1000, 1000)
+ x_0, y_0 = PositionGeometry.grid_slot(location_view=view, grid_index=0, grid_total=8)
+ x_4, y_4 = PositionGeometry.grid_slot(location_view=view, grid_index=4, grid_total=8)
+ self.assertAlmostEqual(x_0, x_4)
+ self.assertLess(y_0, y_4)
+
+ def test_clamps_to_viewbox_margin(self):
+ view = self._make_view(0, 0, 100, 100)
+ x, y = PositionGeometry.grid_slot(location_view=view, grid_index=0, grid_total=16)
+ margin_fraction = PositionGeometry.DEFAULT_VIEWBOX_MARGIN_FRACTION
+ margin = 100 * margin_fraction
+ self.assertGreaterEqual(x, margin)
+ self.assertLessEqual(x, 100 - margin)
+ self.assertGreaterEqual(y, margin)
+ self.assertLessEqual(y, 100 - margin)
+
+
+class TestPositionGeometryDefaultIconScale(BaseTestCase):
+
+ def _fixtures(self, viewbox_width, viewbox_height):
+ from hi.apps.common.svg_models import SvgViewBox
+ from hi.apps.location.models import Location
+
+ entity = Entity.objects.create(
+ name='Scale Test Entity',
+ entity_type_str=str(EntityType.CAMERA),
+ )
+ location = Location.objects.create(
+ name='Test Location',
+ svg_view_box_str=f'0 0 {viewbox_width} {viewbox_height}',
+ )
+ location_view = Mock()
+ location_view.location = location
+ location_view.svg_view_box = SvgViewBox(
+ x=0, y=0, width=viewbox_width, height=viewbox_height,
+ )
+ return entity, location, location_view
+
+ def test_zero_viewbox_clamps_to_min_scale(self):
+ entity, location, location_view = self._fixtures(0, 0)
+ scale = PositionGeometry.default_icon_scale(
+ entity=entity, location_view=location_view,
+ )
+ self.assertEqual(scale, Decimal(str(location.svg_position_bounds.min_scale)))
+
+ def test_very_large_viewbox_clamps_to_max_scale(self):
+ entity, location, location_view = self._fixtures(100000, 100000)
+ scale = PositionGeometry.default_icon_scale(
+ entity=entity, location_view=location_view,
+ )
+ self.assertEqual(scale, Decimal(str(location.svg_position_bounds.max_scale)))
+
+ def test_very_small_viewbox_clamps_to_min_scale(self):
+ entity, location, location_view = self._fixtures(10, 10)
+ scale = PositionGeometry.default_icon_scale(
+ entity=entity, location_view=location_view,
+ )
+ self.assertEqual(scale, Decimal(str(location.svg_position_bounds.min_scale)))
+
+
+class TestPositionGeometryPathCenter(BaseTestCase):
+
+ def test_path_center_averages_extracted_coords(self):
+ # Square corners: average is the center.
+ x, y = PositionGeometry.path_center('M 0,0 L 10,0 L 10,10 L 0,10 Z')
+ self.assertAlmostEqual(x, 5.0)
+ self.assertAlmostEqual(y, 5.0)
+
+ def test_path_center_returns_none_for_empty(self):
+ self.assertEqual(PositionGeometry.path_center(''), (None, None))
+
+ def test_path_center_returns_none_for_too_few_coords(self):
+ # Single point: 2 numbers, below the 4-number minimum.
+ self.assertEqual(PositionGeometry.path_center('M 5,5'), (None, None))
+
+ def test_path_center_handles_negative_and_decimal_coords(self):
+ x, y = PositionGeometry.path_center('M -10,-5 L 10,5')
+ self.assertAlmostEqual(x, 0.0)
+ self.assertAlmostEqual(y, 0.0)
diff --git a/src/hi/apps/system/templates/system/panes/integration_paused_card.html b/src/hi/apps/system/templates/system/panes/integration_paused_card.html
new file mode 100644
index 00000000..fd6b52ae
--- /dev/null
+++ b/src/hi/apps/system/templates/system/panes/integration_paused_card.html
@@ -0,0 +1,33 @@
+{% load icons %}
+{% comment %}
+ Placeholder card for a configured integration whose monitor is
+ not running (typically because the integration is paused). Mirrors
+ health_status_card.html's visual shape so the system-info grid
+ reads consistently — but with a paused-state badge and a click
+ target that takes the operator to the integration manage page
+ where they can resume it.
+
+ Context:
+ integration_data : IntegrationData (required)
+{% endcomment %}
+<a href="{% url 'integrations_manage' integration_id=integration_data.integration_id %}"
+ class="clickable-card">
+ <div class="card border-warning">
+ <div class="card-body">
+ <div class="d-flex justify-content-between align-items-center mb-2">
+ <h6 class="mb-0">{{ integration_data.label }}</h6>
+ <span class="badge monitor-status-badge badge-warning">
+ {% icon "pause" size="sm" css_class="mr-1" %}Paused
+ </span>
+ </div>
+ <div class="row">
+ <div class="col-12">
+ <small class="text-muted">
+ No active monitor. Resume the integration from its manage page
+ to start collecting status.
+ </small>
+ </div>
+ </div>
+ </div>
+ </div>
+</a>
diff --git a/src/hi/apps/system/templates/system/panes/system_info.html b/src/hi/apps/system/templates/system/panes/system_info.html
index 2a7390bd..5d053db7 100644
--- a/src/hi/apps/system/templates/system/panes/system_info.html
+++ b/src/hi/apps/system/templates/system/panes/system_info.html
@@ -37,12 +37,16 @@
</div>
<div class="row">
- {% for integration_provider in integration_providers %}
+ {% for item in integration_health_items %}
<div class="col-lg-6 col-md-12 mb-3">
- {% include "system/panes/health_status_card.html" with health_status_provider=integration_provider %}
+ {% if item.health_status_provider %}
+ {% include "system/panes/health_status_card.html" with health_status_provider=item.health_status_provider %}
+ {% else %}
+ {% include "system/panes/integration_paused_card.html" with integration_data=item.integration_data %}
+ {% endif %}
</div>
{% empty %}
- <div class="col-12 text-secondary"><em>No integrations enabled.</em></div>
+ <div class="col-12 text-secondary"><em>No integrations configured.</em></div>
{% endfor %}
</div>
diff --git a/src/hi/apps/system/views.py b/src/hi/apps/system/views.py
index 59643810..e7512c4a 100644
--- a/src/hi/apps/system/views.py
+++ b/src/hi/apps/system/views.py
@@ -31,13 +31,28 @@ class SystemInfoView( ConfigPageView ):
AppMonitorManager().get_health_status_providers(),
key = lambda m: m.get_provider_info().provider_name
)
- integration_providers = sorted(
- IntegrationManager().get_health_status_providers(),
- key = lambda m: m.get_provider_info().provider_name
+ # Pair every configured integration with its running monitor
+ # (when present). A missing monitor for a configured
+ # integration → placeholder rendered in the template (paused
+ # or otherwise not running). Surface only configured
+ # integrations; unconfigured ones don't appear here.
+ integration_manager = IntegrationManager()
+ configured_integration_data_list = integration_manager.get_integration_data_list(
+ enabled_only = True,
)
+ provider_by_integration_id = integration_manager.get_health_status_provider_map()
+ integration_health_items = [
+ { 'integration_data': integration_data,
+ 'health_status_provider':
+ provider_by_integration_id.get( integration_data.integration_id ) }
+ for integration_data in sorted(
+ configured_integration_data_list,
+ key = lambda data: data.integration_metadata.label,
+ )
+ ]
return {
'app_monitor_providers': app_monitor_providers,
- 'integration_providers': integration_providers,
+ 'integration_health_items': integration_health_items,
'weather_provider': WeatherSourceManager(),
'background_task_provider': AsyncioHealthStatusProvider(),
}
diff --git a/src/hi/integrations/entity_operations.py b/src/hi/integrations/entity_operations.py
index 5ad0895d..9fb4daec 100644
--- a/src/hi/integrations/entity_operations.py
+++ b/src/hi/integrations/entity_operations.py
@@ -7,16 +7,16 @@ are distinct from the read-only analytical methods on EntityUserDataDetector.
"""
import logging
-from typing import Iterable, Optional, Set
+from typing import Dict, Iterable, Optional, Set
from django.db import transaction
from hi.apps.attribute.enums import AttributeType
-from hi.apps.common.processing_result import ProcessingResult
from hi.apps.entity.models import Entity, EntityState, EntityStateDelegation
from hi.apps.sense.models import Sensor
from hi.apps.control.models import Controller
+from .sync_result import IntegrationSyncResult
from .transient_models import IntegrationRemovalSummary
from .user_data_detector import EntityUserDataDetector
@@ -69,15 +69,20 @@ class EntityIntegrationOperations:
if not candidate_ids:
break
- added_this_pass : Set[int] = set()
- for candidate_id in candidate_ids:
- principal_ids = set(
- EntityStateDelegation.objects.filter(
- delegate_entity_id = candidate_id,
- ).values_list( 'entity_state__entity_id', flat = True )
- )
- if principal_ids and principal_ids.issubset( closure ):
- added_this_pass.add( candidate_id )
+ # Single bulk query for every candidate's full principal
+ # set, then group in Python — replaces a per-candidate
+ # query that was O(passes × candidates) on the DB.
+ principals_by_candidate : Dict[int, Set[int]] = {}
+ for delegate_id, principal_id in EntityStateDelegation.objects.filter(
+ delegate_entity_id__in = candidate_ids,
+ ).values_list( 'delegate_entity_id', 'entity_state__entity_id' ):
+ principals_by_candidate.setdefault( delegate_id, set() ).add( principal_id )
+
+ added_this_pass = {
+ candidate_id
+ for candidate_id, principal_ids in principals_by_candidate.items()
+ if principal_ids and principal_ids.issubset( closure )
+ }
if not added_this_pass:
break
@@ -98,6 +103,57 @@ class EntityIntegrationOperations:
)
return EntityIntegrationOperations.collect_removal_closure( seed )
+ @classmethod
+ def remove_entities_with_closure(
+ cls,
+ seed_entity_ids : Iterable[int],
+ integration_name : str,
+ preserve_user_data : bool = True,
+ result : Optional[IntegrationSyncResult] = None ):
+ """Canonical removal for integration-owned entities.
+
+ Walks ``collect_removal_closure(seed_entity_ids)`` so every
+ delegate entity that would be orphaned by the removal (e.g.,
+ the Area auto-created when a camera was placed in a view) is
+ included. Each entity in the closure is then handled the
+ same way:
+
+ * ``preserve_user_data=True`` (the SAFE pattern, used by
+ DELETE SAFE on disable and by sync-time refresh
+ removals): entities carrying operator-added attributes
+ are preserved via ``[Disconnected]`` rename; others are
+ hard-deleted.
+
+ * ``preserve_user_data=False`` (the DELETE ALL pattern):
+ every entity in the closure is hard-deleted, including
+ those with user-added data.
+
+ ``result`` is optional. When provided, each closure entity's
+ name is appended to ``result.removed_list``; the preserve
+ path also adds its diagnostic note to ``result.info_list``.
+
+ Each entity in the closure is classified by its *own* user
+ data, independent of the seed's classification. This
+ produces the right outcome in the camera-preserved /
+ Area-no-user-data corner: an auto-created Area's display
+ purpose depends on the principal's live state, which the
+ preserve path removes — so deleting the now-purposeless
+ Area is correct even when its principal is being kept.
+ """
+ closure_ids = cls.collect_removal_closure( seed_entity_ids )
+ for entity in Entity.objects.filter( id__in = closure_ids ):
+ if result is not None:
+ result.removed_list.append( entity.name )
+ if preserve_user_data and EntityUserDataDetector.has_user_created_attributes( entity ):
+ cls.preserve_with_user_data(
+ entity = entity,
+ integration_name = integration_name,
+ result = result,
+ )
+ else:
+ entity.delete()
+ return
+
@staticmethod
def summarize_for_removal( integration_id : str ) -> IntegrationRemovalSummary:
"""
@@ -123,7 +179,7 @@ class EntityIntegrationOperations:
@staticmethod
def preserve_with_user_data( entity : Entity,
integration_name : str,
- result : Optional[ProcessingResult] = None ):
+ result : Optional[IntegrationSyncResult] = None ):
"""
Preserve an entity with user-created data by disconnecting it from
its integration and removing only integration-related components
@@ -133,7 +189,8 @@ class EntityIntegrationOperations:
Args:
entity: The Entity to preserve.
integration_name: Name of the integration (used in result messages).
- result: Optional ProcessingResult to append a status message to.
+ result: Optional IntegrationSyncResult to append a status
+ message to.
"""
original_name = entity.name
@@ -209,7 +266,7 @@ class EntityIntegrationOperations:
entity.save()
if result is not None:
- result.message_list.append(
- f'Preserved {integration_name} entity "{original_name}" with user data, '
+ result.info_list.append(
+ f'Preserved {integration_name} item "{original_name}" with user data, '
f'disconnected from integration and renamed to "{entity.name}"'
)
diff --git a/src/hi/integrations/integration_attribute_edit_context.py b/src/hi/integrations/integration_attribute_edit_context.py
index 00f5e9ff..72d088be 100644
--- a/src/hi/integrations/integration_attribute_edit_context.py
+++ b/src/hi/integrations/integration_attribute_edit_context.py
@@ -33,12 +33,17 @@ class IntegrationAttributeItemEditContext(AttributeItemEditContext):
update_button_label : str = 'UPDATE',
suppress_history : bool = False,
show_secrets : bool = False,
+ is_review_mode : bool = False,
+ pre_sync_url : Optional[str] = None,
) -> None:
"""
Initialize context for Integration attribute editing.
-
- Args:
- integration: The Integration instance that owns the attributes
+
+ Review-mode flags (`is_review_mode` + `pre_sync_url`) drive the
+ Review Config back-from-pre-sync flow: when set, the modal's
+ cancel slot becomes a CONTINUE action that returns to the
+ pre-sync modal instead of dismissing. First-time Configure
+ leaves them unset and keeps the CANCEL/dismiss behavior.
"""
super().__init__( owner_type = 'integration', owner = integration_data.integration )
self.integration_data = integration_data
@@ -46,7 +51,9 @@ class IntegrationAttributeItemEditContext(AttributeItemEditContext):
self._update_button_label = update_button_label
self._suppress_history = suppress_history
self._show_secrets = show_secrets
-
+ self._is_review_mode = is_review_mode
+ self._pre_sync_url = pre_sync_url
+
return
@property
@@ -106,5 +113,7 @@ class IntegrationAttributeItemEditContext(AttributeItemEditContext):
template_context.update({
'integration_data': self.integration_data,
'health_status': self._health_status,
+ 'is_review_mode': self._is_review_mode,
+ 'pre_sync_url': self._pre_sync_url,
})
return template_context
diff --git a/src/hi/integrations/integration_gateway.py b/src/hi/integrations/integration_gateway.py
index 5b3e6c51..4f3821f5 100644
--- a/src/hi/integrations/integration_gateway.py
+++ b/src/hi/integrations/integration_gateway.py
@@ -8,6 +8,7 @@ from hi.apps.system.health_status_provider import HealthStatusProvider
from .integration_controller import IntegrationController
from .integration_manage_view_pane import IntegrationManageViewPane
+from .integration_synchronizer import IntegrationSynchronizer
from .models import IntegrationAttribute
from .transient_models import (
ConnectionTestResult,
@@ -44,6 +45,17 @@ class IntegrationGateway:
def get_health_status_provider(self) -> HealthStatusProvider:
raise NotImplementedError('Subclasses must override this method')
+ def get_synchronizer(self) -> Optional[IntegrationSynchronizer]:
+ """
+ Return the integration's synchronizer when it supports sync;
+ None otherwise. Sync is an opt-in capability — not every
+ integration requires one. The framework owns the sync workflow
+ (pre-sync confirmation, sync execution, post-sync placement);
+ the synchronizer participates by providing the integration-
+ specific work plus a small amount of peripheral metadata.
+ """
+ return None
+
def validate_configuration(
self,
integration_attributes: List[IntegrationAttribute]
diff --git a/src/hi/integrations/integration_manager.py b/src/hi/integrations/integration_manager.py
index b8fe2605..65ffbf53 100644
--- a/src/hi/integrations/integration_manager.py
+++ b/src/hi/integrations/integration_manager.py
@@ -26,7 +26,6 @@ from .integration_gateway import IntegrationGateway
from .transient_models import IntegrationKey
from .models import Integration, IntegrationAttribute
from .transient_models import IntegrationMetaData
-from .user_data_detector import EntityUserDataDetector
logger = logging.getLogger(__name__)
@@ -118,6 +117,18 @@ class IntegrationManager( Singleton ):
def get_health_status_providers(self) -> List[HealthStatusProvider]:
with self._data_lock:
return list( self._monitor_map.values() )
+
+ def get_health_status_provider_map(self) -> Dict[str, HealthStatusProvider]:
+ """Snapshot of running monitors keyed by integration_id.
+
+ Callers that want to pair every configured integration with
+ its monitor (when present) — e.g., the system-info page —
+ use this alongside ``get_integration_data_list``. A missing
+ key for a configured integration means no live monitor
+ (the integration is paused or its monitor failed to start).
+ """
+ with self._data_lock:
+ return dict( self._monitor_map )
async def initialize( self, event_loop ) -> None:
"""
@@ -316,6 +327,12 @@ class IntegrationManager( Singleton ):
new_attribute_types.append( attribute_type )
else:
existing_attr = existing_attributes[integration_key]
+ if existing_attr.name != attribute_type.label:
+ existing_attr.name = attribute_type.label
+ existing_attr.save(
+ update_fields = ['name'],
+ track_history = False,
+ )
description = attribute_type.description or ''
if existing_attr.description != description:
existing_attr.description = description
@@ -358,8 +375,23 @@ class IntegrationManager( Singleton ):
return
def enable_integration( self, integration_data : IntegrationData ):
+ """
+ Idempotent: enabling an already-enabled integration is a no-op.
+
+ The is_enabled re-read happens inside the data lock and atomic
+ transaction so the disabled→enabled transition (which also
+ un-pauses) cannot race with another caller. Callers can invoke
+ this unconditionally without first checking is_enabled, which
+ avoids a TOCTOU window between caller check and manager write.
+ """
with self._data_lock:
with transaction.atomic():
+ # Re-read fresh state inside the lock; another caller
+ # may have enabled the integration between the caller's
+ # check (if any) and our acquiring this lock.
+ integration_data.integration.refresh_from_db()
+ if integration_data.integration.is_enabled:
+ return
integration_data.integration.is_enabled = True
integration_data.integration.is_paused = False
integration_data.integration.save()
@@ -396,33 +428,44 @@ class IntegrationManager( Singleton ):
# in-flight sync work.
self._stop_integration_monitor( integration_data = integration_data )
- integration_id = integration_data.integration_id
+ integration_id = integration_data.integration_id
- with transaction.atomic():
- # Targeted entity set includes the integration's own entities
- # plus any delegate entities that would be orphaned by their
- # removal (e.g., the Area entity auto-created when a motion
- # sensor was added to a view).
- target_ids = EntityIntegrationOperations.get_removal_entity_ids(
- integration_id = integration_id,
- )
- entities = list( Entity.objects.filter( id__in = target_ids ) )
- if mode == IntegrationDisableMode.ALL:
- for entity in entities:
- entity.delete()
- else: # SAFE
- for entity in entities:
- if EntityUserDataDetector.has_user_created_attributes( entity ):
- EntityIntegrationOperations.preserve_with_user_data(
- entity = entity,
- integration_name = integration_id,
- )
- else:
- entity.delete()
-
- integration_data.integration.is_enabled = False
- integration_data.integration.is_paused = False
- integration_data.integration.save()
+ # DB-level entity removal does not need the manager's data
+ # lock — it operates on rows, not on the in-memory monitor
+ # map, and transaction.atomic() handles row-level
+ # concurrency. Holding _data_lock across the closure walk
+ # and cascading deletes would block all other lifecycle
+ # calls on every integration for the duration of a wide
+ # removal.
+ with transaction.atomic():
+ # Seed: every entity attached to this integration. The
+ # closure walk inside the helper picks up delegate
+ # entities (e.g., Area entities auto-created when a
+ # motion sensor was placed in a view) that would be
+ # orphaned by the removal.
+ seed_entity_ids = list(
+ Entity.objects
+ .filter( integration_id = integration_id )
+ .values_list( 'id', flat = True )
+ )
+ EntityIntegrationOperations.remove_entities_with_closure(
+ seed_entity_ids = seed_entity_ids,
+ integration_name = integration_id,
+ preserve_user_data = ( mode != IntegrationDisableMode.ALL ),
+ )
+
+ with self._data_lock:
+ # Re-read inside the lock: a concurrent lifecycle call
+ # may have touched the row while we were doing the
+ # lock-free DB removal. The disable intent still wins
+ # (entities are gone), so we unconditionally flip both
+ # flags to the disabled state — but refresh first so
+ # we don't clobber unrelated fields a concurrent caller
+ # may have written.
+ integration_data.integration.refresh_from_db()
+ integration_data.integration.is_enabled = False
+ integration_data.integration.is_paused = False
+ integration_data.integration.save()
return
def pause_integration( self, integration_data : IntegrationData ):
diff --git a/src/hi/integrations/integration_synchronizer.py b/src/hi/integrations/integration_synchronizer.py
new file mode 100644
index 00000000..b5e9f4a0
--- /dev/null
+++ b/src/hi/integrations/integration_synchronizer.py
@@ -0,0 +1,177 @@
+"""
+Per-integration synchronizer base class.
+
+The general integration framework owns the sync workflow (pre-sync
+confirmation modal, sync execution view, post-sync placement modal).
+The synchronizer is the per-integration participant that the framework
+hands off to for the integration-specific work plus a small amount of
+peripheral metadata the framework surfaces alongside.
+
+Each integration that supports sync provides a concrete subclass and
+returns an instance of it from `IntegrationGateway.get_synchronizer()`.
+Sync is opt-in: a gateway whose integration does not support sync
+returns None.
+"""
+import logging
+from typing import List, Optional
+
+from hi.apps.common.database_lock import ExclusionLockContext
+from hi.apps.entity.entity_placement import (
+ EntityPlacementInput,
+ EntityPlacementItem,
+)
+from hi.apps.entity.models import Entity
+
+from .entity_operations import EntityIntegrationOperations
+from .sync_result import IntegrationSyncResult
+
+logger = logging.getLogger(__name__)
+
+
+class IntegrationSynchronizer:
+ """
+ Base class for per-integration synchronizers.
+
+ The framework calls `sync()`. The base implementation acquires a
+ process-wide synchronization lock, delegates to the subclass's
+ `_sync_impl()`, and converts unexpected RuntimeError into a result
+ object. Subclasses implement the integration-specific work in
+ `_sync_impl()` and the small metadata accessors below.
+
+ Synchronization is process-wide rather than per-integration: at
+ most one integration sync runs at a time. Concurrent syncs across
+ integrations could race over shared infrastructure (entity tables,
+ location-view bookkeeping in later phases) and the user is unlikely
+ to need parallelism here. Override at a subclass level if a future
+ integration genuinely needs concurrent sync.
+ """
+
+ # Single shared lock name across all integration syncs. See class
+ # docstring above for the rationale.
+ SYNCHRONIZATION_LOCK_NAME = 'integrations_sync'
+
+ def get_description(self, is_initial_import: bool) -> Optional[str]:
+ """
+ Optional copy describing what this integration's sync will do,
+ surfaced to the operator in the framework's pre-sync
+ confirmation modal alongside a generic lead message.
+
+ `is_initial_import` distinguishes the first-time IMPORT (no
+ entities have been imported yet) from subsequent REFRESH
+ operations. The two contexts mean different things to the
+ operator and integrations are encouraged to provide tailored
+ copy for each. Return None to render only the generic lead
+ text.
+ """
+ return None
+
+ def get_result_title(self, is_initial_import: bool) -> str:
+ """
+ Short, generic header for the sync result modal: 'Import
+ Result' for the first-time path, 'Refresh Result' otherwise.
+ The integration's identity is surfaced in the modal body
+ (logo + label) rather than the title bar — keeps the title
+ bar contrast predictable regardless of integration. Override
+ only if a specific integration genuinely needs custom copy.
+ """
+ if is_initial_import:
+ return 'Import Result'
+ return 'Refresh Result'
+
+ def sync(self, is_initial_import: bool) -> IntegrationSyncResult:
+ """
+ Public entry point used by the framework. Wraps `_sync_impl`
+ with the sync lock and standard error handling. Subclasses
+ override `_sync_impl` rather than this method.
+
+ ``is_initial_import`` is the operator-intent flag from the
+ sync flow (Import for first-time, Refresh otherwise);
+ threaded down so each subclass can title its result
+ consistently.
+ """
+ try:
+ with ExclusionLockContext(name=self.SYNCHRONIZATION_LOCK_NAME):
+ logger.debug(f'{self.__class__.__name__} sync started.')
+ return self._sync_impl(is_initial_import=is_initial_import)
+ except RuntimeError as e:
+ logger.exception(e)
+ return IntegrationSyncResult(
+ title=self.get_result_title(is_initial_import=is_initial_import),
+ error_list=[str(e)],
+ )
+ finally:
+ logger.debug(f'{self.__class__.__name__} sync ended.')
+
+ def _sync_impl(self, is_initial_import: bool) -> IntegrationSyncResult:
+ """
+ Integration-specific sync work. Subclasses must override.
+ Called with the synchronization lock held.
+ """
+ raise NotImplementedError('Subclasses must override this method')
+
+ def group_entities_for_placement(
+ self, entities : List[Entity],
+ ) -> EntityPlacementInput:
+ """Partition a set of entities into the
+ ``EntityPlacementInput`` shape consumed by the placement
+ modal.
+
+ Two callers:
+
+ * The sync flow passes in the entities just *created* during
+ this sync run (existing-entity updates do not need
+ re-placement).
+ * A future "place unplaced items" recovery feature will pass
+ in entities that already exist for the integration but have
+ no EntityView row.
+
+ Either caller receives the same shape; the per-integration
+ grouping logic lives in this method so both callers agree
+ on what "groups" means for this integration.
+
+ Default implementation: every entity is ungrouped. Subclasses
+ override to provide a meaningful domain grouping (e.g., HASS
+ by entity_type, ZM single "Monitors" group).
+ """
+ return EntityPlacementInput(
+ ungrouped_items = [
+ EntityPlacementItem(
+ key = self._placement_item_key( entity = entity ),
+ label = entity.name,
+ entity = entity,
+ )
+ for entity in entities
+ ],
+ )
+
+ def _placement_item_key( self, entity : Entity ) -> str:
+ """Stable per-entity placement key. Subclasses may override
+ for custom keying; the default uses the entity's
+ integration_key when available, falling back to the row id."""
+ integration_key = entity.integration_key
+ if integration_key:
+ return f'{integration_key.integration_id}:{integration_key.integration_name}'
+ return f'entity:{entity.id}'
+
+ def _remove_entity_intelligently(self,
+ entity: Entity,
+ result: IntegrationSyncResult,
+ integration_name: str):
+ """
+ Remove an entity that no longer exists in the integration.
+
+ Delegates to ``EntityIntegrationOperations.remove_entities_with_closure``
+ — the same path the integration-disable SAFE flow uses. The
+ closure walk picks up delegate entities (e.g., the Area
+ auto-created when a camera was placed in a view) when their
+ only remaining principal is being removed. Operator-added
+ attributes on any closure entity trigger the
+ ``[Disconnected]`` preserve path; otherwise the entity is
+ hard-deleted.
+ """
+ EntityIntegrationOperations.remove_entities_with_closure(
+ seed_entity_ids = { entity.id },
+ integration_name = integration_name,
+ preserve_user_data = True,
+ result = result,
+ )
diff --git a/src/hi/integrations/placement_request.py b/src/hi/integrations/placement_request.py
new file mode 100644
index 00000000..fdcbd8de
--- /dev/null
+++ b/src/hi/integrations/placement_request.py
@@ -0,0 +1,332 @@
+"""
+Placement view request shape — parsing the inputs, encoding the
+outputs.
+
+The placement modal carries two related concerns that this module
+owns:
+
+* ``PlacementUrlParams`` — the URL/form-param contract
+ (``is_initial_import``, ``entity_ids``). Single source of truth
+ for key names and value encodings; build URLs and parse requests
+ via this class rather than handling raw strings.
+
+* ``PlacementFormParser`` — the placement-form-body parser. The
+ placement modal carries a three-level inheritance: top default
+ → group default → per-entity. Empty selections at any level
+ inherit from the parent; explicit ``__skip__`` overrides
+ inheritance with "don't place this entity"; a top-level
+ ``__new_view__`` value creates one fresh ``LocationView`` named
+ after the integration; a top-level ``__new_collection__`` value
+ creates one fresh ``Collection``. Group/entity overrides to
+ existing views or collections remain in effect even when the
+ top is one of the new-* sentinels.
+
+ Form values for the dropdowns are *tagged* so views and
+ collections can share the same select element without colliding
+ on numeric ids:
+
+ ``view:<id>`` — existing LocationView
+ ``collection:<id>`` — existing Collection
+ ``__new_view__`` — create one fresh LocationView (top only)
+ ``__new_collection__`` — create one fresh Collection (top only)
+ ``__skip__`` — explicit no-op overriding parent
+ ``''`` — inherit from parent (top → skip-all)
+
+ ``parse(request, integration_data)`` returns a list of
+ ``PlacementDecision`` values for the placement service to apply.
+"""
+import logging
+from dataclasses import dataclass, field
+from typing import Dict, List, Optional, Tuple
+
+from django.core.exceptions import BadRequest
+from django.utils.http import urlencode
+
+from hi.apps.collection.collection_manager import CollectionManager
+from hi.apps.collection.models import Collection
+from hi.apps.common.utils import str_to_bool
+from hi.apps.entity.entity_placement import PlacementDecision
+from hi.apps.entity.models import Entity
+from hi.apps.location.location_manager import LocationManager
+from hi.apps.location.models import Location, LocationView
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass(frozen=True)
+class PlacementUrlParams:
+ """Encoded contract for the placement view's URL/form params.
+
+ Single source of truth for key names, value encodings, and
+ list separators — callers build URLs and parse requests via
+ this class rather than handling raw strings. Renaming a key
+ or changing an encoding happens in exactly one place.
+
+ Scope: the URL query params (``?is_initial_import=…&entity_ids=…``)
+ and the matching hidden form fields the placement modal POSTs
+ back. Does *not* cover the per-entity / per-group form fields
+ consumed by ``PlacementFormParser`` — those have their own
+ contract owned by that parser.
+ """
+
+ KEY_IS_INITIAL_IMPORT = 'is_initial_import'
+ KEY_ENTITY_IDS = 'entity_ids'
+ ENTITY_IDS_SEP = ','
+ TRUE_VALUE = '1'
+ FALSE_VALUE = '0'
+
+ is_initial_import : bool = False
+ entity_ids : List[int] = field(default_factory=list)
+
+ def to_query_dict(self) -> Dict[str, str]:
+ """Sparse query dict — keys are omitted when their value
+ is the default, keeping URLs free of redundant
+ ``?is_initial_import=0`` cruft."""
+ result : Dict[str, str] = {}
+ if self.is_initial_import:
+ result[self.KEY_IS_INITIAL_IMPORT] = self.TRUE_VALUE
+ if self.entity_ids:
+ result[self.KEY_ENTITY_IDS] = self.ENTITY_IDS_SEP.join(
+ str(i) for i in self.entity_ids
+ )
+ return result
+
+ def append_to_url( self, base_url : str ) -> str:
+ """Return ``base_url`` with these params encoded as a
+ query string. Empty params produce no '?' suffix."""
+ qd = self.to_query_dict()
+ return f'{base_url}?{urlencode(qd)}' if qd else base_url
+
+ def is_initial_import_form_value(self) -> str:
+ """The hidden-form-field encoding of ``is_initial_import``
+ for templates that need to round-trip the flag through a
+ POST."""
+ return self.TRUE_VALUE if self.is_initial_import else self.FALSE_VALUE
+
+ @classmethod
+ def from_data(cls, data) -> 'PlacementUrlParams':
+ """Parse from ``request.GET`` or ``request.POST`` (or any
+ QueryDict-like). Malformed ``entity_ids`` raises BadRequest
+ so a tampered request fails loudly rather than silently
+ widening scope."""
+ is_initial = str_to_bool( data.get( cls.KEY_IS_INITIAL_IMPORT, '' ) )
+ raw = ( data.get( cls.KEY_ENTITY_IDS, '' ) or '' ).strip()
+ entity_ids : List[int] = []
+ if raw:
+ try:
+ entity_ids = [
+ int( piece )
+ for piece in raw.split( cls.ENTITY_IDS_SEP )
+ if piece.strip()
+ ]
+ except ValueError:
+ raise BadRequest( f'Invalid {cls.KEY_ENTITY_IDS} parameter.' )
+ return cls( is_initial_import = is_initial, entity_ids = entity_ids )
+
+
+class PlacementFormParser:
+ """Translates placement modal form input into a list of
+ ``PlacementDecision`` values, applying three-level inheritance
+ and the skip / new-view / new-collection sentinels."""
+
+ FORM_VALUE_SKIP = '__skip__'
+ FORM_VALUE_NEW_VIEW = '__new_view__'
+ FORM_VALUE_NEW_COLLECTION = '__new_collection__'
+
+ @classmethod
+ def parse( cls, request, integration_data ) -> List[PlacementDecision]:
+ decisions = []
+ view_lookup = cls._build_view_lookup()
+ collection_lookup = cls._build_collection_lookup()
+
+ top_value = request.POST.get('top_view', '').strip()
+ top_target = cls._resolve_top_target(
+ request = request,
+ top_value = top_value,
+ view_lookup = view_lookup,
+ collection_lookup = collection_lookup,
+ integration_data = integration_data,
+ )
+
+ # Discover group indices by scanning POST keys.
+ group_indices = sorted({
+ int(k.split('_')[2])
+ for k in request.POST.keys()
+ if k.startswith('all_group_') and k.endswith('_entity_ids')
+ })
+ for group_index in group_indices:
+ group_value = request.POST.get(
+ f'group_view_{group_index}', '' ).strip()
+ group_target = cls._resolve_child_choice(
+ form_value = group_value,
+ parent_target = top_target,
+ view_lookup = view_lookup,
+ collection_lookup = collection_lookup,
+ )
+ entity_id_list = request.POST.getlist(
+ f'all_group_{group_index}_entity_ids' )
+ entities = list( Entity.objects.filter(
+ id__in = [int(e) for e in entity_id_list]
+ ) )
+ entity_by_id = { e.id: e for e in entities }
+ for entity_id_str in entity_id_list:
+ entity = entity_by_id.get( int(entity_id_str) )
+ if entity is None:
+ continue
+ entity_value = request.POST.get(
+ f'group_{group_index}_entity_{entity.id}_view', '' ).strip()
+ entity_target = cls._resolve_child_choice(
+ form_value = entity_value,
+ parent_target = group_target,
+ view_lookup = view_lookup,
+ collection_lookup = collection_lookup,
+ )
+ decisions.append( cls._make_decision(
+ entity = entity, target = entity_target,
+ ) )
+
+ # Ungrouped items: no group level — entity inherits from top.
+ ungrouped_ids = request.POST.getlist( 'ungrouped_entity_ids' )
+ if ungrouped_ids:
+ ungrouped = list( Entity.objects.filter(
+ id__in = [int(e) for e in ungrouped_ids]
+ ) )
+ ungrouped_by_id = { e.id: e for e in ungrouped }
+ for entity_id_str in ungrouped_ids:
+ entity = ungrouped_by_id.get( int(entity_id_str) )
+ if entity is None:
+ continue
+ entity_value = request.POST.get(
+ f'ungrouped_entity_{entity.id}_view', '' ).strip()
+ entity_target = cls._resolve_child_choice(
+ form_value = entity_value,
+ parent_target = top_target,
+ view_lookup = view_lookup,
+ collection_lookup = collection_lookup,
+ )
+ decisions.append( cls._make_decision(
+ entity = entity, target = entity_target,
+ ) )
+
+ return decisions
+
+ @classmethod
+ def _make_decision( cls, entity, target ) -> PlacementDecision:
+ """target is a 2-tuple (location_view, collection) where at
+ most one is non-None, or (None, None) for skip."""
+ location_view, collection = target
+ return PlacementDecision(
+ entity = entity,
+ location_view = location_view,
+ collection = collection,
+ )
+
+ @classmethod
+ def _resolve_top_target( cls,
+ request,
+ top_value : str,
+ view_lookup : dict,
+ collection_lookup : dict,
+ integration_data,
+ ) -> Tuple[Optional[LocationView], Optional[Collection]]:
+ """Top-level form value → (location_view, collection) target.
+
+ Top values: ''=skip-all, '__new_view__'=create fresh view,
+ '__new_collection__'=create fresh collection,
+ 'view:<id>'=existing view, 'collection:<id>'=existing
+ collection. Creating a new view/collection is the side
+ effect of the corresponding sentinel; the new object
+ becomes the top default for everything else.
+ """
+ if top_value == cls.FORM_VALUE_NEW_VIEW:
+ return cls._create_new_view(
+ request = request, integration_data = integration_data,
+ ), None
+ if top_value == cls.FORM_VALUE_NEW_COLLECTION:
+ return None, cls._create_new_collection(
+ integration_data = integration_data,
+ )
+ if top_value == '':
+ return None, None
+ return cls._lookup_tagged_target(
+ tagged_value = top_value,
+ view_lookup = view_lookup,
+ collection_lookup = collection_lookup,
+ )
+
+ @classmethod
+ def _resolve_child_choice(
+ cls,
+ form_value : str,
+ parent_target : Tuple[Optional[LocationView], Optional[Collection]],
+ view_lookup : dict,
+ collection_lookup : dict,
+ ) -> Tuple[Optional[LocationView], Optional[Collection]]:
+ """Group/entity form value → (location_view, collection)
+ target. Empty inherits from parent; '__skip__' overrides
+ any inherited parent value with skip; otherwise it's a
+ tagged existing-target id ('view:<id>' or 'collection:<id>').
+ Group/entity dropdowns do not offer the new-* sentinels —
+ only the top level can create a new target."""
+ if form_value == '':
+ return parent_target
+ if form_value == cls.FORM_VALUE_SKIP:
+ return None, None
+ return cls._lookup_tagged_target(
+ tagged_value = form_value,
+ view_lookup = view_lookup,
+ collection_lookup = collection_lookup,
+ )
+
+ @classmethod
+ def _lookup_tagged_target(
+ cls,
+ tagged_value : str,
+ view_lookup : dict,
+ collection_lookup : dict,
+ ) -> Tuple[Optional[LocationView], Optional[Collection]]:
+ """Parse 'view:<id>' or 'collection:<id>' into a
+ (location_view, collection) tuple. Unknown tag prefix or
+ missing id resolves to skip."""
+ if ':' not in tagged_value:
+ return None, None
+ kind, _, raw_id = tagged_value.partition(':')
+ if kind == 'view':
+ return view_lookup.get( raw_id ), None
+ if kind == 'collection':
+ return None, collection_lookup.get( raw_id )
+ return None, None
+
+ @classmethod
+ def _create_new_view( cls, request, integration_data ) -> LocationView:
+ """Create a single LocationView named after the integration
+ label, attached to the operator's current default Location.
+ ``LocationManager.create_location_view`` handles name
+ collisions via its built-in disambiguation."""
+ try:
+ location = LocationManager().get_default_location( request = request )
+ except Location.DoesNotExist:
+ raise BadRequest(
+ 'Cannot create a new view: no Location is configured.'
+ )
+ return LocationManager().create_location_view(
+ location = location,
+ name = integration_data.label,
+ )
+
+ @classmethod
+ def _create_new_collection( cls, integration_data ) -> Collection:
+ """Create a single Collection named after the integration
+ label. ``CollectionManager.create_collection`` handles name
+ collisions via its built-in disambiguation."""
+ return CollectionManager().create_collection(
+ name = integration_data.label,
+ )
+
+ @classmethod
+ def _build_view_lookup( cls ) -> dict:
+ return { str(v.id): v for v in LocationView.objects.all() }
+
+ @classmethod
+ def _build_collection_lookup( cls ) -> dict:
+ return { str(c.id): c for c in Collection.objects.all() }
diff --git a/src/hi/integrations/sync_mixins.py b/src/hi/integrations/sync_mixins.py
deleted file mode 100644
index 2d7050b2..00000000
--- a/src/hi/integrations/sync_mixins.py
+++ /dev/null
@@ -1,47 +0,0 @@
-"""
-Mixins for integration synchronization operations.
-
-This module provides common functionality for integration sync operations,
-particularly around intelligent entity deletion that preserves user data.
-"""
-
-import logging
-
-from hi.apps.common.processing_result import ProcessingResult
-from hi.apps.entity.models import Entity
-
-from .entity_operations import EntityIntegrationOperations
-from .user_data_detector import EntityUserDataDetector
-
-logger = logging.getLogger(__name__)
-
-
-class IntegrationSyncMixin:
- """
- Mixin providing common functionality for integration synchronization operations.
-
- Provides intelligent entity deletion that preserves user-created data
- while removing integration-specific components.
- """
-
- def _remove_entity_intelligently(self,
- entity: Entity,
- result: ProcessingResult,
- integration_name: str):
- """
- Remove an entity that no longer exists in the integration.
-
- If the entity has user-created attributes, preserve the entity but
- disconnect it from the integration and remove only integration-related
- components. Otherwise, perform complete deletion.
- """
- if EntityUserDataDetector.has_user_created_attributes(entity):
- EntityIntegrationOperations.preserve_with_user_data(
- entity = entity,
- integration_name = integration_name,
- result = result,
- )
- else:
- # No user data, safe to delete completely
- entity.delete() # Deletion cascades to all related data
- result.message_list.append(f'Removed stale {integration_name} entity: {entity}')
diff --git a/src/hi/integrations/sync_result.py b/src/hi/integrations/sync_result.py
new file mode 100644
index 00000000..18b9d578
--- /dev/null
+++ b/src/hi/integrations/sync_result.py
@@ -0,0 +1,74 @@
+"""
+Transient data shapes returned by integration sync operations.
+
+The framework owns the sync workflow (pre-sync modal, sync view,
+post-sync placement modal). Each integration's
+``IntegrationSynchronizer.sync()`` returns an
+``IntegrationSyncResult`` describing what happened during sync —
+title, structured change counts, info/error notes — plus an
+optional ``EntityPlacementInput`` that drives the placement modal
+when the sync produced new entities to place.
+
+The placement input shape lives in ``hi.apps.entity.entity_placement``
+because it isn't sync-specific: any future flow that bulk-places
+entities (e.g., a "place unplaced items" recovery feature) builds
+the same shape from a different source. Sync is one supplier among
+several.
+
+The result modal renders a counts-driven lead summary
+("N created, M updated, R removed") with per-category disclosures
+that enumerate the affected items by name, plus collapsible
+Details (``info_list``) and Errors (``error_list``) sections.
+Counts are derived from list lengths — the lists are the source
+of truth. ``info_list`` carries diagnostic context the per-item
+lists can't express ("Found N upstream items", "Filtered N by
+allowlist", etc.).
+"""
+from dataclasses import dataclass, field
+from typing import List, Optional
+
+from hi.apps.entity.entity_placement import EntityPlacementInput
+
+
+@dataclass
+class IntegrationSyncResult:
+ """Outcome of a single integration sync run.
+
+ ``placement_input`` is None when the sync produced no new
+ entities to place (the typical refresh-with-no-new-items case);
+ populated when there's something for the placement modal to
+ show. The framework uses presence/absence of placement_input —
+ not emptiness checks against groups/ungrouped_items — to decide
+ whether to show the placement.
+
+ ``created_list`` / ``updated_list`` / ``removed_list`` hold the
+ *names* of entities affected by this sync run, populated by the
+ per-integration synchronizer as it walks upstream items. The
+ result modal uses list length for the count badges and the
+ list contents for per-category "Show items" disclosures so the
+ operator can see which entities were touched. Names only —
+ per-attribute change detail is intentionally not surfaced.
+
+ ``info_list`` carries diagnostic notes — "Found N upstream
+ items", "Filtered N by allowlist" — that the per-item lists
+ can't express. Rendered as a collapsible Details section in
+ the result modal. ``error_list`` is the parallel for failures.
+ """
+ title: str
+ placement_input: Optional[EntityPlacementInput] = None
+ created_list: List[str] = field(default_factory=list)
+ updated_list: List[str] = field(default_factory=list)
+ removed_list: List[str] = field(default_factory=list)
+ info_list: List[str] = field(default_factory=list)
+ error_list: List[str] = field(default_factory=list)
+ footer_message: str = ''
+
+ @property
+ def has_changes(self) -> bool:
+ """True if the sync produced any operator-relevant change.
+ Drives the 'Nothing new' lead line when False."""
+ return bool(
+ self.created_list
+ or self.updated_list
+ or self.removed_list
+ )
diff --git a/src/hi/integrations/templates/integrations/modals/integration_disable.html b/src/hi/integrations/templates/integrations/modals/integration_disable.html
index 4f743034..8684250d 100644
--- a/src/hi/integrations/templates/integrations/modals/integration_disable.html
+++ b/src/hi/integrations/templates/integrations/modals/integration_disable.html
@@ -15,14 +15,14 @@
{% endblock %}
{% block body %}
-<h4>Remove {{ integration_data.label }} Integration?</h4>
+<h4>Disable {{ integration_data.label }} Integration?</h4>
{% if removal_summary.total_count == 0 %}
-<p>This integration has no attached entities.</p>
+<p>This integration has no attached items.</p>
{% elif removal_summary.has_mixed_state %}
<p>
This integration has <strong>{{ removal_summary.total_count }}</strong>
- {% if removal_summary.total_count == 1 %}entity{% else %}entities{% endif %}.
+ {% if removal_summary.total_count == 1 %}item{% else %}items{% endif %}.
<strong>{{ removal_summary.user_data_count }}</strong> of
{% if removal_summary.user_data_count == 1 %}them has{% else %}them have{% endif %}
custom data you've added.
@@ -30,14 +30,14 @@
<ul>
<li>
<strong>DELETE SAFE</strong> — delete the {{ removal_summary.deletable_count }}
- {% if removal_summary.deletable_count == 1 %}entity{% else %}entities{% endif %}
+ {% if removal_summary.deletable_count == 1 %}item{% else %}items{% endif %}
without custom data, and preserve the {{ removal_summary.user_data_count }} with custom
data (disconnected from this integration, prefixed with
<code>[Disconnected]</code>, custom attributes and layout retained).
</li>
<li>
<strong>DELETE ALL</strong> — delete all {{ removal_summary.total_count }}
- {% if removal_summary.total_count == 1 %}entity{% else %}entities{% endif %}
+ {% if removal_summary.total_count == 1 %}item{% else %}items{% endif %}
and all the custom data associated with these items.
You will not be able to recover the deleted custom data.
</li>
@@ -45,14 +45,14 @@
{% else %}
<p>
This integration has <strong>{{ removal_summary.total_count }}</strong>
- {% if removal_summary.total_count == 1 %}entity{% else %}entities{% endif %}.
+ {% if removal_summary.total_count == 1 %}item{% else %}items{% endif %}.
None have custom data you've added, so all will be deleted.
</p>
{% endif %}
<p class="text-muted small">
Configuration values are retained. If you re-configure this integration
- later, it will start fresh without reconnecting to any preserved entities.
+ later, it will start fresh without reconnecting to any preserved items.
</p>
{% endblock %}
diff --git a/src/hi/integrations/templates/integrations/modals/integrations_select.html b/src/hi/integrations/templates/integrations/modals/integrations_select.html
index c8924826..dadc7473 100644
--- a/src/hi/integrations/templates/integrations/modals/integrations_select.html
+++ b/src/hi/integrations/templates/integrations/modals/integrations_select.html
@@ -1,10 +1,10 @@
-{% extends "modals/action_done.html" %}
+{% extends "modals/action_ok.html" %}
{% load icons static %}
-{% block modal_dialog_class %}hi-modal-dialog-600{% endblock %}
+{% block modal_dialog_class %}hi-modal-dialog-700{% endblock %}
{% block title_text %}
-Select Integrations
+All Integrations
{% endblock %}
{% block body %}
@@ -24,11 +24,11 @@ Select Integrations
{% icon "disabled" size="sm" css_class="hi-icon-left" %}Not configured
</span>
{% elif integration_data.integration.is_paused %}
- <span class="text-weight-bold text-warning">
+ <span class="font-weight-bold text-warning">
{% icon "pause" size="sm" css_class="hi-icon-left" %}Paused
</span>
{% else %}
- <span class="text-weight-bold text-primary">
+ <span class="font-weight-bold text-primary">
{% icon "check-circle" size="sm" css_class="hi-icon-left" %}Running
</span>
{% endif %}
@@ -38,12 +38,12 @@ Select Integrations
{% if integration_data.integration.is_enabled %}
<a href="{% url 'integrations_disable' integration_id=integration_data.integration.integration_id %}"
role="button" class="btn btn-danger btn-control" data-async="modal">
- {% icon "delete" size="sm" css_class="hi-icon-left" %}REMOVE
+ {% icon "delete" size="sm" css_class="hi-icon-left" %}DISABLE
</a>
{% else %}
<a href="{% url 'integrations_enable' integration_id=integration_data.integration.integration_id %}"
class="btn btn-primary btn-control" role="button" data-async="modal">
- {% icon "plug" size="sm" css_class="hi-icon-left" %}CONFIGURE
+ {% icon "settings" size="sm" css_class="hi-icon-left" %}CONFIGURE
</a>
{% endif %}
</div>
diff --git a/src/hi/integrations/templates/integrations/modals/placement.html b/src/hi/integrations/templates/integrations/modals/placement.html
new file mode 100644
index 00000000..966c88f1
--- /dev/null
+++ b/src/hi/integrations/templates/integrations/modals/placement.html
@@ -0,0 +1,202 @@
+{% extends "modals/action_2_with_cancel.html" %}
+{% load icons %}
+
+{% comment %}
+Post-sync entity placement placement.
+
+Progressive disclosure: by default only the top-level decision is
+visible ("Place all new items in [target]") with an inventory
+preview underneath ("5 lights · 3 outlets · ..."). The group rows
+and per-item rows are hidden behind a "Place differently"
+disclosure. Inside the disclosure, group rows are single-line and
+each carries its own per-item drill-down disclosure.
+
+Three-level inheritance under the hood is unchanged: top default →
+group default → per-item. Empty selections at any level inherit
+from the level above; explicit "Don't place" at any level prevents
+placement for that branch.
+
+The top level alone offers a "+ New view" option, which creates one
+fresh LocationView (named after the integration, attached to the
+operator's current default Location) on Apply. Group/entity
+overrides to existing views remain in effect even when the top is
+"+ New view".
+
+Existing-view dropdowns are rendered as <optgroup>-per-Location so
+multi-Location deployments can disambiguate views with shared names
+("All", "Default", etc.).
+
+Context:
+ integration_data : IntegrationData (required)
+ placement_input : EntityPlacementInput (required)
+ location_view_groups : List[(Location, List[LocationView])] (required)
+ collection_list : List[Collection] (required)
+ top_default_value : str (required) — pre-selected value for
+ the top dropdown ('__new_view__',
+ 'view:<id>', 'collection:<id>', or '')
+ new_view_name : str (required) — pre-disambiguated name
+ shown in the '+ New view: "X"' option
+ label; matches what the apply path will
+ actually create.
+ new_collection_name : str (required) — pre-disambiguated name
+ shown in the '+ New collection: "X"'
+ option label; matches what the apply
+ path will actually create.
+ inventory_preview : List[{'label', 'count'}] (required) —
+ group label + count tuples for the
+ summary line; empty for all-ungrouped
+ inputs (preview hidden in that case)
+ placement_url : str (required) — same URL that rendered
+ this modal; the form POSTs back to it
+ and the view branches on the submitted
+ ``action`` value.
+ is_initial_import : bool (required)
+{% endcomment %}
+
+{% block title_text %}
+Place new items
+{% endblock %}
+
+{% block preamble %}
+<form id="hi-placement-form" method="post" action="{{ placement_url }}"
+ class="form" data-async="modal">
+ {% csrf_token %}
+ {% comment %}
+ Pre-sync intent threaded forward so the post-dispatch modal
+ titles itself consistently with what the operator clicked.
+ {% endcomment %}
+ <input type="hidden" name="is_initial_import"
+ value="{{ is_initial_import|yesno:'1,0' }}">
+{% endblock %}
+
+{% block body %}
+
+ <div class="d-flex align-items-center mb-2 hi-placement-top">
+ <div class="flex-grow-1">
+ <strong>Place all new items in</strong>
+ </div>
+ <select name="top_view" class="form-control form-control-sm w-auto">
+ <option value="" {% if top_default_value == "" %}selected{% endif %}>Don't place</option>
+ <option value="__new_view__" {% if top_default_value == "__new_view__" %}selected{% endif %}>+ New view: "{{ new_view_name }}"</option>
+ <option value="__new_collection__" {% if top_default_value == "__new_collection__" %}selected{% endif %}>+ New collection: "{{ new_collection_name }}"</option>
+ {% include "integrations/panes/placement_target_options.html" with selected_view_id=top_default_view_id selected_collection_id=top_default_collection_id %}
+ </select>
+ </div>
+
+ {% if inventory_preview %}
+ <div class="text-muted small mb-3 hi-placement-preview">
+ {% for entry in inventory_preview %}{{ entry.count }} {{ entry.label|lower }}{% if not forloop.last %} · {% endif %}{% endfor %}
+ </div>
+ {% endif %}
+
+ {% if placement_input.groups or placement_input.ungrouped_items %}
+ <div class="mb-2">
+ <a class="btn btn-sm btn-outline-primary" data-toggle="collapse"
+ href="#hi-placement-overrides" role="button"
+ aria-expanded="false" aria-controls="hi-placement-overrides">
+ {% icon "chevron-down" size="sm" css_class="hi-icon-left" %}Place differently
+ </a>
+ </div>
+
+ <div class="collapse" id="hi-placement-overrides">
+ <div class="text-muted small mb-2">
+ Override the top choice per group, or drill into a group
+ for per-item placement. Empty selections inherit from the
+ level above.
+ </div>
+
+ {% for group in placement_input.groups %}
+ {% with forloop.counter0 as group_index %}
+ <div class="hi-placement-group border-bottom py-2">
+ <div class="d-flex align-items-center">
+ <div class="flex-grow-1">
+ <strong>{{ group.label }}</strong>
+ <span class="badge badge-light ml-1">{{ group.items|length }}</span>
+ </div>
+ <select name="group_view_{{ group_index }}" class="form-control form-control-sm w-auto">
+ <option value="">Use top choice</option>
+ <option value="__skip__">Don't place</option>
+ {% include "integrations/panes/placement_target_options.html" %}
+ </select>
+ <a class="btn btn-sm btn-link" data-toggle="collapse"
+ href="#hi-drill-{{ group_index }}" role="button"
+ aria-expanded="false" aria-controls="hi-drill-{{ group_index }}">
+ Per item ▸
+ </a>
+ </div>
+ <div class="collapse mt-2 pl-3" id="hi-drill-{{ group_index }}">
+ {% for item in group.items %}
+ <div class="d-flex align-items-center py-1">
+ <div class="flex-grow-1 small">{{ item.label }}</div>
+ <select name="group_{{ group_index }}_entity_{{ item.entity.id }}_view"
+ class="form-control form-control-sm w-auto">
+ <option value="">Use group choice</option>
+ <option value="__skip__">Don't place</option>
+ {% include "integrations/panes/placement_target_options.html" %}
+ </select>
+ </div>
+ {% endfor %}
+ </div>
+ </div>
+ {% endwith %}
+ {% endfor %}
+
+ {% if placement_input.ungrouped_items %}
+ <div class="hi-placement-ungrouped py-2">
+ <div class="d-flex align-items-center mb-1">
+ <div class="flex-grow-1">
+ <strong>Other items</strong>
+ <span class="badge badge-light ml-1">{{ placement_input.ungrouped_items|length }}</span>
+ </div>
+ </div>
+ <div class="pl-3">
+ {% for item in placement_input.ungrouped_items %}
+ <div class="d-flex align-items-center py-1">
+ <div class="flex-grow-1 small">{{ item.label }}</div>
+ <select name="ungrouped_entity_{{ item.entity.id }}_view"
+ class="form-control form-control-sm w-auto">
+ <option value="">Use top choice</option>
+ <option value="__skip__">Don't place</option>
+ {% include "integrations/panes/placement_target_options.html" %}
+ </select>
+ </div>
+ {% endfor %}
+ </div>
+ </div>
+ {% endif %}
+ </div>
+ {% endif %}
+
+ {% comment %}
+ Hidden POST membership for groups/ungrouped: the placement
+ form parser needs to know which entities belong to which
+ group/ungrouped bucket regardless of whether the operator
+ opened any drill-down. Kept outside the disclosure so they
+ POST whether or not the operator expanded the override section.
+ {% endcomment %}
+ {% for group in placement_input.groups %}
+ {% with forloop.counter0 as group_index %}
+ {% for item in group.items %}
+ <input type="hidden" name="all_group_{{ group_index }}_entity_ids" value="{{ item.entity.id }}">
+ {% endfor %}
+ {% endwith %}
+ {% endfor %}
+ {% for item in placement_input.ungrouped_items %}
+ <input type="hidden" name="ungrouped_entity_ids" value="{{ item.entity.id }}">
+ {% endfor %}
+{% endblock %}
+
+{% block action_left %}
+<button type="submit" name="action" value="dismiss"
+ class="btn btn-outline-tertiary">NOT NOW</button>
+{% endblock %}
+
+{% block action_right %}
+<button type="submit" name="action" value="apply" class="btn btn-primary">
+ {% icon "check-circle" size="sm" css_class="hi-icon-left" %}APPLY
+</button>
+{% endblock %}
+
+{% block postamble %}
+</form>
+{% endblock %}
diff --git a/src/hi/integrations/templates/integrations/modals/placement_dismiss.html b/src/hi/integrations/templates/integrations/modals/placement_dismiss.html
new file mode 100644
index 00000000..d11908d1
--- /dev/null
+++ b/src/hi/integrations/templates/integrations/modals/placement_dismiss.html
@@ -0,0 +1,51 @@
+{% extends "modals/action_2_with_cancel.html" %}
+{% load icons %}
+
+{% comment %}
+Confirmation shown when the operator clicks NOT NOW on the
+placement modal. Names the consequences explicitly so the
+operator doesn't dismiss accidentally.
+
+Two paths forward:
+
+* GO BACK navigates to the integration's placement GET endpoint,
+ which renders the placement again seeded with the integration's
+ currently-unplaced entities. (After a fresh sync nothing has
+ been placed yet, so the operator gets back the same set.)
+* OK, PLACE LATER confirms dismissal: page reloads so the
+ background integrations page reflects the newly-imported
+ entities, and the operator can address them later from edit
+ mode.
+
+Context:
+ integration_data : IntegrationData (required)
+ placement_url : str (required) — GO BACK target
+{% endcomment %}
+
+{% block header_class %}bg-secondary{% endblock %}
+
+{% block title_text %}
+Items left unplaced
+{% endblock %}
+
+{% block body %}
+<p>
+ The new items from <strong>{{ integration_data.label }}</strong>
+ are imported but won't appear in any view yet. You can place them
+ in views and collections at any time from edit mode.
+</p>
+{% endblock %}
+
+{% block action_left %}
+<a class="btn btn-outline-tertiary" role="button"
+ href="{{ placement_url }}" data-async="modal">
+ {% icon "chevron-left" size="sm" css_class="hi-icon-left" %}GO BACK
+</a>
+{% endblock %}
+
+{% block action_right %}
+<a id="hi-modal-cancel" role="button"
+ class="btn btn-secondary"
+ href="#"
+ onclick="location.reload(); return false;">OK, PLACE LATER</a>
+{% endblock %}
diff --git a/src/hi/integrations/templates/integrations/modals/post_placement.html b/src/hi/integrations/templates/integrations/modals/post_placement.html
new file mode 100644
index 00000000..c5bcc8df
--- /dev/null
+++ b/src/hi/integrations/templates/integrations/modals/post_placement.html
@@ -0,0 +1,126 @@
+{% extends "modals/action_3.html" %}
+{% load icons %}
+
+{% comment %}
+Post-dispatch summary modal.
+
+Recap of the operator's placement decisions, plus a primary action
+button that lands them on whatever needs follow-up:
+
+* If any placement targeted a LocationView, the primary action is
+ REFINE on the highest-count view (drag entities into spatial
+ position via edit mode).
+* If every placement targeted a Collection, the primary action is
+ REVIEW on the highest-count collection (read-only collection page;
+ collections need no spatial refinement).
+
+Secondary affected targets render as inline links: views go to
+their REFINE URL, collections to their read-only view URL.
+
+Context:
+ integration_data : IntegrationData (required)
+ outcome : PlacementOutcome (required)
+ primary_action : (PlacementSummary, url) | None
+ secondary_action_list : List[(PlacementSummary, url)]
+ is_initial_import : bool (required)
+{% endcomment %}
+
+{% block title_text %}
+{% if is_initial_import %}
+Import complete
+{% else %}
+Refresh complete
+{% endif %}
+{% endblock %}
+
+{% block body %}
+{% if outcome.summaries %}
+<ul class="list-unstyled">
+ {% for summary in outcome.summaries %}
+ <li>
+ <strong>{{ summary.placed_entity_count }}</strong>
+ {% if summary.placed_entity_count == 1 %}item{% else %}items{% endif %}
+ placed in
+ <strong>{{ summary.target_name }}</strong>.
+ </li>
+ {% endfor %}
+</ul>
+{% if outcome.skipped_entity_count > 0 %}
+<p class="text-muted">
+ <strong>{{ outcome.skipped_entity_count }}</strong> left unplaced.
+ You can place them in views or collections later from edit mode.
+</p>
+{% endif %}
+{% if primary_action and primary_action.0.is_view %}
+<p>
+ Imported items start at a default position in each view;
+ use <strong>Refine</strong> to drag them into place.
+</p>
+{% endif %}
+{% else %}
+<p>
+ Nothing was placed. You can place these items in views or
+ collections later from edit mode.
+</p>
+{% endif %}
+
+{% if secondary_action_list %}
+<div class="mt-2 small">
+ Other affected:
+ {% for summary, action_url in secondary_action_list %}
+ <a href="{{ action_url }}" class="badge badge-light ml-1">{{ summary.target_name }}</a>
+ {% endfor %}
+</div>
+{% endif %}
+{% endblock %}
+
+{% comment %}
+ Footer:
+ * Two-button layout when there's a primary REFINE/REVIEW
+ action to offer. Left = DONE (operator finished placing;
+ refinement is optional polish). Right = REFINE/REVIEW on
+ the highest-occupied target.
+ * Single centered OK button when nothing was placed (operator
+ chose 'Don't place' everywhere) — no real action was
+ completed, so OK ('acknowledge info, dismiss') is more
+ accurate than DONE ('action completed'). Centered via the
+ action_3 layout's action_center slot — using a side slot
+ would look skewed compared to other single-button modals
+ across the app.
+
+ Either button reloads the page on dismiss. The modal-to-modal
+ flow that brought the operator here (Configure → pre-sync →
+ result → placement → post-dispatch) never refreshed the
+ underlying integrations page; the entities just imported and
+ placed need to surface there.
+{% endcomment %}
+{% block action_left %}
+{% if primary_action %}
+<a id="hi-modal-cancel" role="button"
+ class="btn btn-outline-tertiary"
+ href="#"
+ onclick="location.reload(); return false;">DONE</a>
+{% endif %}
+{% endblock %}
+
+{% block action_center %}
+{% if not primary_action %}
+<a id="hi-modal-ok" role="button"
+ class="btn btn-primary"
+ href="#"
+ onclick="location.reload(); return false;">OK</a>
+{% endif %}
+{% endblock %}
+
+{% block action_right %}
+{% if primary_action %}
+<a class="btn btn-primary" href="{{ primary_action.1 }}">
+ {% if primary_action.0.is_view %}
+ {% icon "edit" size="sm" css_class="hi-icon-left" %}REFINE
+ {% else %}
+ {% icon "view" size="sm" css_class="hi-icon-left" %}REVIEW
+ {% endif %}
+ {{ primary_action.0.target_name }}
+</a>
+{% endif %}
+{% endblock %}
diff --git a/src/hi/integrations/templates/integrations/modals/pre_sync_confirm.html b/src/hi/integrations/templates/integrations/modals/pre_sync_confirm.html
new file mode 100644
index 00000000..0e050743
--- /dev/null
+++ b/src/hi/integrations/templates/integrations/modals/pre_sync_confirm.html
@@ -0,0 +1,114 @@
+{% extends "modals/action_2_with_cancel.html" %}
+{% load icons %}
+
+{% comment %}
+Pre-sync confirmation modal for integrations.
+
+Shown as the last step of the Configure flow (first-time import) and
+when the operator clicks the IMPORT / REFRESH button on the
+integration manage page (subsequent refreshes). The modal confirms
+intent and explains what the operation will do; it does NOT surface
+integration health. Health is surfaced on the manage page itself, and
+an unhealthy integration's attempt will surface its failure inline
+with a useful error message.
+
+The first-time IMPORT and subsequent REFRESH paths are both rendered
+by this template. They differ in title, lead text, and primary action
+label, controlled by `is_initial_import`. The synchronizer's
+description copy is also import/refresh-aware.
+
+The REVIEW CONFIG action is rendered only on the first-time path: in
+that path the user just came from the Configure modal and may have
+breezed past secondary configuration that the synchronizer's
+description now calls out (e.g., HASS allowlist). REVIEW CONFIG
+re-opens the same Configure modal as a "back one step" affordance;
+saving from there returns to this modal. On the manage-page entry
+path, the user came from the manage page and the inherited CANCEL
+already takes them "back" to it.
+
+Context:
+ integration_data : IntegrationData (required) — for label, id.
+ is_initial_import : bool (required) — True when no entities for
+ this integration have been imported yet
+ (initial IMPORT); False for subsequent
+ REFRESH operations.
+ sync_description : Optional[str] — per-integration text from
+ IntegrationSynchronizer.get_description.
+ sync_url : str (required) — URL the action posts to.
+ review_config_url : str (required) — URL the REVIEW CONFIG
+ action opens (the integrations_enable
+ modal).
+{% endcomment %}
+
+{% comment %}
+First-time path only: override the inherited dismiss-only CANCEL with
+one that triggers a full page reload. Reason: the operator's
+underlying page (typically integrations home) was rendered before the
+integration was enabled and is therefore stale; a plain dismiss would
+leave them on a pre-enable view. On the refresh path the underlying
+page is already current, so we keep the inherited dismiss behavior.
+{% endcomment %}
+
+{% block title_text %}
+{% if is_initial_import %}
+Import from {{ integration_data.label }}?
+{% else %}
+Refresh from {{ integration_data.label }}?
+{% endif %}
+{% endblock %}
+
+{% block body %}
+{% if is_initial_import %}
+<p>
+ Import will pull items from <strong>{{ integration_data.label }}</strong>
+ into Home Information for the first time. Imported items can be
+ placed into your views in the next step.
+</p>
+{% else %}
+<p>
+ Refresh adds new items from <strong>{{ integration_data.label }}</strong>,
+ updates ones that have changed, and removes ones no longer present.
+</p>
+{% endif %}
+
+{% if sync_description %}
+<p class="text-muted">{{ sync_description }}</p>
+{% endif %}
+{% endblock %}
+
+{% block action_left %}
+{% if is_initial_import %}
+<a id="hi-modal-cancel" role="button"
+ class="btn btn-outline-tertiary"
+ href="#"
+ onclick="location.reload(); return false;">
+ {% icon "close" size="lg" css_class="hi-icon-left" %}SKIP
+</a>
+{% else %}
+{{ block.super }}
+{% endif %}
+{% endblock %}
+
+{% block action_center %}
+{% if is_initial_import %}
+<a href="{{ review_config_url }}"
+ role="button"
+ class="btn btn-outline-primary"
+ data-async="modal">
+ {% icon "settings" size="lg" css_class="hi-icon-left" %}REVIEW CONFIG
+</a>
+{% endif %}
+{% endblock %}
+
+{% block action_right %}
+<form action="{{ sync_url }}" method="post" class="form" data-async="modal">
+ {% csrf_token %}
+ <button type="submit" class="btn btn-primary">
+ {% if is_initial_import %}
+ {% icon "upload" size="lg" css_class="hi-icon-left" %}IMPORT
+ {% else %}
+ {% icon "sync" size="lg" css_class="hi-icon-left" %}REFRESH
+ {% endif %}
+ </button>
+</form>
+{% endblock %}
diff --git a/src/hi/integrations/templates/integrations/modals/sync_result.html b/src/hi/integrations/templates/integrations/modals/sync_result.html
new file mode 100644
index 00000000..a94897fd
--- /dev/null
+++ b/src/hi/integrations/templates/integrations/modals/sync_result.html
@@ -0,0 +1,278 @@
+{% extends "modals/action_3.html" %}
+{% load icons %}
+{% load static %}
+
+{% comment %}
+ Integration sync result modal.
+
+ The single end-of-sync surface: always rendered after sync
+ completes, regardless of what changed. Updates and removes are
+ surfaced here in their own right rather than being silently
+ swallowed by an automatic transition to the placement.
+
+ Renders a hero headline, a stat-card row of change counts,
+ color-coded per-category enumerations of affected entities, and
+ collapsible Errors / Details sections. When the sync produced
+ newly-created entities, the footer's primary CTA navigates to
+ the placement modal (via antinode modal-to-modal); otherwise
+ the footer is a single dismissal button.
+
+ The modal title bar keeps the generic HI logo + short generic
+ title ('Import Result' / 'Refresh Result'); the integration's
+ identity is surfaced as a body subtitle row (logo + label) where
+ the white background gives the transparent integration logos
+ predictable contrast.
+
+ Context:
+ sync_result : IntegrationSyncResult (required)
+ integration_data : IntegrationData (required)
+ placement_url : str (optional) — target of the 'Place N items'
+ CTA. Required when sync_result.created_list is
+ non-empty; ignored otherwise.
+{% endcomment %}
+
+{% block modal_dialog_class %}hi-modal-dialog-600{% endblock %}
+
+{% block title_text %}
+{{ sync_result.title }}
+{% endblock %}
+
+{% block body %}
+{% if integration_data %}
+<div class="d-flex align-items-center mb-3 pb-2 border-bottom">
+ <img class="mr-2"
+ style="height: 24px; width: auto;"
+ src="{% static integration_data.integration_metadata.logo_static_path %}"
+ alt="{{ integration_data.label }} Logo">
+ <div class="text-muted small text-uppercase"
+ style="letter-spacing: 0.05em;">
+ {{ integration_data.label }}
+ </div>
+</div>
+{% endif %}
+
+{% comment %}
+ Hero headline — the operator's first read of the modal. Errors
+ take precedence; otherwise the change-count summary speaks.
+ Centered, with a leading status icon at display weight so this
+ zone clearly outranks the detail sections below.
+{% endcomment %}
+{% if sync_result.error_list and not sync_result.has_changes %}
+ <div class="text-center mb-4">
+ <div class="text-danger mb-1" style="font-size: 2.5rem; line-height: 1;">&#x26A0;</div>
+ <h3 class="text-danger mb-1">
+ {% if is_initial_import %}Import failed{% else %}Refresh failed{% endif %}
+ </h3>
+ <div class="text-muted small">
+ {{ sync_result.error_list|length }} error{{ sync_result.error_list|length|pluralize }} — see details below.
+ </div>
+ </div>
+{% elif sync_result.error_list %}
+ <div class="text-center mb-4">
+ <div class="text-warning mb-1" style="font-size: 2.5rem; line-height: 1;">&#x26A0;</div>
+ <h3 class="text-warning mb-1">
+ {% if is_initial_import %}Import completed with errors{% else %}Refresh completed with errors{% endif %}
+ </h3>
+ <div class="text-muted small">
+ {{ sync_result.error_list|length }} error{{ sync_result.error_list|length|pluralize }} — see details below.
+ </div>
+ </div>
+{% elif not sync_result.has_changes %}
+ <div class="text-center mb-4">
+ <div class="text-muted mb-1" style="font-size: 2.5rem; line-height: 1;">&#x2014;</div>
+ <h3 class="text-muted mb-1">
+ {% if is_initial_import %}Nothing to import{% else %}Nothing new{% endif %}
+ </h3>
+ <div class="text-muted small">
+ {% if is_initial_import %}
+ No items found upstream.
+ {% else %}
+ No changes since the last refresh.
+ {% endif %}
+ </div>
+ </div>
+{% else %}
+ <div class="text-center mb-3">
+ <div class="text-success mb-1" style="font-size: 2.5rem; line-height: 1;">&#x2713;</div>
+ <h3 class="text-success mb-1">
+ {% if is_initial_import %}Import complete{% else %}Refresh complete{% endif %}
+ </h3>
+ </div>
+
+ {% comment %}
+ Stat-card row: big number + label per non-zero category.
+ Visually anchors the result so the operator's eye lands on
+ 'what changed and how much' before scanning the per-category
+ item lists. Only non-zero categories render — symmetry is less
+ important than not implying a third stat that doesn't exist.
+ {% endcomment %}
+ <div class="d-flex justify-content-around text-center mb-4 pb-3 border-bottom">
+ {% if sync_result.created_list %}
+ <div class="px-3">
+ <div class="text-success font-weight-bold"
+ style="font-size: 2rem; line-height: 1;">
+ {{ sync_result.created_list|length }}
+ </div>
+ <div class="text-muted small text-uppercase"
+ style="letter-spacing: 0.05em;">Created</div>
+ </div>
+ {% endif %}
+ {% if sync_result.updated_list %}
+ <div class="px-3">
+ <div class="text-info font-weight-bold"
+ style="font-size: 2rem; line-height: 1;">
+ {{ sync_result.updated_list|length }}
+ </div>
+ <div class="text-muted small text-uppercase"
+ style="letter-spacing: 0.05em;">Updated</div>
+ </div>
+ {% endif %}
+ {% if sync_result.removed_list %}
+ <div class="px-3">
+ <div class="text-secondary font-weight-bold"
+ style="font-size: 2rem; line-height: 1;">
+ {{ sync_result.removed_list|length }}
+ </div>
+ <div class="text-muted small text-uppercase"
+ style="letter-spacing: 0.05em;">Removed</div>
+ </div>
+ {% endif %}
+ </div>
+
+ {% comment %}
+ Per-category item enumeration — color-coded left border bars
+ matching the stat colors so the eye links each list back to
+ its stat card. Section header is small/uppercase to subordinate
+ the affordance to the entity names themselves.
+ {% endcomment %}
+ {% if sync_result.removed_list %}
+ <div class="mb-3 pl-3" style="border-left: 3px solid #6c757d;">
+ <div class="small text-secondary text-uppercase mb-1"
+ style="letter-spacing: 0.05em;">
+ Removed ({{ sync_result.removed_list|length }})
+ </div>
+ <ul class="list-unstyled small mb-0"
+ style="max-height: 160px; overflow-y: auto;">
+ {% for name in sync_result.removed_list %}
+ <li>{{ name }}</li>
+ {% endfor %}
+ </ul>
+ </div>
+ {% endif %}
+
+ {% if sync_result.updated_list %}
+ <div class="mb-3 pl-3" style="border-left: 3px solid #17a2b8;">
+ <div class="small text-info text-uppercase mb-1"
+ style="letter-spacing: 0.05em;">
+ Updated ({{ sync_result.updated_list|length }})
+ </div>
+ <ul class="list-unstyled small mb-0"
+ style="max-height: 160px; overflow-y: auto;">
+ {% for name in sync_result.updated_list %}
+ <li>{{ name }}</li>
+ {% endfor %}
+ </ul>
+ </div>
+ {% endif %}
+
+ {% if sync_result.created_list %}
+ <div class="mb-3 pl-3" style="border-left: 3px solid #28a745;">
+ <div class="small text-success text-uppercase mb-1"
+ style="letter-spacing: 0.05em;">
+ Created ({{ sync_result.created_list|length }})
+ </div>
+ <ul class="list-unstyled small mb-0"
+ style="max-height: 160px; overflow-y: auto;">
+ {% for name in sync_result.created_list %}
+ <li>{{ name }}</li>
+ {% endfor %}
+ </ul>
+ </div>
+ {% endif %}
+{% endif %}
+
+{% comment %}
+ Actionable hint (e.g., HASS allowlist) — promoted from muted
+ footer text to a real callout.
+{% endcomment %}
+{% if sync_result.footer_message %}
+ <div class="alert alert-info small mb-3">
+ {{ sync_result.footer_message }}
+ </div>
+{% endif %}
+
+{% comment %}Errors detail — expanded by default when present.{% endcomment %}
+{% if sync_result.error_list %}
+<div class="mb-2 pl-3" style="border-left: 3px solid #dc3545;">
+ <a class="small text-danger text-uppercase" data-toggle="collapse"
+ href="#hi-sync-result-errors" role="button"
+ aria-expanded="true" aria-controls="hi-sync-result-errors"
+ style="letter-spacing: 0.05em;">
+ Errors ({{ sync_result.error_list|length }})
+ </a>
+ <div class="collapse show" id="hi-sync-result-errors">
+ <ul class="list-unstyled small mt-1 mb-0">
+ {% for error_message in sync_result.error_list %}
+ <li class="text-danger">{{ error_message }}</li>
+ {% endfor %}
+ </ul>
+ </div>
+</div>
+{% endif %}
+
+{% comment %}Diagnostic notes — collapsed by default.{% endcomment %}
+{% if sync_result.info_list %}
+<div class="mt-2">
+ <a class="text-muted small" data-toggle="collapse"
+ href="#hi-sync-result-info" role="button"
+ aria-expanded="false" aria-controls="hi-sync-result-info">
+ Show details ({{ sync_result.info_list|length }})
+ </a>
+ <div class="collapse" id="hi-sync-result-info">
+ <ul class="small mt-1 mb-0 text-muted"
+ style="max-height: 200px; overflow-y: auto;">
+ {% for info_message in sync_result.info_list %}
+ <li>{{ info_message }}</li>
+ {% endfor %}
+ </ul>
+ </div>
+</div>
+{% endif %}
+{% endblock %}
+
+{% comment %}
+ Each footer block is declared unconditionally; the {% if %} is
+ inside the block content, not around the {% block %} tag.
+ Django parses block declarations regardless of enclosing if-
+ conditions, so wrapping the declarations would render both
+ branches simultaneously.
+
+ Page-reload onclick on the dismiss buttons: the modal-to-modal
+ flow that lands here never refreshed the underlying integrations
+ page, so a plain dismiss leaves a stale background. Reload makes
+ the background page consistent with anything the sync changed.
+{% endcomment %}
+{% block action_left %}
+{% if sync_result.created_list and placement_url %}
+<a id="hi-modal-cancel" role="button"
+ class="btn btn-outline-tertiary"
+ href="#"
+ onclick="location.reload(); return false;">{% icon "close" size="sm" css_class="hi-icon-left" %}Place Later</a>
+{% endif %}
+{% endblock %}
+
+{% block action_center %}
+{% if not sync_result.created_list or not placement_url %}
+<a id="hi-modal-ok" role="button"
+ class="btn btn-primary"
+ href="#"
+ onclick="location.reload(); return false;">OK</a>
+{% endif %}
+{% endblock %}
+
+{% block action_right %}
+{% if sync_result.created_list and placement_url %}
+<a class="btn btn-primary" role="button"
+ href="{{ placement_url }}" data-async="modal">Place {{ sync_result.created_list|length }} new item{{ sync_result.created_list|length|pluralize }} {% icon "chevron-right" size="sm" css_class="hi-icon-right" %}</a>
+{% endif %}
+{% endblock %}
diff --git a/src/hi/integrations/templates/integrations/pages/integration_manage.html b/src/hi/integrations/templates/integrations/pages/integration_manage.html
index 20b9a864..c3ba544c 100644
--- a/src/hi/integrations/templates/integrations/pages/integration_manage.html
+++ b/src/hi/integrations/templates/integrations/pages/integration_manage.html
@@ -5,11 +5,10 @@
<div id="hi-integration-settings" class="d-flex">
<nav class="nav flex-column hi-vertical-nav">
<div class="hi-vertical-nav-header">
- <h6 class="text-muted mb-2">INTEGRATIONS</h6>
- <a class="btn btn-sm btn-outline-secondary w-100" role="button"
+ <a class="btn btn-outline-primary w-100" role="button"
href="{% url 'integrations_select' %}"
data-async="modal">
- {% icon "settings" size="sm" css_class="hi-icon-left" %}Manage
+ {% icon "settings" size="sm" css_class="hi-icon-left" %}INTEGRATIONS
</a>
</div>
{% for integration_data in core.integration_data_list %}
@@ -34,10 +33,31 @@
<div class="tab-content m-3">
<!-- Root container for this attribute editing context -->
- <div id="{{ attr_item_context.container_html_id }}"
+ <div id="{{ attr_item_context.container_html_id }}"
class="{{ DIVID.ATTR_V2_CONTAINER_CLASS }}" >
-
+
<div class=" border-bottom mb-2 pb-2">
+ {% comment %}
+ Framework-owned manage page header. Title/logo come from
+ integration metadata; lifecycle and sync actions are
+ rendered here unconditionally so individual integrations
+ can't accidentally omit them. The per-integration
+ template below is a content seam for any
+ integration-specific custom UI; for current
+ integrations it is empty.
+ {% endcomment %}
+ <div class="d-flex justify-content-between">
+ <div class="h3 integration-title">
+ <img class="img-fluid"
+ src="{% static core.integration_data.integration_metadata.logo_static_path %}"
+ alt="{{ core.integration_data.integration_metadata.label }} Logo">
+ {{ core.integration_data.integration_metadata.label }}
+ </div>
+ <div class="d-flex align-items-center">
+ {% include "integrations/panes/lifecycle_actions.html" %}
+ {% include "integrations/panes/sync_actions.html" %}
+ </div>
+ </div>
{% include core.manage_view_template_name %}
</div>
diff --git a/src/hi/integrations/templates/integrations/pages/no_integrations.html b/src/hi/integrations/templates/integrations/pages/no_integrations.html
index eaced5c3..b7e12c7c 100644
--- a/src/hi/integrations/templates/integrations/pages/no_integrations.html
+++ b/src/hi/integrations/templates/integrations/pages/no_integrations.html
@@ -7,7 +7,7 @@
<a class="btn btn-primary btn-lg" role="button"
href="{% url 'integrations_select' %}"
data-async="modal">
- MANAGE INTEGRATIONS
+ CONFIGURE INTEGRATIONS
</a>
</div>
{% endblock %}
diff --git a/src/hi/integrations/templates/integrations/panes/integration_edit_content_body.html b/src/hi/integrations/templates/integrations/panes/integration_edit_content_body.html
index 92c49445..f6e455bc 100644
--- a/src/hi/integrations/templates/integrations/panes/integration_edit_content_body.html
+++ b/src/hi/integrations/templates/integrations/panes/integration_edit_content_body.html
@@ -6,11 +6,19 @@
{% block additional_actions %}
{% if show_modal_cancel %}
+{% if is_review_mode %}
+<a role="button" {% if autofocus %}autofocus="autofocus"{% endif %}
+ class="btn btn-outline-tertiary" href="{{ pre_sync_url }}"
+ data-async="modal">
+ CONTINUE {% icon "chevron-right" size="sm" css_class="hi-icon-right" %}
+</a>
+{% else %}
<a id="hi-modal-cancel" role="button" {% if autofocus %}autofocus="autofocus"{% endif %}
class="btn btn-outline-tertiary" href="#" data-dismiss="modal">
{% icon "cancel" size="sm" css_class="hi-icon-left" %}CANCEL
</a>
{% endif %}
+{% endif %}
<!-- Integration Health Status Display -->
{% if health_status %}
diff --git a/src/hi/integrations/templates/integrations/panes/lifecycle_actions.html b/src/hi/integrations/templates/integrations/panes/lifecycle_actions.html
index 4680f6ea..423884ce 100644
--- a/src/hi/integrations/templates/integrations/panes/lifecycle_actions.html
+++ b/src/hi/integrations/templates/integrations/panes/lifecycle_actions.html
@@ -15,12 +15,12 @@
data-async="true">
{% csrf_token %}
{% if core.integration_data.is_paused %}
- <button type="submit" class="btn btn-outline-primary">
- {% icon "play" size="sm" css_class="hi-icon-left" %}RESUME
+ <button type="submit" class="btn btn-primary">
+ {% icon "play" size="lg" css_class="hi-icon-left" %}RESUME
</button>
{% else %}
<button type="submit" class="btn btn-outline-secondary">
- {% icon "pause" size="sm" css_class="hi-icon-left" %}PAUSE
+ {% icon "pause" size="lg" css_class="hi-icon-left" %}PAUSE
</button>
{% endif %}
</form>
diff --git a/src/hi/integrations/templates/integrations/panes/placement_target_options.html b/src/hi/integrations/templates/integrations/panes/placement_target_options.html
new file mode 100644
index 00000000..f6c3127e
--- /dev/null
+++ b/src/hi/integrations/templates/integrations/panes/placement_target_options.html
@@ -0,0 +1,36 @@
+{% comment %}
+Reusable dropdown options for placement target-selects (LocationViews
++ Collections).
+
+Renders LocationViews first as one <optgroup> per Location (ordered
+by Location.order_id, views within by LocationView.order_id), then
+a single 'Collections' <optgroup>. Option values are *tagged* —
+``view:<id>`` or ``collection:<id>`` — so views and collections can
+share the same select element without colliding on numeric ids.
+
+Optionally honors ``selected_view_id`` / ``selected_collection_id``
+(passed via ``include … with …``) by adding the ``selected``
+attribute to the matching option. Used by the placement's top
+dropdown so the smart-default sticks; group/entity dropdowns don't
+pass them.
+
+Context:
+ location_view_groups : List[(Location, List[LocationView])]
+ collection_list : List[Collection]
+ selected_view_id : Optional[int]
+ selected_collection_id : Optional[int]
+{% endcomment %}
+{% for location, views in location_view_groups %}
+<optgroup label="{{ location.name }} (Views)">
+ {% for view in views %}
+ <option value="view:{{ view.id }}"{% if selected_view_id == view.id %} selected{% endif %}>{{ view.name }}</option>
+ {% endfor %}
+</optgroup>
+{% endfor %}
+{% if collection_list %}
+<optgroup label="Collections">
+ {% for collection in collection_list %}
+ <option value="collection:{{ collection.id }}"{% if selected_collection_id == collection.id %} selected{% endif %}>{{ collection.name }}</option>
+ {% endfor %}
+</optgroup>
+{% endif %}
diff --git a/src/hi/integrations/templates/integrations/panes/sync_actions.html b/src/hi/integrations/templates/integrations/panes/sync_actions.html
new file mode 100644
index 00000000..15098313
--- /dev/null
+++ b/src/hi/integrations/templates/integrations/panes/sync_actions.html
@@ -0,0 +1,26 @@
+{% load icons %}
+{% comment %}
+ Shared IMPORT / REFRESH framework action.
+
+ Sync is a framework concern; integrations participate by providing an
+ IntegrationSynchronizer from their gateway's get_synchronizer().
+ Rendering is conditional on (a) the integration being enabled and
+ (b) the gateway returning a synchronizer. Integrations whose gateway
+ returns None (sync is opt-in) get no button.
+
+ Label flips on `core.has_entities`: IMPORT for the first-time path,
+ REFRESH for subsequent re-syncs. The framework manage view computes
+ has_entities into the `core` context.
+{% endcomment %}
+{% if core.integration_data.is_enabled and core.integration_data.integration_gateway.get_synchronizer %}
+<a href="{% url 'integrations_pre_sync' integration_id=core.integration_data.integration_id %}"
+ class="btn {% if core.has_entities %}btn-outline-secondary{% else %}btn-outline-primary{% endif %}"
+ role="button"
+ data-async="modal">
+ {% if core.has_entities %}
+ {% icon "sync" size="lg" css_class="hi-icon-left" %}REFRESH
+ {% else %}
+ {% icon "upload" size="lg" css_class="hi-icon-left" %}IMPORT
+ {% endif %}
+</a>
+{% endif %}
diff --git a/src/hi/integrations/tests/test_entity_operations.py b/src/hi/integrations/tests/test_entity_operations.py
index 285d64ff..d9cce6b0 100644
--- a/src/hi/integrations/tests/test_entity_operations.py
+++ b/src/hi/integrations/tests/test_entity_operations.py
@@ -3,7 +3,8 @@ Unit tests for EntityIntegrationOperations.
Only covers behavior that encodes real classification / transformation /
graph-traversal logic. The preserve_with_user_data path is already tested
-indirectly via test_sync_mixins (which exercises _remove_entity_intelligently).
+indirectly via test_integration_synchronizer (which exercises
+_remove_entity_intelligently).
"""
import logging
diff --git a/src/hi/integrations/tests/test_integration_manager.py b/src/hi/integrations/tests/test_integration_manager.py
index f2cfdd61..f68cb8f1 100644
--- a/src/hi/integrations/tests/test_integration_manager.py
+++ b/src/hi/integrations/tests/test_integration_manager.py
@@ -570,13 +570,15 @@ class IntegrationManagerTestCase(TestCase):
# Call method
manager.ensure_all_attributes_exist(metadata, integration)
-
+
# Verify no new attributes were created
self.assertEqual(integration.attributes.count(), 1)
-
- # Verify existing attribute was not modified
+
+ # Existing attribute keeps the operator's value but the name
+ # is reconciled to the code-side label so future label
+ # renames propagate on next sync.
attr = integration.attributes.first()
- self.assertEqual(attr.name, 'Existing Attribute')
+ self.assertEqual(attr.name, MockIntegrationAttributeType.TEST_ATTR.label)
self.assertEqual(attr.value, 'existing_value')
def test_disable_integration_database_transaction(self):
@@ -1014,7 +1016,68 @@ class IntegrationManagerTestCase(TestCase):
manager._monitor_map['test_integration'] = mock_monitor2
manager._stop_integration_monitor(data)
-
+
# Verify stop was not called on already stopped monitor
mock_monitor2.stop.assert_not_called()
self.assertNotIn('test_integration', manager._monitor_map)
+
+ def test_enable_integration_is_idempotent_and_preserves_pause(self):
+ """Calling enable_integration on an already-enabled integration is a no-op.
+
+ The Review Config flow re-posts the same configure form on an
+ already-enabled integration. Without idempotency the
+ unconditional is_paused=False inside enable_integration would
+ un-pause a paused integration as a side effect of saving its
+ config. This test pins that contract.
+ """
+ manager = IntegrationManager()
+ manager.reset_for_testing()
+
+ integration = Integration.objects.create(
+ integration_id='enable_idempotent_test',
+ is_enabled=True,
+ is_paused=True,
+ )
+ gateway = MockIntegrationGateway('enable_idempotent_test')
+ data = IntegrationData(integration_gateway=gateway, integration=integration)
+
+ with patch.object(manager, '_launch_integration_monitor_task') as mock_launch:
+ with patch.object(manager, 'refresh_integrations_from_db') as mock_refresh:
+ manager.enable_integration(data)
+
+ mock_launch.assert_not_called()
+ mock_refresh.assert_not_called()
+
+ integration.refresh_from_db()
+ self.assertTrue(integration.is_enabled)
+ # The critical assertion: is_paused was NOT clobbered to False.
+ self.assertTrue(integration.is_paused)
+
+ def test_enable_integration_first_time_enables_and_unpauses(self):
+ """First-time enable transitions disabled→enabled and unpauses.
+
+ Regression guard: even after the idempotency change, the
+ first-time-enable path must still flip is_enabled to True,
+ clear is_paused, refresh from db, and launch the monitor.
+ """
+ manager = IntegrationManager()
+ manager.reset_for_testing()
+
+ integration = Integration.objects.create(
+ integration_id='enable_first_time_test',
+ is_enabled=False,
+ is_paused=False,
+ )
+ gateway = MockIntegrationGateway('enable_first_time_test')
+ data = IntegrationData(integration_gateway=gateway, integration=integration)
+
+ with patch.object(manager, '_launch_integration_monitor_task') as mock_launch:
+ with patch.object(manager, 'refresh_integrations_from_db') as mock_refresh:
+ manager.enable_integration(data)
+
+ mock_launch.assert_called_once_with(integration_data=data)
+ mock_refresh.assert_called_once()
+
+ integration.refresh_from_db()
+ self.assertTrue(integration.is_enabled)
+ self.assertFalse(integration.is_paused)
diff --git a/src/hi/integrations/tests/test_sync_mixins.py b/src/hi/integrations/tests/test_integration_synchronizer.py
similarity index 80%
rename from src/hi/integrations/tests/test_sync_mixins.py
rename to src/hi/integrations/tests/test_integration_synchronizer.py
index 8804c639..e2fc0efd 100644
--- a/src/hi/integrations/tests/test_sync_mixins.py
+++ b/src/hi/integrations/tests/test_integration_synchronizer.py
@@ -1,5 +1,5 @@
"""
-Unit tests for IntegrationSyncMixin.
+Unit tests for IntegrationSynchronizer's intelligent entity-removal helper.
"""
import logging
@@ -10,24 +10,33 @@ from hi.apps.attribute.enums import AttributeType
from hi.apps.entity.models import Entity, EntityAttribute, EntityState
from hi.apps.sense.models import Sensor
from hi.apps.control.models import Controller
-from hi.apps.common.processing_result import ProcessingResult
-from hi.integrations.sync_mixins import IntegrationSyncMixin
+from hi.integrations.integration_synchronizer import IntegrationSynchronizer
+from hi.integrations.sync_result import IntegrationSyncResult
logging.disable(logging.CRITICAL)
-class TestSynchronizer(IntegrationSyncMixin):
- """Test class that uses the IntegrationSyncMixin."""
- pass
+class TestSynchronizer(IntegrationSynchronizer):
+ """Concrete IntegrationSynchronizer used to exercise the
+ intelligent-removal helper. Stubs the abstract hooks so the class
+ can be instantiated; sync() itself is not exercised here."""
+ def get_result_title(self, is_initial_import=False):
+ return 'Test Sync Result'
-class IntegrationSyncMixinTestCase(TestCase):
- """Test cases for IntegrationSyncMixin functionality."""
+ def _sync_impl(self, is_initial_import=False):
+ return IntegrationSyncResult(
+ title=self.get_result_title(is_initial_import=is_initial_import),
+ )
+
+
+class IntegrationSynchronizerRemovalTestCase(TestCase):
+ """Test cases for IntegrationSynchronizer's _remove_entity_intelligently."""
def setUp(self):
"""Set up test data."""
self.synchronizer = TestSynchronizer()
- self.result = ProcessingResult(title='Test Import Result')
+ self.result = IntegrationSyncResult(title='Test Import Result')
# Create a test entity
self.entity = Entity.objects.create(
@@ -73,12 +82,12 @@ class IntegrationSyncMixinTestCase(TestCase):
# Entity should be completely deleted
self.assertFalse(Entity.objects.filter(id=entity_id).exists())
-
- # Check result message content and quality
- self.assertEqual(len(self.result.message_list), 1)
- message = self.result.message_list[0]
- self.assertIn('Removed stale TestIntegration entity', message)
- self.assertIn('Test Entity', message) # Should include entity name for debugging
+
+ # Hard delete records the entity name in removed_list and
+ # adds nothing to info_list — the per-category list itself
+ # is what enumerates 'what was removed'.
+ self.assertEqual(self.result.removed_list, ['Test Entity'])
+ self.assertEqual(self.result.info_list, [])
# Verify complete cleanup - no orphaned attributes or states
self.assertEqual(EntityAttribute.objects.filter(entity_id=entity_id).count(), 0)
@@ -160,13 +169,17 @@ class IntegrationSyncMixinTestCase(TestCase):
# Entity state should be deleted (orphaned)
self.assertFalse(EntityState.objects.filter(id=state_id).exists())
- # Check result message content and completeness
- self.assertEqual(len(self.result.message_list), 1)
- message = self.result.message_list[0]
- self.assertIn('Preserved TestIntegration entity', message)
+ # Preservation records the original name in removed_list
+ # (captured before the rename) and surfaces a diagnostic
+ # info note — the operator wants to know an entity was
+ # disconnected and renamed, not just see a name in a list.
+ self.assertEqual(self.result.removed_list, [original_name])
+ self.assertEqual(len(self.result.info_list), 1)
+ message = self.result.info_list[0]
+ self.assertIn('Preserved TestIntegration item', message)
self.assertIn('disconnected from integration', message)
- self.assertIn(original_name, message) # Should reference original name
- self.assertIn('[Disconnected]', message) # Should show new name
+ self.assertIn(original_name, message)
+ self.assertIn('[Disconnected]', message)
# Verify integration payload is cleared
self.entity.refresh_from_db()
@@ -340,12 +353,9 @@ class IntegrationSyncMixinTestCase(TestCase):
self.entity, self.result, 'TestIntegration'
)
- # Entity should be completely deleted
+ # Entity should be completely deleted; name recorded.
self.assertFalse(Entity.objects.filter(id=entity_id).exists())
-
- # Verify message indicates successful deletion
- self.assertEqual(len(self.result.message_list), 1)
- self.assertIn('Removed stale TestIntegration entity', self.result.message_list[0])
+ self.assertEqual(self.result.removed_list, ['Test Entity'])
def test_entity_with_integration_payload_preservation(self):
"""Test that integration_payload is preserved during entity preservation."""
@@ -585,19 +595,18 @@ class IntegrationSyncMixinTestCase(TestCase):
self.assertFalse(Controller.objects.filter(id__in=component_ids).exists())
self.assertFalse(EntityAttribute.objects.filter(id__in=attribute_ids).exists())
- # Verify message indicates successful deletion
- self.assertEqual(len(self.result.message_list), 1)
- message = self.result.message_list[0]
- self.assertIn('Removed stale TestIntegration entity', message)
- self.assertIn('Test Entity', message)
+ # Hard delete records the name in removed_list; no
+ # narrative info entry.
+ self.assertEqual(self.result.removed_list, ['Test Entity'])
+ self.assertEqual(self.result.info_list, [])
- def test_result_message_accumulation(self):
- """Test that ProcessingResult properly accumulates messages from multiple operations."""
- # Add some initial messages to result
- self.result.message_list.append('Initial message')
- self.result.message_list.append('Another message')
-
- # Create user data to trigger preservation
+ def test_result_info_list_accumulation(self):
+ """Pre-existing info_list entries are preserved when the
+ preservation path appends its diagnostic note."""
+ self.result.info_list.append('Initial message')
+ self.result.info_list.append('Another message')
+
+ # Create user data to trigger preservation.
EntityAttribute.objects.create(
entity=self.entity,
name='User Note',
@@ -605,25 +614,22 @@ class IntegrationSyncMixinTestCase(TestCase):
value_type_str='TEXT',
attribute_type_str=str(AttributeType.CUSTOM)
)
-
- # Call the method
+
self.synchronizer._remove_entity_intelligently(
self.entity, self.result, 'TestIntegration'
)
-
- # Should have 3 messages total (2 existing + 1 new)
- self.assertEqual(len(self.result.message_list), 3)
-
- # New message should be last
- self.assertIn('Preserved TestIntegration entity', self.result.message_list[2])
-
- # Original messages should be preserved
- self.assertEqual(self.result.message_list[0], 'Initial message')
- self.assertEqual(self.result.message_list[1], 'Another message')
+
+ # 3 entries: 2 pre-existing + 1 preservation note.
+ self.assertEqual(len(self.result.info_list), 3)
+ self.assertIn('Preserved TestIntegration item', self.result.info_list[2])
+ self.assertEqual(self.result.info_list[0], 'Initial message')
+ self.assertEqual(self.result.info_list[1], 'Another message')
+ # And removed_list captured the name exactly once.
+ self.assertEqual(self.result.removed_list, ['Test Entity'])
-class IntegrationSyncMixinTransactionTestCase(TransactionTestCase):
- """Transaction-specific tests for IntegrationSyncMixin."""
+class IntegrationSynchronizerRemovalTransactionTestCase(TransactionTestCase):
+ """Transaction-specific tests for _remove_entity_intelligently."""
def setUp(self):
"""Set up test data."""
@@ -633,7 +639,7 @@ class IntegrationSyncMixinTransactionTestCase(TransactionTestCase):
initializer.run(sender=None)
self.synchronizer = TestSynchronizer()
- self.result = ProcessingResult(title='Test Import Result')
+ self.result = IntegrationSyncResult(title='Test Import Result')
# Create a test entity
self.entity = Entity.objects.create(
@@ -742,12 +748,14 @@ class IntegrationSyncMixinTransactionTestCase(TransactionTestCase):
self.assertEqual(remaining_attributes.count(), 1)
self.assertEqual(remaining_attributes.first().name, 'User Note')
- # Verify operation was logged
- self.assertEqual(len(self.result.message_list), 1)
- message = self.result.message_list[0]
- self.assertIn('Preserved TestIntegration entity', message)
+ # Preservation diagnostic surfaces in info_list; the
+ # original (pre-rename) name is captured in removed_list.
+ self.assertEqual(len(self.result.info_list), 1)
+ message = self.result.info_list[0]
+ self.assertIn('Preserved TestIntegration item', message)
self.assertIn('disconnected from integration', message)
-
+ self.assertEqual(self.result.removed_list, ['Test Entity'])
+
def test_preservation_with_database_constraint_validation(self):
"""Test that preservation operations respect database constraints and maintain referential integrity."""
# Create user attribute to trigger preservation
@@ -821,10 +829,10 @@ class IntegrationSyncMixinTransactionTestCase(TransactionTestCase):
self.assertTrue(Sensor.objects.filter(id=user_sensor.id).exists())
self.assertTrue(EntityAttribute.objects.filter(id=user_attr.id).exists())
- # Verify message was added
- self.assertEqual(len(self.result.message_list), 1)
- self.assertIn('Preserved TestIntegration entity', self.result.message_list[0])
-
+ # Preservation note surfaces in info_list.
+ self.assertEqual(len(self.result.info_list), 1)
+ self.assertIn('Preserved TestIntegration item', self.result.info_list[0])
+
# Verify database integrity: remaining state has valid relationships
remaining_state = EntityState.objects.get(id=second_state_id)
remaining_sensors = remaining_state.sensors.all()
@@ -1041,7 +1049,7 @@ class IntegrationSyncMixinTransactionTestCase(TransactionTestCase):
)
# Create fresh result for each test
- test_result = ProcessingResult(title='Test Result')
+ test_result = IntegrationSyncResult(title='Test Result')
# Execute preservation
self.synchronizer._remove_entity_intelligently(
@@ -1056,6 +1064,148 @@ class IntegrationSyncMixinTransactionTestCase(TransactionTestCase):
self.assertIsNone(entity.integration_id)
self.assertIsNone(entity.integration_name)
- # Verify result message was added
- self.assertEqual(len(test_result.message_list), 1)
- self.assertIn('Preserved TestIntegration entity', test_result.message_list[0])
+ # Preservation note surfaces in info_list.
+ self.assertEqual(len(test_result.info_list), 1)
+ self.assertIn('Preserved TestIntegration item', test_result.info_list[0])
+
+
+
+class IntegrationSynchronizerOrphanDelegateTestCase(TestCase):
+ """Refresh-time entity removal must clean up delegate entities
+ (e.g., the Area auto-created when a camera/motion-detector was
+ placed in a view) that become orphaned by the removal — the same
+ closure the integration-disable path uses."""
+
+ def setUp(self):
+ from hi.apps.entity.models import EntityStateDelegation
+
+ self.synchronizer = TestSynchronizer()
+ self.result = IntegrationSyncResult(title='Test')
+ self.EntityStateDelegation = EntityStateDelegation
+
+ # Camera entity (integration-owned).
+ self.camera = Entity.objects.create(
+ name='Cam 1',
+ entity_type_str='CAMERA',
+ integration_id='test_integration',
+ integration_name='cam_1',
+ )
+ self.camera_state = EntityState.objects.create(
+ entity=self.camera,
+ entity_state_type_str='MOVEMENT',
+ name='Motion',
+ )
+
+ # Area entity (delegate, Hi-side, no integration_id).
+ self.area = Entity.objects.create(
+ name='Cam 1 Area',
+ entity_type_str='AREA',
+ )
+ self.EntityStateDelegation.objects.create(
+ entity_state=self.camera_state,
+ delegate_entity=self.area,
+ )
+
+ def test_orphan_delegate_area_is_deleted_when_only_principal_removed(self):
+ """Camera removed → Area has no remaining principal → Area
+ is part of the closure and gets deleted."""
+ camera_id = self.camera.id
+ area_id = self.area.id
+
+ self.synchronizer._remove_entity_intelligently(
+ self.camera, self.result, 'TestIntegration',
+ )
+
+ self.assertFalse(Entity.objects.filter(id=camera_id).exists())
+ self.assertFalse(Entity.objects.filter(id=area_id).exists())
+ # Both names surface in the result's removed_list.
+ self.assertIn('Cam 1', self.result.removed_list)
+ self.assertIn('Cam 1 Area', self.result.removed_list)
+
+ def test_shared_delegate_area_survives_when_other_principals_remain(self):
+ """Camera A removed; Area still serves Camera B → Area stays."""
+ camera_b = Entity.objects.create(
+ name='Cam 2',
+ entity_type_str='CAMERA',
+ integration_id='test_integration',
+ integration_name='cam_2',
+ )
+ camera_b_state = EntityState.objects.create(
+ entity=camera_b,
+ entity_state_type_str='MOVEMENT',
+ name='Motion',
+ )
+ # Area also delegates from Camera B's state — shared delegate.
+ self.EntityStateDelegation.objects.create(
+ entity_state=camera_b_state,
+ delegate_entity=self.area,
+ )
+
+ camera_id = self.camera.id
+ area_id = self.area.id
+
+ self.synchronizer._remove_entity_intelligently(
+ self.camera, self.result, 'TestIntegration',
+ )
+
+ self.assertFalse(Entity.objects.filter(id=camera_id).exists())
+ # Area must remain — Camera B still uses it.
+ self.assertTrue(Entity.objects.filter(id=area_id).exists())
+ # Result reports only Cam 1's removal.
+ self.assertEqual(self.result.removed_list, ['Cam 1'])
+
+ def test_orphan_delegate_with_user_data_is_preserved_not_deleted(self):
+ """Operator added a custom attribute to the auto-created
+ Area → Area is preserved (disconnected/renamed) rather than
+ hard-deleted, even though it became an orphan."""
+ EntityAttribute.objects.create(
+ entity=self.area,
+ name='Floor Plan Note',
+ value='Has skylight on east side',
+ value_type_str='TEXT',
+ attribute_type_str=str(AttributeType.CUSTOM),
+ )
+
+ camera_id = self.camera.id
+ area_id = self.area.id
+
+ self.synchronizer._remove_entity_intelligently(
+ self.camera, self.result, 'TestIntegration',
+ )
+
+ self.assertFalse(Entity.objects.filter(id=camera_id).exists())
+ # Area persists with operator-added data.
+ self.assertTrue(Entity.objects.filter(id=area_id).exists())
+ self.area.refresh_from_db()
+ self.assertTrue(self.area.name.startswith('[Disconnected]'))
+
+ def test_orphan_delegate_deleted_when_only_principal_has_user_data(self):
+ """Camera carries user data so it is preserved (kept as
+ [Disconnected]); Area carries none. Even though the
+ principal survives in name, the Area is correctly hard-
+ deleted — see the rationale documented on
+ ``EntityIntegrationOperations.remove_entities_with_closure``.
+ Pinning this case prevents a well-intentioned future
+ refactor from flipping it back to preservation."""
+ EntityAttribute.objects.create(
+ entity=self.camera,
+ name='Lens Notes',
+ value='Wide-angle, dome housing',
+ value_type_str='TEXT',
+ attribute_type_str=str(AttributeType.CUSTOM),
+ )
+
+ camera_id = self.camera.id
+ area_id = self.area.id
+
+ self.synchronizer._remove_entity_intelligently(
+ self.camera, self.result, 'TestIntegration',
+ )
+
+ # Camera kept with [Disconnected] rename (user data).
+ self.assertTrue(Entity.objects.filter(id=camera_id).exists())
+ self.camera.refresh_from_db()
+ self.assertTrue(self.camera.name.startswith('[Disconnected]'))
+ # Area is gone — its display purpose is negated once the
+ # principal's integration-derived state is removed.
+ self.assertFalse(Entity.objects.filter(id=area_id).exists())
diff --git a/src/hi/integrations/tests/test_placement_form.py b/src/hi/integrations/tests/test_placement_form.py
new file mode 100644
index 00000000..7db55c88
--- /dev/null
+++ b/src/hi/integrations/tests/test_placement_form.py
@@ -0,0 +1,274 @@
+"""
+Tests for PlacementFormParser.
+
+Three-level inheritance (top → group → entity) and skip / new-view
+sentinel resolution. Drives the parser directly with a request
+factory; doesn't touch the placement view or modal rendering.
+"""
+import logging
+
+from django.http import QueryDict
+from django.test import TestCase
+
+from hi.apps.entity.enums import EntityType
+from hi.apps.entity.models import Entity
+from hi.apps.location.models import Location, LocationView
+from hi.integrations.placement_request import PlacementFormParser
+
+logging.disable(logging.CRITICAL)
+
+
+class _FakeIntegrationData:
+ """Stand-in carrying the only field PlacementFormParser reads."""
+ def __init__(self, label):
+ self.label = label
+ self.integration_id = 'parser_test'
+
+
+class _RequestStub:
+ """Minimal request-like with a POST QueryDict."""
+ def __init__(self, post):
+ self.POST = post
+
+ @property
+ def view_parameters(self):
+ # _create_new_view paths through LocationManager() which
+ # doesn't touch view_parameters in its create_location_view
+ # branch, but get_default_location does. Tests that exercise
+ # the new-view path stub get_default_location instead.
+ raise AttributeError('view_parameters not available in stub')
+
+
+class PlacementFormParserTests(TestCase):
+
+ def setUp(self):
+ self.location = Location.objects.create(
+ name='Test', svg_view_box_str='0 0 100 100',
+ )
+ self.view_a = LocationView.objects.create(
+ location=self.location, name='Kitchen', order_id=1,
+ svg_view_box_str='0 0 100 100', svg_rotate=0,
+ svg_style_name_str='COLOR', location_view_type_str='DEFAULT',
+ )
+ self.view_b = LocationView.objects.create(
+ location=self.location, name='Living Room', order_id=2,
+ svg_view_box_str='0 0 100 100', svg_rotate=0,
+ svg_style_name_str='COLOR', location_view_type_str='DEFAULT',
+ )
+ self.entity_a = Entity.objects.create(
+ name='Cam 1', entity_type_str=str(EntityType.CAMERA),
+ integration_id='parser_test', integration_name='cam_1',
+ )
+ self.entity_b = Entity.objects.create(
+ name='Cam 2', entity_type_str=str(EntityType.CAMERA),
+ integration_id='parser_test', integration_name='cam_2',
+ )
+ self.ungrouped_entity = Entity.objects.create(
+ name='Thing', entity_type_str=str(EntityType.OTHER),
+ integration_id='parser_test', integration_name='thing_1',
+ )
+ self.integration_data = _FakeIntegrationData(label='Parser Test')
+
+ def _post(self, **fields):
+ qd = QueryDict(mutable=True)
+ for key, value in fields.items():
+ if isinstance(value, list):
+ qd.setlist(key, value)
+ else:
+ qd[key] = value
+ return _RequestStub(post=qd)
+
+ def test_top_inherits_to_groups_and_entities(self):
+ request = self._post(
+ top_view=f'view:{self.view_a.id}',
+ all_group_0_entity_ids=[str(self.entity_a.id), str(self.entity_b.id)],
+ )
+ decisions = PlacementFormParser.parse(
+ request=request, integration_data=self.integration_data,
+ )
+ self.assertEqual(len(decisions), 2)
+ for d in decisions:
+ self.assertEqual(d.location_view, self.view_a)
+
+ def test_group_overrides_top(self):
+ request = self._post(**{
+ 'top_view': f'view:{self.view_a.id}',
+ 'all_group_0_entity_ids': [str(self.entity_a.id)],
+ 'group_view_0': f'view:{self.view_b.id}',
+ })
+ decisions = PlacementFormParser.parse(
+ request=request, integration_data=self.integration_data,
+ )
+ self.assertEqual(decisions[0].location_view, self.view_b)
+
+ def test_entity_overrides_group(self):
+ request = self._post(**{
+ 'top_view': f'view:{self.view_a.id}',
+ 'all_group_0_entity_ids': [str(self.entity_a.id), str(self.entity_b.id)],
+ 'group_view_0': f'view:{self.view_a.id}',
+ f'group_0_entity_{self.entity_b.id}_view': f'view:{self.view_b.id}',
+ })
+ decisions = PlacementFormParser.parse(
+ request=request, integration_data=self.integration_data,
+ )
+ by_entity = {d.entity.id: d.location_view for d in decisions}
+ self.assertEqual(by_entity[self.entity_a.id], self.view_a)
+ self.assertEqual(by_entity[self.entity_b.id], self.view_b)
+
+ def test_explicit_skip_at_group_overrides_top(self):
+ request = self._post(**{
+ 'top_view': f'view:{self.view_a.id}',
+ 'all_group_0_entity_ids': [str(self.entity_a.id)],
+ 'group_view_0': '__skip__',
+ })
+ decisions = PlacementFormParser.parse(
+ request=request, integration_data=self.integration_data,
+ )
+ self.assertIsNone(decisions[0].location_view)
+
+ def test_explicit_skip_at_entity_overrides_group(self):
+ request = self._post(**{
+ 'top_view': f'view:{self.view_a.id}',
+ 'all_group_0_entity_ids': [str(self.entity_a.id), str(self.entity_b.id)],
+ f'group_0_entity_{self.entity_a.id}_view': '__skip__',
+ })
+ decisions = PlacementFormParser.parse(
+ request=request, integration_data=self.integration_data,
+ )
+ by_entity = {d.entity.id: d.location_view for d in decisions}
+ self.assertIsNone(by_entity[self.entity_a.id])
+ self.assertEqual(by_entity[self.entity_b.id], self.view_a)
+
+ def test_skip_all_at_top(self):
+ request = self._post(
+ top_view='',
+ all_group_0_entity_ids=[str(self.entity_a.id)],
+ )
+ decisions = PlacementFormParser.parse(
+ request=request, integration_data=self.integration_data,
+ )
+ self.assertIsNone(decisions[0].location_view)
+
+ def test_ungrouped_inherits_from_top(self):
+ request = self._post(
+ top_view=f'view:{self.view_a.id}',
+ ungrouped_entity_ids=[str(self.ungrouped_entity.id)],
+ )
+ decisions = PlacementFormParser.parse(
+ request=request, integration_data=self.integration_data,
+ )
+ self.assertEqual(decisions[0].entity, self.ungrouped_entity)
+ self.assertEqual(decisions[0].location_view, self.view_a)
+
+ def test_ungrouped_entity_override_wins(self):
+ request = self._post(**{
+ 'top_view': f'view:{self.view_a.id}',
+ 'ungrouped_entity_ids': [str(self.ungrouped_entity.id)],
+ f'ungrouped_entity_{self.ungrouped_entity.id}_view': f'view:{self.view_b.id}',
+ })
+ decisions = PlacementFormParser.parse(
+ request=request, integration_data=self.integration_data,
+ )
+ self.assertEqual(decisions[0].location_view, self.view_b)
+
+ def test_collection_target_via_top(self):
+ """Top dropdown's existing-collection option routes inherited
+ entities to that Collection, not a LocationView."""
+ from hi.apps.collection.enums import CollectionType, CollectionViewType
+ from hi.apps.collection.models import Collection
+ collection = Collection(
+ name='Tools', order_id=0,
+ )
+ collection.collection_type = CollectionType.default()
+ collection.collection_view_type = CollectionViewType.default()
+ collection.save()
+
+ request = self._post(
+ top_view=f'collection:{collection.id}',
+ all_group_0_entity_ids=[str(self.entity_a.id)],
+ )
+ decisions = PlacementFormParser.parse(
+ request=request, integration_data=self.integration_data,
+ )
+ self.assertIsNone(decisions[0].location_view)
+ self.assertEqual(decisions[0].collection, collection)
+
+ def test_mixed_view_and_collection_targets(self):
+ """One group routes to a LocationView; another routes to a
+ Collection — both targets coexist in the same submission."""
+ from hi.apps.collection.enums import CollectionType, CollectionViewType
+ from hi.apps.collection.models import Collection
+ collection = Collection(name='Tools', order_id=0)
+ collection.collection_type = CollectionType.default()
+ collection.collection_view_type = CollectionViewType.default()
+ collection.save()
+
+ request = self._post(**{
+ 'top_view': '',
+ 'all_group_0_entity_ids': [str(self.entity_a.id)],
+ 'group_view_0': f'view:{self.view_a.id}',
+ 'all_group_1_entity_ids': [str(self.entity_b.id)],
+ 'group_view_1': f'collection:{collection.id}',
+ })
+ decisions = PlacementFormParser.parse(
+ request=request, integration_data=self.integration_data,
+ )
+ by_entity = {d.entity.id: d for d in decisions}
+ self.assertEqual(by_entity[self.entity_a.id].location_view, self.view_a)
+ self.assertIsNone(by_entity[self.entity_a.id].collection)
+ self.assertEqual(by_entity[self.entity_b.id].collection, collection)
+ self.assertIsNone(by_entity[self.entity_b.id].location_view)
+
+ def test_new_collection_creates_collection_and_inherits_to_entities(self):
+ """top='__new_collection__' creates a fresh Collection named
+ after the integration label; entities inherit that target."""
+ from hi.apps.collection.models import Collection
+ before_ids = set(Collection.objects.values_list('id', flat=True))
+ request = self._post(
+ top_view='__new_collection__',
+ all_group_0_entity_ids=[str(self.entity_a.id)],
+ )
+ decisions = PlacementFormParser.parse(
+ request=request, integration_data=self.integration_data,
+ )
+ new_ids = (
+ set(Collection.objects.values_list('id', flat=True)) - before_ids
+ )
+ self.assertEqual(len(new_ids), 1)
+ new_collection = Collection.objects.get(id=new_ids.pop())
+ self.assertEqual(new_collection.name, 'Parser Test')
+ self.assertEqual(decisions[0].collection, new_collection)
+ self.assertIsNone(decisions[0].location_view)
+
+ def test_new_view_creates_view_and_inherits_to_entities(self):
+ from unittest.mock import patch
+ request = self._post(
+ top_view='__new_view__',
+ all_group_0_entity_ids=[str(self.entity_a.id)],
+ )
+ # _create_new_view ultimately calls
+ # LocationManager().get_default_location(request) → must be
+ # patched because the request stub doesn't carry session
+ # state. The patched return is the test's existing Location;
+ # the parser then creates a real LocationView attached to it.
+ with patch(
+ 'hi.integrations.placement_request.LocationManager',
+ ) as mock_manager_cls:
+ instance = mock_manager_cls.return_value
+ instance.get_default_location.return_value = self.location
+ new_view = LocationView.objects.create(
+ location=self.location, name='Parser Test', order_id=99,
+ svg_view_box_str='0 0 100 100', svg_rotate=0,
+ svg_style_name_str='COLOR', location_view_type_str='DEFAULT',
+ )
+ instance.create_location_view.return_value = new_view
+
+ decisions = PlacementFormParser.parse(
+ request=request, integration_data=self.integration_data,
+ )
+
+ self.assertEqual(decisions[0].location_view, new_view)
+ # The factory was called with the integration label.
+ instance.create_location_view.assert_called_once_with(
+ location=self.location, name='Parser Test',
+ )
diff --git a/src/hi/integrations/tests/test_placement_request.py b/src/hi/integrations/tests/test_placement_request.py
new file mode 100644
index 00000000..d1fac3c4
--- /dev/null
+++ b/src/hi/integrations/tests/test_placement_request.py
@@ -0,0 +1,152 @@
+"""
+Direct unit tests for ``PlacementUrlParams``.
+
+The class is the single source of truth for the placement view's
+URL/form-param contract — key names, value encodings, list
+separators, parser. Most behaviors are exercised indirectly through
+view tests, but pinning the class directly catches contract drift
+(e.g., a key rename, an encoding change, a sloppy parser fix) before
+it cascades into hard-to-trace view-level test failures.
+"""
+import logging
+
+from django.core.exceptions import BadRequest
+from django.http import QueryDict
+from django.test import SimpleTestCase
+
+from hi.integrations.placement_request import PlacementUrlParams
+
+logging.disable(logging.CRITICAL)
+
+
+class PlacementUrlParamsToQueryDictTests(SimpleTestCase):
+
+ def test_defaults_produce_empty_dict(self):
+ """Sparse encoding: a default-constructed params object
+ contributes no query keys. Keeps URLs free of redundant
+ ``?is_initial_import=0`` cruft."""
+ params = PlacementUrlParams()
+ self.assertEqual(params.to_query_dict(), {})
+
+ def test_is_initial_import_only_emits_its_key(self):
+ params = PlacementUrlParams(is_initial_import=True)
+ self.assertEqual(
+ params.to_query_dict(),
+ {PlacementUrlParams.KEY_IS_INITIAL_IMPORT: PlacementUrlParams.TRUE_VALUE},
+ )
+
+ def test_entity_ids_only_emits_its_key(self):
+ params = PlacementUrlParams(entity_ids=[1, 2, 3])
+ self.assertEqual(
+ params.to_query_dict(),
+ {PlacementUrlParams.KEY_ENTITY_IDS: '1,2,3'},
+ )
+
+ def test_both_fields_populated(self):
+ params = PlacementUrlParams(is_initial_import=True, entity_ids=[7, 8])
+ self.assertEqual(
+ params.to_query_dict(),
+ {
+ PlacementUrlParams.KEY_IS_INITIAL_IMPORT: PlacementUrlParams.TRUE_VALUE,
+ PlacementUrlParams.KEY_ENTITY_IDS: '7,8',
+ },
+ )
+
+
+class PlacementUrlParamsAppendToUrlTests(SimpleTestCase):
+
+ def test_default_params_append_no_query_string(self):
+ params = PlacementUrlParams()
+ self.assertEqual(
+ params.append_to_url('/placement/test'),
+ '/placement/test',
+ )
+
+ def test_populated_params_append_url_encoded_query(self):
+ """Goes through ``django.utils.http.urlencode`` so the
+ comma in ``entity_ids`` is encoded to %2C — protects against
+ any future field whose value contains URL-reserved chars."""
+ params = PlacementUrlParams(is_initial_import=True, entity_ids=[1, 2])
+ url = params.append_to_url('/placement/test')
+ self.assertTrue(url.startswith('/placement/test?'))
+ self.assertIn('is_initial_import=1', url)
+ # Comma is URL-encoded by urlencode.
+ self.assertIn('entity_ids=1%2C2', url)
+
+
+class PlacementUrlParamsFromDataTests(SimpleTestCase):
+
+ def test_empty_data_returns_default_params(self):
+ result = PlacementUrlParams.from_data(QueryDict(''))
+ self.assertEqual(result, PlacementUrlParams())
+
+ def test_round_trip_preserves_values(self):
+ """The contract guarantee: ``to_query_dict`` →
+ ``QueryDict`` → ``from_data`` reconstructs an equivalent
+ params object. Any encoder/decoder asymmetry breaks this."""
+ original = PlacementUrlParams(is_initial_import=True, entity_ids=[3, 1, 4])
+ qd = QueryDict(mutable=True)
+ for k, v in original.to_query_dict().items():
+ qd[k] = v
+ roundtripped = PlacementUrlParams.from_data(qd)
+ self.assertEqual(original, roundtripped)
+
+ def test_is_initial_import_accepts_robust_truthy_spellings(self):
+ """``str_to_bool`` accepts '1', 'true', 'yes', etc. so a
+ hand-crafted URL or a future encoding change on the producer
+ side doesn't silently parse as False."""
+ for truthy in ('1', 'true', 'TRUE', 'yes', 'on'):
+ with self.subTest(value=truthy):
+ qd = QueryDict(f'is_initial_import={truthy}')
+ self.assertTrue(PlacementUrlParams.from_data(qd).is_initial_import)
+
+ def test_is_initial_import_falsy_values(self):
+ """Anything not-truthy parses as False, including the
+ canonical FALSE_VALUE encoding and absence."""
+ for falsy in ('0', 'false', 'no', '', 'garbage'):
+ with self.subTest(value=falsy):
+ qd = QueryDict(f'is_initial_import={falsy}')
+ self.assertFalse(PlacementUrlParams.from_data(qd).is_initial_import)
+
+ def test_entity_ids_parses_comma_separated_integers(self):
+ qd = QueryDict('entity_ids=10,20,30')
+ result = PlacementUrlParams.from_data(qd)
+ self.assertEqual(result.entity_ids, [10, 20, 30])
+
+ def test_entity_ids_tolerates_whitespace_around_tokens(self):
+ """The parser uses ``int(piece)`` which strips its own
+ whitespace. Defensive — guards against a producer that
+ accidentally introduces spaces."""
+ qd = QueryDict('entity_ids=10, 20 ,30')
+ result = PlacementUrlParams.from_data(qd)
+ self.assertEqual(result.entity_ids, [10, 20, 30])
+
+ def test_entity_ids_malformed_raises_bad_request(self):
+ """Tampered input fails loudly rather than silently
+ widening scope (e.g., dropping the unparseable id and
+ proceeding with a partial set)."""
+ qd = QueryDict('entity_ids=1,abc,3')
+ with self.assertRaises(BadRequest):
+ PlacementUrlParams.from_data(qd)
+
+ def test_entity_ids_absent_returns_empty_list(self):
+ qd = QueryDict('is_initial_import=1')
+ result = PlacementUrlParams.from_data(qd)
+ self.assertEqual(result.entity_ids, [])
+
+
+class PlacementUrlParamsFormValueTests(SimpleTestCase):
+
+ def test_is_initial_import_form_value_true_returns_true_value(self):
+ params = PlacementUrlParams(is_initial_import=True)
+ self.assertEqual(
+ params.is_initial_import_form_value(),
+ PlacementUrlParams.TRUE_VALUE,
+ )
+
+ def test_is_initial_import_form_value_false_returns_false_value(self):
+ params = PlacementUrlParams(is_initial_import=False)
+ self.assertEqual(
+ params.is_initial_import_form_value(),
+ PlacementUrlParams.FALSE_VALUE,
+ )
diff --git a/src/hi/integrations/tests/test_sync_result.py b/src/hi/integrations/tests/test_sync_result.py
new file mode 100644
index 00000000..bd15905f
--- /dev/null
+++ b/src/hi/integrations/tests/test_sync_result.py
@@ -0,0 +1,117 @@
+"""
+Tests for the IntegrationSyncResult shape.
+
+Sync-vocabulary fields: title, per-category name lists
+(created_list / updated_list / removed_list), info_list /
+error_list / footer_message, plus the optional placement_input
+that bridges to the placement modal when the sync produced new
+entities to place.
+
+Tests for the EntityPlacementInput / EntityPlacementItem /
+EntityPlacementGroup data shapes themselves live in
+hi/apps/entity/tests/test_entity_placement.py.
+"""
+import logging
+
+from django.test import SimpleTestCase
+
+from hi.apps.entity.entity_placement import (
+ EntityPlacementGroup,
+ EntityPlacementInput,
+ EntityPlacementItem,
+)
+from hi.integrations.sync_result import IntegrationSyncResult
+
+logging.disable(logging.CRITICAL)
+
+
+class _FakeEntity:
+ """Stand-in for Entity used in shape tests; we never persist."""
+ def __init__(self, name):
+ self.name = name
+
+
+class IntegrationSyncResultTests(SimpleTestCase):
+
+ def test_default_collections_are_independent(self):
+ """Default-factory lists must not be shared across instances.
+
+ Regression guard for the standard mutable-default-arg trap;
+ important because synchronizers append into these lists.
+ """
+ a = IntegrationSyncResult(title='A')
+ b = IntegrationSyncResult(title='B')
+
+ a.info_list.append('msg-a')
+ a.error_list.append('err-a')
+
+ self.assertEqual(b.info_list, [])
+ self.assertEqual(b.error_list, [])
+
+ def test_field_shape(self):
+ """title / per-category lists / info_list / error_list /
+ footer_message round-trip cleanly. Counts in the modal are
+ derived from list lengths, so the lists are the source of
+ truth."""
+ result = IntegrationSyncResult(
+ title='Sync Done',
+ created_list=['New A', 'New B', 'New C'],
+ updated_list=['Existing X', 'Existing Y'],
+ removed_list=['Stale Z'],
+ info_list=['Found 50 upstream items'],
+ error_list=['warning x'],
+ footer_message='see settings',
+ )
+ self.assertEqual(result.title, 'Sync Done')
+ self.assertEqual(result.created_list, ['New A', 'New B', 'New C'])
+ self.assertEqual(result.updated_list, ['Existing X', 'Existing Y'])
+ self.assertEqual(result.removed_list, ['Stale Z'])
+ self.assertEqual(result.info_list, ['Found 50 upstream items'])
+ self.assertEqual(result.error_list, ['warning x'])
+ self.assertEqual(result.footer_message, 'see settings')
+
+ def test_has_changes_true_when_any_list_nonempty(self):
+ for kwargs in (
+ {'created_list': ['a']},
+ {'updated_list': ['a']},
+ {'removed_list': ['a']},
+ {'created_list': ['a'], 'updated_list': ['b']},
+ ):
+ result = IntegrationSyncResult(title='X', **kwargs)
+ self.assertTrue(result.has_changes, kwargs)
+
+ def test_has_changes_false_when_all_lists_empty(self):
+ # Nothing-new refresh: no changes even if info_list has lines.
+ result = IntegrationSyncResult(
+ title='Empty',
+ info_list=['Found 12 upstream items'],
+ )
+ self.assertFalse(result.has_changes)
+
+ def test_placement_input_default_is_none(self):
+ """A bare sync result has no placement_input — that's the
+ signal the framework uses to decide whether to show the
+ placement modal."""
+ result = IntegrationSyncResult(title='Empty')
+ self.assertIsNone(result.placement_input)
+
+ def test_placement_input_carries_groups_and_ungrouped(self):
+ """placement_input wires sync results to the placement: the
+ synchronizer populates groups/ungrouped via
+ group_entities_for_placement and stashes the input on the
+ result."""
+ entity = _FakeEntity('Camera 1')
+ placement_input = EntityPlacementInput(
+ groups=[EntityPlacementGroup(
+ label='Monitors',
+ items=[EntityPlacementItem(
+ key='zm:1', label='Camera 1', entity=entity,
+ )],
+ )],
+ )
+ result = IntegrationSyncResult(
+ title='Sync',
+ placement_input=placement_input,
+ )
+ self.assertIs(result.placement_input, placement_input)
+ self.assertEqual(result.placement_input.groups[0].label, 'Monitors')
diff --git a/src/hi/integrations/tests/test_views.py b/src/hi/integrations/tests/test_views.py
index 4ff9cf5e..6d490085 100644
--- a/src/hi/integrations/tests/test_views.py
+++ b/src/hi/integrations/tests/test_views.py
@@ -184,3 +184,984 @@ class RemoveViewTests(SyncViewTestCase):
self.assertErrorResponse(response)
mock_disable.assert_not_called()
+
+
+# --------------------------------------------------------------------------
+# Pre-sync confirmation modal + framework Sync view tests
+# --------------------------------------------------------------------------
+
+
+class _SyncTestSynchronizer:
+ """
+ Stand-in synchronizer for pre-sync / sync view tests. Stays
+ intentionally minimal (does NOT extend IntegrationSynchronizer) to
+ avoid acquiring the real lock or running framework retry logic in
+ unit tests; the views only need methods the framework actually
+ calls on it.
+ """
+ def __init__(self, description='Test integration sync description.'):
+ self._description = description
+ self.sync_called = False
+
+ def get_description(self, is_initial_import):
+ self.last_is_initial_import = is_initial_import
+ return self._description
+
+ def get_result_title(self, is_initial_import):
+ return 'Test Sync Result'
+
+ def sync(self, is_initial_import=False):
+ from hi.integrations.sync_result import IntegrationSyncResult
+ self.sync_called = True
+ return IntegrationSyncResult(
+ title='Test Sync Result',
+ info_list=['Synced.'],
+ )
+
+
+class _SyncTestHealthStatusProvider:
+ @property
+ def health_status(self):
+ # The pre-sync template renders the health badge partial; tests
+ # don't need a real provider, just a stand-in that returns
+ # something safe to traverse from a Django template.
+ return Mock(status=Mock(name='HEALTHY'), is_healthy=True)
+
+
+class _SyncCapableGateway(IntegrationGateway):
+ """Gateway that provides a synchronizer + health provider."""
+
+ def __init__(self, integration_id='sync_view_test', synchronizer=None):
+ self.integration_id = integration_id
+ self._synchronizer = (
+ synchronizer if synchronizer is not None else _SyncTestSynchronizer()
+ )
+
+ def get_metadata(self):
+ return IntegrationMetaData(
+ integration_id=self.integration_id,
+ label='Sync View Test Integration',
+ attribute_type=_PauseResumeTestAttributeType,
+ allow_entity_deletion=True,
+ )
+
+ def get_manage_view_pane(self):
+ return Mock()
+
+ def get_monitor(self):
+ return Mock()
+
+ def get_controller(self):
+ return Mock()
+
+ def get_synchronizer(self):
+ return self._synchronizer
+
+ def get_health_status_provider(self):
+ return _SyncTestHealthStatusProvider()
+
+
+class _SyncIncapableGateway(IntegrationGateway):
+ """Gateway whose integration does NOT support sync."""
+
+ def __init__(self, integration_id='no_sync_view_test'):
+ self.integration_id = integration_id
+
+ def get_metadata(self):
+ return IntegrationMetaData(
+ integration_id=self.integration_id,
+ label='No Sync Test Integration',
+ attribute_type=_PauseResumeTestAttributeType,
+ allow_entity_deletion=True,
+ )
+
+ def get_manage_view_pane(self):
+ return Mock()
+
+ def get_monitor(self):
+ return Mock()
+
+ def get_controller(self):
+ return Mock()
+
+
+class PreSyncViewTests(SyncViewTestCase):
+ """
+ Framework pre-sync confirmation modal. Renders the synchronizer
+ description plus IMPORT/REFRESH and (first-time only) REVIEW
+ CONFIG actions; 404s when the integration does not provide a
+ synchronizer.
+ """
+
+ INTEGRATION_ID = 'sync_view_test'
+
+ def setUp(self):
+ super().setUp()
+ IntegrationManager().reset_for_testing()
+
+ self.integration = Integration.objects.create(
+ integration_id=self.INTEGRATION_ID,
+ is_enabled=True,
+ is_paused=False,
+ )
+ self.synchronizer = _SyncTestSynchronizer(
+ description='HASS-flavored fake description.'
+ )
+ self.gateway = _SyncCapableGateway(
+ integration_id=self.INTEGRATION_ID,
+ synchronizer=self.synchronizer,
+ )
+ IntegrationManager()._integration_data_map[self.INTEGRATION_ID] = IntegrationData(
+ integration_gateway=self.gateway,
+ integration=self.integration,
+ )
+
+ def _url(self):
+ return reverse(
+ 'integrations_pre_sync',
+ kwargs={'integration_id': self.INTEGRATION_ID},
+ )
+
+ def test_get_returns_modal_with_description(self):
+ response = self.client.get(self._url())
+ self.assertSuccessResponse(response)
+ body = response.content.decode()
+ self.assertIn('HASS-flavored fake description.', body)
+
+ def test_get_404s_when_integration_has_no_synchronizer(self):
+ # Replace the integration_data with one whose gateway returns
+ # None from get_synchronizer.
+ IntegrationManager()._integration_data_map[self.INTEGRATION_ID] = IntegrationData(
+ integration_gateway=_SyncIncapableGateway(self.INTEGRATION_ID),
+ integration=self.integration,
+ )
+ response = self.client.get(self._url())
+ self.assertEqual(response.status_code, 404)
+
+ def test_review_config_action_present_on_initial_import(self):
+ """REVIEW CONFIG button is shown only on the first-time path.
+
+ With no entities for this integration, is_initial_import=True
+ and the REVIEW CONFIG affordance must appear so the user can
+ return to the configure step.
+ """
+ response = self.client.get(self._url())
+ self.assertSuccessResponse(response)
+ self.assertIn('REVIEW CONFIG', response.content.decode())
+
+ def test_review_config_action_absent_after_initial_import(self):
+ """REVIEW CONFIG is omitted on the manage-page entry path.
+
+ With at least one entity already imported, is_initial_import
+ is False; the user came from the manage page and CANCEL takes
+ them back, so REVIEW CONFIG is unnecessary.
+ """
+ from hi.apps.entity.enums import EntityType
+ from hi.apps.entity.models import Entity
+ Entity.objects.create(
+ integration_id=self.INTEGRATION_ID,
+ integration_name='already_imported',
+ name='Already Imported',
+ entity_type_str=EntityType.default_value(),
+ )
+ response = self.client.get(self._url())
+ self.assertSuccessResponse(response)
+ self.assertNotIn('REVIEW CONFIG', response.content.decode())
+
+
+class SyncViewTests(SyncViewTestCase):
+ """
+ Framework Sync view: POSTs invoke the synchronizer's sync() and
+ return the result modal. 404s when the integration does not
+ provide a synchronizer.
+ """
+
+ INTEGRATION_ID = 'sync_view_test'
+
+ def setUp(self):
+ super().setUp()
+ IntegrationManager().reset_for_testing()
+
+ self.integration = Integration.objects.create(
+ integration_id=self.INTEGRATION_ID,
+ is_enabled=True,
+ is_paused=False,
+ )
+ self.synchronizer = _SyncTestSynchronizer()
+ self.gateway = _SyncCapableGateway(
+ integration_id=self.INTEGRATION_ID,
+ synchronizer=self.synchronizer,
+ )
+ IntegrationManager()._integration_data_map[self.INTEGRATION_ID] = IntegrationData(
+ integration_gateway=self.gateway,
+ integration=self.integration,
+ )
+
+ def _url(self):
+ return reverse(
+ 'integrations_sync',
+ kwargs={'integration_id': self.INTEGRATION_ID},
+ )
+
+ def test_post_invokes_synchronizer_sync(self):
+ response = self.client.post(self._url())
+ self.assertSuccessResponse(response)
+ self.assertTrue(self.synchronizer.sync_called)
+
+ def test_post_404s_when_integration_has_no_synchronizer(self):
+ IntegrationManager()._integration_data_map[self.INTEGRATION_ID] = IntegrationData(
+ integration_gateway=_SyncIncapableGateway(self.INTEGRATION_ID),
+ integration=self.integration,
+ )
+ response = self.client.post(self._url())
+ self.assertEqual(response.status_code, 404)
+
+
+# --------------------------------------------------------------------------
+# IntegrationEnableView tests for the Review Config (post-enable) path
+# --------------------------------------------------------------------------
+
+
+class EnableViewReviewConfigTests(SyncViewTestCase):
+ """
+ IntegrationEnableView accepts both first-time Configure and Review
+ Config (post-enable). The button label switches with state, and
+ the post-enable GET no longer 400s.
+ """
+
+ INTEGRATION_ID = 'enable_review_view_test'
+
+ def setUp(self):
+ super().setUp()
+ IntegrationManager().reset_for_testing()
+ self.integration = Integration.objects.create(
+ integration_id=self.INTEGRATION_ID,
+ is_enabled=True,
+ is_paused=False,
+ )
+ self.gateway = _SyncCapableGateway(integration_id=self.INTEGRATION_ID)
+ IntegrationManager()._integration_data_map[self.INTEGRATION_ID] = IntegrationData(
+ integration_gateway=self.gateway,
+ integration=self.integration,
+ )
+
+ def _url(self):
+ return reverse(
+ 'integrations_enable',
+ kwargs={'integration_id': self.INTEGRATION_ID},
+ )
+
+ def test_get_post_enable_does_not_400(self):
+ """Removed is_enabled BadRequest: GET on an enabled integration
+ must return 200 so Review Config can re-render the form."""
+ response = self.client.get(self._url())
+ self.assertSuccessResponse(response)
+
+ def test_get_post_enable_renders_update_button_label(self):
+ """Review-mode GET uses 'UPDATE' as the action label, not 'CONFIGURE'."""
+ response = self.client.get(self._url())
+ self.assertSuccessResponse(response)
+ body = response.content.decode()
+ self.assertIn('UPDATE', body)
+ self.assertNotIn('CONFIGURE', body)
+
+ def test_get_post_enable_renders_continue_action(self):
+ """Review-mode GET replaces the dismiss CANCEL with a CONTINUE
+ action that returns to the pre-sync modal. Without this swap a
+ user reviewing config with no changes has only SAVE (which
+ re-saves) or CANCEL (which aborts the whole sync flow) — both
+ wrong for the read-only review path."""
+ response = self.client.get(self._url())
+ self.assertSuccessResponse(response)
+ body = response.content.decode()
+ self.assertIn('CONTINUE', body)
+ # Cancel button has id="hi-modal-cancel"; its absence in review
+ # mode is what we're pinning here.
+ self.assertNotIn('hi-modal-cancel', body)
+ # The CONTINUE action must point at the pre-sync URL.
+ self.assertIn(
+ reverse('integrations_pre_sync', kwargs={'integration_id': self.INTEGRATION_ID}),
+ body,
+ )
+
+ def test_get_first_time_renders_configure_button_label(self):
+ """First-time GET (is_enabled=False) keeps the original
+ 'CONFIGURE' label and the dismiss CANCEL."""
+ self.integration.is_enabled = False
+ self.integration.save()
+ response = self.client.get(self._url())
+ self.assertSuccessResponse(response)
+ body = response.content.decode()
+ self.assertIn('CONFIGURE', body)
+ self.assertIn('hi-modal-cancel', body)
+ self.assertNotIn('CONTINUE', body)
+
+
+# --------------------------------------------------------------------------
+# Placement + post-placement + refine (Phase 3) tests
+# --------------------------------------------------------------------------
+
+
+class _PlacementTestSynchronizer:
+ """Synchronizer stub that returns a populated IntegrationSyncResult.
+
+ Three entities placed across two groups + one ungrouped item:
+ enough to exercise group default, drill-down override, and
+ ungrouped per-item paths.
+ """
+ def __init__(self, sync_result):
+ self._sync_result = sync_result
+ self.sync_called = False
+
+ def get_description(self, is_initial_import):
+ return None
+
+ def get_result_title(self, is_initial_import):
+ return 'Placement Test'
+
+ def sync(self, is_initial_import=False):
+ self.sync_called = True
+ return self._sync_result
+
+
+class _PlacementTestGateway(IntegrationGateway):
+ """Placement gateway with a synchronizer + minimal stubs."""
+
+ def __init__(self, integration_id, synchronizer):
+ self.integration_id = integration_id
+ self._synchronizer = synchronizer
+
+ def get_metadata(self):
+ return IntegrationMetaData(
+ integration_id=self.integration_id,
+ label='Placement Test',
+ attribute_type=_PauseResumeTestAttributeType,
+ allow_entity_deletion=True,
+ )
+
+ def get_manage_view_pane(self):
+ return Mock()
+
+ def get_monitor(self):
+ return Mock()
+
+ def get_controller(self):
+ return Mock()
+
+ def get_synchronizer(self):
+ return self._synchronizer
+
+ def get_health_status_provider(self):
+ return Mock()
+
+
+class PlacementFlowTests(SyncViewTestCase):
+ """End-to-end placement flow: sync → placement modal → apply →
+ post-placement modal."""
+
+ INTEGRATION_ID = 'placement_test'
+
+ def setUp(self):
+ super().setUp()
+ IntegrationManager().reset_for_testing()
+
+ from hi.apps.entity.entity_placement import (
+ EntityPlacementGroup,
+ EntityPlacementInput,
+ EntityPlacementItem,
+ )
+ from hi.apps.entity.enums import EntityType
+ from hi.apps.entity.models import Entity
+ from hi.apps.location.models import Location, LocationView
+ from hi.integrations.sync_result import IntegrationSyncResult
+
+ self.integration = Integration.objects.create(
+ integration_id=self.INTEGRATION_ID,
+ is_enabled=True,
+ is_paused=False,
+ )
+ self.location = Location.objects.create(
+ name='Test Location',
+ svg_view_box_str='0 0 1000 1000',
+ )
+ self.view_a = LocationView.objects.create(
+ location=self.location, name='Kitchen', order_id=1,
+ svg_view_box_str='0 0 1000 1000',
+ svg_rotate=0, svg_style_name_str='COLOR',
+ location_view_type_str='DEFAULT',
+ )
+ self.view_b = LocationView.objects.create(
+ location=self.location, name='Living Room', order_id=2,
+ svg_view_box_str='0 0 1000 1000',
+ svg_rotate=0, svg_style_name_str='COLOR',
+ location_view_type_str='DEFAULT',
+ )
+
+ self.entity_a = Entity.objects.create(
+ name='Cam 1',
+ entity_type_str=str(EntityType.CAMERA),
+ integration_id=self.INTEGRATION_ID,
+ integration_name='cam_1',
+ )
+ self.entity_b = Entity.objects.create(
+ name='Cam 2',
+ entity_type_str=str(EntityType.CAMERA),
+ integration_id=self.INTEGRATION_ID,
+ integration_name='cam_2',
+ )
+ self.entity_c = Entity.objects.create(
+ name='Light 1',
+ entity_type_str=str(EntityType.LIGHT),
+ integration_id=self.INTEGRATION_ID,
+ integration_name='light_1',
+ )
+ self.ungrouped_entity = Entity.objects.create(
+ name='Ungrouped Thing',
+ entity_type_str=str(EntityType.OTHER),
+ integration_id=self.INTEGRATION_ID,
+ integration_name='thing_1',
+ )
+
+ self.sync_result = IntegrationSyncResult(
+ title='Placement Test',
+ created_list=['Cam 1', 'Cam 2', 'Light 1', 'Ungrouped Thing'],
+ placement_input=EntityPlacementInput(
+ groups=[
+ EntityPlacementGroup(
+ label='Cameras',
+ items=[
+ EntityPlacementItem(key='placement_test:cam_1', label='Cam 1', entity=self.entity_a),
+ EntityPlacementItem(key='placement_test:cam_2', label='Cam 2', entity=self.entity_b),
+ ],
+ ),
+ EntityPlacementGroup(
+ label='Lights',
+ items=[
+ EntityPlacementItem(key='placement_test:light_1', label='Light 1', entity=self.entity_c),
+ ],
+ ),
+ ],
+ ungrouped_items=[
+ EntityPlacementItem(
+ key='placement_test:thing_1',
+ label='Ungrouped Thing',
+ entity=self.ungrouped_entity,
+ ),
+ ],
+ ),
+ )
+
+ self.synchronizer = _PlacementTestSynchronizer(sync_result=self.sync_result)
+ self.gateway = _PlacementTestGateway(
+ integration_id=self.INTEGRATION_ID, synchronizer=self.synchronizer,
+ )
+ IntegrationManager()._integration_data_map[self.INTEGRATION_ID] = IntegrationData(
+ integration_gateway=self.gateway, integration=self.integration,
+ )
+
+ def _sync_url(self):
+ return reverse(
+ 'integrations_sync', kwargs={'integration_id': self.INTEGRATION_ID},
+ )
+
+ def _placement_url(self):
+ # GET renders / POST processes — same URL after the
+ # GET+POST view consolidation.
+ return reverse(
+ 'integrations_placement',
+ kwargs={'integration_id': self.INTEGRATION_ID},
+ )
+
+ def test_sync_renders_result_modal_with_place_items_cta(self):
+ """Sync that produced new entities → sync result modal with
+ a primary 'Place N items' CTA pointing at the placement
+ GET endpoint. The placement is no longer rendered directly
+ from the sync POST response — placement is opt-in."""
+ response = self.client.post(self._sync_url())
+ self.assertSuccessResponse(response)
+ body = response.content.decode()
+ # Result-modal markers (NOT placement markers).
+ # Hero copy is is_initial_import-aware. Test setup leaves
+ # Entity rows in the DB so the sync view sees this as a
+ # Refresh, not an Initial Import.
+ self.assertIn('Refresh complete', body)
+ self.assertIn('Place Later', body)
+ self.assertIn('Place 4 new items', body)
+ self.assertIn(self._placement_url(), body)
+ # No placement artifacts in the response — operator must
+ # click the CTA to reach the placement.
+ self.assertNotIn('APPLY', body)
+
+ def test_sync_renders_result_modal_without_cta_when_no_creates(self):
+ """Sync result with no created entities → result modal with
+ no 'Place items' CTA. Single centered OK is the only footer
+ action (matches the project's 'acknowledge info, dismiss'
+ single-button convention)."""
+ from hi.integrations.sync_result import IntegrationSyncResult
+ self.synchronizer._sync_result = IntegrationSyncResult(title='Empty')
+ response = self.client.post(self._sync_url())
+ self.assertSuccessResponse(response)
+ body = response.content.decode()
+ self.assertIn('hi-modal-ok', body)
+ self.assertNotIn('Place ', body)
+ self.assertNotIn('APPLY', body)
+
+ def test_sync_renders_result_modal_with_updates_and_removes_visible(self):
+ """Update/remove signal is no longer swallowed by the
+ placement when there are also creates — every change kind
+ is enumerated in the result modal even though the modal
+ ultimately routes the operator to placement."""
+ from hi.integrations.sync_result import IntegrationSyncResult
+ self.synchronizer._sync_result = IntegrationSyncResult(
+ title='Mixed Result',
+ created_list=['Brand New Light'],
+ updated_list=['Old Name → New Name'],
+ removed_list=['Stale Sensor'],
+ placement_input=self.sync_result.placement_input,
+ )
+ response = self.client.post(self._sync_url())
+ self.assertSuccessResponse(response)
+ body = response.content.decode()
+ # All three categories visible in the result.
+ self.assertIn('Brand New Light', body)
+ self.assertIn('Old Name → New Name', body)
+ self.assertIn('Stale Sensor', body)
+ # And the CTA still routes to the placement.
+ self.assertIn('Place 1 new item', body)
+
+ def test_placement_top_inherits_to_groups_and_entities(self):
+ """Top view chosen, groups + entities at default → every
+ entity goes to the top view."""
+ from hi.apps.entity.models import EntityView
+ response = self.client.post(self._placement_url(), {
+ 'top_view': f'view:{self.view_a.id}',
+ 'all_group_0_entity_ids': [str(self.entity_a.id), str(self.entity_b.id)],
+ 'all_group_1_entity_ids': [str(self.entity_c.id)],
+ 'ungrouped_entity_ids': [str(self.ungrouped_entity.id)],
+ })
+ self.assertSuccessResponse(response)
+ for entity in [self.entity_a, self.entity_b, self.entity_c, self.ungrouped_entity]:
+ self.assertTrue(EntityView.objects.filter(
+ entity=entity, location_view=self.view_a).exists())
+
+ def test_placement_group_overrides_top(self):
+ """Group view overrides top for entities in that group;
+ other groups still inherit top."""
+ from hi.apps.entity.models import EntityView
+ response = self.client.post(self._placement_url(), {
+ 'top_view': f'view:{self.view_a.id}',
+ 'all_group_0_entity_ids': [str(self.entity_a.id), str(self.entity_b.id)],
+ 'all_group_1_entity_ids': [str(self.entity_c.id)],
+ 'group_view_0': f'view:{self.view_b.id}', # Cameras → view_b
+ # group_view_1 left blank → inherits view_a
+ })
+ self.assertSuccessResponse(response)
+ self.assertTrue(EntityView.objects.filter(
+ entity=self.entity_a, location_view=self.view_b).exists())
+ self.assertTrue(EntityView.objects.filter(
+ entity=self.entity_b, location_view=self.view_b).exists())
+ self.assertTrue(EntityView.objects.filter(
+ entity=self.entity_c, location_view=self.view_a).exists())
+
+ def test_placement_drill_down_override_wins(self):
+ """Per-entity override beats group default for that entity."""
+ from hi.apps.entity.models import EntityView
+ response = self.client.post(self._placement_url(), {
+ 'top_view': f'view:{self.view_a.id}',
+ 'all_group_0_entity_ids': [str(self.entity_a.id), str(self.entity_b.id)],
+ 'group_view_0': f'view:{self.view_a.id}',
+ f'group_0_entity_{self.entity_b.id}_view': f'view:{self.view_b.id}',
+ })
+ self.assertSuccessResponse(response)
+ self.assertTrue(EntityView.objects.filter(
+ entity=self.entity_a, location_view=self.view_a).exists())
+ self.assertTrue(EntityView.objects.filter(
+ entity=self.entity_b, location_view=self.view_b).exists())
+ self.assertFalse(EntityView.objects.filter(
+ entity=self.entity_b, location_view=self.view_a).exists())
+
+ def test_placement_skip_at_top_skips_everything(self):
+ """top='' + groups inherit + entities inherit → all skipped."""
+ from hi.apps.entity.models import EntityView
+ response = self.client.post(self._placement_url(), {
+ 'top_view': '',
+ 'all_group_0_entity_ids': [str(self.entity_a.id)],
+ })
+ self.assertSuccessResponse(response)
+ self.assertFalse(EntityView.objects.filter(entity=self.entity_a).exists())
+
+ def test_placement_explicit_group_skip_overrides_top(self):
+ """Top view chosen, group explicitly skipped → those entities
+ don't get placed even though top has a view."""
+ from hi.apps.entity.models import EntityView
+ response = self.client.post(self._placement_url(), {
+ 'top_view': f'view:{self.view_a.id}',
+ 'all_group_0_entity_ids': [str(self.entity_a.id)],
+ 'group_view_0': '__skip__',
+ })
+ self.assertSuccessResponse(response)
+ self.assertFalse(EntityView.objects.filter(entity=self.entity_a).exists())
+
+ def test_placement_explicit_entity_skip_overrides_group(self):
+ """Group inherits top, but specific entity is explicitly skipped."""
+ from hi.apps.entity.models import EntityView
+ response = self.client.post(self._placement_url(), {
+ 'top_view': f'view:{self.view_a.id}',
+ 'all_group_0_entity_ids': [str(self.entity_a.id), str(self.entity_b.id)],
+ f'group_0_entity_{self.entity_a.id}_view': '__skip__',
+ })
+ self.assertSuccessResponse(response)
+ self.assertFalse(EntityView.objects.filter(entity=self.entity_a).exists())
+ self.assertTrue(EntityView.objects.filter(
+ entity=self.entity_b, location_view=self.view_a).exists())
+
+ def test_placement_new_view_creates_view_and_places_inherited_entities(self):
+ """top='__new__' creates a fresh LocationView named after the
+ integration; entities at default inherit it; existing-view
+ overrides at group/entity levels still apply."""
+ from hi.apps.entity.models import EntityView
+ from hi.apps.location.models import LocationView
+ before_view_ids = set(LocationView.objects.values_list('id', flat=True))
+ response = self.client.post(self._placement_url(), {
+ 'top_view': '__new_view__',
+ 'all_group_0_entity_ids': [str(self.entity_a.id), str(self.entity_b.id)],
+ 'all_group_1_entity_ids': [str(self.entity_c.id)],
+ 'group_view_1': f'view:{self.view_a.id}', # Lights → existing view
+ })
+ self.assertSuccessResponse(response)
+ new_view_ids = (
+ set(LocationView.objects.values_list('id', flat=True)) - before_view_ids
+ )
+ self.assertEqual(len(new_view_ids), 1)
+ new_view = LocationView.objects.get(id=new_view_ids.pop())
+ # Cameras inherited the new view.
+ self.assertTrue(EntityView.objects.filter(
+ entity=self.entity_a, location_view=new_view).exists())
+ self.assertTrue(EntityView.objects.filter(
+ entity=self.entity_b, location_view=new_view).exists())
+ # Lights took the explicit existing-view override.
+ self.assertTrue(EntityView.objects.filter(
+ entity=self.entity_c, location_view=self.view_a).exists())
+ # New view name = integration label.
+ self.assertEqual(new_view.name, 'Placement Test')
+
+ def test_post_placement_modal_renders_refine_for_primary_view(self):
+ """The post-placement modal includes a REFINE button targeting
+ the affected view, plus the view's name in the summary."""
+ response = self.client.post(self._placement_url(), {
+ 'top_view': f'view:{self.view_a.id}',
+ 'all_group_0_entity_ids': [str(self.entity_a.id)],
+ })
+ self.assertSuccessResponse(response)
+ body = response.content.decode()
+ self.assertIn('REFINE', body)
+ self.assertIn('Kitchen', body)
+ self.assertIn(reverse(
+ 'integrations_refine', kwargs={'location_view_id': self.view_a.id}
+ ), body)
+
+ def test_post_placement_primary_is_highest_count(self):
+ """When multiple views are affected, primary REFINE points at
+ the view with the most placed entities."""
+ # Cameras (2) → view_b; Light (1) → view_a. view_b wins.
+ response = self.client.post(self._placement_url(), {
+ 'top_view': f'view:{self.view_b.id}',
+ 'all_group_0_entity_ids': [str(self.entity_a.id), str(self.entity_b.id)],
+ 'all_group_1_entity_ids': [str(self.entity_c.id)],
+ 'group_view_1': f'view:{self.view_a.id}', # Lights → view_a
+ })
+ self.assertSuccessResponse(response)
+ body = response.content.decode()
+ primary_refine_idx = body.find('REFINE')
+ self.assertGreaterEqual(primary_refine_idx, 0)
+ slice_after_refine = body[primary_refine_idx:primary_refine_idx + 200]
+ self.assertIn('Living Room', slice_after_refine)
+
+
+class PlacementDismissAndShowTests(SyncViewTestCase):
+ """NOT NOW → dismiss-confirm modal → GO BACK → placement
+ modal re-renders. Round-trip covers the dismiss + show views
+ plus their hidden-input handshake."""
+
+ INTEGRATION_ID = 'placement_test'
+
+ def setUp(self):
+ super().setUp()
+ IntegrationManager().reset_for_testing()
+
+ from hi.apps.entity.entity_placement import (
+ EntityPlacementGroup,
+ EntityPlacementInput,
+ EntityPlacementItem,
+ )
+ from hi.apps.entity.enums import EntityType
+ from hi.apps.entity.models import Entity
+ from hi.apps.location.models import Location, LocationView
+ from hi.integrations.sync_result import IntegrationSyncResult
+
+ self.integration = Integration.objects.create(
+ integration_id=self.INTEGRATION_ID,
+ is_enabled=True,
+ is_paused=False,
+ )
+ self.location = Location.objects.create(
+ name='Test Location', svg_view_box_str='0 0 100 100',
+ )
+ self.view_a = LocationView.objects.create(
+ location=self.location, name='Kitchen', order_id=1,
+ svg_view_box_str='0 0 100 100', svg_rotate=0,
+ svg_style_name_str='COLOR', location_view_type_str='DEFAULT',
+ )
+ self.entity_a = Entity.objects.create(
+ name='Cam 1', entity_type_str=str(EntityType.CAMERA),
+ integration_id=self.INTEGRATION_ID, integration_name='cam_1',
+ )
+ self.entity_b = Entity.objects.create(
+ name='Cam 2', entity_type_str=str(EntityType.CAMERA),
+ integration_id=self.INTEGRATION_ID, integration_name='cam_2',
+ )
+
+ self.sync_result = IntegrationSyncResult(
+ title='Placement Test',
+ placement_input=EntityPlacementInput(
+ groups=[
+ EntityPlacementGroup(
+ label='Cameras',
+ items=[
+ EntityPlacementItem(key='placement_test:cam_1', label='Cam 1', entity=self.entity_a),
+ EntityPlacementItem(key='placement_test:cam_2', label='Cam 2', entity=self.entity_b),
+ ],
+ ),
+ ],
+ ),
+ )
+ self.synchronizer = _PlacementTestSynchronizer(sync_result=self.sync_result)
+ # Stub group_entities_for_placement so the GET placement can
+ # rebuild from unplaced entities.
+
+ def group_for_placement(entities):
+ items = [
+ EntityPlacementItem(
+ key=f'placement_test:{e.integration_name}',
+ label=e.name, entity=e,
+ )
+ for e in entities
+ ]
+ if not items:
+ return EntityPlacementInput()
+ return EntityPlacementInput(
+ groups=[EntityPlacementGroup(label='Cameras', items=items)],
+ )
+ self.synchronizer.group_entities_for_placement = group_for_placement
+
+ self.gateway = _PlacementTestGateway(
+ integration_id=self.INTEGRATION_ID, synchronizer=self.synchronizer,
+ )
+ IntegrationManager()._integration_data_map[self.INTEGRATION_ID] = IntegrationData(
+ integration_gateway=self.gateway, integration=self.integration,
+ )
+
+ def _placement_url(self):
+ return reverse(
+ 'integrations_placement',
+ kwargs={'integration_id': self.INTEGRATION_ID},
+ )
+
+ def test_dismiss_renders_confirmation_with_placement_link(self):
+ """The placement form's NOT NOW button (action=dismiss)
+ routes back to the same placement URL where the view's
+ POST handler renders the confirmation modal. GO BACK links
+ to the placement GET with is_initial_import threaded
+ through."""
+ response = self.client.post(self._placement_url(), {
+ 'action': 'dismiss',
+ 'is_initial_import': '1',
+ })
+ self.assertSuccessResponse(response)
+ body = response.content.decode()
+ # Confirmation copy.
+ self.assertIn('Items left unplaced', body)
+ self.assertIn('GO BACK', body)
+ self.assertIn('OK, PLACE LATER', body)
+ # GO BACK targets the placement GET with is_initial_import=1.
+ self.assertIn(self._placement_url() + '?is_initial_import=1', body)
+
+ def test_placement_get_renders_from_unplaced_entities(self):
+ """The GET placement queries entities for the integration
+ that have no EntityView row, runs them through the
+ synchronizer's group_entities_for_placement, and renders the
+ placement modal."""
+ response = self.client.get(self._placement_url())
+ self.assertSuccessResponse(response)
+ body = response.content.decode()
+ # Placement rendered (APPLY button + entity ids in form).
+ self.assertIn('APPLY', body)
+ self.assertIn('Cameras', body)
+ self.assertIn(f'value="{self.entity_a.id}"', body)
+ self.assertIn(f'value="{self.entity_b.id}"', body)
+
+ def test_placement_get_scopes_to_entity_ids_url_param(self):
+ """When the URL carries ``entity_ids=...``, the placement
+ filters the unplaced set to those ids — protects the sync-
+ result CTA from showing pre-existing unplaced entities the
+ operator didn't just import."""
+ from hi.apps.entity.models import Entity
+ from hi.apps.entity.enums import EntityType
+ # Add a pre-existing unplaced entity that would otherwise
+ # show up alongside cam_a/cam_b under the all-unplaced query.
+ prior_unplaced = Entity.objects.create(
+ name='Prior Unplaced Cam',
+ entity_type_str=str(EntityType.CAMERA),
+ integration_id=self.INTEGRATION_ID,
+ integration_name='prior_unplaced',
+ )
+ # CTA URL targets only the two newly-imported cameras.
+ scoped_url = (
+ self._placement_url()
+ + f'?entity_ids={self.entity_a.id},{self.entity_b.id}'
+ )
+ response = self.client.get(scoped_url)
+ self.assertSuccessResponse(response)
+ body = response.content.decode()
+ self.assertIn(f'value="{self.entity_a.id}"', body)
+ self.assertIn(f'value="{self.entity_b.id}"', body)
+ # Pre-existing unplaced entity must NOT appear.
+ self.assertNotIn(f'value="{prior_unplaced.id}"', body)
+ self.assertNotIn('Prior Unplaced Cam', body)
+
+ def test_placement_get_invalid_entity_ids_param_400s(self):
+ """Tampered or malformed ``entity_ids`` fails loudly."""
+ bad_url = self._placement_url() + '?entity_ids=1,abc'
+ response = self.client.get(bad_url)
+ self.assertEqual(response.status_code, 400)
+
+ def test_placement_get_renders_acknowledgement_when_no_unplaced(self):
+ """When every entity for the integration is already placed,
+ the GET placement renders the legacy result modal with
+ a brief 'no items' message rather than an empty placement."""
+ from hi.apps.entity.models import EntityView
+ EntityView.objects.create(entity=self.entity_a, location_view=self.view_a)
+ EntityView.objects.create(entity=self.entity_b, location_view=self.view_a)
+
+ response = self.client.get(self._placement_url())
+ self.assertSuccessResponse(response)
+ body = response.content.decode()
+ self.assertNotIn('APPLY', body)
+ self.assertIn('No items left to place.', body)
+
+ def test_placement_get_smart_default_picks_most_occupied_existing_view(self):
+ """Refresh path: top dropdown is pre-selected to whichever
+ existing target (view OR collection) holds the most entities
+ for this integration. Entities in view_a outnumber any
+ collection placement → top default = view_a."""
+ from hi.apps.entity.models import EntityView
+ from hi.apps.entity.models import Entity
+ from hi.apps.entity.enums import EntityType
+ # Place several entities (not from this placement's
+ # placement_input — pre-existing 'placed' state is what
+ # the smart default queries against).
+ for index in range(3):
+ placed = Entity.objects.create(
+ name=f'Already Placed {index}',
+ entity_type_str=str(EntityType.CAMERA),
+ integration_id=self.INTEGRATION_ID,
+ integration_name=f'placed_{index}',
+ )
+ EntityView.objects.create(
+ entity=placed, location_view=self.view_a,
+ )
+
+ response = self.client.get(self._placement_url())
+ self.assertSuccessResponse(response)
+ body = response.content.decode()
+ # Top dropdown is pre-selected to view_a.
+ self.assertIn(
+ f'value="view:{self.view_a.id}" selected', body,
+ )
+
+ def test_placement_get_smart_default_falls_back_to_dont_add_when_no_history(self):
+ """Refresh path with no prior placements for this integration
+ → top dropdown defaults to 'Don't place' (operator picks)."""
+ response = self.client.get(self._placement_url())
+ self.assertSuccessResponse(response)
+ body = response.content.decode()
+ # 'Don't place' option carries the selected attribute.
+ self.assertIn('value="" selected', body)
+
+ def test_placement_get_disambiguates_new_view_name_when_collision_exists(self):
+ """When a LocationView already exists in the default Location
+ with the integration's label, the '+ New view' option label
+ shows the disambiguated name '(2)' so the operator's
+ expectation matches the apply-time outcome."""
+ from hi.apps.location.models import Location, LocationView
+ # The PlacementDismissAndShowTests fixture builds a Location
+ # named 'Test Location' with one view 'Kitchen'. Add a view
+ # named 'Placement Test' (matching INTEGRATION_LABEL) to
+ # collide with the new-view default.
+ location = Location.objects.first()
+ LocationView.objects.create(
+ location=location, name='Placement Test', order_id=99,
+ svg_view_box_str='0 0 100 100', svg_rotate=0,
+ svg_style_name_str='COLOR', location_view_type_str='DEFAULT',
+ )
+
+ response = self.client.get(self._placement_url())
+ self.assertSuccessResponse(response)
+ body = response.content.decode()
+ # New-view option label reflects disambiguation, not the raw
+ # integration label.
+ self.assertIn('+ New view: "Placement Test (2)"', body)
+
+ def test_placement_get_inventory_preview_shows_group_counts(self):
+ """When the placement_input has groups, the modal renders
+ a single-line preview of label/count tuples beneath the
+ top dropdown."""
+ response = self.client.get(self._placement_url())
+ self.assertSuccessResponse(response)
+ body = response.content.decode()
+ # The PlacementGetFlow fixture builds a single 'Cameras'
+ # group with 2 items; the preview line lower-cases the
+ # label and shows the count.
+ self.assertIn('2 cameras', body)
+ # Group rows are behind the disclosure (collapsed by
+ # default) — the disclosure affordance is rendered.
+ self.assertIn('Place differently', body)
+
+
+class RefineViewTests(SyncViewTestCase):
+ """The refine-edit-mode entry point flips view_mode and points the
+ session at the chosen LocationView."""
+
+ def setUp(self):
+ super().setUp()
+ from hi.apps.location.models import Location, LocationView
+ location = Location.objects.create(
+ name='Test', svg_view_box_str='0 0 100 100',
+ )
+ self.location_view = LocationView.objects.create(
+ location=location, name='Refine View', order_id=1,
+ svg_view_box_str='0 0 100 100',
+ svg_rotate=0, svg_style_name_str='COLOR',
+ location_view_type_str='DEFAULT',
+ )
+
+ def test_refine_redirects_to_location_view(self):
+ from hi.enums import ViewMode
+ response = self.client.get(reverse(
+ 'integrations_refine',
+ kwargs={'location_view_id': self.location_view.id},
+ ))
+ self.assertEqual(response.status_code, 302)
+ self.assertEqual(
+ response.url,
+ reverse('location_view', kwargs={'location_view_id': self.location_view.id}),
+ )
+ # Session reflects edit mode + chosen view.
+ self.assertEqual(self.client.session.get('view_mode'), str(ViewMode.EDIT))
+ self.assertEqual(self.client.session.get('location_view_id'), self.location_view.id)
+
+ def test_refine_404s_for_unknown_view(self):
+ response = self.client.get(reverse(
+ 'integrations_refine', kwargs={'location_view_id': 99999},
+ ))
+ self.assertEqual(response.status_code, 404)
diff --git a/src/hi/integrations/transient_models.py b/src/hi/integrations/transient_models.py
index db48325d..1451f24a 100644
--- a/src/hi/integrations/transient_models.py
+++ b/src/hi/integrations/transient_models.py
@@ -156,3 +156,4 @@ class IntegrationValidationResult:
status=status,
error_message=error_message
)
+
diff --git a/src/hi/integrations/urls.py b/src/hi/integrations/urls.py
index 534b533c..fd038a49 100644
--- a/src/hi/integrations/urls.py
+++ b/src/hi/integrations/urls.py
@@ -32,9 +32,25 @@ urlpatterns = [
name='integrations_resume' ),
re_path( r'^health/(?P<integration_id>[\w\-]+)$',
- views.IntegrationHealthStatusView.as_view(),
+ views.IntegrationHealthStatusView.as_view(),
name='integrations_health_status' ),
+ re_path( r'^pre-sync/(?P<integration_id>[\w\-]+)$',
+ views.IntegrationPreSyncView.as_view(),
+ name='integrations_pre_sync' ),
+
+ re_path( r'^sync/(?P<integration_id>[\w\-]+)$',
+ views.IntegrationSyncView.as_view(),
+ name='integrations_sync' ),
+
+ re_path( r'^placement/(?P<integration_id>[\w\-]+)$',
+ views.IntegrationPlacementView.as_view(),
+ name='integrations_placement' ),
+
+ re_path( r'^refine/(?P<location_view_id>\d+)$',
+ views.IntegrationRefineView.as_view(),
+ name='integrations_refine' ),
+
re_path( r'^manage/(?P<integration_id>[\w\-]*)$',
views.IntegrationManageView.as_view(),
name='integrations_manage' ),
diff --git a/src/hi/integrations/view_mixins.py b/src/hi/integrations/view_mixins.py
index 20e6bdc8..6109c2a2 100644
--- a/src/hi/integrations/view_mixins.py
+++ b/src/hi/integrations/view_mixins.py
@@ -1,6 +1,15 @@
+from django.db.models import Count
from django.http import Http404
+from django.urls import reverse
+
+from hi.apps.collection.collection_manager import CollectionManager
+from hi.apps.collection.models import Collection, CollectionEntity
+from hi.apps.entity.models import EntityView
+from hi.apps.location.location_manager import LocationManager
+from hi.apps.location.models import Location, LocationView
from .integration_manager import IntegrationManager
+from .placement_request import PlacementUrlParams
class IntegrationViewMixin:
@@ -80,4 +89,287 @@ class IntegrationViewMixin:
return
-
+class IntegrationPlacementViewMixin:
+ """Modal context builders shared across the placement /
+ dismiss-confirm / post-dispatch views. Knows UI conventions
+ (URL routing for the integration placement flow, location-view
+ dropdown shape) but no business logic.
+
+ Designed to be mixed into ``HiModalView`` subclasses so the
+ rendering methods can call ``self.modal_response(...)`` directly.
+ """
+
+ def render_placement( self,
+ request,
+ integration_data,
+ placement_input,
+ is_initial_import : bool,
+ entity_id_filter = None ):
+ """Render the placement modal seeded with an
+ ``EntityPlacementInput``. Dropdowns offer both LocationView
+ and Collection targets; the top dropdown additionally offers
+ '+ New view' and '+ New collection' sentinels.
+
+ Computes two presentation aids in the view rather than the
+ template: a smart default for the top dropdown
+ (``top_default_value``) and an inventory preview line shown
+ beneath it (``inventory_preview``). The template is then a
+ thin renderer of these and the placement_input itself.
+ """
+ location_view_groups = self._build_location_view_groups()
+ collection_list = self._build_collection_list()
+ new_view_name, new_collection_name = self._derive_new_target_names(
+ request = request,
+ integration_label = integration_data.label,
+ )
+ top_default_value = self._compute_top_default_value(
+ integration_id = integration_data.integration_id,
+ is_initial_import = is_initial_import,
+ )
+ # Decompose the tagged value into per-kind ids so the
+ # template can do direct integer comparisons in the
+ # existing-view / existing-collection option loops.
+ top_default_view_id = None
+ top_default_collection_id = None
+ if top_default_value.startswith( 'view:' ):
+ top_default_view_id = int( top_default_value[ len('view:') : ] )
+ elif top_default_value.startswith( 'collection:' ):
+ top_default_collection_id = int( top_default_value[ len('collection:') : ] )
+ inventory_preview = self._build_inventory_preview(
+ placement_input = placement_input,
+ )
+ # The form posts back to the same URL that rendered the
+ # modal — single CBV, GET renders / POST processes.
+ placement_url = reverse(
+ 'integrations_placement',
+ kwargs = { 'integration_id': integration_data.integration_id },
+ )
+ return self.modal_response(
+ request,
+ context = {
+ 'integration_data': integration_data,
+ 'placement_input': placement_input,
+ 'location_view_groups': location_view_groups,
+ 'collection_list': collection_list,
+ 'top_default_value': top_default_value,
+ 'top_default_view_id': top_default_view_id,
+ 'top_default_collection_id': top_default_collection_id,
+ 'new_view_name': new_view_name,
+ 'new_collection_name': new_collection_name,
+ 'inventory_preview': inventory_preview,
+ 'placement_url': placement_url,
+ 'is_initial_import': is_initial_import,
+ },
+ template_name = 'integrations/modals/placement.html',
+ )
+
+ def render_dismiss_confirm( self,
+ request,
+ integration_data,
+ is_initial_import : bool,
+ entity_ids = None ):
+ """Render the NOT NOW confirmation modal. GO BACK targets
+ the placement GET endpoint, with is_initial_import and
+ (when present) the entity-id scope threaded through as
+ query parameters so the operator returns to the same set
+ they were viewing."""
+ placement_url = PlacementUrlParams(
+ is_initial_import = is_initial_import,
+ entity_ids = list( entity_ids ) if entity_ids else [],
+ ).append_to_url( reverse(
+ 'integrations_placement',
+ kwargs = { 'integration_id': integration_data.integration_id },
+ ) )
+ return self.modal_response(
+ request,
+ context = {
+ 'integration_data': integration_data,
+ 'placement_url': placement_url,
+ },
+ template_name = 'integrations/modals/placement_dismiss.html',
+ )
+
+ def render_post_placement( self,
+ request,
+ integration_data,
+ outcome,
+ is_initial_import : bool ):
+ """Render the post-dispatch summary modal from a
+ ``PlacementOutcome``.
+
+ The primary action button is REFINE for view-targeted
+ primary summaries (drag entities into spatial position) and
+ REVIEW for collection-targeted primary summaries (no spatial
+ refinement; the link just lands on the collection's view
+ page). ``PlacementOutcome.primary_summary`` already prefers
+ view-targeted summaries when any exist, so the REFINE path
+ is taken whenever the operator placed at least one entity
+ into a LocationView."""
+ primary = outcome.primary_summary
+ primary_action = None
+ secondary_action_list = []
+ if primary is not None:
+ primary_action = ( primary, self._summary_url( primary ) )
+ for summary in outcome.secondary_summaries:
+ secondary_action_list.append(
+ ( summary, self._summary_url( summary ) )
+ )
+ return self.modal_response(
+ request,
+ context = {
+ 'integration_data': integration_data,
+ 'outcome': outcome,
+ 'is_initial_import': is_initial_import,
+ 'primary_action': primary_action,
+ 'secondary_action_list': secondary_action_list,
+ },
+ template_name = 'integrations/modals/post_placement.html',
+ )
+
+ def _build_location_view_groups( self ):
+ """Existing-views dropdown source: ``[(Location,
+ [LocationView])]`` ordered by Location.order_id, views by
+ LocationView.order_id within each. Always grouped (never
+ flat) so multi-Location deployments can disambiguate views
+ with shared names. Single SQL query joining LocationView ↔
+ Location; insertion-order in the dict preserves the sort
+ from the database. Empty Locations drop out, which is the
+ right behavior for a dropdown source."""
+ queryset = LocationView.objects.select_related('location').order_by(
+ 'location__order_id', 'order_id',
+ )
+ groups : dict = {}
+ for view in queryset:
+ groups.setdefault( view.location, [] ).append( view )
+ return list( groups.items() )
+
+ def _build_collection_list( self ):
+ """Existing-collections dropdown source for the placement
+ modal. Single optgroup keyed by 'Collections'; ordered by
+ Collection.order_id."""
+ return list( Collection.objects.order_by('order_id').all() )
+
+ def _summary_url( self, summary ) -> str:
+ """URL for the post-dispatch modal's per-summary action.
+ Views go through ``integrations_refine`` (which lands the
+ operator in edit mode for that view); collections link to
+ the read-only ``collection_view`` page."""
+ if summary.is_view:
+ return reverse(
+ 'integrations_refine',
+ kwargs = { 'location_view_id': summary.location_view.id },
+ )
+ return reverse(
+ 'collection_view',
+ kwargs = { 'collection_id': summary.collection.id },
+ )
+
+ def _compute_top_default_value( self,
+ integration_id : str,
+ is_initial_import : bool ) -> str:
+ """Smart default for the placement's top dropdown.
+
+ On Initial Import the operator has no existing target — pre-
+ select '+ New view' so they can click APPLY without further
+ input.
+
+ On Refresh, prefer whichever existing target (LocationView
+ OR Collection) currently holds the most entities for this
+ integration. Ties broken by id ascending (deterministic).
+ Falls back to '' (Don't place) when no existing target holds
+ any of this integration's entities — operator picks.
+ """
+ if is_initial_import:
+ return '__new_view__'
+
+ view_counts = list(
+ EntityView.objects
+ .filter( entity__integration_id = integration_id )
+ .values( 'location_view_id' )
+ .annotate( count = Count( 'id' ) )
+ .order_by( '-count', 'location_view_id' )
+ )
+ collection_counts = list(
+ CollectionEntity.objects
+ .filter( entity__integration_id = integration_id )
+ .values( 'collection_id' )
+ .annotate( count = Count( 'id' ) )
+ .order_by( '-count', 'collection_id' )
+ )
+
+ top_view = view_counts[0] if view_counts else None
+ top_collection = collection_counts[0] if collection_counts else None
+
+ if top_view and top_collection:
+ view_count = top_view['count']
+ collection_count = top_collection['count']
+ if view_count > collection_count:
+ return f'view:{top_view["location_view_id"]}'
+ if collection_count > view_count:
+ return f'collection:{top_collection["collection_id"]}'
+ # Equal counts — prefer lower target type ordinal. Views
+ # before collections is an arbitrary but deterministic
+ # tiebreak; the operator's own count was already a true
+ # tie so either answer is fine.
+ return f'view:{top_view["location_view_id"]}'
+
+ if top_view:
+ return f'view:{top_view["location_view_id"]}'
+ if top_collection:
+ return f'collection:{top_collection["collection_id"]}'
+ return ''
+
+ def _derive_new_target_names( self, request, integration_label : str ) -> tuple:
+ """Pre-resolve the names that the '+ New view' / '+ New
+ collection' options would actually produce on Apply, so the
+ dropdown labels match the operator's eventual reality.
+
+ Without this, an operator who already has a view named
+ 'Home Assistant' would see the option 'New view: "Home
+ Assistant"' but get a view named 'Home Assistant (2)' on
+ save — confusing.
+
+ Returns ``(new_view_name, new_collection_name)``. Falls
+ back to ``integration_label`` for the view name when no
+ default Location is configured (the apply path will raise
+ BadRequest in that case anyway; the modal label just shows
+ the un-disambiguated label).
+
+ Race-condition note: another operator could create a same-
+ named view/collection between render and submit, in which
+ case the apply-time disambiguation produces a different
+ suffix than the modal advertised. This is an extremely rare
+ case and the apply-time logic always picks a free name, so
+ no special handling is needed.
+ """
+ try:
+ location = LocationManager().get_default_location( request = request )
+ new_view_name = LocationManager().resolve_unique_view_name(
+ location = location,
+ requested_name = integration_label,
+ )
+ except Location.DoesNotExist:
+ new_view_name = integration_label
+ new_collection_name = CollectionManager().resolve_unique_collection_name(
+ requested_name = integration_label,
+ )
+ return new_view_name, new_collection_name
+
+ def _build_inventory_preview( self, placement_input ) -> list:
+ """Compact label/count summary of what's about to be placed.
+
+ Used as a single-line preview beneath the top dropdown when
+ the operator has the group rows collapsed — preserves the
+ 'free preview of what's about to be imported' signal that
+ the always-visible group cards previously provided.
+
+ Returns an empty list for the all-ungrouped case (HomeBox-
+ style). Callers should hide the preview entirely in that
+ case, since restating the count is just noise.
+ """
+ if not placement_input.groups:
+ return []
+ return [
+ { 'label': group.label, 'count': len( group.items ) }
+ for group in placement_input.groups
+ ]
diff --git a/src/hi/integrations/views.py b/src/hi/integrations/views.py
index 7eaf290e..8765312b 100644
--- a/src/hi/integrations/views.py
+++ b/src/hi/integrations/views.py
@@ -1,10 +1,12 @@
import logging
from django.core.exceptions import BadRequest
+from django.shortcuts import redirect
from django.urls import reverse
from django.views.generic import View
from hi.apps.common import antinode
+from hi.enums import ViewMode, ViewType
from hi.exceptions import ForceRedirectException
from hi.hi_async_view import HiModalView
from hi.views import page_not_found_response
@@ -13,14 +15,18 @@ from hi.apps.attribute.response_helpers import AttributeRedirectResponse
from hi.apps.attribute.view_mixins import AttributeEditViewMixin
from hi.apps.config.enums import ConfigPageType
from hi.apps.config.views import ConfigPageView
+from hi.apps.entity.entity_placement import EntityPlacementService
+from hi.apps.entity.models import Entity
+from hi.apps.location.models import LocationView
+from .placement_request import PlacementFormParser, PlacementUrlParams
from .entity_operations import EntityIntegrationOperations
from .enums import IntegrationDisableMode
from .exceptions import IntegrationConnectionError
from .integration_attribute_edit_context import IntegrationAttributeItemEditContext
from .integration_manager import IntegrationManager
from .models import IntegrationAttribute
-from .view_mixins import IntegrationViewMixin
+from .view_mixins import IntegrationPlacementViewMixin, IntegrationViewMixin
logger = logging.getLogger(__name__)
@@ -73,6 +79,298 @@ class IntegrationHealthStatusView( HiModalView, IntegrationViewMixin ):
return self.modal_response( request, context )
+class IntegrationPreSyncView( HiModalView, IntegrationViewMixin ):
+ """
+ Pre-sync confirmation modal. Surfaces the synchronizer's
+ description and offers Sync / Not now actions. Used as the last
+ step of the Configure flow (first-time sync) and from the IMPORT /
+ REFRESH button on the integration manage page (subsequent syncs).
+
+ The modal does not display integration health: an unhealthy
+ integration's sync attempt will surface its failure inline with a
+ useful error message, and rendering health here would also expose
+ the brief race window between IntegrationManager.enable_integration
+ flipping is_enabled in the DB and the manager singleton's
+ notify_settings_changed reload (driven by a 0.1s post-commit
+ delayed signal processor — deliberately deferred to avoid a
+ different, worse class of problems).
+
+ 404s when the integration does not provide a synchronizer (sync is
+ opt-in capability — not every integration supports it).
+ """
+
+ def get_template_name( self ) -> str:
+ return 'integrations/modals/pre_sync_confirm.html'
+
+ def get( self, request, *args, **kwargs ):
+ integration_id = kwargs.get('integration_id')
+ integration_data = self.get_integration_data(
+ integration_id = integration_id,
+ )
+ synchronizer = integration_data.integration_gateway.get_synchronizer()
+ if synchronizer is None:
+ return page_not_found_response( request )
+
+ is_initial_import = not Entity.objects.filter(
+ integration_id = integration_data.integration_id,
+ ).exists()
+ sync_url = reverse(
+ 'integrations_sync',
+ kwargs = { 'integration_id': integration_data.integration_id },
+ )
+ review_config_url = reverse(
+ 'integrations_enable',
+ kwargs = { 'integration_id': integration_data.integration_id },
+ )
+
+ context = {
+ 'integration_data': integration_data,
+ 'is_initial_import': is_initial_import,
+ 'sync_description': synchronizer.get_description(
+ is_initial_import = is_initial_import,
+ ),
+ 'sync_url': sync_url,
+ 'review_config_url': review_config_url,
+ }
+ return self.modal_response( request, context )
+
+
+class IntegrationSyncView( HiModalView, IntegrationViewMixin ):
+ """
+ Framework sync execution view. Invokes the integration's
+ synchronizer and always renders the sync result modal — the
+ operator's single end-of-sync surface. When the sync produced
+ new entities to place, the result modal exposes a primary
+ 'Place N new items' CTA that navigates (via antinode modal-to-
+ modal) to the placement GET endpoint where the operator picks
+ targets. When there are no new entities (refresh-with-updates,
+ refresh-with-removes, errors, or nothing-new), the result modal
+ shows just a dismissal action.
+
+ This shape was chosen so updates and removes are never silently
+ swallowed by an automatic transition to the placement: the
+ operator always sees what changed, and only opts into placement
+ when there's actually something to place.
+ """
+
+ def get_template_name( self ) -> str:
+ return 'integrations/modals/sync_result.html'
+
+ def post( self, request, *args, **kwargs ):
+ integration_id = kwargs.get('integration_id')
+ integration_data = self.get_integration_data(
+ integration_id = integration_id,
+ )
+ synchronizer = integration_data.integration_gateway.get_synchronizer()
+ if synchronizer is None:
+ return page_not_found_response( request )
+
+ # Compute the operator-flow flag BEFORE running sync so the
+ # entities the sync is about to create don't change the
+ # answer. is_initial_import = "no entities for this
+ # integration before this sync ran"; threaded through to the
+ # placement GET URL so a downstream Place-items click
+ # carries the same operator intent.
+ is_initial_import = not Entity.objects.filter(
+ integration_id = integration_data.integration_id,
+ ).exists()
+
+ sync_result = synchronizer.sync( is_initial_import = is_initial_import )
+
+ # Scope the placement to just the entities this sync created.
+ # Without scoping, the placement's GET endpoint queries every
+ # unplaced entity for the integration, including pre-existing
+ # ones from prior incomplete placements.
+ new_entity_ids = (
+ sync_result.placement_input.all_entity_ids()
+ if sync_result.placement_input is not None else []
+ )
+ placement_url = PlacementUrlParams(
+ is_initial_import = is_initial_import,
+ entity_ids = new_entity_ids,
+ ).append_to_url( reverse(
+ 'integrations_placement',
+ kwargs = { 'integration_id': integration_data.integration_id },
+ ) )
+
+ return self.modal_response(
+ request,
+ context = {
+ 'sync_result': sync_result,
+ 'integration_data': integration_data,
+ 'is_initial_import': is_initial_import,
+ 'placement_url': placement_url,
+ },
+ template_name = 'integrations/modals/sync_result.html',
+ )
+
+
+class IntegrationPlacementView( HiModalView, IntegrationViewMixin,
+ IntegrationPlacementViewMixin ):
+ """Placement modal — single CBV handling both the GET (render)
+ and POST (form submission) paths on one URL.
+
+ GET queries currently-unplaced entities for the integration
+ (optionally scoped by ``entity_ids`` URL param), runs them
+ through the synchronizer's ``group_entities_for_placement``,
+ and renders the placement modal. Empty result falls back to
+ a brief acknowledgement modal so the operator isn't dropped
+ onto an empty placement.
+
+ POST processes the placement form. The form has two submit
+ buttons — APPLY and NOT NOW — sharing ``name="action"`` with
+ distinct values; this view branches on the value to render
+ either the post-dispatch summary modal (apply path) or the
+ dismiss-confirm modal (not-now path).
+ """
+
+ DISMISS_ACTION_VALUE = 'dismiss'
+
+ def get_template_name( self ) -> str:
+ return 'integrations/modals/placement.html'
+
+ def get( self, request, *args, **kwargs ):
+ integration_id = kwargs.get('integration_id')
+ integration_data = self.get_integration_data(
+ integration_id = integration_id,
+ )
+ synchronizer = integration_data.integration_gateway.get_synchronizer()
+ if synchronizer is None:
+ return page_not_found_response( request )
+
+ url_params = PlacementUrlParams.from_data( request.GET )
+ is_initial_import = url_params.is_initial_import
+ entity_id_filter = set( url_params.entity_ids ) if url_params.entity_ids else None
+
+ entities = EntityPlacementService.query_unplaced_entities(
+ integration_id = integration_data.integration_id,
+ )
+ # When the caller scoped the URL to specific entity ids
+ # (sync-result CTA), narrow the unplaced set to those.
+ # Without scoping, the placement operates on the full
+ # unplaced set for the integration (recovery flow).
+ if entity_id_filter is not None:
+ entities = [ e for e in entities if e.id in entity_id_filter ]
+
+ placement_input = synchronizer.group_entities_for_placement(
+ entities = entities,
+ )
+ if placement_input.is_empty():
+ return self._render_empty(
+ request = request,
+ integration_data = integration_data,
+ synchronizer = synchronizer,
+ is_initial_import = is_initial_import,
+ )
+ return self.render_placement(
+ request = request,
+ integration_data = integration_data,
+ placement_input = placement_input,
+ is_initial_import = is_initial_import,
+ entity_id_filter = entity_id_filter,
+ )
+
+ def post( self, request, *args, **kwargs ):
+ integration_id = kwargs.get('integration_id')
+ integration_data = self.get_integration_data(
+ integration_id = integration_id,
+ )
+ url_params = PlacementUrlParams.from_data( request.POST )
+ is_initial_import = url_params.is_initial_import
+
+ if request.POST.get('action') == self.DISMISS_ACTION_VALUE:
+ entity_ids = self._extract_placement_entity_ids( request )
+ return self.render_dismiss_confirm(
+ request = request,
+ integration_data = integration_data,
+ entity_ids = entity_ids,
+ is_initial_import = is_initial_import,
+ )
+
+ decisions = PlacementFormParser.parse(
+ request = request, integration_data = integration_data,
+ )
+ outcome = EntityPlacementService.apply_decisions( decisions = decisions )
+ return self.render_post_placement(
+ request = request,
+ integration_data = integration_data,
+ outcome = outcome,
+ is_initial_import = is_initial_import,
+ )
+
+ @staticmethod
+ def _extract_placement_entity_ids( request ):
+ """Pull the entity ids the placement form just posted.
+ The placement renders ``all_group_<i>_entity_ids`` per
+ group plus a single ``ungrouped_entity_ids`` field — both
+ carry the entity ids regardless of whether the operator
+ opened any drill-down."""
+ ids = []
+ for key, values in request.POST.lists():
+ if key == 'ungrouped_entity_ids' or (
+ key.startswith( 'all_group_' )
+ and key.endswith( '_entity_ids' )
+ ):
+ for value in values:
+ try:
+ ids.append( int(value) )
+ except (TypeError, ValueError):
+ continue
+ return ids
+
+ def _render_empty( self, request, integration_data,
+ synchronizer, is_initial_import : bool ):
+ """No-unplaced-items acknowledgement: render the result
+ modal with the integration's icon + a brief 'no items'
+ info note rather than an empty placement. Counts stay
+ zero so the modal lead reads 'Nothing new.'"""
+ from hi.integrations.sync_result import IntegrationSyncResult
+ sync_result = IntegrationSyncResult(
+ title = synchronizer.get_result_title(
+ is_initial_import = is_initial_import,
+ ),
+ info_list = [ 'No items left to place.' ],
+ )
+ return self.modal_response(
+ request,
+ context = {
+ 'sync_result': sync_result,
+ 'integration_data': integration_data,
+ 'is_initial_import': is_initial_import,
+ },
+ template_name = 'integrations/modals/sync_result.html',
+ )
+
+
+class IntegrationRefineView( View ):
+ """
+ Convenience entry to edit-mode for a specific LocationView,
+ used by the post-dispatch modal's REFINE button(s). Sets the
+ session's current LocationView, flips view mode to EDIT, and
+ redirects to the location view page.
+ """
+
+ def get(self, request, *args, **kwargs):
+ try:
+ location_view_id = int( kwargs.get('location_view_id') )
+ except (TypeError, ValueError):
+ raise BadRequest( 'Invalid location_view_id' )
+ try:
+ location_view = LocationView.objects.get( id = location_view_id )
+ except LocationView.DoesNotExist:
+ return page_not_found_response( request )
+
+ request.view_parameters.view_type = ViewType.LOCATION_VIEW
+ request.view_parameters.update_location_view( location_view )
+ request.view_parameters.view_mode = ViewMode.EDIT
+ request.view_parameters.to_session( request )
+
+ return redirect( reverse(
+ 'location_view',
+ kwargs = { 'location_view_id': location_view.id },
+ ) )
+
+
class IntegrationEnableView( HiModalView, IntegrationViewMixin, AttributeEditViewMixin ):
def get_template_name( self ) -> str:
@@ -85,9 +383,18 @@ class IntegrationEnableView( HiModalView, IntegrationViewMixin, AttributeEditVie
integration_data = self.get_integration_data(
integration_id = integration_id,
)
-
- if integration_data.integration.is_enabled:
- raise BadRequest( f'{integration_data.label} is already configured' )
+
+ # Both first-time Configure (is_enabled=False) and Review Config
+ # from the pre-sync modal (is_enabled=True) land here. Review
+ # mode swaps CONFIGURE→UPDATE for the action button and replaces
+ # the dismiss-CANCEL with a CONTINUE that returns to pre-sync.
+ is_review_mode = integration_data.integration.is_enabled
+ pre_sync_url = (
+ reverse(
+ 'integrations_pre_sync',
+ kwargs = { 'integration_id': integration_data.integration_id },
+ ) if is_review_mode else None
+ )
integration_manager.ensure_all_attributes_exist(
integration_metadata = integration_data.integration_metadata,
@@ -95,10 +402,11 @@ class IntegrationEnableView( HiModalView, IntegrationViewMixin, AttributeEditVie
)
attr_item_context = IntegrationAttributeItemEditContext(
integration_data = integration_data,
- update_button_label = 'CONFIGURE',
+ update_button_label = 'UPDATE' if is_review_mode else 'CONFIGURE',
suppress_history = True,
show_secrets = True,
-
+ is_review_mode = is_review_mode,
+ pre_sync_url = pre_sync_url,
)
template_context = self.create_initial_template_context(
attr_item_context= attr_item_context,
@@ -111,14 +419,27 @@ class IntegrationEnableView( HiModalView, IntegrationViewMixin, AttributeEditVie
integration_data = self.get_integration_data(
integration_id = integration_id,
)
- if integration_data.integration.is_enabled:
- raise BadRequest( f'{integration_data.label} is already configured' )
+
+ # Both first-time Configure (is_enabled=False) and Review Config
+ # from the pre-sync modal (is_enabled=True) post here. Review
+ # mode flags drive the button label and the cancel→continue
+ # swap on form-error rerenders. enable_integration is
+ # idempotent, so the call below is safe in both contexts.
+ is_review_mode = integration_data.integration.is_enabled
+ pre_sync_url = (
+ reverse(
+ 'integrations_pre_sync',
+ kwargs = { 'integration_id': integration_data.integration_id },
+ ) if is_review_mode else None
+ )
attr_item_context = IntegrationAttributeItemEditContext(
integration_data = integration_data,
- update_button_label = 'CONFIGURE',
+ update_button_label = 'UPDATE' if is_review_mode else 'CONFIGURE',
suppress_history = True,
show_secrets = True,
+ is_review_mode = is_review_mode,
+ pre_sync_url = pre_sync_url,
)
response = self.post_attribute_form(
request = request,
@@ -132,6 +453,43 @@ class IntegrationEnableView( HiModalView, IntegrationViewMixin, AttributeEditVie
integration_manager.enable_integration(
integration_data = integration_data,
)
+
+ # Configure flow last step: when the integration supports sync,
+ # transition directly into the pre-sync confirmation modal
+ # instead of redirecting to the manage page. attr.js's response
+ # handler (extended for `data.modal`) closes the Configure
+ # modal and opens the new modal in its place via antinode's
+ # AN.displayModal — same lifecycle antinode applies to its own
+ # modal-to-modal transitions.
+ synchronizer = integration_data.integration_gateway.get_synchronizer()
+ if synchronizer is not None:
+ is_initial_import = not Entity.objects.filter(
+ integration_id = integration_data.integration_id,
+ ).exists()
+ sync_url = reverse(
+ 'integrations_sync',
+ kwargs = { 'integration_id': integration_data.integration_id },
+ )
+ review_config_url = reverse(
+ 'integrations_enable',
+ kwargs = { 'integration_id': integration_data.integration_id },
+ )
+ return self.modal_response(
+ request,
+ context = {
+ 'integration_data': integration_data,
+ 'is_initial_import': is_initial_import,
+ 'sync_description': synchronizer.get_description(
+ is_initial_import = is_initial_import,
+ ),
+ 'sync_url': sync_url,
+ 'review_config_url': review_config_url,
+ },
+ template_name = 'integrations/modals/pre_sync_confirm.html',
+ )
+
+ # Integrations without a synchronizer keep the original
+ # redirect-to-manage-page behavior.
redirect_url = reverse( 'integrations_manage',
kwargs = { 'integration_id': integration_id } )
return AttributeRedirectResponse( url = redirect_url )
@@ -272,6 +630,10 @@ class IntegrationManageView( ConfigPageView, IntegrationViewMixin, AttributeEdit
attr_item_context= attr_item_context,
)
)
+ has_entities = Entity.objects.filter(
+ integration_id = integration_data.integration_id,
+ ).exists()
+
template_context.update({
# Extra needed on initial view only for tabbed navigation. Not
# needed for attribute edit operations.
@@ -283,6 +645,7 @@ class IntegrationManageView( ConfigPageView, IntegrationViewMixin, AttributeEdit
'integration_data': integration_data,
'manage_view_template_name': manage_template_name,
'health_status': health_status_provider.health_status,
+ 'has_entities': has_entities,
},
})
return template_context
diff --git a/src/hi/services/hass/enums.py b/src/hi/services/hass/enums.py
index f01ec2ae..f5b97f2c 100644
--- a/src/hi/services/hass/enums.py
+++ b/src/hi/services/hass/enums.py
@@ -30,7 +30,7 @@ class HassAttributeType( IntegrationAttributeType ):
True,
)
IMPORT_ALLOWLIST = (
- 'Import Allowlist',
+ 'Allowed Item Types',
'HA domains and device classes to import (one per line). '
'Use "domain" for all classes, or "domain:class" for specific ones.',
AttributeValueType.TEXT,
diff --git a/src/hi/services/hass/hass_converter.py b/src/hi/services/hass/hass_converter.py
index 001d06cf..366e5673 100644
--- a/src/hi/services/hass/hass_converter.py
+++ b/src/hi/services/hass/hass_converter.py
@@ -634,8 +634,6 @@ class HassConverter:
controller.delete()
continue
- if not messages:
- messages.append( f'No changes found for {entity}.' )
return messages
@classmethod
diff --git a/src/hi/services/hass/hass_manage_view_pane.py b/src/hi/services/hass/hass_manage_view_pane.py
index 2bc17282..51302a19 100644
--- a/src/hi/services/hass/hass_manage_view_pane.py
+++ b/src/hi/services/hass/hass_manage_view_pane.py
@@ -1,6 +1,5 @@
from typing import Dict
-from hi.apps.entity.models import Entity
from hi.integrations.integration_data import IntegrationData
from hi.integrations.integration_manage_view_pane import IntegrationManageViewPane
@@ -11,9 +10,4 @@ class HassManageViewPane( IntegrationManageViewPane ):
return 'hass/panes/hass_manage.html'
def get_template_context( self, integration_data : IntegrationData ) -> Dict[ str, object ]:
-
- has_entities = Entity.objects.filter( integration_id = integration_data.integration_id ).exists()
-
- return {
- 'has_entities': has_entities,
- }
+ return {}
diff --git a/src/hi/services/hass/hass_sync.py b/src/hi/services/hass/hass_sync.py
index f65a75f0..0687ba6e 100644
--- a/src/hi/services/hass/hass_sync.py
+++ b/src/hi/services/hass/hass_sync.py
@@ -1,14 +1,19 @@
import logging
-from typing import Dict
+from typing import Dict, List, Optional
from django.db import transaction
-from hi.apps.common.database_lock import ExclusionLockContext
-from hi.apps.common.processing_result import ProcessingResult
from hi.apps.entity.models import Entity
+from hi.apps.entity.entity_placement import (
+ EntityPlacementInput,
+ EntityPlacementItem,
+ EntityPlacementGroup,
+)
+
+from hi.integrations.integration_synchronizer import IntegrationSynchronizer
+from hi.integrations.sync_result import IntegrationSyncResult
from hi.integrations.transient_models import IntegrationKey
-from hi.integrations.sync_mixins import IntegrationSyncMixin
from .hass_converter import HassConverter
from .hass_models import HassDevice
@@ -18,30 +23,18 @@ from .hass_metadata import HassMetaData
logger = logging.getLogger(__name__)
-class HassSynchronizer( HassMixin, IntegrationSyncMixin ):
+class HassSynchronizer( IntegrationSynchronizer, HassMixin ):
- SYNCHRONIZATION_LOCK_NAME = 'hass_integration_sync'
+ def get_description(self, is_initial_import: bool) -> Optional[str]:
+ if is_initial_import:
+ return 'Only items matching your Allowed Item Types setting will be imported.'
+ return 'Only items matching your Allowed Item Types setting are compared.'
- def __init__(self):
- return
-
- def sync( self ) -> ProcessingResult:
- try:
- with ExclusionLockContext( name = self.SYNCHRONIZATION_LOCK_NAME ):
- logger.debug( 'HAss integration sync started.' )
- return self._sync_helper()
- except RuntimeError as e:
- logger.exception( e )
- return ProcessingResult(
- title = 'Home Assistant Import Result',
- error_list = [ str(e) ],
- )
- finally:
- logger.debug( 'HAss integration sync ended.' )
-
- def _sync_helper( self ) -> ProcessingResult:
+ def _sync_impl( self, is_initial_import: bool ) -> IntegrationSyncResult:
hass_manager = self.hass_manager()
- result = ProcessingResult( title = 'Home Assistant Import Result' )
+ result = IntegrationSyncResult(
+ title = self.get_result_title( is_initial_import = is_initial_import ),
+ )
hass_client = hass_manager.hass_client
if not hass_client:
@@ -50,17 +43,17 @@ class HassSynchronizer( HassMixin, IntegrationSyncMixin ):
return result
hass_entity_id_to_state = hass_manager.fetch_hass_states_from_api()
- result.message_list.append( f'Found {len(hass_entity_id_to_state)} current Home Assistant states.' )
+ result.info_list.append( f'Found {len(hass_entity_id_to_state)} current Home Assistant states.' )
integration_key_to_entity = self._get_existing_hass_entities( result = result )
- result.message_list.append( f'Found {len(integration_key_to_entity)} existing Home Assistant entities.' )
+ result.info_list.append( f'Found {len(integration_key_to_entity)} existing Home Assistant items.' )
import_allowlist = hass_manager.import_allowlist
hass_device_id_to_device = HassConverter.hass_states_to_hass_devices(
hass_entity_id_to_state = hass_entity_id_to_state,
import_allowlist = import_allowlist,
)
- result.message_list.append( f'Found {len(hass_device_id_to_device)} current Home Assistant devices.' )
+ result.info_list.append( f'Found {len(hass_device_id_to_device)} current Home Assistant devices.' )
if import_allowlist:
total_states = len( hass_entity_id_to_state )
@@ -70,12 +63,12 @@ class HassSynchronizer( HassMixin, IntegrationSyncMixin ):
)
skipped_count = total_states - imported_states
if skipped_count > 0:
- result.message_list.append(
- f'Filtered {skipped_count} states not matching the Import Allowlist.'
+ result.info_list.append(
+ f'Filtered {skipped_count} states not matching the Allowed Item Types.'
)
result.footer_message = (
'Not seeing all your Home Assistant items? '
- 'Check the "Import Allowlist" in the Home Assistant '
+ 'Check the "Allowed Item Types" in the Home Assistant '
'integration settings to add more domains or device classes.'
)
@@ -83,7 +76,13 @@ class HassSynchronizer( HassMixin, IntegrationSyncMixin ):
HassConverter.hass_device_to_integration_key( hass_device ): hass_device
for hass_device in hass_device_id_to_device.values()
}
-
+
+ # Track newly-created entities only — existing-entity updates
+ # don't need re-placement and shouldn't surface in the
+ # dispatcher modal (refresh-with-no-new-items must produce
+ # an empty sync result).
+ created_entities: List[Entity] = []
+
with transaction.atomic():
for integration_key, hass_device in integration_key_to_hass_device.items():
entity = integration_key_to_entity.get( integration_key )
@@ -92,8 +91,9 @@ class HassSynchronizer( HassMixin, IntegrationSyncMixin ):
hass_device = hass_device,
result = result )
else:
- self._create_entity( hass_device = hass_device,
- result = result )
+ entity = self._create_entity( hass_device = hass_device,
+ result = result )
+ created_entities.append( entity )
continue
for integration_key, entity in integration_key_to_entity.items():
@@ -101,10 +101,14 @@ class HassSynchronizer( HassMixin, IntegrationSyncMixin ):
self._remove_entity( entity = entity,
result = result )
continue
-
+
+ if created_entities:
+ result.placement_input = self.group_entities_for_placement(
+ entities = created_entities,
+ )
return result
- def _get_existing_hass_entities( self, result : ProcessingResult ) -> Dict[ IntegrationKey, Entity ]:
+ def _get_existing_hass_entities( self, result : IntegrationSyncResult ) -> Dict[ IntegrationKey, Entity ]:
logger.debug( 'Getting existing HAss entities.' )
integration_key_to_entity = dict()
@@ -112,7 +116,7 @@ class HassSynchronizer( HassMixin, IntegrationSyncMixin ):
for entity in entity_queryset:
integration_key = entity.integration_key
if not integration_key:
- result.error_list.append( f'Entity found without valid Home Assistant Id: {entity}' )
+ result.error_list.append( f'Item found without valid Home Assistant Id: {entity}' )
mock_hass_device_id = 1000000 + entity.id # We need a (unique) placeholder for removals
integration_key = IntegrationKey(
integration_id = HassMetaData.integration_id,
@@ -125,37 +129,60 @@ class HassSynchronizer( HassMixin, IntegrationSyncMixin ):
def _create_entity( self,
hass_device : HassDevice,
- result : ProcessingResult ):
+ result : IntegrationSyncResult ) -> Entity:
entity = HassConverter.create_models_for_hass_device(
hass_device = hass_device,
add_alarm_events = self.hass_manager().should_add_alarm_events,
)
- result.message_list.append( f'Created Home Assistant entity: {entity}' )
- return
-
+ result.created_list.append( entity.name )
+ return entity
+
def _update_entity( self,
entity : Entity,
hass_device : HassDevice,
- result : ProcessingResult ):
-
- message_list = HassConverter.update_models_for_hass_device(
+ result : IntegrationSyncResult ):
+ # update_models_for_hass_device returns a list of change
+ # description strings — non-empty means at least one
+ # operator-visible change was made.
+ change_messages = HassConverter.update_models_for_hass_device(
entity = entity,
hass_device = hass_device,
)
- for message in message_list:
- result.message_list.append( message )
- continue
+ if change_messages:
+ result.updated_list.append( entity.name )
return
-
+
def _remove_entity( self,
entity : Entity,
- result : ProcessingResult ):
+ result : IntegrationSyncResult ):
"""
Remove an entity that no longer exists in the HASS integration.
-
+
Uses intelligent deletion that preserves user-created data.
"""
self._remove_entity_intelligently(entity, result, 'HASS')
return
-
+ def group_entities_for_placement( self, entities ) -> EntityPlacementInput:
+ """Group HASS entities by Hi-side entity_type_str.
+
+ HASS uses no ungrouped bucket — every entity has a type.
+ Groups are ordered by their label alphabetically for stable
+ presentation. Falls back to an 'Other' bucket for entities
+ without a recorded type."""
+ type_to_items: Dict[str, List[EntityPlacementItem]] = {}
+ for entity in entities:
+ type_label = str( entity.entity_type_str or 'Other' )
+ type_to_items.setdefault( type_label, [] ).append(
+ EntityPlacementItem(
+ key = self._placement_item_key( entity = entity ),
+ label = entity.name,
+ entity = entity,
+ )
+ )
+ continue
+ groups = [
+ EntityPlacementGroup( label = label, items = type_to_items[label] )
+ for label in sorted( type_to_items.keys() )
+ ]
+ return EntityPlacementInput( groups = groups )
diff --git a/src/hi/services/hass/integration.py b/src/hi/services/hass/integration.py
index da733623..d8abdfe5 100644
--- a/src/hi/services/hass/integration.py
+++ b/src/hi/services/hass/integration.py
@@ -7,6 +7,7 @@ from hi.apps.system.health_status_provider import HealthStatusProvider
from hi.integrations.integration_controller import IntegrationController
from hi.integrations.integration_gateway import IntegrationGateway
from hi.integrations.integration_manage_view_pane import IntegrationManageViewPane
+from hi.integrations.integration_synchronizer import IntegrationSynchronizer
from hi.integrations.models import IntegrationAttribute
from hi.integrations.transient_models import (
ConnectionTestResult,
@@ -19,6 +20,7 @@ from .hass_controller import HassController
from .hass_manage_view_pane import HassManageViewPane
from .hass_manager import HassManager
from .hass_metadata import HassMetaData
+from .hass_sync import HassSynchronizer
from .monitors import HassMonitor
logger = logging.getLogger(__name__)
@@ -52,7 +54,10 @@ class HassGateway( IntegrationGateway ):
def get_health_status_provider(self) -> HealthStatusProvider:
return HassManager()
-
+
+ def get_synchronizer(self) -> IntegrationSynchronizer:
+ return HassSynchronizer()
+
def validate_configuration(
self, integration_attributes: List[IntegrationAttribute]
) -> IntegrationValidationResult:
diff --git a/src/hi/services/hass/templates/hass/panes/hass_manage.html b/src/hi/services/hass/templates/hass/panes/hass_manage.html
index f12658ed..55b46348 100644
--- a/src/hi/services/hass/templates/hass/panes/hass_manage.html
+++ b/src/hi/services/hass/templates/hass/panes/hass_manage.html
@@ -1,30 +1,7 @@
-{% load static %}
-{% load icons %}
-<div class="d-flex justify-content-between">
- <div class="h3 integration-title">
- <img class="img-fluid"
- src="{% static core.integration_data.integration_metadata.logo_static_path %}"
- alt="{{ core.integration_data.integration_metadata.label }} Logo">
- {{ core.integration_data.integration_metadata.label }}
- </div>
- <div class="d-flex">
- {% include "integrations/panes/lifecycle_actions.html" %}
- <form action="{% url 'hass_sync' %}"
- method="POST" role="form" data-async="true">
- {% csrf_token %}
- <button type="submit" class="btn btn-outline-secondary" role="button"
- name="action" value="sync" >
- {% if has_entities %}
- {% icon "sync" size="sm" css_class="hi-icon-left" %}RE-SYNC
- {% else %}
- {% icon "upload" size="sm" css_class="hi-icon-left" %}IMPORT
- {% endif %}
- </button>
- </form>
- </div>
-</div>
-{% if not has_entities %}
-<div class="alert alert-warning text-center">
- Use the "IMPORT" button to add items from Home Assistant.
-</div>
-{% endif %}
+{% comment %}
+ Integration-specific custom content slot for the Home Assistant
+ manage page. The framework owns the page header (title/logo,
+ lifecycle actions, sync actions) and the attribute editor; this
+ template renders any HASS-specific UI between them. Currently empty
+ — kept as a documented extension point.
+{% endcomment %}
diff --git a/src/hi/services/hass/tests/test_hass_sync.py b/src/hi/services/hass/tests/test_hass_sync.py
index bb102ba0..d3a0cf1c 100644
--- a/src/hi/services/hass/tests/test_hass_sync.py
+++ b/src/hi/services/hass/tests/test_hass_sync.py
@@ -4,8 +4,8 @@ import os
from unittest.mock import Mock, patch
from django.test import TestCase
-from hi.apps.common.processing_result import ProcessingResult
from hi.apps.entity.models import Entity
+from hi.integrations.sync_result import IntegrationSyncResult
from hi.integrations.transient_models import IntegrationKey
from hi.services.hass.hass_sync import HassSynchronizer
@@ -23,18 +23,17 @@ class TestHassSynchronizerInitialization(TestCase):
self.assertIsInstance(synchronizer, HassSynchronizer)
def test_synchronization_lock_name_constant(self):
- """Test SYNCHRONIZATION_LOCK_NAME constant is properly defined"""
- self.assertEqual(HassSynchronizer.SYNCHRONIZATION_LOCK_NAME, 'hass_integration_sync')
+ """All integration synchronizers share a single process-wide
+ sync lock name; the base class declares it and subclasses do
+ not override."""
+ self.assertEqual(HassSynchronizer.SYNCHRONIZATION_LOCK_NAME, 'integrations_sync')
def test_inherits_from_mixins(self):
"""Test that HassSynchronizer inherits from required mixins"""
synchronizer = HassSynchronizer()
-
+
# Should inherit from HassMixin
self.assertTrue(hasattr(synchronizer, 'hass_manager'))
-
- # Should inherit from IntegrationSyncMixin
- self.assertTrue(hasattr(synchronizer, '_remove_entity_intelligently'))
class TestHassSynchronizerSyncMethod(TestCase):
@@ -43,12 +42,12 @@ class TestHassSynchronizerSyncMethod(TestCase):
def setUp(self):
self.synchronizer = HassSynchronizer()
- @patch('hi.services.hass.hass_sync.ExclusionLockContext')
- @patch.object(HassSynchronizer, '_sync_helper')
- def test_sync_handles_runtime_error(self, mock_sync_helper, mock_lock_context):
+ @patch('hi.integrations.integration_synchronizer.ExclusionLockContext')
+ @patch.object(HassSynchronizer, '_sync_impl')
+ def test_sync_handles_runtime_error(self, mock_sync_impl, mock_lock_context):
"""Test sync method handles RuntimeError exceptions"""
# Mock RuntimeError in sync helper
- mock_sync_helper.side_effect = RuntimeError("Database connection failed")
+ mock_sync_impl.side_effect = RuntimeError("Database connection failed")
# Mock lock context manager properly
mock_context = Mock()
@@ -56,17 +55,17 @@ class TestHassSynchronizerSyncMethod(TestCase):
mock_context.__exit__ = Mock(return_value=False)
mock_lock_context.return_value = mock_context
- result = self.synchronizer.sync()
+ result = self.synchronizer.sync(is_initial_import=True)
# Verify error handling
self.assertIn('Database connection failed', result.error_list[0])
- @patch('hi.services.hass.hass_sync.ExclusionLockContext')
- @patch.object(HassSynchronizer, '_sync_helper')
- def test_sync_returns_error_result_on_exception(self, mock_sync_helper, mock_lock_context):
- """Test sync method returns proper error result when _sync_helper raises exception"""
+ @patch('hi.integrations.integration_synchronizer.ExclusionLockContext')
+ @patch.object(HassSynchronizer, '_sync_impl')
+ def test_sync_returns_error_result_on_exception(self, mock_sync_impl, mock_lock_context):
+ """Test sync method returns proper error result when _sync_impl raises exception"""
# Mock RuntimeError in sync helper
- mock_sync_helper.side_effect = RuntimeError("Database connection failed")
+ mock_sync_impl.side_effect = RuntimeError("Database connection failed")
# Mock lock context manager properly
mock_context = Mock()
@@ -74,16 +73,16 @@ class TestHassSynchronizerSyncMethod(TestCase):
mock_context.__exit__ = Mock(return_value=False)
mock_lock_context.return_value = mock_context
- result = self.synchronizer.sync()
+ result = self.synchronizer.sync(is_initial_import=True)
# Verify actual error result structure and content
self.assertEqual(len(result.error_list), 1)
self.assertIn('Database connection failed', result.error_list[0])
- self.assertEqual(len(result.message_list), 0) # No success messages on error
+ self.assertEqual(len(result.info_list), 0) # No success messages on error
class TestHassSynchronizerSyncHelper(TestCase):
- """Test _sync_helper method logic"""
+ """Test _sync_impl method logic"""
def setUp(self):
self.synchronizer = HassSynchronizer()
@@ -142,7 +141,7 @@ class TestHassSynchronizerTransactionBehavior(TestCase):
def setUp(self):
self.synchronizer = HassSynchronizer()
- def test_sync_helper_executes_entity_operations_atomically(self):
+ def test_sync_impl_executes_entity_operations_atomically(self):
"""Test that all entity operations in sync_helper execute within single transaction"""
with patch.object(self.synchronizer, 'hass_manager') as mock_hass_manager, \
patch.object(self.synchronizer, '_get_existing_hass_entities') as mock_get_entities, \
@@ -168,7 +167,7 @@ class TestHassSynchronizerTransactionBehavior(TestCase):
mock_atomic.return_value.__enter__ = Mock()
mock_atomic.return_value.__exit__ = Mock()
- result = self.synchronizer._sync_helper()
+ result = self.synchronizer._sync_impl(is_initial_import=True)
# Verify atomic transaction was used exactly once
mock_atomic.assert_called_once()
@@ -180,7 +179,7 @@ class TestHassSynchronizerTransactionBehavior(TestCase):
# Verify successful result
self.assertEqual(len(result.error_list), 0)
- def test_sync_helper_rollback_behavior_on_entity_operation_failure(self):
+ def test_sync_impl_rollback_behavior_on_entity_operation_failure(self):
"""Test that transaction rollback works when entity operations fail"""
with patch.object(self.synchronizer, 'hass_manager') as mock_hass_manager, \
patch.object(self.synchronizer, '_get_existing_hass_entities') as mock_get_entities:
@@ -202,7 +201,7 @@ class TestHassSynchronizerTransactionBehavior(TestCase):
# Transaction should propagate the exception (allowing rollback)
with self.assertRaises(Exception) as context:
- self.synchronizer._sync_helper()
+ self.synchronizer._sync_impl(is_initial_import=True)
self.assertEqual(str(context.exception), "Entity creation failed")
@@ -228,7 +227,7 @@ class TestHassSynchronizerErrorScenarios(TestCase):
self.synchronizer = HassSynchronizer()
@patch.object(HassSynchronizer, 'hass_manager')
- def test_sync_helper_handles_api_fetch_failure(self, mock_hass_manager):
+ def test_sync_impl_handles_api_fetch_failure(self, mock_hass_manager):
"""Test sync helper handles API fetch failures"""
# Mock manager with client that fails API fetch
mock_manager = Mock()
@@ -238,14 +237,14 @@ class TestHassSynchronizerErrorScenarios(TestCase):
mock_hass_manager.return_value = mock_manager
with self.assertRaises(Exception) as context:
- self.synchronizer._sync_helper()
+ self.synchronizer._sync_impl(is_initial_import=True)
self.assertEqual(str(context.exception), "API connection failed")
@patch('hi.services.hass.hass_sync.HassConverter.hass_states_to_hass_devices')
@patch.object(HassSynchronizer, '_get_existing_hass_entities')
@patch.object(HassSynchronizer, 'hass_manager')
- def test_sync_helper_handles_converter_failure(
+ def test_sync_impl_handles_converter_failure(
self, mock_hass_manager,
mock_get_entities, mock_states_to_devices ):
"""Test sync helper handles converter failures"""
@@ -262,7 +261,7 @@ class TestHassSynchronizerErrorScenarios(TestCase):
mock_states_to_devices.side_effect = ValueError("Invalid state data format")
with self.assertRaises(ValueError) as context:
- self.synchronizer._sync_helper()
+ self.synchronizer._sync_impl(is_initial_import=True)
self.assertEqual(str(context.exception), "Invalid state data format")
@@ -272,7 +271,7 @@ class TestHassSynchronizerErrorScenarios(TestCase):
# Mock database query failure
mock_entity_objects.filter.side_effect = Exception("Database connection lost")
- result = ProcessingResult(title='Test')
+ result = IntegrationSyncResult(title='Test')
with self.assertRaises(Exception) as context:
self.synchronizer._get_existing_hass_entities(result)
@@ -281,24 +280,85 @@ class TestHassSynchronizerErrorScenarios(TestCase):
class TestHassSynchronizerMixinIntegration(TestCase):
- """Test integration with HassMixin and IntegrationSyncMixin"""
-
+ """Test integration with HassMixin"""
+
def setUp(self):
self.synchronizer = HassSynchronizer()
-
+
@patch('hi.services.hass.hass_mixins.HassManager')
def test_hass_mixin_integration(self, mock_manager_class):
"""Test HassMixin integration provides hass_manager access"""
mock_manager_instance = Mock()
mock_manager_class.return_value = mock_manager_instance
-
+
# Should be able to access hass_manager through mixin
result = self.synchronizer.hass_manager()
-
+
self.assertEqual(result, mock_manager_instance)
-
- def test_integration_sync_mixin_methods_available(self):
- """Test IntegrationSyncMixin methods are available"""
- # Should have _remove_entity_intelligently method from mixin
- self.assertTrue(hasattr(self.synchronizer, '_remove_entity_intelligently'))
- self.assertTrue(callable(getattr(self.synchronizer, '_remove_entity_intelligently')))
+
+
+class TestHassSynchronizerSyncResultGrouping(TestCase):
+ """Phase 2 grouping behavior: HASS-imported entities are grouped
+ by Hi-side entity_type_str. The /api/states endpoint exposes no
+ area metadata, so the synchronizer falls back to entity_type as
+ the meaningful, available signal."""
+
+ def setUp(self):
+ self.synchronizer = HassSynchronizer()
+
+ def _entity(self, name, entity_type_str, integration_name):
+ entity = Mock()
+ entity.name = name
+ entity.entity_type_str = entity_type_str
+ entity.integration_key = IntegrationKey(
+ integration_id='hass',
+ integration_name=integration_name,
+ )
+ entity.id = 0
+ return entity
+
+ def test_groups_built_by_entity_type_alphabetical(self):
+ """Group ordering is alphabetical for stable presentation."""
+ entities = [
+ self._entity('Kitchen Light', 'LIGHT', 'light.kitchen'),
+ self._entity('Hall Sensor', 'SENSOR', 'binary_sensor.hall'),
+ self._entity('Bedroom Light', 'LIGHT', 'light.bedroom'),
+ ]
+ placement_input = self.synchronizer.group_entities_for_placement(entities)
+
+ self.assertEqual(placement_input.ungrouped_items, [])
+ self.assertEqual(
+ [group.label for group in placement_input.groups],
+ ['LIGHT', 'SENSOR'],
+ )
+ self.assertEqual(
+ [item.label for item in placement_input.groups[0].items],
+ ['Kitchen Light', 'Bedroom Light'],
+ )
+ self.assertEqual(
+ [item.label for item in placement_input.groups[1].items],
+ ['Hall Sensor'],
+ )
+
+ def test_falls_back_to_other_when_entity_type_missing(self):
+ """Entities missing entity_type_str land in an 'Other' bucket
+ rather than dropping out of the result entirely."""
+ entity = self._entity('Mystery', '', 'sensor.mystery')
+ entity.entity_type_str = None
+ placement_input = self.synchronizer.group_entities_for_placement([entity])
+
+ self.assertEqual(placement_input.ungrouped_items, [])
+ self.assertEqual(len(placement_input.groups), 1)
+ self.assertEqual(placement_input.groups[0].label, 'Other')
+ self.assertEqual(placement_input.groups[0].items[0].entity, entity)
+
+ def test_empty_input_yields_empty_groups(self):
+ placement_input = self.synchronizer.group_entities_for_placement([])
+ self.assertEqual(placement_input.groups, [])
+ self.assertEqual(placement_input.ungrouped_items, [])
+ self.assertTrue(placement_input.is_empty())
+
+ def test_item_key_uses_integration_key(self):
+ entity = self._entity('Front Camera', 'CAMERA', 'camera.front')
+ placement_input = self.synchronizer.group_entities_for_placement([entity])
+ self.assertEqual(placement_input.groups[0].items[0].key, 'hass:camera.front')
diff --git a/src/hi/services/hass/urls.py b/src/hi/services/hass/urls.py
index 94673cd5..9cd4f55f 100644
--- a/src/hi/services/hass/urls.py
+++ b/src/hi/services/hass/urls.py
@@ -1,13 +1,17 @@
+"""
+Per-integration URL extension point.
-from django.urls import re_path
+The framework owns lifecycle, configure, sync, and manage URLs for
+every integration (see hi/integrations/urls.py). Add Home
+Assistant-specific URLs here when an integration genuinely needs an
+endpoint the framework does not provide. URLs added here mount under
+``services/hass/``.
-from . import views
+Currently no integration-specific endpoints are required.
+"""
+from django.urls import re_path # noqa: F401
+from . import views # noqa: F401
-urlpatterns = [
- re_path( r'^sync$',
- views.HassSyncView.as_view(),
- name='hass_sync' ),
-
-]
+urlpatterns = []
diff --git a/src/hi/services/hass/views.py b/src/hi/services/hass/views.py
index 0ed711a3..fd6063bc 100644
--- a/src/hi/services/hass/views.py
+++ b/src/hi/services/hass/views.py
@@ -1,17 +1,10 @@
-from hi.hi_async_view import HiModalView
+"""
+Per-integration view extension point.
-from .hass_sync import HassSynchronizer
+The framework owns lifecycle, configure, sync, and manage views for
+every integration (see hi/integrations/views.py). Define Home
+Assistant-specific views here only when an integration genuinely
+needs UI the framework does not provide.
-
-class HassSyncView( HiModalView ):
-
- def get_template_name( self ) -> str:
- return 'common/modals/processing_result.html'
-
- def post(self, request, *args, **kwargs):
-
- processing_result = HassSynchronizer().sync()
- context = {
- 'processing_result': processing_result,
- }
- return self.modal_response( request, context )
+Currently no integration-specific views are required.
+"""
diff --git a/src/hi/services/homebox/hb_client.py b/src/hi/services/homebox/hb_client.py
index 4294414c..65ae9f6d 100644
--- a/src/hi/services/homebox/hb_client.py
+++ b/src/hi/services/homebox/hb_client.py
@@ -128,6 +128,14 @@ class HbClient:
"""
Fetches the list of items and, for each one, fetches the full details.
Returns a list of fully populated HbItem objects.
+
+ A failed detail fetch propagates rather than being swallowed
+ per-item: a partial-success outcome here is more dangerous
+ than a clean failure (it silently drops items, which the
+ sync layer then misinterprets as upstream removals or a
+ clean 'nothing to import'). The sync flow's outer try/except
+ converts the propagated error into an operator-visible
+ ``error_list`` entry with the underlying message.
"""
items_summary = self.get_items_summary()
@@ -135,12 +143,9 @@ class HbClient:
for summary in items_summary:
item_id = summary.get('id')
if item_id:
- try:
- url_detail = f"{self._api_url}/{self.API_VERSION}/items/{item_id}"
- item_detail = self._make_request('GET', url_detail)
- full_items.append(HbItem(api_dict=item_detail, client=self))
- except Exception as e:
- logger.error(f"Error fetching details for item {item_id}: {e}")
+ url_detail = f"{self._api_url}/{self.API_VERSION}/items/{item_id}"
+ item_detail = self._make_request('GET', url_detail)
+ full_items.append(HbItem(api_dict=item_detail, client=self))
return full_items
diff --git a/src/hi/services/homebox/hb_converter.py b/src/hi/services/homebox/hb_converter.py
index 6f821dfd..f43e4dc4 100644
--- a/src/hi/services/homebox/hb_converter.py
+++ b/src/hi/services/homebox/hb_converter.py
@@ -114,12 +114,17 @@ class HbConverter:
@classmethod
def hb_item_to_entity_payload( cls, hb_item: HbItem ) -> Dict:
+ # Timestamps (createdAt / updatedAt) are deliberately excluded.
+ # They are metadata about *when* a change happened, not the
+ # content of the change — and real HomeBox can tick updatedAt
+ # for housekeeping events (label re-associations, internal
+ # caches) the operator doesn't care about. Including them
+ # would make payload-equality change detection report
+ # spurious updates on every refresh.
payload: Dict = {
'quantity': hb_item.quantity,
'insured': hb_item.insured,
'archived': hb_item.archived,
- 'created_at': hb_item.created_at,
- 'updated_at': hb_item.updated_at,
'purchase_price': hb_item.purchase_price,
'asset_id': hb_item.asset_id,
'sync_child_items_locations': hb_item.sync_child_items_locations,
diff --git a/src/hi/services/homebox/hb_manage_view_pane.py b/src/hi/services/homebox/hb_manage_view_pane.py
index 94226b33..6d40dce5 100644
--- a/src/hi/services/homebox/hb_manage_view_pane.py
+++ b/src/hi/services/homebox/hb_manage_view_pane.py
@@ -1,6 +1,5 @@
from typing import Dict
-from hi.apps.entity.models import Entity
from hi.integrations.integration_data import IntegrationData
from hi.integrations.integration_manage_view_pane import IntegrationManageViewPane
@@ -11,9 +10,4 @@ class HbManageViewPane( IntegrationManageViewPane ):
return 'homebox/panes/hb_manage.html'
def get_template_context( self, integration_data : IntegrationData ) -> Dict[ str, object ]:
-
- has_entities = Entity.objects.filter( integration_id = integration_data.integration_id ).exists()
-
- return {
- 'has_entities': has_entities,
- }
+ return {}
diff --git a/src/hi/services/homebox/hb_sync.py b/src/hi/services/homebox/hb_sync.py
index b9cf5da3..16752648 100644
--- a/src/hi/services/homebox/hb_sync.py
+++ b/src/hi/services/homebox/hb_sync.py
@@ -1,14 +1,13 @@
import logging
-from typing import Dict, List
+from typing import Dict, List, Optional
from django.db import transaction
-from hi.apps.common.database_lock import ExclusionLockContext
-from hi.apps.common.processing_result import ProcessingResult
from hi.apps.entity.models import Entity, EntityAttribute
+from hi.integrations.integration_synchronizer import IntegrationSynchronizer
+from hi.integrations.sync_result import IntegrationSyncResult
from hi.integrations.transient_models import IntegrationKey
-from hi.integrations.sync_mixins import IntegrationSyncMixin
from .hb_converter import HbConverter
from .hb_metadata import HbMetaData
@@ -18,30 +17,19 @@ from .hb_models import HbItem
logger = logging.getLogger(__name__)
-class HomeBoxSynchronizer( HomeBoxMixin, IntegrationSyncMixin ):
+class HomeBoxSynchronizer( IntegrationSynchronizer, HomeBoxMixin ):
- SYNCHRONIZATION_LOCK_NAME = 'hb_integration_sync'
-
- def __init__(self):
- return
-
- def sync( self ) -> ProcessingResult:
- try:
- with ExclusionLockContext( name = self.SYNCHRONIZATION_LOCK_NAME ):
- logger.debug( 'HomeBox integration sync started.' )
- return self._sync_helper()
- except RuntimeError as e:
- logger.exception( e )
- return ProcessingResult(
- title = 'HomeBox Import Result',
- error_list = [ str(e) ],
- )
- finally:
- logger.debug( 'HomeBox integration sync ended.' )
+ def get_description(self, is_initial_import: bool) -> Optional[str]:
+ return (
+ 'HomeBox Labels and Locations are kept as metadata on '
+ 'each item, not as separate organizational concepts in HI.'
+ )
- def _sync_helper( self ) -> ProcessingResult:
+ def _sync_impl( self, is_initial_import: bool ) -> IntegrationSyncResult:
hb_manager = self.hb_manager()
- result = ProcessingResult( title = 'HomeBox Import Result' )
+ result = IntegrationSyncResult(
+ title = self.get_result_title( is_initial_import = is_initial_import ),
+ )
if not hb_manager.hb_client:
health_status = hb_manager.health_status
@@ -62,16 +50,29 @@ class HomeBoxSynchronizer( HomeBoxMixin, IntegrationSyncMixin ):
result.error_list.append( f'Cannot sync HomeBox: {e}' )
return result
- result.message_list.append( f'Found {len(item_list)} current HomeBox items.' )
-
- self._sync_helper_entities( item_list = item_list, result = result )
+ result.info_list.append( f'Found {len(item_list)} current HomeBox items.' )
+ # Existing-entity updates do not need re-placement; only
+ # newly-created entities surface in the dispatcher.
+ created_entities = self._sync_helper_entities(
+ item_list = item_list, result = result )
+ if created_entities:
+ result.placement_input = self.group_entities_for_placement(
+ entities = created_entities,
+ )
return result
-
- def _sync_helper_entities( self,
- item_list: List[HbItem],
- result: ProcessingResult ):
-
+
+ # group_entities_for_placement: HomeBox has no domain notion of
+ # grouping, so the base-class default (all-ungrouped) is exactly
+ # what we want. No override needed.
+
+ def _sync_helper_entities( self,
+ item_list: List[HbItem],
+ result: IntegrationSyncResult ) -> List[Entity]:
+ """Sync HomeBox items and return newly-created entities (for
+ the caller to feed into group_entities_for_placement).
+ Existing-entity updates do not contribute — they don't need
+ re-placement."""
integration_key_to_item = dict()
for item in item_list:
try:
@@ -82,8 +83,9 @@ class HomeBoxSynchronizer( HomeBoxMixin, IntegrationSyncMixin ):
continue
integration_key_to_entity = self._get_existing_hb_entities( result = result )
- result.message_list.append( f'Found {len(integration_key_to_entity)} existing HomeBox entities.' )
+ result.info_list.append( f'Found {len(integration_key_to_entity)} existing HomeBox items.' )
+ created_entities: List[Entity] = []
with transaction.atomic():
for integration_key, hb_item in integration_key_to_item.items():
entity = integration_key_to_entity.get( integration_key )
@@ -95,8 +97,9 @@ class HomeBoxSynchronizer( HomeBoxMixin, IntegrationSyncMixin ):
)
else:
entity = self._create_entity( item = hb_item, result = result )
-
- self._sync_helper_entity_attributes(
+ created_entities.append( entity )
+
+ self._sync_helper_entity_attributes(
entity = entity,
hb_item = hb_item,
result = result,
@@ -107,8 +110,9 @@ class HomeBoxSynchronizer( HomeBoxMixin, IntegrationSyncMixin ):
if integration_key not in integration_key_to_item:
self._remove_entity( entity = entity, result = result )
continue
+ return created_entities
- def _get_existing_hb_entities( self, result : ProcessingResult ) -> Dict[ IntegrationKey, Entity ]:
+ def _get_existing_hb_entities( self, result : IntegrationSyncResult ) -> Dict[ IntegrationKey, Entity ]:
logger.debug( 'Getting existing HomeBox entities.' )
integration_key_to_entity = dict()
@@ -116,7 +120,7 @@ class HomeBoxSynchronizer( HomeBoxMixin, IntegrationSyncMixin ):
for entity in entity_queryset:
integration_key = entity.integration_key
if not integration_key:
- result.error_list.append( f'Entity found without valid HomeBox Id: {entity}' )
+ result.error_list.append( f'Item found without valid HomeBox Id: {entity}' )
mock_hb_device_id = 1000000 + entity.id # We need a (unique) placeholder for removals
integration_key = IntegrationKey(
integration_id = HbMetaData.integration_id,
@@ -130,34 +134,35 @@ class HomeBoxSynchronizer( HomeBoxMixin, IntegrationSyncMixin ):
def _create_entity( self,
item : HbItem,
- result : ProcessingResult ) -> Entity:
+ result : IntegrationSyncResult ) -> Entity:
entity = HbConverter.create_models_for_hb_item( hb_item = item )
-
- result.message_list.append( f'Created HomeBox entity: {entity}' )
+ result.created_list.append( entity.name )
return entity
def _update_entity( self,
entity : Entity,
item : HbItem,
- result : ProcessingResult ):
- message_list = HbConverter.update_models_for_hb_item( entity = entity, hb_item = item )
-
- if message_list:
- result.message_list.append( f'Updated HomeBox entity: {entity} ({", ".join(message_list)})' )
- else:
- result.message_list.append( f'No changes found for HomeBox entity: {entity}' )
+ result : IntegrationSyncResult ):
+ # update_models_for_hb_item returns a list of change
+ # description strings — non-empty means at least one
+ # operator-visible change was made.
+ change_messages = HbConverter.update_models_for_hb_item(
+ entity = entity, hb_item = item,
+ )
+ if change_messages and entity.name not in result.updated_list:
+ result.updated_list.append( entity.name )
return
def _remove_entity( self,
entity : Entity,
- result : ProcessingResult ):
+ result : IntegrationSyncResult ):
self._remove_entity_intelligently( entity, result, 'HomeBox' )
return
def _sync_helper_entity_attributes( self,
entity: Entity,
hb_item: HbItem,
- result: ProcessingResult ):
+ result: IntegrationSyncResult ):
attribute_message_list = list()
integration_key_to_regular_field = dict()
@@ -247,12 +252,20 @@ class HomeBoxSynchronizer( HomeBoxMixin, IntegrationSyncMixin ):
del integration_key_to_attr[field_key]
continue
- if attribute_message_list:
- message = (
- f'Updated HomeBox entity attributes: {entity} '
- f'({", ".join(attribute_message_list)})'
- )
- result.message_list.append( message )
+ # An attribute-level change still means this entity was
+ # modified by the sync. Mark it in updated_list (with dedup
+ # against the entity-level path above) so the operator
+ # sees the entity name. Skip the mark when this entity was
+ # just created — its attributes are new because the entity
+ # is new, not because of a refresh-time update. Per-attribute
+ # detail itself stays internal — entity-name granularity is
+ # the contract.
+ if (
+ attribute_message_list
+ and entity.name not in result.created_list
+ and entity.name not in result.updated_list
+ ):
+ result.updated_list.append( entity.name )
return
def _get_existing_hb_attributes( self, entity: Entity ) -> Dict[ IntegrationKey, EntityAttribute ]:
diff --git a/src/hi/services/homebox/integration.py b/src/hi/services/homebox/integration.py
index cef77961..9fd856bb 100644
--- a/src/hi/services/homebox/integration.py
+++ b/src/hi/services/homebox/integration.py
@@ -7,6 +7,7 @@ from hi.apps.system.health_status_provider import HealthStatusProvider
from hi.integrations.integration_controller import IntegrationController
from hi.integrations.integration_gateway import IntegrationGateway
from hi.integrations.integration_manage_view_pane import IntegrationManageViewPane
+from hi.integrations.integration_synchronizer import IntegrationSynchronizer
from hi.integrations.models import IntegrationAttribute
from hi.integrations.transient_models import (
ConnectionTestResult,
@@ -19,6 +20,7 @@ from .hb_controller import HomeBoxController
from .hb_manage_view_pane import HbManageViewPane
from .hb_manager import HomeBoxManager
from .hb_metadata import HbMetaData
+from .hb_sync import HomeBoxSynchronizer
from .monitors import HomeBoxMonitor
logger = logging.getLogger(__name__)
@@ -52,6 +54,9 @@ class HomeBoxGateway(IntegrationGateway):
def get_health_status_provider(self) -> HealthStatusProvider:
return HomeBoxManager()
+ def get_synchronizer(self) -> IntegrationSynchronizer:
+ return HomeBoxSynchronizer()
+
def validate_configuration(
self,
integration_attributes: List[IntegrationAttribute]
diff --git a/src/hi/services/homebox/templates/homebox/panes/hb_manage.html b/src/hi/services/homebox/templates/homebox/panes/hb_manage.html
index fbaad1c4..a29825a7 100644
--- a/src/hi/services/homebox/templates/homebox/panes/hb_manage.html
+++ b/src/hi/services/homebox/templates/homebox/panes/hb_manage.html
@@ -1,31 +1,7 @@
-{% load static %}
-{% load icons %}
-
-<div class="d-flex justify-content-between">
- <div class="h3 integration-title">
- <img class="img-fluid"
- src="{% static core.integration_data.integration_metadata.logo_static_path %}"
- alt="{{ core.integration_data.integration_metadata.label }} Logo">
- {{ core.integration_data.integration_metadata.label }}
- </div>
- <div class="d-flex">
- {% include "integrations/panes/lifecycle_actions.html" %}
- <form action="{% url 'hb_sync' %}"
- method="POST" role="form" data-async="true">
- {% csrf_token %}
- <button type="submit" class="btn btn-outline-secondary" role="button"
- name="action" value="sync" >
- {% if has_entities %}
- {% icon "sync" size="sm" css_class="hi-icon-left" %}RE-SYNC
- {% else %}
- {% icon "upload" size="sm" css_class="hi-icon-left" %}IMPORT
- {% endif %}
- </button>
- </form>
- </div>
-</div>
-{% if not has_entities %}
-<div class="alert alert-warning text-center">
- Use the "IMPORT" button to add items from HomeBox.
-</div>
-{% endif %}
+{% comment %}
+ Integration-specific custom content slot for the HomeBox manage
+ page. The framework owns the page header (title/logo, lifecycle
+ actions, sync actions) and the attribute editor; this template
+ renders any HomeBox-specific UI between them. Currently empty —
+ kept as a documented extension point.
+{% endcomment %}
diff --git a/src/hi/services/homebox/tests/test_hb_client.py b/src/hi/services/homebox/tests/test_hb_client.py
index ee7d5e63..6d7558eb 100644
--- a/src/hi/services/homebox/tests/test_hb_client.py
+++ b/src/hi/services/homebox/tests/test_hb_client.py
@@ -6,7 +6,6 @@ from django.test import SimpleTestCase
from requests import Response
from hi.services.homebox.hb_client import HbClient
-from hi.services.homebox.hb_models import HbItem
logging.disable(logging.CRITICAL)
@@ -131,24 +130,45 @@ class TestHbClient(SimpleTestCase):
client.get_items_summary()
self.assertIn('URL may be incorrect', str(context.exception))
- def test_get_items_fetches_detail_and_skips_invalid_or_failed_items(self):
+ def test_get_items_fetches_detail_for_each_item(self):
+ """Happy path: each summary entry fans out to a detail
+ fetch and the detail responses are wrapped as HbItems.
+ Items with no id are skipped (still safe — the summary
+ is the only signal)."""
with patch.object(HbClient, '_login'):
client = HbClient(api_options=self._api_options())
client._make_request = Mock(side_effect=[
{'items': [{'id': 'item-1'}, {'id': 'item-2'}, {}, {'id': 'item-3'}]},
{'id': 'item-1', 'name': 'One'},
- Exception('detail request failed'),
+ {'id': 'item-2', 'name': 'Two'},
{'id': 'item-3', 'name': 'Three'},
])
items = client.get_items()
- self.assertEqual(len(items), 2)
- self.assertIsInstance(items[0], HbItem)
- self.assertIsInstance(items[1], HbItem)
- self.assertEqual(items[0].id, 'item-1')
- self.assertEqual(items[1].id, 'item-3')
+ self.assertEqual(len(items), 3)
+ self.assertEqual([i.id for i in items], ['item-1', 'item-2', 'item-3'])
+
+ def test_get_items_propagates_detail_fetch_failures(self):
+ """A failed detail fetch propagates rather than being
+ silently dropped: a partial-success outcome here is
+ misinterpreted by the sync layer as upstream removals or a
+ clean 'nothing to import,' which masks real upstream
+ problems. The sync flow's outer try/except converts the
+ propagated error into an ``error_list`` entry."""
+ with patch.object(HbClient, '_login'):
+ client = HbClient(api_options=self._api_options())
+
+ client._make_request = Mock(side_effect=[
+ {'items': [{'id': 'item-1'}, {'id': 'item-2'}]},
+ {'id': 'item-1', 'name': 'One'},
+ Exception('detail request failed'),
+ ])
+
+ with self.assertRaises(Exception) as context:
+ client.get_items()
+ self.assertIn('detail request failed', str(context.exception))
def test_download_attachment_returns_none_when_request_is_not_response(self):
with patch.object(HbClient, '_login'):
diff --git a/src/hi/services/homebox/tests/test_hb_converter.py b/src/hi/services/homebox/tests/test_hb_converter.py
index 7da1d984..d40518cc 100644
--- a/src/hi/services/homebox/tests/test_hb_converter.py
+++ b/src/hi/services/homebox/tests/test_hb_converter.py
@@ -162,3 +162,56 @@ class TestHbConverter(TestCase):
created_attribute.refresh_from_db()
self.assertEqual(created_attribute.order_id, 1)
self.assertEqual(created_attribute.file_value.name, original_name)
+
+
+
+class TestHbConverterPayloadTimestampOmission(TestCase):
+ """Regression coverage for the timestamp-omission contract on
+ ``hb_item_to_entity_payload``.
+
+ Timestamps are deliberately excluded from the payload — they
+ are metadata about *when* a change happened, not *what*
+ changed. Including them caused spurious 'updated' reports on
+ every refresh because real HomeBox can tick ``updatedAt`` for
+ housekeeping events the operator doesn't care about. These
+ tests pin the contract so a future re-add (e.g., 'for
+ completeness') silently re-introducing the bug fails loudly."""
+
+ def _mock_item(self, **api_overrides):
+ api_dict = {
+ 'id': 'item-1',
+ 'name': 'Item 1',
+ 'description': 'desc',
+ 'quantity': 1,
+ 'createdAt': '2026-01-01T00:00:00+00:00',
+ 'updatedAt': '2026-01-01T00:00:00+00:00',
+ 'location': {'id': 'loc-1', 'name': 'Garage'},
+ 'labels': [{'id': 'lab-1', 'name': 'Tools'}],
+ 'fields': [],
+ 'attachments': [],
+ }
+ api_dict.update(api_overrides)
+ return HbItem(api_dict=api_dict, client=Mock())
+
+ def test_payload_excludes_timestamp_keys(self):
+ item = self._mock_item()
+ payload = HbConverter.hb_item_to_entity_payload(hb_item=item)
+ self.assertNotIn('created_at', payload)
+ self.assertNotIn('updated_at', payload)
+
+ def test_payloads_compare_equal_when_only_timestamps_differ(self):
+ """The change-detection signal: two payloads identical
+ except for timestamps must compare equal so a refresh
+ against unchanged upstream content reports zero updates."""
+ earlier = self._mock_item(
+ createdAt='2026-01-01T00:00:00+00:00',
+ updatedAt='2026-01-01T00:00:00+00:00',
+ )
+ later = self._mock_item(
+ createdAt='2026-04-15T12:34:56+00:00',
+ updatedAt='2026-05-04T08:00:00+00:00',
+ )
+ self.assertEqual(
+ HbConverter.hb_item_to_entity_payload(hb_item=earlier),
+ HbConverter.hb_item_to_entity_payload(hb_item=later),
+ )
diff --git a/src/hi/services/homebox/tests/test_hb_sync.py b/src/hi/services/homebox/tests/test_hb_sync.py
index f7c35a49..4d792278 100644
--- a/src/hi/services/homebox/tests/test_hb_sync.py
+++ b/src/hi/services/homebox/tests/test_hb_sync.py
@@ -4,7 +4,7 @@ from unittest.mock import ANY, Mock, patch
from django.test import SimpleTestCase
-from hi.apps.common.processing_result import ProcessingResult
+from hi.integrations.sync_result import IntegrationSyncResult
from hi.integrations.transient_models import IntegrationKey
from hi.services.homebox.hb_metadata import HbMetaData
from hi.services.homebox.hb_sync import HomeBoxSynchronizer
@@ -28,11 +28,11 @@ class TestHomeBoxSynchronizer(SimpleTestCase):
manager.fetch_hb_items_from_api.return_value = [Mock(), Mock(), Mock()]
with patch.object(synchronizer, 'hb_manager', return_value=manager), \
- patch.object(synchronizer, '_sync_helper_entities') as sync_entities_mock:
- result = synchronizer._sync_helper()
+ patch.object(synchronizer, '_sync_helper_entities', return_value=[]) as sync_entities_mock:
+ result = synchronizer._sync_impl(is_initial_import=True)
- self.assertIsInstance(result, ProcessingResult)
- self.assertIn('Found 3 current HomeBox items.', result.message_list)
+ self.assertIsInstance(result, IntegrationSyncResult)
+ self.assertIn('Found 3 current HomeBox items.', result.info_list)
sync_entities_mock.assert_called_once_with(
item_list=manager.fetch_hb_items_from_api.return_value,
result=result,
@@ -40,7 +40,7 @@ class TestHomeBoxSynchronizer(SimpleTestCase):
def test_sync_helper_entities_create_update_remove_entities(self):
synchronizer = HomeBoxSynchronizer()
- result = ProcessingResult(title='HomeBox Import Result')
+ result = IntegrationSyncResult(title='HomeBox Import Result')
item_new = Mock(name='item_new')
item_existing = Mock(name='item_existing')
@@ -135,13 +135,13 @@ class TestHomeBoxSynchronizer(SimpleTestCase):
item_existing,
)
- self.assertIn('Found 2 existing HomeBox entities.', result.message_list)
+ self.assertIn('Found 2 existing HomeBox items.', result.info_list)
self.assertTrue(any('Ignoring HomeBox item due to missing/invalid id' in message
for message in result.error_list))
def test_sync_helper_entity_attributes_create_update_remove_fields_and_attachments(self):
synchronizer = HomeBoxSynchronizer()
- result = ProcessingResult(title='HomeBox Import Result')
+ result = IntegrationSyncResult(title='HomeBox Import Result')
entity = Mock(name='entity')
entity.id = 10
@@ -287,8 +287,69 @@ class TestHomeBoxSynchronizer(SimpleTestCase):
stale_attr.delete.assert_called_once()
foreign_attr.delete.assert_not_called()
- self.assertEqual(len(result.message_list), 1)
- self.assertIn('Updated HomeBox entity attributes', result.message_list[0])
- self.assertIn('Field attribute added: Field New', result.message_list[0])
- self.assertIn('Attachment attribute added: Attachment New', result.message_list[0])
- self.assertIn('Field attribute removed: Stale Field', result.message_list[0])
+ # Per-attribute change detail is no longer surfaced in the
+ # sync result (counts at the entity level capture the
+ # operator-relevant signal). The persistence behavior above
+ # — created/updated/deleted attribute records — remains the
+ # contract this test pins.
+ self.assertEqual(result.info_list, [])
+
+
+class TestHomeBoxSynchronizerSyncResultGrouping(SimpleTestCase):
+ """Phase 2 grouping behavior: HomeBox has no domain notion of
+ grouping, so every imported item lands in `ungrouped_items`.
+ `groups` stays empty. The framework's placement modal decides
+ how to surface ungrouped items at render time."""
+
+ def test_sync_impl_populates_ungrouped_items_only(self):
+ synchronizer = HomeBoxSynchronizer()
+ manager = Mock()
+ manager.hb_client = object()
+ manager.fetch_hb_items_from_api.return_value = [Mock(), Mock()]
+
+ entity_a = Mock()
+ entity_a.name = 'Cordless Drill'
+ entity_a.integration_key = IntegrationKey(
+ integration_id=HbMetaData.integration_id,
+ integration_name='item.42',
+ )
+ entity_a.id = 0
+ entity_b = Mock()
+ entity_b.name = 'Stud Finder'
+ entity_b.integration_key = IntegrationKey(
+ integration_id=HbMetaData.integration_id,
+ integration_name='item.43',
+ )
+ entity_b.id = 0
+
+ with patch.object(synchronizer, 'hb_manager', return_value=manager), \
+ patch.object(synchronizer, '_sync_helper_entities',
+ return_value=[entity_a, entity_b]):
+ result = synchronizer._sync_impl(is_initial_import=True)
+
+ self.assertIsNotNone(result.placement_input)
+ self.assertEqual(result.placement_input.groups, [])
+ self.assertEqual(len(result.placement_input.ungrouped_items), 2)
+ labels = [item.label for item in result.placement_input.ungrouped_items]
+ self.assertEqual(labels, ['Cordless Drill', 'Stud Finder'])
+ keys = [item.key for item in result.placement_input.ungrouped_items]
+ self.assertEqual(
+ keys,
+ [
+ f'{HbMetaData.integration_id}:item.42',
+ f'{HbMetaData.integration_id}:item.43',
+ ],
+ )
+
+ def test_sync_impl_emits_empty_when_no_items_imported(self):
+ synchronizer = HomeBoxSynchronizer()
+ manager = Mock()
+ manager.hb_client = object()
+ manager.fetch_hb_items_from_api.return_value = []
+
+ with patch.object(synchronizer, 'hb_manager', return_value=manager), \
+ patch.object(synchronizer, '_sync_helper_entities', return_value=[]):
+ result = synchronizer._sync_impl(is_initial_import=True)
+
+ # No newly-created entities → placement_input is None.
+ self.assertIsNone(result.placement_input)
diff --git a/src/hi/services/homebox/urls.py b/src/hi/services/homebox/urls.py
index 71f86b4a..4303b860 100644
--- a/src/hi/services/homebox/urls.py
+++ b/src/hi/services/homebox/urls.py
@@ -1,14 +1,17 @@
-from django.urls import re_path
+"""
+Per-integration URL extension point.
-from . import views
+The framework owns lifecycle, configure, sync, and manage URLs for
+every integration (see hi/integrations/urls.py). Add HomeBox-specific
+URLs here when an integration genuinely needs an endpoint the
+framework does not provide. URLs added here mount under
+``services/homebox/``.
+Currently no integration-specific endpoints are required.
+"""
+from django.urls import re_path # noqa: F401
-urlpatterns = [
+from . import views # noqa: F401
- re_path(
- r'^sync$',
- views.HbSyncView.as_view(),
- name='hb_sync',
- ),
-]
+urlpatterns = []
diff --git a/src/hi/services/homebox/views.py b/src/hi/services/homebox/views.py
index 3f1a6e50..90145f7d 100644
--- a/src/hi/services/homebox/views.py
+++ b/src/hi/services/homebox/views.py
@@ -1,17 +1,10 @@
-from hi.hi_async_view import HiModalView
+"""
+Per-integration view extension point.
-from .hb_sync import HomeBoxSynchronizer
+The framework owns lifecycle, configure, sync, and manage views for
+every integration (see hi/integrations/views.py). Define
+HomeBox-specific views here only when an integration genuinely needs
+UI the framework does not provide.
-
-class HbSyncView( HiModalView ):
-
- def get_template_name( self ) -> str:
- return 'common/modals/processing_result.html'
-
- def post(self, request, *args, **kwargs):
-
- processing_result = HomeBoxSynchronizer().sync()
- context = {
- 'processing_result': processing_result,
- }
- return self.modal_response( request, context )
+Currently no integration-specific views are required.
+"""
diff --git a/src/hi/services/zoneminder/integration.py b/src/hi/services/zoneminder/integration.py
index a92171f5..770c7bc1 100644
--- a/src/hi/services/zoneminder/integration.py
+++ b/src/hi/services/zoneminder/integration.py
@@ -12,6 +12,7 @@ from hi.apps.system.health_status_provider import HealthStatusProvider
from hi.integrations.integration_controller import IntegrationController
from hi.integrations.integration_gateway import IntegrationGateway
from hi.integrations.integration_manage_view_pane import IntegrationManageViewPane
+from hi.integrations.integration_synchronizer import IntegrationSynchronizer
from hi.integrations.models import IntegrationAttribute
from hi.integrations.transient_models import (
ConnectionTestResult,
@@ -25,6 +26,7 @@ from .zm_controller import ZoneMinderController
from .zm_manage_view_pane import ZmManageViewPane
from .zm_manager import ZoneMinderManager
from .zm_metadata import ZmMetaData
+from .zm_sync import ZoneMinderSynchronizer
from .monitors import ZoneMinderMonitor
from .zm_mixins import ZoneMinderMixin
@@ -59,7 +61,10 @@ class ZoneMinderGateway( IntegrationGateway, ZoneMinderMixin ):
def get_health_status_provider(self) -> HealthStatusProvider:
return ZoneMinderManager()
-
+
+ def get_synchronizer(self) -> IntegrationSynchronizer:
+ return ZoneMinderSynchronizer()
+
def validate_configuration(
self,
integration_attributes: List[IntegrationAttribute]
diff --git a/src/hi/services/zoneminder/templates/zoneminder/panes/zm_manage.html b/src/hi/services/zoneminder/templates/zoneminder/panes/zm_manage.html
index 7d5b36b3..27f14470 100644
--- a/src/hi/services/zoneminder/templates/zoneminder/panes/zm_manage.html
+++ b/src/hi/services/zoneminder/templates/zoneminder/panes/zm_manage.html
@@ -1,31 +1,7 @@
-{% load static %}
-{% load icons %}
-
-<div class="d-flex justify-content-between">
- <div class="h3 integration-title">
- <img class="img-fluid"
- src="{% static core.integration_data.integration_metadata.logo_static_path %}"
- alt="{{ core.integration_data.integration_metadata.label }} Logo">
- {{ core.integration_data.integration_metadata.label }}
- </div>
- <div class="d-flex">
- {% include "integrations/panes/lifecycle_actions.html" %}
- <form action="{% url 'zm_sync' %}"
- method="POST" role="form" data-async="">
- {% csrf_token %}
- <button type="submit" class="btn btn btn-outline-secondary" role="button"
- name="action" value="sync" >
- {% if has_entities %}
- {% icon "sync" size="sm" css_class="hi-icon-left" %}RE-SYNC
- {% else %}
- {% icon "upload" size="sm" css_class="hi-icon-left" %}IMPORT
- {% endif %}
- </button>
- </form>
- </div>
-</div>
-{% if not has_entities %}
-<div class="alert alert-warning text-center">
- Use the "IMPORT" button to add items from ZoneMinder.
-</div>
-{% endif %}
+{% comment %}
+ Integration-specific custom content slot for the ZoneMinder manage
+ page. The framework owns the page header (title/logo, lifecycle
+ actions, sync actions) and the attribute editor; this template
+ renders any ZM-specific UI between them. Currently empty — kept as
+ a documented extension point.
+{% endcomment %}
diff --git a/src/hi/services/zoneminder/tests/test_zm_sync.py b/src/hi/services/zoneminder/tests/test_zm_sync.py
index 705e83d5..78c658fa 100644
--- a/src/hi/services/zoneminder/tests/test_zm_sync.py
+++ b/src/hi/services/zoneminder/tests/test_zm_sync.py
@@ -4,10 +4,10 @@ import os
from unittest.mock import Mock, patch, call
from django.test import TestCase
-from hi.apps.common.processing_result import ProcessingResult
from hi.apps.entity.models import Entity
from hi.apps.sense.models import Sensor
+from hi.integrations.sync_result import IntegrationSyncResult
from hi.integrations.transient_models import IntegrationKey
from hi.services.zoneminder.zm_sync import ZoneMinderSynchronizer
@@ -22,7 +22,7 @@ class TestZoneMinderSynchronizerLockBehavior(TestCase):
def setUp(self):
self.synchronizer = ZoneMinderSynchronizer()
- @patch('hi.services.zoneminder.zm_sync.ExclusionLockContext')
+ @patch('hi.integrations.integration_synchronizer.ExclusionLockContext')
def test_sync_uses_exclusion_lock(self, mock_lock_context):
"""Test sync method uses exclusion lock and returns sync results"""
# Mock a successful lock context
@@ -34,31 +34,31 @@ class TestZoneMinderSynchronizerLockBehavior(TestCase):
mock_manager.zm_client = None
self.synchronizer._zm_manager = mock_manager
- result = self.synchronizer.sync()
+ result = self.synchronizer.sync(is_initial_import=True)
# Test lock usage
- mock_lock_context.assert_called_once_with(name='zm_integration_sync')
+ mock_lock_context.assert_called_once_with(name='integrations_sync')
# Test actual behavior: should return result with error when client disabled
- self.assertEqual(result.title, 'ZM Import Result')
+ self.assertEqual(result.title, 'Import Result')
self.assertGreater(len(result.error_list), 0)
self.assertIn('Sync problem. ZM integration disabled?', result.error_list[0])
- @patch('hi.services.zoneminder.zm_sync.ExclusionLockContext')
+ @patch('hi.integrations.integration_synchronizer.ExclusionLockContext')
def test_sync_handles_lock_runtime_error(self, mock_lock_context):
"""Test sync method handles RuntimeError from lock context and returns proper error result"""
lock_error_msg = "Lock acquisition failed"
mock_lock_context.side_effect = RuntimeError(lock_error_msg)
- result = self.synchronizer.sync()
+ result = self.synchronizer.sync(is_initial_import=True)
# Test error handling behavior
- self.assertEqual(result.title, 'ZM Import Result')
+ self.assertEqual(result.title, 'Import Result')
self.assertEqual(len(result.error_list), 1)
self.assertIn(lock_error_msg, result.error_list[0])
# Test that no sync operations were attempted
- self.assertEqual(len(result.message_list), 0)
+ self.assertEqual(len(result.info_list), 0)
# Test that result is properly formed for error condition
self.assertIsNotNone(result.title)
@@ -75,42 +75,44 @@ class TestZoneMinderSynchronizerSyncHelper(TestCase):
self.mock_manager = Mock()
self.synchronizer._zm_manager = self.mock_manager
- def test_sync_helper_client_not_available(self):
+ def test_sync_impl_client_not_available(self):
"""Test sync helper handles missing ZM client gracefully"""
self.mock_manager.zm_client = None
- result = self.synchronizer._sync_helper()
+ result = self.synchronizer._sync_impl(is_initial_import=True)
- self.assertEqual(result.title, 'ZM Import Result')
+ self.assertEqual(result.title, 'Import Result')
self.assertIn('Sync problem. ZM integration disabled?', result.error_list[0])
- def test_sync_helper_calls_both_sync_methods(self):
+ def test_sync_impl_calls_both_sync_methods(self):
"""Test sync helper coordinates state and monitor sync and aggregates their results"""
self.mock_manager.zm_client = Mock() # Client available
- # Mock the sync methods to simulate successful operations
+ # Mock the sync methods to simulate successful operations.
+ # _sync_monitors now returns the list of imported entities so
+ # the caller can assemble the "Monitors" group.
def mock_sync_states(result):
- result.message_list.append('States synced successfully')
+ result.info_list.append('States synced successfully')
return result
-
+
def mock_sync_monitors(result):
- result.message_list.append('Monitors synced successfully')
- return result
+ result.info_list.append('Monitors synced successfully')
+ return []
# Patch the methods to track their execution and simulate behavior
with patch.object(self.synchronizer, '_sync_states', side_effect=mock_sync_states) as mock_sync_states, \
patch.object(self.synchronizer, '_sync_monitors', side_effect=mock_sync_monitors) as mock_sync_monitors:
- result = self.synchronizer._sync_helper()
+ result = self.synchronizer._sync_impl(is_initial_import=True)
# Test coordination: both methods called with same result
mock_sync_states.assert_called_once()
mock_sync_monitors.assert_called_once()
# Test result aggregation: messages from both operations
- self.assertEqual(result.title, 'ZM Import Result')
- self.assertIn('States synced successfully', result.message_list)
- self.assertIn('Monitors synced successfully', result.message_list)
+ self.assertEqual(result.title, 'Import Result')
+ self.assertIn('States synced successfully', result.info_list)
+ self.assertIn('Monitors synced successfully', result.info_list)
# Test that sync_states was called before sync_monitors
self.assertEqual(mock_sync_states.call_args[1]['result'], result)
@@ -157,7 +159,7 @@ class TestZoneMinderSynchronizerStateSync(TestCase):
# Simulate the actual behavior of _create_zm_entity
def mock_create_behavior(run_state_name_label_dict, result):
- result.message_list.append(f'Created ZM entity: {mock_created_entity}')
+ result.info_list.append(f'Created ZM entity: {mock_created_entity}')
return mock_created_entity
mock_create_entity.side_effect = mock_create_behavior
@@ -169,7 +171,7 @@ class TestZoneMinderSynchronizerStateSync(TestCase):
mock_sensor.entity_state = mock_entity_state
mock_sensor_filter.return_value.select_related.return_value.first.return_value = mock_sensor
- result = ProcessingResult(title='Test')
+ result = IntegrationSyncResult(title='Test')
self.synchronizer._sync_states(result)
# Verify entity creation was called with correct parameters
@@ -179,7 +181,7 @@ class TestZoneMinderSynchronizerStateSync(TestCase):
self.assertEqual(call_args[1]['run_state_name_label_dict'], expected_dict)
# Verify result contains creation information
- self.assertGreater(len(result.message_list), 0)
+ self.assertGreater(len(result.info_list), 0)
# Test behavior: should not have errors when successful
self.assertEqual(len(result.error_list), 0)
@@ -200,7 +202,7 @@ class TestZoneMinderSynchronizerStateSync(TestCase):
# No sensor found
mock_sensor_filter.return_value.select_related.return_value.first.return_value = None
- result = ProcessingResult(title='Test')
+ result = IntegrationSyncResult(title='Test')
returned_result = self.synchronizer._sync_states(result)
# Test behavior: function should handle error gracefully
@@ -209,7 +211,7 @@ class TestZoneMinderSynchronizerStateSync(TestCase):
# Should return early without processing further
self.assertIsNone(returned_result)
# Should not have created any entities since sensor missing
- self.assertEqual(len(result.message_list), 0)
+ self.assertEqual(len(result.info_list), 0)
@patch.object(Entity.objects, 'filter_by_integration_key')
@patch.object(Sensor.objects, 'filter_by_integration_key')
@@ -236,7 +238,7 @@ class TestZoneMinderSynchronizerStateSync(TestCase):
mock_sensor.name = 'ZM Run State'
mock_sensor_filter.return_value.select_related.return_value.first.return_value = mock_sensor
- result = ProcessingResult(title='Test')
+ result = IntegrationSyncResult(title='Test')
self.synchronizer._sync_states(result)
# Test actual state transformation
@@ -251,9 +253,9 @@ class TestZoneMinderSynchronizerStateSync(TestCase):
# Test successful processing behavior
self.assertEqual(len(result.error_list), 0)
- self.assertGreater(len(result.message_list), 0)
+ self.assertGreater(len(result.info_list), 0)
# Verify the state dict is included in the message for debugging
- message = result.message_list[0]
+ message = result.info_list[0]
self.assertIn('Updated ZM state values to:', message)
self.assertIn('start', message)
self.assertIn('pause', message)
@@ -284,7 +286,7 @@ class TestZoneMinderSynchronizerStateSync(TestCase):
mock_sensor.name = 'ZM Run State'
mock_sensor_filter.return_value.select_related.return_value.first.return_value = mock_sensor
- result = ProcessingResult(title='Test')
+ result = IntegrationSyncResult(title='Test')
self.synchronizer._sync_states(result)
# Test no persistence when no changes
@@ -297,7 +299,7 @@ class TestZoneMinderSynchronizerStateSync(TestCase):
self.assertEqual(len(result.error_list), 0)
# Test no update messages generated
- update_messages = [msg for msg in result.message_list if 'Updated ZM state values' in msg]
+ update_messages = [msg for msg in result.info_list if 'Updated ZM state values' in msg]
self.assertEqual(len(update_messages), 0)
@@ -323,15 +325,15 @@ class TestZoneMinderSynchronizerMonitorSync(TestCase):
# Mock the individual sync methods to test coordination
def mock_fetch_monitors(result):
- result.message_list.append('Fetched 1 monitor from ZM')
+ result.info_list.append('Fetched 1 monitor from ZM')
return {integration_key: mock_monitor}
def mock_get_existing(result):
- result.message_list.append('Found 0 existing entities')
+ result.info_list.append('Found 0 existing items')
return {}
def mock_create_entity(zm_monitor, result):
- result.message_list.append(f'Created entity for monitor {zm_monitor.name.return_value}')
+ result.info_list.append(f'Created entity for monitor {zm_monitor.name.return_value}')
return Mock()
with patch.object(self.synchronizer, '_fetch_zm_monitors', side_effect=mock_fetch_monitors), \
@@ -340,7 +342,7 @@ class TestZoneMinderSynchronizerMonitorSync(TestCase):
patch.object(self.synchronizer, '_update_entity') as mock_update, \
patch.object(self.synchronizer, '_remove_entity') as mock_remove:
- result = ProcessingResult(title='Test')
+ result = IntegrationSyncResult(title='Test')
self.synchronizer._sync_monitors(result)
# Test creation path was taken
@@ -349,9 +351,9 @@ class TestZoneMinderSynchronizerMonitorSync(TestCase):
mock_remove.assert_not_called()
# Test result aggregation from all sync phases
- self.assertIn('Fetched 1 monitor from ZM', result.message_list)
- self.assertIn('Found 0 existing entities', result.message_list)
- self.assertIn('Created entity for monitor Test Camera', result.message_list)
+ self.assertIn('Fetched 1 monitor from ZM', result.info_list)
+ self.assertIn('Found 0 existing items', result.info_list)
+ self.assertIn('Created entity for monitor Test Camera', result.info_list)
# Test no errors in successful creation scenario
self.assertEqual(len(result.error_list), 0)
@@ -370,7 +372,7 @@ class TestZoneMinderSynchronizerMonitorSync(TestCase):
mock_fetch.return_value = {integration_key: mock_monitor}
mock_get_existing.return_value = {integration_key: mock_entity}
- result = ProcessingResult(title='Test')
+ result = IntegrationSyncResult(title='Test')
self.synchronizer._sync_monitors(result)
mock_update.assert_called_once_with(entity=mock_entity, zm_monitor=mock_monitor, result=result)
@@ -387,15 +389,15 @@ class TestZoneMinderSynchronizerMonitorSync(TestCase):
# Mock the individual sync methods to test coordination
def mock_fetch_monitors(result):
- result.message_list.append('Fetched 0 monitors from ZM')
+ result.info_list.append('Fetched 0 monitors from ZM')
return {} # No current monitors
def mock_get_existing(result):
- result.message_list.append('Found 1 existing entity')
+ result.info_list.append('Found 1 existing item')
return {integration_key: mock_entity}
def mock_remove_entity(entity, result):
- result.message_list.append(f'Removed stale entity {entity.name}')
+ result.info_list.append(f'Removed stale entity {entity.name}')
with patch.object(self.synchronizer, '_fetch_zm_monitors', side_effect=mock_fetch_monitors), \
patch.object(self.synchronizer, '_get_existing_zm_monitor_entities', side_effect=mock_get_existing), \
@@ -403,7 +405,7 @@ class TestZoneMinderSynchronizerMonitorSync(TestCase):
patch.object(self.synchronizer, '_update_entity') as mock_update, \
patch.object(self.synchronizer, '_remove_entity', side_effect=mock_remove_entity) as mock_remove:
- result = ProcessingResult(title='Test')
+ result = IntegrationSyncResult(title='Test')
self.synchronizer._sync_monitors(result)
# Test removal path was taken
@@ -412,9 +414,9 @@ class TestZoneMinderSynchronizerMonitorSync(TestCase):
mock_update.assert_not_called()
# Test result tracking for cleanup scenario
- self.assertIn('Fetched 0 monitors from ZM', result.message_list)
- self.assertIn('Found 1 existing entity', result.message_list)
- self.assertIn('Removed stale entity Deleted Camera', result.message_list)
+ self.assertIn('Fetched 0 monitors from ZM', result.info_list)
+ self.assertIn('Found 1 existing item', result.info_list)
+ self.assertIn('Removed stale entity Deleted Camera', result.info_list)
# Test no errors in successful removal scenario
self.assertEqual(len(result.error_list), 0)
@@ -446,7 +448,7 @@ class TestZoneMinderSynchronizerFetchMonitors(TestCase):
key2 = IntegrationKey(integration_id='zm', integration_name='monitor.456')
self.mock_manager._to_integration_key.side_effect = [key1, key2]
- result = ProcessingResult(title='Test')
+ result = IntegrationSyncResult(title='Test')
result_dict = self.synchronizer._fetch_zm_monitors(result)
# Should call integration key generation for each monitor
@@ -465,7 +467,7 @@ class TestZoneMinderSynchronizerFetchMonitors(TestCase):
"""Test _fetch_zm_monitors forces reload of monitor data"""
self.mock_manager.get_zm_monitors.return_value = []
- result = ProcessingResult(title='Test')
+ result = IntegrationSyncResult(title='Test')
self.synchronizer._fetch_zm_monitors(result)
self.mock_manager.get_zm_monitors.assert_called_once_with(force_load=True)
@@ -487,7 +489,7 @@ class TestZoneMinderSynchronizerExistingEntities(TestCase):
"""Test _get_existing_zm_monitor_entities filters by correct integration ID"""
mock_filter.return_value = []
- result = ProcessingResult(title='Test')
+ result = IntegrationSyncResult(title='Test')
self.synchronizer._get_existing_zm_monitor_entities(result)
mock_filter.assert_called_once_with(integration_id=ZmMetaData.integration_id)
@@ -501,11 +503,11 @@ class TestZoneMinderSynchronizerExistingEntities(TestCase):
mock_entity.integration_key = None
mock_filter.return_value = [mock_entity]
- result = ProcessingResult(title='Test')
+ result = IntegrationSyncResult(title='Test')
result_dict = self.synchronizer._get_existing_zm_monitor_entities(result)
# Should add error message
- self.assertIn('ZM entity found without integration name', result.error_list[0])
+ self.assertIn('ZM item found without integration name', result.error_list[0])
# Should NOT include entity in result (mock key doesn't start with 'monitor' prefix)
self.assertEqual(len(result_dict), 0)
@@ -524,7 +526,7 @@ class TestZoneMinderSynchronizerExistingEntities(TestCase):
mock_filter.return_value = [mock_monitor_entity, mock_other_entity]
- result = ProcessingResult(title='Test')
+ result = IntegrationSyncResult(title='Test')
result_dict = self.synchronizer._get_existing_zm_monitor_entities(result)
# Should only include monitor entity
@@ -563,7 +565,7 @@ class TestZoneMinderSynchronizerEntityCreation(TestCase):
integration_id='zm', integration_name='run.state'
)
- result = ProcessingResult(title='Test')
+ result = IntegrationSyncResult(title='Test')
self.synchronizer._create_zm_entity(run_state_dict, result)
mock_atomic.assert_called_once()
@@ -600,7 +602,7 @@ class TestZoneMinderSynchronizerEntityCreation(TestCase):
mock_movement_sensor.entity_state = Mock()
mock_create_movement.return_value = mock_movement_sensor
- result = ProcessingResult(title='Test')
+ result = IntegrationSyncResult(title='Test')
self.synchronizer._create_monitor_entity(mock_monitor, result)
# Should create all components
@@ -635,7 +637,7 @@ class TestZoneMinderSynchronizerEntityCreation(TestCase):
mock_movement_sensor = Mock()
mock_create_movement.return_value = mock_movement_sensor
- result = ProcessingResult(title='Test')
+ result = IntegrationSyncResult(title='Test')
self.synchronizer._create_monitor_entity(mock_monitor, result)
# Should not create event
@@ -667,7 +669,7 @@ class TestZoneMinderSynchronizerEntityUpdate(TestCase):
mock_monitor.name.return_value = 'New Name'
mock_monitor.id.return_value = 456
- result = ProcessingResult(title='Test')
+ result = IntegrationSyncResult(title='Test')
self.synchronizer._update_entity(mock_entity, mock_monitor, result)
# Test name update behavior
@@ -680,13 +682,11 @@ class TestZoneMinderSynchronizerEntityUpdate(TestCase):
self.assertEqual(mock_entity.can_user_delete, True) # User delete flag unchanged
self.assertEqual(mock_entity.integration_key, original_integration_key) # Integration key unchanged
- # Test result tracking
+ # Rename surfaces the old → new transition in updated_list
+ # (operator can see both names at a glance).
self.assertEqual(len(result.error_list), 0)
- self.assertGreater(len(result.message_list), 0)
- update_message = result.message_list[0]
- self.assertIn('Name changed for', update_message)
- self.assertIn('New Name', update_message)
-
+ self.assertEqual(result.updated_list, ['Old Name → New Name'])
+
def test_update_entity_no_change_when_name_same(self):
"""Test _update_entity doesn't save when name unchanged and preserves all entity state"""
mock_entity = Mock()
@@ -694,30 +694,21 @@ class TestZoneMinderSynchronizerEntityUpdate(TestCase):
mock_entity.id = 789
mock_entity.entity_type_str = 'CAMERA'
mock_entity.save = Mock()
-
+
mock_monitor = Mock()
mock_monitor.name.return_value = 'Same Name'
mock_monitor.id.return_value = 999
-
- result = ProcessingResult(title='Test')
+
+ result = IntegrationSyncResult(title='Test')
self.synchronizer._update_entity(mock_entity, mock_monitor, result)
-
- # Test no persistence when no changes
+
+ # Test no persistence when no changes.
mock_entity.save.assert_not_called()
-
- # Test complete state preservation
- self.assertEqual(mock_entity.name, 'Same Name') # Name unchanged
- self.assertEqual(mock_entity.id, 789) # ID unchanged
- self.assertEqual(mock_entity.entity_type_str, 'CAMERA') # Type unchanged
-
- # Test result tracking for no-change scenario
+
+ # No-change path appends nothing and surfaces nothing.
self.assertEqual(len(result.error_list), 0)
- self.assertGreater(len(result.message_list), 0)
- no_change_message = result.message_list[0]
- self.assertIn('No changes found for', no_change_message)
-
- # Test that the entity object itself is referenced in the message
- self.assertIn(str(mock_entity), no_change_message)
+ self.assertEqual(result.updated_list, [])
+ self.assertEqual(result.info_list, [])
class TestZoneMinderSynchronizerEntityRemoval(TestCase):
@@ -730,7 +721,7 @@ class TestZoneMinderSynchronizerEntityRemoval(TestCase):
def test_remove_entity_calls_intelligent_deletion(self, mock_intelligent_removal):
"""Test _remove_entity calls intelligent deletion with correct parameters"""
mock_entity = Mock()
- result = ProcessingResult(title='Test')
+ result = IntegrationSyncResult(title='Test')
self.synchronizer._remove_entity(mock_entity, result)
@@ -828,14 +819,14 @@ class TestZoneMinderSynchronizerWithRealData(TestCase):
integration_id='zm', integration_name='run.state'
)
- result = ProcessingResult(title='Test')
+ result = IntegrationSyncResult(title='Test')
self.synchronizer._sync_states(result)
# Should update to real state names
expected_states = {'default': 'default', 'Away': 'Away', 'HomeDay': 'HomeDay', 'Disabled': 'Disabled'}
self.assertEqual(mock_entity_state.value_range_dict, expected_states)
mock_entity_state.save.assert_called_once()
- self.assertIn('Updated ZM state values to:', result.message_list[0])
+ self.assertIn('Updated ZM state values to:', result.info_list[0])
@patch.object(ZoneMinderSynchronizer, '_fetch_zm_monitors')
@patch.object(ZoneMinderSynchronizer, '_get_existing_zm_monitor_entities')
@@ -858,7 +849,7 @@ class TestZoneMinderSynchronizerWithRealData(TestCase):
mock_fetch.return_value = integration_key_to_monitor
mock_get_existing.return_value = {} # No existing entities
- result = ProcessingResult(title='Test')
+ result = IntegrationSyncResult(title='Test')
self.synchronizer._sync_monitors(result)
# Should create entities for all real monitors
@@ -906,13 +897,13 @@ class TestZoneMinderSynchronizerWithRealData(TestCase):
# Use real monitor data
real_monitor = self.create_mock_monitors_from_real_data()[0] # HighCamera
- result = ProcessingResult(title='Test')
+ result = IntegrationSyncResult(title='Test')
self.synchronizer._update_entity(mock_entity, real_monitor, result)
# Should update to real name from ZM API
self.assertEqual(mock_entity.name, 'HighCamera')
mock_entity.save.assert_called_once()
- self.assertIn('Name changed for', result.message_list[0])
+ self.assertEqual(result.updated_list, ['Camera_001 → HighCamera'])
@patch.object(Entity.objects, 'filter')
def test_get_existing_entities_with_real_monitor_id_patterns(self, mock_filter):
@@ -938,14 +929,14 @@ class TestZoneMinderSynchronizerWithRealData(TestCase):
mock_filter.return_value = mock_entities
- result = ProcessingResult(title='Test')
+ result = IntegrationSyncResult(title='Test')
result_dict = self.synchronizer._get_existing_zm_monitor_entities(result)
# Should find 4 valid monitor entities (broken entity is filtered out)
self.assertEqual(len(result_dict), 4)
# Should have error message for broken entity
- self.assertIn('ZM entity found without integration name', result.error_list[0])
+ self.assertIn('ZM item found without integration name', result.error_list[0])
# Should include all real monitor integration keys
integration_names = [key.integration_name for key in result_dict.keys()]
@@ -1009,7 +1000,7 @@ class TestZoneMinderSynchronizerWithRealData(TestCase):
mock_create_controller.reset_mock()
mock_create_event.reset_mock()
- result = ProcessingResult(title='Test')
+ result = IntegrationSyncResult(title='Test')
self.synchronizer._create_monitor_entity(monitor, result)
# Should create all components for each monitor
@@ -1023,5 +1014,57 @@ class TestZoneMinderSynchronizerWithRealData(TestCase):
# Should use transaction
mock_atomic.assert_called()
- # Should log creation
- self.assertIn('Create new camera entity:', result.message_list[0])
+ # Creation records the entity name in created_list.
+ self.assertEqual(len(result.created_list), 1)
+
+
+class TestZoneMinderSynchronizerSyncResultGrouping(TestCase):
+ """Phase 2 grouping behavior: every imported monitor entity goes
+ into a single 'Monitors' group on the IntegrationSyncResult.
+
+ The single-group choice reflects the typical ZM UX — operators
+ place all cameras into the same view — while the placement
+ modal's drill-down still allows per-monitor placement when needed."""
+
+ def setUp(self):
+ self.synchronizer = ZoneMinderSynchronizer()
+ self.mock_manager = Mock()
+ self.mock_manager.zm_client = Mock()
+ self.synchronizer._zm_manager = self.mock_manager
+
+ def _imported_entity(self, name, integration_name):
+ entity = Mock()
+ entity.name = name
+ entity.integration_key = IntegrationKey(
+ integration_id='zm',
+ integration_name=integration_name,
+ )
+ entity.id = 0
+ return entity
+
+ def test_sync_impl_emits_single_monitors_group(self):
+ entity_a = self._imported_entity('Front Door', 'monitor.1')
+ entity_b = self._imported_entity('Driveway', 'monitor.2')
+ with patch.object(self.synchronizer, '_sync_states'), \
+ patch.object(self.synchronizer, '_sync_monitors',
+ return_value=[entity_a, entity_b]):
+ result = self.synchronizer._sync_impl(is_initial_import=True)
+
+ self.assertIsNotNone(result.placement_input)
+ self.assertEqual(result.placement_input.ungrouped_items, [])
+ self.assertEqual(len(result.placement_input.groups), 1)
+ group = result.placement_input.groups[0]
+ self.assertEqual(group.label, 'Monitors')
+ self.assertEqual([item.entity for item in group.items], [entity_a, entity_b])
+ # Stable per-item key built from the integration_key.
+ self.assertEqual(group.items[0].key, 'zm:monitor.1')
+ self.assertEqual(group.items[1].key, 'zm:monitor.2')
+
+ def test_sync_impl_emits_no_placement_input_when_no_monitors_imported(self):
+ with patch.object(self.synchronizer, '_sync_states'), \
+ patch.object(self.synchronizer, '_sync_monitors', return_value=[]):
+ result = self.synchronizer._sync_impl(is_initial_import=True)
+
+ # No newly-created entities → no placement input → placement
+ # modal is not shown.
+ self.assertIsNone(result.placement_input)
diff --git a/src/hi/services/zoneminder/urls.py b/src/hi/services/zoneminder/urls.py
index 3acc8bd3..5170f9e6 100644
--- a/src/hi/services/zoneminder/urls.py
+++ b/src/hi/services/zoneminder/urls.py
@@ -1,13 +1,17 @@
+"""
+Per-integration URL extension point.
-from django.urls import re_path
+The framework owns lifecycle, configure, sync, and manage URLs for
+every integration (see hi/integrations/urls.py). Add
+ZoneMinder-specific URLs here when an integration genuinely needs an
+endpoint the framework does not provide. URLs added here mount under
+``services/zoneminder/``.
-from . import views
+Currently no integration-specific endpoints are required.
+"""
+from django.urls import re_path # noqa: F401
+from . import views # noqa: F401
-urlpatterns = [
- re_path( r'^sync$',
- views.ZmSyncView.as_view(),
- name='zm_sync' ),
-
-]
+urlpatterns = []
diff --git a/src/hi/services/zoneminder/views.py b/src/hi/services/zoneminder/views.py
index 1deffaf0..251f7e2a 100644
--- a/src/hi/services/zoneminder/views.py
+++ b/src/hi/services/zoneminder/views.py
@@ -1,17 +1,10 @@
-from hi.hi_async_view import HiModalView
+"""
+Per-integration view extension point.
-from .zm_sync import ZoneMinderSynchronizer
+The framework owns lifecycle, configure, sync, and manage views for
+every integration (see hi/integrations/views.py). Define
+ZoneMinder-specific views here only when an integration genuinely
+needs UI the framework does not provide.
-
-class ZmSyncView( HiModalView ):
-
- def get_template_name( self ) -> str:
- return 'common/modals/processing_result.html'
-
- def post(self, request, *args, **kwargs):
-
- processing_result = ZoneMinderSynchronizer().sync()
- context = {
- 'processing_result': processing_result,
- }
- return self.modal_response( request, context )
+Currently no integration-specific views are required.
+"""
diff --git a/src/hi/services/zoneminder/zm_manage_view_pane.py b/src/hi/services/zoneminder/zm_manage_view_pane.py
index 3d3432e3..fe02fb61 100644
--- a/src/hi/services/zoneminder/zm_manage_view_pane.py
+++ b/src/hi/services/zoneminder/zm_manage_view_pane.py
@@ -1,6 +1,5 @@
from typing import Dict
-from hi.apps.entity.models import Entity
from hi.integrations.integration_data import IntegrationData
from hi.integrations.integration_manage_view_pane import IntegrationManageViewPane
@@ -11,9 +10,4 @@ class ZmManageViewPane( IntegrationManageViewPane ):
return 'zoneminder/panes/zm_manage.html'
def get_template_context( self, integration_data : IntegrationData ) -> Dict[ str, object ]:
-
- has_entities = Entity.objects.filter( integration_id = integration_data.integration_id ).exists()
-
- return {
- 'has_entities': has_entities,
- }
+ return {}
diff --git a/src/hi/services/zoneminder/zm_sync.py b/src/hi/services/zoneminder/zm_sync.py
index e358b7f6..5662519f 100644
--- a/src/hi/services/zoneminder/zm_sync.py
+++ b/src/hi/services/zoneminder/zm_sync.py
@@ -1,19 +1,24 @@
import logging
from .pyzm_client.helpers.Monitor import Monitor as ZmMonitor
-from typing import Dict
+from typing import Dict, Optional
from django.db import transaction
-from hi.apps.common.database_lock import ExclusionLockContext
-from hi.apps.common.processing_result import ProcessingResult
from hi.apps.entity.enums import EntityType
from hi.apps.entity.models import Entity
from hi.apps.sense.models import Sensor
from hi.apps.model_helper import HiModelHelper
+from hi.apps.entity.entity_placement import (
+ EntityPlacementInput,
+ EntityPlacementItem,
+ EntityPlacementGroup,
+)
+
+from hi.integrations.integration_synchronizer import IntegrationSynchronizer
+from hi.integrations.sync_result import IntegrationSyncResult
from hi.integrations.transient_models import IntegrationKey
-from hi.integrations.sync_mixins import IntegrationSyncMixin
from .zm_metadata import ZmMetaData
from .zm_mixins import ZoneMinderMixin
@@ -21,9 +26,7 @@ from .zm_mixins import ZoneMinderMixin
logger = logging.getLogger(__name__)
-class ZoneMinderSynchronizer( ZoneMinderMixin, IntegrationSyncMixin ):
-
- SYNCHRONIZATION_LOCK_NAME = 'zm_integration_sync'
+class ZoneMinderSynchronizer( IntegrationSynchronizer, ZoneMinderMixin ):
MONITOR_FUNCTION_NAME_LABEL_DICT = {
'None': 'None',
@@ -33,37 +36,59 @@ class ZoneMinderSynchronizer( ZoneMinderMixin, IntegrationSyncMixin ):
'Mocord': 'Mocord',
'Nodect': 'Nodect',
}
-
- def __init__(self):
- return
-
- def sync( self ) -> ProcessingResult:
- try:
- with ExclusionLockContext( name = self.SYNCHRONIZATION_LOCK_NAME ):
- logger.debug( 'ZoneMinder integration sync started.' )
- return self._sync_helper()
- except RuntimeError as e:
- return ProcessingResult(
- title = 'ZM Import Result',
- error_list = [ str(e) ],
+
+ def get_description(self, is_initial_import: bool) -> Optional[str]:
+ if is_initial_import:
+ return (
+ 'Each monitor becomes a camera with motion and'
+ ' run-state sensors.'
)
- finally:
- logger.debug( 'ZoneMinder integration sync ended.' )
-
- def _sync_helper( self ) -> ProcessingResult:
- result = ProcessingResult( title = 'ZM Import Result' )
+ return None
+
+ def _sync_impl( self, is_initial_import: bool ) -> IntegrationSyncResult:
+ result = IntegrationSyncResult(
+ title = self.get_result_title( is_initial_import = is_initial_import ),
+ )
if not self.zm_manager().zm_client:
logger.debug( 'ZoneMinder client not created. ZM integration disabled?' )
result.error_list.append( 'Sync problem. ZM integration disabled?' )
return result
-
+
self._sync_states( result = result )
- self._sync_monitors( result = result )
-
+ created_monitor_entities = self._sync_monitors( result = result )
+
+ # Existing-entity updates do not need re-placement; only
+ # newly-created monitor entities surface in the dispatcher.
+ if created_monitor_entities:
+ result.placement_input = self.group_entities_for_placement(
+ entities = created_monitor_entities,
+ )
return result
- def _sync_states( self, result : ProcessingResult ) -> ProcessingResult:
+ def group_entities_for_placement( self, entities ) -> EntityPlacementInput:
+ """Single 'Monitors' group: ZM monitors typically share a
+ view, and the operator's first instinct is 'all cameras →
+ same place.' The dispatcher's drill-down still allows
+ per-monitor placement when needed.
+
+ Empty input → empty placement input (no dispatcher
+ rendering)."""
+ if not entities:
+ return EntityPlacementInput()
+ items = [
+ EntityPlacementItem(
+ key = self._placement_item_key( entity = entity ),
+ label = entity.name,
+ entity = entity,
+ )
+ for entity in entities
+ ]
+ return EntityPlacementInput(
+ groups = [ EntityPlacementGroup( label = 'Monitors', items = items ) ],
+ )
+
+ def _sync_states( self, result : IntegrationSyncResult ) -> IntegrationSyncResult:
zm_manager = self.zm_manager()
zm_run_state_list = zm_manager.get_zm_states( force_load = True )
@@ -95,18 +120,24 @@ class ZoneMinderSynchronizer( ZoneMinderMixin, IntegrationSyncMixin ):
if existing_state_values != new_state_values:
entity_state.value_range_dict = new_state_values_dict
entity_state.save()
- result.message_list.append( f'Updated ZM state values to: {new_state_values_dict}' )
+ result.info_list.append(
+ f'Updated ZM state values to: {new_state_values_dict}'
+ )
return
- def _sync_monitors( self, result : ProcessingResult ) -> ProcessingResult:
-
+ def _sync_monitors( self, result : IntegrationSyncResult ):
+ """Sync monitors and return the list of newly-created monitor
+ entities (for the caller to feed into
+ group_entities_for_placement). Updates to existing entities
+ do not contribute — they don't need re-placement."""
integration_key_to_monitor = self._fetch_zm_monitors( result = result )
- result.message_list.append( f'Found {len(integration_key_to_monitor)} current ZM monitors.' )
-
+ result.info_list.append( f'Found {len(integration_key_to_monitor)} current ZM monitors.' )
+
integration_key_to_entity = self._get_existing_zm_monitor_entities( result = result )
- result.message_list.append( f'Found {len(integration_key_to_entity)} existing ZM entities.' )
+ result.info_list.append( f'Found {len(integration_key_to_entity)} existing ZM items.' )
+ created_entities = []
for integration_key, zm_monitor in integration_key_to_monitor.items():
entity = integration_key_to_entity.get( integration_key )
if entity:
@@ -114,8 +145,9 @@ class ZoneMinderSynchronizer( ZoneMinderMixin, IntegrationSyncMixin ):
zm_monitor = zm_monitor,
result = result )
else:
- self._create_monitor_entity( zm_monitor = zm_monitor,
- result = result )
+ entity = self._create_monitor_entity( zm_monitor = zm_monitor,
+ result = result )
+ created_entities.append( entity )
continue
for integration_key, entity in integration_key_to_entity.items():
@@ -123,10 +155,10 @@ class ZoneMinderSynchronizer( ZoneMinderMixin, IntegrationSyncMixin ):
self._remove_entity( entity = entity,
result = result )
continue
-
- return
- def _fetch_zm_monitors( self, result : ProcessingResult ) -> Dict[ IntegrationKey, ZmMonitor ]:
+ return created_entities
+
+ def _fetch_zm_monitors( self, result : IntegrationSyncResult ) -> Dict[ IntegrationKey, ZmMonitor ]:
zm_manager = self.zm_manager()
logger.debug( 'Getting current ZM monitors.' )
@@ -141,7 +173,7 @@ class ZoneMinderSynchronizer( ZoneMinderMixin, IntegrationSyncMixin ):
return integration_key_to_monitor
- def _get_existing_zm_monitor_entities( self, result : ProcessingResult ) -> Dict[IntegrationKey, Entity]:
+ def _get_existing_zm_monitor_entities( self, result : IntegrationSyncResult ) -> Dict[IntegrationKey, Entity]:
logger.debug( 'Getting existing ZM entities.' )
integration_key_to_entity = dict()
@@ -149,7 +181,7 @@ class ZoneMinderSynchronizer( ZoneMinderMixin, IntegrationSyncMixin ):
for entity in entity_queryset:
integration_key = entity.integration_key
if not integration_key:
- result.error_list.append( f'ZM entity found without integration name: {entity}' )
+ result.error_list.append( f'ZM item found without integration name: {entity}' )
mock_monitor_id = 1000000 + entity.id # We need a (unique) placeholder (will remove later)
integration_key = IntegrationKey(
integration_id = ZmMetaData.integration_id,
@@ -164,7 +196,7 @@ class ZoneMinderSynchronizer( ZoneMinderMixin, IntegrationSyncMixin ):
def _create_zm_entity( self,
run_state_name_label_dict : Dict[ str, str ],
- result : ProcessingResult ):
+ result : IntegrationSyncResult ):
zm_manager = self.zm_manager()
with transaction.atomic():
@@ -183,12 +215,16 @@ class ZoneMinderSynchronizer( ZoneMinderMixin, IntegrationSyncMixin ):
name_label_dict = run_state_name_label_dict,
)
- result.message_list.append( f'Created ZM entity: {zm_entity}' )
+ # The singleton ZM service entity isn't a placement candidate
+ # (already attached to the integration root) — surface as an
+ # info note rather than as a created_list entry so it doesn't
+ # inflate the count of placeable monitors.
+ result.info_list.append( f'Created ZM service item: {zm_entity}' )
return zm_entity
def _create_monitor_entity( self,
zm_monitor : ZmMonitor,
- result : ProcessingResult ):
+ result : IntegrationSyncResult ) -> Entity:
zm_manager = self.zm_manager()
with transaction.atomic():
@@ -233,25 +269,24 @@ class ZoneMinderSynchronizer( ZoneMinderMixin, IntegrationSyncMixin ):
),
)
- result.message_list.append( f'Create new camera entity: {entity}' )
- return
-
+ result.created_list.append( entity.name )
+ return entity
+
def _update_entity( self,
entity : Entity,
zm_monitor : ZmMonitor,
- result : ProcessingResult ):
-
+ result : IntegrationSyncResult ):
if entity.name != zm_monitor.name():
- result.message_list.append(f'Name changed for {entity}. Setting to "{zm_monitor.name()}"')
+ old_name = entity.name
entity.name = zm_monitor.name()
entity.save()
- else:
- result.message_list.append( f'No changes found for {entity}.' )
+ # Surface the rename so the operator sees both names.
+ result.updated_list.append( f'{old_name} → {entity.name}' )
return
def _remove_entity( self,
entity : Entity,
- result : ProcessingResult ):
+ result : IntegrationSyncResult ):
"""
Remove an entity that no longer exists in the ZoneMinder integration.
diff --git a/src/hi/simulator/management/__init__.py b/src/hi/simulator/management/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/simulator/management/commands/__init__.py b/src/hi/simulator/management/commands/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/simulator/management/commands/seed_sim_profiles.py b/src/hi/simulator/management/commands/seed_sim_profiles.py
new file mode 100644
index 00000000..9f6a1844
--- /dev/null
+++ b/src/hi/simulator/management/commands/seed_sim_profiles.py
@@ -0,0 +1,416 @@
+"""
+Seed the simulator with a curated suite of SimProfiles for manual
+testing of the integration sync flows.
+
+Five profiles, each designed to exercise a specific scenario:
+
+ * empty — zero items in every integration. Tests the
+ initial-import-with-nothing path and the
+ refresh-against-emptied-upstream path.
+ * baseline — the realistic small-install set. Mixed HASS
+ device types, a handful of HomeBox items, a
+ few ZM monitors. Used as the *before* state
+ for delta tests.
+ * baseline-changed — same shape as baseline, with one removal,
+ one rename, and one addition per integration.
+ Importing baseline then switching the
+ simulator to this profile and clicking
+ Refresh exercises every change kind in a
+ single click.
+ * hass-zoo — one HASS entity of every supported type.
+ Visual / grouping coverage for the HASS
+ converter; HomeBox/ZM stay empty.
+ * volume — large counts (30 HASS, 25 HomeBox, 10 ZM
+ monitors). Stresses modal list overflow
+ scrolling and dispatcher group sizing.
+
+Re-running the command is a no-op when the named profile exists.
+Pass ``--reset`` to delete the matching profile (and its entities)
+before recreating.
+"""
+from django.core.management.base import BaseCommand
+from django.db import transaction
+
+from hi.simulator.enums import SimEntityType
+from hi.simulator.models import DbSimEntity, SimProfile
+from hi.simulator.services.hass.sim_models import (
+ HassInsteonDimmerLightSwitchFields,
+ HassInsteonDualBandLightSwitchFields,
+ HassInsteonLightSwitchFields,
+ HassInsteonMotionDetectorFields,
+ HassInsteonOpenCloseSensorFields,
+ HassInsteonOutletFields,
+)
+from hi.simulator.services.homebox.sim_models import (
+ HomeBoxInventoryItemFields,
+)
+from hi.simulator.services.zoneminder.sim_models import (
+ ZmMonitorSimEntityFields,
+ ZmServerSimEntityFields,
+)
+
+
+PROFILE_NAMES = [
+ 'empty',
+ 'baseline',
+ 'baseline-changed',
+ 'hass-zoo',
+ 'volume',
+]
+
+
+class Command(BaseCommand):
+ help = (
+ 'Seed the simulator with a curated set of SimProfiles for '
+ 'integration sync testing (empty, baseline, baseline-changed, '
+ 'hass-zoo, volume).'
+ )
+
+ def add_arguments(self, parser):
+ parser.add_argument(
+ '--reset',
+ action = 'store_true',
+ help = (
+ 'Delete and recreate any of the seeded profiles that '
+ 'already exist. Default behavior is to leave existing '
+ 'profiles untouched.'
+ ),
+ )
+ parser.add_argument(
+ '--only',
+ nargs = '+',
+ choices = PROFILE_NAMES,
+ help = 'Restrict seeding to the named profile(s).',
+ )
+
+ def handle(self, *args, **options):
+ targets = options.get('only') or PROFILE_NAMES
+ reset = options.get('reset', False)
+
+ builders = {
+ 'empty': self._build_empty,
+ 'baseline': self._build_baseline,
+ 'baseline-changed': self._build_baseline_changed,
+ 'hass-zoo': self._build_hass_zoo,
+ 'volume': self._build_volume,
+ }
+
+ for name in targets:
+ self._seed_profile(
+ name = name,
+ builder = builders[name],
+ reset = reset,
+ )
+
+ # ----- profile orchestration -----
+
+ def _seed_profile(self, name, builder, reset):
+ existing = SimProfile.objects.filter(name = name).first()
+ if existing:
+ if not reset:
+ self.stdout.write(
+ f' skip {name}: already exists '
+ '(pass --reset to recreate)'
+ )
+ return
+ self.stdout.write(f' reset {name}: deleting existing profile')
+ existing.delete() # cascades to db_sim_entities
+
+ with transaction.atomic():
+ profile = SimProfile.objects.create(name = name)
+ count = builder(profile)
+ self.stdout.write(
+ self.style.SUCCESS(
+ f' ok {name}: created with {count} entit'
+ f'{"y" if count == 1 else "ies"}'
+ )
+ )
+
+ # ----- builders -----
+
+ def _build_empty(self, profile: SimProfile) -> int:
+ return 0
+
+ def _build_baseline(self, profile: SimProfile) -> int:
+ # HASS: one of each common device kind (5 entities).
+ self._add_hass_light_switch( profile, 'Garage Light' , '01.AA.01' )
+ self._add_hass_dimmer( profile, 'Den Lamp' , '01.AA.02' )
+ self._add_hass_motion( profile, 'Hallway Motion' , '01.AA.03' )
+ self._add_hass_open_close( profile, 'Front Door' , '01.AA.04' )
+ self._add_hass_outlet( profile, 'Kitchen Outlet' , '01.AA.05' )
+
+ # HomeBox: 4 items with mixed metadata richness. ``item_id``
+ # is the per-item stable id used by the integration's
+ # change-detection — kept identical across baseline /
+ # baseline-changed for items that should be 'the same item'.
+ self._add_homebox_item(
+ profile, 'Cordless Drill',
+ item_id = 'cordless-drill',
+ description = 'DeWalt 20V 1/2-inch drill driver',
+ manufacturer = 'DeWalt',
+ model_number = 'DCD777',
+ serial_number = 'DW-100231',
+ quantity = 1,
+ )
+ self._add_homebox_item(
+ profile, 'Stud Finder',
+ item_id = 'stud-finder',
+ manufacturer = 'Franklin Sensors',
+ quantity = 1,
+ )
+ self._add_homebox_item(
+ profile, 'Soldering Iron Kit',
+ item_id = 'soldering-iron-kit',
+ description = 'Adjustable temp 60W with tips',
+ quantity = 2,
+ )
+ self._add_homebox_item(
+ profile, 'Spare Light Bulbs',
+ item_id = 'spare-light-bulbs',
+ quantity = 12,
+ )
+
+ # ZoneMinder: 1 server (singleton) + 2 monitors.
+ self._add_zm_server( profile )
+ self._add_zm_monitor( profile, 'Front Door Camera' , monitor_id = 1 )
+ self._add_zm_monitor( profile, 'Driveway Camera' , monitor_id = 2 )
+
+ return profile.db_sim_entities.count()
+
+ def _build_baseline_changed(self, profile: SimProfile) -> int:
+ # Designed so that importing `baseline` first, then switching
+ # the simulator to this profile and hitting Refresh, exercises
+ # remove + update + create in a single sync.
+
+ # HASS deltas vs baseline:
+ # Garage Light — kept (no change)
+ # Den Lamp — RENAMED to "Den Reading Lamp" (update)
+ # Hallway Motion — kept
+ # Front Door — REMOVED (drop)
+ # Kitchen Outlet — kept
+ # <new> Patio Switch — ADDED (create)
+ self._add_hass_light_switch( profile, 'Garage Light' , '01.AA.01' )
+ self._add_hass_dimmer( profile, 'Den Reading Lamp' , '01.AA.02' )
+ self._add_hass_motion( profile, 'Hallway Motion' , '01.AA.03' )
+ # Front Door (01.AA.04) intentionally absent.
+ self._add_hass_outlet( profile, 'Kitchen Outlet' , '01.AA.05' )
+ self._add_hass_light_switch( profile, 'Patio Switch' , '01.AA.06' )
+
+ # HomeBox deltas:
+ # Cordless Drill — kept (same item_id, same content)
+ # Stud Finder — same item_id, manufacturer changed
+ # (attribute update path)
+ # Soldering Iron — REMOVED (item_id absent)
+ # Spare Bulbs — kept (same item_id, same content)
+ # <new> Caulk Gun — ADDED (new item_id)
+ # Identity carries via ``item_id`` (the simulator's stable
+ # API id), not row order — so the order here doesn't matter
+ # for change-detection.
+ self._add_homebox_item(
+ profile, 'Cordless Drill',
+ item_id = 'cordless-drill',
+ description = 'DeWalt 20V 1/2-inch drill driver',
+ manufacturer = 'DeWalt',
+ model_number = 'DCD777',
+ serial_number = 'DW-100231',
+ quantity = 1,
+ )
+ self._add_homebox_item(
+ profile, 'Stud Finder',
+ item_id = 'stud-finder',
+ manufacturer = 'Bosch', # changed from 'Franklin Sensors'
+ quantity = 1,
+ )
+ self._add_homebox_item(
+ profile, 'Spare Light Bulbs',
+ item_id = 'spare-light-bulbs',
+ quantity = 12,
+ )
+ self._add_homebox_item(
+ profile, 'Caulk Gun',
+ item_id = 'caulk-gun',
+ description = '10-oz cartridge gun, dripless',
+ quantity = 1,
+ )
+
+ # ZoneMinder deltas:
+ # ZM Server — kept
+ # Front Door Camera — RENAMED to "Front Porch Camera"
+ # Driveway Camera — REMOVED
+ # <new> Backyard Cam — ADDED
+ self._add_zm_server( profile )
+ self._add_zm_monitor( profile, 'Front Porch Camera' , monitor_id = 1 )
+ self._add_zm_monitor( profile, 'Backyard Camera' , monitor_id = 3 )
+
+ return profile.db_sim_entities.count()
+
+ def _build_hass_zoo(self, profile: SimProfile) -> int:
+ # One of every HASS sim entity definition type.
+ self._add_hass_light_switch( profile, 'Zoo Light Switch' , '01.BB.01' )
+ self._add_hass_dimmer( profile, 'Zoo Dimmer' , '01.BB.02' )
+ self._add_hass_dual_band( profile, 'Zoo Dual Band Switch' , '01.BB.03' )
+ self._add_hass_motion( profile, 'Zoo Motion' , '01.BB.04' )
+ self._add_hass_open_close( profile, 'Zoo Open/Close' , '01.BB.05' )
+ self._add_hass_outlet( profile, 'Zoo Outlet' , '01.BB.06' )
+ return profile.db_sim_entities.count()
+
+ def _build_volume(self, profile: SimProfile) -> int:
+ # 30 HASS items spread across types with a heavy bias toward
+ # the most common (lights). Insteon addresses are sequential
+ # under the 01.CC.* prefix to avoid colliding with other
+ # profiles if they happen to share a database load.
+ light_types = [
+ self._add_hass_light_switch,
+ self._add_hass_dimmer,
+ self._add_hass_dual_band,
+ ]
+ for index in range(20):
+ adder = light_types[index % len(light_types)]
+ adder(profile, f'Volume Light {index + 1:02}',
+ f'01.CC.{index + 1:02X}')
+ for index in range(5):
+ self._add_hass_motion(
+ profile, f'Volume Motion {index + 1:02}',
+ f'01.CD.{index + 1:02X}',
+ )
+ for index in range(3):
+ self._add_hass_open_close(
+ profile, f'Volume Door {index + 1:02}',
+ f'01.CE.{index + 1:02X}',
+ )
+ for index in range(2):
+ self._add_hass_outlet(
+ profile, f'Volume Outlet {index + 1:02}',
+ f'01.CF.{index + 1:02X}',
+ )
+
+ # 25 HomeBox items, varied metadata.
+ for index in range(25):
+ self._add_homebox_item(
+ profile,
+ f'Volume Item {index + 1:03}',
+ item_id = f'volume-item-{index + 1:03}',
+ description = (
+ f'Stress-test inventory item #{index + 1}'
+ if index % 3 == 0 else ''
+ ),
+ manufacturer = 'Acme' if index % 5 == 0 else '',
+ quantity = (index % 4) + 1,
+ )
+
+ # ZM: 1 server + 10 monitors.
+ self._add_zm_server(profile)
+ for index in range(10):
+ self._add_zm_monitor(
+ profile,
+ f'Volume Camera {index + 1:02}',
+ monitor_id = 100 + index,
+ )
+
+ return profile.db_sim_entities.count()
+
+ # ----- per-integration row builders -----
+
+ def _add_hass_light_switch(self, profile, name, addr):
+ self._create_db_entity(
+ profile = profile,
+ simulator_id = 'hass',
+ fields_class = HassInsteonLightSwitchFields,
+ sim_entity_type = SimEntityType.LIGHT,
+ fields_kwargs = {'name': name, 'insteon_address': addr},
+ )
+
+ def _add_hass_dimmer(self, profile, name, addr):
+ self._create_db_entity(
+ profile = profile,
+ simulator_id = 'hass',
+ fields_class = HassInsteonDimmerLightSwitchFields,
+ sim_entity_type = SimEntityType.LIGHT,
+ fields_kwargs = {'name': name, 'insteon_address': addr},
+ )
+
+ def _add_hass_dual_band(self, profile, name, addr):
+ self._create_db_entity(
+ profile = profile,
+ simulator_id = 'hass',
+ fields_class = HassInsteonDualBandLightSwitchFields,
+ sim_entity_type = SimEntityType.LIGHT,
+ fields_kwargs = {'name': name, 'insteon_address': addr},
+ )
+
+ def _add_hass_motion(self, profile, name, addr):
+ self._create_db_entity(
+ profile = profile,
+ simulator_id = 'hass',
+ fields_class = HassInsteonMotionDetectorFields,
+ sim_entity_type = SimEntityType.MOTION_SENSOR,
+ fields_kwargs = {'name': name, 'insteon_address': addr},
+ )
+
+ def _add_hass_open_close(self, profile, name, addr):
+ self._create_db_entity(
+ profile = profile,
+ simulator_id = 'hass',
+ fields_class = HassInsteonOpenCloseSensorFields,
+ sim_entity_type = SimEntityType.OPEN_CLOSE_SENSOR,
+ fields_kwargs = {'name': name, 'insteon_address': addr},
+ )
+
+ def _add_hass_outlet(self, profile, name, addr):
+ self._create_db_entity(
+ profile = profile,
+ simulator_id = 'hass',
+ fields_class = HassInsteonOutletFields,
+ sim_entity_type = SimEntityType.ELECTRICAL_OUTLET,
+ fields_kwargs = {'name': name, 'insteon_address': addr},
+ )
+
+ def _add_homebox_item(self, profile, name, **fields_kwargs):
+ kwargs = {'name': name}
+ kwargs.update(fields_kwargs)
+ self._create_db_entity(
+ profile = profile,
+ simulator_id = 'hb',
+ fields_class = HomeBoxInventoryItemFields,
+ sim_entity_type = SimEntityType.OTHER,
+ fields_kwargs = kwargs,
+ )
+
+ def _add_zm_server(self, profile):
+ self._create_db_entity(
+ profile = profile,
+ simulator_id = 'zm',
+ fields_class = ZmServerSimEntityFields,
+ sim_entity_type = SimEntityType.SERVICE,
+ fields_kwargs = {'name': 'ZM Server'},
+ )
+
+ def _add_zm_monitor(self, profile, name, monitor_id):
+ self._create_db_entity(
+ profile = profile,
+ simulator_id = 'zm',
+ fields_class = ZmMonitorSimEntityFields,
+ sim_entity_type = SimEntityType.MOTION_SENSOR,
+ fields_kwargs = {'name': name, 'monitor_id': monitor_id},
+ )
+
+ # ----- low-level row creator -----
+
+ def _create_db_entity(self,
+ profile: SimProfile,
+ simulator_id: str,
+ fields_class,
+ sim_entity_type: SimEntityType,
+ fields_kwargs: dict):
+ # Instantiate the dataclass to get a validated, defaults-filled
+ # instance, then serialize via the same to_json_dict() the
+ # simulator uses at runtime — keeps the persisted shape in
+ # lock-step with how the simulator reads it back.
+ fields_instance = fields_class(**fields_kwargs)
+ DbSimEntity.objects.create(
+ sim_profile = profile,
+ simulator_id = simulator_id,
+ entity_fields_class_id = fields_class.class_id(),
+ sim_entity_type_str = str(sim_entity_type),
+ sim_entity_fields_json = fields_instance.to_json_dict(),
+ )
diff --git a/src/hi/simulator/services/homebox/api/views.py b/src/hi/simulator/services/homebox/api/views.py
index 67b198ab..4819851f 100644
--- a/src/hi/simulator/services/homebox/api/views.py
+++ b/src/hi/simulator/services/homebox/api/views.py
@@ -13,8 +13,6 @@ shapes and the response shapes match the real HomeBox API closely enough
for the integration's HbItem parser to consume them unchanged.
"""
-import logging
-
from django.http import JsonResponse
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
@@ -23,8 +21,6 @@ from django.views.generic import View
from hi.simulator.services.homebox.sim_models import build_item_api_dict
from hi.simulator.services.homebox.simulator import HomeBoxSimulator
-logger = logging.getLogger(__name__)
-
# Static token returned by the simulator's login endpoint. Not validated
# on subsequent requests; the simulator simply ignores the Authorization
@@ -39,25 +35,38 @@ class LoginView( View ):
return JsonResponse( { 'token': _STATIC_SIM_TOKEN } )
+def _api_id_for(fields, sim_entity_id) -> str:
+ """The id rule the simulator's HomeBox API emits for an item.
+
+ Single source of truth so the list view and the detail-by-id
+ view agree on identity. Prefer the operator-supplied
+ ``item_id`` (stable across profiles); fall back to the row PK
+ for items that don't set one.
+ """
+ return fields.item_id or str(sim_entity_id)
+
+
class AllItemsView( View ):
def get(self, request, *args, **kwargs):
- try:
- simulator = HomeBoxSimulator()
- items = [
- build_item_api_dict(
- sim_entity_id = sim_entity_id,
- fields = fields,
- archived_state = archived_state,
- )
- for ( sim_entity_id, fields, archived_state )
- in simulator.get_sim_entity_pairs()
- ]
- return JsonResponse( { 'items': items } )
-
- except Exception:
- logger.exception( 'Problem processing HomeBox items list' )
- return JsonResponse( { 'items': [] } )
+ # No broad except: if entity hydration or dict-building
+ # fails for any reason, surface a real 500 with the
+ # traceback so problems are visible. Returning an empty
+ # items list silently was previously masking real bugs.
+ simulator = HomeBoxSimulator()
+ items = [
+ build_item_api_dict(
+ sim_entity_id = sim_entity_id,
+ fields = fields,
+ archived_state = archived_state,
+ created_at = created_at,
+ updated_at = updated_at,
+ )
+ for ( sim_entity_id, fields, archived_state,
+ created_at, updated_at )
+ in simulator.get_sim_entity_pairs()
+ ]
+ return JsonResponse( { 'items': items } )
class ItemDetailView( View ):
@@ -65,11 +74,14 @@ class ItemDetailView( View ):
def get(self, request, *args, **kwargs):
item_id = kwargs.get('item_id')
simulator = HomeBoxSimulator()
- for ( sim_entity_id, fields, archived_state ) in simulator.get_sim_entity_pairs():
- if str(sim_entity_id) == item_id:
+ for ( sim_entity_id, fields, archived_state,
+ created_at, updated_at ) in simulator.get_sim_entity_pairs():
+ if _api_id_for(fields, sim_entity_id) == item_id:
return JsonResponse( build_item_api_dict(
sim_entity_id = sim_entity_id,
fields = fields,
archived_state = archived_state,
+ created_at = created_at,
+ updated_at = updated_at,
))
return JsonResponse( { 'message': f'Item {item_id} not found' }, status = 404 )
diff --git a/src/hi/simulator/services/homebox/sim_models.py b/src/hi/simulator/services/homebox/sim_models.py
index 28228e10..d730b4f2 100644
--- a/src/hi/simulator/services/homebox/sim_models.py
+++ b/src/hi/simulator/services/homebox/sim_models.py
@@ -13,7 +13,6 @@ The to_api_dict helper builds the JSON shape the integration's HbItem parser
from dataclasses import dataclass
from typing import Any, Dict, List
-import hi.apps.common.datetimeproxy as datetimeproxy
from hi.apps.common.utils import str_to_bool
from hi.simulator.base_models import SimEntityFields, SimState, SimEntityDefinition
@@ -22,8 +21,18 @@ from hi.simulator.enums import SimEntityType, SimStateType
@dataclass( frozen = True )
class HomeBoxInventoryItemFields( SimEntityFields ):
- """ User-editable metadata for a simulated HomeBox inventory item. """
+ """ User-editable metadata for a simulated HomeBox inventory item.
+
+ ``item_id`` is the identity the simulator's API emits as the
+ item's ``id``. Stable across profiles when the operator sets a
+ matching value in two profiles (e.g. baseline + baseline-changed
+ sharing 'cordless-drill'); when left empty the simulator falls
+ back to the row's auto-assigned ``DbSimEntity`` PK, which keeps
+ historical UI-created items working but means the same logical
+ item in two different profiles ends up with different ids.
+ """
+ item_id : str = ''
description : str = ''
serial_number : str = ''
model_number : str = ''
@@ -70,19 +79,25 @@ HOMEBOX_SIM_ENTITY_DEFINITION_LIST: List[SimEntityDefinition] = [
def build_item_api_dict( sim_entity_id : int,
fields : HomeBoxInventoryItemFields,
- archived_state : HomeBoxItemArchivedState ) -> Dict[ str, Any ]:
+ archived_state : HomeBoxItemArchivedState,
+ created_at,
+ updated_at ) -> Dict[ str, Any ]:
"""
Build the HomeBox item JSON shape returned by the simulator's API,
matching the fields the integration's HbItem parser consumes.
Fields not in the simulator's scope (custom fields, attachments,
- location, labels) are emitted as empty/null. Timestamps are emitted
- as the current time on every call; the integration uses them only
- for change detection.
+ location, labels) are emitted as empty/null. Timestamps come
+ from the persisted ``DbSimEntity`` so they're stable across
+ reads — change only when the operator actually edits the row,
+ matching real HomeBox behavior.
"""
- now_iso = datetimeproxy.now().isoformat()
+ # Prefer the operator-supplied stable id; fall back to the
+ # auto-assigned PK for items that don't set one (legacy and
+ # UI-created profiles).
+ item_id = fields.item_id or str(sim_entity_id)
return {
- 'id' : str(sim_entity_id),
+ 'id' : item_id,
'name' : fields.name,
'description' : fields.description,
'serialNumber' : fields.serial_number,
@@ -95,6 +110,6 @@ def build_item_api_dict( sim_entity_id : int,
'attachments' : [],
'location' : None,
'labels' : [],
- 'createdAt' : now_iso,
- 'updatedAt' : now_iso,
+ 'createdAt' : created_at.isoformat(),
+ 'updatedAt' : updated_at.isoformat(),
}
diff --git a/src/hi/simulator/services/homebox/simulator.py b/src/hi/simulator/services/homebox/simulator.py
index 3f8ada86..b4e90ac6 100644
--- a/src/hi/simulator/services/homebox/simulator.py
+++ b/src/hi/simulator/services/homebox/simulator.py
@@ -26,9 +26,17 @@ class HomeBoxSimulator( Simulator ):
def get_sim_entity_pairs(self):
"""
- Iterate (sim_entity_id, fields, archived_state) tuples for every
- configured HomeBox inventory item in the active profile. Used by
- the API views to build item responses.
+ Iterate (sim_entity_id, fields, archived_state, created_at,
+ updated_at) tuples for every configured HomeBox inventory
+ item in the active profile. Used by the API views to build
+ item responses.
+
+ The two timestamps come from the persisted ``DbSimEntity``
+ — stable across reads, only ticking when the operator
+ actually edits the row. This matches real HomeBox behavior
+ and prevents the converter's payload-equality change
+ detection from flagging untouched items as 'updated' on
+ every refresh.
"""
for sim_entity in self._sim_entity_map.values():
fields = sim_entity.sim_entity_fields
@@ -37,4 +45,11 @@ class HomeBoxSimulator( Simulator ):
archived_state = sim_entity._sim_state_map.get( 'archived' )
if not isinstance( archived_state, HomeBoxItemArchivedState ):
continue
- yield ( sim_entity.id, fields, archived_state )
+ db_row = sim_entity.db_sim_entity
+ yield (
+ sim_entity.id,
+ fields,
+ archived_state,
+ db_row.created_datetime,
+ db_row.updated_datetime,
+ )
diff --git a/src/hi/simulator/simulator_manager.py b/src/hi/simulator/simulator_manager.py
index 93222515..bd689527 100644
--- a/src/hi/simulator/simulator_manager.py
+++ b/src/hi/simulator/simulator_manager.py
@@ -38,6 +38,40 @@ class SimulatorManager( Singleton ):
def current_sim_profile(self) -> SimProfile:
return self._current_sim_profile
+ @classmethod
+ def clone_sim_profile( cls,
+ source_profile : SimProfile,
+ new_name : str ) -> SimProfile:
+ """Create a new ``SimProfile`` with ``new_name`` populated
+ with copies of every ``DbSimEntity`` row under
+ ``source_profile``. Returns the new profile (caller is
+ responsible for switching to it if desired).
+
+ Pure DB-side clone — does not touch the in-memory simulator
+ state. The caller's subsequent ``set_sim_profile()`` (when
+ they switch to the clone) is what triggers the simulator
+ instances to load the cloned rows.
+
+ Wrap this call in ``transaction.atomic()`` at the call site
+ so a failure mid-clone leaves no partial profile behind.
+ ``DbSimEntity`` JSON blobs are immutable strings — no
+ deep-copy needed; passing ``json`` references between rows
+ is safe because Django's JSONField round-trips through
+ json.dumps on save.
+ """
+ new_profile = SimProfile.objects.create( name = new_name )
+ DbSimEntity.objects.bulk_create([
+ DbSimEntity(
+ sim_profile = new_profile,
+ simulator_id = row.simulator_id,
+ entity_fields_class_id = row.entity_fields_class_id,
+ sim_entity_type_str = row.sim_entity_type_str,
+ sim_entity_fields_json = row.sim_entity_fields_json,
+ )
+ for row in source_profile.db_sim_entities.all()
+ ])
+ return new_profile
+
def set_sim_profile( self, sim_profile : SimProfile ):
should_reload_instances = bool( not sim_profile
or ( sim_profile != self._current_sim_profile ))
diff --git a/src/hi/simulator/templates/simulator/modals/sim_profile_clone.html b/src/hi/simulator/templates/simulator/modals/sim_profile_clone.html
new file mode 100644
index 00000000..2007c015
--- /dev/null
+++ b/src/hi/simulator/templates/simulator/modals/sim_profile_clone.html
@@ -0,0 +1,42 @@
+{% extends "modals/action_with_cancel.html" %}
+{% load icons %}
+
+{% comment %}
+ Clone the source profile into a new profile with operator-chosen
+ name. The form is pre-filled with '<source> (copy)' (or the next
+ free numeric variant), but the operator can edit before submit.
+
+ Context:
+ source_profile : SimProfile (required) — the profile being cloned
+ sim_profile_form : SimProfileForm (required) — name input
+{% endcomment %}
+
+{% block preamble %}
+<form action="{% url 'simulator_profile_clone' profile_id=source_profile.id %}" method="post"
+ class="form" data-async="modal">
+ {% csrf_token %}
+{% endblock %}
+
+{% block title_text %}
+Clone Simulator Profile
+{% endblock %}
+
+{% block body %}
+<p>
+ Cloning <strong>{{ source_profile.name }}</strong>. The new
+ profile will contain a copy of every simulated entity from
+ the source. Choose a name for the new profile:
+</p>
+{% include "simulator/panes/sim_profile_form.html" %}
+{% endblock %}
+
+{% block action_right %}
+<button id="hi-simulator-profile-clone-submit" type="submit" class="btn btn-primary"
+ name="action" value="clone">
+ {% icon "plus" size="sm" css_class="hi-icon-left" %}CLONE
+</button>
+{% endblock %}
+
+{% block postamble %}
+</form>
+{% endblock %}
diff --git a/src/hi/simulator/templates/simulator/panes/sim_profile_header.html b/src/hi/simulator/templates/simulator/panes/sim_profile_header.html
index 4343db3e..bcf8972b 100644
--- a/src/hi/simulator/templates/simulator/panes/sim_profile_header.html
+++ b/src/hi/simulator/templates/simulator/panes/sim_profile_header.html
@@ -15,6 +15,13 @@
RENAME: {{ current_sim_profile.name }}
</a>
</div>
+ <div class="">
+ <a role="button" class="btn btn-secondary"
+ href="{% url 'simulator_profile_clone' profile_id=current_sim_profile.id %}"
+ data-async="modal">
+ CLONE: {{ current_sim_profile.name }}
+ </a>
+ </div>
<div class="">
<a role="button" class="btn btn-danger"
href="{% url 'simulator_profile_delete' profile_id=current_sim_profile.id %}"
diff --git a/src/hi/simulator/urls.py b/src/hi/simulator/urls.py
index 54229f68..44ffb012 100644
--- a/src/hi/simulator/urls.py
+++ b/src/hi/simulator/urls.py
@@ -29,6 +29,10 @@ urlpatterns = [
re_path( r'^profile/delete/(?P<profile_id>\d+)$',
views.ProfileDeleteView.as_view(),
name = 'simulator_profile_delete' ),
+
+ re_path( r'^profile/clone/(?P<profile_id>\d+)$',
+ views.ProfileCloneView.as_view(),
+ name = 'simulator_profile_clone' ),
re_path( r'^profile/switch/(?P<profile_id>\d+)$',
views.ProfileSwitchView.as_view(),
diff --git a/src/hi/simulator/views.py b/src/hi/simulator/views.py
index 322c918a..a4498274 100644
--- a/src/hi/simulator/views.py
+++ b/src/hi/simulator/views.py
@@ -1,4 +1,5 @@
from django.core.exceptions import BadRequest
+from django.db import transaction
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
@@ -9,7 +10,7 @@ import hi.apps.common.antinode as antinode
from .enums import SimulatorFaultMode
from .exceptions import SimEntityValidationError
from . import forms
-from .models import DbSimEntity
+from .models import DbSimEntity, SimProfile
from .simulator_manager import SimulatorManager
from .sim_entity import SimEntity
from .view_mixins import SimulatorViewMixin
@@ -88,6 +89,73 @@ class ProfileEditView( View, SimulatorViewMixin ):
return antinode.refresh_response()
+class ProfileCloneView( View, SimulatorViewMixin ):
+ """
+ Clone the current profile into a new profile with operator-
+ chosen name. The clone copies the profile row and every
+ DbSimEntity row beneath it; SimState values are not persisted
+ (rebuilt from class defaults on every profile load), so the
+ clone naturally gets fresh state semantics with no extra work.
+
+ The new profile becomes the active profile after creation —
+ matches the Create flow's behavior and gives the operator
+ immediate visual confirmation in the simulator UI.
+ """
+
+ MODAL_TEMPLATE_NAME = 'simulator/modals/sim_profile_clone.html'
+
+ def get(self, request, *args, **kwargs):
+ source_profile = self.get_sim_profile( request, *args, **kwargs )
+ suggested_name = self._suggest_name( source_profile.name )
+ sim_profile_form = forms.SimProfileForm(
+ initial = { 'name': suggested_name },
+ )
+ context = {
+ 'source_profile': source_profile,
+ 'sim_profile_form': sim_profile_form,
+ }
+ return render( request, self.MODAL_TEMPLATE_NAME, context )
+
+ def post(self, request, *args, **kwargs):
+ source_profile = self.get_sim_profile( request, *args, **kwargs )
+ sim_profile_form = forms.SimProfileForm( request.POST )
+ if not sim_profile_form.is_valid():
+ context = {
+ 'source_profile': source_profile,
+ 'sim_profile_form': sim_profile_form,
+ }
+ return render( request, self.MODAL_TEMPLATE_NAME, context )
+
+ new_name = sim_profile_form.cleaned_data['name']
+ with transaction.atomic():
+ new_profile = SimulatorManager.clone_sim_profile(
+ source_profile = source_profile,
+ new_name = new_name,
+ )
+ SimulatorManager().set_sim_profile( sim_profile = new_profile )
+ return antinode.refresh_response()
+
+ @staticmethod
+ def _suggest_name( source_name : str ) -> str:
+ """Default new-name suggestion: '<source> (copy)'.
+
+ If that name is already taken, append a numeric suffix
+ ('<source> (copy 2)', '(copy 3)', ...) until a free name
+ is found. Bounded probe — no DB-side lock — because the
+ unique-name constraint at submit time is the actual
+ guard; this is just a friendly default, and a race here
+ means the operator sees a 'name already exists' on submit
+ and edits the field, which is acceptable."""
+ candidate = f'{source_name} (copy)'
+ if not SimProfile.objects.filter( name = candidate ).exists():
+ return candidate
+ for index in range( 2, 100 ):
+ candidate = f'{source_name} (copy {index})'
+ if not SimProfile.objects.filter( name = candidate ).exists():
+ return candidate
+ return f'{source_name} (copy)'
+
+
class ProfileSwitchView( View, SimulatorViewMixin ):
def get(self, request, *args, **kwargs):
diff --git a/src/hi/static/js/antinode.js b/src/hi/static/js/antinode.js
index c45f0049..46fc6e8d 100644
--- a/src/hi/static/js/antinode.js
+++ b/src/hi/static/js/antinode.js
@@ -299,6 +299,16 @@
let targetObj = getNewModal();
targetObj.append( modalContent );
showModal( targetObj );
+ },
+
+ // Close the modal that contains the given DOM node, if any.
+ // Mirrors the close-source-modal step antinode itself runs in
+ // beforeAsyncCall before issuing async requests. Exposed so
+ // outside form handlers (notably attr.js) can defer modal
+ // lifecycle to antinode rather than reaching into Bootstrap
+ // directly.
+ hideModalIfNeeded: function( eventObj ) {
+ hideModalIfNeeded( eventObj );
}
}
diff --git a/src/hi/static/js/attr.js b/src/hi/static/js/attr.js
index 73cb2ede..1d1db04c 100644
--- a/src/hi/static/js/attr.js
+++ b/src/hi/static/js/attr.js
@@ -336,6 +336,25 @@
window.location.href = data.redirect;
return;
}
+
+ // Modal-to-modal transition. The current modal hosting the
+ // submitted form is dismissed and a new modal containing
+ // the server-supplied HTML is opened in its place. Used by
+ // multi-step flows that stay in modal context (e.g.
+ // Configure -> pre-sync confirmation). Modal lifecycle is
+ // delegated to antinode (close + open) so attribute forms
+ // and antinode-handled forms share the same behavior.
+ if (data.modal) {
+ if (typeof AN !== 'undefined') {
+ if (typeof AN.hideModalIfNeeded === 'function') {
+ AN.hideModalIfNeeded($form);
+ }
+ if (typeof AN.displayModal === 'function') {
+ AN.displayModal(data.modal);
+ }
+ }
+ return;
+ }
// Process DOM updates first (works for both success and error)
const lastAppendTarget = this.processDOMUpdates(data, options);