Skip to content

Home Information - Your home, your data, organized.

Python

Move group_entities_for_placement to IntegrationGateway + URL conf factoring (#362)

Tony Cd9223766b963
diff --git a/src/hi/integrations/connector/integration_connector.py b/src/hi/integrations/connector/integration_connector.py
index d0ff0ab4..b13ad2c2 100644
--- a/src/hi/integrations/connector/integration_connector.py
+++ b/src/hi/integrations/connector/integration_connector.py
@@ -13,15 +13,11 @@ Sync is opt-in: a gateway whose integration does not support sync
returns None.
"""
import logging
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict, Optional
from django.db import transaction
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 hi.apps.entity.transient_models import VideoSnapshot, VideoStream
from hi.apps.monitor.periodic_monitor import PeriodicMonitor
@@ -286,50 +282,6 @@ class IntegrationConnector:
f'{self.__class__.__name__} must override get_integration_metadata()'
)
- 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 reconnect_disconnected_items(
self,
integration_key_to_upstream : Dict[ IntegrationKey, Any ],
diff --git a/src/hi/integrations/connector/sync_result.py b/src/hi/integrations/connector/sync_result.py
index f9cc9c94..13dfba4a 100644
--- a/src/hi/integrations/connector/sync_result.py
+++ b/src/hi/integrations/connector/sync_result.py
@@ -28,6 +28,7 @@ from dataclasses import dataclass, field
from typing import List, Optional
from hi.apps.entity.entity_placement import EntityPlacementInput
+from hi.apps.entity.models import Entity
@dataclass
@@ -71,9 +72,17 @@ class IntegrationSyncResult:
breadcrumbs — 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.
+
+ ``created_entities`` carries the just-created ``Entity``
+ instances back to the framework caller, which passes them
+ through ``gateway.group_entities_for_placement`` to build the
+ ``placement_input``. Keeping the grouping out of the connector
+ keeps Connect-sync and Import-run flows on a single grouping
+ method per integration.
"""
title: str
placement_input: Optional[EntityPlacementInput] = None
+ created_entities: List[Entity] = field(default_factory=list)
created_list: List[str] = field(default_factory=list)
updated_list: List[str] = field(default_factory=list)
reconnected_list: List[str] = field(default_factory=list)
diff --git a/src/hi/integrations/connector/urls.py b/src/hi/integrations/connector/urls.py
new file mode 100644
index 00000000..553a3923
--- /dev/null
+++ b/src/hi/integrations/connector/urls.py
@@ -0,0 +1,37 @@
+from django.urls import path, re_path
+
+from . import views
+
+
+urlpatterns = [
+ path( '',
+ views.IntegrationHomeView.as_view(),
+ name='integrations_connect_home' ),
+ path( 'select',
+ views.IntegrationSelectView.as_view(),
+ name='integrations_connect_select' ),
+ re_path( r'^enable/(?P<integration_id>[\w\-]+)$',
+ views.ConnectorConfigureView.as_view(),
+ name='integrations_connect_configure' ),
+ re_path( r'^disable/(?P<integration_id>[\w\-]+)$',
+ views.IntegrationDisableView.as_view(),
+ name='integrations_connect_disable' ),
+ re_path( r'^pause/(?P<integration_id>[\w\-]+)$',
+ views.IntegrationPauseView.as_view(),
+ name='integrations_connect_pause' ),
+ re_path( r'^resume/(?P<integration_id>[\w\-]+)$',
+ views.IntegrationResumeView.as_view(),
+ name='integrations_connect_resume' ),
+ re_path( r'^health/(?P<integration_id>[\w\-]+)$',
+ views.IntegrationHealthStatusView.as_view(),
+ name='integrations_connect_health_status' ),
+ re_path( r'^pre-sync/(?P<integration_id>[\w\-]+)$',
+ views.IntegrationPreSyncView.as_view(),
+ name='integrations_connect_pre_sync' ),
+ re_path( r'^sync/(?P<integration_id>[\w\-]+)$',
+ views.IntegrationSyncView.as_view(),
+ name='integrations_connect_sync' ),
+ re_path( r'^manage/(?P<integration_id>[\w\-]*)$',
+ views.ConnectorManageView.as_view(),
+ name='integrations_connect_manage' ),
+]
diff --git a/src/hi/integrations/connector/view_mixins.py b/src/hi/integrations/connector/view_mixins.py
new file mode 100644
index 00000000..a4e292fe
--- /dev/null
+++ b/src/hi/integrations/connector/view_mixins.py
@@ -0,0 +1,74 @@
+from django.urls import reverse
+
+from hi.apps.entity.models import Entity
+from hi.apps.sense.sensor_response_manager import SensorResponseManager
+from hi.views import page_not_found_response
+
+from hi.integrations.integration_metadata_cache import IntegrationMetadataCache
+from hi.integrations.placement_request import PlacementUrlParams
+
+
+class ConnectorViewMixin:
+ """Connect-mode-specific view helpers. Lives in the connector
+ sub-package because every method here is meaningful only to the
+ Connect capability — sync runs, sync-result modals, and the
+ placement CTA off a sync result."""
+
+ def render_sync_result( self,
+ request,
+ integration_data,
+ preserve_user_data : bool = True ):
+ """Run the integration's connector and render the
+ sync-result modal. Shared by the initial-connect flow
+ (ConnectorConfigureView.post after enable) and the update-check
+ flow (IntegrationSyncView.post after pre-sync confirm).
+
+ Returns the modal response directly, including the placement
+ URL for the 'Place new items' CTA when sync produced new
+ entities. Cache invalidations run in a ``finally`` so a
+ partial-commit failure during sync also flushes."""
+ gateway = integration_data.integration_gateway
+ connector = gateway.get_connector()
+ if connector is None:
+ return page_not_found_response( request )
+
+ is_initial_connect = not Entity.objects.filter(
+ integration_id = integration_data.integration_id,
+ ).exists()
+
+ try:
+ sync_result = connector.sync(
+ is_initial_connect = is_initial_connect,
+ preserve_user_data = preserve_user_data,
+ )
+ finally:
+ IntegrationMetadataCache().invalidate()
+ SensorResponseManager().invalidate_local_sensor_cache()
+
+ if sync_result.created_entities:
+ sync_result.placement_input = gateway.group_entities_for_placement(
+ entities = sync_result.created_entities,
+ )
+
+ new_entity_ids = (
+ sync_result.placement_input.all_entity_ids()
+ if sync_result.placement_input is not None else []
+ )
+ placement_url = PlacementUrlParams(
+ is_initial_connect = is_initial_connect,
+ 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_connect': is_initial_connect,
+ 'placement_url': placement_url,
+ },
+ template_name = 'integrations/connector/modals/sync_result.html',
+ )
diff --git a/src/hi/integrations/connector/views.py b/src/hi/integrations/connector/views.py
index 2796dcbe..b3152de8 100644
--- a/src/hi/integrations/connector/views.py
+++ b/src/hi/integrations/connector/views.py
@@ -1,13 +1,11 @@
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.apps.common.utils import str_to_bool
-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
@@ -16,26 +14,19 @@ 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 hi.apps.sense.sensor_response_manager import SensorResponseManager
from hi.integrations.enums import IntegrationCapability, IntegrationDisableMode
from hi.integrations.exceptions import IntegrationConnectionError
from hi.integrations.integration_manager import IntegrationManager
from hi.integrations.integration_metadata_cache import IntegrationMetadataCache
-from hi.integrations.models import IntegrationAttribute
from hi.integrations.entity_operations import EntityIntegrationOperations
from hi.integrations.integration_attribute_edit_context import IntegrationAttributeItemEditContext
-from hi.integrations.placement_request import PlacementFormParser, PlacementUrlParams
from .sync_check import IntegrationSyncCheck
-from .sync_result import IntegrationSyncResult
-from hi.integrations.view_mixins import (
- IntegrationPlacementViewMixin,
- IntegrationViewMixin,
-)
+from hi.integrations.view_mixins import IntegrationViewMixin
+from hi.integrations.connector.view_mixins import ConnectorViewMixin
from hi.integrations.views import CapabilityConfigureView
logger = logging.getLogger(__name__)
@@ -61,7 +52,7 @@ class IntegrationHomeView( ConfigPageView, IntegrationViewMixin ):
kwargs = { 'integration_id': integration_data.integration_id })
raise ForceRedirectException( redirect_url )
-
+
class IntegrationSelectView( HiModalView, IntegrationViewMixin ):
def get_template_name( self ) -> str:
@@ -94,7 +85,7 @@ class IntegrationPreSyncView( HiModalView, IntegrationViewMixin ):
"""
Pre-sync confirmation modal for the manage-page UPDATE
button. Surfaces the synchronizer's description and offers
- Sync / Not now actions. Not used in the first-time sync
+ Sync / Not now actions. Not used in the first-time sync
enable flow.
On the update-check path the modal additionally surfaces the
@@ -120,7 +111,7 @@ class IntegrationPreSyncView( HiModalView, IntegrationViewMixin ):
integration_id = integration_data.integration_id,
).exists()
sync_url = reverse(
- 'integrations_sync',
+ 'integrations_connect_sync',
kwargs = { 'integration_id': integration_data.integration_id },
)
@@ -142,7 +133,7 @@ class IntegrationPreSyncView( HiModalView, IntegrationViewMixin ):
return self.modal_response( request, context )
-class IntegrationSyncView( HiModalView, IntegrationViewMixin ):
+class IntegrationSyncView( HiModalView, IntegrationViewMixin, ConnectorViewMixin ):
"""
Framework sync execution view. Invokes the integration's
connector and always renders the sync result modal — the
@@ -181,166 +172,7 @@ class IntegrationSyncView( HiModalView, IntegrationViewMixin ):
)
-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 connector'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_data = self.get_integration_data( request, *args, **kwargs )
- connector = integration_data.integration_gateway.get_connector()
- if connector is None:
- return page_not_found_response( request )
-
- url_params = PlacementUrlParams.from_data( request.GET )
- is_initial_connect = url_params.is_initial_connect
- 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 = connector.group_entities_for_placement(
- entities = entities,
- )
- if placement_input.is_empty():
- return self._render_empty(
- request = request,
- integration_data = integration_data,
- connector = connector,
- is_initial_connect = is_initial_connect,
- )
- return self.render_placement(
- request = request,
- integration_data = integration_data,
- placement_input = placement_input,
- is_initial_connect = is_initial_connect,
- entity_id_filter = entity_id_filter,
- )
-
- def post( self, request, *args, **kwargs ):
- integration_data = self.get_integration_data( request, *args, **kwargs )
- url_params = PlacementUrlParams.from_data( request.POST )
- is_initial_connect = url_params.is_initial_connect
-
- 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_connect = is_initial_connect,
- )
-
- 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_connect = is_initial_connect,
- )
-
- @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,
- connector, is_initial_connect : 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.'"""
- sync_result = IntegrationSyncResult(
- title = connector.get_result_title(
- is_initial_connect = is_initial_connect,
- ),
- info_list = [ 'No items left to place.' ],
- )
- return self.modal_response(
- request,
- context = {
- 'sync_result': sync_result,
- 'integration_data': integration_data,
- 'is_initial_connect': is_initial_connect,
- },
- template_name = 'integrations/connector/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 ConnectorConfigureView( CapabilityConfigureView ):
+class ConnectorConfigureView( CapabilityConfigureView, ConnectorViewMixin ):
capability = IntegrationCapability.CONNECT
button_label = 'CONNECT'
@@ -385,7 +217,7 @@ class ConnectorConfigureView( CapabilityConfigureView ):
)
return AttributeRedirectResponse( url = redirect_url )
-
+
class IntegrationDisableView( HiModalView, IntegrationViewMixin ):
"""
Remove confirmation dialog. Classifies attached entities on GET to
@@ -437,7 +269,7 @@ class IntegrationDisableView( HiModalView, IntegrationViewMixin ):
'disable_mode_all': IntegrationDisableMode.ALL.name,
}
-
+
class IntegrationPauseView( View, IntegrationViewMixin ):
def post(self, request, *args, **kwargs):
@@ -479,7 +311,7 @@ class ConnectorManageView( ConfigPageView, IntegrationViewMixin, AttributeEditVi
def config_page_type(self) -> ConfigPageType:
return ConfigPageType.INTEGRATIONS_CONNECT
-
+
def get_main_template_name( self ) -> str:
return 'integrations/connector/pages/integration_manage.html'
@@ -571,13 +403,13 @@ class ConnectorManageView( ConfigPageView, IntegrationViewMixin, AttributeEditVi
# Get health status from the integration gateway
health_status_provider = integration_data.integration_gateway.get_connector().get_health_status_provider()
-
+
attr_item_context = IntegrationAttributeItemEditContext(
integration_data = integration_data,
capability = IntegrationCapability.CONNECT,
health_status = health_status_provider.health_status,
)
-
+
return self.post_attribute_form(
request = request,
attr_item_context = attr_item_context,
@@ -591,61 +423,5 @@ class ConnectorManageView( ConfigPageView, IntegrationViewMixin, AttributeEditVi
self.validate_attributes_extra_helper(
attr_item_context,
regular_attributes_formset,
- error_title = 'Cannot save settings.' )
+ error_title = 'Cannot save settings.' )
return
-
-
-class IntegrationAttributeHistoryInlineView( View,
- IntegrationViewMixin,
- AttributeEditViewMixin ):
-
- def get(self, request, integration_id, attribute_id, *args, **kwargs):
- # Validate that the attribute belongs to this integration for security
- try:
- attribute = IntegrationAttribute.objects.select_related('integration').get(
- pk = attribute_id, integration_id = integration_id )
- except IntegrationAttribute.DoesNotExist:
- return page_not_found_response(request, "Attribute not found.")
-
- integration_data = IntegrationManager().get_integration_data(
- integration_id = attribute.integration.integration_id,
- )
- attr_item_context = IntegrationAttributeItemEditContext(
- integration_data = integration_data,
- capability = IntegrationCapability.CONNECT,
- )
- return self.get_history(
- request = request,
- attribute = attribute,
- attr_item_context = attr_item_context,
- )
-
-
-class IntegrationAttributeRestoreInlineView( View,
- IntegrationViewMixin,
- AttributeEditViewMixin ):
- """View for restoring IntegrationAttribute values from history inline."""
-
- def get(self, request, integration_id, attribute_id, history_id, *args, **kwargs):
- """ Need to do restore in a GET since nested in main form and cannot have a form in a form """
- try:
- attribute = IntegrationAttribute.objects.select_related('integration').get(
- pk = attribute_id, integration_id = integration_id
- )
- except IntegrationAttribute.DoesNotExist:
- return page_not_found_response(request, "Attribute not found.")
-
- integration_data = IntegrationManager().get_integration_data(
- integration_id = attribute.integration.integration_id,
- )
-
- attr_item_context = IntegrationAttributeItemEditContext(
- integration_data = integration_data,
- capability = IntegrationCapability.CONNECT,
- )
- return self.post_restore(
- request = request,
- attribute = attribute,
- history_id = history_id,
- attr_item_context = attr_item_context,
- )
diff --git a/src/hi/integrations/importer/integration_importer.py b/src/hi/integrations/importer/integration_importer.py
index c92cebf7..394b47a2 100644
--- a/src/hi/integrations/importer/integration_importer.py
+++ b/src/hi/integrations/importer/integration_importer.py
@@ -11,11 +11,6 @@ candidate-listing, item ingest, and discard operations.
"""
from typing import List
-from hi.apps.entity.entity_placement import (
- EntityPlacementInput,
- EntityPlacementItem,
-)
-from hi.apps.entity.models import Entity
from hi.integrations.models import IntegrationAttribute
from hi.integrations.transient_models import (
IntegrationMetaData,
@@ -63,22 +58,3 @@ class IntegrationImporter:
Connect-mode entities (if somehow coexisting) stay
untouched."""
raise NotImplementedError('Subclasses must override this method')
-
- def group_entities_for_placement(
- self, entities: List[Entity],
- ) -> EntityPlacementInput:
- """Partition just-imported entities into the
- EntityPlacementInput shape consumed by the placement modal.
-
- Default: every entity is ungrouped. Subclasses override to
- provide a domain grouping where one exists."""
- return EntityPlacementInput(
- ungrouped_items = [
- EntityPlacementItem(
- key = f'entity:{entity.id}',
- label = entity.name,
- entity = entity,
- )
- for entity in entities
- ],
- )
diff --git a/src/hi/integrations/importer/transient_models.py b/src/hi/integrations/importer/transient_models.py
index 92eaac2d..3b59c246 100644
--- a/src/hi/integrations/importer/transient_models.py
+++ b/src/hi/integrations/importer/transient_models.py
@@ -2,6 +2,7 @@ from dataclasses import dataclass, field
from typing import List, Optional
from hi.apps.entity.entity_placement import EntityPlacementInput
+from hi.apps.entity.models import Entity
@dataclass
@@ -28,9 +29,15 @@ class IntegrationImportResult:
``placement_input`` is None when the import produced no new
entities to place; populated when the result modal should expose
the post-import placement flow.
+
+ ``created_entities`` carries the just-created ``Entity``
+ instances back to the framework caller, which passes them
+ through ``gateway.group_entities_for_placement`` to build the
+ ``placement_input`` — same shape as the Connect-sync flow.
"""
title: str
placement_input: Optional[EntityPlacementInput] = None
+ created_entities: List[Entity] = field(default_factory=list)
items_imported_count: int = 0
items_skipped_count: int = 0
imported_list: List[str] = field(default_factory=list)
diff --git a/src/hi/integrations/importer/urls.py b/src/hi/integrations/importer/urls.py
new file mode 100644
index 00000000..60ac4cae
--- /dev/null
+++ b/src/hi/integrations/importer/urls.py
@@ -0,0 +1,22 @@
+from django.urls import path, re_path
+
+from . import views
+
+
+urlpatterns = [
+ path( '',
+ views.DataImportPageView.as_view(),
+ name='integrations_import_home' ),
+ path( 'info',
+ views.DataImportInfoView.as_view(),
+ name='integrations_import_info' ),
+ re_path( r'^configure/(?P<integration_id>[\w\-]+)$',
+ views.ImporterConfigureView.as_view(),
+ name='integrations_import_configure' ),
+ re_path( r'^run/(?P<integration_id>[\w\-]+)$',
+ views.ImporterRunView.as_view(),
+ name='integrations_import_run' ),
+ re_path( r'^discard/(?P<integration_id>[\w\-]+)$',
+ views.ImporterDiscardView.as_view(),
+ name='integrations_import_discard' ),
+]
diff --git a/src/hi/integrations/importer/views.py b/src/hi/integrations/importer/views.py
index 6967f845..6aeb45fd 100644
--- a/src/hi/integrations/importer/views.py
+++ b/src/hi/integrations/importer/views.py
@@ -157,6 +157,11 @@ class ImporterRunView( HiModalView, IntegrationViewMixin ):
IntegrationMetadataCache().invalidate()
SensorResponseManager().invalidate_local_sensor_cache()
+ if result.created_entities:
+ result.placement_input = integration_data.integration_gateway.group_entities_for_placement(
+ entities = result.created_entities,
+ )
+
new_entity_ids = (
result.placement_input.all_entity_ids()
if result.placement_input is not None else []
diff --git a/src/hi/integrations/integration_gateway.py b/src/hi/integrations/integration_gateway.py
index cdcb70bf..f2507bed 100644
--- a/src/hi/integrations/integration_gateway.py
+++ b/src/hi/integrations/integration_gateway.py
@@ -1,4 +1,11 @@
-from typing import List, Optional
+from typing import Dict, List, Optional
+
+from hi.apps.entity.entity_placement import (
+ EntityPlacementGroup,
+ EntityPlacementInput,
+ EntityPlacementItem,
+)
+from hi.apps.entity.models import Entity
from hi.integrations.connector.integration_connector import IntegrationConnector
from hi.integrations.importer.integration_importer import IntegrationImporter
@@ -77,3 +84,47 @@ class IntegrationGateway:
relaunching monitors (Resume).
"""
raise NotImplementedError('Subclasses must override this method')
+
+ def group_entities_for_placement(
+ self, entities: List[Entity],
+ ) -> EntityPlacementInput:
+ """Partition the given entities into the EntityPlacementInput
+ shape consumed by the placement modal. Capability-neutral —
+ both Connect-sync and Import-run flows feed entities through
+ this same method, so a given integration groups its entities
+ the same way regardless of how they arrived.
+
+ Default: group by ``EntityType`` using the humanized type
+ label as the group name. Sorted alphabetically by label for
+ stable presentation. Subclasses override when a different
+ domain grouping makes sense (e.g., ZM/Frigate use a single
+ static named group for their single-type case)."""
+ type_label_to_items: Dict[str, List[EntityPlacementItem]] = {}
+ for entity in entities:
+ type_label = entity.entity_type.label
+ type_label_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_label_to_items[label] )
+ for label in sorted( type_label_to_items.keys() )
+ ]
+ return EntityPlacementInput( groups = groups )
+
+ def _placement_item_key(self, entity: Entity) -> str:
+ """Stable per-entity placement key. Prefers the live
+ integration_key, falls back to previous_integration_key for
+ imported/detached entities, then to the row id as a final
+ fallback for entities with no integration provenance at all."""
+ if entity.integration_key:
+ ikey = entity.integration_key
+ return f'{ikey.integration_id}:{ikey.integration_name}'
+ if entity.previous_integration_key:
+ pkey = entity.previous_integration_key
+ return f'{pkey.integration_id}:{pkey.integration_name}'
+ return f'entity:{entity.id}'
diff --git a/src/hi/integrations/templates/integrations/connector/modals/integration_disable.html b/src/hi/integrations/templates/integrations/connector/modals/integration_disable.html
index 34ef00a4..5cc38989 100644
--- a/src/hi/integrations/templates/integrations/connector/modals/integration_disable.html
+++ b/src/hi/integrations/templates/integrations/connector/modals/integration_disable.html
@@ -4,7 +4,7 @@
{% block header_class %}bg-secondary{% endblock %}
{% block preamble %}
-<form action="{% url 'integrations_disable' integration_id=integration_data.integration_id %}"
+<form action="{% url 'integrations_connect_disable' integration_id=integration_data.integration_id %}"
method="post"
class="form" data-async="modal">
{% csrf_token %}
diff --git a/src/hi/integrations/templates/integrations/connector/modals/integrations_select.html b/src/hi/integrations/templates/integrations/connector/modals/integrations_select.html
index 18b60cfa..94f030aa 100644
--- a/src/hi/integrations/templates/integrations/connector/modals/integrations_select.html
+++ b/src/hi/integrations/templates/integrations/connector/modals/integrations_select.html
@@ -35,7 +35,7 @@ All Integrations
<div class="col-3">
{% if integration_data.integration.is_enabled %}
- <a href="{% url 'integrations_disable' integration_id=integration_data.integration.integration_id %}"
+ <a href="{% url 'integrations_connect_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" %}DISABLE
</a>
diff --git a/src/hi/integrations/templates/integrations/connector/pages/integration_manage.html b/src/hi/integrations/templates/integrations/connector/pages/integration_manage.html
index 345f44cc..073de00a 100644
--- a/src/hi/integrations/templates/integrations/connector/pages/integration_manage.html
+++ b/src/hi/integrations/templates/integrations/connector/pages/integration_manage.html
@@ -6,7 +6,7 @@
<nav class="nav flex-column hi-vertical-nav">
<div class="hi-vertical-nav-header">
<a class="btn btn-outline-primary w-100" role="button"
- href="{% url 'integrations_select' %}"
+ href="{% url 'integrations_connect_select' %}"
data-async="modal">
{% icon "settings" size="sm" css_class="hi-icon-left" %}INTEGRATIONS
</a>
@@ -59,7 +59,7 @@
<div class="alert alert-info py-2 mt-2 mb-0" role="status">
{% icon "sync" size="sm" css_class="hi-icon-left" %}{{ core.sync_check_result.summary_message }}
Click
- <a href="{% url 'integrations_pre_sync' integration_id=core.integration_data.integration_id %}"
+ <a href="{% url 'integrations_connect_pre_sync' integration_id=core.integration_data.integration_id %}"
class="alert-link"
data-async="modal">Update</a>.
</div>
diff --git a/src/hi/integrations/templates/integrations/connector/pages/no_integrations.html b/src/hi/integrations/templates/integrations/connector/pages/no_integrations.html
index b7e12c7c..9bfd2011 100644
--- a/src/hi/integrations/templates/integrations/connector/pages/no_integrations.html
+++ b/src/hi/integrations/templates/integrations/connector/pages/no_integrations.html
@@ -5,7 +5,7 @@
</div>
<div class="text-center m-4 p-4">
<a class="btn btn-primary btn-lg" role="button"
- href="{% url 'integrations_select' %}"
+ href="{% url 'integrations_connect_select' %}"
data-async="modal">
CONFIGURE INTEGRATIONS
</a>
diff --git a/src/hi/integrations/templates/integrations/connector/panes/lifecycle_actions.html b/src/hi/integrations/templates/integrations/connector/panes/lifecycle_actions.html
index 423884ce..97b54668 100644
--- a/src/hi/integrations/templates/integrations/connector/panes/lifecycle_actions.html
+++ b/src/hi/integrations/templates/integrations/connector/panes/lifecycle_actions.html
@@ -11,7 +11,7 @@
{% if core.integration_data.is_enabled %}
<form class="mr-2"
method="post"
- action="{% if core.integration_data.is_paused %}{% url 'integrations_resume' integration_id=core.integration_data.integration_id %}{% else %}{% url 'integrations_pause' integration_id=core.integration_data.integration_id %}{% endif %}"
+ action="{% if core.integration_data.is_paused %}{% url 'integrations_connect_resume' integration_id=core.integration_data.integration_id %}{% else %}{% url 'integrations_connect_pause' integration_id=core.integration_data.integration_id %}{% endif %}"
data-async="true">
{% csrf_token %}
{% if core.integration_data.is_paused %}
diff --git a/src/hi/integrations/templates/integrations/connector/panes/sync_actions.html b/src/hi/integrations/templates/integrations/connector/panes/sync_actions.html
index 9af77fbd..3d265fd8 100644
--- a/src/hi/integrations/templates/integrations/connector/panes/sync_actions.html
+++ b/src/hi/integrations/templates/integrations/connector/panes/sync_actions.html
@@ -19,7 +19,7 @@
nothing to compare against on a first run.
{% endcomment %}
{% if core.integration_data.is_enabled and core.integration_data.integration_gateway.get_connector %}
-<a href="{% url 'integrations_pre_sync' integration_id=core.integration_data.integration_id %}"
+<a href="{% url 'integrations_connect_pre_sync' integration_id=core.integration_data.integration_id %}"
class="btn {% if core.has_entities %}{% if core.sync_check_result.needs_sync %}btn-primary{% else %}btn-outline-secondary{% endif %}{% else %}btn-outline-primary{% endif %}"
role="button"
data-async="modal">
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..8bb8b05c 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
@@ -15,7 +15,7 @@
<!-- Integration Health Status Display -->
{% if health_status %}
<div class="ml-3">
- <a href="{% url 'integrations_health_status' integration_id=integration_data.integration_id %}"
+ <a href="{% url 'integrations_connect_health_status' integration_id=integration_data.integration_id %}"
class="btn btn-link p-0 d-flex align-items-center text-decoration-none"
data-async="modal"
title="View health status details">
diff --git a/src/hi/integrations/tests/test_integration_gateway.py b/src/hi/integrations/tests/test_integration_gateway.py
new file mode 100644
index 00000000..ded69b00
--- /dev/null
+++ b/src/hi/integrations/tests/test_integration_gateway.py
@@ -0,0 +1,62 @@
+"""Framework-level IntegrationGateway tests — exercises the
+defaults that integrations either inherit or override.
+"""
+import logging
+
+from django.test import TestCase
+
+from hi.apps.entity.enums import EntityType
+from hi.apps.entity.models import Entity
+from hi.integrations.integration_gateway import IntegrationGateway
+
+logging.disable(logging.CRITICAL)
+
+
+class TestIntegrationGatewayPlacementItemKey(TestCase):
+ """Verify the three precedence branches of the unified
+ _placement_item_key helper:
+
+ 1. live integration_key -> "<id>:<name>"
+ 2. previous_integration_key (detached/imported) -> "<id>:<name>"
+ 3. neither populated (native) -> "entity:<id>"
+
+ Precedence is enforced by integration_key.setter clearing the
+ previous-pair on attach, so only one of the keys is populated
+ in any real lifecycle state."""
+
+ def setUp(self):
+ self.gateway = IntegrationGateway()
+
+ def test_uses_integration_key_when_attached(self):
+ entity = Entity.objects.create(
+ name='Live',
+ entity_type_str=str(EntityType.LIGHT),
+ integration_id='hass',
+ integration_name='light.kitchen',
+ )
+ self.assertEqual(
+ self.gateway._placement_item_key(entity=entity),
+ 'hass:light.kitchen',
+ )
+
+ def test_uses_previous_integration_key_when_detached(self):
+ entity = Entity.objects.create(
+ name='Detached',
+ entity_type_str=str(EntityType.LIGHT),
+ previous_integration_id='hb',
+ previous_integration_name='item.42',
+ )
+ self.assertEqual(
+ self.gateway._placement_item_key(entity=entity),
+ 'hb:item.42',
+ )
+
+ def test_falls_back_to_entity_id_when_native(self):
+ entity = Entity.objects.create(
+ name='Native',
+ entity_type_str=str(EntityType.OTHER),
+ )
+ self.assertEqual(
+ self.gateway._placement_item_key(entity=entity),
+ f'entity:{entity.id}',
+ )
diff --git a/src/hi/integrations/tests/test_views.py b/src/hi/integrations/tests/test_views.py
index 1a75a403..f83f1339 100644
--- a/src/hi/integrations/tests/test_views.py
+++ b/src/hi/integrations/tests/test_views.py
@@ -66,7 +66,7 @@ class PauseResumeViewTests(SyncViewTestCase):
IntegrationManager()._integration_data_map['pause_resume_view_test'] = self.integration_data
def test_pause_view_delegates_to_manager(self):
- url = reverse('integrations_pause', kwargs={'integration_id': 'pause_resume_view_test'})
+ url = reverse('integrations_connect_pause', kwargs={'integration_id': 'pause_resume_view_test'})
with patch.object(IntegrationManager, 'pause_integration') as mock_pause:
response = self.client.post(url)
@@ -76,7 +76,7 @@ class PauseResumeViewTests(SyncViewTestCase):
self.assertEqual(call_kwargs['integration_data'].integration_id, 'pause_resume_view_test')
def test_resume_view_delegates_to_manager(self):
- url = reverse('integrations_resume', kwargs={'integration_id': 'pause_resume_view_test'})
+ url = reverse('integrations_connect_resume', kwargs={'integration_id': 'pause_resume_view_test'})
with patch.object(IntegrationManager, 'resume_integration') as mock_resume:
response = self.client.post(url)
@@ -89,7 +89,7 @@ class PauseResumeViewTests(SyncViewTestCase):
self.integration.is_enabled = False
self.integration.save()
- url = reverse('integrations_pause', kwargs={'integration_id': 'pause_resume_view_test'})
+ url = reverse('integrations_connect_pause', kwargs={'integration_id': 'pause_resume_view_test'})
with patch.object(IntegrationManager, 'pause_integration') as mock_pause:
response = self.client.post(url)
@@ -100,7 +100,7 @@ class PauseResumeViewTests(SyncViewTestCase):
self.integration.is_enabled = False
self.integration.save()
- url = reverse('integrations_resume', kwargs={'integration_id': 'pause_resume_view_test'})
+ url = reverse('integrations_connect_resume', kwargs={'integration_id': 'pause_resume_view_test'})
with patch.object(IntegrationManager, 'resume_integration') as mock_resume:
response = self.client.post(url)
@@ -136,7 +136,7 @@ class RemoveViewTests(SyncViewTestCase):
IntegrationManager()._integration_data_map[self.INTEGRATION_ID] = integration_data
def _url(self):
- return reverse('integrations_disable', kwargs={'integration_id': self.INTEGRATION_ID})
+ return reverse('integrations_connect_disable', kwargs={'integration_id': self.INTEGRATION_ID})
def test_post_with_mode_safe_dispatches_safe(self):
with patch.object(IntegrationManager, 'disable_integration') as mock_disable:
@@ -302,7 +302,7 @@ class PreSyncViewTests(SyncViewTestCase):
def _url(self):
return reverse(
- 'integrations_pre_sync',
+ 'integrations_connect_pre_sync',
kwargs={'integration_id': self.INTEGRATION_ID},
)
@@ -412,7 +412,7 @@ class SyncViewTests(SyncViewTestCase):
def _url(self):
return reverse(
- 'integrations_sync',
+ 'integrations_connect_sync',
kwargs={'integration_id': self.INTEGRATION_ID},
)
@@ -715,7 +715,7 @@ class PlacementFlowTests(SyncViewTestCase):
def _sync_url(self):
return reverse(
- 'integrations_sync', kwargs={'integration_id': self.INTEGRATION_ID},
+ 'integrations_connect_sync', kwargs={'integration_id': self.INTEGRATION_ID},
)
def _placement_url(self):
@@ -990,8 +990,11 @@ class PlacementDismissAndShowTests(SyncViewTestCase):
),
)
self.synchronizer = _PlacementTestSynchronizer(sync_result=self.sync_result)
- # Stub group_entities_for_placement so the GET placement can
- # rebuild from unplaced entities.
+ self.gateway = _PlacementTestGateway(
+ integration_id=self.INTEGRATION_ID, synchronizer=self.synchronizer,
+ )
+ # Stub group_entities_for_placement on the gateway so the GET
+ # placement can rebuild from unplaced entities.
def group_for_placement(entities):
items = [
@@ -1006,11 +1009,7 @@ class PlacementDismissAndShowTests(SyncViewTestCase):
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,
- )
+ self.gateway.group_entities_for_placement = group_for_placement
IntegrationManager()._integration_data_map[self.INTEGRATION_ID] = IntegrationData(
integration_gateway=self.gateway, integration=self.integration,
)
@@ -1285,7 +1284,7 @@ class ConnectorManageViewSyncCheckContextTests(SyncViewTestCase):
# inline anchor that links to the pre-sync modal, so the
# rendered HTML carries both the link text and the URL.
self.assertIn(
- reverse('integrations_pre_sync',
+ reverse('integrations_connect_pre_sync',
kwargs={'integration_id': self.INTEGRATION_ID}),
body,
)
@@ -1293,7 +1292,7 @@ class ConnectorManageViewSyncCheckContextTests(SyncViewTestCase):
def _refresh_link_url(self):
return reverse(
- 'integrations_pre_sync',
+ 'integrations_connect_pre_sync',
kwargs={'integration_id': self.INTEGRATION_ID},
)
diff --git a/src/hi/integrations/urls.py b/src/hi/integrations/urls.py
index 9d1a6c94..7f58d3cd 100644
--- a/src/hi/integrations/urls.py
+++ b/src/hi/integrations/urls.py
@@ -4,92 +4,30 @@ from django.urls import re_path, include
from hi.apps.common.module_utils import import_module_safe
-from .connector import views
-from .importer import views as importer_views
+from . import views
urlpatterns = [
- path( '',
- views.IntegrationHomeView.as_view(),
- name='integrations_connect_home' ),
-
- path( 'import/',
- importer_views.DataImportPageView.as_view(),
- name='integrations_import_home' ),
-
- path( 'import/info',
- importer_views.DataImportInfoView.as_view(),
- name='integrations_import_info' ),
-
- re_path( r'^import/configure/(?P<integration_id>[\w\-]+)$',
- importer_views.ImporterConfigureView.as_view(),
- name='integrations_import_configure' ),
-
- re_path( r'^import/run/(?P<integration_id>[\w\-]+)$',
- importer_views.ImporterRunView.as_view(),
- name='integrations_import_run' ),
-
- re_path( r'^import/discard/(?P<integration_id>[\w\-]+)$',
- importer_views.ImporterDiscardView.as_view(),
- name='integrations_import_discard' ),
-
- path( 'select',
- views.IntegrationSelectView.as_view(),
- name='integrations_select' ),
-
- re_path( r'^enable/(?P<integration_id>[\w\-]+)$',
- views.ConnectorConfigureView.as_view(),
- name='integrations_connect_configure' ),
-
- re_path( r'^disable/(?P<integration_id>[\w\-]+)$',
- views.IntegrationDisableView.as_view(),
- name='integrations_disable' ),
-
- re_path( r'^pause/(?P<integration_id>[\w\-]+)$',
- views.IntegrationPauseView.as_view(),
- name='integrations_pause' ),
-
- re_path( r'^resume/(?P<integration_id>[\w\-]+)$',
- views.IntegrationResumeView.as_view(),
- name='integrations_resume' ),
-
- re_path( r'^health/(?P<integration_id>[\w\-]+)$',
- 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' ),
+ path( 'connect/', include( 'hi.integrations.connector.urls' )),
+ path( 'import/', include( 'hi.integrations.importer.urls' )),
re_path( r'^placement/(?P<integration_id>[\w\-]+)$',
views.IntegrationPlacementView.as_view(),
name='integrations_placement' ),
-
path( 'refine/<int:location_view_id>',
views.IntegrationRefineView.as_view(),
name='integrations_refine' ),
-
- re_path( r'^manage/(?P<integration_id>[\w\-]*)$',
- views.ConnectorManageView.as_view(),
- name='integrations_connect_manage' ),
-
- path( 'attribute/history/<int:integration_id>/<int:attribute_id>/',
- views.IntegrationAttributeHistoryInlineView.as_view(),
- name='integration_attribute_history_inline'),
-
- path( 'attribute/restore/<int:integration_id>/<int:attribute_id>/<int:history_id>/',
+ path( 'attribute/history/<int:integration_id>/<int:attribute_id>/',
+ views.IntegrationAttributeHistoryInlineView.as_view(),
+ name='integration_attribute_history_inline' ),
+ path( 'attribute/restore/<int:integration_id>/<int:attribute_id>/<int:history_id>/',
views.IntegrationAttributeRestoreInlineView.as_view(),
- name='integration_attribute_restore_inline'),
+ name='integration_attribute_restore_inline' ),
]
def discover_urls():
""" Add urls (if any) from all integrations """
-
discovered_url_modules = dict()
for app_config in apps.get_app_configs():
if not app_config.name.startswith( 'hi.services' ):
@@ -100,18 +38,15 @@ def discover_urls():
urls_module = import_module_safe( module_name = module_name )
if not urls_module:
continue
-
discovered_url_modules[short_name] = urls_module
-
except Exception:
pass
continue
-
return discovered_url_modules
for short_name, urls_module in discover_urls().items():
urlpatterns.append(
- re_path(f"services/{short_name}/", include( urls_module ))
+ re_path( f"services/{short_name}/", include( urls_module ))
)
continue
diff --git a/src/hi/integrations/view_mixins.py b/src/hi/integrations/view_mixins.py
index 00fe997d..bfeebbda 100644
--- a/src/hi/integrations/view_mixins.py
+++ b/src/hi/integrations/view_mixins.py
@@ -10,12 +10,9 @@ from hi.apps.collection.models import Collection, CollectionEntity
from hi.apps.entity.models import Entity, EntityView
from hi.apps.location.location_manager import LocationManager
from hi.apps.location.models import Location, LocationView
-from hi.apps.sense.sensor_response_manager import SensorResponseManager
-from hi.views import page_not_found_response
from hi.integrations.enums import IntegrationCapability
from hi.integrations.integration_manager import IntegrationManager
-from hi.integrations.integration_metadata_cache import IntegrationMetadataCache
from hi.integrations.placement_request import PlacementUrlParams
@@ -110,59 +107,6 @@ class IntegrationViewMixin:
enabled_only = enabled_only,
capabilities = capabilities,
)
-
- def render_sync_result( self,
- request,
- integration_data,
- preserve_user_data : bool = True ):
- """Run the integration's connector and render the
- sync-result modal. Shared by the initial-connect flow
- (ConnectorConfigureView.post after enable) and the update-check
- flow (IntegrationSyncView.post after pre-sync confirm).
-
- Returns the modal response directly, including the placement
- URL for the 'Place N new items' CTA when sync produced new
- entities. Cache invalidations run in a ``finally`` so a
- partial-commit failure during sync also flushes."""
- connector = integration_data.integration_gateway.get_connector()
- if connector is None:
- return page_not_found_response( request )
-
- is_initial_connect = not Entity.objects.filter(
- integration_id = integration_data.integration_id,
- ).exists()
-
- try:
- sync_result = connector.sync(
- is_initial_connect = is_initial_connect,
- preserve_user_data = preserve_user_data,
- )
- finally:
- IntegrationMetadataCache().invalidate()
- SensorResponseManager().invalidate_local_sensor_cache()
-
- new_entity_ids = (
- sync_result.placement_input.all_entity_ids()
- if sync_result.placement_input is not None else []
- )
- placement_url = PlacementUrlParams(
- is_initial_connect = is_initial_connect,
- 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_connect': is_initial_connect,
- 'placement_url': placement_url,
- },
- template_name = 'integrations/connector/modals/sync_result.html',
- )
def validate_attributes_extra_helper( self,
attr_item_context,
@@ -499,9 +443,10 @@ class IntegrationPlacementViewMixin:
'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.
+ Returns an empty list for the rare truly-ungrouped case
+ (no groups, only ``ungrouped_items``). Callers should hide
+ the preview entirely in that case, since restating the
+ count is just noise.
"""
if not placement_input.groups:
return []
diff --git a/src/hi/integrations/views.py b/src/hi/integrations/views.py
index 3e235bef..46756912 100644
--- a/src/hi/integrations/views.py
+++ b/src/hi/integrations/views.py
@@ -1,16 +1,29 @@
"""
Framework-level integration views shared across capabilities.
"""
+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.attribute.view_mixins import AttributeEditViewMixin
+from hi.apps.entity.entity_placement import EntityPlacementService
+from hi.apps.location.models import LocationView
+from hi.enums import ViewMode, ViewType
from hi.hi_async_view import HiModalView
+from hi.views import page_not_found_response
+from hi.integrations.connector.sync_result import IntegrationSyncResult
from hi.integrations.enums import IntegrationCapability
from hi.integrations.integration_attribute_edit_context import (
IntegrationAttributeItemEditContext,
)
from hi.integrations.integration_manager import IntegrationManager
+from hi.integrations.models import IntegrationAttribute
+from hi.integrations.placement_request import PlacementFormParser, PlacementUrlParams
from hi.integrations.view_mixins import (
CapabilityBlockViewMixin,
+ IntegrationPlacementViewMixin,
IntegrationViewMixin,
)
@@ -113,3 +126,218 @@ class CapabilityConfigureView( HiModalView,
error_title = self.error_title,
)
return
+
+
+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 connector'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_data = self.get_integration_data( request, *args, **kwargs )
+ connector = integration_data.integration_gateway.get_connector()
+ if connector is None:
+ return page_not_found_response( request )
+
+ url_params = PlacementUrlParams.from_data( request.GET )
+ is_initial_connect = url_params.is_initial_connect
+ 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 = integration_data.integration_gateway.group_entities_for_placement(
+ entities = entities,
+ )
+ if placement_input.is_empty():
+ return self._render_empty(
+ request = request,
+ integration_data = integration_data,
+ connector = connector,
+ is_initial_connect = is_initial_connect,
+ )
+ return self.render_placement(
+ request = request,
+ integration_data = integration_data,
+ placement_input = placement_input,
+ is_initial_connect = is_initial_connect,
+ entity_id_filter = entity_id_filter,
+ )
+
+ def post( self, request, *args, **kwargs ):
+ integration_data = self.get_integration_data( request, *args, **kwargs )
+ url_params = PlacementUrlParams.from_data( request.POST )
+ is_initial_connect = url_params.is_initial_connect
+
+ 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_connect = is_initial_connect,
+ )
+
+ 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_connect = is_initial_connect,
+ )
+
+ @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,
+ connector, is_initial_connect : 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.'"""
+ sync_result = IntegrationSyncResult(
+ title = connector.get_result_title(
+ is_initial_connect = is_initial_connect,
+ ),
+ info_list = [ 'No items left to place.' ],
+ )
+ return self.modal_response(
+ request,
+ context = {
+ 'sync_result': sync_result,
+ 'integration_data': integration_data,
+ 'is_initial_connect': is_initial_connect,
+ },
+ template_name = 'integrations/connector/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 IntegrationAttributeHistoryInlineView( View,
+ IntegrationViewMixin,
+ AttributeEditViewMixin ):
+
+ def get(self, request, integration_id, attribute_id, *args, **kwargs):
+ # Validate that the attribute belongs to this integration for security
+ try:
+ attribute = IntegrationAttribute.objects.select_related('integration').get(
+ pk = attribute_id, integration_id = integration_id )
+ except IntegrationAttribute.DoesNotExist:
+ return page_not_found_response(request, "Attribute not found.")
+
+ integration_data = IntegrationManager().get_integration_data(
+ integration_id = attribute.integration.integration_id,
+ )
+ attr_item_context = IntegrationAttributeItemEditContext(
+ integration_data = integration_data,
+ capability = IntegrationCapability.CONNECT,
+ )
+ return self.get_history(
+ request = request,
+ attribute = attribute,
+ attr_item_context = attr_item_context,
+ )
+
+
+class IntegrationAttributeRestoreInlineView( View,
+ IntegrationViewMixin,
+ AttributeEditViewMixin ):
+ """View for restoring IntegrationAttribute values from history inline."""
+
+ def get(self, request, integration_id, attribute_id, history_id, *args, **kwargs):
+ """ Need to do restore in a GET since nested in main form and cannot have a form in a form """
+ try:
+ attribute = IntegrationAttribute.objects.select_related('integration').get(
+ pk = attribute_id, integration_id = integration_id
+ )
+ except IntegrationAttribute.DoesNotExist:
+ return page_not_found_response(request, "Attribute not found.")
+
+ integration_data = IntegrationManager().get_integration_data(
+ integration_id = attribute.integration.integration_id,
+ )
+
+ attr_item_context = IntegrationAttributeItemEditContext(
+ integration_data = integration_data,
+ capability = IntegrationCapability.CONNECT,
+ )
+ return self.post_restore(
+ request = request,
+ attribute = attribute,
+ history_id = history_id,
+ attr_item_context = attr_item_context,
+ )
diff --git a/src/hi/services/frigate/frigate_connector.py b/src/hi/services/frigate/frigate_connector.py
index 3b9a9fb8..e85052ec 100644
--- a/src/hi/services/frigate/frigate_connector.py
+++ b/src/hi/services/frigate/frigate_connector.py
@@ -5,11 +5,6 @@ from asgiref.sync import sync_to_async
from django.db import transaction
from hi.apps.entity.enums import EntityType, VideoStreamType
-from hi.apps.entity.entity_placement import (
- EntityPlacementGroup,
- EntityPlacementInput,
- EntityPlacementItem,
-)
from hi.apps.entity.models import Entity
from hi.apps.entity.transient_models import VideoSnapshot, VideoStream
from hi.apps.model_helper import HiModelHelper
@@ -186,31 +181,9 @@ class FrigateConnector( IntegrationConnector, FrigateMixin ):
return result
created_camera_entities = self._sync_cameras( result = result )
- if created_camera_entities:
- result.placement_input = self.group_entities_for_placement(
- entities = created_camera_entities,
- )
+ result.created_entities = created_camera_entities
return result
- def group_entities_for_placement( self, entities ) -> EntityPlacementInput:
- """Single 'Cameras' placement group: Frigate cameras usually
- share a wall-of-views layout, so 'all cameras → same place'
- is the right default. Operators can still drill into
- per-camera placement from the dispatcher."""
- 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 = 'Cameras', items = items ) ],
- )
-
def _sync_cameras( self, result : IntegrationSyncResult ) -> List[ Entity ]:
integration_key_to_camera = self._fetch_frigate_cameras( result = result )
result.info_list.append(
diff --git a/src/hi/services/frigate/tests/test_frigate_connector.py b/src/hi/services/frigate/tests/test_frigate_connector.py
index a53cdd70..9e05ad36 100644
--- a/src/hi/services/frigate/tests/test_frigate_connector.py
+++ b/src/hi/services/frigate/tests/test_frigate_connector.py
@@ -216,11 +216,9 @@ class TestFrigateSyncImpl( _FrigateSyncTestBase ):
self.assertEqual( names, { 'front_yard', 'back_door', 'driveway' } )
self.assertEqual( set( result.created_list ), names )
- # Placement input should carry one group with all three cameras.
- self.assertIsNotNone( result.placement_input )
- self.assertEqual( len( result.placement_input.groups ), 1 )
- self.assertEqual( result.placement_input.groups[0].label, 'Cameras' )
- self.assertEqual( len( result.placement_input.groups[0].items ), 3 )
+ # Created entities flow through to the framework caller, which
+ # builds placement_input via gateway.group_entities_for_placement.
+ self.assertEqual( len( result.created_entities ), 3 )
def test_sync_skips_event_definition_when_alarm_events_disabled(self):
# Default in setUp is should_add_alarm_events=False.
diff --git a/src/hi/services/hass/hass_connector.py b/src/hi/services/hass/hass_connector.py
index c4d05d17..e16a5c55 100644
--- a/src/hi/services/hass/hass_connector.py
+++ b/src/hi/services/hass/hass_connector.py
@@ -7,11 +7,6 @@ from django.db import transaction
from hi.apps.entity.models import Entity
from hi.apps.entity.transient_models import VideoSnapshot
-from hi.apps.entity.entity_placement import (
- EntityPlacementInput,
- EntityPlacementItem,
- EntityPlacementGroup,
-)
from hi.apps.system.health_status_provider import HealthStatusProvider
from hi.integrations.connector.integration_connector import IntegrationConnector
@@ -227,10 +222,7 @@ class HassConnector( IntegrationConnector, HassMixin ):
result = result )
continue
- if created_entities:
- result.placement_input = self.group_entities_for_placement(
- entities = created_entities,
- )
+ result.created_entities = created_entities
return result
def _rebuild_integration_components( self,
@@ -303,26 +295,3 @@ class HassConnector( IntegrationConnector, HassMixin ):
self._remove_entity_intelligently(entity, result)
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 6bdec7db..5c364c01 100644
--- a/src/hi/services/hass/integration.py
+++ b/src/hi/services/hass/integration.py
@@ -68,3 +68,4 @@ class HassGateway( IntegrationGateway ):
except Exception as e:
logger.exception(f'Error in HASS access validation: {e}')
return ConnectionTestResult.failure(f'Access validation error: {e}')
+
diff --git a/src/hi/services/hass/tests/test_hass_connector.py b/src/hi/services/hass/tests/test_hass_connector.py
index 696f62b4..37bb24e0 100644
--- a/src/hi/services/hass/tests/test_hass_connector.py
+++ b/src/hi/services/hass/tests/test_hass_connector.py
@@ -10,6 +10,7 @@ from hi.integrations.transient_models import IntegrationKey
from hi.services.hass.hass_connector import HassConnector
from hi.services.hass.hass_models import HassState
+from hi.services.hass.integration import HassGateway
logging.disable(logging.CRITICAL)
@@ -298,38 +299,38 @@ class TestHassConnectorMixinIntegration(TestCase):
class TestHassConnectorSyncResultGrouping(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."""
+ """Default-grouping behavior: entities are grouped by EntityType
+ using the humanized type label. Exercised here against
+ HassGateway (which uses the framework default) — the same
+ behavior applies to any integration that doesn't override
+ group_entities_for_placement."""
def setUp(self):
- self.synchronizer = HassConnector()
+ self.synchronizer = HassGateway()
- 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(
+ def _entity(self, name, entity_type, integration_name):
+ entity = Entity.objects.create(
+ name=name,
+ entity_type_str=str(entity_type),
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."""
+ """Group ordering is alphabetical by humanized type label."""
+ from hi.apps.entity.enums import EntityType
entities = [
- self._entity('Kitchen Light', 'LIGHT', 'light.kitchen'),
- self._entity('Hall Sensor', 'SENSOR', 'binary_sensor.hall'),
- self._entity('Bedroom Light', 'LIGHT', 'light.bedroom'),
+ self._entity('Kitchen Light', EntityType.LIGHT, 'light.kitchen'),
+ self._entity('Hall Sensor', EntityType.MOTION_SENSOR, 'binary_sensor.hall'),
+ self._entity('Bedroom Light', EntityType.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'],
+ ['Light', 'Motion Sensor'],
)
self.assertEqual(
[item.label for item in placement_input.groups[0].items],
@@ -340,11 +341,15 @@ class TestHassConnectorSyncResultGrouping(TestCase):
['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
+ def test_falls_back_to_other_when_entity_type_unknown(self):
+ """Entities with an unrecognized entity_type_str fall into
+ the 'Other' bucket (EntityType.default())."""
+ entity = Entity.objects.create(
+ name='Mystery',
+ entity_type_str='UNRECOGNIZED_FUTURE_TYPE',
+ integration_id='hass',
+ integration_name='sensor.mystery',
+ )
placement_input = self.synchronizer.group_entities_for_placement([entity])
self.assertEqual(placement_input.ungrouped_items, [])
@@ -359,7 +364,8 @@ class TestHassConnectorSyncResultGrouping(TestCase):
self.assertTrue(placement_input.is_empty())
def test_item_key_uses_integration_key(self):
- entity = self._entity('Front Camera', 'CAMERA', 'camera.front')
+ from hi.apps.entity.enums import EntityType
+ entity = self._entity('Front Camera', EntityType.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/homebox/connector/homebox_connector.py b/src/hi/services/homebox/connector/homebox_connector.py
index f4f8d9f9..5ff1df6e 100644
--- a/src/hi/services/homebox/connector/homebox_connector.py
+++ b/src/hi/services/homebox/connector/homebox_connector.py
@@ -136,15 +136,17 @@ class HomeBoxConnector( IntegrationConnector, HomeBoxMixin ):
# 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,
- )
+ result.created_entities = created_entities
return result
- # 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.
+ # group_entities_for_placement: no override. HomeBox inherits
+ # the gateway base default (group by EntityType). Today
+ # ``HbConverter.hb_item_to_entity_type`` stamps every imported
+ # item as ``EntityType.OTHER``, so the result is a single
+ # ``Other`` group — functionally equivalent to ungrouped, just
+ # with an extra label level. A future HomeBox-specific override
+ # (e.g. by upstream Location, read from ``integration_payload``)
+ # will replace this default.
def _sync_helper_entities( self,
item_list: List[HbItem],
diff --git a/src/hi/services/homebox/importer/homebox_importer.py b/src/hi/services/homebox/importer/homebox_importer.py
index 1f3a92a5..4fb6454f 100644
--- a/src/hi/services/homebox/importer/homebox_importer.py
+++ b/src/hi/services/homebox/importer/homebox_importer.py
@@ -140,10 +140,7 @@ class HomeBoxImporter( IntegrationImporter, HomeBoxMixin ):
result.imported_list.append( entity.name )
created_entities.append( entity )
- if created_entities:
- result.placement_input = self.group_entities_for_placement(
- entities = created_entities,
- )
+ result.created_entities = created_entities
def discard_imported_data( self, integration_id: str ) -> IntegrationDiscardResult:
"""Remove all entities previously imported under this
diff --git a/src/hi/services/homebox/tests/test_homebox_connector.py b/src/hi/services/homebox/tests/test_homebox_connector.py
index 9bfc7569..108e8fa6 100644
--- a/src/hi/services/homebox/tests/test_homebox_connector.py
+++ b/src/hi/services/homebox/tests/test_homebox_connector.py
@@ -131,13 +131,14 @@ class TestHomeBoxConnector(SimpleTestCase):
for message in result.error_list))
-class TestHomeBoxConnectorSyncResultGrouping(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):
+class TestHomeBoxConnectorSyncImplCreatedEntities(SimpleTestCase):
+ """HomeBoxConnector._sync_impl reports newly-created entities
+ on result.created_entities. The framework caller does the
+ grouping via the gateway (HomeBox inherits the by-EntityType
+ default; with HbConverter currently stamping every item as
+ OTHER, the operator sees a single 'Other' group)."""
+
+ def test_sync_impl_populates_created_entities(self):
synchronizer = HomeBoxConnector()
manager = Mock()
manager.hb_client = object()
@@ -163,19 +164,9 @@ class TestHomeBoxConnectorSyncResultGrouping(SimpleTestCase):
return_value=[entity_a, entity_b]):
result = synchronizer._sync_impl(is_initial_connect=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',
- ],
- )
+ # Created entities flow through to the framework caller, which
+ # groups them via gateway.group_entities_for_placement.
+ self.assertEqual(result.created_entities, [entity_a, entity_b])
def test_sync_impl_emits_empty_when_no_items_imported(self):
synchronizer = HomeBoxConnector()
@@ -187,7 +178,9 @@ class TestHomeBoxConnectorSyncResultGrouping(SimpleTestCase):
patch.object(synchronizer, '_sync_helper_entities', return_value=[]):
result = synchronizer._sync_impl(is_initial_connect=True)
- # No newly-created entities → placement_input is None.
+ # No newly-created entities → empty created_entities → framework
+ # caller leaves placement_input as None.
+ self.assertEqual(result.created_entities, [])
self.assertIsNone(result.placement_input)
diff --git a/src/hi/services/zoneminder/tests/test_zm_connector.py b/src/hi/services/zoneminder/tests/test_zm_connector.py
index 4827c3f7..73226ee0 100644
--- a/src/hi/services/zoneminder/tests/test_zm_connector.py
+++ b/src/hi/services/zoneminder/tests/test_zm_connector.py
@@ -927,13 +927,14 @@ class TestZmConnectorWithRealData(TestCase):
self.assertEqual(len(result.created_list), 1)
-class TestZmConnectorSyncResultGrouping(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."""
+class TestZmConnectorSyncImplCreatedEntities(TestCase):
+ """ZmConnector._sync_impl reports ALL newly-created entities on
+ result.created_entities, including the ZM service entity when
+ it was just created. The framework caller (render_sync_result)
+ feeds this list through gateway.group_entities_for_placement,
+ where the by-EntityType default produces a 'Camera' group and a
+ 'Service' group (the operator may skip the service entity in the
+ placement modal — the system does not hide it)."""
def setUp(self):
self.synchronizer = ZmConnector()
@@ -951,31 +952,40 @@ class TestZmConnectorSyncResultGrouping(TestCase):
entity.id = 0
return entity
- def test_sync_impl_emits_single_monitors_group(self):
+ def test_includes_freshly_created_service_entity(self):
+ service_entity = self._imported_entity('ZoneMinder', 'service')
entity_a = self._imported_entity('Front Door', 'monitor.1')
entity_b = self._imported_entity('Driveway', 'monitor.2')
- with patch.object(self.synchronizer, '_sync_states'), \
+ with patch.object(self.synchronizer, '_sync_states',
+ return_value=service_entity), \
patch.object(self.synchronizer, '_sync_monitors',
return_value=[entity_a, entity_b]):
result = self.synchronizer._sync_impl(is_initial_connect=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'), \
+ self.assertEqual(
+ result.created_entities,
+ [service_entity, entity_a, entity_b],
+ )
+
+ def test_omits_service_entity_when_not_freshly_created(self):
+ # _sync_states returns None when the service entity already
+ # existed (re-sync after initial connect).
+ entity_a = self._imported_entity('Front Door', 'monitor.1')
+ with patch.object(self.synchronizer, '_sync_states',
+ return_value=None), \
+ patch.object(self.synchronizer, '_sync_monitors',
+ return_value=[entity_a]):
+ result = self.synchronizer._sync_impl(is_initial_connect=False)
+
+ self.assertEqual(result.created_entities, [entity_a])
+
+ def test_empty_when_nothing_created(self):
+ with patch.object(self.synchronizer, '_sync_states',
+ return_value=None), \
patch.object(self.synchronizer, '_sync_monitors', return_value=[]):
result = self.synchronizer._sync_impl(is_initial_connect=True)
- # No newly-created entities → no placement input → placement
- # modal is not shown.
+ self.assertEqual(result.created_entities, [])
self.assertIsNone(result.placement_input)
diff --git a/src/hi/services/zoneminder/zm_connector.py b/src/hi/services/zoneminder/zm_connector.py
index 9823baa7..719fb9a2 100644
--- a/src/hi/services/zoneminder/zm_connector.py
+++ b/src/hi/services/zoneminder/zm_connector.py
@@ -15,12 +15,6 @@ from hi.apps.system.health_status_provider import HealthStatusProvider
from hi.apps.model_helper import HiModelHelper
-from hi.apps.entity.entity_placement import (
- EntityPlacementInput,
- EntityPlacementItem,
- EntityPlacementGroup,
-)
-
from hi.integrations.connector.integration_connector import IntegrationConnector
from hi.integrations.connector.sync_check import IntegrationSyncCheck, SyncDelta
from hi.integrations.connector.sync_result import IntegrationSyncResult
@@ -249,51 +243,32 @@ class ZmConnector( IntegrationConnector, ZoneMinderMixin ):
result.error_list.append( 'Sync problem. ZM integration disabled?' )
return result
- self._sync_states( result = result )
+ created_service_entity = self._sync_states( 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 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
+ result.created_entities = [
+ *( [ created_service_entity ] if created_service_entity else [] ),
+ *created_monitor_entities,
]
- return EntityPlacementInput(
- groups = [ EntityPlacementGroup( label = 'Monitors', items = items ) ],
- )
+ return result
- def _sync_states( self, result : IntegrationSyncResult ) -> IntegrationSyncResult:
+ def _sync_states( self, result : IntegrationSyncResult ) -> Optional[Entity]:
+ """Returns the freshly-created ZM service entity when this
+ sync run had to create one; None otherwise. Caller appends
+ the return value (when non-None) to ``result.created_entities``
+ so the framework's placement step treats the service entity
+ symmetrically with everything else created this run."""
zm_manager = self.zm_manager()
-
+
zm_run_state_list = zm_manager.get_zm_states( force_load = True )
new_state_values_dict = { x.name(): x.name() for x in zm_run_state_list }
-
+
zm_entity = Entity.objects.filter_by_integration_key(
integration_key = zm_manager._zm_integration_key(),
).first()
-
+
+ created_service_entity = None
if not zm_entity:
- _ = self._create_zm_entity(
+ created_service_entity = self._create_zm_entity(
run_state_name_label_dict = new_state_values_dict,
result = result,
)
@@ -304,7 +279,7 @@ class ZmConnector( IntegrationConnector, ZoneMinderMixin ):
if not zm_run_state_sensor:
result.error_list.append( 'Missing ZoneMinder sensor for ZM state.' )
- return
+ return created_service_entity
entity_state = zm_run_state_sensor.entity_state
new_state_values = new_state_values_dict.keys()
@@ -318,7 +293,7 @@ class ZmConnector( IntegrationConnector, ZoneMinderMixin ):
f'Updated ZM state values to: {new_state_values_dict}'
)
- return
+ return created_service_entity
def _sync_monitors( self, result : IntegrationSyncResult ):
"""Sync monitors and return the list of newly-created monitor