Skip to content

Home Information - Your home, your data, organized.

Python

[Refactor] Decouple Entity Attribute Editing from Edit Mode (#128)

Tony Ce63203a3b627
diff --git a/src/hi/apps/entity/templates/entity/edit/panes/entity_details.html b/src/hi/apps/entity/templates/entity/edit/panes/entity_edit_mode_panel.html
similarity index 79%
rename from src/hi/apps/entity/templates/entity/edit/panes/entity_details.html
rename to src/hi/apps/entity/templates/entity/edit/panes/entity_edit_mode_panel.html
index 5383cc08..40defa64 100644
--- a/src/hi/apps/entity/templates/entity/edit/panes/entity_details.html
+++ b/src/hi/apps/entity/templates/entity/edit/panes/entity_edit_mode_panel.html
@@ -1,5 +1,5 @@
<div class="d-flex justify-content-between mt-2">
- <div class="h4">Item</div>
+ <div class="h4">Item Properties</div>
<div class="">
<a href="{% url 'edit_item_details_close' %}"
class="btn btn-tertiary" role="button" data-async="true">
@@ -8,10 +8,16 @@
</div>
</div>
-<div id="{{ DIVID.ENTITY_EDIT_PANE }}">
- {% include "entity/edit/panes/entity_edit.html" %}
+<div id="{{ DIVID.ENTITY_PROPERTIES_PANE }}">
+ {% include "entity/edit/panes/entity_properties_edit.html" %}
</div>
+{% if entity.integration_id %}
+<div class="my-2">
+ <div class="h6">Integration: <strong>{{ entity.integration_id }}</strong></div>
+</div>
+{% endif %}
+
{% if entity.can_user_delete %}
<div class="">
<a href="{% url 'entity_edit_entity_delete' entity_id=entity.id %}"
@@ -19,8 +25,6 @@
DELETE ITEM
</a>
</div>
-{% else %}
-<div class="h6 text-center">Integration Source: {{ entity.integration_id }}</div>
{% endif %}
{% if entity_position_form %}
@@ -49,4 +53,4 @@
</a>
</div>
-</div>
+</div>
\ No newline at end of file
diff --git a/src/hi/apps/entity/templates/entity/edit/panes/entity_properties_edit.html b/src/hi/apps/entity/templates/entity/edit/panes/entity_properties_edit.html
new file mode 100644
index 00000000..69c266a6
--- /dev/null
+++ b/src/hi/apps/entity/templates/entity/edit/panes/entity_properties_edit.html
@@ -0,0 +1,16 @@
+{% load icons %}
+<form action="{% url 'entity_properties_edit' entity_id=entity.id %}"
+ method="post"
+ class="form" data-async="true">
+ {% csrf_token %}
+ <div>
+ {% include "entity/edit/panes/entity_form.html" %}
+ </div>
+
+ <div class="text-center" >
+ <button id="hi-entity-properties-edit-button" type="submit" class="btn btn-primary"
+ name="action" value="update">
+ {% icon "save" size="sm" css_class="hi-icon-left" %}UPDATE
+ </button>
+ </div>
+</form>
\ No newline at end of file
diff --git a/src/hi/apps/entity/tests/test_views.py b/src/hi/apps/entity/tests/test_views.py
index 3bebf23c..b8654edc 100644
--- a/src/hi/apps/entity/tests/test_views.py
+++ b/src/hi/apps/entity/tests/test_views.py
@@ -38,8 +38,8 @@ class TestEntityEditView(SyncViewTestCase):
self.assertSuccessResponse(response)
self.assertJsonResponse(response)
- def test_post_valid_entity_edit(self):
- """Test successful entity edit with valid form data."""
+ def test_post_valid_entity_edit_with_formset(self):
+ """Test successful entity edit with formset data (full editing)."""
url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})
# Prepare valid form data including required formset management forms
@@ -63,6 +63,28 @@ class TestEntityEditView(SyncViewTestCase):
self.assertEqual(self.entity.name, 'Updated Entity Name')
self.assertEqual(self.entity.entity_type_str, 'wall_switch')
+ def test_post_valid_entity_properties_only(self):
+ """Test successful entity properties edit via EntityPropertiesEditView."""
+
+ url = reverse('entity_properties_edit', kwargs={'entity_id': self.entity.id})
+
+ # Prepare valid form data for properties-only editing
+ # This simulates the entity_properties_edit.html form submission
+ form_data = {
+ 'name': 'Properties Only Update',
+ 'entity_type_str': 'motion_sensor', # Use valid EntityType choice (lowercase enum name)
+ }
+
+ response = self.client.post(url, form_data)
+
+ self.assertSuccessResponse(response)
+ self.assertJsonResponse(response)
+
+ # Verify entity was actually updated
+ self.entity.refresh_from_db()
+ self.assertEqual(self.entity.name, 'Properties Only Update')
+ self.assertEqual(self.entity.entity_type_str, 'motion_sensor')
+
# Tests for form validation errors removed - Django's form validation
# is already thoroughly tested by Django itself. These tests were testing
# Django internals rather than application-specific behavior.
@@ -79,6 +101,56 @@ class TestEntityEditView(SyncViewTestCase):
self.assertEqual(response.status_code, 404)
+class TestEntityPropertiesEditView(SyncViewTestCase):
+ """
+ Tests for EntityPropertiesEditView - handles entity properties (name, type) editing only.
+ This view is used by the sidebar in edit mode and only accepts POST requests.
+ """
+
+ def setUp(self):
+ super().setUp()
+ # Create test entity
+ self.entity = Entity.objects.create(
+ integration_id='test.entity.props',
+ integration_name='test_integration',
+ name='Test Properties Entity',
+ entity_type_str='LIGHT'
+ )
+
+ def test_post_valid_properties_edit(self):
+ """Test successful entity properties edit."""
+ url = reverse('entity_properties_edit', kwargs={'entity_id': self.entity.id})
+
+ form_data = {
+ 'name': 'Updated Properties Name',
+ 'entity_type_str': 'wall_switch',
+ }
+
+ response = self.client.post(url, form_data)
+
+ self.assertSuccessResponse(response)
+ self.assertJsonResponse(response)
+
+ # Verify entity was actually updated
+ self.entity.refresh_from_db()
+ self.assertEqual(self.entity.name, 'Updated Properties Name')
+ self.assertEqual(self.entity.entity_type_str, 'wall_switch')
+
+ def test_nonexistent_entity_returns_404(self):
+ """Test that editing nonexistent entity returns 404."""
+ url = reverse('entity_properties_edit', kwargs={'entity_id': 99999})
+ response = self.client.post(url, {'name': 'Test', 'entity_type_str': 'light'})
+
+ self.assertEqual(response.status_code, 404)
+
+ def test_get_not_allowed(self):
+ """Test that GET requests are not allowed (only POST)."""
+ url = reverse('entity_properties_edit', kwargs={'entity_id': self.entity.id})
+ response = self.client.get(url)
+
+ self.assertEqual(response.status_code, 405)
+
+
class TestEntityAttributeUploadView(SyncViewTestCase):
"""
Tests for EntityAttributeUploadView - demonstrates file upload testing.
diff --git a/src/hi/apps/entity/urls.py b/src/hi/apps/entity/urls.py
index dbd03d43..57c7ccc1 100644
--- a/src/hi/apps/entity/urls.py
+++ b/src/hi/apps/entity/urls.py
@@ -9,6 +9,10 @@ urlpatterns = [
views.EntityEditView.as_view(),
name='entity_edit'),
+ re_path( r'^entity/properties/edit/(?P<entity_id>\d+)$',
+ views.EntityPropertiesEditView.as_view(),
+ name='entity_properties_edit'),
+
re_path( r'^status/(?P<entity_id>\d+)$',
views.EntityStatusView.as_view(),
name='entity_status' ),
diff --git a/src/hi/apps/entity/view_mixins.py b/src/hi/apps/entity/view_mixins.py
index 78cfef5e..68264cc9 100644
--- a/src/hi/apps/entity/view_mixins.py
+++ b/src/hi/apps/entity/view_mixins.py
@@ -22,22 +22,29 @@ class EntityViewMixin:
except Entity.DoesNotExist:
raise Http404( request )
- def entity_edit_response( self,
- request : HttpRequest,
- entity_edit_data : EntityEditData,
- status_code : int = 200 ):
+ def entity_modal_response( self,
+ request : HttpRequest,
+ entity_edit_data : EntityEditData,
+ status_code : int = 200 ):
+ """Return modal response for full entity editing (properties + attributes)"""
context = entity_edit_data.to_template_context()
- if request.view_parameters.is_editing:
- template = get_template( 'entity/edit/panes/entity_edit.html' )
- content = template.render( context, request = request )
- return antinode.response(
- insert_map = {
- DIVID['ENTITY_EDIT_PANE']: content,
- },
- status = status_code,
- )
return antinode.modal_from_template(
request = request,
template_name = 'entity/modals/entity_edit.html',
context = context,
)
+
+ def entity_properties_response( self,
+ request : HttpRequest,
+ entity_edit_data : EntityEditData,
+ status_code : int = 200 ):
+ """Return sidebar response for entity properties editing only (name, type)"""
+ context = entity_edit_data.to_template_context()
+ template = get_template( 'entity/edit/panes/entity_properties_edit.html' )
+ content = template.render( context, request = request )
+ return antinode.response(
+ insert_map = {
+ DIVID['ENTITY_PROPERTIES_PANE']: content,
+ },
+ status = status_code,
+ )
diff --git a/src/hi/apps/entity/views.py b/src/hi/apps/entity/views.py
index bcae5d43..fc983ad0 100644
--- a/src/hi/apps/entity/views.py
+++ b/src/hi/apps/entity/views.py
@@ -21,19 +21,87 @@ from .view_mixins import EntityViewMixin
logger = logging.getLogger(__name__)
-class EntityEditView( View, EntityViewMixin ):
+class BaseEntityEditMixin:
+ """Shared logic for entity editing operations"""
+
+ def _handle_entity_form_save(self, request, entity, entity_form, entity_attribute_formset=None, original_entity_type_str=None):
+ """Handle saving entity form and optional formset with transition logic"""
+ if original_entity_type_str is None:
+ original_entity_type_str = entity.entity_type_str
+
+ transition_response = None
+
+ with transaction.atomic():
+ entity_form.save()
+ if entity_attribute_formset:
+ entity_attribute_formset.save()
+
+ # Handle transitions within same transaction but defer response
+ entity_type_changed = original_entity_type_str != entity.entity_type_str
+ if entity_type_changed:
+ transition_response = self._handle_entity_type_change(request, entity)
+
+ return transition_response
+
+ def _recreate_fresh_formset(self, entity):
+ """Recreate formset to preserve 'max' to show new form"""
+ return forms.EntityAttributeFormSet(
+ instance = entity,
+ prefix = f'entity-{entity.id}',
+ )
+
+ def _handle_entity_type_change(self, request, entity):
+ """Handle EntityType changes with appropriate transition logic"""
+ try:
+ # Always attempt advanced transition handling regardless of mode/view
+ current_location_view = LocationManager().get_default_location_view( request = request )
+ transition_occurred, transition_type = EntityManager().handle_entity_type_transition(
+ entity = entity,
+ location_view = current_location_view,
+ )
+
+ if self._needs_full_page_refresh(transition_occurred, transition_type):
+ return antinode.refresh_response()
+
+ # Simple transitions can continue with sidebar-only refresh
+ # (will fall through to normal response method)
+ return None
+
+ except Exception as e:
+ logger.warning(f'EntityType transition failed: {e}, falling back to page refresh')
+ return antinode.refresh_response()
+
+ def _needs_full_page_refresh(self, transition_occurred, transition_type):
+ """Determine if EntityType change requires full page refresh"""
+ if not transition_occurred:
+ # Transition failed, use page refresh for safety
+ return True
+
+ if transition_type == "path_to_path":
+ # Path style changes only, sidebar refresh sufficient
+ return False
+
+ # All other transitions need full refresh to show visual changes:
+ # - icon_to_icon: New icon type needs to be visible
+ # - icon_to_path: Database structure changed
+ # - path_to_icon: Database structure changed
+ return True
+
+
+class EntityEditView( BaseEntityEditMixin, View, EntityViewMixin ):
+ """Handle full entity editing including attributes - used by modal"""
def get( self, request, *args, **kwargs ):
entity = self.get_entity( request, *args, **kwargs )
entity_edit_data = EntityEditData( entity = entity )
- return self.entity_edit_response(
+ return self.entity_modal_response(
request = request,
entity_edit_data = entity_edit_data,
)
def post( self, request, *args, **kwargs ):
entity = self.get_entity( request, *args, **kwargs )
-
+
# Store original entity_type_str to detect changes
original_entity_type_str = entity.entity_type_str
@@ -44,28 +112,20 @@ class EntityEditView( View, EntityViewMixin ):
instance = entity,
prefix = f'entity-{entity.id}',
)
- if entity_form.is_valid() and entity_attribute_formset.is_valid():
- # Track EntityType change and response needed after transaction
- entity_type_changed = original_entity_type_str != entity.entity_type_str
- transition_response = None
+
+ form_valid = entity_form.is_valid() and entity_attribute_formset.is_valid()
+
+ if form_valid:
+ transition_response = self._handle_entity_form_save(
+ request, entity, entity_form, entity_attribute_formset, original_entity_type_str
+ )
- with transaction.atomic():
- entity_form.save()
- entity_attribute_formset.save()
-
- # Handle transitions within same transaction but defer response
- if entity_type_changed:
- transition_response = self._handle_entity_type_change(request, entity)
-
# Now that transaction is committed, handle any transition response
if transition_response is not None:
return transition_response
- # Recreate to preserve "max" to show new form
- entity_attribute_formset = forms.EntityAttributeFormSet(
- instance = entity,
- prefix = f'entity-{entity.id}',
- )
+ # Recreate formset to preserve "max" to show new form
+ entity_attribute_formset = self._recreate_fresh_formset(entity)
status_code = 200
else:
status_code = 400
@@ -75,48 +135,49 @@ class EntityEditView( View, EntityViewMixin ):
entity_form = entity_form,
entity_attribute_formset = entity_attribute_formset,
)
- return self.entity_edit_response(
+ return self.entity_modal_response(
request = request,
entity_edit_data = entity_edit_data,
status_code = status_code,
)
-
- def _handle_entity_type_change(self, request, entity):
- """Handle EntityType changes with appropriate transition logic"""
- try:
- # Always attempt advanced transition handling regardless of mode/view
- current_location_view = LocationManager().get_default_location_view( request = request )
- transition_occurred, transition_type = EntityManager().handle_entity_type_transition(
- entity = entity,
- location_view = current_location_view,
+
+
+class EntityPropertiesEditView( BaseEntityEditMixin, View, EntityViewMixin ):
+ """Handle entity properties editing (name, type) only - used by sidebar"""
+
+ def post( self, request, *args, **kwargs ):
+ entity = self.get_entity( request, *args, **kwargs )
+
+ # Store original entity_type_str to detect changes
+ original_entity_type_str = entity.entity_type_str
+
+ entity_form = forms.EntityForm( request.POST, instance = entity )
+ form_valid = entity_form.is_valid()
+
+ if form_valid:
+ transition_response = self._handle_entity_form_save(
+ request, entity, entity_form, None, original_entity_type_str
)
- if self._needs_full_page_refresh(transition_occurred, transition_type):
- return antinode.refresh_response()
-
- # Simple transitions can continue with sidebar-only refresh
- # (will fall through to normal entity_edit_response)
- return None
-
- except Exception as e:
- logger.warning(f'EntityType transition failed: {e}, falling back to page refresh')
- return antinode.refresh_response()
-
- def _needs_full_page_refresh(self, transition_occurred, transition_type):
- """Determine if EntityType change requires full page refresh"""
- if not transition_occurred:
- # Transition failed, use page refresh for safety
- return True
+ # Now that transaction is committed, handle any transition response
+ if transition_response is not None:
+ return transition_response
- if transition_type == "path_to_path":
- # Path style changes only, sidebar refresh sufficient
- return False
+ status_code = 200
+ else:
+ status_code = 400
- # All other transitions need full refresh to show visual changes:
- # - icon_to_icon: New icon type needs to be visible
- # - icon_to_path: Database structure changed
- # - path_to_icon: Database structure changed
- return True
+ # For properties editing, we create EntityEditData without formset
+ entity_edit_data = EntityEditData(
+ entity = entity,
+ entity_form = entity_form,
+ entity_attribute_formset = None,
+ )
+ return self.entity_properties_response(
+ request = request,
+ entity_edit_data = entity_edit_data,
+ status_code = status_code,
+ )
class EntityAttributeUploadView( View, EntityViewMixin ):
@@ -141,7 +202,7 @@ class EntityAttributeUploadView( View, EntityViewMixin ):
entity = entity,
entity_attribute_upload_form = entity_attribute_upload_form,
)
- return self.entity_edit_response(
+ return self.entity_modal_response(
request = request,
entity_edit_data = entity_edit_data,
status_code = status_code,
@@ -193,7 +254,7 @@ class EntityStateHistoryView( HiModalView, EntityViewMixin, SensorHistoryMixin )
class EntityDetailsView( HiSideView, EntityViewMixin ):
def get_template_name( self ) -> str:
- return 'entity/edit/panes/entity_details.html'
+ return 'entity/edit/panes/entity_edit_mode_panel.html'
def should_push_url( self ):
return True
diff --git a/src/hi/constants.py b/src/hi/constants.py
index af1b44b6..5027f686 100644
--- a/src/hi/constants.py
+++ b/src/hi/constants.py
@@ -46,8 +46,8 @@ DIVID = {
'LOCATION_EDIT_PANE': 'hi-location-edit',
'LOCATION_VIEW_EDIT_PANE': 'hi-location-view-edit',
- 'ENTITY_EDIT_PANE': 'hi-entity-edit',
'COLLECTION_EDIT_PANE': 'hi-collection-edit',
+ 'ENTITY_PROPERTIES_PANE': 'hi-entity-properties',
'ENTITY_POSITION_EDIT_PANE': 'hi-entity-position-edit',
'COLLECTION_POSITION_EDIT_PANE': 'hi-collection-position-edit',