Skip to content

Home Information - Your home, your data, organized.

Python

Issue #288: EventDefinition lifecycle cleanup on integration disconnect (#290)

Tony C75a7892f67e2
diff --git a/src/hi/apps/event/models.py b/src/hi/apps/event/models.py
index 0c41fc13..79a0d1dd 100644
--- a/src/hi/apps/event/models.py
+++ b/src/hi/apps/event/models.py
@@ -1,3 +1,20 @@
+"""
+Event-system models.
+
+Lifecycle note (Issue #288): EventDefinition is integration-attached
+(inherits IntegrationDetailsModel). Integration-owned rows
+(``integration_id IS NOT NULL``) are cleaned up at the integration
+disconnect / sync-removal boundary by
+``hi.integrations.event_definition_operations.EventDefinitionOperations``,
+not by a generalized "EntityState delete cascades to parent" rule.
+User-owned rows are not touched by integration cleanup; the existing
+``on_delete=CASCADE`` on ``EventClause.entity_state`` and
+``ControlAction.controller`` continues to apply, which can leave a
+user-owned EventDefinition silently semantically changed (clauseless,
+or with reduced clauses) — that broader UX is deferred to a separate
+redesign.
+"""
+
from django.db import models
from hi.apps.alert.enums import AlarmLevel
diff --git a/src/hi/apps/event/templates/event/panes/event_definitions.html b/src/hi/apps/event/templates/event/panes/event_definitions.html
index 0d20542e..17c12b05 100644
--- a/src/hi/apps/event/templates/event/panes/event_definitions.html
+++ b/src/hi/apps/event/templates/event/panes/event_definitions.html
@@ -1,10 +1,13 @@
{% extends "config/pages/config_base.html" %}
-{% load icons %}
+{% load icons integration_tags static %}
{% block config_content %}
<div class="container-fluid">
<div class="d-flex justify-content-between my-1">
- <div class="h3">Trigger Rules</div>
+ <div class="h3">
+ Trigger Rules
+ <span class="badge badge-secondary align-middle ml-1" style="font-size: 0.5em;">BETA</span>
+ </div>
<div>
<a role="button" class="btn btn-outline-primary"
href="{% url 'event_definition_add' %}"
@@ -13,6 +16,10 @@
</a>
</div>
</div>
+ <p class="text-muted mb-3">
+ Triggers alerts or actions when entity states match a defined condition.
+ The current interface covers the core cases; richer editing is planned.
+ </p>
<div class="table-responsive">
<table class="table table-striped">
@@ -41,6 +48,10 @@
data-async="modal" >
{{ event_definition.name }}
</a>
+ {% if event_definition.integration_id %}
+ {% integration_logo_path event_definition as logo_path %}
+ {% if logo_path %}<img src="{% static logo_path %}" class="hi-integration-logo--inline ml-1" alt="{% integration_display_name event_definition %}" title="{% integration_display_name event_definition %}">{% endif %}
+ {% endif %}
</td>
<td>
{{ event_definition.event_type.label }}
diff --git a/src/hi/integrations/entity_operations.py b/src/hi/integrations/entity_operations.py
index 3e4cbc9c..e0c582b6 100644
--- a/src/hi/integrations/entity_operations.py
+++ b/src/hi/integrations/entity_operations.py
@@ -4,6 +4,14 @@ Operations on entities with respect to their integration attachment.
This module holds mutating operations (disconnect, preserve, detach) that
act on Entity instances relative to the integration that owns them. These
are distinct from the read-only analytical methods on EntityUserDataDetector.
+
+EventDefinition cleanup (Issue #288) is integration-scoped and is
+invoked here from both ``preserve_with_user_data`` and the hard-delete
+branch of ``remove_entities_with_closure``. See
+``EventDefinitionOperations`` for the policy: only EventDefinition rows
+whose own ``integration_id`` matches are removed; user-owned
+EventDefinitions referencing the entity's states are intentionally
+left alone (deferred to the broader EventDefinition UX redesign).
"""
import logging
@@ -16,6 +24,7 @@ from hi.apps.entity.models import Entity, EntityState, EntityStateDelegation
from hi.apps.sense.models import Sensor
from hi.apps.control.models import Controller
+from .event_definition_operations import EventDefinitionOperations
from .sync_result import IntegrationSyncResult
from .transient_models import IntegrationKey, IntegrationRemovalSummary
from .user_data_detector import EntityUserDataDetector
@@ -156,6 +165,13 @@ class EntityIntegrationOperations:
else:
if result is not None:
result.removed_list.append( entity.name )
+ # Django's DB-level CASCADE from Entity.delete() reaches
+ # EventClause / ControlAction (the children) but stops
+ # there — the parent EventDefinition row is never
+ # touched. Delete integration-owned EventDefinitions
+ # for this entity first, then let CASCADE handle the
+ # rest of the entity graph.
+ EventDefinitionOperations.delete_for_entity( entity )
entity.delete()
return
@@ -270,14 +286,22 @@ class EntityIntegrationOperations:
Preserve an entity with user-created data by disconnecting it
from its integration and removing only integration-related
components (sensors, controllers, orphaned states,
- integration-owned attributes). The entity's previous
- integration identity is recorded on the entity so the
- auto-reconnect path can recognize it if the same upstream
- key reappears later. The detached state is signaled
- structurally — ``integration_id`` becomes NULL and
- ``previous_integration_id`` carries the prior identity — and
- surfaced to the operator via a "Detached from <integration>"
- badge in the entity-detail UI.
+ integration-owned attributes, integration-owned
+ EventDefinitions). The entity's previous integration identity
+ is recorded on the entity so the auto-reconnect path can
+ recognize it if the same upstream key reappears later. The
+ detached state is signaled structurally — ``integration_id``
+ becomes NULL and ``previous_integration_id`` carries the prior
+ identity — and surfaced to the operator via a "Detached from
+ <integration>" badge in the entity-detail UI.
+
+ Issue #288: integration-owned EventDefinitions are removed
+ first inside the atomic block via
+ ``EventDefinitionOperations.delete_for_entity``. User-owned
+ EventDefinitions (``integration_id IS NULL``) referencing this
+ entity's states are intentionally NOT touched here — the
+ broader UX of broken/partial user rules is deferred to a
+ separate redesign.
Args:
entity: The Entity to preserve.
@@ -297,6 +321,15 @@ class EntityIntegrationOperations:
)
with transaction.atomic():
+ # Remove integration-owned EventDefinitions for this entity.
+ # Done first so the parent rows are gone before the states/
+ # controllers they reference are deleted below; CASCADE on
+ # EventClause/ControlAction reaches only the children, so
+ # parents must be removed explicitly here. See
+ # EventDefinitionOperations docstring for the integration-
+ # scoped policy.
+ EventDefinitionOperations.delete_for_entity( entity )
+
# Remove integration-related sensors
if sensor_ids_to_remove:
removed_sensor_count = Sensor.objects.filter(
diff --git a/src/hi/integrations/event_definition_operations.py b/src/hi/integrations/event_definition_operations.py
new file mode 100644
index 00000000..49339079
--- /dev/null
+++ b/src/hi/integrations/event_definition_operations.py
@@ -0,0 +1,120 @@
+"""
+Operations on EventDefinition rows with respect to integration ownership.
+
+This module holds the integration-scoped cleanup helpers for
+EventDefinition. The policy is deliberately narrow:
+
+ * Only EventDefinition rows whose own ``integration_id`` matches the
+ disconnecting integration are removed. User-owned EventDefinition
+ rows (``integration_id IS NULL``) are never touched here, even when
+ they reference an entity state that an integration is about to
+ delete. The silent semantic change of a user-owned multi-clause
+ rule losing one of its clauses is a known gap deferred to the
+ broader EventDefinition UX redesign.
+ * The cleanup is invoked at the integration disconnect / sync-removal
+ boundary (``EntityIntegrationOperations``); there is no general
+ "EntityState delete cascades to parent EventDefinition" rule.
+
+EventDefinition has no FK back to Entity. The reverse path is
+``EventDefinition → EventClause → EntityState → Entity``, traversed
+explicitly in the queries below. Children
+(``EventClause`` / ``ControlAction`` / ``AlarmAction`` / ``EventHistory``)
+have ``on_delete=CASCADE`` to ``EventDefinition`` and are removed by
+the parent delete; we do not need to enumerate them here.
+"""
+
+import logging
+from typing import Iterable, List
+
+from hi.apps.entity.models import Entity
+from hi.apps.event.models import EventDefinition
+
+logger = logging.getLogger(__name__)
+
+
+class EventDefinitionOperations:
+ """
+ Integration-scoped cleanup of EventDefinition rows.
+
+ All methods are explicit and integration-id-bounded. Callers are
+ expected to invoke these from inside their own ``transaction.atomic``
+ boundary; the helpers do not open transactions themselves.
+ """
+
+ @staticmethod
+ def delete_for_integration( integration_id : str ) -> int:
+ """
+ Delete every EventDefinition whose own ``integration_id`` matches.
+
+ Used by Disable-ALL and as a backstop. Does not consider clauses
+ — the integration_id on the EventDefinition itself is the
+ ownership signal.
+ """
+ if not integration_id:
+ return 0
+ _, per_model = EventDefinition.objects.filter(
+ integration_id = integration_id,
+ ).delete()
+ deleted_count = per_model.get( EventDefinition._meta.label, 0 )
+ if deleted_count:
+ logger.debug(
+ f'Removed {deleted_count} integration EventDefinitions '
+ f'for integration_id={integration_id}'
+ )
+ return deleted_count
+
+ @classmethod
+ def delete_for_entity( cls, entity : Entity ) -> int:
+ """
+ Delete EventDefinitions owned by this entity's integration whose
+ clauses reference any of this entity's states.
+
+ Used by ``EntityIntegrationOperations.preserve_with_user_data``
+ and per-entity sync removal. Returns 0 (no-op) when the entity
+ is not currently integration-attached, so callers can invoke
+ this unconditionally.
+ """
+ if not entity.integration_id:
+ return 0
+ return cls.delete_for_entity_closure(
+ entity_ids = [ entity.id ],
+ integration_id = entity.integration_id,
+ )
+
+ @staticmethod
+ def delete_for_entity_closure( entity_ids : Iterable[int],
+ integration_id : str ) -> int:
+ """
+ Batched form of ``delete_for_entity`` for a closure of entities.
+
+ Deletes every EventDefinition where:
+ * the EventDefinition's own ``integration_id`` matches, AND
+ * at least one of its EventClauses references an EntityState
+ owned by an entity in ``entity_ids``.
+
+ Two-step (lookup-then-delete) to avoid issues with
+ ``queryset.delete()`` on a ``.distinct()`` queryset across a
+ joined relation.
+ """
+ entity_id_list : List[int] = list( entity_ids )
+ if not entity_id_list or not integration_id:
+ return 0
+ target_ids = list(
+ EventDefinition.objects.filter(
+ integration_id = integration_id,
+ event_clauses__entity_state__entity_id__in = entity_id_list,
+ ).values_list( 'id', flat = True ).distinct()
+ )
+ if not target_ids:
+ return 0
+ _, per_model = EventDefinition.objects.filter(
+ id__in = target_ids,
+ ).delete()
+ deleted_count = per_model.get( EventDefinition._meta.label, 0 )
+ if deleted_count:
+ logger.debug(
+ f'Removed {deleted_count} integration EventDefinitions '
+ f'for integration_id={integration_id} '
+ f'over {len(entity_id_list)} entities'
+ )
+ return deleted_count
diff --git a/src/hi/integrations/tests/test_entity_operations.py b/src/hi/integrations/tests/test_entity_operations.py
index 8b6770ef..7db63b14 100644
--- a/src/hi/integrations/tests/test_entity_operations.py
+++ b/src/hi/integrations/tests/test_entity_operations.py
@@ -13,6 +13,8 @@ from django.test import TestCase
from hi.apps.attribute.enums import AttributeType, AttributeValueType
from hi.apps.entity.models import Entity, EntityAttribute, EntityState, EntityStateDelegation
+from hi.apps.event.models import EventClause, EventDefinition
+from hi.apps.sense.models import Sensor
from hi.integrations.entity_operations import EntityIntegrationOperations
logging.disable(logging.CRITICAL)
@@ -533,3 +535,195 @@ class PreserveWithUserDataNamePreservationTests(TestCase):
# Detached state is signaled by the previous_integration_* columns.
self.assertEqual(entity.previous_integration_id, 'hass')
self.assertIsNone(entity.integration_id)
+
+
+class EventDefinitionCleanupTests(TestCase):
+ """
+ Phase 2 wiring: preserve_with_user_data and the hard-delete branch
+ of remove_entities_with_closure must remove integration-owned
+ EventDefinitions for the affected entities. User-owned
+ EventDefinitions are intentionally left untouched (see policy in
+ EventDefinitionOperations).
+ """
+
+ INTEGRATION_ID = 'test_integration'
+ OTHER_INTEGRATION_ID = 'other_integration'
+
+ def _make_integration_entity(self, name, integration_id=INTEGRATION_ID):
+ entity = Entity.objects.create(
+ name=name,
+ entity_type_str='CAMERA',
+ integration_id=integration_id,
+ integration_name=f'device_{name}',
+ )
+ # Force the preserve path: give the entity user-created data.
+ EntityAttribute.objects.create(
+ entity=entity,
+ name='User Note',
+ value='retain me',
+ value_type_str=str(AttributeValueType.TEXT),
+ attribute_type_str=str(AttributeType.CUSTOM),
+ )
+ return entity
+
+ def _make_state_with_integration_sensor(self, entity):
+ # The integration sensor + state shape that converters produce.
+ # The sensor's integration_id presence is what
+ # EntityUserDataDetector uses to classify the state as
+ # integration-related (so it becomes orphaned and deleted on
+ # preserve).
+ state = EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='MOVEMENT',
+ name=f'{entity.name} Motion',
+ )
+ Sensor.objects.create(
+ entity_state=state,
+ name=f'{entity.name} Sensor',
+ sensor_type_str='DEFAULT',
+ integration_id=self.INTEGRATION_ID,
+ integration_name=f'sensor_{entity.name}',
+ )
+ return state
+
+ def _make_event_def(self, name, integration_id=INTEGRATION_ID):
+ return EventDefinition.objects.create(
+ name=name,
+ event_type_str='SECURITY',
+ event_window_secs=60,
+ dedupe_window_secs=300,
+ integration_id=integration_id,
+ integration_name=f'event_{name}' if integration_id else None,
+ )
+
+ def test_preserve_removes_integration_event_definition(self):
+ entity = self._make_integration_entity('cam')
+ state = self._make_state_with_integration_sensor(entity)
+ event_def = self._make_event_def('cam alarm')
+ EventClause.objects.create(
+ event_definition=event_def,
+ entity_state=state,
+ value='active',
+ )
+
+ EntityIntegrationOperations.preserve_with_user_data(
+ entity=entity,
+ integration_name=self.INTEGRATION_ID,
+ )
+
+ self.assertFalse(EventDefinition.objects.filter(id=event_def.id).exists())
+
+ def test_preserve_leaves_user_event_definition_untouched(self):
+ # User-owned EventDefinition referencing the entity's state must
+ # survive disconnect. This documents the deferred gap: the
+ # CASCADE on EventClause.entity_state will still delete the
+ # clause when the orphaned state is deleted, leaving the
+ # EventDefinition silently semantically changed — that broader
+ # UX issue is out of scope here.
+ entity = self._make_integration_entity('cam')
+ state = self._make_state_with_integration_sensor(entity)
+ user_event_def = self._make_event_def('user rule', integration_id=None)
+ EventClause.objects.create(
+ event_definition=user_event_def,
+ entity_state=state,
+ value='active',
+ )
+
+ EntityIntegrationOperations.preserve_with_user_data(
+ entity=entity,
+ integration_name=self.INTEGRATION_ID,
+ )
+
+ self.assertTrue(EventDefinition.objects.filter(id=user_event_def.id).exists())
+
+ def test_preserve_leaves_other_integration_event_definition_untouched(self):
+ entity = self._make_integration_entity('cam')
+ state = self._make_state_with_integration_sensor(entity)
+ other_event_def = self._make_event_def(
+ 'other', integration_id=self.OTHER_INTEGRATION_ID,
+ )
+ EventClause.objects.create(
+ event_definition=other_event_def,
+ entity_state=state,
+ value='active',
+ )
+
+ EntityIntegrationOperations.preserve_with_user_data(
+ entity=entity,
+ integration_name=self.INTEGRATION_ID,
+ )
+
+ self.assertTrue(EventDefinition.objects.filter(id=other_event_def.id).exists())
+
+ def test_hard_delete_removes_integration_event_definition(self):
+ # No user data → remove_entities_with_closure takes the
+ # hard-delete branch. Without the explicit cleanup, CASCADE
+ # from Entity.delete() reaches EventClause but stops short
+ # of EventDefinition.
+ entity = Entity.objects.create(
+ name='cam',
+ entity_type_str='CAMERA',
+ integration_id=self.INTEGRATION_ID,
+ integration_name='device_cam',
+ )
+ state = EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='MOVEMENT',
+ )
+ event_def = self._make_event_def('cam alarm')
+ EventClause.objects.create(
+ event_definition=event_def,
+ entity_state=state,
+ value='active',
+ )
+
+ EntityIntegrationOperations.remove_entities_with_closure(
+ seed_entity_ids=[entity.id],
+ integration_name=self.INTEGRATION_ID,
+ preserve_user_data=False,
+ )
+
+ self.assertFalse(Entity.objects.filter(id=entity.id).exists())
+ self.assertFalse(EventDefinition.objects.filter(id=event_def.id).exists())
+
+ def test_closure_expansion_removes_event_definitions_on_delegate(self):
+ # remove_entities_with_closure pulls in delegate entities. A
+ # delegate's own integration-owned EventDefinitions must be
+ # removed too — the cleanup is per-entity inside the loop.
+ principal = Entity.objects.create(
+ name='principal',
+ entity_type_str='CAMERA',
+ integration_id=self.INTEGRATION_ID,
+ integration_name='principal_device',
+ )
+ principal_state = EntityState.objects.create(
+ entity=principal, entity_state_type_str='DISCRETE',
+ )
+ delegate = Entity.objects.create(
+ name='delegate',
+ entity_type_str='AREA',
+ integration_id=self.INTEGRATION_ID,
+ integration_name='delegate_device',
+ )
+ EntityStateDelegation.objects.create(
+ entity_state=principal_state,
+ delegate_entity=delegate,
+ )
+ delegate_state = EntityState.objects.create(
+ entity=delegate, entity_state_type_str='MOVEMENT',
+ )
+ delegate_event_def = self._make_event_def('delegate alarm')
+ EventClause.objects.create(
+ event_definition=delegate_event_def,
+ entity_state=delegate_state,
+ value='active',
+ )
+
+ EntityIntegrationOperations.remove_entities_with_closure(
+ seed_entity_ids=[principal.id],
+ integration_name=self.INTEGRATION_ID,
+ preserve_user_data=False,
+ )
+
+ self.assertFalse(Entity.objects.filter(id__in=[principal.id, delegate.id]).exists())
+ self.assertFalse(EventDefinition.objects.filter(id=delegate_event_def.id).exists())
diff --git a/src/hi/integrations/tests/test_event_definition_operations.py b/src/hi/integrations/tests/test_event_definition_operations.py
new file mode 100644
index 00000000..4b5f5751
--- /dev/null
+++ b/src/hi/integrations/tests/test_event_definition_operations.py
@@ -0,0 +1,286 @@
+"""
+Unit tests for EventDefinitionOperations.
+
+Pins the integration-scoped deletion semantics: only EventDefinition
+rows whose own integration_id matches are removed, even when a
+user-owned EventDefinition or one owned by a different integration
+references the same EntityState.
+"""
+
+import logging
+
+from django.test import TestCase
+
+from hi.apps.entity.models import Entity, EntityState
+from hi.apps.event.models import AlarmAction, EventClause, EventDefinition
+
+from hi.integrations.event_definition_operations import EventDefinitionOperations
+
+logging.disable(logging.CRITICAL)
+
+
+class _FixtureMixin:
+ """
+ Small builders shared across the test classes. Kept here rather
+ than in BaseTestCase because they're only useful to this module.
+ """
+
+ INTEGRATION_ID = 'test_integration'
+ OTHER_INTEGRATION_ID = 'other_integration'
+
+ def _make_entity(self, name, integration_id=INTEGRATION_ID, integration_name=None):
+ return Entity.objects.create(
+ name=name,
+ entity_type_str='LIGHT',
+ integration_id=integration_id,
+ integration_name=integration_name or f'device_{name}',
+ )
+
+ def _make_state(self, entity, name='state'):
+ return EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='ON_OFF',
+ name=name,
+ )
+
+ def _make_event_def(self, name, integration_id=INTEGRATION_ID, integration_name=None):
+ return EventDefinition.objects.create(
+ name=name,
+ event_type_str='SECURITY',
+ event_window_secs=60,
+ dedupe_window_secs=300,
+ integration_id=integration_id,
+ integration_name=integration_name,
+ )
+
+ def _attach_clause(self, event_def, entity_state, value='on'):
+ return EventClause.objects.create(
+ event_definition=event_def,
+ entity_state=entity_state,
+ value=value,
+ )
+
+
+class DeleteForIntegrationTests(_FixtureMixin, TestCase):
+
+ def test_deletes_only_matching_integration(self):
+ # Three EventDefinitions: target integration, other integration, user-owned.
+ target = self._make_event_def('target', integration_id=self.INTEGRATION_ID)
+ other = self._make_event_def('other', integration_id=self.OTHER_INTEGRATION_ID)
+ user_owned = self._make_event_def('user', integration_id=None)
+
+ deleted = EventDefinitionOperations.delete_for_integration(self.INTEGRATION_ID)
+
+ self.assertEqual(deleted, 1)
+ self.assertFalse(EventDefinition.objects.filter(id=target.id).exists())
+ self.assertTrue(EventDefinition.objects.filter(id=other.id).exists())
+ self.assertTrue(EventDefinition.objects.filter(id=user_owned.id).exists())
+
+ def test_no_match_returns_zero(self):
+ self._make_event_def('user', integration_id=None)
+ self.assertEqual(
+ EventDefinitionOperations.delete_for_integration(self.INTEGRATION_ID), 0,
+ )
+
+ def test_empty_integration_id_returns_zero_without_deleting(self):
+ # Defensive: caller passing None/empty must not nuke every user-owned
+ # EventDefinition (those have integration_id=NULL and would match a
+ # naive filter on integration_id=None).
+ user_owned = self._make_event_def('user', integration_id=None)
+
+ deleted = EventDefinitionOperations.delete_for_integration('')
+ self.assertEqual(deleted, 0)
+ self.assertTrue(EventDefinition.objects.filter(id=user_owned.id).exists())
+
+ deleted = EventDefinitionOperations.delete_for_integration(None)
+ self.assertEqual(deleted, 0)
+ self.assertTrue(EventDefinition.objects.filter(id=user_owned.id).exists())
+
+
+class DeleteForEntityTests(_FixtureMixin, TestCase):
+
+ def test_deletes_integration_event_def_referencing_entity(self):
+ entity = self._make_entity('cam')
+ state = self._make_state(entity)
+ event_def = self._make_event_def('cam alarm')
+ self._attach_clause(event_def, state)
+
+ deleted = EventDefinitionOperations.delete_for_entity(entity)
+
+ self.assertEqual(deleted, 1)
+ self.assertFalse(EventDefinition.objects.filter(id=event_def.id).exists())
+
+ def test_leaves_user_owned_event_def_untouched(self):
+ entity = self._make_entity('cam')
+ state = self._make_state(entity)
+ user_event_def = self._make_event_def('user rule', integration_id=None)
+ self._attach_clause(user_event_def, state)
+
+ deleted = EventDefinitionOperations.delete_for_entity(entity)
+
+ self.assertEqual(deleted, 0)
+ self.assertTrue(EventDefinition.objects.filter(id=user_event_def.id).exists())
+
+ def test_leaves_other_integration_event_def_untouched(self):
+ # An EventDefinition owned by a *different* integration that happens
+ # to reference this entity's state must not be deleted by a disconnect
+ # of this integration. (Rare in practice, but the predicate must
+ # respect ownership.)
+ entity = self._make_entity('cam')
+ state = self._make_state(entity)
+ other_event_def = self._make_event_def('other', integration_id=self.OTHER_INTEGRATION_ID)
+ self._attach_clause(other_event_def, state)
+
+ deleted = EventDefinitionOperations.delete_for_entity(entity)
+
+ self.assertEqual(deleted, 0)
+ self.assertTrue(EventDefinition.objects.filter(id=other_event_def.id).exists())
+
+ def test_no_op_when_entity_has_no_integration(self):
+ # Entity already detached (integration_id NULL): caller can invoke
+ # delete_for_entity unconditionally and get a clean no-op.
+ entity = Entity.objects.create(name='detached', entity_type_str='LIGHT')
+ state = self._make_state(entity)
+ event_def = self._make_event_def('orphan-but-integration-owned')
+ self._attach_clause(event_def, state)
+
+ deleted = EventDefinitionOperations.delete_for_entity(entity)
+
+ self.assertEqual(deleted, 0)
+ self.assertTrue(EventDefinition.objects.filter(id=event_def.id).exists())
+
+ def test_event_def_with_no_matching_clause_untouched(self):
+ # Integration-owned EventDefinition whose clauses do NOT reference
+ # this entity's states is left alone — delete_for_entity is scoped
+ # to entities, not to whole-integration cleanup.
+ entity = self._make_entity('cam')
+ other_entity = self._make_entity('other_cam')
+ other_state = self._make_state(other_entity)
+ event_def = self._make_event_def('other rule')
+ self._attach_clause(event_def, other_state)
+
+ deleted = EventDefinitionOperations.delete_for_entity(entity)
+
+ self.assertEqual(deleted, 0)
+ self.assertTrue(EventDefinition.objects.filter(id=event_def.id).exists())
+
+ def test_cascade_removes_clauses_and_actions(self):
+ # Regression: the model-level CASCADE on EventClause/AlarmAction
+ # parents should remove children when the parent EventDefinition
+ # is deleted by the helper.
+ entity = self._make_entity('cam')
+ state = self._make_state(entity)
+ event_def = self._make_event_def('cam alarm')
+ clause = self._attach_clause(event_def, state)
+ action = AlarmAction.objects.create(
+ event_definition=event_def,
+ security_level_str='HIGH',
+ alarm_level_str='CRITICAL',
+ alarm_lifetime_secs=600,
+ )
+
+ EventDefinitionOperations.delete_for_entity(entity)
+
+ self.assertFalse(EventClause.objects.filter(id=clause.id).exists())
+ self.assertFalse(AlarmAction.objects.filter(id=action.id).exists())
+
+
+class DeleteForEntityClosureTests(_FixtureMixin, TestCase):
+
+ def test_batch_deletes_across_multiple_entities(self):
+ entity_a = self._make_entity('a')
+ entity_b = self._make_entity('b')
+ state_a = self._make_state(entity_a)
+ state_b = self._make_state(entity_b)
+
+ ed_a = self._make_event_def('rule a')
+ self._attach_clause(ed_a, state_a)
+ ed_b = self._make_event_def('rule b')
+ self._attach_clause(ed_b, state_b)
+
+ deleted = EventDefinitionOperations.delete_for_entity_closure(
+ entity_ids=[entity_a.id, entity_b.id],
+ integration_id=self.INTEGRATION_ID,
+ )
+
+ self.assertEqual(deleted, 2)
+ self.assertFalse(EventDefinition.objects.filter(id__in=[ed_a.id, ed_b.id]).exists())
+
+ def test_distinct_when_event_def_spans_multiple_entities(self):
+ # An EventDefinition with clauses on two different entities, both in
+ # the closure, must only be counted/deleted once.
+ entity_a = self._make_entity('a')
+ entity_b = self._make_entity('b')
+ state_a = self._make_state(entity_a)
+ state_b = self._make_state(entity_b)
+
+ ed = self._make_event_def('multi-clause')
+ self._attach_clause(ed, state_a, value='on')
+ self._attach_clause(ed, state_b, value='off')
+
+ deleted = EventDefinitionOperations.delete_for_entity_closure(
+ entity_ids=[entity_a.id, entity_b.id],
+ integration_id=self.INTEGRATION_ID,
+ )
+
+ self.assertEqual(deleted, 1)
+ self.assertFalse(EventDefinition.objects.filter(id=ed.id).exists())
+
+ def test_partial_closure_still_matches(self):
+ # An integration EventDefinition with clauses on two entities where
+ # only ONE is in the closure: still deleted (any matching clause
+ # qualifies). Consistent with policy — the EventDefinition's purpose
+ # was tied to the integration, and one of its referenced states is
+ # disappearing.
+ entity_a = self._make_entity('a')
+ entity_b = self._make_entity('b')
+ state_a = self._make_state(entity_a)
+ state_b = self._make_state(entity_b)
+
+ ed = self._make_event_def('multi-clause partial')
+ self._attach_clause(ed, state_a, value='on')
+ self._attach_clause(ed, state_b, value='off')
+
+ deleted = EventDefinitionOperations.delete_for_entity_closure(
+ entity_ids=[entity_a.id],
+ integration_id=self.INTEGRATION_ID,
+ )
+
+ self.assertEqual(deleted, 1)
+ self.assertFalse(EventDefinition.objects.filter(id=ed.id).exists())
+
+ def test_empty_inputs_return_zero(self):
+ self._make_event_def('user', integration_id=None)
+
+ self.assertEqual(
+ EventDefinitionOperations.delete_for_entity_closure(
+ entity_ids=[], integration_id=self.INTEGRATION_ID,
+ ), 0,
+ )
+ self.assertEqual(
+ EventDefinitionOperations.delete_for_entity_closure(
+ entity_ids=[1, 2, 3], integration_id=None,
+ ), 0,
+ )
+ self.assertEqual(
+ EventDefinitionOperations.delete_for_entity_closure(
+ entity_ids=[1, 2, 3], integration_id='',
+ ), 0,
+ )
+
+ def test_user_owned_with_clause_on_closure_entity_untouched(self):
+ # Symmetric to delete_for_entity's user-owned test: user-owned
+ # EventDefinitions are never touched, even when the closure
+ # includes the entity their clauses reference.
+ entity = self._make_entity('cam')
+ state = self._make_state(entity)
+ user_event_def = self._make_event_def('user rule', integration_id=None)
+ self._attach_clause(user_event_def, state)
+
+ deleted = EventDefinitionOperations.delete_for_entity_closure(
+ entity_ids=[entity.id],
+ integration_id=self.INTEGRATION_ID,
+ )
+
+ self.assertEqual(deleted, 0)
+ self.assertTrue(EventDefinition.objects.filter(id=user_event_def.id).exists())
diff --git a/src/hi/integrations/tests/test_integration_manager.py b/src/hi/integrations/tests/test_integration_manager.py
index 2a4e9dea..61f52081 100644
--- a/src/hi/integrations/tests/test_integration_manager.py
+++ b/src/hi/integrations/tests/test_integration_manager.py
@@ -10,7 +10,8 @@ from unittest.mock import Mock, AsyncMock, patch
from django.test import TestCase
from hi.apps.attribute.enums import AttributeType, AttributeValueType
-from hi.apps.entity.models import Entity, EntityAttribute
+from hi.apps.entity.models import Entity, EntityAttribute, EntityState
+from hi.apps.event.models import EventClause, EventDefinition
from hi.integrations.exceptions import IntegrationConnectionError
from hi.integrations.integration_manager import IntegrationManager
from hi.integrations.integration_data import IntegrationData
@@ -712,6 +713,118 @@ class IntegrationManagerTestCase(TestCase):
# Configuration attributes retained even when entities all deleted.
self.assertEqual(integration.attributes.count(), 1)
+ def _attach_integration_event_def(self, entity, integration_id, name='alarm'):
+ """Attach an integration-owned EventDefinition referencing one of
+ the entity's states. Used by the disable-EventDefinition-cleanup
+ regression tests below."""
+ state = EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='MOVEMENT',
+ name=f'{entity.name} State',
+ )
+ event_def = EventDefinition.objects.create(
+ name=name,
+ event_type_str='SECURITY',
+ event_window_secs=60,
+ dedupe_window_secs=300,
+ integration_id=integration_id,
+ integration_name=f'event_{entity.id}',
+ )
+ EventClause.objects.create(
+ event_definition=event_def,
+ entity_state=state,
+ value='active',
+ )
+ return event_def
+
+ def test_disable_safe_removes_integration_event_definitions(self):
+ """Issue #288: SAFE-disable removes integration-owned EventDefinitions
+ for both hard-deleted (no user data) and preserved (user data)
+ entities. The cleanup happens via EntityIntegrationOperations
+ regardless of which branch the entity takes."""
+ manager = IntegrationManager()
+ manager.reset_for_testing()
+
+ integration_id = 'disable_safe_event_def_test'
+ _, data, integration_only_entity, user_data_entity = (
+ self._make_integration_with_entities(integration_id, include_user_data_entity=True)
+ )
+ no_user_event_def = self._attach_integration_event_def(
+ integration_only_entity, integration_id, name='no_user_alarm',
+ )
+ preserve_event_def = self._attach_integration_event_def(
+ user_data_entity, integration_id, name='preserve_alarm',
+ )
+
+ with patch.object(manager, '_stop_integration_monitor'):
+ manager.disable_integration(data, mode=IntegrationDisableMode.SAFE)
+
+ self.assertFalse(EventDefinition.objects.filter(id=no_user_event_def.id).exists())
+ self.assertFalse(EventDefinition.objects.filter(id=preserve_event_def.id).exists())
+
+ def test_disable_all_removes_integration_event_definitions(self):
+ """Issue #288: ALL-disable hard-deletes every entity and must also
+ remove all integration-owned EventDefinitions. CASCADE from
+ Entity.delete() reaches the children but stops short of the
+ EventDefinition parent — explicit cleanup in the hard-delete
+ branch covers it."""
+ manager = IntegrationManager()
+ manager.reset_for_testing()
+
+ integration_id = 'disable_all_event_def_test'
+ _, data, integration_only_entity, user_data_entity = (
+ self._make_integration_with_entities(integration_id, include_user_data_entity=True)
+ )
+ event_def_a = self._attach_integration_event_def(
+ integration_only_entity, integration_id, name='alarm_a',
+ )
+ event_def_b = self._attach_integration_event_def(
+ user_data_entity, integration_id, name='alarm_b',
+ )
+
+ with patch.object(manager, '_stop_integration_monitor'):
+ manager.disable_integration(data, mode=IntegrationDisableMode.ALL)
+
+ self.assertFalse(EventDefinition.objects.filter(
+ id__in=[event_def_a.id, event_def_b.id],
+ ).exists())
+
+ def test_disable_does_not_touch_other_integration_event_definitions(self):
+ """Disabling one integration must not collateral-remove
+ EventDefinitions owned by another integration, even when the
+ other integration's EventDefinitions reference entity states
+ that share names with the disconnecting integration's."""
+ manager = IntegrationManager()
+ manager.reset_for_testing()
+
+ integration_id = 'disable_isolation_test'
+ _, data, integration_only_entity, _ = (
+ self._make_integration_with_entities(
+ integration_id, include_user_data_entity=False,
+ )
+ )
+ target_event_def = self._attach_integration_event_def(
+ integration_only_entity, integration_id, name='target',
+ )
+
+ # Independent entity + EventDefinition owned by a different
+ # integration — must survive.
+ other_entity = Entity.objects.create(
+ name='Other Integration Entity',
+ entity_type_str='LIGHT',
+ integration_id='other_integration',
+ integration_name='other_device',
+ )
+ other_event_def = self._attach_integration_event_def(
+ other_entity, 'other_integration', name='other',
+ )
+
+ with patch.object(manager, '_stop_integration_monitor'):
+ manager.disable_integration(data, mode=IntegrationDisableMode.ALL)
+
+ self.assertFalse(EventDefinition.objects.filter(id=target_event_def.id).exists())
+ self.assertTrue(EventDefinition.objects.filter(id=other_event_def.id).exists())
+
def test_disable_integration_stops_monitor_before_entity_changes(self):
"""Monitors must stop before any entity mutation to avoid races with sync."""
manager = IntegrationManager()
diff --git a/src/hi/integrations/tests/test_integration_synchronizer.py b/src/hi/integrations/tests/test_integration_synchronizer.py
index a513ae23..a9f9a860 100644
--- a/src/hi/integrations/tests/test_integration_synchronizer.py
+++ b/src/hi/integrations/tests/test_integration_synchronizer.py
@@ -24,6 +24,7 @@ from django.test import TestCase, TransactionTestCase
from hi.apps.attribute.enums import AttributeType
from hi.apps.entity.models import Entity, EntityAttribute, EntityState
+from hi.apps.event.models import EventClause, EventDefinition
from hi.apps.sense.models import Sensor
from hi.apps.control.models import Controller
from hi.integrations.integration_synchronizer import IntegrationSynchronizer
@@ -336,6 +337,67 @@ class IntegrationSynchronizerRemovalTestCase(TestCase):
# User sensor should be preserved
self.assertTrue(Sensor.objects.filter(id=user_sensor2.id).exists())
+ def test_sync_remove_no_user_data_removes_event_definition(self):
+ """Issue #288: sync-time refresh removal of an entity with no
+ user data takes the hard-delete branch; integration-owned
+ EventDefinitions referencing that entity must be cleaned up
+ even though Entity.delete()'s CASCADE only reaches the
+ EventClause child."""
+ event_def = EventDefinition.objects.create(
+ name='Sync Removal Alarm',
+ event_type_str='SECURITY',
+ event_window_secs=60,
+ dedupe_window_secs=300,
+ integration_id='test_integration',
+ integration_name='event_sync_removal',
+ )
+ EventClause.objects.create(
+ event_definition=event_def,
+ entity_state=self.entity_state,
+ value='active',
+ )
+
+ self.synchronizer._remove_entity_intelligently(
+ self.entity, self.result,
+ )
+
+ self.assertFalse(EventDefinition.objects.filter(id=event_def.id).exists())
+
+ def test_sync_remove_with_user_data_removes_integration_event_definition(self):
+ """Issue #288: sync-time refresh removal of a preserved entity
+ (entity stays, integration components stripped) must also
+ remove the integration-owned EventDefinition."""
+ EntityAttribute.objects.create(
+ entity=self.entity,
+ name='User Note',
+ value='retain me',
+ value_type_str='TEXT',
+ attribute_type_str=str(AttributeType.CUSTOM),
+ )
+ event_def = EventDefinition.objects.create(
+ name='Preserve Cycle Alarm',
+ event_type_str='SECURITY',
+ event_window_secs=60,
+ dedupe_window_secs=300,
+ integration_id='test_integration',
+ integration_name='event_preserve_cycle',
+ )
+ EventClause.objects.create(
+ event_definition=event_def,
+ entity_state=self.entity_state,
+ value='active',
+ )
+
+ self.synchronizer._remove_entity_intelligently(
+ self.entity, self.result,
+ )
+
+ # Entity preserved (user data branch), but the integration-owned
+ # EventDefinition was removed.
+ self.entity.refresh_from_db()
+ self.assertIsNone(self.entity.integration_id)
+ self.assertFalse(EventDefinition.objects.filter(id=event_def.id).exists())
+
def test_remove_entity_with_no_states(self):
"""Test deletion of entity with no entity states."""
# Remove the default entity state
diff --git a/src/hi/services/hass/tests/test_hass_converter_create.py b/src/hi/services/hass/tests/test_hass_converter_create.py
index a927f99b..26c0c122 100644
--- a/src/hi/services/hass/tests/test_hass_converter_create.py
+++ b/src/hi/services/hass/tests/test_hass_converter_create.py
@@ -15,7 +15,10 @@ import logging
from django.test import TestCase
-from hi.apps.entity.models import Entity, EntityState
+from hi.apps.attribute.enums import AttributeType, AttributeValueType
+from hi.apps.entity.models import Entity, EntityAttribute, EntityState
+from hi.apps.event.models import EventDefinition
+from hi.integrations.entity_operations import EntityIntegrationOperations
from hi.services.hass.hass_converter import HassConverter
from hi.services.hass.hass_metadata import HassMetaData
from hi.services.hass.hass_models import HassDevice
@@ -156,3 +159,107 @@ class CreateModelsForHassDeviceReconnectContractTests(TestCase):
existing.refresh_from_db()
self.assertEqual(existing.integration_id, HassMetaData.integration_id)
self.assertIsNotNone(existing.integration_name)
+
+
+class EventDefinitionLifecycleCycleTests(TestCase):
+ """
+ Issue #288 Phase 3: end-to-end EventDefinition lifecycle for HASS
+ across disable/re-enable cycles. Verifies that integration-owned
+ EventDefinitions return to a stable count rather than accumulating.
+
+ Uses a binary_sensor + motion device_class state — the converter
+ maps that to ``EntityStateType.MOVEMENT`` and creates a
+ ``create_movement_event_definition`` when ``add_alarm_events=True``.
+ A single state shape is enough to exercise the cycle; the
+ connectivity / open_close / battery branches share the same
+ cleanup-and-recreate dispatch.
+ """
+
+ def _build_motion_sensor_device(self, device_id='hallway_motion'):
+ api_dict = {
+ 'entity_id': f'binary_sensor.{device_id}',
+ 'state': 'off',
+ 'attributes': {
+ 'friendly_name': device_id.replace('_', ' ').title(),
+ 'device_class': 'motion',
+ },
+ 'last_changed': '2026-01-01T00:00:00+00:00',
+ 'last_reported': '2026-01-01T00:00:00+00:00',
+ 'last_updated': '2026-01-01T00:00:00+00:00',
+ 'context': {'id': 'ctx', 'parent_id': None, 'user_id': None},
+ }
+ hass_state = HassConverter.create_hass_state(api_dict)
+ device = HassDevice(device_id=device_id)
+ device.add_state(hass_state)
+ return device
+
+ def _hass_event_def_count(self):
+ return EventDefinition.objects.filter(
+ integration_id=HassMetaData.integration_id,
+ ).count()
+
+ def test_motion_sensor_creates_one_event_definition(self):
+ # Sanity: the chosen state shape actually drives the
+ # add_alarm_events branch we're exercising.
+ device = self._build_motion_sensor_device()
+ HassConverter.create_models_for_hass_device(
+ hass_device=device,
+ add_alarm_events=True,
+ )
+ self.assertEqual(self._hass_event_def_count(), 1)
+
+ def test_hard_delete_then_recreate_cycle_baseline_count(self):
+ device = self._build_motion_sensor_device()
+ entity = HassConverter.create_models_for_hass_device(
+ hass_device=device,
+ add_alarm_events=True,
+ )
+ self.assertEqual(self._hass_event_def_count(), 1)
+
+ EntityIntegrationOperations.remove_entities_with_closure(
+ seed_entity_ids=[entity.id],
+ integration_name=HassMetaData.integration_id,
+ preserve_user_data=False,
+ )
+ self.assertEqual(self._hass_event_def_count(), 0)
+
+ # Re-import the same upstream device. Without Phase 2 cleanup,
+ # the prior EventDefinition would still be present and we'd see
+ # 2; with the fix, we're back to 1.
+ HassConverter.create_models_for_hass_device(
+ hass_device=self._build_motion_sensor_device(),
+ add_alarm_events=True,
+ )
+ self.assertEqual(self._hass_event_def_count(), 1)
+
+ def test_preserve_then_reconnect_cycle_baseline_count(self):
+ device = self._build_motion_sensor_device()
+ entity = HassConverter.create_models_for_hass_device(
+ hass_device=device,
+ add_alarm_events=True,
+ )
+ EntityAttribute.objects.create(
+ entity=entity,
+ name='User Note',
+ value='retain me',
+ value_type_str=str(AttributeValueType.TEXT),
+ attribute_type_str=str(AttributeType.CUSTOM),
+ )
+ self.assertEqual(self._hass_event_def_count(), 1)
+
+ EntityIntegrationOperations.preserve_with_user_data(
+ entity=entity,
+ integration_name=HassMetaData.integration_id,
+ )
+ self.assertEqual(self._hass_event_def_count(), 0)
+
+ # Reconnect dispatch is the same converter call with
+ # ``entity=existing``. Should recreate exactly one
+ # EventDefinition for the upstream item.
+ entity.refresh_from_db()
+ HassConverter.create_models_for_hass_device(
+ hass_device=self._build_motion_sensor_device(),
+ add_alarm_events=True,
+ entity=entity,
+ )
+ self.assertEqual(self._hass_event_def_count(), 1)
diff --git a/src/hi/services/zoneminder/tests/test_zm_sync.py b/src/hi/services/zoneminder/tests/test_zm_sync.py
index 29cd4bc6..28261523 100644
--- a/src/hi/services/zoneminder/tests/test_zm_sync.py
+++ b/src/hi/services/zoneminder/tests/test_zm_sync.py
@@ -4,9 +4,12 @@ import os
from unittest.mock import Mock, patch, call
from django.test import TestCase
-from hi.apps.entity.models import Entity
+from hi.apps.attribute.enums import AttributeType, AttributeValueType
+from hi.apps.entity.models import Entity, EntityAttribute
+from hi.apps.event.models import EventDefinition
from hi.apps.sense.models import Sensor
+from hi.integrations.entity_operations import EntityIntegrationOperations
from hi.integrations.integration_manager import IntegrationManager
from hi.integrations.sync_result import IntegrationSyncResult
from hi.integrations.transient_models import IntegrationKey
@@ -1111,3 +1114,124 @@ class CreateMonitorEntityReconnectContractTests(TestCase):
self.assertEqual(existing.integration_id, ZmMetaData.integration_id)
self.assertEqual(existing.integration_name, 'monitor.101')
self.assertTrue(existing.has_video_stream)
+
+
+class EventDefinitionLifecycleCycleTests(TestCase):
+ """
+ Issue #288 Phase 3: end-to-end EventDefinition lifecycle across
+ disable/re-enable cycles. Verifies that integration-owned
+ EventDefinitions return to a stable count (one per monitor) instead
+ of accumulating across cycles, on both the hard-delete path and
+ the preserve-and-reconnect path.
+ """
+
+ MONITOR_ID = 77
+
+ def setUp(self):
+ # IntegrationManager is a process-wide singleton; reset its
+ # in-memory state so prior tests in the suite cannot pollute
+ # ours (and ours cannot pollute theirs).
+ IntegrationManager().reset_for_testing()
+
+ self.synchronizer = ZoneMinderSynchronizer()
+
+ self.mock_manager = Mock()
+ self.mock_manager.ZM_MONITOR_INTEGRATION_NAME_PREFIX = 'monitor'
+ self.mock_manager.MOVEMENT_SENSOR_PREFIX = 'monitor.motion'
+ self.mock_manager.MONITOR_FUNCTION_SENSOR_PREFIX = 'monitor.function'
+ self.mock_manager.MOVEMENT_EVENT_PREFIX = 'monitor.motion'
+ # Alarm event creation must be on for this test class — that's
+ # what we're exercising.
+ self.mock_manager.should_add_alarm_events = True
+
+ def make_key(prefix, zm_monitor_id):
+ return IntegrationKey(
+ integration_id=ZmMetaData.integration_id,
+ integration_name=f'{prefix}.{zm_monitor_id}',
+ )
+ self.mock_manager._to_integration_key.side_effect = make_key
+
+ self.synchronizer._zm_manager = self.mock_manager
+
+ def _mock_monitor(self, monitor_id=None, name='Driveway'):
+ monitor = Mock()
+ monitor.id.return_value = monitor_id if monitor_id is not None else self.MONITOR_ID
+ monitor.name.return_value = name
+ return monitor
+
+ def _create_monitor(self, name='Driveway'):
+ result = IntegrationSyncResult(title='Create')
+ return self.synchronizer._create_monitor_entity(
+ zm_monitor=self._mock_monitor(name=name),
+ result=result,
+ )
+
+ def _zm_event_def_count(self):
+ return EventDefinition.objects.filter(
+ integration_id=ZmMetaData.integration_id,
+ ).count()
+
+ def test_hard_delete_then_recreate_cycle_baseline_count(self):
+ # Cycle: create, hard-delete, recreate. Without Phase 2 cleanup
+ # the EventDefinition would accumulate; with it, count returns
+ # to exactly one.
+ self._create_monitor()
+ self.assertEqual(self._zm_event_def_count(), 1)
+
+ # Take the hard-delete branch (no user data on the entity).
+ EntityIntegrationOperations.remove_entities_with_closure(
+ seed_entity_ids=[
+ Entity.objects.get(integration_id=ZmMetaData.integration_id).id,
+ ],
+ integration_name=ZmMetaData.integration_id,
+ preserve_user_data=False,
+ )
+ self.assertEqual(self._zm_event_def_count(), 0)
+
+ # Recreate (next sync sees the monitor as new).
+ self._create_monitor()
+ self.assertEqual(self._zm_event_def_count(), 1)
+
+ # One more cycle to be sure we're not just clean-on-first-loop.
+ EntityIntegrationOperations.remove_entities_with_closure(
+ seed_entity_ids=[
+ Entity.objects.get(integration_id=ZmMetaData.integration_id).id,
+ ],
+ integration_name=ZmMetaData.integration_id,
+ preserve_user_data=False,
+ )
+ self._create_monitor()
+ self.assertEqual(self._zm_event_def_count(), 1)
+
+ def test_preserve_then_reconnect_cycle_baseline_count(self):
+ # Cycle: create, preserve-disconnect (user data forces SAFE
+ # branch), reconnect via _rebuild_integration_components.
+ # End state: exactly one integration-owned EventDefinition.
+ entity = self._create_monitor()
+ EntityAttribute.objects.create(
+ entity=entity,
+ name='User Note',
+ value='retain me',
+ value_type_str=str(AttributeValueType.TEXT),
+ attribute_type_str=str(AttributeType.CUSTOM),
+ )
+ self.assertEqual(self._zm_event_def_count(), 1)
+
+ # SAFE path: preserve_with_user_data should remove the
+ # integration EventDefinition.
+ EntityIntegrationOperations.preserve_with_user_data(
+ entity=entity,
+ integration_name=ZmMetaData.integration_id,
+ )
+ self.assertEqual(self._zm_event_def_count(), 0)
+
+ # Reconnect path uses the same converter as fresh-create with
+ # entity=existing. Should recreate exactly one EventDefinition.
+ entity.refresh_from_db()
+ result = IntegrationSyncResult(title='Reconnect')
+ self.synchronizer._rebuild_integration_components(
+ entity=entity,
+ upstream=self._mock_monitor(),
+ result=result,
+ )
+ self.assertEqual(self._zm_event_def_count(), 1)
diff --git a/src/hi/static/css/main.css b/src/hi/static/css/main.css
index eeec4eb1..5ed80e48 100644
--- a/src/hi/static/css/main.css
+++ b/src/hi/static/css/main.css
@@ -218,7 +218,7 @@ a.clickable-card:active {
color: var(--on-primary-color);
}
-.bg-secondary, .btn-secondary {
+.bg-secondary, .btn-secondary, .badge-secondary {
color: var(--on-secondary-color) !important;
background-color: var(--secondary-color) !important;
border-color: var(--secondary-highlight-color) !important;