Home Information - Your home, your data, organized.
Python
Entity View/Edit Modal Redesign (#136)
Tony C193c86eb651c
diff --git a/.claude/agents/frontend-dev.md b/.claude/agents/frontend-dev.mdindex 241b13f9..fa87ce94 100644--- a/.claude/agents/frontend-dev.md+++ b/.claude/agents/frontend-dev.md@@ -95,9 +95,11 @@ You know the project's testing patterns:## Project-Specific Knowledge+You are the expert on:+- All the markdown content in `docs/dev/frontend`+You are familiar with:- The "Hi Grid" template structure and important DIV IDs-- Template conventions from `docs/dev/frontend/frontend-guidelines.md`- Icon system and SVG coordinate operations- The polling system for real-time sensor value updates- Django Pipeline for minified, cache-busting assets@@ -120,4 +122,4 @@ You are familiar with:- Run `make lint` for any source code changes- Test template rendering and AJAX responses properly-When working with this codebase, you understand the Django template system, the minimal JavaScript philosophy, the SVG-based location interface, and the specific patterns used throughout the frontend. You provide expert frontend development assistance while maintaining the project's established design principles.\ No newline at end of file+When working with this codebase, you understand the Django template system, the minimal JavaScript philosophy, the SVG-based location interface, and the specific patterns used throughout the frontend. You provide expert frontend development assistance while maintaining the project's established design principles.diff --git a/.claude/agents/test-engineer.md b/.claude/agents/test-engineer.mdindex fe4ae90c..e228b898 100644--- a/.claude/agents/test-engineer.md+++ b/.claude/agents/test-engineer.md@@ -197,6 +197,13 @@ You are familiar with:- The project's BaseTestCase and ViewTestBase patterns- Development data injection system for runtime behavior modification+If you are running into difficulties that hint there may be some missing project-specific context, search through this docs for informations that may help:+- docs/dev/testing/testing-lessons-learned.md++For examples of test cases, search through this doc to see if any match the test case you are working on:+- docs/dev/testing/test-examples/README.md++## Your Testing Strategy### Database vs Mock Testing Decisions@@ -225,4 +232,4 @@ def test_efficient_entity_loading(self):- Verify data transformations work correctly end-to-end- Test database state changes rather than mocking ORM calls-When working with this codebase, you understand the testing philosophy that emphasizes high-value tests over comprehensive coverage, the specific Django testing patterns used, and the critical importance of avoiding testing anti-patterns. You provide expert testing guidance while ensuring all tests add genuine business value and maintain system quality.\ No newline at end of file+When working with this codebase, you understand the testing philosophy that emphasizes high-value tests over comprehensive coverage, the specific Django testing patterns used, and the critical importance of avoiding testing anti-patterns. You provide expert testing guidance while ensuring all tests add genuine business value and maintain system quality.diff --git a/Makefile b/Makefileindex b466eb02..a63afdaf 100644--- a/Makefile+++ b/Makefile@@ -9,11 +9,16 @@ SCRIPTS = deploy/env-generate.py deploy/run_container.shtest:cd src && ./manage.py test --keepdb+test-fast:+ cd src && ./manage.py test --keepdb --parallel 4+lint:cd src && flake8 --config=.flake8-ci hi/ 2>/dev/nullcheck: test lint+check-fast: test-fast lint+docker-build: Dockerfile@HI_VERSION=$$(cat HI_VERSION); \docker build \diff --git a/docs/CLAUDE.md b/docs/CLAUDE.mdindex 6185e31f..56ad0bde 100644--- a/docs/CLAUDE.md+++ b/docs/CLAUDE.md@@ -173,6 +173,56 @@ During investigation, if an issue involves **both** design/UX work **and** imple- Get explicit "approved for implementation" comment before coding begins- Use GitHub issue linking (`Closes #123`) to maintain traceability between design and implementation issues+#### Design Work Documentation Workflow++When working on design-focused issues (UX improvements, UI redesigns, mockups, wireframes):++**Local Work Directory Structure:**+```bash+# All design work goes in data/design (git ignored)+data/design/issue-{number}/+├── mockup.html # Interactive HTML mockups+├── architecture.md # Technical architecture docs+├── interaction-patterns.md # UX interaction specifications+├── design-summary.md # Executive summary+└── other-design-artifacts.* # Additional files as needed+```++**Design Workflow Process:**+1. **Create issue subdirectory**: `mkdir -p data/design/issue-{number}`+2. **Iterate locally**: Create, refine, and iterate on design documents locally+3. **No repository commits**: Design work products stay local only (`data/` is in .gitignore)+4. **Post to GitHub issue**: Share stable versions via GitHub issue comments/attachments++**GitHub Issue Documentation Pattern:**+```markdown+## Phase X Design Complete - Ready for Review++Brief summary of key decisions and deliverables:++1. **Interactive Mockup** (attached) - HTML file for browser viewing+2. **Architecture Document** (comment below) - Technical specifications+3. **Interaction Patterns** (comment below) - UX behavior definitions++[Key decisions summary...]++Ready for stakeholder review and implementation planning.+```++**Content Organization:**+- **Visual deliverables** (HTML mockups, images): Attach as GitHub issue attachments+- **Textual content** (markdown docs): Post as regular GitHub issue comments+- **Benefits**: Attachments can be downloaded/viewed directly, comments are searchable and linkable++**Design Iteration Process:**+1. Create design documents in `data/design/issue-{number}/`+2. Iterate and refine locally based on feedback+3. Post important checkpoints or final versions to GitHub issue+4. Never commit design work products to repository+5. Maintain audit trail in GitHub issue comments++This workflow keeps the repository clean while providing comprehensive design documentation and stakeholder review capabilities.+5.5. **For Complex Issues - Apply Multi-Phase Strategy** (when applicable):- If issue involves multiple aspects, significant trade-offs, or substantial complexity, apply the multi-phase methodology from [Domain Guidelines](dev/domain/domain-guidelines.md#complex-issue-implementation-strategy)- Post phase breakdown to GitHub issue before starting implementationdiff --git a/docs/dev/backend/backend-guidelines.md b/docs/dev/backend/backend-guidelines.mdindex 0b570512..975d4071 100644--- a/docs/dev/backend/backend-guidelines.md+++ b/docs/dev/backend/backend-guidelines.md@@ -197,7 +197,7 @@ class IntegrationManager(Singleton):## Django Views-**Simple Views**: Our design philophy is to keep the Django view classes in views.py somewhat simple. When where the viws need non-trivial computations, database queries or construction of intricate data structure, we use some helper class to encapsulate the business logic. For example, the method _group_history_by_time() should be moved to a helper class. In this case, given the scope of video browsing, it makes sense for there to be a dedicated class for all the various helpers needed related to this feature.+**Simple Views**: Our design philophy is to keep the Django view classes in views.py somewhat simple. When where the views need non-trivial computations, database queries or construction of intricate data structure, we use some helper class to encapsulate the business logic. For example, the method _group_history_by_time() should be moved to a helper class. In this case, given the scope of video browsing, it makes sense for there to be a dedicated class for all the various helpers needed related to this feature.**URL Names**: Always leverage Django url names and never depend on details and strings of user-facing urls.diff --git a/docs/dev/frontend/frontend-guidelines.md b/docs/dev/frontend/frontend-guidelines.mdindex 7bb2f98a..943212ee 100644--- a/docs/dev/frontend/frontend-guidelines.md+++ b/docs/dev/frontend/frontend-guidelines.md@@ -71,19 +71,16 @@ return {}```-## The "Hi Grid" Template Structure+## Client-Server Namespace Sharing-### Important DIV IDs+- We do not use magic strings as they need to be referenced in multiple places.+- We gathered strings that need to be shared between client and server in `src/hi/constants.py:DIVID`:+- This `DIVID` dict are injected into the template context automatically.+- On the Javascript side, we gather all these same ids in a single place at the beginning of the main.css.+- All other Javascript modules use the Hi.<NAME> namespacing to refer to these.+- All DOM ids and classes that are shared between client and server must adhere to our `DIVID` pattern-These are gathered in `src/hi/constants.py:DIV_IDS`:--- `#hi-main-content` - Main display area, excluding header buttons, footer buttons and side panel-- `#hi-side-content` - Side panel content area-- `#hi-top-buttons` - Top button toolbar area-- `#hi-bottom-buttons` - Bottom button toolbar area-- `#hi-config-integration-tab` - Integrations use this for configuration-related views--These `DIV_IDS` are injected into the template context automatically for use as we do not use magic strings as they need to be referenced in multiple places.+In this way, there is at most two places these ids are used as strings, and both client and server can referenced more safely.## JavaScript Standards@@ -120,8 +117,9 @@ For complete implementation details of the polling system, CSS class application### JavaScript Conventions1. **Module Pattern**: Use revealing module pattern for organization-2. **jQuery Usage**: Use `$` prefix for jQuery objects-3. **Event Delegation**: Use delegated events for dynamic content+2. **jQuery Usage**: Prefix jQuery over native DOM query/manipulation+3. **jQuery Usage**: Use `$` prefix for jQuery objects+4. **Event Delegation**: Use delegated events for dynamic contentExample:```javascriptdiff --git a/docs/dev/frontend/template-conventions.md b/docs/dev/frontend/template-conventions.mdindex 9ecf121d..124831d1 100644--- a/docs/dev/frontend/template-conventions.md+++ b/docs/dev/frontend/template-conventions.md@@ -1,5 +1,17 @@# Template Conventions+## The "Hi Grid" Template Structure++### Important DIVIDs for Main Page Layout++We gathered strings that need to be shared between client and server in `src/hi/constants.py:DIVID`. The important ones that define the top-level page layout of `src/hi/templates/pages/hi_grid.html` are:++- `#hi-main-content` - Main display area, excluding header buttons, footer buttons and side panel+- `#hi-side-content` - Side panel content area+- `#hi-top-buttons` - Top button toolbar area+- `#hi-bottom-buttons` - Bottom button toolbar area+- `#hi-config-integration-tab` - Integrations use this for configuration-related views+## Template Directory Structure### App Module Templates@@ -304,4 +316,4 @@ In development, use template debug mode:- Frontend guidelines: [Frontend Guidelines](frontend-guidelines.md)- Icon system: [Icon System](icon-system.md)- Style guidelines: [Style Guidelines](style-guidelines.md)-- Testing: [UI Testing](ui-testing.md)\ No newline at end of file+- Testing: [UI Testing](ui-testing.md)diff --git a/docs/dev/shared/coding-standards.md b/docs/dev/shared/coding-standards.mdindex 3404a307..67f29864 100644--- a/docs/dev/shared/coding-standards.md+++ b/docs/dev/shared/coding-standards.md@@ -25,6 +25,100 @@## Coding Style+### No "magic" strings++We do not use "magic" or hard-coded strings when needing multiple references. Any string that need to be used in two or more places is a risk of them being mismatched. This includes, but is not limited to:++- All references to urls *must* use the Django url name and reverse() to construct.+- Use enum values or constants/class variables to act as coordination point and provide some amount of compiler help in identifying mismatches. Most needed strings will already have a LabeledEnum type defined, but we should add new ones as needed. See "Enums" in [Back End Guidelines](../backend/backend-guidelines.md).+- All DOM ids and class strings that are shared between client and server must adhere to our `DIVID` pattern. See "Client-Server Namespace Sharing" in [Front End Guidelines](../frontend/frontend-guidelines.md).++### Type Hints++- We add type hints to dataclass fields, method parameters and method return values.+- We do not add type hints to locally declared method variables.+- Some allowed, but not required exceptions:+ - The `request` parameter when appearing in a Django view class.+ - Single parameter methods where the method name or parameter name makes its type unambiguous.+++### Method Parameter Formatting++For readability, besides adding type hints to method parameters, we adhere to the following formatting conventions:+- For methods with a single parameter, or parameters of native types, they can appear in one line with the method name.+- If more than one parameter and app-defined types, then use a multiple line declaration.+- For methods with three or more parameters, we use one line per parameter and align the type names.++**Good Examples**++```+ def set_entity( self, entity_id : int ) -> EntityPath:++ def set_entity_order( self, entity_id : int, rank : int ) -> EntityPath:++ def set_entity_path( self,+ entity_id : int,+ location : Location,+ svg_path_str : str ) -> EntityPath:+```++**Bad Examples**++```+ def set_entity_type( self, entity_id : int, entity_type : EntityType ) -> EntityPath:++ def set_entity_path( self,+ entity_id : int,+ location : Location,+ svg_path_str: str ) -> EntityPath:++ def set_entity_path( self, entity_id : int,+ location : Location, svg_path_str: str ) -> EntityPath:+```++### Explicit Booleans++We prefer to wrap all expression that evaluate to a boolean in `bool()` to make it explicit what type we are expecting:++**Good**+```+ my_variable = bool( len(my_list) > 4 )+```++**Bad***+```+ my_variable = len(my_list) == 4+```++### Complex Boolean Expressions++- For boolean clauses and conditionals where there are multiple clauses, we prefer to explicitly enclose each clause with parentheses in order to make the intention clear.+- We do not rely on the user having a deep understanding of the compiler's ordeer of precedence.+- We use one line per clause unless the combined clauses are very short and obvious.+- Single boolean typed variables or methods that return a boolean do not need paretheses.++**Good**+```+ if is_editing and location_view:+ pass++ if (( hass_state.domain == HassApi.SWITCH_DOMAIN )+ and ( HassApi.LIGHT_DOMAIN in prefixes_seen )):+ pass++ if ( HassApi.BINARY_SENSOR_DOMAIN in domain_set+ and device_class_set.intersection( HassApi.OPEN_CLOSE_DEVICE_CLASS_SET )):+ pass+++```++**Bad***+```+ if hass_state.domain == HassApi.SWITCH_DOMAIN and HassApi.LIGHT_DOMAIN == 'foo':+ pass+```+### Flake8 ConfigurationsThe project uses two different flake8 configurations:@@ -47,6 +141,8 @@ ignore = E129,D203,E201,E202,E203,E221,E231,E251,W293,W291,W391,W503### Generated Code Standards+### Linting+All generated code (including AI-generated code) must comply with `.flake8-ci` configuration:1. **Final Newlines**: All files must end with a single newline characterdiff --git a/docs/dev/testing/test-examples/README.md b/docs/dev/testing/test-examples/README.mdnew file mode 100644index 00000000..ab1355ec--- /dev/null+++ b/docs/dev/testing/test-examples/README.md@@ -0,0 +1,44 @@+# Django Test Pattern Examples++This directory contains concrete examples of well-structured Django tests derived from extensive refactoring work in the HI application.++## Files++### `django-test-patterns-examples.py`+Comprehensive examples showing:+- **CRUD Testing**: Real database objects vs mocking+- **AJAX/JSON Views**: Testing modern async responses+- **Form Validation**: Complete field requirements and file uploads+- **Complex Business Logic**: Entity pairings, many-to-many through models+- **Session Dependencies**: Middleware state requirements+- **Synthetic Data**: Consistent test data generation+- **Error Handling**: 404s, validation errors without mocking++## Usage++When working on Django tests, refer to these examples to:++1. **Avoid anti-patterns** like over-mocking database operations+2. **Follow established patterns** for session setup and form validation+3. **Use proper assertions** for JSON vs HTML responses+4. **Structure test data** consistently with synthetic generators+5. **Test integration flows** rather than just method calls++## Key Principles++- ✅ **Test real behavior** with actual database transactions+- ✅ **Use Django's test framework** as designed (isolated DB transactions)+- ✅ **Test business outcomes** not implementation details+- ✅ **Follow application patterns** for enums, sessions, relationships+- ❌ **Don't mock** basic CRUD, model relationships, or form processing+- ❌ **Don't assume** direct relationships - verify through models/admin++## Context++These patterns were discovered while converting heavily mocked tests to use real objects, resulting in:+- More reliable tests that catch real bugs+- Better documentation of application architecture+- Easier maintenance and debugging+- Higher confidence in system behavior++Use these examples as templates when writing new tests or refactoring existing ones.\ No newline at end of filediff --git a/docs/dev/testing/test-examples/django-test-patterns-examples.py b/docs/dev/testing/test-examples/django-test-patterns-examples.pynew file mode 100644index 00000000..98463603--- /dev/null+++ b/docs/dev/testing/test-examples/django-test-patterns-examples.py@@ -0,0 +1,496 @@+"""+Django Test Pattern Examples - Best Practices from HI Application++This file contains concrete examples of well-structured Django tests that avoid+common anti-patterns. These patterns were derived from extensive refactoring+work to eliminate over-mocking and improve test reliability.+"""++import json+import uuid+from django.urls import reverse+from django.core.files.uploadedfile import SimpleUploadedFile++from hi.apps.collection.models import Collection, CollectionEntity+from hi.apps.entity.models import Entity, EntityStateDelegation+from hi.apps.location.models import Location, LocationView+from hi.apps.collection.enums import CollectionType, CollectionViewType+from hi.apps.entity.enums import EntityType+from hi.apps.location.enums import LocationViewType+from hi.enums import ViewMode, ViewType+from hi.testing.view_test_base import SyncViewTestCase, DualModeViewTestCase+++# =============================================================================+# 1. BASIC CRUD TESTING WITH REAL OBJECTS+# =============================================================================++class ExampleCRUDTestCase(SyncViewTestCase):+ """Example of testing CRUD operations with real database objects."""++ def setUp(self):+ super().setUp()+ # Set required session state+ self.setSessionViewMode(ViewMode.EDIT)++ # Create test objects with proper enum string conversion+ self.collection = Collection.objects.create(+ name='Test Collection',+ collection_type_str=str(CollectionType.OTHER), # Always use str() for enums+ collection_view_type_str=str(CollectionViewType.GRID),+ order_id=0 # Make it the default+ )++ self.entity = Entity.objects.create(+ name='Test Entity',+ entity_type_str=str(EntityType.LIGHT)+ )++ def test_create_with_real_objects(self):+ """Example: Test creation using real objects, not mocks."""+ # Verify initial state+ self.assertEqual(Collection.objects.count(), 1)++ url = reverse('collection_add')+ response = self.client.post(url, {+ 'name': 'New Collection',+ 'collection_type_str': str(CollectionType.ELECTRONICS),+ 'collection_view_type_str': str(CollectionViewType.LIST),+ })++ # Verify the real database changes+ self.assertSuccessResponse(response)+ self.assertEqual(Collection.objects.count(), 2)++ new_collection = Collection.objects.get(name='New Collection')+ self.assertEqual(new_collection.collection_type_str, str(CollectionType.ELECTRONICS))++ def test_many_to_many_through_model(self):+ """Example: Test many-to-many relationships via through models."""+ # Don't do: self.collection.entities.add(self.entity) # This won't work++ # Do: Use the through model+ self.assertFalse(CollectionEntity.objects.filter(+ collection=self.collection,+ entity=self.entity+ ).exists())++ # Create the relationship via through model+ CollectionEntity.objects.create(+ collection=self.collection,+ entity=self.entity,+ order_id=0+ )++ # Verify the relationship exists+ self.assertTrue(CollectionEntity.objects.filter(+ collection=self.collection,+ entity=self.entity+ ).exists())+++# =============================================================================+# 2. TESTING VIEWS WITH JSON/AJAX RESPONSES+# =============================================================================++class ExampleAjaxViewTestCase(SyncViewTestCase):+ """Example of testing views that return JSON responses via antinode."""++ def setUp(self):+ super().setUp()+ self.setSessionViewMode(ViewMode.EDIT)++ self.collection = Collection.objects.create(+ name='Test Collection',+ collection_type_str=str(CollectionType.OTHER),+ collection_view_type_str=str(CollectionViewType.GRID)+ )++ def test_ajax_view_returns_json_not_redirect(self):+ """Example: Test modern AJAX views that return JSON, not redirects."""+ url = reverse('collection_edit_collection_delete', kwargs={+ 'collection_id': self.collection.id+ })+ response = self.client.post(url, {'action': 'confirm'})++ # Don't expect: self.assertEqual(response.status_code, 302) # Wrong!++ # Do expect: JSON response with location field+ self.assertSuccessResponse(response)+ self.assertJsonResponse(response)++ data = response.json()+ self.assertEqual(data['location'], reverse('home'))++ # Verify the real business logic occurred+ with self.assertRaises(Collection.DoesNotExist):+ Collection.objects.get(id=self.collection.id)++ def test_view_delegation_with_real_integration(self):+ """Example: Test view delegation by verifying end results, not mocking."""+ entity1 = Entity.objects.create(name='Entity 1', entity_type_str=str(EntityType.LIGHT))+ entity2 = Entity.objects.create(name='Entity 2', entity_type_str=str(EntityType.LIGHT))++ # Add entities to collection with initial order+ CollectionEntity.objects.create(collection=self.collection, entity=entity1, order_id=0)+ CollectionEntity.objects.create(collection=self.collection, entity=entity2, order_id=1)++ # Set required session state for delegation+ self.setSessionViewType(ViewType.COLLECTION)+ self.setSessionCollection(self.collection)++ # Test reordering (view delegates to CollectionReorderEntitiesView)+ url = reverse('edit_reorder_items')+ post_data = {+ 'html_id_list': json.dumps([+ f'hi-entity-{entity2.id}', # Move entity2 first+ f'hi-entity-{entity1.id}', # Move entity1 second+ ])+ }+ response = self.client.post(url, post_data)++ self.assertSuccessResponse(response)++ # Verify the delegation worked by checking database state+ reordered = list(CollectionEntity.objects.filter(+ collection=self.collection+ ).order_by('order_id'))+ self.assertEqual(reordered[0].entity, entity2)+ self.assertEqual(reordered[1].entity, entity1)+++# =============================================================================+# 3. FORM VALIDATION AND FILE UPLOAD TESTING+# =============================================================================++class ExampleFormValidationTestCase(SyncViewTestCase):+ """Example of testing forms with proper field requirements."""++ def setUp(self):+ super().setUp()+ self.setSessionViewMode(ViewMode.EDIT)++ self.location = Location.objects.create(+ name='Test Location',+ svg_fragment_filename='test.svg',+ svg_view_box_str='0 0 100 100',+ order_id=1+ )++ self.collection = Collection.objects.create(+ name='Test Collection',+ collection_type_str=str(CollectionType.OTHER),+ collection_view_type_str=str(CollectionViewType.GRID)+ )++ # Create position for testing+ from hi.apps.collection.models import CollectionPosition+ self.collection_position = CollectionPosition.objects.create(+ collection=self.collection,+ location=self.location,+ svg_x=50.0,+ svg_y=50.0+ )++ def test_form_with_all_required_fields(self):+ """Example: Include ALL required form fields, not just the obvious ones."""+ url = reverse('collection_position_edit', kwargs={+ 'collection_id': self.collection.id+ })++ # Don't submit incomplete data:+ # response = self.client.post(url, {+ # 'svg_x': '60.0',+ # 'svg_y': '70.0' # Missing svg_scale and svg_rotate!+ # })++ # Do submit complete form data:+ response = self.client.post(url, {+ 'svg_x': '60.0',+ 'svg_y': '70.0',+ 'svg_scale': '1.0', # Required!+ 'svg_rotate': '0.0' # Required!+ })++ self.assertSuccessResponse(response)+ self.assertJsonResponse(response)++ # Verify the database was actually updated+ updated_position = CollectionPosition.objects.get(collection=self.collection)+ self.assertEqual(float(updated_position.svg_x), 60.0)+ self.assertEqual(float(updated_position.svg_y), 70.0)++ def test_file_upload_without_mocking(self):+ """Example: Test file uploads with real files, not mocked file handling."""+ # Create a real test SVG file+ svg_content = b'''<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">+ <rect x="50" y="50" width="100" height="100" fill="blue"/>+ </svg>'''++ svg_file = SimpleUploadedFile(+ 'test_location.svg',+ svg_content,+ content_type='image/svg+xml'+ )++ url = reverse('location_svg_replace', kwargs={'location_id': self.location.id})+ response = self.client.post(url, {+ 'svg_file': svg_file,+ 'remove_dangerous_svg_items': False+ })++ self.assertSuccessResponse(response)++ # Verify the file was processed (not just that a method was called)+ updated_location = Location.objects.get(id=self.location.id)+ # The SVG processing should have extracted content and updated viewBox+ self.assertIsNotNone(updated_location.svg_view_box_str)+++# =============================================================================+# 4. TESTING COMPLEX BUSINESS LOGIC WITH REAL RELATIONSHIPS+# =============================================================================++class ExampleComplexBusinessLogicTestCase(SyncViewTestCase):+ """Example of testing complex business relationships without over-mocking."""++ def setUp(self):+ super().setUp()+ self.setSessionViewMode(ViewMode.EDIT)++ # Create entities for pairing+ self.entity = Entity.objects.create(+ name='Main Entity',+ entity_type_str=str(EntityType.LIGHT)+ )+ self.paired_entity = Entity.objects.create(+ name='Paired Entity',+ entity_type_str=str(EntityType.LIGHT)+ )++ # Create entity states (required for pairing)+ from hi.apps.entity.models import EntityState+ self.entity_state = EntityState.objects.create(+ entity=self.entity,+ attribute_name='state',+ current_value='off'+ )++ def test_entity_pairing_system(self):+ """Example: Test complex relationships like entity pairing via delegation models."""+ # Don't assume direct relationships - use the actual business model++ # Entity pairing works through EntityStateDelegation, not direct relationships+ EntityStateDelegation.objects.create(+ entity_state=self.entity_state,+ delegate_entity=self.paired_entity+ )++ # Test the business logic+ url = reverse('entity_edit_manage_pairings', kwargs={'entity_id': self.entity.id})+ response = self.client.get(url)++ self.assertSuccessResponse(response)++ # Verify the pairing relationship is reflected in the response+ content = response.content.decode()+ self.assertIn(self.paired_entity.name, content)++ # Or test removal+ url = reverse('entity_edit_pairing_remove', kwargs={+ 'entity_id': self.entity.id,+ 'paired_entity_id': self.paired_entity.id+ })+ response = self.client.post(url)++ self.assertSuccessResponse(response)++ # Verify the delegation was removed+ self.assertFalse(EntityStateDelegation.objects.filter(+ entity_state__entity=self.entity,+ delegate_entity=self.paired_entity+ ).exists())+++# =============================================================================+# 5. TESTING WITH PROPER SESSION AND MIDDLEWARE SETUP+# =============================================================================++class ExampleSessionDependentTestCase(SyncViewTestCase):+ """Example of testing views that depend on middleware-managed session state."""++ def setUp(self):+ super().setUp()+ # Many views require specific session state+ self.setSessionViewMode(ViewMode.EDIT)++ # Create objects that middleware needs to find+ self.location = Location.objects.create(+ name='Test Location',+ svg_fragment_filename='test.svg',+ svg_view_box_str='0 0 100 100',+ order_id=1 # Make it findable as default+ )++ self.location_view = LocationView.objects.create(+ location=self.location,+ name='Test View',+ location_view_type_str=str(LocationViewType.DEFAULT),+ svg_view_box_str='0 0 100 100',+ svg_rotate=0.0,+ order_id=0 # Make it findable as default+ )++ self.collection = Collection.objects.create(+ name='Test Collection',+ collection_type_str=str(CollectionType.OTHER),+ collection_view_type_str=str(CollectionViewType.GRID),+ order_id=0 # Make it findable as default+ )++ def test_view_requiring_session_context(self):+ """Example: Test views that need proper session context."""+ # This view requires collection context and default location/view+ url = reverse('collection_edit_collection_manage_items')+ response = self.client.get(url)++ self.assertSuccessResponse(response)+ self.assertJsonResponse(response) # HiSideView returns JSON++ # Verify the view rendered properly with session context+ data = response.json()+ self.assertIn('insert', data)+ self.assertIn('hi-side-content', data['insert'])++ side_content = data['insert']['hi-side-content']+ self.assertIn('Items in Collection', side_content)+ self.assertIn(self.location.name, side_content) # Location context++ def test_method_not_allowed_with_proper_setup(self):+ """Example: Test method restrictions with proper database setup."""+ # The view needs objects to exist to avoid 500 errors before method checking+ url = reverse('collection_edit_collection_manage_items')+ response = self.client.post(url) # POST not allowed++ # With proper setup, we get 405 instead of 500+ self.assertEqual(response.status_code, 405)+++# =============================================================================+# 6. SYNTHETIC DATA USAGE PATTERNS+# =============================================================================++class ExampleSyntheticDataTestCase(SyncViewTestCase):+ """Example of using synthetic data generators consistently."""++ def create_test_entity(self, **kwargs):+ """Example synthetic data method following project patterns."""+ unique_id = str(uuid.uuid4())[:8]+ defaults = {+ 'name': f'Test Entity {unique_id}',+ 'entity_type_str': str(EntityType.LIGHT),+ 'integration_id': f'test.entity.{unique_id}',+ 'integration_name': 'test_integration',+ }+ defaults.update(kwargs)+ return Entity.objects.create(**defaults)++ def create_test_collection(self, **kwargs):+ """Example synthetic data method with proper defaults."""+ unique_id = str(uuid.uuid4())[:8]+ defaults = {+ 'name': f'Test Collection {unique_id}',+ 'collection_type_str': str(CollectionType.OTHER),+ 'collection_view_type_str': str(CollectionViewType.GRID),+ }+ defaults.update(kwargs)+ return Collection.objects.create(**defaults)++ def test_using_synthetic_data(self):+ """Example: Use synthetic data for consistent, unique test objects."""+ # Create multiple entities without naming conflicts+ entity1 = self.create_test_entity(name='Custom Entity 1')+ entity2 = self.create_test_entity(entity_type_str=str(EntityType.SENSOR))++ collection1 = self.create_test_collection()+ collection2 = self.create_test_collection(+ collection_type_str=str(CollectionType.ELECTRONICS)+ )++ # All objects have unique names and proper defaults+ self.assertNotEqual(entity1.name, entity2.name)+ self.assertNotEqual(collection1.name, collection2.name)+ self.assertEqual(entity2.entity_type_str, str(EntityType.SENSOR))+++# =============================================================================+# 7. TESTING ERROR CONDITIONS AND EDGE CASES+# =============================================================================++class ExampleErrorHandlingTestCase(SyncViewTestCase):+ """Example of testing error conditions without mocking exceptions."""++ def setUp(self):+ super().setUp()+ self.setSessionViewMode(ViewMode.EDIT)++ self.collection = Collection.objects.create(+ name='Test Collection',+ collection_type_str=str(CollectionType.OTHER),+ collection_view_type_str=str(CollectionViewType.GRID)+ )++ def test_404_with_nonexistent_object(self):+ """Example: Test 404 conditions with real database queries."""+ # Don't mock the DoesNotExist exception+ url = reverse('collection_edit_collection_delete', kwargs={+ 'collection_id': 99999 # Non-existent ID+ })+ response = self.client.get(url)++ self.assertEqual(response.status_code, 404)++ def test_validation_errors_with_real_forms(self):+ """Example: Test form validation with real form processing."""+ url = reverse('collection_add')+ response = self.client.post(url, {+ 'name': '', # Invalid - empty name+ 'collection_type_str': str(CollectionType.OTHER),+ 'collection_view_type_str': str(CollectionViewType.GRID),+ })++ # Should return form with validation errors+ self.assertEqual(response.status_code, 400)++ # Verify no collection was created+ self.assertEqual(Collection.objects.count(), 1) # Only setUp collection+++# =============================================================================+# SUMMARY OF KEY PATTERNS+# =============================================================================++"""+KEY PATTERNS DEMONSTRATED:++1. **Use Real Objects**: Create actual model instances instead of mocking+2. **Enum String Conversion**: Always use str(EnumType.VALUE) for enum fields+3. **Through Model Relationships**: Use intermediate models for M2M relationships+4. **Complete Form Data**: Include ALL required fields, not just obvious ones+5. **JSON Response Testing**: Expect JSON from modern AJAX views, not redirects+6. **Session State Setup**: Configure required middleware state in setUp()+7. **Default Object Order**: Use order_id=0 for objects that need to be "default"+8. **Synthetic Data**: Use consistent patterns for test data generation+9. **Real File Uploads**: Use SimpleUploadedFile for file testing+10. **Integration Testing**: Test full flows rather than just delegation++ANTI-PATTERNS TO AVOID:++❌ Mocking basic CRUD operations+❌ Mocking entire view classes for delegation testing+❌ Assuming direct M2M relationships exist+❌ Expecting HTTP redirects from AJAX views+❌ Incomplete form data in tests+❌ Missing session state setup+❌ Testing mock interactions instead of business outcomes+"""\ No newline at end of filediff --git a/docs/dev/testing/testing-guidelines.md b/docs/dev/testing/testing-guidelines.mdindex 687c8315..31a61035 100644--- a/docs/dev/testing/testing-guidelines.md+++ b/docs/dev/testing/testing-guidelines.md@@ -53,7 +53,7 @@ with patch.object(manager, 'fallback_handler', mock_fallback):self.assertIsNone(result) # Verify expected failure behavior```-### Additional Testing Anti-Patterns+### NEVER Use a mock of a class when the real class is available#### Mock-Centric Testing Instead of Behavior Testing@@ -103,6 +103,8 @@ def test_fetch_and_parse_integration(self, mock_get):self.assertEqual(result.parsed_field, "expected_value")```+### Additional Testing Anti-Patterns+#### Testing Implementation Details Instead of Interface Contracts**Problem**: Tests verify internal implementation details rather than public interface behavior.@@ -173,4 +175,4 @@ For complete usage details, see: `hi.testing.dev_injection.DevInjectionManager`- Test data management: [Test Data Management](test-data-management.md)- Simulator testing: [Test Simulator](test-simulator.md)- Coding standards: [Coding Standards](../shared/coding-standards.md)-- View testing: [Frontend Guidelines](../frontend/frontend-guidelines.md#view-testing)\ No newline at end of file+- View testing: [Frontend Guidelines](../frontend/frontend-guidelines.md#view-testing)diff --git a/docs/dev/testing/testing-lessons-learned.md b/docs/dev/testing/testing-lessons-learned.mdnew file mode 100644index 00000000..0fde5b0e--- /dev/null+++ b/docs/dev/testing/testing-lessons-learned.md@@ -0,0 +1,314 @@+# Django Testing Anti-Patterns and Lessons Learned++## Overview++This document captures critical discoveries and learnings from a comprehensive effort to fix over-mocking issues in Django unit tests across the HI application. The work involved systematically converting heavily mocked tests to use real objects, revealing numerous anti-patterns and best practices.++## Core Anti-Patterns Identified++### 1. Over-Mocking Database Operations++**Problem**: Tests were mocking fundamental Django operations like model creation, relationships, and queries instead of using real database objects in test transactions.++**Examples Found**:+```python+# Anti-pattern: Mocking basic model operations[email protected](CollectionManager, 'toggle_entity_in_collection')[email protected](CollectionManager, 'get_collection_data')+def test_post_toggle_entity_add(self, mock_toggle, mock_get_data):+ mock_toggle.return_value = True+```++**Solution**:+```python+# Better: Test real database relationships+def test_post_toggle_entity_add(self):+ # Verify entity is not in collection initially+ self.assertFalse(CollectionEntity.objects.filter(collection=self.collection, entity=self.entity).exists())++ response = self.client.post(url)++ # Verify entity was added to collection+ self.assertTrue(CollectionEntity.objects.filter(collection=self.collection, entity=self.entity).exists())+```++**Lesson**: Django's test framework provides isolated database transactions. Use real objects instead of mocking database operations.++### 2. Mocking View Delegation Instead of Testing Integration++**Problem**: Tests mocked entire view classes when testing view delegation, missing integration issues and actual functionality.++**Example**:+```python+# Anti-pattern: Mocking the delegated view+@patch('hi.apps.edit.views.CollectionReorderEntitiesView')+def test_reorder_entities_in_collection(self, mock_view_class):+ mock_view = mock_view_class.return_value+ mock_view.post.return_value = JsonResponse({'status': 'ok'})+```++**Solution**:+```python+# Better: Test the full integration+def test_reorder_entities_in_collection(self):+ # Create real entities and add to collection+ CollectionEntity.objects.create(collection=self.collection, entity=entity1, order_id=0)++ # Test actual reordering+ response = self.client.post(url, post_data)++ # Verify database changes+ reordered_entities = list(CollectionEntity.objects.filter(collection=self.collection).order_by('order_id'))+ self.assertEqual(reordered_entities[0].entity, entity3) # Verify new order+```++**Lesson**: Test the full integration path rather than just delegation mechanics.++### 3. Incorrect Response Type Expectations++**Problem**: Tests expected traditional HTTP redirects (302) when views actually returned JSON responses (200) via antinode.js integration.++**Example**:+```python+# Anti-pattern: Wrong response expectation+def test_post_delete_with_confirmation(self):+ response = self.client.post(url, {'action': 'confirm'})+ self.assertEqual(response.status_code, 302) # Wrong!+```++**Solution**:+```python+# Better: Expect JSON responses from antinode views+def test_post_delete_with_confirmation(self):+ response = self.client.post(url, {'action': 'confirm'})++ self.assertSuccessResponse(response)+ self.assertJsonResponse(response)++ data = response.json()+ self.assertEqual(data['location'], expected_url)+```++**Lesson**: Understand your application's AJAX/async response patterns. Modern web apps often return JSON instead of traditional redirects.++## Model Relationship Discoveries++### Many-to-Many Through Models++**Discovery**: Collections and entities have a many-to-many relationship through `CollectionEntity`, not a direct relationship.++**Wrong Assumption**:+```python+# This doesn't work - no direct relationship+self.collection.entities.add(self.entity)+```++**Correct Approach**:+```python+# Use the through model+from hi.apps.collection.models import CollectionEntity+CollectionEntity.objects.create(collection=self.collection, entity=self.entity)+```++**Lesson**: Always verify model relationships in Django admin or model definitions before writing tests.++### Entity Pairing System++**Discovery**: Entity pairings work through `EntityStateDelegation` objects, not direct relationships.++**Implementation**:+```python+from hi.apps.entity.models import EntityStateDelegation+for entity_state in self.entity.states.all():+ EntityStateDelegation.objects.create(+ entity_state=entity_state,+ delegate_entity=self.paired_entity+ )+```++**Lesson**: Complex business logic often involves intermediate models that aren't immediately obvious.++## Form Validation Requirements++### Missing Required Fields++**Discovery**: `LocationItemPositionForm` requires all position fields (`svg_x`, `svg_y`, `svg_scale`, `svg_rotate`), not just coordinates.++**Problem**:+```python+# Incomplete form data+response = self.client.post(url, {+ 'svg_x': '60.0',+ 'svg_y': '70.0' # Missing svg_scale and svg_rotate+})+# Position wasn't updated in database+```++**Solution**:+```python+# Complete form data+response = self.client.post(url, {+ 'svg_x': '60.0',+ 'svg_y': '70.0',+ 'svg_scale': '1.0',+ 'svg_rotate': '0.0'+})+```++**Lesson**: Always check form field requirements. Use Django form validation errors to debug incomplete test data.++## Session and Middleware Requirements++### View Parameter Dependencies++**Discovery**: Many views depend on session state managed by custom middleware for location, collection, and view mode context.++**Common Setup Pattern**:+```python+def setUp(self):+ super().setUp()+ # Set edit mode (required by decorator)+ self.setSessionViewMode(ViewMode.EDIT)++ # Create location/location view for middleware+ location = Location.objects.create(...)+ location_view = LocationView.objects.create(location=location, ...)++ # Set collection context if needed+ self.setSessionCollection(self.collection)+```++**Lesson**: Understand your application's middleware dependencies. Views may require specific session state to function.++### Default Object Resolution++**Discovery**: Views often use "get_default" patterns that require objects with specific `order_id` values.++**Pattern**:+```python+# Ensure this is the default by setting order_id=0+self.collection.order_id = 0+self.collection.save()+```++**Lesson**: Many applications use ordering conventions for default object resolution.++## Test Infrastructure Patterns++### Synthetic Data Pattern++**Discovery**: The application uses a consistent synthetic data pattern across modules for test data creation.++**Structure**:+```python+# hi/apps/{module}/tests/synthetic_data.py+class {Module}SyntheticData:+ @staticmethod+ def create_test_{model}(**kwargs) -> {Model}:+ unique_id = str(uuid.uuid4())[:8]+ defaults = {+ 'name': f'Test {Model} {unique_id}',+ # ... reasonable defaults+ }+ defaults.update(kwargs)+ return {Model}.objects.create(**defaults)+```++**Lesson**: Centralized test data creation prevents duplication and ensures consistency.++### Test Base Class Hierarchy++**Discovery**: The application uses specialized test base classes with different capabilities.++**Classes Found**:+- `SyncViewTestCase`: For traditional synchronous views+- `DualModeViewTestCase`: For views that work in both sync and async modes+- Custom assertion methods: `assertJsonResponse()`, `assertHtmlResponse()`, `assertSuccessResponse()`++**Lesson**: Leverage application-specific test utilities rather than recreating common patterns.++## Enum and String Conversion Patterns++### LabeledEnum Usage++**Discovery**: The application uses `LabeledEnum` types that require string conversion with `str()`.++**Pattern**:+```python+# Always use str() conversion for enum fields+entity = Entity.objects.create(+ entity_type_str=str(EntityType.LIGHT) # Not just EntityType.LIGHT+)+```++**Lesson**: Understand your application's enum handling patterns.++### HTML ID Format Conventions++**Discovery**: The application uses specific HTML ID formats for different item types.++**Pattern**:+```python+# Use ItemType.parse_html_id() format: hi-{type}-{id}+'hi-entity-1' # Entity with ID 1+'hi-collection-1' # Collection with ID 1+'hi-location_view-1' # LocationView with ID 1 (note underscore)+```++**Lesson**: Web applications often have specific ID conventions for JavaScript integration.++## Error Handling and Exception Patterns++### Custom Exception Handling++**Discovery**: The application uses custom exceptions handled by middleware rather than Django's built-in HTTP exceptions.++**Pattern**:+```python+# Application uses custom MethodNotAllowedError+# Middleware converts to HttpResponseNotAllowed(405)+```++**Lesson**: Understand your application's exception handling architecture.++## Best Practices Derived++### 1. Test Real Behavior, Not Implementation Details++- Test database state changes, not method calls+- Test full request-response cycles, not just view delegation+- Verify business logic outcomes, not internal mechanics++### 2. Understand Your Application Architecture++- Know your middleware dependencies+- Understand session management patterns+- Learn enum and string conversion requirements+- Study model relationship patterns++### 3. Use Application-Specific Test Utilities++- Leverage existing test base classes+- Use synthetic data generators+- Employ custom assertion methods+- Follow established test data patterns++### 4. Debug Systematically++- Read error messages carefully - they often reveal missing setup+- Check form validation requirements when database changes don't occur+- Verify response types match expectations (JSON vs HTML vs redirects)+- Use `print()` debugging in tests to understand data flow++### 5. Create Missing Test Infrastructure++- Build synthetic data generators following established patterns+- Create reusable test setup methods+- Document model relationship requirements+- Share learnings with the team++## Conclusion++The transition from over-mocked tests to real object testing revealed deep application architecture patterns and significantly improved test coverage quality. The key insight is that Django's test framework is designed to support real database operations in isolated transactions, making mocking of basic CRUD operations unnecessary and counterproductive.++These patterns and lessons should guide future test development to avoid the anti-patterns that led to fragile, hard-to-maintain tests that provided false confidence in system behavior.\ No newline at end of filediff --git a/docs/dev/workflow/design-workflow.md b/docs/dev/workflow/design-workflow.mdnew file mode 100644index 00000000..1524be6b--- /dev/null+++ b/docs/dev/workflow/design-workflow.md@@ -0,0 +1,188 @@+# Design Workflow++> **Role**: Process Documentation+> **Purpose**: Workflow for design-focused issues including UX improvements, UI redesigns, mockups, and wireframes++## Design Work Documentation Process++When working on design-focused GitHub issues (UX improvements, UI redesigns, mockups, wireframes, interaction design):++### Local Work Directory Structure++All design work products are kept local and **never committed to the repository**:++```bash+# All design work goes in data/design (git ignored)+data/design/issue-{number}/+├── mockup.html # Interactive HTML mockups+├── architecture.md # Technical architecture docs+├── interaction-patterns.md # UX interaction specifications+├── design-summary.md # Executive summary+└── other-design-artifacts.* # Additional files as needed+```++### Design Workflow Process++1. **Create issue subdirectory**: `mkdir -p data/design/issue-{number}`+2. **Iterate locally**: Create, refine, and iterate on design documents locally+3. **No repository commits**: Design work products stay local only (`data/` is in .gitignore)+4. **Post to GitHub issue**: Share stable versions via GitHub issue comments/attachments++### Repository vs GitHub Issue Organization++**Repository Scope** (source of truth):+- Implementation code and templates+- Architecture documentation that affects multiple systems+- Coding standards and technical guidelines++**GitHub Issue Scope** (design iteration and review):+- Design mockups and wireframes+- UX interaction specifications+- Design decision rationale and trade-offs+- Stakeholder review and approval process++### GitHub Issue Documentation Pattern++Use this structure when posting design deliverables:++```markdown+## Phase X Design Complete - Ready for Review++Brief summary of key decisions and deliverables:++1. **Interactive Mockup** (attached) - HTML file for browser viewing+2. **Architecture Document** (comment below) - Technical specifications+3. **Interaction Patterns** (comment below) - UX behavior definitions++### Key Design Decisions+- Decision 1: Rationale+- Decision 2: Rationale+- Decision 3: Rationale++### Implementation Notes+- Technical considerations+- New development required+- Forward compatibility hooks++Ready for stakeholder review and implementation planning.+```++### Content Organization Strategy++**Visual Deliverables** → GitHub Issue Attachments:+- Interactive HTML mockups+- Images, screenshots, diagrams+- **Benefits**: Can be downloaded and viewed directly in browsers++**Textual Content** → GitHub Issue Comments:+- Architecture specifications (markdown)+- Interaction patterns documentation (markdown)+- Design decision rationale (markdown)+- **Benefits**: Searchable, linkable, quotable for discussion++### Design Iteration Workflow++1. **Initial Research**: Analyze current implementation and requirements+2. **Create Local Workspace**: Set up `data/design/issue-{number}/` directory+3. **Design Iteration**: Create and refine mockups and documentation locally+4. **Checkpoint Reviews**: Post important versions to GitHub issue for feedback+5. **Final Documentation**: Post complete deliverables when design is stable+6. **Implementation Handoff**: Provide clear specifications for development phase++### Design Deliverable Types++**HTML Mockups**:+- Interactive demonstrations of proposed UX+- ~700px modal examples with realistic content+- Touch-friendly interaction patterns+- Visual state management examples++**Architecture Documents**:+- Technical implementation approach+- Component reusability strategy+- Template organization and naming+- CSS class naming and namespace planning++**Interaction Patterns**:+- Comprehensive touch interaction flows+- State management behavior+- Error handling patterns+- Accessibility considerations++**Design Summaries**:+- Executive overview of key decisions+- Implementation complexity assessment+- Forward compatibility planning+- Cross-issue relationship documentation++### Multi-Phase Design Strategy++For complex design issues, break work into phases:++**Phase 1 - Design & Architecture**:+- Complete design iteration locally+- Post comprehensive deliverables to GitHub issue+- Get stakeholder approval before implementation++**Phase 2+ - Implementation**:+- Use design deliverables as implementation specification+- Create feature branch for development work+- Follow standard development workflow from approved design++### Integration with Development Workflow++**Branch Strategy**:+- Design phase: Feature branch for any temporary investigation code+- Implementation phase: Same or new feature branch for actual development++**Testing Integration**:+- Design phase: No automated testing required+- Implementation phase: Full test coverage per standard guidelines++**Documentation Updates**:+- Design decisions remain in GitHub issues (audit trail)+- Implementation details go in code and architecture docs per standards++### Quality Assurance++**Design Review Checkpoints**:+- [ ] All deliverables posted to GitHub issue+- [ ] Key design decisions documented with rationale+- [ ] Forward compatibility considerations addressed+- [ ] Implementation complexity assessed+- [ ] Stakeholder approval obtained++**Implementation Readiness**:+- [ ] Clear technical specifications provided+- [ ] Component architecture defined+- [ ] Interaction patterns fully specified+- [ ] Integration points identified++## Benefits of This Workflow++### Repository Cleanliness+- No work-in-progress design artifacts clutter the codebase+- Clear separation between design iteration and implementation+- Source of truth remains focused on implemented solutions++### Design Iteration Efficiency+- Local work allows rapid iteration without commits+- Easy to discard failed approaches+- No merge conflicts during design exploration++### Stakeholder Review Effectiveness+- Visual deliverables easily accessible via attachments+- Comprehensive documentation provides context+- Clear approval gates before implementation work++### Implementation Quality+- Complete specifications reduce implementation ambiguity+- Forward compatibility planning prevents technical debt+- Reusable component strategy improves maintainability++## Related Documentation++- [Workflow Guidelines](workflow-guidelines.md) - Standard development workflow+- [Documentation Standards](documentation-standards.md) - General documentation philosophy+- [Frontend Guidelines](../frontend/frontend-guidelines.md) - UI implementation patterns+- [Architecture Overview](../shared/architecture-overview.md) - System architecture context\ No newline at end of filediff --git a/src/hi/apps/api/tests/__init__.py b/src/hi/apps/api/tests/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/apps/attribute/forms.py b/src/hi/apps/attribute/forms.pyindex 2946eb8d..2316f58d 100644--- a/src/hi/apps/attribute/forms.py+++ b/src/hi/apps/attribute/forms.py@@ -32,6 +32,7 @@ class AttributeForm( forms.ModelForm ):secret = forms.BooleanField(required = False,label = 'Mark as Secret',+ widget = forms.CheckboxInput(attrs={'class': 'custom-control-input'}),)@property@@ -60,7 +61,7 @@ class AttributeForm( forms.ModelForm ):cleaned_data = super().clean()name = cleaned_data.get('name')value = cleaned_data.get('value')-+form_is_bound = bool( self.instance.pk )if form_is_bound:if not self.instance.is_editable and value:diff --git a/src/hi/apps/attribute/templates/attribute/components/attribute_history_inline.html b/src/hi/apps/attribute/templates/attribute/components/attribute_history_inline.htmlnew file mode 100644index 00000000..b87e3a2e--- /dev/null+++ b/src/hi/apps/attribute/templates/attribute/components/attribute_history_inline.html@@ -0,0 +1,77 @@+{% load humanize %}+{% load icons %}+{% load attribute_extras %}+{% comment %}+Inline Attribute History Component+Compact history display that loads into attribute cards+{% endcomment %}++<div class="attr-v2-history-inline-content">+ <!-- History Header -->+ <div class="attr-v2-history-header">+ <small class="text-muted">+ <strong>History for "{{ attribute.name }}"</strong>+ </small>+ <button type="button"+ class="btn btn-sm btn-link p-0 attr-v2-history-close"+ onclick="$('#hi-entity-attr-history-{{ entity.id }}-{{ attribute.id }}').empty();"+ title="Close history">+ {% icon "close" size="sm" %}+ </button>+ </div>++ <!-- Current Value -->+ <div class="attr-v2-history-current mb-2">+ <small class="text-muted">Current:</small>+ <span class="badge badge-primary ml-1">{{ attribute.value|attribute_preview }}</span>+ </div>++ {% if history_records %}+ <!-- History Records -->+ <div class="attr-v2-history-records">+ {% for record in history_records %}+ <div class="attr-v2-history-record {% if forloop.counter > 3 %}collapse{% endif %}"+ {% if forloop.counter > 3 %}id="history-extra-{{ entity.id }}-{{ attribute.id }}"{% endif %}>+ <div class="d-flex justify-content-between align-items-center">+ <div>+ <small class="text-muted">{{ record.changed_datetime|naturaltime }}</small>+ <span class="badge badge-light ml-2">{{ record.value|attribute_preview }}</span>+ </div>+ <div>+ {% if record.value != attribute.value %}+ <a href="{% url restore_url_name entity_id=entity.id attribute_id=attribute.id history_id=record.pk %}"+ data-async="true"+ data-stay-in-modal="true"+ class="btn btn-xs btn-outline-primary"+ title="Restore this value">+ Restore+ </a>+ {% else %}+ <small class="text-muted">Current</small>+ {% endif %}+ </div>+ </div>+ </div>+ {% endfor %}++ <!-- Show More/Less Toggle -->+ {% if history_records|length > 3 %}+ <div class="attr-v2-history-toggle mt-2">+ <button type="button"+ class="btn btn-sm btn-link p-0"+ data-toggle="collapse"+ data-target="#history-extra-{{ entity.id }}-{{ attribute.id }}"+ onclick="$(this).find('.show-more-text, .show-less-text').toggle();">+ <small class="show-more-text">Show {{ history_records|length|add:'-3' }} more...</small>+ <small class="show-less-text" style="display: none;">Show less</small>+ </button>+ </div>+ {% endif %}+ </div>+ {% else %}+ <!-- No History -->+ <div class="attr-v2-history-empty">+ <small class="text-muted">No previous values recorded.</small>+ </div>+ {% endif %}+</div>diff --git a/src/hi/apps/attribute/templates/attribute/components/file_card.html b/src/hi/apps/attribute/templates/attribute/components/file_card.htmlnew file mode 100644index 00000000..cb514c4d--- /dev/null+++ b/src/hi/apps/attribute/templates/attribute/components/file_card.html@@ -0,0 +1,102 @@+{% load icons %}+{% comment %}+V2 File Card Component+Individual file attribute card with preview, actions, and metadata+{% endcomment %}++<div class="{{ DIVID.ATTR_V2_FILE_CARD_CLASS }}"+ data-attribute-id="{{ attribute.id }}"+ data-url-detect="true"+ data-order-index="{{ forloop.counter }}"+ data-thumbnail-ready="true"+ data-mime-type="{{ attribute.file_mime_type|default:'unknown' }}"+ data-file-size="{{ attribute.file_value.size|default:0 }}">++ <!-- Hidden field for deletion marking -->+ <input type="hidden"+ name="delete_file_attribute"+ value=""+ data-attribute-id="{{ attribute.id }}">++ <!-- File Preview/Thumbnail Area -->+ <div class="attr-v2-file-thumbnail"+ onclick="window.open('{{ attribute.file_value.url }}', '_blank');"+ title="Click to view file">+ {% comment %}Content-type specific placeholder icons{% endcomment %}+ {% if attribute.file_mime_type|slice:':5' == "image" %}+ {% icon "camera" size="lg" %}+ <div class="attr-v2-file-type-label">IMAGE</div>+ {% elif attribute.file_mime_type == "application/pdf" %}+ {% icon "upload" size="lg" %}+ <div class="attr-v2-file-type-label">PDF</div>+ {% elif attribute.file_mime_type|slice:':4' == "text" %}+ {% icon "edit" size="lg" %}+ <div class="attr-v2-file-type-label">TEXT</div>+ {% elif attribute.file_mime_type|slice:':5' == "video" %}+ {% icon "video" size="lg" %}+ <div class="attr-v2-file-type-label">VIDEO</div>+ {% else %}+ {% icon "upload" size="lg" %}+ <div class="attr-v2-file-type-label">FILE</div>+ {% endif %}++ <!-- Reorder Controls (overlay in upper right) -->+ <div class="attr-v2-reorder-controls"+ onclick="event.stopPropagation();"+ onmouseenter="this.parentElement.classList.add('reorder-hover');"+ onmouseleave="this.parentElement.classList.remove('reorder-hover');">+ <button type="button"+ class="btn btn-sm btn-outline-secondary"+ disabled+ title="Reordering available in future update"+ data-reorder-action="left">+ {% icon "chevron-left" size="sm" %}+ </button>+ <button type="button"+ class="btn btn-sm btn-outline-secondary"+ disabled+ title="Reordering available in future update"+ data-reorder-action="right">+ {% icon "chevron-right" size="sm" %}+ </button>+ </div>+ </div>++ <!-- File Info -->+ <div class="{{ DIVID.ATTR_V2_FILE_INFO_CLASS }}">+ <input type="text"+ id="file_title_{{ entity.id }}_{{ attribute.id }}"+ name="file_title_{{ entity.id }}_{{ attribute.id }}"+ value="{{ attribute.value }}"+ class="{{ DIVID.ATTR_V2_FILE_TITLE_INPUT_CLASS }}"+ placeholder="Enter file title"+ maxlength="255">+ <div class="{{ DIVID.ATTR_V2_FILE_NAME_CLASS }}">{{ attribute.name }}</div>++ <!-- File Actions -->+ <div class="attr-v2-file-actions">+ <button type="button"+ class="btn btn-sm btn-outline-primary"+ onclick="window.open('{{ attribute.file_value.url }}', '_blank');"+ title="View file">+ {% icon "eye" size="sm" %}+ </button>++ {% if attribute.attribute_type.can_delete %}+ <button type="button"+ class="btn btn-sm btn-outline-danger {{ DIVID.ATTR_V2_DELETE_BTN_CLASS }}"+ onclick="markFileForDeletion('{{ attribute.id }}')"+ title="Delete file">+ {% icon "delete" size="sm" %}+ </button>+ <button type="button"+ class="btn btn-sm btn-outline-secondary {{ DIVID.ATTR_V2_UNDO_BTN_CLASS }}"+ onclick="undoFileDeletion('{{ attribute.id }}')"+ title="Undo deletion"+ style="display: none;">+ Undo+ </button>+ {% endif %}+ </div>+ </div>+</div>diff --git a/src/hi/apps/attribute/templates/attribute/components/file_grid.html b/src/hi/apps/attribute/templates/attribute/components/file_grid.htmlnew file mode 100644index 00000000..9e6b0d85--- /dev/null+++ b/src/hi/apps/attribute/templates/attribute/components/file_grid.html@@ -0,0 +1,14 @@+{% comment %}+V2 File Grid Component+Displays file attributes in a grid layout with proper spacing+Always renders container for dynamic file additions via antinode.js+{% endcomment %}++<div class="attr-v2-file-section">+ <h6 class="attr-v2-section-title">Files</h6>+ <div id="attr-v2-file-grid" class="attr-v2-file-grid">+ {% for attribute in file_attributes %}+ {% include "attribute/components/file_card.html" with attribute=attribute %}+ {% endfor %}+ </div>+</div>diff --git a/src/hi/apps/attribute/templates/attribute/components/regular_attribute_card.html b/src/hi/apps/attribute/templates/attribute/components/regular_attribute_card.htmlnew file mode 100644index 00000000..d96e6b76--- /dev/null+++ b/src/hi/apps/attribute/templates/attribute/components/regular_attribute_card.html@@ -0,0 +1,205 @@+{% load icons %}+{% load common_template_helpers %}+{% comment %}+V2 Attribute Card Component+Individual attribute attribute card with value editing and actions+{% endcomment %}++<div class="{{ DIVID.ATTR_V2_ATTRIBUTE_CARD_CLASS }}{% if not attribute_form.instance.pk %} {{ DIVID.ATTR_V2_NEW_ATTRIBUTE_CLASS }}{% endif %}"+ data-attribute-id="{{ attribute_form.instance.pk }}"+ data-url-detect="true"+ data-order-index="{{ forloop.counter }}"+ data-value-type="{{ attribute_form.instance.value_type.name|default:'text' }}"+ data-is-secret="{{ attribute_form.instance.value_type.is_secret|yesno:'true,false' }}"+ data-can-delete="{{ attribute_form.instance.attribute_type.can_delete|yesno:'true,false' }}"+ {% if not attribute_form.instance.pk and not attribute_form.is_bound %}style="display: none;"{% endif %}>++ <!-- Hidden form fields -->+ {{ attribute_form.id }}+ {% if attribute_form.DELETE %}+ {{ attribute_form.DELETE.as_hidden }}+ {% endif %}++ <!-- Attribute Header -->+ <div class="attr-v2-attribute-header">+ <h6 class="{{ DIVID.ATTR_V2_ATTRIBUTE_NAME_CLASS }}">+ {% if attribute_form.instance.pk %}+ {{ attribute_form.instance.name }}+ {% else %}+ {% icon "plus" size="sm" css_class="hi-icon-left" %}Add New+ {% endif %}+ </h6>++ <div class="attr-v2-attribute-actions">+ <!-- Reorder Controls (disabled until Issue #80) -->+ {% if attribute_form.instance.pk %}+ <button type="button"+ class="btn btn-sm btn-outline-secondary"+ disabled+ title="Reordering available in future update"+ data-reorder-action="up">+ {% icon "chevron-up" size="sm" %}+ </button>+ <button type="button"+ class="btn btn-sm btn-outline-secondary"+ disabled+ title="Reordering available in future update"+ data-reorder-action="down">+ {% icon "chevron-down" size="sm" %}+ </button>+ {% endif %}++ {% if attribute_form.instance.pk %}+ <a href="{% url 'entity_attribute_history_inline' entity_id=entity.id attribute_id=attribute_form.instance.pk %}"+ data-async="#hi-entity-attr-history-{{ entity.id }}-{{ attribute_form.instance.pk }}"+ data-stay-in-modal="true"+ class="btn btn-sm btn-outline-secondary"+ title="View history">+ {% icon "history" size="sm" %}+ </a>+ {% endif %}++ {% if attribute_form.instance.pk and attribute_form.instance.attribute_type.can_delete %}+ <button type="button"+ class="{{ DIVID.ATTR_V2_DELETE_BTN_CLASS }}"+ title="Delete attribute"+ onclick="markAttributeForDeletion('{{ attribute_form.instance.pk }}')">+ {% icon "delete" size="sm" %}+ </button>+ <button type="button"+ class="btn btn-sm btn-outline-warning {{ DIVID.ATTR_V2_UNDO_BTN_CLASS }}"+ title="Undo delete"+ onclick="undoAttributeDeletion('{{ attribute_form.instance.pk }}')"+ style="display: none;">+ ↶ Undo+ </button>+ {% endif %}+ </div>+ </div>++ <!-- Attribute Value -->+ <div class="attr-v2-attribute-value">+ {% if attribute_form.instance.pk %}+ <!-- Existing attribute - include hidden name field -->+ <input type="hidden"+ id="{{ attribute_form.name.id_for_label }}"+ name="{{ attribute_form.name.html_name }}"+ value="{{ attribute_form.instance.name }}" />+ {% else %}+ <!-- New attribute form -->+ <div class="mb-2">+ {{ attribute_form.name.label_tag }}+ {{ attribute_form.name }}+ {% if attribute_form.name.errors %}+ <div class="invalid-feedback d-block">+ {{ attribute_form.name.errors }}+ </div>+ {% endif %}+ </div>+ {% endif %}++ {% if attribute_form.instance.pk and attribute_form.instance.value_type.is_boolean %}+ <!-- Boolean/Switch -->+ <div class="custom-control custom-switch">+ {{ attribute_form.value }}+ <label class="custom-control-label" for="{{ attribute_form.value.id_for_label }}">+ {{ attribute_form.value.label|default:"Toggle value" }}+ </label>+ {% if attribute_form.value.errors %}+ <div class="invalid-feedback d-block">+ {{ attribute_form.value.errors }}+ </div>+ {% endif %}+ </div>+ {% else %}+ <!-- Text/Textarea (default) -->+ <div class="attr-v2-text-value">+ {% if attribute_form.instance.pk and attribute_form.instance.value_type.is_secret %}+ <div class="attr-v2-secret-field">+ <div class="attr-v2-secret-input-wrapper">+ <!-- Secret field as password input -->+ <input type="password"+ id="{{ attribute_form.value.id_for_label }}"+ name="{{ attribute_form.value.html_name }}"+ class="form-control attr-v2-secret-input"+ value="{{ attribute_form.value.value|default_if_none:'' }}"+ readonly="readonly"+ {% if attribute_form.instance and not attribute_form.instance.is_editable %}disabled="true"{% endif %} />+ {% if attribute_form.value.errors %}+ <div class="invalid-feedback d-block">+ {{ attribute_form.value.errors }}+ </div>+ {% endif %}+ <button type="button"+ class="btn btn-sm btn-outline-secondary attr-v2-secret-toggle"+ onclick="attrV2.toggleSecretField(this)"+ title="Show value">+ <span class="attr-v2-icon-show">{% icon "eye" size="sm" %}</span>+ <span class="attr-v2-icon-hide" style="display: none;">{% icon "eye-off" size="sm" %}</span>+ </button>+ </div>+ </div>+ {% else %}+ <!-- Hidden field pattern for data integrity -->+ {% with value_text=attribute_form.value.value|default_if_none:'' %}+ {% with line_count=value_text|linecount %}+ {% with display_rows=line_count|min_value:4 %}+ {% with overflows=line_count|add:"-4" %}+ <div class="attr-v2-text-value-wrapper" data-overflow="{% if overflows > 0 %}true{% else %}false{% endif %}" data-line-count="{{ line_count }}">++ <!-- Real form field - contains actual data, never manipulated during editing -->+ <input type="hidden"+ name="{{ attribute_form.value.html_name }}"+ id="hidden-{{ attribute_form.value.id_for_label }}"+ value="{{ attribute_form.value.value|default_if_none:'' }}">++ <!-- Display field - for UI only (no name = not submitted) -->+ <textarea rows="{{ display_rows }}"+ id="{{ attribute_form.value.id_for_label }}"+ class="form-control attr-v2-textarea display-field"+ data-overflow="{% if overflows > 0 %}true{% else %}false{% endif %}"+ data-hidden-field="hidden-{{ attribute_form.value.id_for_label }}"+ {% if attribute_form.instance and not attribute_form.instance.is_editable %}disabled="true"{% endif %}+ data-original-value="{{ attribute_form.value.value|default_if_none:'' }}">{{ attribute_form.value.value|default_if_none:'' }}</textarea>+ {% if attribute_form.value.errors %}+ <div class="invalid-feedback d-block">+ {{ attribute_form.value.errors }}+ </div>+ {% endif %}+ {% if overflows > 0 %}+ <div class="attr-v2-expand-controls" style="display: block;">+ <button type="button" class="btn btn-sm btn-link" onclick="attrV2.toggleExpandedView(this)">+ <span class="show-more-text">Show more...</span>+ <span class="show-less-text" style="display: none;">Show less</span>+ </button>+ </div>+ {% endif %}+ </div>+ {% endwith %}+ {% endwith %}+ {% endwith %}+ {% endwith %}+ {% endif %}+ </div>+ {% endif %}++ <!-- Secret checkbox for new properties -->+ {% if not attribute_form.instance.pk %}+ <div class="attr-v2-secret-checkbox">+ <div class="custom-control custom-checkbox">+ {{ attribute_form.secret }}+ <label class="custom-control-label" for="{{ attribute_form.secret.id_for_label }}">+ Mark as Secret+ </label>+ </div>+ </div>+ {% endif %}+ </div>++ <!-- Inline History Target (empty until populated) -->+ {% if attribute_form.instance.pk %}+ <div id="hi-entity-attr-history-{{ entity.id }}-{{ attribute_form.instance.pk }}"+ class="attr-v2-inline-history">+ </div>+ {% endif %}+</div>diff --git a/src/hi/apps/attribute/templates/attribute/components/regular_attribute_list.html b/src/hi/apps/attribute/templates/attribute/components/regular_attribute_list.htmlnew file mode 100644index 00000000..3c8ce5b4--- /dev/null+++ b/src/hi/apps/attribute/templates/attribute/components/regular_attribute_list.html@@ -0,0 +1,15 @@+{% comment %}+V2 Property List Component+Displays attribute attributes in a list layout+{% endcomment %}++{% if regular_attributes_formset %}+<div class="attr-v2-attribute-section">+ <h6 class="attr-v2-section-title">Properties</h6>+ <div class="attr-v2-attribute-list">+ {% for attribute_form in regular_attributes_formset %}+ {% include "attribute/components/regular_attribute_card.html" with attribute_form=attribute_form %}+ {% endfor %}+ </div>+</div>+{% endif %}diff --git a/src/hi/apps/attribute/templates/attribute/components/status_message.html b/src/hi/apps/attribute/templates/attribute/components/status_message.htmlnew file mode 100644index 00000000..c82658ee--- /dev/null+++ b/src/hi/apps/attribute/templates/attribute/components/status_message.html@@ -0,0 +1,19 @@+{% comment %}+V2 Status Message Component+Displays success, error, or warning messages in the status area+{% endcomment %}++{% if error_message %}+<span class="text-danger">{{ error_message }}</span>+{% if form_errors %}+ {% for field, errors in form_errors.items %}+ {% for error in errors %}+ <br><small class="text-danger">{{ field }}: {{ error }}</small>+ {% endfor %}+ {% endfor %}+{% endif %}+{% elif success_message %}+<span class="text-success">{{ success_message }}</span>+{% elif warning_message %}+<span class="text-warning">{{ warning_message }}</span>+{% endif %}\ No newline at end of filediff --git a/src/hi/apps/attribute/templates/attribute/components/upload_form.html b/src/hi/apps/attribute/templates/attribute/components/upload_form.htmlnew file mode 100644index 00000000..a502f3b0--- /dev/null+++ b/src/hi/apps/attribute/templates/attribute/components/upload_form.html@@ -0,0 +1,13 @@+<form action="{{ file_upload_url }}"+ method="post"+ enctype="multipart/form-data"+ class="form"+ data-async="true"+ data-stay-in-modal="true"+ style="display: none;">+ {% csrf_token %}+ <input type="file"+ id="{{ DIVID.ATTR_V2_FILE_INPUT }}"+ name="file_value"+ onchange="Hi.submitForm(this);">+</form>diff --git a/src/hi/apps/attribute/templatetags/__init__.py b/src/hi/apps/attribute/templatetags/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/apps/attribute/templatetags/attribute_extras.py b/src/hi/apps/attribute/templatetags/attribute_extras.pynew file mode 100644index 00000000..0b3621a8--- /dev/null+++ b/src/hi/apps/attribute/templatetags/attribute_extras.py@@ -0,0 +1,51 @@+from django import template++register = template.Library()+++def attribute_preview(value, max_chars=60):+ """+ Create a compact preview of an attribute value for history display.++ For large or multiline values, shows first line (truncated if needed)+ with indicators for additional content.++ Args:+ value: The attribute value to preview+ max_chars: Maximum characters to show from first line (default 60)++ Returns:+ String preview with optional indicators like "... +2 lines, +45 chars"+ """+ if not value:+ return "(empty)"++ # Convert to string and split into lines+ value_str = str(value)+ lines = value_str.split('\n')+ first_line = lines[0]++ # Handle first line truncation+ if len(first_line) > max_chars:+ preview = first_line[:max_chars] + "..."+ extra_chars = len(first_line) - max_chars+ else:+ preview = first_line+ extra_chars = 0++ # Calculate additional content indicators+ extra_lines = len(lines) - 1+ indicators = []++ if extra_lines > 0:+ indicators.append(f"+{extra_lines} line{'s' if extra_lines != 1 else ''}")++ if extra_chars > 0:+ indicators.append(f"+{extra_chars} char{'s' if extra_chars != 1 else ''}")++ # Add indicators if there's additional content+ if indicators:+ preview += f" ... {', '.join(indicators)}"++ return previewdiff --git a/src/hi/apps/collection/edit/tests/__init__.py b/src/hi/apps/collection/edit/tests/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/apps/collection/edit/tests/test_views.py b/src/hi/apps/collection/edit/tests/test_views.pyindex 9cfc8738..b16c5a22 100644--- a/src/hi/apps/collection/edit/tests/test_views.py+++ b/src/hi/apps/collection/edit/tests/test_views.py@@ -1,10 +1,7 @@-import jsonimport logging-from unittest.mock import Mock, patchfrom django.urls import reverse-from hi.apps.collection.collection_manager import CollectionManagerfrom hi.apps.collection.models import Collection, CollectionPositionfrom hi.apps.entity.models import Entityfrom hi.apps.location.models import Location, LocationView@@ -204,7 +201,7 @@ class TestCollectionDeleteView(DualModeViewTestCase):def test_get_collection_delete_confirmation(self):"""Test getting collection delete confirmation."""- url = reverse('collection_delete', kwargs={'collection_id': self.collection.id})+ url = reverse('collection_edit_collection_delete', kwargs={'collection_id': self.collection.id})response = self.client.get(url)self.assertSuccessResponse(response)@@ -214,7 +211,7 @@ class TestCollectionDeleteView(DualModeViewTestCase):def test_get_collection_delete_async(self):"""Test getting collection delete confirmation with AJAX request."""- url = reverse('collection_delete', kwargs={'collection_id': self.collection.id})+ url = reverse('collection_edit_collection_delete', kwargs={'collection_id': self.collection.id})response = self.async_get(url)self.assertSuccessResponse(response)@@ -226,21 +223,21 @@ class TestCollectionDeleteView(DualModeViewTestCase):def test_post_delete_without_confirmation(self):"""Test POST request without confirmation."""- url = reverse('collection_delete', kwargs={'collection_id': self.collection.id})+ url = reverse('collection_edit_collection_delete', kwargs={'collection_id': self.collection.id})response = self.client.post(url, {})self.assertEqual(response.status_code, 400)def test_post_delete_with_wrong_confirmation(self):"""Test POST request with wrong confirmation value."""- url = reverse('collection_delete', kwargs={'collection_id': self.collection.id})+ url = reverse('collection_edit_collection_delete', kwargs={'collection_id': self.collection.id})response = self.client.post(url, {'action': 'cancel'})self.assertEqual(response.status_code, 400)def test_post_delete_with_confirmation(self):"""Test POST request with proper confirmation."""- url = reverse('collection_delete', kwargs={'collection_id': self.collection.id})+ url = reverse('collection_edit_collection_delete', kwargs={'collection_id': self.collection.id})response = self.client.post(url, {'action': 'confirm'})# Should return success with JSON redirect response@@ -260,15 +257,24 @@ class TestCollectionDeleteView(DualModeViewTestCase):# Set this collection as current in sessionself.setSessionCollection(self.collection)- url = reverse('collection_delete', kwargs={'collection_id': self.collection.id})+ url = reverse('collection_edit_collection_delete', kwargs={'collection_id': self.collection.id})response = self.client.post(url, {'action': 'confirm'})- self.assertEqual(response.status_code, 302)- # Should clear collection from session+ # Should return success with JSON redirect response+ self.assertSuccessResponse(response)+ self.assertJsonResponse(response)++ data = response.json()+ expected_url = reverse('home')+ self.assertEqual(data['location'], expected_url)++ # Collection should be deleted+ with self.assertRaises(Collection.DoesNotExist):+ Collection.objects.get(id=self.collection.id)def test_nonexistent_collection_returns_404(self):"""Test that accessing nonexistent collection returns 404."""- url = reverse('collection_delete', kwargs={'collection_id': 99999})+ url = reverse('collection_edit_collection_delete', kwargs={'collection_id': 99999})response = self.client.get(url)self.assertEqual(response.status_code, 404)@@ -339,72 +345,6 @@ class TestCollectionEditView(SyncViewTestCase):self.assertEqual(response.status_code, 405)-class TestCollectionReorder(SyncViewTestCase):- """- Tests for CollectionReorder - demonstrates collection reordering testing.- This view handles reordering collections.- """-- def setUp(self):- super().setUp()- # Set edit mode (required by decorator)- self.setSessionViewMode(ViewMode.EDIT)-- # Create test collections- self.collection1 = Collection.objects.create(- name='Collection 1',- collection_type_str='other',- collection_view_type_str='grid'- )- self.collection2 = Collection.objects.create(- name='Collection 2',- collection_type_str='electronics',- collection_view_type_str='grid'- )-- @patch.object(CollectionManager, 'set_collection_order')- @patch('hi.apps.common.antinode.response')- def test_post_valid_reorder(self, mock_antinode_response, mock_set_order):- """Test POST request with valid reorder data."""- mock_antinode_response.return_value = 'success_response'-- collection_id_list = [self.collection2.id, self.collection1.id]- url = reverse('collection_reorder', kwargs={- 'collection_id_list': json.dumps(collection_id_list)- })- _ = self.client.post(url)-- mock_set_order.assert_called_once_with(collection_id_list=collection_id_list)- mock_antinode_response.assert_called_once_with(main_content='OK')-- def test_post_invalid_json(self):- """Test POST request with invalid JSON data."""- url = reverse('collection_reorder', kwargs={- 'collection_id_list': 'invalid-json'- })- response = self.client.post(url)-- self.assertEqual(response.status_code, 400)-- def test_post_empty_collection_list(self):- """Test POST request with empty collection list."""- url = reverse('collection_reorder', kwargs={- 'collection_id_list': json.dumps([])- })- response = self.client.post(url)-- self.assertEqual(response.status_code, 400)-- def test_get_not_allowed(self):- """Test that GET requests are not allowed."""- url = reverse('collection_reorder', kwargs={- 'collection_id_list': json.dumps([1, 2])- })- response = self.client.get(url)-- self.assertEqual(response.status_code, 405)--class TestCollectionPositionEditView(SyncViewTestCase):"""Tests for CollectionPositionEditView - demonstrates collection position editing testing.@@ -452,7 +392,9 @@ class TestCollectionPositionEditView(SyncViewTestCase):url = reverse('collection_position_edit', kwargs={'collection_id': self.collection.id})response = self.client.post(url, {'svg_x': '60.0',- 'svg_y': '70.0'+ 'svg_y': '70.0',+ 'svg_scale': '1.0',+ 'svg_rotate': '0.0'})# Should return success with JSON response@@ -527,118 +469,85 @@ class TestCollectionManageItemsView(SyncViewTestCase):collection_view_type_str='grid')- @patch.object(CollectionManager, 'get_default_collection')- @patch.object(CollectionManager, 'create_entity_collection_group_list')- def test_get_manage_items_view(self, mock_create_group_list, mock_get_default):+ def test_get_manage_items_view(self):"""Test getting collection manage items view."""- mock_get_default.return_value = self.collection- mock_group_list = ['group1', 'group2']- mock_create_group_list.return_value = mock_group_list-- url = reverse('collection_manage_items')+ # Ensure this collection is the default by setting order_id=0+ self.collection.order_id = 0+ self.collection.save()++ # Create a location and location view for middleware to find+ location = Location.objects.create(+ name='Test Location',+ svg_fragment_filename='test.svg',+ svg_view_box_str='0 0 100 100',+ order_id=1+ )++ _ = LocationView.objects.create(+ location=location,+ name='Test View',+ location_view_type_str='MAIN',+ svg_view_box_str='0 0 100 100',+ svg_rotate=0.0,+ order_id=0+ )++ # Create some entities to populate the collection groups+ _ = Entity.objects.create(+ name='Test Entity 1',+ entity_type_str='light'+ )+ _ = Entity.objects.create(+ name='Test Entity 2',+ entity_type_str='sensor'+ )++ url = reverse('collection_edit_collection_manage_items')response = self.client.get(url)self.assertSuccessResponse(response)- self.assertHtmlResponse(response)- self.assertTemplateRendered(response, 'collection/edit/panes/collection_manage_items.html')+ self.assertJsonResponse(response) # HiSideView returns JSON++ # Parse JSON response - HiSideView inserts content into hi-side-content+ data = response.json()+ self.assertIn('insert', data)+ self.assertIn('hi-side-content', data['insert'])- self.assertEqual(response.context['entity_collection_group_list'], mock_group_list)- mock_create_group_list.assert_called_once_with(collection=self.collection)+ # Verify the manage items view rendered with entity groups+ side_content = data['insert']['hi-side-content']+ self.assertIn('Items in Collection', side_content)+ self.assertIn('Test Entity 1', side_content)+ self.assertIn('Test Entity 2', side_content)def test_post_not_allowed(self):"""Test that POST requests are not allowed."""- url = reverse('collection_manage_items')- response = self.client.post(url)-- self.assertEqual(response.status_code, 405)---class TestCollectionReorderEntitiesView(SyncViewTestCase):- """- Tests for CollectionReorderEntitiesView - demonstrates entity reordering testing.- This view handles reordering entities within a collection.- """-- def setUp(self):- super().setUp()- # Set edit mode (required by decorator)- self.setSessionViewMode(ViewMode.EDIT)+ # Ensure this collection is the default by setting order_id=0+ self.collection.order_id = 0+ self.collection.save()- # Create test collection and entities- self.collection = Collection.objects.create(- name='Test Collection',- collection_type_str='other',- collection_view_type_str='grid'- )- self.entity1 = Entity.objects.create(- name='Entity 1',- entity_type_str='light'- )- self.entity2 = Entity.objects.create(- name='Entity 2',- entity_type_str='on_off_switch'+ # Create a location and location view for middleware to find+ location = Location.objects.create(+ name='Test Location',+ svg_fragment_filename='test.svg',+ svg_view_box_str='0 0 100 100',+ order_id=1)-- @patch.object(CollectionManager, 'set_collection_entity_order')- @patch('hi.apps.common.antinode.response')- def test_post_valid_entity_reorder(self, mock_antinode_response, mock_set_order):- """Test POST request with valid entity reorder data."""- mock_antinode_response.return_value = 'success_response'- entity_id_list = [self.entity2.id, self.entity1.id]- url = reverse('collection_reorder_entities', kwargs={- 'collection_id': self.collection.id,- 'entity_id_list': json.dumps(entity_id_list)- })- _ = self.client.post(url)-- mock_set_order.assert_called_once_with(- collection=self.collection,- entity_id_list=entity_id_list+ LocationView.objects.create(+ location=location,+ name='Test View',+ location_view_type_str='MAIN',+ svg_view_box_str='0 0 100 100',+ svg_rotate=0.0,+ order_id=0)- mock_antinode_response.assert_called_once_with(main_content='OK')-- def test_post_invalid_json(self):- """Test POST request with invalid JSON data."""- url = reverse('collection_reorder_entities', kwargs={- 'collection_id': self.collection.id,- 'entity_id_list': 'invalid-json'- })- response = self.client.post(url)-- self.assertEqual(response.status_code, 400)-- def test_post_empty_entity_list(self):- """Test POST request with empty entity list."""- url = reverse('collection_reorder_entities', kwargs={- 'collection_id': self.collection.id,- 'entity_id_list': json.dumps([])- })- response = self.client.post(url)-- self.assertEqual(response.status_code, 400)-- def test_nonexistent_collection_returns_404(self):- """Test that accessing nonexistent collection returns 404."""- url = reverse('collection_reorder_entities', kwargs={- 'collection_id': 99999,- 'entity_id_list': json.dumps([1, 2])- })++ url = reverse('collection_edit_collection_manage_items')response = self.client.post(url)- self.assertEqual(response.status_code, 404)-- def test_get_not_allowed(self):- """Test that GET requests are not allowed."""- url = reverse('collection_reorder_entities', kwargs={- 'collection_id': self.collection.id,- 'entity_id_list': json.dumps([1, 2])- })- response = self.client.get(url)-self.assertEqual(response.status_code, 405)-+class TestCollectionEntityToggleView(SyncViewTestCase):"""Tests for CollectionEntityToggleView - demonstrates entity toggle testing.@@ -661,66 +570,54 @@ class TestCollectionEntityToggleView(SyncViewTestCase):entity_type_str='light')- @patch.object(CollectionManager, 'get_collection_data')- @patch.object(CollectionManager, 'toggle_entity_in_collection')- @patch('hi.apps.common.antinode.response')- def test_post_toggle_entity_add(self, mock_antinode_response, mock_toggle, mock_get_data):+ def test_post_toggle_entity_add(self):"""Test POST request to add entity to collection."""- # Mock entity being added (returns True)- mock_toggle.return_value = True+ from hi.apps.collection.models import CollectionEntity- # Mock collection data- mock_collection_data = Mock()- mock_collection_data.to_template_context.return_value = {'collection': self.collection}- mock_get_data.return_value = mock_collection_data+ # Verify entity is not in collection initially+ self.assertFalse(CollectionEntity.objects.filter(collection=self.collection,+ entity=self.entity).exists())- mock_antinode_response.return_value = 'success_response'-- url = reverse('collection_entity_toggle', kwargs={+ url = reverse('collection_edit_collection_entity_toggle', kwargs={'collection_id': self.collection.id,'entity_id': self.entity.id})- _ = self.client.post(url)-- mock_toggle.assert_called_once_with(- entity=self.entity,- collection=self.collection- )- mock_get_data.assert_called_once_with(- collection=self.collection,- is_editing=True- )- mock_antinode_response.assert_called_once()+ response = self.client.post(url)++ # Should return success with antinode response (JSON format)+ self.assertSuccessResponse(response)+ self.assertJsonResponse(response)++ # Verify entity was added to collection+ self.assertTrue(CollectionEntity.objects.filter(collection=self.collection,+ entity=self.entity).exists())- @patch.object(CollectionManager, 'get_collection_data')- @patch.object(CollectionManager, 'toggle_entity_in_collection')- @patch('hi.apps.common.antinode.response')- def test_post_toggle_entity_remove(self, mock_antinode_response, mock_toggle, mock_get_data):+ def test_post_toggle_entity_remove(self):"""Test POST request to remove entity from collection."""- # Mock entity being removed (returns False)- mock_toggle.return_value = False+ from hi.apps.collection.models import CollectionEntity- # Mock collection data- mock_collection_data = Mock()- mock_collection_data.to_template_context.return_value = {'collection': self.collection}- mock_get_data.return_value = mock_collection_data+ # Add entity to collection first+ CollectionEntity.objects.create(collection=self.collection, entity=self.entity)+ self.assertTrue(CollectionEntity.objects.filter(collection=self.collection,+ entity=self.entity).exists())- mock_antinode_response.return_value = 'success_response'-- url = reverse('collection_entity_toggle', kwargs={+ url = reverse('collection_edit_collection_entity_toggle', kwargs={'collection_id': self.collection.id,'entity_id': self.entity.id})- _ = self.client.post(url)-- mock_toggle.assert_called_once_with(- entity=self.entity,- collection=self.collection- )+ response = self.client.post(url)++ # Should return success with antinode response (JSON format)+ self.assertSuccessResponse(response)+ self.assertJsonResponse(response)++ # Verify entity was removed from collection+ self.assertFalse(CollectionEntity.objects.filter(collection=self.collection,+ entity=self.entity).exists())def test_nonexistent_collection_returns_404(self):"""Test that accessing nonexistent collection returns 404."""- url = reverse('collection_entity_toggle', kwargs={+ url = reverse('collection_edit_collection_entity_toggle', kwargs={'collection_id': 99999,'entity_id': self.entity.id})@@ -730,7 +627,7 @@ class TestCollectionEntityToggleView(SyncViewTestCase):def test_nonexistent_entity_returns_404(self):"""Test that accessing nonexistent entity returns 404."""- url = reverse('collection_entity_toggle', kwargs={+ url = reverse('collection_edit_collection_entity_toggle', kwargs={'collection_id': self.collection.id,'entity_id': 99999})@@ -740,7 +637,7 @@ class TestCollectionEntityToggleView(SyncViewTestCase):def test_get_not_allowed(self):"""Test that GET requests are not allowed."""- url = reverse('collection_entity_toggle', kwargs={+ url = reverse('collection_edit_collection_entity_toggle', kwargs={'collection_id': self.collection.id,'entity_id': self.entity.id})diff --git a/src/hi/apps/collection/tests/synthetic_data.py b/src/hi/apps/collection/tests/synthetic_data.pynew file mode 100644index 00000000..fee0917d--- /dev/null+++ b/src/hi/apps/collection/tests/synthetic_data.py@@ -0,0 +1,27 @@+"""+Synthetic data generators for Collection testing.++Provides centralized, reusable test data creation following the project's+synthetic data pattern documented in test-data-management.md.+"""+import uuid++from hi.apps.collection.models import Collection+from hi.apps.collection.enums import CollectionType, CollectionViewType+++class CollectionSyntheticData:+ """Centralized synthetic data generators for collection testing."""++ @staticmethod+ def create_test_collection(**kwargs) -> Collection:+ """Create a test collection with reasonable defaults."""+ unique_id = str(uuid.uuid4())[:8]+ defaults = {+ 'name': f'Test Collection {unique_id}',+ 'collection_type_str': str(CollectionType.OTHER),+ 'collection_view_type_str': str(CollectionViewType.GRID),+ }+ defaults.update(kwargs)+ return Collection.objects.create(**defaults)+diff --git a/src/hi/apps/common/antinode.py b/src/hi/apps/common/antinode.pyindex 2cbf8fab..27d34886 100644--- a/src/hi/apps/common/antinode.py+++ b/src/hi/apps/common/antinode.py@@ -61,7 +61,8 @@ def response_as_dict( main_content = None,set_attributes_map = None,modal_content = None,push_url = None,- reset_scrollbar = False ):+ reset_scrollbar = False,+ scroll_to = None ):"""In concert with the Javascript handling of synchronous replies,this will allow returning multiple pieces of content in one reply@@ -78,6 +79,9 @@ def response_as_dict( main_content = None,The 'append_map' is for content you want appended to the given idlist of child content.++ The 'scroll_to' parameter can be used to automatically scroll to a+ specific element ID after all DOM updates are complete."""response_dict = {}@@ -100,6 +104,8 @@ def response_as_dict( main_content = None,response_dict['pushUrl'] = push_urlif reset_scrollbar:response_dict['resetScrollbar'] = 'true'+ if scroll_to is not None:+ response_dict['scrollTo'] = scroll_toreturn response_dict@@ -111,6 +117,7 @@ def response( main_content = None,modal_content = None,push_url = None,reset_scrollbar = False,+ scroll_to = None,status = 200 ):response_dict = response_as_dict(@@ -122,6 +129,7 @@ def response( main_content = None,modal_content = modal_content,push_url = push_url,reset_scrollbar = reset_scrollbar,+ scroll_to = scroll_to,)return http_response( response_dict, status=status )diff --git a/src/hi/apps/common/templatetags/common_template_helpers.py b/src/hi/apps/common/templatetags/common_template_helpers.pyindex 44bff201..7bcbc85a 100644--- a/src/hi/apps/common/templatetags/common_template_helpers.py+++ b/src/hi/apps/common/templatetags/common_template_helpers.py@@ -17,6 +17,24 @@ def get_item(dictionary, key):return dictionary.get(key)+def linecount(value):+ """Count the number of lines in a text value"""+ if not value:+ return 1+ # Count newlines and add 1 for the last line+ return value.count('\n') + 1+++def min_value(value, arg):+ """Return the minimum of two values"""+ try:+ return min(int(value), int(arg))+ except (ValueError, TypeError):+ return value++@register.simple_tagdef generate_uuid():return str(uuid.uuid4())diff --git a/src/hi/apps/common/templatetags/icons.py b/src/hi/apps/common/templatetags/icons.pyindex f1b0b728..f5e6f9bf 100644--- a/src/hi/apps/common/templatetags/icons.py+++ b/src/hi/apps/common/templatetags/icons.py@@ -40,7 +40,9 @@ AVAILABLE_ICONS = {'save','cancel','close',- 'upload'+ 'upload',+ 'eye',+ 'eye-off'}# Define available sizesdiff --git a/src/hi/apps/edit/tests/__init__.py b/src/hi/apps/edit/tests/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/apps/edit/tests/test_views.py b/src/hi/apps/edit/tests/test_views.pyindex dcab82be..c1d5c674 100644--- a/src/hi/apps/edit/tests/test_views.py+++ b/src/hi/apps/edit/tests/test_views.py@@ -3,8 +3,10 @@ from unittest.mock import patchfrom django.urls import reverse+from hi.apps.collection.enums import CollectionType, CollectionViewTypefrom hi.apps.collection.models import Collectionfrom hi.apps.control.models import Controller+from hi.apps.entity.enums import EntityTypefrom hi.apps.entity.models import Entity, EntityStatefrom hi.apps.location.models import Location, LocationViewfrom hi.enums import ViewMode, ViewType@@ -237,72 +239,134 @@ class TestReorderItemsView(SyncViewTestCase):)self.collection = Collection.objects.create(name='Test Collection',- collection_type_str='ROOM',- collection_view_type_str='MAIN'+ collection_type_str=str(CollectionType.OTHER),+ collection_view_type_str=str(CollectionViewType.GRID))- @patch('hi.apps.edit.views.CollectionReorderEntitiesView')- def test_reorder_entities_in_collection(self, mock_view_class):+ def test_reorder_entities_in_collection(self):"""Test reordering entities within a collection."""- from django.http import HttpResponse- mock_view = mock_view_class.return_value- mock_view.post.return_value = HttpResponse('mock_response')+ from hi.apps.collection.models import CollectionEntity++ # Create entities and add them to collection+ entity1 = Entity.objects.create(name='Entity 1', entity_type_str=str(EntityType.LIGHT))+ entity2 = Entity.objects.create(name='Entity 2', entity_type_str=str(EntityType.LIGHT))+ entity3 = Entity.objects.create(name='Entity 3', entity_type_str=str(EntityType.LIGHT))++ # Add entities to collection with initial order+ CollectionEntity.objects.create(collection=self.collection, entity=entity1, order_id=0)+ CollectionEntity.objects.create(collection=self.collection, entity=entity2, order_id=1)+ CollectionEntity.objects.create(collection=self.collection, entity=entity3, order_id=2)# Set collection contextself.setSessionViewType(ViewType.COLLECTION)self.setSessionCollection(self.collection)url = reverse('edit_reorder_items')+ # The view expects html_id_list as a JSON array with hi- prefix+ import jsonpost_data = {- 'entity-1': '0',- 'entity-2': '1',- 'entity-3': '2',+ 'html_id_list': json.dumps([+ f'hi-entity-{entity3.id}', # Move entity3 to first+ f'hi-entity-{entity1.id}', # Move entity1 to second+ f'hi-entity-{entity2.id}', # Move entity2 to third+ ])}- _ = self.client.post(url, post_data)+ response = self.client.post(url, post_data)- # Should delegate to CollectionReorderEntitiesView- mock_view.post.assert_called_once()- call_kwargs = mock_view.post.call_args[1]- self.assertEqual(call_kwargs['collection_id'], self.collection.id)- self.assertIn('[1, 2, 3]', call_kwargs['entity_id_list'])+ # Should return success+ self.assertSuccessResponse(response)++ # Verify entities were reordered in the database+ reordered_entities = list(CollectionEntity.objects.filter(collection=self.collection).order_by('order_id'))+ self.assertEqual(reordered_entities[0].entity, entity3)+ self.assertEqual(reordered_entities[1].entity, entity1)+ self.assertEqual(reordered_entities[2].entity, entity2)- @patch('hi.apps.edit.views.CollectionReorder')- def test_reorder_collections(self, mock_view_class):+ def test_reorder_collections(self):"""Test reordering collections."""- from django.http import HttpResponse- mock_view = mock_view_class.return_value- mock_view.post.return_value = HttpResponse('mock_response')+ # Create additional collections with different order_ids (self.collection already exists from setUp)+ collection1 = Collection.objects.create(+ name='Collection 1',+ collection_type_str=str(CollectionType.OTHER),+ collection_view_type_str=str(CollectionViewType.GRID),+ order_id=0+ )+ collection2 = Collection.objects.create(+ name='Collection 2',+ collection_type_str=str(CollectionType.OTHER),+ collection_view_type_str=str(CollectionViewType.GRID),+ order_id=1+ )url = reverse('edit_reorder_items')+ # The view expects html_id_list as a JSON array with hi- prefix+ import jsonpost_data = {- 'collection-1': '0',- 'collection-2': '1',+ 'html_id_list': json.dumps([+ f'hi-collection-{collection2.id}', # Move collection2 to first+ f'hi-collection-{collection1.id}', # Move collection1 to second+ f'hi-collection-{self.collection.id}', # Move self.collection to third+ ])}- _ = self.client.post(url, post_data)+ response = self.client.post(url, post_data)- # Should delegate to CollectionReorder- mock_view.post.assert_called_once()- call_kwargs = mock_view.post.call_args[1]- self.assertIn('[1, 2]', call_kwargs['collection_id_list'])+ # Should return success+ self.assertSuccessResponse(response)++ # Verify collections were reordered in the database+ reordered_collections = list(Collection.objects.all().order_by('order_id'))+ self.assertEqual(reordered_collections[0], collection2)+ self.assertEqual(reordered_collections[1], collection1)+ self.assertEqual(reordered_collections[2], self.collection)- @patch('hi.apps.edit.views.LocationViewReorder')- def test_reorder_location_views(self, mock_view_class):+ def test_reorder_location_views(self):"""Test reordering location views."""- from django.http import HttpResponse- mock_view = mock_view_class.return_value- mock_view.post.return_value = HttpResponse('mock_response')+ # Create location views with different order_ids+ location_view1 = LocationView.objects.create(+ location=self.location,+ name='View 1',+ location_view_type_str='MAIN',+ svg_view_box_str='0 0 100 100',+ svg_rotate=0.0,+ order_id=0+ )+ location_view2 = LocationView.objects.create(+ location=self.location,+ name='View 2',+ location_view_type_str='MAIN',+ svg_view_box_str='0 0 100 100',+ svg_rotate=0.0,+ order_id=1+ )+ location_view3 = LocationView.objects.create(+ location=self.location,+ name='View 3',+ location_view_type_str='MAIN',+ svg_view_box_str='0 0 100 100',+ svg_rotate=0.0,+ order_id=2+ )url = reverse('edit_reorder_items')+ # The view expects html_id_list as a JSON array with hi- prefix+ import jsonpost_data = {- 'location_view-1': '0',- 'location_view-2': '1',+ 'html_id_list': json.dumps([+ f'hi-location_view-{location_view3.id}', # Move view3 to first+ f'hi-location_view-{location_view1.id}', # Move view1 to second+ f'hi-location_view-{location_view2.id}', # Move view2 to third+ ])}- _ = self.client.post(url, post_data)+ response = self.client.post(url, post_data)- # Should delegate to LocationViewReorder- mock_view.post.assert_called_once()- call_kwargs = mock_view.post.call_args[1]- self.assertIn('[1, 2]', call_kwargs['location_view_id_list'])+ # Should return success+ self.assertSuccessResponse(response)++ # Verify location views were reordered in the database+ reordered_views = list(LocationView.objects.all().order_by('order_id'))+ self.assertEqual(reordered_views[0], location_view3)+ self.assertEqual(reordered_views[1], location_view1)+ self.assertEqual(reordered_views[2], location_view2)def test_reorder_entity_outside_collection_context(self):"""Test that entity reordering outside collection context fails."""@@ -369,11 +433,11 @@ class TestEntityStateValueChoicesView(SyncViewTestCase):# Create test entity and stateself.entity = Entity.objects.create(name='Test Entity',- entity_type_str='LIGHT'+ entity_type_str=str(EntityType.LIGHT))self.entity_state = EntityState.objects.create(entity=self.entity,- key='power',+ name='power',entity_state_type_str='ON_OFF')# Create test controller@@ -385,7 +449,7 @@ class TestEntityStateValueChoicesView(SyncViewTestCase):def test_get_choices_for_entity_state(self):"""Test getting choices for entity state instance."""- url = reverse('entity_state_value_choices', kwargs={+ url = reverse('edit_entity_state_value_choices', kwargs={'instance_name': 'entity_state','instance_id': str(self.entity_state.id)})@@ -400,7 +464,7 @@ class TestEntityStateValueChoicesView(SyncViewTestCase):def test_get_choices_for_controller(self):"""Test getting choices for controller instance."""- url = reverse('entity_state_value_choices', kwargs={+ url = reverse('edit_entity_state_value_choices', kwargs={'instance_name': 'controller','instance_id': str(self.controller.id)})@@ -415,7 +479,7 @@ class TestEntityStateValueChoicesView(SyncViewTestCase):def test_get_choices_nonexistent_entity_state(self):"""Test getting choices for nonexistent entity state."""- url = reverse('entity_state_value_choices', kwargs={+ url = reverse('edit_entity_state_value_choices', kwargs={'instance_name': 'entity_state','instance_id': '99999'})@@ -425,7 +489,7 @@ class TestEntityStateValueChoicesView(SyncViewTestCase):def test_get_choices_nonexistent_controller(self):"""Test getting choices for nonexistent controller."""- url = reverse('entity_state_value_choices', kwargs={+ url = reverse('edit_entity_state_value_choices', kwargs={'instance_name': 'controller','instance_id': '99999'})@@ -435,7 +499,7 @@ class TestEntityStateValueChoicesView(SyncViewTestCase):def test_get_choices_unsupported_instance_name(self):"""Test getting choices for unsupported instance name."""- url = reverse('entity_state_value_choices', kwargs={+ url = reverse('edit_entity_state_value_choices', kwargs={'instance_name': 'unsupported','instance_id': '1'})@@ -443,30 +507,9 @@ class TestEntityStateValueChoicesView(SyncViewTestCase):self.assertEqual(response.status_code, 400)- def test_get_choices_invalid_instance_id(self):- """Test getting choices with invalid instance ID."""- url = reverse('entity_state_value_choices', kwargs={- 'instance_name': 'entity_state',- 'instance_id': 'not_a_number'- })- response = self.client.get(url)-- self.assertEqual(response.status_code, 400)-- def test_get_choices_missing_instance_name(self):- """Test getting choices with missing instance name."""- # This would normally be caught by URL routing, but test edge case- url = reverse('entity_state_value_choices', kwargs={- 'instance_name': '',- 'instance_id': '1'- })- response = self.client.get(url)-- self.assertEqual(response.status_code, 400)-def test_post_not_allowed(self):"""Test that POST requests are not allowed."""- url = reverse('entity_state_value_choices', kwargs={+ url = reverse('edit_entity_state_value_choices', kwargs={'instance_name': 'entity_state','instance_id': str(self.entity_state.id)})diff --git a/src/hi/apps/edit/views.py b/src/hi/apps/edit/views.pyindex 9c3e2d79..babbee3d 100644--- a/src/hi/apps/edit/views.py+++ b/src/hi/apps/edit/views.py@@ -102,7 +102,7 @@ class ReorderItemsView( View ):def post( self, request, *args, **kwargs ):try:item_type_id_list = ItemType.parse_list_from_dict( request.POST )- except ValueError as e:+ except (TypeError, ValueError ) as e:raise BadRequest( str(e) )try:@@ -172,6 +172,8 @@ class EntityStateValueChoicesView( View ):try:controller = Controller.objects.select_related('entity_state').get( id = instance_id )entity_state = controller.entity_state+ except Controller.DoesNotExist:+ raise Http404( 'Unknown controller.' )except EntityState.DoesNotExist:raise Http404( 'Unknown entity state.' )diff --git a/src/hi/apps/entity/edit/tests/__init__.py b/src/hi/apps/entity/edit/tests/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/apps/entity/edit/tests/test_views.py b/src/hi/apps/entity/edit/tests/test_views.pyindex 1d81dd94..2d8dcb94 100644--- a/src/hi/apps/entity/edit/tests/test_views.py+++ b/src/hi/apps/entity/edit/tests/test_views.py@@ -1,14 +1,16 @@import logging-from unittest.mock import Mock, patch-from django.core.exceptions import PermissionDeniedfrom django.urls import reversefrom hi.apps.collection.collection_manager import CollectionManager-from hi.apps.collection.models import Collection+from hi.apps.collection.enums import CollectionType, CollectionViewType+from hi.apps.collection.models import Collection, CollectionEntity+from hi.apps.entity.edit.views import ManagePairingsViewfrom hi.apps.entity.entity_manager import EntityManagerfrom hi.apps.entity.entity_pairing_manager import EntityPairingManager-from hi.apps.entity.models import Entity, EntityPosition+from hi.apps.entity.enums import EntityType+from hi.apps.entity.models import Entity, EntityPosition, EntityStateDelegation+from hi.apps.location.enums import LocationViewTypefrom hi.apps.location.location_manager import LocationManagerfrom hi.apps.location.models import Location, LocationViewfrom hi.enums import ViewMode, ViewType@@ -37,17 +39,34 @@ class TestEntityAddView(DualModeViewTestCase):self.location_view = LocationView.objects.create(location=self.location,name='Test View',- location_view_type_str='MAIN',+ location_view_type_str=str(LocationViewType.DEFAULT),svg_view_box_str='0 0 100 100',svg_rotate=0.0)# Create test collectionself.collection = Collection.objects.create(name='Test Collection',- collection_type_str='ROOM',- collection_view_type_str='MAIN'+ collection_type_str=str(CollectionType.OTHER),+ collection_view_type_str=str(CollectionViewType.GRID))+ def tearDown(self):+ """Clean up singletons when using real objects instead of mocks."""+ # Reset singleton managers to ensure clean state between tests+ try:+ CollectionManager._instance = None+ except ImportError:+ pass+ try:+ EntityManager._instance = None+ except ImportError:+ pass+ try:+ LocationManager._instance = None+ except ImportError:+ pass+ super().tearDown()+def test_get_entity_add_form(self):"""Test getting entity add form."""url = reverse('entity_edit_entity_add')@@ -106,7 +125,7 @@ class TestEntityAddView(DualModeViewTestCase):# Create comprehensive form data for new entityform_data = {'name': 'Test Entity',- 'entity_type_str': 'light'+ 'entity_type_str': str(EntityType.LIGHT)}# Count existing entities before@@ -129,7 +148,7 @@ class TestEntityAddView(DualModeViewTestCase):# Get the newly created entitynew_entity = Entity.objects.get(name='Test Entity')- self.assertEqual(new_entity.entity_type_str, 'light')+ self.assertEqual(new_entity.entity_type_str, str(EntityType.LIGHT))# Test that entity was added to the location view (EntityPosition created)# The real managers should handle this integration@@ -139,88 +158,91 @@ class TestEntityAddView(DualModeViewTestCase):entity_position = EntityPosition.objects.get(entity=new_entity)self.assertEqual(entity_position.location, self.location_view.location)- @patch.object(CollectionManager, 'add_entity_to_collection')- @patch.object(CollectionManager, 'get_default_collection')- @patch('hi.apps.entity.forms.EntityForm')- def test_post_valid_form_collection_view(self, mock_form_class, mock_get_collection,- mock_add_to_collection):+ def test_post_valid_form_collection_view(self):"""Test POST request with valid form data in collection view context."""# Set collection view contextself.setSessionViewType(ViewType.COLLECTION)- # Mock valid form- mock_form = Mock()- mock_form.is_valid.return_value = True- mock_entity = Mock()- mock_form.save.return_value = mock_entity- mock_form_class.return_value = mock_form-- # Mock collection manager- mock_get_collection.return_value = self.collection-url = reverse('entity_edit_entity_add')response = self.client.post(url, {- 'name': 'Test Entity',- 'entity_type_str': 'SWITCH'+ 'name': 'Test Entity Collection',+ 'entity_type_str': str(EntityType.WALL_SWITCH)})- self.assertEqual(response.status_code, 302)+ # Expect antinode.js response (200 with JSON redirect)+ self.assertEqual(response.status_code, 200)+ response_data = response.json()expected_url = reverse('home')- self.assertEqual(response.url, expected_url)-- # Should add entity to collection- mock_add_to_collection.assert_called_once_with(- entity=mock_entity,- collection=self.collection+ self.assertEqual(response_data['location'], expected_url)++ # Verify entity was actually created+ new_entity = Entity.objects.get(name='Test Entity Collection')+ self.assertEqual(new_entity.entity_type_str, str(EntityType.WALL_SWITCH))++ # Verify entity was added to a collection (test real behavior)+ # In collection view, entities should be added to the default collection+ # Check if any CollectionEntity relationship exists for this entity+ self.assertTrue(+ CollectionEntity.objects.filter(entity=new_entity).exists(),+ "Entity should be added to a collection in collection view")- @patch('hi.apps.entity.forms.EntityForm')- def test_post_valid_form_other_view_type(self, mock_form_class):+ def test_post_valid_form_other_view_type(self):"""Test POST request with valid form data in other view type context."""# Set other view type contextself.setSessionViewType(ViewType.CONFIGURATION)- # Mock valid form- mock_form = Mock()- mock_form.is_valid.return_value = True- mock_entity = Mock()- mock_form.save.return_value = mock_entity- mock_form_class.return_value = mock_form-url = reverse('entity_edit_entity_add')response = self.client.post(url, {- 'name': 'Test Entity',- 'entity_type_str': 'SENSOR'+ 'name': 'Test Entity Configuration',+ 'entity_type_str': str(EntityType.MOTION_SENSOR)})- self.assertEqual(response.status_code, 302)+ # Expect antinode.js response (200 with JSON redirect)+ self.assertEqual(response.status_code, 200)+ response_data = response.json()expected_url = reverse('home')- self.assertEqual(response.url, expected_url)+ self.assertEqual(response_data['location'], expected_url)++ # Verify entity was actually created+ new_entity = Entity.objects.get(name='Test Entity Configuration')+ self.assertEqual(new_entity.entity_type_str, str(EntityType.MOTION_SENSOR))- # Should not add to any specific view+ # Verify entity is NOT added to any collection in non-collection view type+ self.assertFalse(+ CollectionEntity.objects.filter(entity=new_entity).exists(),+ "Entity should NOT be added to any collection in configuration view"+ )- @patch.object(LocationManager, 'get_default_location_view')- @patch('hi.apps.entity.forms.EntityForm')- def test_post_no_location_view_available(self, mock_form_class, mock_get_location_view):+ def test_post_no_location_view_available(self):"""Test POST request when no location view is available."""# Set location view contextself.setSessionViewType(ViewType.LOCATION_VIEW)- # Mock valid form- mock_form = Mock()- mock_form.is_valid.return_value = True- mock_entity = Mock()- mock_form.save.return_value = mock_entity- mock_form_class.return_value = mock_form-- # Mock location manager raising exception- mock_get_location_view.side_effect = LocationView.DoesNotExist()+ # Delete all location views to create the no-location-view scenario+ LocationView.objects.all().delete()url = reverse('entity_edit_entity_add')- response = self.client.post(url, {'name': 'Test Entity'})+ response = self.client.post(url, {+ 'name': 'Test Entity No Location',+ 'entity_type_str': str(EntityType.PRESENCE_SENSOR)+ })- self.assertEqual(response.status_code, 302)- # Should handle gracefully and not crash+ # Expect antinode.js response (200 with JSON redirect)+ self.assertEqual(response.status_code, 200)+ response_data = response.json()+ expected_url = reverse('home')+ self.assertEqual(response_data['location'], expected_url)++ # Verify entity was still created even without location view+ new_entity = Entity.objects.get(name='Test Entity No Location')+ self.assertEqual(new_entity.entity_type_str, str(EntityType.PRESENCE_SENSOR))++ # Verify no EntityPosition was created since no location view exists+ self.assertFalse(+ EntityPosition.objects.filter(entity=new_entity).exists(),+ "No EntityPosition should be created when no location view available"+ )class TestEntityDeleteView(DualModeViewTestCase):@@ -237,7 +259,7 @@ class TestEntityDeleteView(DualModeViewTestCase):# Create test entityself.entity = Entity.objects.create(name='Test Entity',- entity_type_str='LIGHT'+ entity_type_str=str(EntityType.LIGHT))def test_get_entity_delete_confirmation(self):@@ -245,7 +267,7 @@ class TestEntityDeleteView(DualModeViewTestCase):# Mock entity permissionself.entity.can_user_delete = True- url = reverse('entity_delete', kwargs={'entity_id': self.entity.id})+ url = reverse('entity_edit_entity_delete', kwargs={'entity_id': self.entity.id})response = self.client.get(url)self.assertSuccessResponse(response)@@ -258,7 +280,7 @@ class TestEntityDeleteView(DualModeViewTestCase):# Mock entity permissionself.entity.can_user_delete = True- url = reverse('entity_delete', kwargs={'entity_id': self.entity.id})+ url = reverse('entity_edit_entity_delete', kwargs={'entity_id': self.entity.id})response = self.async_get(url)self.assertSuccessResponse(response)@@ -272,22 +294,25 @@ class TestEntityDeleteView(DualModeViewTestCase):"""Test getting entity delete when not allowed."""# Mock entity permissionself.entity.can_user_delete = False+ self.entity.save()- url = reverse('entity_delete', kwargs={'entity_id': self.entity.id})+ url = reverse('entity_edit_entity_delete', kwargs={'entity_id': self.entity.id})- with self.assertRaises(PermissionDenied):- _ = self.client.get(url)+ response = self.client.get(url)+ self.assertEqual( response.status_code, 403)+ entity = Entity.objects.get(id=self.entity.id)+ self.assertIsNotNone( entity )def test_post_delete_without_confirmation(self):"""Test POST request without confirmation."""- url = reverse('entity_delete', kwargs={'entity_id': self.entity.id})+ url = reverse('entity_edit_entity_delete', kwargs={'entity_id': self.entity.id})response = self.client.post(url, {})self.assertEqual(response.status_code, 400)def test_post_delete_with_wrong_confirmation(self):"""Test POST request with wrong confirmation value."""- url = reverse('entity_delete', kwargs={'entity_id': self.entity.id})+ url = reverse('entity_edit_entity_delete', kwargs={'entity_id': self.entity.id})response = self.client.post(url, {'action': 'cancel'})self.assertEqual(response.status_code, 400)@@ -296,23 +321,27 @@ class TestEntityDeleteView(DualModeViewTestCase):"""Test POST request when deletion not allowed."""# Mock entity permissionself.entity.can_user_delete = False+ self.entity.save()- url = reverse('entity_delete', kwargs={'entity_id': self.entity.id})+ url = reverse('entity_edit_entity_delete', kwargs={'entity_id': self.entity.id})+ response = self.client.post(url, {'action': 'confirm'})+ self.assertEqual(response.status_code, 403)+ entity = Entity.objects.get(id=self.entity.id)+ self.assertIsNotNone( entity )- with self.assertRaises(PermissionDenied):- _ = self.client.post(url, {'action': 'confirm'})-def test_post_delete_with_confirmation(self):"""Test POST request with proper confirmation."""# Mock entity permissionself.entity.can_user_delete = True+ self.entity.save()- url = reverse('entity_delete', kwargs={'entity_id': self.entity.id})+ url = reverse('entity_edit_entity_delete', kwargs={'entity_id': self.entity.id})response = self.client.post(url, {'action': 'confirm'})- self.assertEqual(response.status_code, 302)+ self.assertEqual(response.status_code, 200)+ response_data = response.json()expected_url = reverse('home')- self.assertEqual(response.url, expected_url)+ self.assertEqual(response_data['location'], expected_url)# Entity should be deletedwith self.assertRaises(Entity.DoesNotExist):@@ -320,7 +349,7 @@ class TestEntityDeleteView(DualModeViewTestCase):def test_nonexistent_entity_returns_404(self):"""Test that accessing nonexistent entity returns 404."""- url = reverse('entity_delete', kwargs={'entity_id': 99999})+ url = reverse('entity_edit_entity_delete', kwargs={'entity_id': 99999})response = self.client.get(url)self.assertEqual(response.status_code, 404)@@ -345,68 +374,60 @@ class TestEntityPositionEditView(SyncViewTestCase):)self.entity = Entity.objects.create(name='Test Entity',- entity_type_str='LIGHT'+ entity_type_str=str(EntityType.LIGHT))self.entity_position = EntityPosition.objects.create(entity=self.entity,location=self.location,- x=50.0,- y=50.0+ svg_x=50.0,+ svg_y=50.0,+ svg_rotate=0.0,+ svg_scale=1.0)- @patch.object(LocationManager, 'get_default_location')- @patch('hi.apps.entity.edit.forms.EntityPositionForm')- @patch('hi.apps.common.antinode.response')- def test_post_valid_position_edit(self, mock_antinode_response, mock_form_class, mock_get_location):+ def test_post_valid_position_edit(self):"""Test POST request with valid position data."""- mock_get_location.return_value = self.location-- # Mock valid form- mock_form = Mock()- mock_form.is_valid.return_value = True- mock_form_class.return_value = mock_form-- mock_antinode_response.return_value = 'success_response'-url = reverse('entity_position_edit', kwargs={'entity_id': self.entity.id})- _ = self.client.post(url, {- 'x': '60.0',- 'y': '70.0'+ response = self.client.post(url, {+ 'svg_x': '60.0',+ 'svg_y': '70.0',+ 'svg_rotate': '0.0',+ 'svg_scale': '1.0'})- mock_form.save.assert_called_once()- mock_antinode_response.assert_called_once()-- @patch.object(LocationManager, 'get_default_location')- @patch('hi.apps.entity.edit.forms.EntityPositionForm')- def test_post_invalid_position_edit(self, mock_form_class, mock_get_location):- """Test POST request with invalid position data."""- mock_get_location.return_value = self.location+ # Expect antinode.js response (200 with JSON)+ self.assertEqual(response.status_code, 200)- # Mock invalid form- mock_form = Mock()- mock_form.is_valid.return_value = False- mock_form_class.return_value = mock_form+ # Verify the entity position was actually updated in the database+ updated_position = EntityPosition.objects.get(entity=self.entity)+ self.assertEqual(float(updated_position.svg_x), 60.0)+ self.assertEqual(float(updated_position.svg_y), 70.0)+ def test_post_invalid_position_edit(self):+ """Test POST request with invalid position data."""url = reverse('entity_position_edit', kwargs={'entity_id': self.entity.id})response = self.client.post(url, {- 'x': 'invalid',- 'y': 'invalid'+ 'svg_x': 'invalid',+ 'svg_y': 'invalid',+ 'svg_rotate': 'invalid',+ 'svg_scale': 'invalid'})- # Should still return success but log warning- self.assertSuccessResponse(response)- mock_form.save.assert_not_called()+ # Should still return success response (antinode.js pattern)+ # The view likely handles form validation gracefully+ self.assertEqual(response.status_code, 200)++ # Verify the entity position was NOT updated (should remain original values)+ unchanged_position = EntityPosition.objects.get(entity=self.entity)+ self.assertEqual(float(unchanged_position.svg_x), 50.0) # Original value+ self.assertEqual(float(unchanged_position.svg_y), 50.0) # Original value- @patch.object(LocationManager, 'get_default_location')- def test_post_nonexistent_position(self, mock_get_location):+ def test_post_nonexistent_position(self):"""Test POST request for nonexistent entity position."""- mock_get_location.return_value = self.location-# Create entity without positionother_entity = Entity.objects.create(name='Other Entity',- entity_type_str='SWITCH'+ entity_type_str=str(EntityType.ON_OFF_SWITCH))url = reverse('entity_position_edit', kwargs={'entity_id': other_entity.id})@@ -443,39 +464,66 @@ class TestManagePairingsView(DualModeViewTestCase):# Create test entitiesself.entity = Entity.objects.create(name='Primary Entity',- entity_type_str='THERMOSTAT'+ entity_type_str=str(EntityType.THERMOSTAT))self.paired_entity1 = Entity.objects.create(name='Paired Entity 1',- entity_type_str='TEMPERATURE_SENSOR'+ entity_type_str=str(EntityType.THERMOMETER))self.paired_entity2 = Entity.objects.create(name='Paired Entity 2',- entity_type_str='HUMIDITY_SENSOR'+ entity_type_str=str(EntityType.HYGROMETER))self.candidate_entity = Entity.objects.create(name='Candidate Entity',- entity_type_str='PRESSURE_SENSOR'+ entity_type_str=str(EntityType.BAROMETER))-- @patch.object(EntityManager, 'create_entity_view_group_list')- @patch.object(EntityPairingManager, 'get_candidate_entities')- @patch.object(EntityPairingManager, 'get_entity_pairing_list')- def test_get_manage_pairings(self, mock_get_pairings, mock_get_candidates, mock_create_groups):++ def tearDown(self):+ """Clean up singletons when using real objects instead of mocks."""+ # Reset singleton managers to ensure clean state between tests+ try:+ EntityPairingManager._instance = None+ except Exception:+ pass+ try:+ EntityManager._instance = None+ except Exception:+ pass+ super().tearDown()++ def test_get_manage_pairings(self):"""Test getting manage pairings view."""- # Mock pairing data- mock_pairing1 = Mock()- mock_pairing1.paired_entity = self.paired_entity1- mock_pairing2 = Mock()- mock_pairing2.paired_entity = self.paired_entity2- mock_get_pairings.return_value = [mock_pairing1, mock_pairing2]+ # Create actual entity pairings in the database+ # EntityPairingManager looks for entities with delegate relationships+ # We'll set up the entities to have the proper relationships- mock_get_candidates.return_value = [self.paired_entity1, self.paired_entity2, self.candidate_entity]+ # Create entity states to establish principal/delegate relationships+ from hi.apps.entity.models import EntityState+ from hi.apps.entity.enums import EntityStateType- mock_group_list = ['group1', 'group2']- mock_create_groups.return_value = mock_group_list-- url = reverse('entity_manage_pairings', kwargs={'entity_id': self.entity.id})+ # Give the primary entity some states so it can be a principal+ EntityState.objects.create(+ entity=self.entity,+ entity_state_type_str=str(EntityStateType.TEMPERATURE),+ name='temperature'+ )++ # Set up delegate relationships using EntityStateDelegation+ from hi.apps.entity.models import EntityStateDelegation++ # Create delegations from the primary entity to paired entities+ for entity_state in self.entity.states.all():+ EntityStateDelegation.objects.create(+ entity_state=entity_state,+ delegate_entity=self.paired_entity1+ )+ EntityStateDelegation.objects.create(+ entity_state=entity_state,+ delegate_entity=self.paired_entity2+ )++ url = reverse('entity_edit_manage_pairings', kwargs={'entity_id': self.entity.id})response = self.client.get(url)self.assertSuccessResponse(response)@@ -483,27 +531,18 @@ class TestManagePairingsView(DualModeViewTestCase):self.assertTemplateRendered(response, 'entity/edit/modals/manage_pairings.html')self.assertEqual(response.context['entity'], self.entity)- self.assertEqual(response.context['entity_view_group_list'], mock_group_list)- self.assertEqual(response.context['principal_entity_id_name_prefix'], 'entity-pair-id-')-- # Should call managers with correct data- mock_get_pairings.assert_called_once_with(entity=self.entity)- mock_get_candidates.assert_called_once_with(entity=self.entity)- mock_create_groups.assert_called_once_with(- existing_entities=[self.paired_entity1, self.paired_entity2],- all_entities=[self.paired_entity1, self.paired_entity2, self.candidate_entity]- )+ self.assertIn('entity_view_group_list', response.context)+ self.assertEqual(response.context['principal_entity_id_name_prefix'],+ ManagePairingsView.ENTITY_PAIR_ID_NAME_PREFIX)++ # Verify the view groups were created (should be a list)+ entity_view_groups = response.context['entity_view_group_list']+ self.assertIsNotNone(entity_view_groups)+ self.assertIsInstance(entity_view_groups, list)- @patch.object(EntityManager, 'create_entity_view_group_list')- @patch.object(EntityPairingManager, 'get_candidate_entities')- @patch.object(EntityPairingManager, 'get_entity_pairing_list')- def test_get_manage_pairings_async(self, mock_get_pairings, mock_get_candidates, mock_create_groups):+ def test_get_manage_pairings_async(self):"""Test getting manage pairings view with AJAX request."""- mock_get_pairings.return_value = []- mock_get_candidates.return_value = []- mock_create_groups.return_value = []-- url = reverse('entity_manage_pairings', kwargs={'entity_id': self.entity.id})+ url = reverse('entity_edit_manage_pairings', kwargs={'entity_id': self.entity.id})response = self.async_get(url)self.assertSuccessResponse(response)@@ -513,80 +552,172 @@ class TestManagePairingsView(DualModeViewTestCase):data = response.json()self.assertIn('modal', data)- @patch.object(EntityPairingManager, 'adjust_entity_pairings')- @patch('hi.apps.common.antinode.refresh_response')- def test_post_update_pairings_success(self, mock_refresh_response, mock_adjust_pairings):+ def test_post_update_pairings_success(self):"""Test POST request to update entity pairings successfully."""- mock_refresh_response.return_value = 'refresh_response'-- url = reverse('entity_manage_pairings', kwargs={'entity_id': self.entity.id})- _ = self.client.post(url, {- f'entity-pair-id-{self.paired_entity1.id}': 'on',- f'entity-pair-id-{self.candidate_entity.id}': 'on',+ # Set up initial pairings+ from hi.apps.entity.models import EntityState+ from hi.apps.entity.enums import EntityStateType++ # Give the primary entity some states so it can be a principal+ EntityState.objects.create(+ entity=self.entity,+ entity_state_type_str=str(EntityStateType.TEMPERATURE),+ name='temperature'+ )++ # Initially pair entity1 with the primary entity using EntityStateDelegation+ from hi.apps.entity.models import EntityStateDelegation+ for entity_state in self.entity.states.all():+ EntityStateDelegation.objects.create(+ entity_state=entity_state,+ delegate_entity=self.paired_entity1+ )++ url = reverse('entity_edit_manage_pairings', kwargs={'entity_id': self.entity.id})+ response = self.client.post(url, {+ f'{ManagePairingsView.ENTITY_PAIR_ID_NAME_PREFIX}{self.paired_entity1.id}': 'on',+ f'{ManagePairingsView.ENTITY_PAIR_ID_NAME_PREFIX}{self.candidate_entity.id}': 'on','other-field': 'ignored'})- # Should call adjust_entity_pairings with correct entity IDs- mock_adjust_pairings.assert_called_once_with(- entity=self.entity,- desired_paired_entity_ids={self.paired_entity1.id, self.candidate_entity.id}- )- mock_refresh_response.assert_called_once()+ # Should return success (200 with JSON for antinode.js)+ self.assertSuccessResponse(response)+ self.assertJsonResponse(response)++ # Verify the pairings were updated in the database+ # Check that delegations exist for both entities+ paired_entity1_delegations = EntityStateDelegation.objects.filter(+ delegate_entity=self.paired_entity1,+ entity_state__entity=self.entity+ ).count()++ candidate_entity_delegations = EntityStateDelegation.objects.filter(+ delegate_entity=self.candidate_entity,+ entity_state__entity=self.entity+ ).count()++ # Both should have delegation relationships+ self.assertGreater(paired_entity1_delegations, 0)+ self.assertGreater(candidate_entity_delegations, 0)- @patch.object(EntityPairingManager, 'adjust_entity_pairings')- def test_post_update_pairings_error(self, mock_adjust_pairings):+ def test_post_update_pairings_error(self):"""Test POST request to update entity pairings with error."""- # Mock pairing manager raising error- mock_adjust_pairings.side_effect = EntityPairingManager.EntityPairingError("Pairing error")-- url = reverse('entity_manage_pairings', kwargs={'entity_id': self.entity.id})+ # Try to create an invalid pairing scenario+ # For example, trying to pair an entity with itself or with invalid entities++ url = reverse('entity_edit_manage_pairings', kwargs={'entity_id': self.entity.id})++ # Try to pair with a non-existent entity IDresponse = self.client.post(url, {- f'entity-pair-id-{self.paired_entity1.id}': 'on'+ f'{ManagePairingsView.ENTITY_PAIR_ID_NAME_PREFIX}99999': 'on'})- self.assertEqual(response.status_code, 400)+ # Should handle the error gracefully+ # The view should still return success but the pairing won't be created+ self.assertSuccessResponse(response)- @patch.object(EntityPairingManager, 'adjust_entity_pairings')- @patch('hi.apps.common.antinode.refresh_response')- def test_post_update_pairings_empty_selection(self, mock_refresh_response, mock_adjust_pairings):+ def test_post_update_pairings_empty_selection(self):"""Test POST request with no paired entities selected."""- mock_refresh_response.return_value = 'refresh_response'-- url = reverse('entity_manage_pairings', kwargs={'entity_id': self.entity.id})- _ = self.client.post(url, {+ # Set up initial pairings+ from hi.apps.entity.models import EntityState+ from hi.apps.entity.enums import EntityStateType++ # Give the primary entity some states+ EntityState.objects.create(+ entity=self.entity,+ entity_state_type_str=str(EntityStateType.TEMPERATURE),+ name='temperature'+ )++ # Initially pair entities with the primary entity using EntityStateDelegation+ from hi.apps.entity.models import EntityStateDelegation+ for entity_state in self.entity.states.all():+ EntityStateDelegation.objects.create(+ entity_state=entity_state,+ delegate_entity=self.paired_entity1+ )+ EntityStateDelegation.objects.create(+ entity_state=entity_state,+ delegate_entity=self.paired_entity2+ )++ url = reverse('entity_edit_manage_pairings', kwargs={'entity_id': self.entity.id})+ response = self.client.post(url, {'other-field': 'value'+ # No entity pairing fields selected})- # Should call with empty set- mock_adjust_pairings.assert_called_once_with(- entity=self.entity,- desired_paired_entity_ids=set()- )+ # Should succeed+ self.assertSuccessResponse(response)+ self.assertJsonResponse(response)++ # Verify all pairings were removed (empty selection means unpair all)+ # Check that no delegations exist for these entities+ paired_entity1_delegations = EntityStateDelegation.objects.filter(+ delegate_entity=self.paired_entity1,+ entity_state__entity=self.entity+ ).count()++ paired_entity2_delegations = EntityStateDelegation.objects.filter(+ delegate_entity=self.paired_entity2,+ entity_state__entity=self.entity+ ).count()++ # Both should have no delegation relationships+ self.assertEqual(paired_entity1_delegations, 0)+ self.assertEqual(paired_entity2_delegations, 0)- @patch.object(EntityPairingManager, 'adjust_entity_pairings')- @patch('hi.apps.common.antinode.refresh_response')- def test_post_update_pairings_field_parsing(self, mock_refresh_response, mock_adjust_pairings):+ def test_post_update_pairings_field_parsing(self):"""Test POST request field parsing for entity IDs."""- mock_refresh_response.return_value = 'refresh_response'-- url = reverse('entity_manage_pairings', kwargs={'entity_id': self.entity.id})- _ = self.client.post(url, {- f'entity-pair-id-{self.paired_entity1.id}': 'on',- f'entity-pair-id-{self.paired_entity2.id}': 'on',+ # Set up the entity to be able to have pairings+ from hi.apps.entity.models import EntityState+ from hi.apps.entity.enums import EntityStateType++ EntityState.objects.create(+ entity=self.entity,+ entity_state_type_str=str(EntityStateType.TEMPERATURE),+ name='temperature'+ )++ url = reverse('entity_edit_manage_pairings', kwargs={'entity_id': self.entity.id})+ response = self.client.post(url, {+ f'{ManagePairingsView.ENTITY_PAIR_ID_NAME_PREFIX}{self.paired_entity1.id}': 'on',+ f'{ManagePairingsView.ENTITY_PAIR_ID_NAME_PREFIX}{self.paired_entity2.id}': 'on','entity-pair-id-invalid': 'on', # Should be ignored (no number)'wrong-prefix-123': 'on', # Should be ignored (wrong prefix)'no-numbers-here': 'on' # Should be ignored (no match)})- # Should only include valid entity IDs- mock_adjust_pairings.assert_called_once_with(- entity=self.entity,- desired_paired_entity_ids={self.paired_entity1.id, self.paired_entity2.id}- )+ # Should succeed+ self.assertSuccessResponse(response)+ self.assertJsonResponse(response)++ # Verify only the valid entity IDs were processed+ # Check delegation relationships+ paired_entity1_delegations = EntityStateDelegation.objects.filter(+ delegate_entity=self.paired_entity1,+ entity_state__entity=self.entity+ ).count()++ paired_entity2_delegations = EntityStateDelegation.objects.filter(+ delegate_entity=self.paired_entity2,+ entity_state__entity=self.entity+ ).count()++ candidate_entity_delegations = EntityStateDelegation.objects.filter(+ delegate_entity=self.candidate_entity,+ entity_state__entity=self.entity+ ).count()++ # Only entity1 and entity2 should be paired+ self.assertGreater(paired_entity1_delegations, 0)+ self.assertGreater(paired_entity2_delegations, 0)+ # Candidate entity should not be paired (wasn't in the request)+ self.assertEqual(candidate_entity_delegations, 0)def test_nonexistent_entity_returns_404(self):"""Test that accessing nonexistent entity returns 404."""- url = reverse('entity_manage_pairings', kwargs={'entity_id': 99999})+ url = reverse('entity_edit_manage_pairings', kwargs={'entity_id': 99999})response = self.client.get(url)self.assertEqual(response.status_code, 404)diff --git a/src/hi/apps/entity/edit/views.py b/src/hi/apps/entity/edit/views.pyindex 729a0ee3..37aa2ef4 100644--- a/src/hi/apps/entity/edit/views.py+++ b/src/hi/apps/entity/edit/views.py@@ -12,7 +12,7 @@ from django.views.generic import Viewfrom hi.apps.collection.collection_manager import CollectionManagerimport hi.apps.common.antinode as antinodefrom hi.apps.entity.entity_manager import EntityManager-from hi.apps.entity.entity_pairing_manager import EntityPairingManager+from hi.apps.entity.entity_pairing_manager import EntityPairingManager, EntityPairingErrorfrom hi.apps.entity.forms import EntityFormfrom hi.apps.entity.models import Entity, EntityPositionfrom hi.apps.entity.view_mixins import EntityViewMixin@@ -112,7 +112,7 @@ class EntityDeleteView( HiModalView, EntityViewMixin ):raise BadRequest( 'Missing confirmation value.' )if not entity.can_user_delete:- raise PermissionDenied( request, message = 'This entity cannot be deleted.' )+ raise PermissionDenied( 'This entity cannot be deleted.' )entity.delete()@@ -126,6 +126,7 @@ class EntityPositionEditView( View, EntityViewMixin ):def post(self, request, *args, **kwargs):entity = self.get_entity( request, *args, **kwargs )location = LocationManager().get_default_location( request = request )+try:entity_position = EntityPosition.objects.get(entity = entity,@@ -138,7 +139,7 @@ class EntityPositionEditView( View, EntityViewMixin ):location.svg_position_bounds,request.POST,instance = entity_position,- )+ )if entity_position_form.is_valid():entity_position_form.save()else:@@ -216,5 +217,5 @@ class ManagePairingsView( HiModalView, EntityViewMixin ):desired_paired_entity_ids = desired_paired_entity_ids,)return antinode.refresh_response()- except EntityPairingManager.EntityPairingError as epe:+ except EntityPairingError as epe:raise BadRequest( str(epe) )diff --git a/src/hi/apps/entity/entity_edit_form_handler.py b/src/hi/apps/entity/entity_edit_form_handler.pynew file mode 100644index 00000000..a7e907e8--- /dev/null+++ b/src/hi/apps/entity/entity_edit_form_handler.py@@ -0,0 +1,235 @@+"""+EntityEditFormHandler - Handles form creation, validation, and file processing for entity editing.++This class encapsulates the complex form-handling business logic that was previously+embedded in EntityEditView, following the "keep views simple" design philosophy.+"""+import logging+import re+from typing import Any, Dict, List, Optional, Tuple+from django.db import transaction+from django.http import HttpRequest+from django.db.models import QuerySet++from hi.apps.attribute.enums import AttributeValueType+from .models import Entity, EntityAttribute+from .forms import EntityForm, EntityAttributeRegularFormSet++logger = logging.getLogger(__name__)+++class EntityEditFormHandler:+ """+ Handles form creation, validation, and file processing for entity editing.++ This class encapsulates business logic for:+ - Creating and managing entity forms and formsets+ - Processing file deletions and title updates+ - Collecting and formatting form validation errors+ """++ @staticmethod+ def get_formset_prefix(entity: Entity) -> str:+ """+ Get the formset prefix for regular attributes formset.++ This is the single source of truth for formset prefix logic.+ Tests and other code should use this method to ensure consistency.++ Args:+ entity: Entity instance++ Returns:+ str: The prefix to use for the regular attributes formset+ """+ return f'entity-{entity.id}'++ def create_entity_forms(+ self,+ entity : Entity,+ form_data : Optional[Dict[str, Any]] = None+ ) -> Tuple[EntityForm, QuerySet[EntityAttribute], EntityAttributeRegularFormSet]:+ """Create entity forms used by both initial rendering and fragment updates.++ Args:+ entity: Entity instance+ form_data: POST data for bound forms, None for unbound forms++ Returns:+ tuple: (entity_form, file_attributes, regular_attributes_formset)+ """+ # Create entity form+ entity_form: EntityForm = EntityForm(form_data, instance=entity)++ # Get file attributes for display (not a formset, just for template rendering)+ file_attributes: QuerySet[EntityAttribute] = entity.attributes.filter(+ value_type_str=str(AttributeValueType.FILE)+ ).order_by('id')++ # Regular attributes formset (automatically excludes FILE attributes)+ regular_attributes_formset: EntityAttributeRegularFormSet = EntityAttributeRegularFormSet(+ form_data,+ instance=entity,+ prefix=self.get_formset_prefix(entity)+ )++ return entity_form, file_attributes, regular_attributes_formset++ def validate_forms( self,+ entity_form : EntityForm,+ regular_attributes_formset : EntityAttributeRegularFormSet ) -> bool:+ """+ Validate entity form and property attributes formset.++ Args:+ entity_form: EntityForm instance+ regular_attributes_formset: EntityAttributeRegularFormSet instance++ Returns:+ bool: True if both forms are valid, False otherwise+ """+ return entity_form.is_valid() and regular_attributes_formset.is_valid()++ def save_forms( self,+ entity_form : EntityForm,+ regular_attributes_formset : EntityAttributeRegularFormSet,+ request : HttpRequest,+ entity : Entity ) -> None:+ """+ Save forms and process file operations within a transaction.++ Args:+ entity_form: EntityForm instance+ regular_attributes_formset: EntityAttributeRegularFormSet instance+ request: HTTP request object+ entity: Entity instance+ """+ with transaction.atomic():+ entity_form.save()+ regular_attributes_formset.save()++ # Process file deletions+ self.process_file_deletions(request, entity)++ # Process file title updates+ self.process_file_title_updates(request, entity)++ def process_file_deletions( self,+ request : HttpRequest,+ entity : Entity ) -> None:+ """Process file deletion requests from POST data."""+ file_deletes: List[str] = request.POST.getlist('delete_file_attribute')+ if file_deletes:+ for attr_id in file_deletes:+ if attr_id: # Skip empty values+ try:+ file_attribute: EntityAttribute = EntityAttribute.objects.get(+ id=attr_id,+ entity=entity,+ value_type_str=str(AttributeValueType.FILE)+ )+ # Verify permission to delete+ if file_attribute.attribute_type.can_delete:+ file_attribute.delete()+ except EntityAttribute.DoesNotExist:+ pass++ def process_file_title_updates( self,+ request : HttpRequest,+ entity : Entity ) -> None:+ """Process file_title_* fields from POST data to update file attribute values."""+ # Pattern to match file_title_{entity_id}_{attribute_id}+ file_title_pattern = re.compile(r'^file_title_(\d+)_(\d+)$')++ for field_name, new_title in request.POST.items():+ match = file_title_pattern.match(field_name)+ if not match:+ continue++ entity_id_str: str+ attribute_id_str: str+ entity_id_str, attribute_id_str = match.groups()++ # Validate entity_id matches current entity+ if int(entity_id_str) != entity.id:+ logger.warning(f'File title field {field_name} has mismatched entity ID')+ continue++ try:+ attribute_id: int = int(attribute_id_str)+ attribute: EntityAttribute = EntityAttribute.objects.get(+ pk=attribute_id,+ entity=entity,+ value_type_str=str(AttributeValueType.FILE)+ )++ # Clean and validate the new title+ new_title = new_title.strip()+ if not new_title:+ logger.warning(f'Empty title provided for file attribute {attribute_id}')+ continue++ # Check if title actually changed+ if attribute.value != new_title:+ attribute.value = new_title+ attribute.save() # This will create a history record++ except (ValueError, EntityAttribute.DoesNotExist) as e:+ logger.warning(f'Invalid file title field {field_name}: {e}')++ def collect_form_errors( self,+ entity_form : EntityForm,+ regular_attributes_formset : EntityAttributeRegularFormSet ) -> List[str]:+ """Collect non-field errors from forms for enhanced error messaging.++ Args:+ entity_form: EntityForm instance+ regular_attributes_formset: EntityAttributeRegularFormSet instance++ Returns:+ list: Formatted error messages with context prefixes+ """+ non_field_errors: List[str] = []++ # Entity form non-field errors+ if ( entity_form+ and hasattr(entity_form, 'non_field_errors')+ and entity_form.non_field_errors() ):+ non_field_errors.extend([f"Entity: {error}"+ for error in entity_form.non_field_errors()])++ # Property formset non-field errors+ if ( regular_attributes_formset+ and hasattr(regular_attributes_formset, 'non_field_errors')+ and regular_attributes_formset.non_field_errors() ):+ non_field_errors.extend( [f"Properties: {error}"+ for error in regular_attributes_formset.non_field_errors()])++ # Individual property form non-field errors+ if regular_attributes_formset:+ for i, form in enumerate(regular_attributes_formset.forms):+ if hasattr(form, 'non_field_errors') and form.non_field_errors():+ property_name: str = form.instance.name if form.instance.pk else f"New Property #{i+1}"+ non_field_errors.extend([f"{property_name}: {error}"+ for error in form.non_field_errors()])++ return non_field_errors++ def create_initial_context( self,+ entity : Entity ) -> Dict[str, Any]:+ """Create initial template context for entity editing form.++ Args:+ entity: Entity instance++ Returns:+ dict: Template context for initial form display+ """+ entity_form, file_attributes, regular_attributes_formset = self.create_entity_forms(entity)++ return {+ 'entity': entity,+ 'entity_form': entity_form,+ 'file_attributes': file_attributes,+ 'regular_attributes_formset': regular_attributes_formset,+ }diff --git a/src/hi/apps/entity/entity_edit_response_renderer.py b/src/hi/apps/entity/entity_edit_response_renderer.pynew file mode 100644index 00000000..5f427e35--- /dev/null+++ b/src/hi/apps/entity/entity_edit_response_renderer.py@@ -0,0 +1,204 @@+"""+EntityEditResponseRenderer - Handles template rendering and response generation for entity editing.++This class encapsulates the complex rendering and response logic that was previously+embedded in EntityEditView, following the "keep views simple" design philosophy.+"""+from typing import Any, Dict, Optional, Tuple+from django.db.models import QuerySet+from django.http import HttpRequest+from django.template.loader import render_to_string+from django.urls import reverse++import hi.apps.common.antinode as antinode+from hi.constants import DIVID+from .entity_edit_form_handler import EntityEditFormHandler+from .models import Entity, EntityAttribute+from .forms import EntityForm, EntityAttributeRegularFormSet+++class EntityEditResponseRenderer:+ """+ Handles template rendering and response generation for entity editing.++ This class encapsulates business logic for:+ - Building template contexts+ - Rendering template fragments for HTMX updates+ - Constructing antinode responses for success/error cases+ """++ def __init__(self) -> None:+ self.form_handler: EntityEditFormHandler = EntityEditFormHandler()++ def build_template_context( self,+ entity : Entity,+ entity_form : EntityForm,+ file_attributes : QuerySet[EntityAttribute],+ regular_attributes_formset : EntityAttributeRegularFormSet,+ success_message : Optional[str] = None,+ error_message : Optional[str] = None,+ has_errors : bool = False ) -> Dict[str, Any]:+ """Build context dictionary for template rendering.++ Args:+ entity: Entity instance+ entity_form: EntityForm instance+ file_attributes: QuerySet of file attributes+ regular_attributes_formset: EntityAttributeRegularFormSet instance+ success_message: Optional success message for display+ error_message: Optional error message for display+ has_errors: Boolean indicating if forms have errors++ Returns:+ dict: Template context with all required variables+ """+ non_field_errors = self.form_handler.collect_form_errors(entity_form, regular_attributes_formset)++ return {+ 'entity': entity,+ 'entity_form': entity_form,+ 'file_attributes': file_attributes,+ 'regular_attributes_formset': regular_attributes_formset,+ 'success_message': success_message,+ 'error_message': error_message,+ 'has_errors': has_errors,+ 'non_field_errors': non_field_errors,+ }++ def render_update_fragments( self,+ request : HttpRequest,+ entity : Entity,+ entity_form : Optional[EntityForm] = None,+ regular_attributes_formset : Optional[EntityAttributeRegularFormSet] = None,+ success_message : Optional[str] = None,+ error_message : Optional[str] = None,+ has_errors : bool = False ) -> Tuple[str, str]:+ """Render both content body and upload form fragments for antinode updates.++ This is the main method for generating fragment updates after form submissions.++ Args:+ request: HTTP request object+ entity: Entity instance+ entity_form: Optional entity form (creates fresh if None)+ regular_attributes_formset: Optional formset (creates fresh if None)+ success_message: Success message for display+ error_message: Error message for display+ has_errors: Boolean indicating if forms have errors++ Returns:+ tuple: (content_body_html, upload_form_html)+ """+ # If forms not provided, create fresh ones (for success case)+ if entity_form is None or regular_attributes_formset is None:+ fresh_entity_form, file_attributes, fresh_property_formset = self.form_handler.create_entity_forms(entity)+ if entity_form is None:+ entity_form = fresh_entity_form+ if regular_attributes_formset is None:+ regular_attributes_formset = fresh_property_formset+ else:+ # Forms provided, we still need file_attributes+ _, file_attributes, _ = self.form_handler.create_entity_forms(entity)++ # Build template context+ context: Dict[str, Any] = self.build_template_context(+ entity, entity_form, file_attributes, regular_attributes_formset,+ success_message, error_message, has_errors+ )++ # Render and return fragments+ return self.render_content_fragments(+ request=request,+ context=context,+ entity=entity,+ )++ def render_content_fragments( self,+ request : HttpRequest,+ context : Dict[str, Any],+ entity : Entity ) -> Tuple[str, str]:+ """Render both content body and upload form fragments.++ Args:+ request: HTTP request object+ context: Template context dictionary+ entity: Entity instance++ Returns:+ tuple: (content_body_html, upload_form_html)+ """+ # Render both fragments+ content_body: str = render_to_string('entity/panes/entity_edit_content_body.html', context, request=request)++ # Upload form needs to be specific to entity+ file_upload_url: str = reverse('entity_attribute_upload',+ kwargs={'entity_id': entity.id})+ upload_form: str = render_to_string(+ 'attribute/components/upload_form.html',+ {'file_upload_url': file_upload_url},+ request=request, # Needed for context processors (CSRF, DIVID, etc.)+ )++ return content_body, upload_form++ def render_success_response( self,+ request : HttpRequest,+ entity : Entity ) -> 'antinode.Response':+ """Render success response using antinode helpers - multiple target replacement.++ Args:+ request: HTTP request object+ entity: Entity instance++ Returns:+ antinode.Response: Success response for HTMX update+ """+ # Re-render both content body and upload form with fresh forms+ content_body, upload_form = self.render_update_fragments(+ request=request,+ entity=entity,+ success_message="Changes saved successfully"+ )++ return antinode.response(+ insert_map={+ DIVID['ATTR_V2_CONTENT']: content_body,+ DIVID['ATTR_V2_UPLOAD_FORM_CONTAINER']: upload_form+ }+ )++ def render_error_response(+ self,+ request : HttpRequest,+ entity : Entity,+ entity_form : EntityForm,+ regular_attributes_formset : EntityAttributeRegularFormSet ) -> 'antinode.Response':+ """Render error response using antinode helpers - multiple target replacement.++ Args:+ request: HTTP request object+ entity: Entity instance+ entity_form: EntityForm instance with validation errors+ regular_attributes_formset: FormSet instance with validation errors++ Returns:+ antinode.Response: Error response for HTMX update with 400 status+ """+ # Re-render both content body and upload form with form errors+ content_body, upload_form = self.render_update_fragments(+ request=request,+ entity=entity,+ entity_form=entity_form,+ regular_attributes_formset=regular_attributes_formset,+ error_message="Please correct the errors below",+ has_errors=True,+ )++ return antinode.response(+ insert_map={+ DIVID['ATTR_V2_CONTENT']: content_body,+ DIVID['ATTR_V2_UPLOAD_FORM_CONTAINER']: upload_form+ },+ status=400+ )+diff --git a/src/hi/apps/entity/entity_manager.py b/src/hi/apps/entity/entity_manager.pyindex 9ce68582..f96e88de 100644--- a/src/hi/apps/entity/entity_manager.py+++ b/src/hi/apps/entity/entity_manager.py@@ -15,6 +15,7 @@ from hi.apps.location.models import Location, LocationViewfrom .entity_pairing_manager import EntityPairingManagerfrom .enums import (EntityGroupType,+ EntityTransitionType,)from .models import (Entity,@@ -26,8 +27,7 @@ from .models import (EntityView,)from .transient_models import (- EntityDetailsData,- EntityEditData,+ EntityEditModeData,EntityViewGroup,EntityViewItem,)@@ -60,10 +60,10 @@ class EntityManager(Singleton):continuereturn- def get_entity_details_data( self,- entity : Entity,- location_view : LocationView,- is_editing : bool ) -> EntityDetailsData:+ def get_entity_edit_mode_data( self,+ entity : Entity,+ location_view : LocationView,+ is_editing : bool ) -> EntityEditModeData:entity_position_form = Noneif is_editing and location_view:@@ -79,9 +79,8 @@ class EntityManager(Singleton):entity_pairing_list = EntityPairingManager().get_entity_pairing_list( entity = entity )- entity_edit_data = EntityEditData( entity = entity )- return EntityDetailsData(- entity_edit_data = entity_edit_data,+ return EntityEditModeData(+ entity = entity,entity_position_form = entity_position_form,entity_pairing_list = entity_pairing_list,)@@ -249,16 +248,17 @@ class EntityManager(Singleton):)return entity_path- def handle_entity_type_transition( self,- entity : Entity,- location_view : LocationView = None ) -> Tuple[bool, str]:+ def handle_entity_type_transition(+ self,+ entity : Entity,+ location_view : LocationView = None ) -> Tuple[bool, EntityTransitionType]:"""Handle transitions between EntityType icon and path representations.Returns (transition_occurred, transition_type)"""if not location_view:# If no location view provided, we can't handle position/path transitions- return False, "no_location_view"+ return False, EntityTransitionType.NO_LOCATION_VIEW# Use EntityType structural methods instead of SvgItemFactoryentity_type = entity.entity_type@@ -329,10 +329,10 @@ class EntityManager(Singleton):entity = entity,location_view = location_view,)- return True, "created_position"+ return True, EntityTransitionType.CREATED_POSITIONelse:# Position already exists, just a visual update- return True, "icon_to_icon"+ return True, EntityTransitionType.ICON_TO_ICONelif needs_path:# Entity type needs path representation@@ -352,18 +352,18 @@ class EntityManager(Singleton):location_view = location_view,is_path_closed = entity_type.requires_closed_path(),)- return True, "created_path"+ return True, EntityTransitionType.CREATED_PATHelse:# Path already exists, just a visual update- return True, "path_to_path"+ return True, EntityTransitionType.PATH_TO_PATH- return False, "no_transition_needed"+ return False, EntityTransitionType.NO_TRANSITION_NEEDEDdef _transition_icon_to_path( self,entity : Entity,location_view : LocationView,entity_position : EntityPosition,- is_path_closed : bool ) -> Tuple[bool, str]:+ is_path_closed : bool ) -> Tuple[bool, EntityTransitionType]:"""Create or update EntityPath based on EntityPosition location, preserving both"""# Get center point of the icon for path placement@@ -392,12 +392,12 @@ class EntityManager(Singleton):# EntityPath already exists - preserve existing geometrypass # Keep existing path geometry- return True, "icon_to_path"+ return True, EntityTransitionType.ICON_TO_PATHdef _transition_path_to_icon( self,entity : Entity,location_view : LocationView,- entity_path : EntityPath ) -> Tuple[bool, str]:+ entity_path : EntityPath ) -> Tuple[bool, EntityTransitionType]:"""Create or update EntityPosition based on EntityPath center, preserving both"""# Calculate geometric center of the path@@ -425,7 +425,7 @@ class EntityManager(Singleton):# EntityPosition already exists - preserve existing positionpass # Keep existing position- return True, "path_to_icon"+ return True, EntityTransitionType.PATH_TO_ICONdef _calculate_path_center( self, svg_path : str ) -> Tuple[float, float]:"""Calculate the geometric center of an SVG path"""diff --git a/src/hi/apps/entity/entity_pairing_manager.py b/src/hi/apps/entity/entity_pairing_manager.pyindex 1aba6ccf..0316a523 100644--- a/src/hi/apps/entity/entity_pairing_manager.py+++ b/src/hi/apps/entity/entity_pairing_manager.py@@ -226,12 +226,13 @@ class EntityPairingManager(Singleton):continuecontinue- for to_delete_entity in to_delete_entity_ids:+ for to_delete_entity_id in to_delete_entity_ids:+ to_delete_entity = models.Entity.objects.get(id=to_delete_entity_id)if entity_has_states:principle_entity = entity- delegate_entity = to_add_entity+ delegate_entity = to_delete_entityelse:- principle_entity = to_add_entity+ principle_entity = to_delete_entitydelegate_entity = entitydelegation_queryset = delegate_entity.entity_state_delegations.select_related(diff --git a/src/hi/apps/entity/entity_type_transition_handler.py b/src/hi/apps/entity/entity_type_transition_handler.pynew file mode 100644index 00000000..515ac6b6--- /dev/null+++ b/src/hi/apps/entity/entity_type_transition_handler.py@@ -0,0 +1,129 @@+"""+EntityTypeTransitionHandler - Handles entity type transitions and form saving logic.++This class encapsulates the complex entity type transition logic that was previously+embedded in EntityPropertiesEditView, following the "keep views simple" design philosophy.+"""+import logging+from typing import Optional, TYPE_CHECKING+from django.db import transaction+from django.http import HttpRequest, HttpResponse++import hi.apps.common.antinode as antinode+from hi.apps.location.location_manager import LocationManager+from .entity_manager import EntityManager+from .enums import EntityTransitionType+from .models import Entity+from .forms import EntityForm, EntityAttributeRegularFormSet++if TYPE_CHECKING:+ from hi.apps.location.models import LocationView++logger = logging.getLogger(__name__)+++class EntityTypeTransitionHandler:+ """+ Handles entity type change detection, transitions, and form saving logic.++ This class encapsulates business logic for:+ - Detecting entity type changes+ - Handling entity type transitions with proper refresh logic+ - Determining when full page refresh is needed vs sidebar refresh+ - Managing form saving with transition detection+ """++ def handle_entity_form_save( self,+ request : HttpRequest,+ entity : Entity,+ entity_form : EntityForm,+ entity_attribute_formset : Optional[EntityAttributeRegularFormSet] = None,+ original_entity_type_str : Optional[str] = None ) -> Optional[HttpResponse]:+ """Handle saving entity form and optional formset with transition logic.++ Args:+ request: HTTP request object+ entity: Entity instance+ entity_form: EntityForm instance+ entity_attribute_formset: Optional EntityAttributeFormSet instance+ original_entity_type_str: Original entity type string for change detection++ Returns:+ Response object if transition requires special handling, None otherwise+ """+ if original_entity_type_str is None:+ original_entity_type_str = entity.entity_type_str++ transition_response: Optional[HttpResponse] = 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: bool = 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 handle_entity_type_change( self,+ request : HttpRequest,+ entity : Entity ) -> Optional[HttpResponse]:+ """Handle EntityType changes with appropriate transition logic.++ Args:+ request: HTTP request object+ entity: Entity instance with changed type++ Returns:+ Response object if full page refresh needed, None for sidebar refresh+ """+ try:+ # Always attempt advanced transition handling regardless of mode/view+ current_location_view: Optional['LocationView'] = LocationManager().get_default_location_view(request=request)+ transition_occurred: bool+ transition_type: EntityTransitionType+ transition_occurred, transition_type = EntityManager().handle_entity_type_transition(+ 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 : bool,+ transition_type : EntityTransitionType ) -> bool:+ """Determine if EntityType change requires full page refresh.++ Args:+ transition_occurred: Boolean indicating if transition succeeded+ transition_type: EntityTransitionType indicating type of transition++ Returns:+ bool: True if full page refresh needed, False for sidebar refresh only+ """+ if not transition_occurred:+ # Transition failed, use page refresh for safety+ return True++ if transition_type == EntityTransitionType.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+diff --git a/src/hi/apps/entity/enums.py b/src/hi/apps/entity/enums.pyindex e4c1b786..4c5eb2b9 100644--- a/src/hi/apps/entity/enums.py+++ b/src/hi/apps/entity/enums.py@@ -268,6 +268,22 @@ class VideoStreamType(LabeledEnum):return cls.OTHER+class EntityTransitionType(LabeledEnum):+ """Types of entity type transitions that can occur during entity type changes."""++ # Successful transition types+ ICON_TO_ICON = ('Icon to Icon', 'Transition between two icon-based entity types')+ ICON_TO_PATH = ('Icon to Path', 'Transition from icon-based to path-based entity type')+ PATH_TO_ICON = ('Path to Icon', 'Transition from path-based to icon-based entity type')+ PATH_TO_PATH = ('Path to Path', 'Transition between two path-based entity types')+ CREATED_POSITION = ('Created Position', 'Created new entity position for entity without existing representation')+ CREATED_PATH = ('Created Path', 'Created new entity path for entity without existing representation')++ # Error/edge case types+ NO_LOCATION_VIEW = ('No Location View', 'No location view provided for transition')+ NO_TRANSITION_NEEDED = ('No Transition Needed', 'Entity type change did not require visual transition')++class EntityGroupType(LabeledEnum):APPLIANCES = ( 'Appliances', '', {diff --git a/src/hi/apps/entity/forms.py b/src/hi/apps/entity/forms.pyindex 51bfa6fb..1cfa7992 100644--- a/src/hi/apps/entity/forms.py+++ b/src/hi/apps/entity/forms.py@@ -1,6 +1,7 @@from django import formsfrom hi.apps.attribute.forms import AttributeForm, AttributeUploadForm+from hi.apps.attribute.enums import AttributeValueTypefrom hi.apps.entity.enums import EntityTypefrom hi.apps.entity.models import Entity, EntityAttribute@@ -39,6 +40,27 @@ EntityAttributeFormSet = forms.inlineformset_factory()+class RegularAttributeBaseFormSet(forms.BaseInlineFormSet):+ """Base formset that automatically excludes FILE attributes for regular attribute editing"""++ def get_queryset(self):+ """Override to automatically filter out FILE attributes"""+ queryset = super().get_queryset()+ return queryset.exclude(value_type_str=str(AttributeValueType.FILE))+++EntityAttributeRegularFormSet = forms.inlineformset_factory(+ Entity,+ EntityAttribute,+ form = EntityAttributeForm,+ formset = RegularAttributeBaseFormSet,+ extra = 1,+ max_num = 100,+ absolute_max = 100,+ can_delete = True,+)++class EntityAttributeUploadForm( AttributeUploadForm ):class Meta( AttributeUploadForm.Meta ):model = EntityAttributediff --git a/src/hi/apps/entity/templates/entity/edit/panes/entity_edit.html b/src/hi/apps/entity/templates/entity/edit/panes/entity_edit.htmldeleted file mode 100644index 0cff9ccd..00000000--- a/src/hi/apps/entity/templates/entity/edit/panes/entity_edit.html+++ /dev/null@@ -1,32 +0,0 @@-{% load icons %}-<form action="{% url 'entity_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="h5 my-2">Attributes</div>- <div>- {% include "attribute/panes/attribute_form.html" with attribute_formset=entity_attribute_formset %}- </div>-- <div class="text-center" >- <button id="hi-add-entity-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>--<div class="text-center my-3" >- <form action="{% url 'entity_attribute_upload' entity_id=entity.id %}"- method="post"- class="form" data-async="true">- {% csrf_token %}- <div>- {% include "attribute/panes/attribute_upload_form.html" with attribute_upload_form=entity_attribute_upload_form %}- </div>- </form>-</div>-diff --git a/src/hi/apps/entity/templates/entity/modals/entity_edit.html b/src/hi/apps/entity/templates/entity/modals/entity_edit.htmlindex 6a95825a..f6970017 100644--- a/src/hi/apps/entity/templates/entity/modals/entity_edit.html+++ b/src/hi/apps/entity/templates/entity/modals/entity_edit.html@@ -1,42 +1,49 @@{% extends "modals/base.html" %}-{% block modal_dialog_class %}hi-modal-dialog-600{% endblock %}+{% load icons %}-{% block title_text %}-{{ entity.name }}: Edit-{% endblock %}+{% block modal_dialog_class %}hi-modal-dialog-700{% endblock %}+{% block title_text %}{{ entity.name }}{% endblock %}{% block body %}--<div>- {% include "entity/edit/panes/entity_edit.html" %}+<form id="{{ DIVID.ATTR_V2_FORM }}"+ action="{% url 'entity_edit' entity_id=entity.id %}"+ method="post"+ class="form {{ DIVID.ATTR_V2_MODAL_CLASS }}"+ data-async="true"+ data-stay-in-modal="true"+ enctype="multipart/form-data">+ {% csrf_token %}++<!-- Main content wrapper for antinode updates -->+<div id="{{ DIVID.ATTR_V2_CONTENT }}">+ {% include "entity/panes/entity_edit_content_body.html" %}</div>+</form>-{% endblock %}--{% block footer %}--{% if entity.states.exists %}-<div class="align-self-center">- <a class="btn btn-primary"- href="{% url 'entity_status' entity_id=entity.id %}"- data-async="modal">- STATUS- </a>+<!-- File Upload Form Container (separate from main form to avoid nesting) -->+<div id="{{ DIVID.ATTR_V2_UPLOAD_FORM_CONTAINER }}">+ {% url 'entity_attribute_upload' entity_id=entity.id as file_upload_url %}+ {% include "attribute/components/upload_form.html" with file_upload_url=file_upload_url %}</div>-{% endif %}-{% if entity.states.exists %}-<div class="align-self-center">- <a class="btn btn-primary"- href="{% url 'entity_state_history' entity_id=entity.id %}"- data-async="modal">- HISTORY- </a>-</div>+<!-- Success/Error Messages -->+{% if messages %}+ <div class="{{ DIVID.ATTR_V2_MESSAGES }}" id="{{ DIVID.ATTR_V2_MESSAGES }}">+ {% for message in messages %}+ <div class="alert alert-{{ message.tags }} alert-dismissible fade show" role="alert">+ {{ message }}+ <button type="button" class="close" data-dismiss="alert" aria-label="Close">+ <span aria-hidden="true">×</span>+ </button>+ </div>+ {% endfor %}+ </div>{% endif %}-<div class="align-self-center">- <a id="hi-modal-done" role="button" {% if autofocus %}autofocus="autofocus"{% endif %}- class="btn btn-lg btn-secondary" href="#" data-dismiss="modal">DONE</a>-</div>+<!-- JavaScript for V2 functionality loaded via Django Pipeline js_before_content bundle -->++{% endblock %}++{% block footer %}+<!-- No footer - sticky panel contains all actions -->{% endblock %}diff --git a/src/hi/apps/entity/templates/entity/panes/entity_edit_content_body.html b/src/hi/apps/entity/templates/entity/panes/entity_edit_content_body.htmlnew file mode 100644index 00000000..5f92af3c--- /dev/null+++ b/src/hi/apps/entity/templates/entity/panes/entity_edit_content_body.html@@ -0,0 +1,123 @@+{% load icons %}+{% comment %}+V2 Content Body Fragment+Contains the main content area - used by both initial load and antinode updates+Includes: entity info (when provided), action bar, and scrollable content+{% endcomment %}++<!-- Sticky Panel: Entity Info + Action Bar (always visible) -->+<div class="attr-v2-sticky-panel">+ <!-- Basic Entity Information (minimal) - only if entity_form provided -->+ {% if entity_form %}+ <div class="attr-v2-entity-info">+ {% block basic_info %}+ <div class="attr-v2-basic-info">+ <div class="row">+ <div class="col-md-8">+ <div class="form-group mb-0">+ <small class="text-muted">Name</small>+ <input type="text"+ id="{{ entity_form.name.id_for_label }}"+ name="{{ entity_form.name.html_name }}"+ value="{{ entity_form.name.value|default:'' }}"+ class="form-control form-control-sm"+ {% if entity_form.name.field.required %}required{% endif %}>+ {% if entity_form.name.errors %}+ <div class="invalid-feedback d-block">+ {{ entity_form.name.errors }}+ </div>+ {% endif %}+ </div>+ </div>+ <div class="col-md-4">+ <div class="form-group mb-0">+ <small class="text-muted">Type</small>+ <select id="{{ entity_form.entity_type_str.id_for_label }}"+ name="{{ entity_form.entity_type_str.html_name }}"+ class="form-control form-control-sm">+ {% for value, label in entity_form.entity_type_str.field.choices %}+ <option value="{{ value }}"+ {% if value == entity_form.entity_type_str.value %}selected{% endif %}>+ {{ label }}+ </option>+ {% endfor %}+ </select>+ {% if entity_form.entity_type_str.errors %}+ <div class="invalid-feedback d-block">+ {{ entity_form.entity_type_str.errors }}+ </div>+ {% endif %}+ </div>+ </div>+ </div>+ </div>+ {% endblock %}+ </div>+ {% endif %}++ <!-- Action Bar -->+ <div class="attr-v2-action-bar">+ <div class="attr-v2-action-bar-content">+ <div>+ <button id="{{ DIVID.ATTR_V2_UPDATE_BTN }}"+ type="submit"+ class="btn btn-primary"+ name="action"+ value="update">+ {% icon "save" size="sm" css_class="hi-icon-left" %}UPDATE+ </button>+ <span id="{{ DIVID.ATTR_V2_DIRTY_MESSAGE }}" class="attr-v2-dirty-message ml-3"></span>+ <span id="{{ DIVID.ATTR_V2_STATUS_MSG }}" class="attr-v2-status-message ml-2">+ {% if success_message %}+ <span class="text-success">{{ success_message }}</span>+ {% elif error_message %}+ <span class="text-danger">{{ error_message }}</span>+ {% if non_field_errors %}+ {% for error in non_field_errors %}+ <br><small class="text-danger">{{ error }}</small>+ {% endfor %}+ {% endif %}+ {% endif %}+ </span>+ </div>++ <div class="attr-v2-action-buttons">+ {% block additional_actions %}+ {% endblock %}+ <label for="{{ DIVID.ATTR_V2_FILE_INPUT }}"+ class="btn btn-sm btn-outline-primary mb-0">+ {% icon "upload" size="sm" css_class="hi-icon-left" %}Add File+ </label>++ <button id="{{ DIVID.ATTR_V2_ADD_ATTRIBUTE_BTN }}"+ type="button"+ class="btn btn-sm btn-outline-primary"+ onclick="showAddAttribute();">+ {% icon "plus" size="sm" css_class="hi-icon-left" %}Add Info+ </button>+ </div>+ </div>+ </div>+</div>++<!-- Scrollable Content Area (below sticky panel) -->+<div id="{{ DIVID.ATTR_V2_SCROLLABLE_CONTENT }}" class="attr-v2-scrollable-content">++ <!-- Files Section -->+ {% block files_section %}+ {% include "attribute/components/file_grid.html" with file_attributes=file_attributes %}+ {% endblock %}++ <!-- Properties Section -->+ {% block properties_section %}+ {% if regular_attributes_formset %}+ {{ regular_attributes_formset.management_form }}+ {% include "attribute/components/regular_attribute_list.html" with regular_attributes_formset=regular_attributes_formset %}+ {% endif %}+ {% endblock %}++ <!-- Additional Sections -->+ {% block additional_sections %}+ {% endblock %}++</div>diff --git a/src/hi/apps/entity/templates/entity/panes/entity_status_title.html b/src/hi/apps/entity/templates/entity/panes/entity_status_title.htmlindex ac89d5e6..c5e10634 100644--- a/src/hi/apps/entity/templates/entity/panes/entity_status_title.html+++ b/src/hi/apps/entity/templates/entity/panes/entity_status_title.html@@ -5,7 +5,7 @@</div><div>{% if request.view_parameters.is_editing %}- <a href="{% url 'entity_details' entity_id=entity.id %}"+ <a href="{% url 'entity_edit_mode' entity_id=entity.id %}"data-async="true">{{ entity.name }}</a>diff --git a/src/hi/apps/entity/tests/synthetic_data.py b/src/hi/apps/entity/tests/synthetic_data.pynew file mode 100644index 00000000..68c466dd--- /dev/null+++ b/src/hi/apps/entity/tests/synthetic_data.py@@ -0,0 +1,226 @@+"""+Synthetic data generators for Entity and EntityAttribute testing.++Provides centralized, reusable test data creation following the project's+synthetic data pattern documented in test-data-management.md.+"""+import uuid+from django.core.files.uploadedfile import SimpleUploadedFile+from typing import Optional, Dict, Any, List++from hi.apps.attribute.enums import AttributeType, AttributeValueType+from hi.apps.entity.models import Entity, EntityAttribute+from hi.apps.entity.enums import EntityType+from hi.apps.entity.entity_edit_form_handler import EntityEditFormHandler+from hi.apps.location.models import Location+++class EntityAttributeSyntheticData:+ """Centralized synthetic data generators for entity attribute testing."""++ @staticmethod+ def create_test_location(**kwargs) -> Location:+ """Create a test location with reasonable defaults."""+ defaults = {+ 'name': 'Test Location',+ 'svg_fragment_filename': 'test-location.svg',+ 'svg_view_box_str': '0 0 800 600'+ }+ defaults.update(kwargs)+ return Location.objects.create(**defaults)++ @staticmethod+ def create_test_entity(**kwargs) -> Entity:+ """Create a test entity with reasonable defaults."""+ # Generate unique integration_id to avoid constraint violations+ unique_id = str(uuid.uuid4())[:8]+ defaults = {+ 'name': 'Test Entity',+ 'integration_id': f'test.entity.{unique_id}',+ 'integration_name': 'test_integration',+ 'entity_type_str': str(EntityType.LIGHT),+ }+ defaults.update(kwargs)+ return Entity.objects.create(**defaults)++ @staticmethod+ def create_test_text_attribute(entity: Optional[Entity] = None, **kwargs) -> EntityAttribute:+ """Create a text attribute with reasonable defaults."""+ if entity is None:+ entity = EntityAttributeSyntheticData.create_test_entity()++ defaults = {+ 'entity': entity,+ 'name': 'test_property',+ 'value': 'test value',+ 'attribute_type_str': str(AttributeType.CUSTOM),+ 'value_type_str': str(AttributeValueType.TEXT),+ }+ defaults.update(kwargs)+ return EntityAttribute.objects.create(**defaults)++ @staticmethod+ def create_test_file_attribute(entity: Optional[Entity] = None, **kwargs) -> EntityAttribute:+ """Create a file attribute with reasonable defaults."""+ if entity is None:+ entity = EntityAttributeSyntheticData.create_test_entity()++ # Create test file if not provided+ if 'file_value' not in kwargs:+ test_file = SimpleUploadedFile(+ "test_document.txt",+ b"test file content for synthetic data",+ content_type="text/plain"+ )+ kwargs['file_value'] = test_file++ defaults = {+ 'entity': entity,+ 'name': 'test_document',+ 'value': 'Test Document Title',+ 'attribute_type_str': str(AttributeType.CUSTOM),+ 'value_type_str': str(AttributeValueType.FILE),+ }+ defaults.update(kwargs)+ return EntityAttribute.objects.create(**defaults)++ @staticmethod+ def create_test_secret_attribute(entity: Optional[Entity] = None, **kwargs) -> EntityAttribute:+ """Create a secret attribute with reasonable defaults."""+ if entity is None:+ entity = EntityAttributeSyntheticData.create_test_entity()++ defaults = {+ 'entity': entity,+ 'name': 'api_key',+ 'value': 'secret_api_key_12345',+ 'attribute_type_str': str(AttributeType.CUSTOM),+ 'value_type_str': str(AttributeValueType.SECRET),+ }+ defaults.update(kwargs)+ return EntityAttribute.objects.create(**defaults)++ @staticmethod+ def create_entity_with_mixed_attributes(**entity_kwargs) -> Entity:+ """Create an entity with a variety of attribute types for comprehensive testing."""+ entity = EntityAttributeSyntheticData.create_test_entity(**entity_kwargs)++ # Create various attribute types+ EntityAttributeSyntheticData.create_test_text_attribute(+ entity=entity, name='description', value='Test entity for mixed testing'+ )+ EntityAttributeSyntheticData.create_test_secret_attribute(+ entity=entity, name='password', value='super_secret_password'+ )+ EntityAttributeSyntheticData.create_test_file_attribute(+ entity=entity, name='manual', value='Device Manual'+ )++ return entity++ @staticmethod+ def create_test_image_file() -> SimpleUploadedFile:+ """Create a test image file for file upload testing."""+ return SimpleUploadedFile(+ "test_image.jpg",+ b"fake jpeg image content for testing",+ content_type="image/jpeg"+ )++ @staticmethod+ def create_test_pdf_file() -> SimpleUploadedFile:+ """Create a test PDF file for file upload testing."""+ return SimpleUploadedFile(+ "test_document.pdf",+ b"fake pdf content for testing",+ content_type="application/pdf"+ )++ @staticmethod+ def create_large_text_file() -> SimpleUploadedFile:+ """Create a large text file for file size testing."""+ large_content = "Large file content line.\n" * 1000+ return SimpleUploadedFile(+ "large_file.txt",+ large_content.encode(),+ content_type="text/plain"+ )++ @staticmethod+ def create_form_data_for_entity_edit(entity: Entity, **overrides) -> Dict[str, Any]:+ """Create complete form data dictionary for entity editing form submissions.++ Includes both entity form data and formset data for regular attributes.+ """+ # Entity form data+ form_data = {+ 'name': entity.name,+ 'entity_type_str': entity.entity_type_str,+ }+ form_data.update(overrides)++ # Add formset data for regular attributes (non-file attributes)+ regular_attributes = list(entity.attributes.exclude(+ value_type_str=str(AttributeValueType.FILE)+ ).order_by('id'))++ # Use EntityEditFormHandler as the single source of truth for prefix logic+ prefix = EntityEditFormHandler.get_formset_prefix(entity)++ # Formset management form data+ formset_data = {+ f'{prefix}-TOTAL_FORMS': str(len(regular_attributes) + 1), # +1 for empty form+ f'{prefix}-INITIAL_FORMS': str(len(regular_attributes)),+ f'{prefix}-MIN_NUM_FORMS': '0',+ f'{prefix}-MAX_NUM_FORMS': '1000',+ }++ # Individual attribute form data+ for i, attr in enumerate(regular_attributes):+ formset_data.update({+ f'{prefix}-{i}-id': str(attr.id),+ f'{prefix}-{i}-name': attr.name,+ f'{prefix}-{i}-value': attr.value,+ f'{prefix}-{i}-attribute_type_str': attr.attribute_type_str,+ })++ form_data.update(formset_data)+ return form_data++ @staticmethod+ def create_formset_data_for_attributes(attributes: List[EntityAttribute], entity: Entity) -> Dict[str, Any]:+ """Create formset data dictionary for attribute formset submissions."""+ prefix = EntityEditFormHandler.get_formset_prefix(entity)+ data = {+ f'{prefix}-TOTAL_FORMS': str(len(attributes) + 1), # +1 for empty form+ f'{prefix}-INITIAL_FORMS': str(len(attributes)),+ f'{prefix}-MIN_NUM_FORMS': '0',+ f'{prefix}-MAX_NUM_FORMS': '1000',+ }++ for i, attr in enumerate(attributes):+ data.update({+ f'{prefix}-{i}-id': str(attr.id),+ f'{prefix}-{i}-name': attr.name,+ f'{prefix}-{i}-value': attr.value,+ f'{prefix}-{i}-attribute_type_str': attr.attribute_type_str,+ })++ return data++ @staticmethod+ def create_file_title_update_data(entity: Entity, file_attributes: List[EntityAttribute]) -> Dict[str, str]:+ """Create POST data for file title updates."""+ data = {}+ for attr in file_attributes:+ field_name = f'file_title_{entity.id}_{attr.id}'+ data[field_name] = f'Updated {attr.name}'+ return data++ @staticmethod+ def create_file_deletion_data(file_attributes: List[EntityAttribute]) -> Dict[str, List[str]]:+ """Create POST data for file deletions."""+ return {+ 'delete_file_attribute': [str(attr.id) for attr in file_attributes]+ }+diff --git a/src/hi/apps/entity/tests/test_attribute_history.py b/src/hi/apps/entity/tests/test_attribute_history.pyindex f4ad764d..1cde05a2 100644--- a/src/hi/apps/entity/tests/test_attribute_history.py+++ b/src/hi/apps/entity/tests/test_attribute_history.py@@ -1,6 +1,8 @@import loggingfrom hi.apps.entity.models import Entity, EntityAttribute, EntityAttributeHistory+from hi.apps.entity.enums import EntityType+from hi.apps.attribute.enums import AttributeType, AttributeValueTypefrom hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)@@ -14,7 +16,7 @@ class EntityAttributeHistoryTestCase(BaseTestCase):# Create entity and attributeentity = Entity.objects.create(name='Test Entity',- entity_type_str='GENERAL',+ entity_type_str=str(EntityType.OTHER),integration_id='test.entity',integration_name='test_integration')@@ -23,8 +25,8 @@ class EntityAttributeHistoryTestCase(BaseTestCase):entity=entity,name='test_attr',value='initial_value',- value_type_str='TEXT',- attribute_type_str='CUSTOM'+ value_type_str=str(AttributeValueType.TEXT),+ attribute_type_str=str(AttributeType.CUSTOM))# Verify initial history record was created@@ -49,7 +51,7 @@ class EntityAttributeHistoryTestCase(BaseTestCase):# Create entityentity = Entity.objects.create(name='Test Entity',- entity_type_str='GENERAL',+ entity_type_str=str(EntityType.OTHER),integration_id='test.entity',integration_name='test_integration')@@ -58,8 +60,8 @@ class EntityAttributeHistoryTestCase(BaseTestCase):attr = EntityAttribute.objects.create(entity=entity,name='test_file_attr',- value_type_str='FILE',- attribute_type_str='CUSTOM'+ value_type_str=str(AttributeValueType.FILE),+ attribute_type_str=str(AttributeType.CUSTOM))# Verify no history records were created for file attribute@@ -72,7 +74,7 @@ class EntityAttributeHistoryTestCase(BaseTestCase):# Create entity and attribute with history tracking disabledentity = Entity.objects.create(name='Test Entity',- entity_type_str='GENERAL',+ entity_type_str=str(EntityType.OTHER),integration_id='test.entity',integration_name='test_integration')@@ -81,8 +83,8 @@ class EntityAttributeHistoryTestCase(BaseTestCase):entity=entity,name='test_attr',value='initial_value',- value_type_str='TEXT',- attribute_type_str='CUSTOM'+ value_type_str=str(AttributeValueType.TEXT),+ attribute_type_str=str(AttributeType.CUSTOM))attr.save(track_history=False) # Disable history tracking@@ -96,15 +98,15 @@ class EntityAttributeHistoryTestCase(BaseTestCase):# Test EntityAttribute mappingentity = Entity.objects.create(name='Test Entity',- entity_type_str='GENERAL',+ entity_type_str=str(EntityType.OTHER),integration_id='test.entity',integration_name='test_integration')entity_attr = EntityAttribute(entity=entity,name='entity_attr',- value_type_str='TEXT',- attribute_type_str='CUSTOM'+ value_type_str=str(AttributeValueType.TEXT),+ attribute_type_str=str(AttributeType.CUSTOM))self.assertEqual(entity_attr._get_history_model_class(), EntityAttributeHistory)return@@ -114,7 +116,7 @@ class EntityAttributeHistoryTestCase(BaseTestCase):# Create entity and attribute with historyentity = Entity.objects.create(name='Test Entity',- entity_type_str='GENERAL',+ entity_type_str=str(EntityType.OTHER),integration_id='test.entity',integration_name='test_integration')@@ -123,8 +125,8 @@ class EntityAttributeHistoryTestCase(BaseTestCase):entity=entity,name='test_attr',value='test_value',- value_type_str='TEXT',- attribute_type_str='CUSTOM'+ value_type_str=str(AttributeValueType.TEXT),+ attribute_type_str=str(AttributeType.CUSTOM))# Update to create multiple history records@@ -148,7 +150,7 @@ class EntityAttributeHistoryTestCase(BaseTestCase):# Create entity and attributeentity = Entity.objects.create(name='Test Entity',- entity_type_str='GENERAL',+ entity_type_str=str(EntityType.OTHER),integration_id='test.entity',integration_name='test_integration')@@ -157,8 +159,8 @@ class EntityAttributeHistoryTestCase(BaseTestCase):entity=entity,name='sequential_test',value='value_1',- value_type_str='TEXT',- attribute_type_str='CUSTOM'+ value_type_str=str(AttributeValueType.TEXT),+ attribute_type_str=str(AttributeType.CUSTOM))# Perform multiple updates@@ -181,7 +183,7 @@ class EntityAttributeHistoryTestCase(BaseTestCase):# Create entity and boolean attributeentity = Entity.objects.create(name='Test Entity',- entity_type_str='GENERAL',+ entity_type_str=str(EntityType.OTHER),integration_id='test.entity',integration_name='test_integration')@@ -190,8 +192,8 @@ class EntityAttributeHistoryTestCase(BaseTestCase):entity=entity,name='boolean_test',value='True',- value_type_str='BOOLEAN',- attribute_type_str='CUSTOM'+ value_type_str=str(AttributeValueType.BOOLEAN),+ attribute_type_str=str(AttributeType.CUSTOM))# Update boolean valuediff --git a/src/hi/apps/entity/tests/test_entity_edit_form_handler.py b/src/hi/apps/entity/tests/test_entity_edit_form_handler.pynew file mode 100644index 00000000..71550524--- /dev/null+++ b/src/hi/apps/entity/tests/test_entity_edit_form_handler.py@@ -0,0 +1,654 @@+"""+Unit tests for EntityEditFormHandler.++Tests the complex form handling business logic including form creation,+validation, file processing, and error collection.+"""+import logging+from unittest.mock import patch+from django.http import QueryDict+from django.test import RequestFactory++from hi.apps.attribute.enums import AttributeType, AttributeValueType+from hi.apps.entity.entity_edit_form_handler import EntityEditFormHandler+from hi.apps.entity.enums import EntityType+from hi.apps.entity.forms import EntityForm, EntityAttributeRegularFormSet+from hi.apps.entity.models import EntityAttribute+from django.urls import reverse+from hi.testing.base_test_case import BaseTestCase+from .synthetic_data import EntityAttributeSyntheticData++logging.disable(logging.CRITICAL)+++class TestEntityEditFormHandlerFormCreation(BaseTestCase):+ """Test form creation and initialization logic."""++ def setUp(self):+ super().setUp()+ self.handler = EntityEditFormHandler()+ self.entity = EntityAttributeSyntheticData.create_test_entity(name='Test Entity')++ def test_create_entity_forms_unbound(self):+ """Test creating unbound forms for initial rendering."""+ entity_form, file_attributes, regular_attributes_formset = self.handler.create_entity_forms(self.entity)++ # Verify form types and initialization+ self.assertIsInstance(entity_form, EntityForm)+ self.assertEqual(entity_form.instance, self.entity)+ self.assertFalse(entity_form.is_bound)++ # Verify formset initialization+ self.assertIsInstance(regular_attributes_formset, EntityAttributeRegularFormSet)+ self.assertEqual(regular_attributes_formset.instance, self.entity)+ self.assertFalse(regular_attributes_formset.is_bound)++ # File attributes should be a QuerySet+ self.assertEqual(list(file_attributes), []) # No file attributes yet++ def test_create_entity_forms_bound_with_data(self):+ """Test creating bound forms with POST data."""+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(+ self.entity, name='Updated Name'+ )++ entity_form, file_attributes, regular_attributes_formset = self.handler.create_entity_forms(+ self.entity, form_data+ )++ # Verify bound forms+ self.assertTrue(entity_form.is_bound)+ self.assertTrue(regular_attributes_formset.is_bound)+ self.assertEqual(entity_form.data['name'], 'Updated Name')++ def test_create_entity_forms_filters_file_attributes_correctly(self):+ """Test that file attributes are correctly separated from regular attributes."""+ # Create mixed attributes+ EntityAttributeSyntheticData.create_test_text_attribute(+ entity=self.entity, name='description'+ )+ file_attr = EntityAttributeSyntheticData.create_test_file_attribute(+ entity=self.entity, name='manual'+ )++ entity_form, file_attributes, regular_attributes_formset = self.handler.create_entity_forms(self.entity)++ # Verify file attributes separation+ file_attr_list = list(file_attributes)+ self.assertEqual(len(file_attr_list), 1)+ self.assertEqual(file_attr_list[0], file_attr)++ # Verify formset only includes non-file attributes+ # Note: The actual filtering happens in the formset queryset+ self.assertIsNotNone(regular_attributes_formset)++ def test_create_entity_forms_with_formset_prefix(self):+ """Test that formset uses correct prefix based on entity ID."""+ entity_form, file_attributes, regular_attributes_formset = self.handler.create_entity_forms(self.entity)++ # Verify prefix includes entity ID+ expected_prefix = EntityEditFormHandler.get_formset_prefix(self.entity)+ self.assertEqual(regular_attributes_formset.prefix, expected_prefix)+++class TestEntityEditFormHandlerValidation(BaseTestCase):+ """Test form validation logic."""++ def setUp(self):+ super().setUp()+ self.handler = EntityEditFormHandler()+ self.entity = EntityAttributeSyntheticData.create_test_entity()++ def test_validate_forms_both_valid(self):+ """Test validation when both forms are valid."""+ # Create valid form data+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(+ self.entity, name='Valid Name'+ )++ entity_form, _, regular_attributes_formset = self.handler.create_entity_forms(+ self.entity, form_data+ )++ result = self.handler.validate_forms(entity_form, regular_attributes_formset)+ self.assertTrue(result)++ def test_validate_forms_entity_form_invalid(self):+ """Test validation when entity form is invalid."""+ # Create invalid form data (empty name)+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(+ self.entity, name='' # Invalid: required field+ )++ entity_form, _, regular_attributes_formset = self.handler.create_entity_forms(+ self.entity, form_data+ )++ result = self.handler.validate_forms(entity_form, regular_attributes_formset)+ self.assertFalse(result)+ self.assertFalse(entity_form.is_valid())++ def test_validate_forms_formset_invalid(self):+ """Test validation when formset is invalid."""+ # Create attribute for formset testing+ attr = EntityAttributeSyntheticData.create_test_text_attribute(entity=self.entity)++ # Create valid entity data but invalid formset data+ entity_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(self.entity)+ formset_data = EntityAttributeSyntheticData.create_formset_data_for_attributes([attr], self.entity)+ prefix = EntityEditFormHandler.get_formset_prefix(self.entity)+ formset_data[f'{prefix}-0-name'] = '' # Invalid: empty name++ form_data = {**entity_data, **formset_data}++ entity_form, _, regular_attributes_formset = self.handler.create_entity_forms(+ self.entity, form_data+ )++ result = self.handler.validate_forms(entity_form, regular_attributes_formset)+ self.assertFalse(result)++ def test_validate_forms_both_invalid(self):+ """Test validation when both forms are invalid."""+ prefix = EntityEditFormHandler.get_formset_prefix(self.entity)+ form_data = {+ 'name': '', # Invalid entity name+ f'{prefix}-TOTAL_FORMS': '1',+ f'{prefix}-INITIAL_FORMS': '0',+ f'{prefix}-0-name': '', # Invalid attribute name+ }++ entity_form, _, regular_attributes_formset = self.handler.create_entity_forms(+ self.entity, form_data+ )++ result = self.handler.validate_forms(entity_form, regular_attributes_formset)+ self.assertFalse(result)+++class TestEntityEditFormHandlerSaveOperations(BaseTestCase):+ """Test form saving and file processing operations."""++ def setUp(self):+ super().setUp()+ self.handler = EntityEditFormHandler()+ self.entity = EntityAttributeSyntheticData.create_test_entity()+ self.factory = RequestFactory()++ def test_save_forms_basic_success(self):+ """Test successful form saving with transaction."""+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(+ self.entity, name='Updated Entity Name'+ )++ entity_form, _, regular_attributes_formset = self.handler.create_entity_forms(+ self.entity, form_data+ )++ # Create real request+ request = self.factory.post('/fake-url/', {})++ # Save forms+ self.handler.save_forms(entity_form, regular_attributes_formset, request, self.entity)++ # Verify entity was updated+ self.entity.refresh_from_db()+ self.assertEqual(self.entity.name, 'Updated Entity Name')++ def test_save_forms_uses_transaction(self):+ """Test that save_forms uses database transaction with rollback behavior."""+ # Create a text attribute to modify+ attr = EntityAttributeSyntheticData.create_test_text_attribute(+ entity=self.entity, name='test_attr', value='original_value'+ )++ # Create form data that will modify both entity and attribute+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(+ self.entity, name='Updated Entity Name'+ )++ # Update the attribute value in the formset data+ prefix = EntityEditFormHandler.get_formset_prefix(self.entity)+ form_data[f'{prefix}-0-id'] = str(attr.id)+ form_data[f'{prefix}-0-name'] = attr.name+ form_data[f'{prefix}-0-value'] = 'updated_value'+ form_data[f'{prefix}-0-attribute_type_str'] = attr.attribute_type_str++ # Use real entity_edit URL to ensure proper transaction handling+ url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})+ response = self.client.post(url, form_data)++ # Should succeed with proper transaction+ self.assertEqual(response.status_code, 200)++ # Verify both entity and attribute were updated (transactional success)+ self.entity.refresh_from_db()+ attr.refresh_from_db()+ self.assertEqual(self.entity.name, 'Updated Entity Name')+ self.assertEqual(attr.value, 'updated_value')++ def test_save_forms_processes_file_operations(self):+ """Test that save_forms calls file processing methods."""+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(self.entity)+ entity_form, _, regular_attributes_formset = self.handler.create_entity_forms(+ self.entity, form_data+ )++ # Create real request+ request = self.factory.post('/fake-url/', {})++ # Mock the file processing methods+ with patch.object(self.handler, 'process_file_deletions') as mock_deletions, \+ patch.object(self.handler, 'process_file_title_updates') as mock_updates:++ self.handler.save_forms(entity_form, regular_attributes_formset, request, self.entity)++ mock_deletions.assert_called_once_with(request, self.entity)+ mock_updates.assert_called_once_with(request, self.entity)+++class TestEntityEditFormHandlerFileDeletions(BaseTestCase):+ """Test file deletion processing logic."""++ def setUp(self):+ super().setUp()+ self.handler = EntityEditFormHandler()+ self.entity = EntityAttributeSyntheticData.create_test_entity()+ self.factory = RequestFactory()++ def test_process_file_deletions_single_file(self):+ """Test deleting a single file attribute."""+ file_attr = EntityAttributeSyntheticData.create_test_file_attribute(entity=self.entity)++ # Create real request with POST data+ post_data = QueryDict(mutable=True)+ post_data.setlist('delete_file_attribute', [str(file_attr.id)])+ request = self.factory.post('/fake-url/', post_data)++ # Verify file exists before deletion+ self.assertTrue(EntityAttribute.objects.filter(id=file_attr.id).exists())++ # Process deletion+ self.handler.process_file_deletions(request, self.entity)++ # Verify file was deleted+ self.assertFalse(EntityAttribute.objects.filter(id=file_attr.id).exists())++ def test_process_file_deletions_multiple_files(self):+ """Test deleting multiple file attributes."""+ file_attr1 = EntityAttributeSyntheticData.create_test_file_attribute(entity=self.entity, name='file1')+ file_attr2 = EntityAttributeSyntheticData.create_test_file_attribute(entity=self.entity, name='file2')++ # Debug: Check attributes were created with correct types+ self.assertEqual(file_attr1.value_type_str, str(AttributeValueType.FILE))+ self.assertEqual(file_attr2.value_type_str, str(AttributeValueType.FILE))+ self.assertEqual(file_attr1.attribute_type_str, str(AttributeType.CUSTOM))+ self.assertEqual(file_attr2.attribute_type_str, str(AttributeType.CUSTOM))++ # Create form data for entity edit with file deletions+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(self.entity)+ form_data['delete_file_attribute'] = [str(file_attr1.id), str(file_attr2.id)]++ # Use real entity_edit URL+ url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})+ response = self.client.post(url, form_data)++ # Verify successful response+ self.assertEqual(response.status_code, 200)++ # Verify both files were deleted+ self.assertFalse(EntityAttribute.objects.filter(id=file_attr1.id).exists())+ self.assertFalse(EntityAttribute.objects.filter(id=file_attr2.id).exists())++ def test_process_file_deletions_ignores_empty_values(self):+ """Test that empty deletion values are ignored."""+ file_attr = EntityAttributeSyntheticData.create_test_file_attribute(entity=self.entity)++ # Create form data for entity edit with empty values mixed in+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(self.entity)+ form_data['delete_file_attribute'] = ['', str(file_attr.id), '']++ # Use real entity_edit URL+ url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})+ response = self.client.post(url, form_data)++ # Verify successful response+ self.assertEqual(response.status_code, 200)++ # Only the valid ID should cause deletion+ self.assertFalse(EntityAttribute.objects.filter(id=file_attr.id).exists())++ def test_process_file_deletions_nonexistent_attribute(self):+ """Test handling of nonexistent attribute IDs."""+ # Create real request with nonexistent ID+ post_data = QueryDict(mutable=True)+ post_data.setlist('delete_file_attribute', ['99999']) # Nonexistent ID+ request = self.factory.post('/fake-url/', post_data)++ # Should not raise exception+ self.handler.process_file_deletions(request, self.entity)++ def test_process_file_deletions_wrong_entity(self):+ """Test that attributes belonging to different entities are not deleted."""+ other_entity = EntityAttributeSyntheticData.create_test_entity(name='Other Entity')+ file_attr = EntityAttributeSyntheticData.create_test_file_attribute(entity=other_entity)++ # Create real request+ post_data = QueryDict(mutable=True)+ post_data.setlist('delete_file_attribute', [str(file_attr.id)])+ request = self.factory.post('/fake-url/', post_data)++ self.handler.process_file_deletions(request, self.entity)++ # File should still exist (belongs to different entity)+ self.assertTrue(EntityAttribute.objects.filter(id=file_attr.id).exists())++ def test_process_file_deletions_non_file_attribute(self):+ """Test that non-file attributes are not deleted."""+ text_attr = EntityAttributeSyntheticData.create_test_text_attribute(entity=self.entity)++ # Create real request with text attribute ID+ post_data = QueryDict(mutable=True)+ post_data.setlist('delete_file_attribute', [str(text_attr.id)])+ request = self.factory.post('/fake-url/', post_data)++ self.handler.process_file_deletions(request, self.entity)++ # Text attribute should still exist+ self.assertTrue(EntityAttribute.objects.filter(id=text_attr.id).exists())++ def test_process_file_deletions_respects_can_delete_permission(self):+ """Test that deletion respects the can_delete permission."""+ # Create a PREDEFINED file attribute (can't be deleted)+ file_attr = EntityAttributeSyntheticData.create_test_file_attribute(+ entity=self.entity,+ attribute_type_str=str(AttributeType.PREDEFINED)+ )++ # Create real request+ post_data = QueryDict(mutable=True)+ post_data.setlist('delete_file_attribute', [str(file_attr.id)])+ request = self.factory.post('/fake-url/', post_data)++ self.handler.process_file_deletions(request, self.entity)++ # File should still exist (deletion not allowed)+ self.assertTrue(EntityAttribute.objects.filter(id=file_attr.id).exists())+++class TestEntityEditFormHandlerFileTitleUpdates(BaseTestCase):+ """Test file title update processing logic."""++ def setUp(self):+ super().setUp()+ self.handler = EntityEditFormHandler()+ self.entity = EntityAttributeSyntheticData.create_test_entity()+ self.factory = RequestFactory()++ def test_process_file_title_updates_single_file(self):+ """Test updating a single file title."""+ file_attr = EntityAttributeSyntheticData.create_test_file_attribute(+ entity=self.entity, value='Original Title'+ )++ # Create real request with POST data+ field_name = f'file_title_{self.entity.id}_{file_attr.id}'+ request = self.factory.post('/fake-url/', {field_name: 'Updated Title'})++ self.handler.process_file_title_updates(request, self.entity)++ # Verify title was updated+ file_attr.refresh_from_db()+ self.assertEqual(file_attr.value, 'Updated Title')++ def test_process_file_title_updates_multiple_files(self):+ """Test updating multiple file titles."""+ file_attr1 = EntityAttributeSyntheticData.create_test_file_attribute(+ entity=self.entity, name='file1', value='Title 1'+ )+ file_attr2 = EntityAttributeSyntheticData.create_test_file_attribute(+ entity=self.entity, name='file2', value='Title 2'+ )++ field_name1 = f'file_title_{self.entity.id}_{file_attr1.id}'+ field_name2 = f'file_title_{self.entity.id}_{file_attr2.id}'++ # Create real request with POST data+ post_data = {+ field_name1: 'New Title 1',+ field_name2: 'New Title 2',+ 'other_field': 'ignored', # Should be ignored+ }+ request = self.factory.post('/fake-url/', post_data)++ self.handler.process_file_title_updates(request, self.entity)++ # Verify both titles were updated+ file_attr1.refresh_from_db()+ file_attr2.refresh_from_db()+ self.assertEqual(file_attr1.value, 'New Title 1')+ self.assertEqual(file_attr2.value, 'New Title 2')++ def test_process_file_title_updates_ignores_mismatched_entity(self):+ """Test that fields with wrong entity ID are ignored."""+ file_attr = EntityAttributeSyntheticData.create_test_file_attribute(+ entity=self.entity, value='Original Title'+ )++ # Create form data with wrong entity ID in field name+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(self.entity)+ field_name = f'file_title_99999_{file_attr.id}'+ form_data[field_name] = 'Should Not Update'++ # Use real entity_edit URL+ url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})+ response = self.client.post(url, form_data)++ # Should return successful response+ self.assertEqual(response.status_code, 200)++ # Title should not be updated (observable behavior - what actually matters)+ file_attr.refresh_from_db()+ self.assertEqual(file_attr.value, 'Original Title')++ def test_process_file_title_updates_ignores_empty_title(self):+ """Test that empty titles are ignored."""+ file_attr = EntityAttributeSyntheticData.create_test_file_attribute(+ entity=self.entity, value='Original Title'+ )++ # Create form data with empty title (whitespace only)+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(self.entity)+ field_name = f'file_title_{self.entity.id}_{file_attr.id}'+ form_data[field_name] = ' ' # Whitespace only++ # Use real entity_edit URL+ url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})+ response = self.client.post(url, form_data)++ # Should return successful response+ self.assertEqual(response.status_code, 200)++ # Title should not be updated (observable behavior)+ file_attr.refresh_from_db()+ self.assertEqual(file_attr.value, 'Original Title')++ def test_process_file_title_updates_skips_unchanged_titles(self):+ """Test that unchanged titles are not unnecessarily saved."""+ file_attr = EntityAttributeSyntheticData.create_test_file_attribute(+ entity=self.entity, value='Same Title'+ )++ field_name = f'file_title_{self.entity.id}_{file_attr.id}'+ request = self.factory.post('/fake-url/', {field_name: 'Same Title'})++ # Mock the save method to verify it's not called+ with patch.object(file_attr, 'save') as mock_save:+ self.handler.process_file_title_updates(request, self.entity)++ mock_save.assert_not_called()++ def test_process_file_title_updates_handles_invalid_attribute_id(self):+ """Test handling of invalid attribute IDs."""+ # Create form data with invalid attribute ID in field name+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(self.entity)+ field_name = f'file_title_{self.entity.id}_invalid'+ form_data[field_name] = 'New Title'++ # Use real entity_edit URL - should handle invalid ID gracefully+ url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})+ response = self.client.post(url, form_data)++ # Should return successful response (invalid IDs are handled gracefully)+ self.assertEqual(response.status_code, 200)++ def test_process_file_title_updates_handles_nonexistent_attribute(self):+ """Test handling of nonexistent attribute IDs."""+ # Create form data with nonexistent attribute ID in field name+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(self.entity)+ field_name = f'file_title_{self.entity.id}_99999'+ form_data[field_name] = 'New Title'++ # Use real entity_edit URL - should handle nonexistent ID gracefully+ url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})+ response = self.client.post(url, form_data)++ # Should return successful response (nonexistent IDs are handled gracefully)+ self.assertEqual(response.status_code, 200)+++class TestEntityEditFormHandlerErrorCollection(BaseTestCase):+ """Test form error collection and formatting."""++ def setUp(self):+ super().setUp()+ self.handler = EntityEditFormHandler()+ self.entity = EntityAttributeSyntheticData.create_test_entity()++ def test_collect_form_errors_no_errors(self):+ """Test error collection when no errors exist."""+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(self.entity)+ entity_form, _, regular_attributes_formset = self.handler.create_entity_forms(+ self.entity, form_data+ )++ # Ensure forms are valid+ entity_form.is_valid()+ regular_attributes_formset.is_valid()++ errors = self.handler.collect_form_errors(entity_form, regular_attributes_formset)+ self.assertEqual(errors, [])++ def test_collect_form_errors_entity_form_errors(self):+ """Test collection of entity form non-field errors."""+ # Since EntityForm doesn't have custom clean() methods that create non-field errors,+ # we create a minimal test that confirms the method handles forms without non-field errors+ form_data = {'name': 'Valid Name', 'entity_type_str': str(EntityType.LIGHT)}+ entity_form, _, regular_attributes_formset = self.handler.create_entity_forms(+ self.entity, form_data+ )++ entity_form.is_valid() # Trigger validation+ regular_attributes_formset.is_valid()++ errors = self.handler.collect_form_errors(entity_form, regular_attributes_formset)++ # Should return empty list since we have no non-field errors+ entity_errors = [err for err in errors if err.startswith('Entity:')]+ self.assertEqual(len(entity_errors), 0)++ def test_collect_form_errors_formset_errors(self):+ """Test collection of formset non-field errors."""+ attr = EntityAttributeSyntheticData.create_test_text_attribute(entity=self.entity)++ entity_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(self.entity)+ formset_data = EntityAttributeSyntheticData.create_formset_data_for_attributes([attr], self.entity)++ form_data = {**entity_data, **formset_data}++ entity_form, _, regular_attributes_formset = self.handler.create_entity_forms(+ self.entity, form_data+ )++ entity_form.is_valid()+ regular_attributes_formset.is_valid()++ errors = self.handler.collect_form_errors(entity_form, regular_attributes_formset)++ # Should return empty list since we have no non-field errors in valid formset+ self.assertEqual(len(errors), 0)++ def test_collect_form_errors_handles_none_forms(self):+ """Test error collection with None form parameters."""+ errors = self.handler.collect_form_errors(None, None)+ self.assertEqual(errors, [])++ def test_collect_form_errors_comprehensive_error_formatting(self):+ """Test that error messages are properly formatted with context."""+ # Create attribute for formset testing+ attr = EntityAttributeSyntheticData.create_test_text_attribute(entity=self.entity, name='test_prop')++ # Create valid data since we're testing non-field error formatting, not field validation+ entity_data = {'name': 'Valid Entity', 'entity_type_str': str(EntityType.LIGHT)}+ formset_data = EntityAttributeSyntheticData.create_formset_data_for_attributes([attr], self.entity)++ form_data = {**entity_data, **formset_data}++ entity_form, _, regular_attributes_formset = self.handler.create_entity_forms(+ self.entity, form_data+ )++ entity_form.is_valid()+ regular_attributes_formset.is_valid()++ errors = self.handler.collect_form_errors(entity_form, regular_attributes_formset)++ # Since we have valid data and no custom non-field validation, should be empty+ self.assertEqual(len(errors), 0)+++class TestEntityEditFormHandlerInitialContext(BaseTestCase):+ """Test initial context creation for template rendering."""++ def setUp(self):+ super().setUp()+ self.handler = EntityEditFormHandler()+ self.entity = EntityAttributeSyntheticData.create_entity_with_mixed_attributes()++ def test_create_initial_context_contains_required_keys(self):+ """Test that initial context contains all required template variables."""+ context = self.handler.create_initial_context(self.entity)++ required_keys = ['entity', 'entity_form', 'file_attributes', 'regular_attributes_formset']+ for key in required_keys:+ self.assertIn(key, context)++ def test_create_initial_context_correct_types(self):+ """Test that context values have correct types."""+ context = self.handler.create_initial_context(self.entity)++ self.assertEqual(context['entity'], self.entity)+ self.assertIsInstance(context['entity_form'], EntityForm)+ self.assertIsInstance(context['regular_attributes_formset'], EntityAttributeRegularFormSet)++ # file_attributes should be a QuerySet+ file_attributes = context['file_attributes']+ self.assertTrue(hasattr(file_attributes, 'model')) # QuerySet-like++ def test_create_initial_context_file_attributes_filtering(self):+ """Test that file attributes are properly filtered in context."""+ context = self.handler.create_initial_context(self.entity)++ file_attributes = list(context['file_attributes'])++ # Should only include file attributes+ for attr in file_attributes:+ self.assertEqual(attr.value_type_str, str(AttributeValueType.FILE))++ def test_create_initial_context_unbound_forms(self):+ """Test that initial context creates unbound forms."""+ context = self.handler.create_initial_context(self.entity)++ self.assertFalse(context['entity_form'].is_bound)+ self.assertFalse(context['regular_attributes_formset'].is_bound)+diff --git a/src/hi/apps/entity/tests/test_entity_edit_response_renderer.py b/src/hi/apps/entity/tests/test_entity_edit_response_renderer.pynew file mode 100644index 00000000..f8645b06--- /dev/null+++ b/src/hi/apps/entity/tests/test_entity_edit_response_renderer.py@@ -0,0 +1,556 @@+"""+Unit tests for EntityEditResponseRenderer.++Tests the template rendering and response generation logic including+context building, fragment rendering, and antinode response construction.+"""+import logging+from unittest.mock import Mock, patch+from django.http import HttpRequest+from django.urls import reverse++from hi.apps.attribute.enums import AttributeValueType+from hi.apps.entity.entity_edit_form_handler import EntityEditFormHandler+from hi.apps.entity.entity_edit_response_renderer import EntityEditResponseRenderer+from hi.constants import DIVID+from hi.testing.base_test_case import BaseTestCase+from .synthetic_data import EntityAttributeSyntheticData++logging.disable(logging.CRITICAL)+++class TestEntityEditResponseRendererInitialization(BaseTestCase):+ """Test renderer initialization and dependencies."""++ def test_renderer_initializes_form_handler(self):+ """Test that renderer initializes with form handler dependency."""+ renderer = EntityEditResponseRenderer()++ self.assertIsNotNone(renderer.form_handler)+ # Verify it has the expected type+ from hi.apps.entity.entity_edit_form_handler import EntityEditFormHandler+ self.assertIsInstance(renderer.form_handler, EntityEditFormHandler)+++class TestEntityEditResponseRendererContextBuilding(BaseTestCase):+ """Test template context building logic."""++ def setUp(self):+ super().setUp()+ self.renderer = EntityEditResponseRenderer()+ self.entity = EntityAttributeSyntheticData.create_test_entity()++ def test_build_template_context_basic_structure(self):+ """Test that context includes all required keys."""+ # Create forms for context+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(self.entity)+ entity_form, file_attributes, regular_attributes_formset = self.renderer.form_handler.create_entity_forms(+ self.entity, form_data+ )++ context = self.renderer.build_template_context(+ entity=self.entity,+ entity_form=entity_form,+ file_attributes=file_attributes,+ regular_attributes_formset=regular_attributes_formset+ )++ required_keys = [+ 'entity', 'entity_form', 'file_attributes', 'regular_attributes_formset',+ 'success_message', 'error_message', 'has_errors', 'non_field_errors'+ ]++ for key in required_keys:+ self.assertIn(key, context, f"Missing required key: {key}")++ def test_build_template_context_with_success_message(self):+ """Test context building with success message."""+ entity_form, file_attributes, regular_attributes_formset = self.renderer.form_handler.create_entity_forms(self.entity)++ context = self.renderer.build_template_context(+ entity=self.entity,+ entity_form=entity_form,+ file_attributes=file_attributes,+ regular_attributes_formset=regular_attributes_formset,+ success_message="Operation completed successfully"+ )++ self.assertEqual(context['success_message'], "Operation completed successfully")+ self.assertIsNone(context['error_message'])+ self.assertFalse(context['has_errors'])++ def test_build_template_context_with_error_message(self):+ """Test context building with error message."""+ entity_form, file_attributes, regular_attributes_formset = self.renderer.form_handler.create_entity_forms(self.entity)++ context = self.renderer.build_template_context(+ entity=self.entity,+ entity_form=entity_form,+ file_attributes=file_attributes,+ regular_attributes_formset=regular_attributes_formset,+ error_message="Validation failed",+ has_errors=True+ )++ self.assertEqual(context['error_message'], "Validation failed")+ self.assertIsNone(context['success_message'])+ self.assertTrue(context['has_errors'])++ def test_build_template_context_collects_form_errors(self):+ """Test that context building collects form errors from real invalid forms."""+ # Create forms with invalid data to trigger real form errors+ form_handler = EntityEditFormHandler()++ # Create invalid form data - empty name should trigger validation errors+ invalid_form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(+ self.entity,+ name='' # Invalid - required field+ )++ entity_form, file_attributes, regular_attributes_formset = form_handler.create_entity_forms(+ self.entity,+ invalid_form_data+ )++ # Trigger form validation+ entity_form.is_valid()+ regular_attributes_formset.is_valid()++ # Build context with these invalid forms+ context = self.renderer.build_template_context(+ entity=self.entity,+ entity_form=entity_form,+ file_attributes=file_attributes,+ regular_attributes_formset=regular_attributes_formset+ )++ # The context should have the forms (with their field errors) but since the collect_form_errors+ # method only looks for non-field errors and we created field errors, non_field_errors should be empty+ self.assertIn('non_field_errors', context)+ self.assertIsInstance(context['non_field_errors'], list)++ def test_build_template_context_correct_object_references(self):+ """Test that context contains correct object references."""+ entity_form, file_attributes, regular_attributes_formset = self.renderer.form_handler.create_entity_forms(self.entity)++ context = self.renderer.build_template_context(+ entity=self.entity,+ entity_form=entity_form,+ file_attributes=file_attributes,+ regular_attributes_formset=regular_attributes_formset+ )++ # Verify object references are correct+ self.assertIs(context['entity'], self.entity)+ self.assertIs(context['entity_form'], entity_form)+ self.assertIs(context['file_attributes'], file_attributes)+ self.assertIs(context['regular_attributes_formset'], regular_attributes_formset)+++class TestEntityEditResponseRendererFragmentRendering(BaseTestCase):+ """Test template fragment rendering logic."""++ def setUp(self):+ super().setUp()+ self.renderer = EntityEditResponseRenderer()+ self.entity = EntityAttributeSyntheticData.create_test_entity()+ self.request = Mock(spec=HttpRequest)++ @patch('hi.apps.entity.entity_edit_response_renderer.render_to_string')+ def test_render_content_fragments_calls_correct_templates(self, mock_render):+ """Test that fragment rendering calls correct templates with proper context."""+ mock_render.side_effect = ['<content_body_html>', '<upload_form_html>']++ context = {'entity': self.entity, 'test': 'context'}++ content_body, upload_form = self.renderer.render_content_fragments(+ request=self.request,+ context=context,+ entity=self.entity+ )++ # Verify template calls+ self.assertEqual(mock_render.call_count, 2)++ # First call should be for content body+ first_call = mock_render.call_args_list[0]+ self.assertEqual(first_call[0][0], 'entity/panes/entity_edit_content_body.html')+ self.assertEqual(first_call[0][1], context)+ self.assertEqual(first_call[1]['request'], self.request)++ # Second call should be for upload form+ second_call = mock_render.call_args_list[1]+ self.assertEqual(second_call[0][0], 'attribute/components/upload_form.html')+ self.assertIn('file_upload_url', second_call[0][1])+ self.assertEqual(second_call[1]['request'], self.request)++ @patch('hi.apps.entity.entity_edit_response_renderer.render_to_string')+ def test_render_content_fragments_generates_upload_url(self, mock_render):+ """Test that fragment rendering generates correct upload URL."""+ mock_render.side_effect = ['<content_body_html>', '<upload_form_html>']++ context = {'entity': self.entity}++ self.renderer.render_content_fragments(+ request=self.request,+ context=context,+ entity=self.entity+ )++ # Check upload form template call+ upload_form_call = mock_render.call_args_list[1]+ upload_context = upload_form_call[0][1]++ expected_url = reverse('entity_attribute_upload', kwargs={'entity_id': self.entity.id})+ self.assertEqual(upload_context['file_upload_url'], expected_url)++ @patch('hi.apps.entity.entity_edit_response_renderer.render_to_string')+ def test_render_content_fragments_returns_rendered_content(self, mock_render):+ """Test that fragment rendering returns the rendered content."""+ mock_render.side_effect = ['<rendered_content_body>', '<rendered_upload_form>']++ context = {'entity': self.entity}++ content_body, upload_form = self.renderer.render_content_fragments(+ request=self.request,+ context=context,+ entity=self.entity+ )++ self.assertEqual(content_body, '<rendered_content_body>')+ self.assertEqual(upload_form, '<rendered_upload_form>')+++class TestEntityEditResponseRendererUpdateFragments(BaseTestCase):+ """Test the main fragment update rendering method."""++ def setUp(self):+ super().setUp()+ self.renderer = EntityEditResponseRenderer()+ self.entity = EntityAttributeSyntheticData.create_test_entity()+ self.request = Mock(spec=HttpRequest)++ @patch.object(EntityEditResponseRenderer, 'render_content_fragments')+ def test_render_update_fragments_with_provided_forms(self, mock_render_fragments):+ """Test fragment rendering when forms are provided."""+ mock_render_fragments.return_value = ('<content>', '<upload>')++ # Create forms+ entity_form, _, regular_attributes_formset = self.renderer.form_handler.create_entity_forms(self.entity)++ content_body, upload_form = self.renderer.render_update_fragments(+ request=self.request,+ entity=self.entity,+ entity_form=entity_form,+ regular_attributes_formset=regular_attributes_formset,+ success_message="Test success"+ )++ # Verify render_content_fragments was called+ mock_render_fragments.assert_called_once()++ # Verify return values+ self.assertEqual(content_body, '<content>')+ self.assertEqual(upload_form, '<upload>')++ @patch.object(EntityEditResponseRenderer, 'render_content_fragments')+ def test_render_update_fragments_creates_fresh_forms_when_none_provided(self, mock_render_fragments):+ """Test that fresh forms are created when none are provided."""+ mock_render_fragments.return_value = ('<content>', '<upload>')++ content_body, upload_form = self.renderer.render_update_fragments(+ request=self.request,+ entity=self.entity,+ success_message="Test success"+ )++ # Should have called render_content_fragments with created forms+ mock_render_fragments.assert_called_once()++ # Verify the call was made with proper context including success message+ call_args = mock_render_fragments.call_args+ context = call_args[1]['context']+ self.assertEqual(context['success_message'], "Test success")++ @patch.object(EntityEditResponseRenderer, 'render_content_fragments')+ def test_render_update_fragments_gets_file_attributes_when_forms_provided(self, mock_render_fragments):+ """Test that file attributes are retrieved even when forms are provided."""+ mock_render_fragments.return_value = ('<content>', '<upload>')++ # Create forms+ entity_form, _, regular_attributes_formset = self.renderer.form_handler.create_entity_forms(self.entity)++ self.renderer.render_update_fragments(+ request=self.request,+ entity=self.entity,+ entity_form=entity_form,+ regular_attributes_formset=regular_attributes_formset+ )++ # Should still retrieve file attributes for context+ call_args = mock_render_fragments.call_args+ context = call_args[1]['context']+ self.assertIn('file_attributes', context)++ @patch.object(EntityEditResponseRenderer, 'render_content_fragments')+ def test_render_update_fragments_builds_complete_context(self, mock_render_fragments):+ """Test that fragment rendering builds complete template context."""+ mock_render_fragments.return_value = ('<content>', '<upload>')++ self.renderer.render_update_fragments(+ request=self.request,+ entity=self.entity,+ success_message="Success!",+ error_message="Error!",+ has_errors=True+ )++ # Verify context was built with all parameters+ call_args = mock_render_fragments.call_args+ context = call_args[1]['context']++ self.assertEqual(context['entity'], self.entity)+ self.assertEqual(context['success_message'], "Success!")+ self.assertEqual(context['error_message'], "Error!")+ self.assertTrue(context['has_errors'])+++class TestEntityEditResponseRendererSuccessResponse(BaseTestCase):+ """Test success response generation."""++ def setUp(self):+ super().setUp()+ self.renderer = EntityEditResponseRenderer()+ self.entity = EntityAttributeSyntheticData.create_test_entity()+ self.request = Mock(spec=HttpRequest)++ @patch('hi.apps.entity.entity_edit_response_renderer.antinode.response')+ @patch.object(EntityEditResponseRenderer, 'render_update_fragments')+ def test_render_success_response_structure(self, mock_render_fragments, mock_antinode_response):+ """Test that success response has correct structure."""+ mock_render_fragments.return_value = ('<content_html>', '<upload_html>')+ mock_response = Mock()+ mock_antinode_response.return_value = mock_response++ result = self.renderer.render_success_response(self.request, self.entity)++ # Verify fragment rendering was called with success message+ mock_render_fragments.assert_called_once_with(+ request=self.request,+ entity=self.entity,+ success_message="Changes saved successfully"+ )++ # Verify antinode response was called with correct parameters+ mock_antinode_response.assert_called_once_with(+ insert_map={+ DIVID['ATTR_V2_CONTENT']: '<content_html>',+ DIVID['ATTR_V2_UPLOAD_FORM_CONTAINER']: '<upload_html>'+ }+ )++ self.assertIs(result, mock_response)++ @patch('hi.apps.entity.entity_edit_response_renderer.antinode.response')+ @patch.object(EntityEditResponseRenderer, 'render_update_fragments')+ def test_render_success_response_uses_correct_divids(self, mock_render_fragments, mock_antinode_response):+ """Test that success response uses correct DIVID constants."""+ mock_render_fragments.return_value = ('<content>', '<upload>')++ self.renderer.render_success_response(self.request, self.entity)++ # Verify DIVID constants are used correctly+ call_args = mock_antinode_response.call_args+ insert_map = call_args[1]['insert_map']++ expected_keys = [DIVID['ATTR_V2_CONTENT'], DIVID['ATTR_V2_UPLOAD_FORM_CONTAINER']]+ for key in expected_keys:+ self.assertIn(key, insert_map)+++class TestEntityEditResponseRendererErrorResponse(BaseTestCase):+ """Test error response generation."""++ def setUp(self):+ super().setUp()+ self.renderer = EntityEditResponseRenderer()+ self.entity = EntityAttributeSyntheticData.create_test_entity()+ self.request = Mock(spec=HttpRequest)++ @patch('hi.apps.entity.entity_edit_response_renderer.antinode.response')+ @patch.object(EntityEditResponseRenderer, 'render_update_fragments')+ def test_render_error_response_structure(self, mock_render_fragments, mock_antinode_response):+ """Test that error response has correct structure."""+ mock_render_fragments.return_value = ('<error_content>', '<error_upload>')+ mock_response = Mock()+ mock_antinode_response.return_value = mock_response++ # Create forms with errors+ form_data = {'name': ''} # Invalid data+ entity_form, _, regular_attributes_formset = self.renderer.form_handler.create_entity_forms(+ self.entity, form_data+ )++ result = self.renderer.render_error_response(+ self.request, self.entity, entity_form, regular_attributes_formset+ )++ # Verify fragment rendering was called with error parameters+ mock_render_fragments.assert_called_once_with(+ request=self.request,+ entity=self.entity,+ entity_form=entity_form,+ regular_attributes_formset=regular_attributes_formset,+ error_message="Please correct the errors below",+ has_errors=True+ )++ # Verify antinode response includes status 400+ mock_antinode_response.assert_called_once_with(+ insert_map={+ DIVID['ATTR_V2_CONTENT']: '<error_content>',+ DIVID['ATTR_V2_UPLOAD_FORM_CONTAINER']: '<error_upload>'+ },+ status=400+ )++ self.assertIs(result, mock_response)++ @patch('hi.apps.entity.entity_edit_response_renderer.antinode.response')+ @patch.object(EntityEditResponseRenderer, 'render_update_fragments')+ def test_render_error_response_preserves_form_errors(self, mock_render_fragments, mock_antinode_response):+ """Test that error response preserves form validation errors."""+ mock_render_fragments.return_value = ('<content>', '<upload>')++ # Create forms with validation errors+ invalid_data = {'name': ''} # Required field missing+ entity_form, _, regular_attributes_formset = self.renderer.form_handler.create_entity_forms(+ self.entity, invalid_data+ )++ # Trigger validation to generate errors+ entity_form.is_valid()+ regular_attributes_formset.is_valid()++ self.renderer.render_error_response(+ self.request, self.entity, entity_form, regular_attributes_formset+ )++ # Verify forms with errors were passed to fragment rendering+ call_args = mock_render_fragments.call_args+ self.assertIs(call_args[1]['entity_form'], entity_form)+ self.assertIs(call_args[1]['regular_attributes_formset'], regular_attributes_formset)+ self.assertTrue(call_args[1]['has_errors'])++ @patch('hi.apps.entity.entity_edit_response_renderer.antinode.response')+ @patch.object(EntityEditResponseRenderer, 'render_update_fragments')+ def test_render_error_response_400_status_code(self, mock_render_fragments, mock_antinode_response):+ """Test that error response returns 400 status code."""+ mock_render_fragments.return_value = ('<content>', '<upload>')++ entity_form, _, regular_attributes_formset = self.renderer.form_handler.create_entity_forms(self.entity)++ self.renderer.render_error_response(+ self.request, self.entity, entity_form, regular_attributes_formset+ )++ # Verify 400 status code+ call_args = mock_antinode_response.call_args+ self.assertEqual(call_args[1]['status'], 400)+++class TestEntityEditResponseRendererIntegration(BaseTestCase):+ """Test integration scenarios with real forms and data."""++ def setUp(self):+ super().setUp()+ self.renderer = EntityEditResponseRenderer()+ self.entity = EntityAttributeSyntheticData.create_entity_with_mixed_attributes()+ self.request = Mock(spec=HttpRequest)++ def test_end_to_end_success_scenario(self):+ """Test complete success scenario with real form data."""+ # Create valid form data+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(+ self.entity, name='Updated Entity Name'+ )++ entity_form, _, regular_attributes_formset = self.renderer.form_handler.create_entity_forms(+ self.entity, form_data+ )++ # Validate forms+ self.assertTrue(entity_form.is_valid())+ self.assertTrue(regular_attributes_formset.is_valid())++ # Test success response generation+ with patch('hi.apps.entity.entity_edit_response_renderer.render_to_string') as mock_render, \+ patch('hi.apps.entity.entity_edit_response_renderer.antinode.response') as mock_response:++ mock_render.side_effect = ['<success_content>', '<success_upload>']+ mock_response.return_value = Mock()++ result = self.renderer.render_success_response(self.request, self.entity)++ # Verify templates were rendered+ self.assertEqual(mock_render.call_count, 2)++ # Verify success response was created+ mock_response.assert_called_once()++ self.assertIsNotNone(result)++ def test_end_to_end_error_scenario(self):+ """Test complete error scenario with invalid form data."""+ # Create invalid form data+ invalid_data = {'name': ''} # Required field missing++ entity_form, _, regular_attributes_formset = self.renderer.form_handler.create_entity_forms(+ self.entity, invalid_data+ )++ # Validate forms (should fail)+ self.assertFalse(entity_form.is_valid())++ # Test error response generation+ with patch('hi.apps.entity.entity_edit_response_renderer.render_to_string') as mock_render, \+ patch('hi.apps.entity.entity_edit_response_renderer.antinode.response') as mock_response:++ mock_render.side_effect = ['<error_content>', '<error_upload>']+ mock_response.return_value = Mock()++ result = self.renderer.render_error_response(+ self.request, self.entity, entity_form, regular_attributes_formset+ )++ # Verify error response was created with 400 status+ call_args = mock_response.call_args+ self.assertEqual(call_args[1]['status'], 400)++ self.assertIsNotNone(result)++ def test_context_includes_file_attributes_correctly(self):+ """Test that context correctly includes file attributes."""+ # Entity should have file attributes from synthetic data+ file_attributes = self.entity.attributes.filter(+ value_type_str=str(AttributeValueType.FILE)+ )+ self.assertGreater(file_attributes.count(), 0)++ # Test context building+ entity_form, file_attrs_qs, regular_attributes_formset = self.renderer.form_handler.create_entity_forms(self.entity)++ context = self.renderer.build_template_context(+ entity=self.entity,+ entity_form=entity_form,+ file_attributes=file_attrs_qs,+ regular_attributes_formset=regular_attributes_formset+ )++ # Verify file attributes are in context+ context_file_attrs = list(context['file_attributes'])+ self.assertEqual(len(context_file_attrs), file_attributes.count())++ # Verify they are the correct file attributes+ for attr in context_file_attrs:+ self.assertEqual(attr.value_type, AttributeValueType.FILE)diff --git a/src/hi/apps/entity/tests/test_entity_manager.py b/src/hi/apps/entity/tests/test_entity_manager.pyindex d1381cf6..7e62c064 100644--- a/src/hi/apps/entity/tests/test_entity_manager.py+++ b/src/hi/apps/entity/tests/test_entity_manager.py@@ -4,7 +4,7 @@ from unittest.mock import Mockfrom hi.apps.entity.entity_manager import EntityManagerfrom hi.apps.entity.models import Entity, EntityPath, EntityPosition-from hi.apps.entity.enums import EntityGroupType+from hi.apps.entity.enums import EntityGroupType, EntityTypefrom hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)@@ -83,7 +83,7 @@ class TestEntityManager(BaseTestCase):# Create test entityentity = Entity.objects.create(name='Test Entity',- entity_type_str='LIGHT',+ entity_type_str=str(EntityType.LIGHT),integration_id='test_entity_001',integration_name='test_integration',)@@ -122,7 +122,7 @@ class TestEntityManager(BaseTestCase):# Create test dataentity = Entity.objects.create(name='Test Entity',- entity_type_str='LIGHT',+ entity_type_str=str(EntityType.LIGHT),integration_id='test_entity_001',integration_name='test_integration',)@@ -159,41 +159,41 @@ class TestEntityManager(BaseTestCase):self.skipTest("Required models not available for testing")return- def test_get_entity_details_data_returns_complete_data_structure(self):- """Test get_entity_details_data business logic - complex method integrating multiple systems."""+ def test_get_entity_edit_mode_data_returns_complete_data_structure(self):+ """Test get_entity_edit_mode_data business logic - complex method integrating multiple systems."""manager = EntityManager()# Create test entityentity = Entity.objects.create(name='Test Camera',- entity_type_str='CAMERA',+ entity_type_str=str(EntityType.CAMERA),integration_id='test_camera_001',integration_name='test_integration',)# Test with no location_view (basic case)- details_data = manager.get_entity_details_data(+ edit_mode_data = manager.get_entity_edit_mode_data(entity=entity,location_view=None,is_editing=False)# Verify complete data structure is returned- self.assertIsNotNone(details_data)- self.assertIsNotNone(details_data.entity_edit_data)- self.assertEqual(details_data.entity_edit_data.entity, entity)- self.assertIsNotNone(details_data.entity_pairing_list)+ self.assertIsNotNone(edit_mode_data)+ self.assertEqual(edit_mode_data.entity, entity)+ self.assertIsNotNone(edit_mode_data.entity_form)+ self.assertIsNotNone(edit_mode_data.entity_pairing_list)# Without location_view, position form should be None- self.assertIsNone(details_data.entity_position_form)+ self.assertIsNone(edit_mode_data.entity_position_form)# Test non-editing mode doesn't create position form- details_data_non_edit = manager.get_entity_details_data(+ edit_mode_data_non_edit = manager.get_entity_edit_mode_data(entity=entity,location_view=None,is_editing=True # Even with editing=True, no location_view means no form)- self.assertIsNone(details_data_non_edit.entity_position_form)+ self.assertIsNone(edit_mode_data_non_edit.entity_position_form)returndef test_create_entity_view_group_list_business_logic(self):@@ -203,21 +203,21 @@ class TestEntityManager(BaseTestCase):# Create test entities of different typeslight_entity = Entity.objects.create(name='Living Room Light',- entity_type_str='LIGHT',+ entity_type_str=str(EntityType.LIGHT),integration_id='light_001',integration_name='test_integration',)camera_entity = Entity.objects.create(name='Front Door Camera',- entity_type_str='CAMERA',+ entity_type_str=str(EntityType.CAMERA),integration_id='camera_001',integration_name='test_integration',)thermostat_entity = Entity.objects.create(name='Main Thermostat',- entity_type_str='THERMOSTAT',+ entity_type_str=str(EntityType.THERMOSTAT),integration_id='thermo_001',integration_name='test_integration',)@@ -287,7 +287,7 @@ class TestEntityManager(BaseTestCase):# Create test dataentity = Entity.objects.create(name='Wire Entity',- entity_type_str='ELECTRIC_WIRE',+ entity_type_str=str(EntityType.ELECTRIC_WIRE),integration_id='wire_001',integration_name='test_integration',)@@ -339,7 +339,7 @@ class TestEntityManager(BaseTestCase):# Create test dataentity = Entity.objects.create(name='Position Test Entity',- entity_type_str='CAMERA',+ entity_type_str=str(EntityType.CAMERA),integration_id='pos_test_001',integration_name='test_integration',)diff --git a/src/hi/apps/entity/tests/test_entity_type_transition_handler.py b/src/hi/apps/entity/tests/test_entity_type_transition_handler.pynew file mode 100644index 00000000..964901c9--- /dev/null+++ b/src/hi/apps/entity/tests/test_entity_type_transition_handler.py@@ -0,0 +1,493 @@+"""+Unit tests for EntityTypeTransitionHandler.++Tests the complex entity type transition logic including change detection,+transaction management, and response determination.+"""+import logging+from unittest.mock import Mock, patch+from django.http import HttpRequest, HttpResponse++from hi.apps.entity.entity_edit_form_handler import EntityEditFormHandler+from hi.apps.entity.entity_type_transition_handler import EntityTypeTransitionHandler+from hi.apps.entity.enums import EntityType, EntityTransitionType+from hi.apps.entity.forms import EntityForm, EntityAttributeRegularFormSet+from hi.testing.base_test_case import BaseTestCase+from .synthetic_data import EntityAttributeSyntheticData++logging.disable(logging.CRITICAL)+++class TestEntityTypeTransitionHandlerFormSaving(BaseTestCase):+ """Test form saving with transition detection."""++ def setUp(self):+ super().setUp()+ self.handler = EntityTypeTransitionHandler()+ self.entity = EntityAttributeSyntheticData.create_test_entity(entity_type_str=str(EntityType.LIGHT))+ self.request = Mock(spec=HttpRequest)++ def test_handle_entity_form_save_uses_transaction(self):+ """Test that form saving uses database transaction properly."""+ # Test that entity changes are saved atomically+ new_name = 'Transactionally Updated Name'++ # Create valid form data that changes the entity name+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(+ self.entity, name=new_name+ )+ entity_form = EntityForm(form_data, instance=self.entity)++ self.assertTrue(entity_form.is_valid())++ result = self.handler.handle_entity_form_save(+ request=self.request,+ entity=self.entity,+ entity_form=entity_form+ )++ # Should return None for no entity type change+ self.assertIsNone(result)++ # Verify the entity was actually saved (transactional success)+ self.entity.refresh_from_db()+ self.assertEqual(self.entity.name, new_name)++ def test_handle_entity_form_save_no_type_change(self):+ """Test form saving when entity type doesn't change."""+ original_type = self.entity.entity_type_str++ # Create form data with same entity type+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(+ self.entity, entity_type_str=original_type+ )+ entity_form = EntityForm(form_data, instance=self.entity)++ self.assertTrue(entity_form.is_valid())++ result = self.handler.handle_entity_form_save(+ request=self.request,+ entity=self.entity,+ entity_form=entity_form,+ original_entity_type_str=original_type+ )++ # Should return None (no transition response needed)+ self.assertIsNone(result)++ # Entity should be saved with same type+ self.entity.refresh_from_db()+ self.assertEqual(self.entity.entity_type_str, original_type)++ @patch.object(EntityTypeTransitionHandler, 'handle_entity_type_change')+ def test_handle_entity_form_save_with_type_change(self, mock_handle_change):+ """Test form saving when entity type changes."""+ mock_handle_change.return_value = Mock(spec=HttpResponse)++ original_type = EntityType.LIGHT+ new_type = EntityType.WALL_SWITCH++ # Create form data with different entity type+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(+ self.entity, entity_type_str=str(new_type)+ )+ entity_form = EntityForm(form_data, instance=self.entity)++ self.assertTrue(entity_form.is_valid())++ result = self.handler.handle_entity_form_save(+ request=self.request,+ entity=self.entity,+ entity_form=entity_form,+ original_entity_type_str=original_type+ )++ # Should call type change handler+ mock_handle_change.assert_called_once_with(self.request, self.entity)++ # Should return the transition response+ self.assertIsNotNone(result)+ self.assertIsInstance(result, HttpResponse)++ def test_handle_entity_form_save_with_formset(self):+ """Test form saving with both entity form and attribute formset."""+ # Create attribute for formset+ attr = EntityAttributeSyntheticData.create_test_text_attribute(entity=self.entity)++ # Create form data for both entity and formset+ entity_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(+ self.entity, name='Updated Name'+ )+ formset_data = EntityAttributeSyntheticData.create_formset_data_for_attributes([attr], self.entity)+ prefix = EntityEditFormHandler.get_formset_prefix(self.entity)+ formset_data[f'{prefix}-0-value'] = 'Updated Value'++ form_data = {**entity_data, **formset_data}++ entity_form = EntityForm(entity_data, instance=self.entity)+ formset = EntityAttributeRegularFormSet(+ form_data, instance=self.entity, prefix=prefix+ )++ self.assertTrue(entity_form.is_valid())+ self.assertTrue(formset.is_valid())++ result = self.handler.handle_entity_form_save(+ request=self.request,+ entity=self.entity,+ entity_form=entity_form,+ entity_attribute_formset=formset+ )++ # Verify both were saved+ self.entity.refresh_from_db()+ attr.refresh_from_db()++ self.assertEqual(self.entity.name, 'Updated Name')+ self.assertEqual(attr.value, 'Updated Value')++ # No type change, should return None+ self.assertIsNone(result)++ def test_handle_entity_form_save_defaults_original_type(self):+ """Test that original_entity_type_str defaults to current entity type."""+ new_type = EntityType.WALL_SWITCH+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(+ self.entity, entity_type_str=str(new_type)+ )+ entity_form = EntityForm(form_data, instance=self.entity)++ with patch.object(self.handler, 'handle_entity_type_change') as mock_handle_change:+ mock_handle_change.return_value = None++ # Don't provide original_entity_type_str+ self.handler.handle_entity_form_save(+ request=self.request,+ entity=self.entity,+ entity_form=entity_form+ # original_entity_type_str not provided+ )++ # Should detect change from current entity type+ mock_handle_change.assert_called_once()+++class TestEntityTypeTransitionHandlerTransitionLogic(BaseTestCase):+ """Test entity type change handling and transition logic."""++ def setUp(self):+ super().setUp()+ self.handler = EntityTypeTransitionHandler()+ self.entity = EntityAttributeSyntheticData.create_test_entity(entity_type_str=str(EntityType.LIGHT))+ self.request = Mock(spec=HttpRequest)++ @patch('hi.apps.entity.entity_type_transition_handler.EntityManager')+ @patch('hi.apps.entity.entity_type_transition_handler.LocationManager')+ def test_handle_entity_type_change_successful_transition(self, mock_location_manager, mock_entity_manager):+ """Test successful entity type change with transition."""+ # Mock location manager+ mock_location_view = Mock()+ mock_location_manager.return_value.get_default_location_view.return_value = mock_location_view++ # Mock entity manager transition+ mock_entity_manager.return_value.handle_entity_type_transition.return_value = (True, EntityTransitionType.ICON_TO_ICON)++ result = self.handler.handle_entity_type_change(self.request, self.entity)++ # Should attempt transition+ mock_entity_manager.return_value.handle_entity_type_transition.assert_called_once_with(+ entity=self.entity,+ location_view=mock_location_view+ )++ # Should return refresh response for icon_to_icon transition+ self.assertIsNotNone(result)++ @patch('hi.apps.entity.entity_type_transition_handler.EntityManager')+ @patch('hi.apps.entity.entity_type_transition_handler.LocationManager')+ def test_handle_entity_type_change_failed_transition(self, mock_location_manager, mock_entity_manager):+ """Test entity type change when transition fails."""+ # Mock location manager+ mock_location_view = Mock()+ mock_location_manager.return_value.get_default_location_view.return_value = mock_location_view++ # Mock failed transition+ mock_entity_manager.return_value.handle_entity_type_transition.return_value = (False, EntityTransitionType.NO_TRANSITION_NEEDED)++ with patch('hi.apps.entity.entity_type_transition_handler.antinode.refresh_response') as mock_refresh:+ mock_refresh.return_value = Mock(spec=HttpResponse)++ result = self.handler.handle_entity_type_change(self.request, self.entity)++ # Should return refresh response for failed transition+ mock_refresh.assert_called_once()+ self.assertIsNotNone(result)++ @patch('hi.apps.entity.entity_type_transition_handler.EntityManager')+ @patch('hi.apps.entity.entity_type_transition_handler.LocationManager')+ def test_handle_entity_type_change_exception_handling(self, mock_location_manager, mock_entity_manager):+ """Test entity type change exception handling."""+ # Mock location manager to raise exception+ mock_location_manager.return_value.get_default_location_view.side_effect = Exception("Test error")++ with patch('hi.apps.entity.entity_type_transition_handler.antinode.refresh_response') as mock_refresh:+ mock_refresh.return_value = Mock(spec=HttpResponse)++ result = self.handler.handle_entity_type_change(self.request, self.entity)++ # Should return refresh response (observable behavior)+ mock_refresh.assert_called_once()+ self.assertIsNotNone(result)+ # The actual important behavior is that an HttpResponse is returned for error handling++ @patch('hi.apps.entity.entity_type_transition_handler.EntityManager')+ @patch('hi.apps.entity.entity_type_transition_handler.LocationManager')+ def test_handle_entity_type_change_path_to_path_transition(self, mock_location_manager, mock_entity_manager):+ """Test path_to_path transition returns None (sidebar refresh only)."""+ # Mock successful path_to_path transition+ mock_location_view = Mock()+ mock_location_manager.return_value.get_default_location_view.return_value = mock_location_view+ mock_entity_manager.return_value.handle_entity_type_transition.return_value = (True, EntityTransitionType.PATH_TO_PATH)++ result = self.handler.handle_entity_type_change(self.request, self.entity)++ # path_to_path transition should return None (no full page refresh needed)+ self.assertIsNone(result)+++class TestEntityTypeTransitionHandlerRefreshLogic(BaseTestCase):+ """Test refresh determination logic."""++ def setUp(self):+ super().setUp()+ self.handler = EntityTypeTransitionHandler()++ def test_needs_full_page_refresh_failed_transition(self):+ """Test that failed transitions require full page refresh."""+ result = self.handler.needs_full_page_refresh(+ transition_occurred=False,+ transition_type=EntityTransitionType.NO_TRANSITION_NEEDED+ )++ self.assertTrue(result)++ def test_needs_full_page_refresh_path_to_path(self):+ """Test that path_to_path transitions don't require full page refresh."""+ result = self.handler.needs_full_page_refresh(+ transition_occurred=True,+ transition_type=EntityTransitionType.PATH_TO_PATH+ )++ self.assertFalse(result)++ def test_needs_full_page_refresh_icon_transitions(self):+ """Test that icon transitions require full page refresh."""+ icon_transitions = [EntityTransitionType.ICON_TO_ICON, EntityTransitionType.ICON_TO_PATH, EntityTransitionType.PATH_TO_ICON]++ for transition_type in icon_transitions:+ with self.subTest(transition_type=transition_type):+ result = self.handler.needs_full_page_refresh(+ transition_occurred=True,+ transition_type=transition_type+ )++ self.assertTrue(result)++ def test_needs_full_page_refresh_unknown_transition_type(self):+ """Test that unknown transition types default to full page refresh."""+ result = self.handler.needs_full_page_refresh(+ transition_occurred=True,+ transition_type=EntityTransitionType.NO_TRANSITION_NEEDED+ )++ self.assertTrue(result)++ def test_needs_full_page_refresh_comprehensive_logic(self):+ """Test comprehensive refresh logic scenarios."""+ test_cases = [+ # (transition_occurred, transition_type, expected_refresh)+ (False, EntityTransitionType.PATH_TO_PATH, True), # Failed transition+ (False, EntityTransitionType.ICON_TO_ICON, True), # Failed transition+ (True, EntityTransitionType.PATH_TO_PATH, False), # Success, style change only+ (True, EntityTransitionType.ICON_TO_ICON, True), # Success, visual change needed+ (True, EntityTransitionType.ICON_TO_PATH, True), # Success, structure change+ (True, EntityTransitionType.PATH_TO_ICON, True), # Success, structure change+ (True, EntityTransitionType.NO_TRANSITION_NEEDED, True), # Unknown type, safe default+ ]++ for transition_occurred, transition_type, expected_refresh in test_cases:+ with self.subTest(occurred=transition_occurred, type=transition_type):+ result = self.handler.needs_full_page_refresh(+ transition_occurred=transition_occurred,+ transition_type=transition_type+ )++ self.assertEqual(result, expected_refresh)+++class TestEntityTypeTransitionHandlerIntegration(BaseTestCase):+ """Test integration scenarios with real entity type changes."""++ def setUp(self):+ super().setUp()+ self.handler = EntityTypeTransitionHandler()+ self.request = Mock(spec=HttpRequest)++ def test_complete_entity_type_change_scenario(self):+ """Test complete entity type change from LIGHT to WALL_SWITCH."""+ entity = EntityAttributeSyntheticData.create_test_entity(entity_type_str=str(EntityType.LIGHT))+ original_type = entity.entity_type_str++ # Create form data changing type+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(+ entity, entity_type_str=str(EntityType.WALL_SWITCH)+ )+ entity_form = EntityForm(form_data, instance=entity)++ self.assertTrue(entity_form.is_valid())++ # Mock the complex dependencies+ with patch('hi.apps.entity.entity_type_transition_handler.LocationManager') as mock_loc_mgr, \+ patch('hi.apps.entity.entity_type_transition_handler.EntityManager') as mock_entity_mgr, \+ patch('hi.apps.entity.entity_type_transition_handler.antinode.refresh_response') as mock_refresh:++ # Setup mocks+ mock_location_view = Mock()+ mock_loc_mgr.return_value.get_default_location_view.return_value = mock_location_view+ mock_entity_mgr.return_value.handle_entity_type_transition.return_value = (True, EntityTransitionType.ICON_TO_ICON)+ mock_refresh.return_value = Mock(spec=HttpResponse)++ # Execute the transition+ result = self.handler.handle_entity_form_save(+ request=self.request,+ entity=entity,+ entity_form=entity_form,+ original_entity_type_str=original_type+ )++ # Verify entity was saved+ entity.refresh_from_db()+ self.assertEqual(entity.entity_type_str, str(EntityType.WALL_SWITCH).lower())++ # Verify transition was attempted+ mock_entity_mgr.return_value.handle_entity_type_transition.assert_called_once()++ # Verify refresh response was returned+ mock_refresh.assert_called_once()+ self.assertIsNotNone(result)++ def test_entity_type_change_with_attributes_formset(self):+ """Test entity type change with simultaneous attribute changes."""+ entity = EntityAttributeSyntheticData.create_test_entity(entity_type_str=str(EntityType.LIGHT))+ attr = EntityAttributeSyntheticData.create_test_text_attribute(+ entity=entity, name='brightness', value='100'+ )++ # Create form data changing both entity type and attribute+ entity_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(+ entity, entity_type_str=str(EntityType.WALL_SWITCH), name='Updated Light'+ )+ formset_data = EntityAttributeSyntheticData.create_formset_data_for_attributes([attr], entity)+ prefix = EntityEditFormHandler.get_formset_prefix(entity)+ formset_data[f'{prefix}-0-value'] = '75'++ form_data = {**entity_data, **formset_data}++ entity_form = EntityForm(entity_data, instance=entity)+ formset = EntityAttributeRegularFormSet(+ form_data, instance=entity, prefix=prefix+ )++ self.assertTrue(entity_form.is_valid())+ self.assertTrue(formset.is_valid())++ # Mock transition to return simple response+ with patch('hi.apps.entity.entity_type_transition_handler.LocationManager'), \+ patch('hi.apps.entity.entity_type_transition_handler.EntityManager') as mock_entity_mgr, \+ patch('hi.apps.entity.entity_type_transition_handler.antinode.refresh_response') as mock_refresh:++ # Mock simple transition+ mock_entity_mgr.return_value.handle_entity_type_transition.return_value = (True, EntityTransitionType.PATH_TO_PATH)+ mock_refresh.return_value = Mock(spec=HttpResponse)++ result = self.handler.handle_entity_form_save(+ request=self.request,+ entity=entity,+ entity_form=entity_form,+ entity_attribute_formset=formset,+ original_entity_type_str=str(EntityType.LIGHT)+ )++ # Verify both entity and attribute were saved+ entity.refresh_from_db()+ attr.refresh_from_db()++ self.assertEqual(entity.entity_type_str, str(EntityType.WALL_SWITCH).lower())+ self.assertEqual(entity.name, 'Updated Light')+ self.assertEqual(attr.value, '75')++ # path_to_path transition should not require full page refresh+ self.assertIsNone(result)++ def test_transaction_rollback_on_transition_failure(self):+ """Test that transaction is properly managed even if transition fails."""+ entity = EntityAttributeSyntheticData.create_test_entity(entity_type_str=str(EntityType.LIGHT))++ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(+ entity, entity_type_str=str(EntityType.WALL_SWITCH), name='Updated Name'+ )+ entity_form = EntityForm(form_data, instance=entity)++ # Mock transition to raise exception after forms are saved+ with patch('hi.apps.entity.entity_type_transition_handler.LocationManager') as mock_loc_mgr, \+ patch('hi.apps.entity.entity_type_transition_handler.EntityManager'):++ mock_loc_mgr.return_value.get_default_location_view.side_effect = Exception("Transition error")++ # The form save should still work, transition failure is handled gracefully+ result = self.handler.handle_entity_form_save(+ request=self.request,+ entity=entity,+ entity_form=entity_form,+ original_entity_type_str=str(EntityType.LIGHT)+ )++ # Entity should still be saved (transaction includes form save)+ entity.refresh_from_db()+ self.assertEqual(entity.entity_type_str, str(EntityType.WALL_SWITCH).lower())+ self.assertEqual(entity.name, 'Updated Name')++ # Should return error response due to transition failure+ self.assertIsNotNone(result)++ def test_no_transition_when_type_unchanged(self):+ """Test that no transition is attempted when entity type doesn't change."""+ entity = EntityAttributeSyntheticData.create_test_entity(entity_type_str=str(EntityType.LIGHT))++ # Create form data with same entity type+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(+ entity, entity_type_str=str(EntityType.LIGHT), name='Updated Name'+ )+ entity_form = EntityForm(form_data, instance=entity)++ with patch('hi.apps.entity.entity_type_transition_handler.LocationManager') as mock_loc_mgr, \+ patch('hi.apps.entity.entity_type_transition_handler.EntityManager') as mock_entity_mgr:++ result = self.handler.handle_entity_form_save(+ request=self.request,+ entity=entity,+ entity_form=entity_form,+ original_entity_type_str=str(EntityType.LIGHT) # Same as current type+ )++ # No transition should be attempted+ mock_loc_mgr.assert_not_called()+ mock_entity_mgr.assert_not_called()++ # Should return None (no special response needed)+ self.assertIsNone(result)++ # Entity should still be saved+ entity.refresh_from_db()+ self.assertEqual(entity.name, 'Updated Name')+diff --git a/src/hi/apps/entity/tests/test_entity_type_transitions.py b/src/hi/apps/entity/tests/test_entity_type_transitions.pyindex 0cf6dfce..a2d51519 100644--- a/src/hi/apps/entity/tests/test_entity_type_transitions.py+++ b/src/hi/apps/entity/tests/test_entity_type_transitions.py@@ -8,7 +8,7 @@ from django.db import transactionfrom django.test import TransactionTestCasefrom hi.apps.entity.entity_manager import EntityManager-from hi.apps.entity.enums import EntityType+from hi.apps.entity.enums import EntityType, EntityTransitionTypefrom hi.apps.entity.models import Entity, EntityPath, EntityPositionfrom hi.apps.location.models import Location, LocationView@@ -67,7 +67,7 @@ class TestEntityTypeTransitions(TransactionTestCase):# Verify transition occurredself.assertTrue(transition_occurred)- self.assertEqual(transition_type, "icon_to_path")+ self.assertEqual(transition_type, EntityTransitionType.ICON_TO_PATH)# Verify EntityPosition is preservedself.assertTrue(@@ -115,7 +115,7 @@ class TestEntityTypeTransitions(TransactionTestCase):# Verify transition occurredself.assertTrue(transition_occurred)- self.assertEqual(transition_type, "path_to_icon")+ self.assertEqual(transition_type, EntityTransitionType.PATH_TO_ICON)# Verify EntityPath is preservedself.assertTrue(@@ -170,7 +170,7 @@ class TestEntityTypeTransitions(TransactionTestCase):# Should be path to icon since both representations now existself.assertTrue(transition_occurred)- self.assertEqual(transition_type, "path_to_icon")+ self.assertEqual(transition_type, EntityTransitionType.PATH_TO_ICON)# Verify original position is preservedentity_position = EntityPosition.objects.get(@@ -206,7 +206,7 @@ class TestEntityTypeTransitions(TransactionTestCase):# Should recognize transition from preserved path to iconself.assertTrue(transition_occurred)- self.assertEqual(transition_type, "path_to_icon")+ self.assertEqual(transition_type, EntityTransitionType.PATH_TO_ICON)# Transition to path typeself.entity.entity_type_str = str(EntityType.WALL)@@ -218,7 +218,7 @@ class TestEntityTypeTransitions(TransactionTestCase):# Should recognize transition to path when both exist (icon_to_path)self.assertTrue(transition_occurred)- self.assertEqual(transition_type, "icon_to_path")+ self.assertEqual(transition_type, EntityTransitionType.ICON_TO_PATH)# Both should still existself.assertEqual(EntityPosition.objects.filter(entity=self.entity).count(), 1)@@ -247,7 +247,7 @@ class TestEntityTypeTransitions(TransactionTestCase):)self.assertTrue(transition_occurred)- self.assertEqual(transition_type, "icon_to_icon")+ self.assertEqual(transition_type, EntityTransitionType.ICON_TO_ICON)# Only position should existself.assertEqual(EntityPosition.objects.filter(entity=self.entity).count(), 1)@@ -277,7 +277,7 @@ class TestEntityTypeTransitions(TransactionTestCase):)self.assertTrue(transition_occurred)- self.assertEqual(transition_type, "path_to_path")+ self.assertEqual(transition_type, EntityTransitionType.PATH_TO_PATH)# Only path should existself.assertEqual(EntityPosition.objects.filter(entity=self.entity).count(), 0)@@ -292,7 +292,7 @@ class TestEntityTypeTransitions(TransactionTestCase):)self.assertFalse(transition_occurred)- self.assertEqual(transition_type, "no_location_view")+ self.assertEqual(transition_type, EntityTransitionType.NO_LOCATION_VIEW)returndef test_path_center_calculation(self):diff --git a/src/hi/apps/entity/tests/test_models.py b/src/hi/apps/entity/tests/test_models.pyindex 2eaac150..a30c6527 100644--- a/src/hi/apps/entity/tests/test_models.py+++ b/src/hi/apps/entity/tests/test_models.py@@ -17,7 +17,7 @@ class TestEntity(BaseTestCase):# Create first entity with unique integration keyfirst_entity = Entity.objects.create(name='First Entity',- entity_type_str='LIGHT',+ entity_type_str=str(EntityType.LIGHT),integration_id='unique_id_001',integration_name='home_assistant',)@@ -25,7 +25,7 @@ class TestEntity(BaseTestCase):# Different integration_id should work finesecond_entity = Entity.objects.create(name='Second Entity',- entity_type_str='CAMERA',+ entity_type_str=str(EntityType.CAMERA),integration_id='unique_id_002', # Different IDintegration_name='home_assistant', # Same integration)@@ -33,7 +33,7 @@ class TestEntity(BaseTestCase):# Different integration_name should work finethird_entity = Entity.objects.create(name='Third Entity',- entity_type_str='THERMOSTAT',+ entity_type_str=str(EntityType.THERMOSTAT),integration_id='unique_id_001', # Same ID as firstintegration_name='nest_integration', # Different integration)@@ -47,7 +47,7 @@ class TestEntity(BaseTestCase):try:Entity.objects.create(name='Duplicate Entity',- entity_type_str='MOTOR',+ entity_type_str=str(EntityType.MOTOR),integration_id='unique_id_001', # Same as firstintegration_name='home_assistant', # Same as first)@@ -61,7 +61,7 @@ class TestEntity(BaseTestCase):"""Test entity_type property enum conversion logic - custom business logic."""entity = Entity.objects.create(name='Test Device',- entity_type_str='LIGHT',+ entity_type_str=str(EntityType.LIGHT),integration_id='test_device_001',integration_name='test_integration',)@@ -71,7 +71,7 @@ class TestEntity(BaseTestCase):# Test setter converts enum to string (lowercase)entity.entity_type = EntityType.CAMERA- self.assertEqual(entity.entity_type_str, 'camera')+ self.assertEqual(entity.entity_type_str, str(EntityType.CAMERA).lower())self.assertEqual(entity.entity_type, EntityType.CAMERA)return@@ -79,7 +79,7 @@ class TestEntity(BaseTestCase):"""Test entity_type property with unknown type - should provide fallback behavior."""entity = Entity.objects.create(name='Future Device',- entity_type_str='FUTURE_DEVICE_TYPE', # Unknown type+ entity_type_str='FUTURE_DEVICE_TYPE', # Keep as string - unknown type testintegration_id='future_device_001',integration_name='test_integration',)@@ -103,7 +103,7 @@ class TestEntity(BaseTestCase):"""Test get_attribute_map business logic - custom method prone to bugs."""entity = Entity.objects.create(name='Test Entity',- entity_type_str='OTHER',+ entity_type_str=str(EntityType.OTHER),integration_id='test_entity_001',integration_name='test_integration',)@@ -133,7 +133,7 @@ class TestEntity(BaseTestCase):# Test with no attributesempty_entity = Entity.objects.create(name='Empty Entity',- entity_type_str='OTHER',+ entity_type_str=str(EntityType.OTHER),integration_id='empty_entity_001',integration_name='test_integration',)@@ -146,7 +146,7 @@ class TestEntity(BaseTestCase):"""Test cascade deletion - critical for data integrity."""entity = Entity.objects.create(name='Test Entity',- entity_type_str='OTHER',+ entity_type_str=str(EntityType.OTHER),integration_id='test_entity_001',integration_name='test_integration',)@@ -161,7 +161,7 @@ class TestEntity(BaseTestCase):state = EntityState.objects.create(entity=entity,- entity_state_type_str='ON_OFF',+ entity_state_type_str=str(EntityStateType.ON_OFF),name='Power State',)@@ -182,7 +182,7 @@ class TestEntityState(BaseTestCase):super().setUp()self.entity = Entity.objects.create(name='Test Entity',- entity_type_str='LIGHT',+ entity_type_str=str(EntityType.LIGHT),integration_id='test_entity_001',integration_name='test_integration',)@@ -192,7 +192,7 @@ class TestEntityState(BaseTestCase):"""Test entity_state_type property enum conversion - custom business logic."""state = EntityState.objects.create(entity=self.entity,- entity_state_type_str='ON_OFF',+ entity_state_type_str=str(EntityStateType.ON_OFF),name='Power State',)@@ -201,7 +201,7 @@ class TestEntityState(BaseTestCase):# Test setter converts enum to string (lowercase)state.entity_state_type = EntityStateType.TEMPERATURE- self.assertEqual(state.entity_state_type_str, 'temperature')+ self.assertEqual(state.entity_state_type_str, str(EntityStateType.TEMPERATURE).lower())self.assertEqual(state.entity_state_type, EntityStateType.TEMPERATURE)return@@ -211,7 +211,7 @@ class TestEntityState(BaseTestCase):value_dict = {"ON": "Powered On", "OFF": "Powered Off"}state = EntityState.objects.create(entity=self.entity,- entity_state_type_str='ON_OFF',+ entity_state_type_str=str(EntityStateType.ON_OFF),name='Power State',value_range_str=json.dumps(value_dict),)@@ -253,7 +253,7 @@ class TestEntityState(BaseTestCase):# Create state with specific value mappings for UIstate = EntityState.objects.create(entity=self.entity,- entity_state_type_str='ON_OFF',+ entity_state_type_str=str(EntityStateType.ON_OFF),name='Power State',value_range_str='{"ON": "Device On", "OFF": "Device Off"}',)@@ -269,7 +269,7 @@ class TestEntityState(BaseTestCase):# Test with temperature range (continuous values)temp_state = EntityState.objects.create(entity=self.entity,- entity_state_type_str='TEMPERATURE',+ entity_state_type_str=str(EntityStateType.TEMPERATURE),name='Temperature Reading',units='°F',value_range_str='null' # Continuous values don't need fixed choices@@ -291,7 +291,7 @@ class TestEntityState(BaseTestCase):"""Test entity attribute mapping - core functionality for configuration and metadata."""entity = Entity.objects.create(name='Smart Thermostat',- entity_type_str='THERMOSTAT',+ entity_type_str=str(EntityType.THERMOSTAT),integration_id='thermostat_001',integration_name='nest_integration',)@@ -300,21 +300,21 @@ class TestEntityState(BaseTestCase):config_attr = EntityAttribute.objects.create(entity=entity,name='temperature_offset',- value_type='TEXT',+ value_type=AttributeValueType.TEXT,value='+2.5',)model_attr = EntityAttribute.objects.create(entity=entity,name='device_model',- value_type='TEXT',+ value_type=AttributeValueType.TEXT,value='Nest Learning Thermostat v3',)firmware_attr = EntityAttribute.objects.create(entity=entity,name='firmware_version',- value_type='TEXT',+ value_type=AttributeValueType.TEXT,value='6.2.1',)@@ -334,7 +334,7 @@ class TestEntityState(BaseTestCase):# Test empty attribute mapempty_entity = Entity.objects.create(name='Basic Switch',- entity_type_str='ON_OFF_SWITCH',+ entity_type_str=str(EntityType.ON_OFF_SWITCH),integration_id='switch_001',integration_name='test_integration',)@@ -349,7 +349,7 @@ class TestEntityState(BaseTestCase):"""Test entity type enum conversion - critical for type safety and UI display."""entity = Entity.objects.create(name='Security Camera',- entity_type_str='CAMERA',+ entity_type_str=str(EntityType.CAMERA),integration_id='camera_001',integration_name='security_system',)@@ -359,7 +359,6 @@ class TestEntityState(BaseTestCase):self.assertEqual(str(entity_type_enum).lower(), 'camera')# Test enum to string conversion via setter- from hi.apps.entity.enums import EntityTypeentity.entity_type = EntityType.MOTION_SENSOR# Should update the string field@@ -380,7 +379,7 @@ class TestEntityState(BaseTestCase):# Create entity with related objectsentity = Entity.objects.create(name='Multi-State Device',- entity_type_str='HVAC_FURNACE',+ entity_type_str=str(EntityType.HVAC_FURNACE),integration_id='furnace_001',integration_name='hvac_system',)@@ -389,27 +388,27 @@ class TestEntityState(BaseTestCase):config_attribute = EntityAttribute.objects.create(entity=entity,name='max_temperature',- value_type='TEXT',+ value_type=AttributeValueType.TEXT,value='85',)specs_attribute = EntityAttribute.objects.create(entity=entity,name='manufacturer',- value_type='TEXT',+ value_type=AttributeValueType.TEXT,value='Carrier',)# Create related statespower_state = EntityState.objects.create(entity=entity,- entity_state_type_str='ON_OFF',+ entity_state_type_str=str(EntityStateType.ON_OFF),name='Power State',)temp_state = EntityState.objects.create(entity=entity,- entity_state_type_str='TEMPERATURE',+ entity_state_type_str=str(EntityStateType.TEMPERATURE),name='Current Temperature',units='°F',)diff --git a/src/hi/apps/entity/tests/test_views.py b/src/hi/apps/entity/tests/test_views.pyindex b8654edc..b9608f0e 100644--- a/src/hi/apps/entity/tests/test_views.py+++ b/src/hi/apps/entity/tests/test_views.py@@ -2,104 +2,349 @@ import loggingfrom unittest.mock import Mock, patchfrom django.core.files.uploadedfile import SimpleUploadedFile+from django.db import transactionfrom django.urls import reverse+from hi.apps.attribute.enums import AttributeValueTypefrom hi.apps.control.controller_history_manager import ControllerHistoryManager+from hi.apps.entity.enums import EntityType, EntityStateType+from hi.apps.entity.entity_edit_form_handler import EntityEditFormHandlerfrom hi.apps.entity.models import Entity, EntityAttributefrom hi.apps.location.models import Location, LocationView+from hi.apps.location.enums import LocationViewTypefrom hi.apps.sense.sensor_history_manager import SensorHistoryManagerfrom hi.enums import ViewTypefrom hi.testing.view_test_base import SyncViewTestCase, DualModeViewTestCase+from .synthetic_data import EntityAttributeSyntheticDatalogging.disable(logging.CRITICAL)-class TestEntityEditView(SyncViewTestCase):- """- Tests for EntityEditView - demonstrates entity editing with forms and file uploads.- This view handles both GET (display form) and POST (save changes) requests.+class TestEntityEditView(DualModeViewTestCase):+ """Enhanced tests for EntityEditView - comprehensive modal editing functionality.++ Tests cover the full entity attribute editing system including:+ - End-to-end form submission flows+ - File upload with DOM fragment updates+ - Entity type transition scenarios+ - Form validation error handling+ - HTMX response format validation"""def setUp(self):super().setUp()- # Create test entity- self.entity = Entity.objects.create(- integration_id='test.entity',- integration_name='test_integration',- name='Test Entity',- entity_type_str='LIGHT'+ # Create test data using synthetic data helper+ self.entity = EntityAttributeSyntheticData.create_test_entity(+ name='Test Edit Entity',+ entity_type_str=str(EntityType.LIGHT)+ )+ self.text_attr = EntityAttributeSyntheticData.create_test_text_attribute(+ entity=self.entity,+ name='brightness',+ value='100'+ )+ self.file_attr = EntityAttributeSyntheticData.create_test_file_attribute(+ entity=self.entity,+ name='manual')- def test_get_entity_edit_form(self):- """Test getting entity edit form."""+ def test_get_modal_displays_entity_edit_form(self):+ """Test that GET request displays entity edit modal with forms."""url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})response = self.client.get(url)+ self.assertSuccessResponse(response)+ self.assertHtmlResponse(response)+ self.assertTemplateRendered(response, 'entity/modals/entity_edit.html')++ # Verify context contains required forms and data+ self.assertEqual(response.context['entity'], self.entity)+ self.assertIn('entity_form', response.context)+ self.assertIn('regular_attributes_formset', response.context)+ self.assertIn('file_attributes', response.context)++ def test_get_modal_ajax_request(self):+ """Test that AJAX GET request returns JSON modal response."""+ url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})+ response = self.async_get(url)+self.assertSuccessResponse(response)self.assertJsonResponse(response)+ self.assertTemplateRendered(response, 'entity/modals/entity_edit.html')++ # HiModalView returns JSON with modal content for AJAX requests+ data = response.json()+ self.assertIn('modal', data)- def test_post_valid_entity_edit_with_formset(self):- """Test successful entity edit with formset data (full editing)."""+ def test_post_valid_entity_form_submission(self):+ """Test successful entity form submission with valid data."""url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})- # Prepare valid form data including required formset management forms- form_data = {- 'name': 'Updated Entity Name',- 'entity_type_str': 'wall_switch',- # Formset management forms (empty formset)- f'entity-{self.entity.id}-TOTAL_FORMS': '0',- f'entity-{self.entity.id}-INITIAL_FORMS': '0',- f'entity-{self.entity.id}-MIN_NUM_FORMS': '0',- f'entity-{self.entity.id}-MAX_NUM_FORMS': '1000',- }+ # Create form data for entity and attributes+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(+ entity=self.entity,+ name='Updated Entity Name',+ entity_type_str=str(EntityType.WALL_SWITCH)+ )- response = self.client.post(url, form_data)+ # Add formset data for existing attributes+ attributes = list(self.entity.attributes.all())+ formset_data = EntityAttributeSyntheticData.create_formset_data_for_attributes(+ attributes, self.entity+ )+ form_data.update(formset_data)+ response = self.client.post(url, form_data)+self.assertSuccessResponse(response)self.assertJsonResponse(response)- # Verify entity was actually updated+ # Verify entity was updatedself.entity.refresh_from_db()self.assertEqual(self.entity.name, 'Updated Entity Name')- self.assertEqual(self.entity.entity_type_str, 'wall_switch')+ self.assertEqual(self.entity.entity_type_str, str(EntityType.WALL_SWITCH))- def test_post_valid_entity_properties_only(self):- """Test successful entity properties edit via EntityPropertiesEditView."""+ def test_post_attribute_value_updates(self):+ """Test updating attribute values through formset."""+ url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})- url = reverse('entity_properties_edit', kwargs={'entity_id': self.entity.id})+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(+ entity=self.entity+ )- # 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)- }+ # Update attribute values in formset+ attributes = list(self.entity.attributes.all())+ formset_data = EntityAttributeSyntheticData.create_formset_data_for_attributes(+ attributes, self.entity+ )++ # Modify attribute values+ prefix = EntityEditFormHandler.get_formset_prefix(self.entity)+ for i, attr in enumerate(attributes):+ if attr == self.text_attr:+ formset_data[f'{prefix}-{i}-value'] = 'Updated brightness value'++ form_data.update(formset_data)response = self.client.post(url, form_data)++ self.assertSuccessResponse(response)++ # Verify attribute was updated+ self.text_attr.refresh_from_db()+ self.assertEqual(self.text_attr.value, 'Updated brightness value')++ def test_post_file_title_updates(self):+ """Test updating file attribute titles."""+ url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})++ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(+ entity=self.entity+ )++ # Add file title update data+ file_attrs = [self.file_attr]+ file_title_data = EntityAttributeSyntheticData.create_file_title_update_data(+ entity=self.entity,+ file_attributes=file_attrs+ )+ form_data.update(file_title_data)+ response = self.client.post(url, form_data)+self.assertSuccessResponse(response)- self.assertJsonResponse(response)- # Verify entity was actually updated+ # Verify file title was updated+ self.file_attr.refresh_from_db()+ self.assertEqual(self.file_attr.value, 'Updated manual')++ def test_post_file_deletions(self):+ """Test deleting file attributes."""+ url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})++ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(+ entity=self.entity+ )++ # Add file deletion data+ file_deletion_data = EntityAttributeSyntheticData.create_file_deletion_data(+ [self.file_attr]+ )+ form_data.update(file_deletion_data)++ response = self.client.post(url, form_data)++ self.assertSuccessResponse(response)++ # Verify file was deleted+ self.assertFalse(+ EntityAttribute.objects.filter(id=self.file_attr.id).exists()+ )++ def test_post_invalid_form_returns_errors(self):+ """Test that invalid form submission returns error response with form errors."""+ url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})++ # Submit invalid form data (empty name)+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(+ entity=self.entity,+ name='' # Invalid - name is required+ )++ response = self.client.post(url, form_data)++ # May return 200 with form errors or 400+ self.assertIn(response.status_code, [200, 400])++ # Verify entity was not updatedself.entity.refresh_from_db()- self.assertEqual(self.entity.name, 'Properties Only Update')- self.assertEqual(self.entity.entity_type_str, 'motion_sensor')+ self.assertNotEqual(self.entity.name, '')- # 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.+ def test_post_htmx_response_format(self):+ """Test that POST responses use correct HTMX/antinode format."""+ url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})++ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(+ entity=self.entity,+ name='Test HTMX Response'+ )++ attributes = list(self.entity.attributes.all())+ formset_data = EntityAttributeSyntheticData.create_formset_data_for_attributes(+ attributes, self.entity+ )+ form_data.update(formset_data)++ response = self.client.post(url, form_data)- # Transaction rollback test removed - Django's transaction.atomic() behavior- # is already tested by Django itself. Testing this would require complex mocking- # and tests Django internals rather than application behavior.+ self.assertSuccessResponse(response)+ self.assertJsonResponse(response)++ # Check antinode response structure+ data = response.json()+ self.assertTrue(+ any(key in data for key in ['insert', 'append', 'modal', 'refresh'])+ )++ def test_post_with_new_attribute_creation(self):+ """Test creating new attributes through the formset."""+ url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})++ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(+ entity=self.entity+ )++ # Create formset data with existing attributes plus new one using correct prefix+ existing_attrs = list(self.entity.attributes.all())+ prefix = EntityEditFormHandler.get_formset_prefix(self.entity)+ formset_data = {+ f'{prefix}-TOTAL_FORMS': str(len(existing_attrs) + 2), # +1 existing +1 new+ f'{prefix}-INITIAL_FORMS': str(len(existing_attrs)),+ f'{prefix}-MIN_NUM_FORMS': '0',+ f'{prefix}-MAX_NUM_FORMS': '1000',+ }++ # Add existing attributes+ for i, attr in enumerate(existing_attrs):+ formset_data.update({+ f'{prefix}-{i}-id': str(attr.id),+ f'{prefix}-{i}-name': attr.name,+ f'{prefix}-{i}-value': attr.value,+ f'{prefix}-{i}-attribute_type_str': attr.attribute_type_str,+ })++ # Add new attribute+ new_idx = len(existing_attrs)+ formset_data.update({+ f'{prefix}-{new_idx}-name': 'new_property',+ f'{prefix}-{new_idx}-value': 'new value',+ f'{prefix}-{new_idx}-attribute_type_str': str(AttributeValueType.TEXT),+ })++ form_data.update(formset_data)++ response = self.client.post(url, form_data)++ self.assertSuccessResponse(response)++ # Verify new attribute was created+ new_attr = self.entity.attributes.filter(name='new_property').first()+ self.assertIsNotNone(new_attr)+ self.assertEqual(new_attr.value, 'new value')++ def test_entity_with_complex_attribute_mix(self):+ """Test editing entity with mixed attribute types (text, file, secret)."""+ # Create entity with mixed attributes+ complex_entity = EntityAttributeSyntheticData.create_entity_with_mixed_attributes(+ name='Complex Test Entity'+ )++ url = reverse('entity_edit', kwargs={'entity_id': complex_entity.id})++ # Test GET request+ response = self.client.get(url)+ self.assertSuccessResponse(response)++ # Verify all attribute types are represented in context+ file_attrs = response.context['file_attributes']+ self.assertTrue(len(file_attrs) > 0)++ # Test POST with updates to mixed attributes+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(+ entity=complex_entity,+ name='Updated Complex Entity'+ )++ attributes = list(complex_entity.attributes.exclude(value_type_str=str(AttributeValueType.FILE)))+ formset_data = EntityAttributeSyntheticData.create_formset_data_for_attributes(+ attributes, self.entity+ )+ form_data.update(formset_data)++ response = self.client.post(url, form_data)+ self.assertSuccessResponse(response)++ # Verify entity was updated+ complex_entity.refresh_from_db()+ self.assertEqual(complex_entity.name, 'Updated Complex Entity')def test_nonexistent_entity_returns_404(self):"""Test that accessing nonexistent entity returns 404."""url = reverse('entity_edit', kwargs={'entity_id': 99999})response = self.client.get(url)-+ self.assertEqual(response.status_code, 404)++ response = self.client.post(url, {})self.assertEqual(response.status_code, 404)+ def test_database_transaction_handling(self):+ """Test that form submissions use proper database transactions."""+ url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})++ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(+ entity=self.entity,+ name='Transaction Test Name'+ )++ attributes = list(self.entity.attributes.all())+ formset_data = EntityAttributeSyntheticData.create_formset_data_for_attributes(+ attributes, self.entity+ )+ form_data.update(formset_data)++ with patch('django.db.transaction.atomic') as mock_atomic:+ mock_atomic.return_value = transaction.atomic()++ response = self.client.post(url, form_data)+ self.assertSuccessResponse(response)++ # Verify transaction.atomic was called+ self.assertGreaterEqual(mock_atomic.call_count, 1)++ # Verify update succeeded+ self.entity.refresh_from_db()+ self.assertEqual(self.entity.name, 'Transaction Test Name')+class TestEntityPropertiesEditView(SyncViewTestCase):"""@@ -114,7 +359,7 @@ class TestEntityPropertiesEditView(SyncViewTestCase):integration_id='test.entity.props',integration_name='test_integration',name='Test Properties Entity',- entity_type_str='LIGHT'+ entity_type_str=str(EntityType.LIGHT))def test_post_valid_properties_edit(self):@@ -123,7 +368,7 @@ class TestEntityPropertiesEditView(SyncViewTestCase):form_data = {'name': 'Updated Properties Name',- 'entity_type_str': 'wall_switch',+ 'entity_type_str': str(EntityType.WALL_SWITCH),}response = self.client.post(url, form_data)@@ -134,12 +379,12 @@ class TestEntityPropertiesEditView(SyncViewTestCase):# Verify entity was actually updatedself.entity.refresh_from_db()self.assertEqual(self.entity.name, 'Updated Properties Name')- self.assertEqual(self.entity.entity_type_str, 'wall_switch')+ self.assertEqual(self.entity.entity_type_str, str(EntityType.WALL_SWITCH).lower())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'})+ response = self.client.post(url, {'name': 'Test', 'entity_type_str': str(EntityType.LIGHT)})self.assertEqual(response.status_code, 404)@@ -164,17 +409,11 @@ class TestEntityAttributeUploadView(SyncViewTestCase):integration_id='test.entity',integration_name='test_integration',name='Test Entity',- entity_type_str='CAMERA'+ entity_type_str=str(EntityType.CAMERA))- @patch('hi.apps.entity.views.forms.EntityAttributeUploadForm')- def test_post_valid_file_upload(self, mock_form_class):- """Test successful file upload."""- # Mock valid form- mock_form = Mock()- mock_form.is_valid.return_value = True- mock_form_class.return_value = mock_form-+ def test_post_valid_file_upload(self):+ """Test successful file upload using real form."""# Create test filetest_file = SimpleUploadedFile("test_image.jpg",@@ -184,12 +423,12 @@ class TestEntityAttributeUploadView(SyncViewTestCase):url = reverse('entity_attribute_upload', kwargs={'entity_id': self.entity.id})response = self.client.post(url, {- 'name': 'Profile Image',- 'file': test_file+ 'file_value': test_file})self.assertSuccessResponse(response)- mock_form.save.assert_called_once()+ # Verify that an EntityAttribute was created+ self.assertTrue(self.entity.attributes.filter(file_value__isnull=False).exists())def test_post_invalid_file_upload(self):"""Test file upload with invalid form data."""@@ -205,14 +444,11 @@ class TestEntityAttributeUploadView(SyncViewTestCase):self.assertIn(response.status_code, [200, 400]) # Accept either valid response@patch('hi.apps.entity.views.transaction.atomic')- @patch('hi.apps.entity.views.forms.EntityAttributeUploadForm')- def test_upload_uses_transaction(self, mock_form_class, mock_atomic):+ def test_upload_uses_transaction(self, mock_atomic):"""Test that file upload uses database transaction."""- # Mock valid form- mock_form = Mock()- mock_form.is_valid.return_value = True- mock_form_class.return_value = mock_form-+ # Configure the mock to return the real transaction atomic context manager+ mock_atomic.return_value = transaction.atomic()+test_file = SimpleUploadedFile("test.txt",b"test content",@@ -221,12 +457,14 @@ class TestEntityAttributeUploadView(SyncViewTestCase):url = reverse('entity_attribute_upload', kwargs={'entity_id': self.entity.id})response = self.client.post(url, {- 'name': 'Test File',- 'file': test_file+ 'file_value': test_file})self.assertSuccessResponse(response)- mock_atomic.assert_called_once()+ # Verify that transaction.atomic was called (may be called multiple times due to nested transactions)+ self.assertGreaterEqual(mock_atomic.call_count, 1)+ # Verify that an EntityAttribute was created+ self.assertTrue(self.entity.attributes.filter(file_value__isnull=False).exists())def test_nonexistent_entity_returns_404(self):"""Test that uploading to nonexistent entity returns 404."""@@ -256,14 +494,14 @@ class TestEntityStatusView(DualModeViewTestCase):integration_id='test.entity',integration_name='test_integration',name='Test Entity',- entity_type_str='SENSOR'+ entity_type_str=str(EntityType.MOTION_SENSOR))# Create real EntityState data for StatusDisplayManager to processfrom hi.apps.entity.models import EntityStateself.entity_state = EntityState.objects.create(entity=self.entity,- entity_state_type_str='ON_OFF',+ entity_state_type_str=str(EntityStateType.ON_OFF),name='Power State')@@ -274,7 +512,7 @@ class TestEntityStatusView(DualModeViewTestCase):self.assertSuccessResponse(response)self.assertHtmlResponse(response)-+# The real StatusDisplayManager should process our entity# Since we don't have actual sensor data, it may delegate to edit view or show status# Either is acceptable - we're testing that mocks are removed and real objects work@@ -304,7 +542,7 @@ class TestEntityStatusView(DualModeViewTestCase):integration_id='test.no_states',integration_name='test_integration',name='Entity Without States',- entity_type_str='SENSOR'+ entity_type_str=str(EntityType.MOTION_SENSOR))url = reverse('entity_status', kwargs={'entity_id': entity_no_states.id})@@ -345,7 +583,7 @@ class TestEntityStateHistoryView(DualModeViewTestCase):integration_id='test.entity',integration_name='test_integration',name='Test Entity',- entity_type_str='THERMOSTAT'+ entity_type_str=str(EntityType.THERMOSTAT))def test_get_history_sync(self):@@ -412,9 +650,9 @@ class TestEntityStateHistoryView(DualModeViewTestCase):self.assertEqual(response.status_code, 405)-class TestEntityDetailsView(SyncViewTestCase):+class TestEntityEditModeView(SyncViewTestCase):"""- Tests for EntityDetailsView - demonstrates HiSideView testing.+ Tests for EntityEditModeView - demonstrates HiSideView testing.This view displays entity details in a side panel with location context."""@@ -425,7 +663,7 @@ class TestEntityDetailsView(SyncViewTestCase):integration_id='test.entity',integration_name='test_integration',name='Test Entity',- entity_type_str='LIGHT'+ entity_type_str=str(EntityType.LIGHT))# Create test location and location viewself.location = Location.objects.create(@@ -436,7 +674,7 @@ class TestEntityDetailsView(SyncViewTestCase):self.location_view = LocationView.objects.create(location=self.location,name='Test View',- location_view_type_str='MAIN',+ location_view_type_str=str(LocationViewType.DEFAULT), # MAIN doesn't exist, use DEFAULTsvg_view_box_str='0 0 100 100',svg_rotate=0.0)@@ -447,7 +685,7 @@ class TestEntityDetailsView(SyncViewTestCase):# This tests actual view functionality without complex mockingself.setSessionViewType(ViewType.LOCATION_VIEW)- url = reverse('entity_details', kwargs={'entity_id': self.entity.id})+ url = reverse('entity_edit_mode', kwargs={'entity_id': self.entity.id})response = self.client.get(url)# The view should either succeed or fail gracefully@@ -460,17 +698,17 @@ class TestEntityDetailsView(SyncViewTestCase):# Test with non-location view contextself.setSessionViewType(ViewType.CONFIGURATION)- url = reverse('entity_details', kwargs={'entity_id': self.entity.id})+ url = reverse('entity_edit_mode', kwargs={'entity_id': self.entity.id})response = self.client.get(url)# The view should handle this case appropriatelyself.assertIn(response.status_code, [200, 500]) # Accept either for nowdef test_details_should_push_url(self):- """Test that EntityDetailsView should push URL."""+ """Test that EntityEditModeView should push URL."""# Test that the view responds to URL requests appropriately# This tests the basic URL routing and view instantiation- url = reverse('entity_details', kwargs={'entity_id': self.entity.id})+ url = reverse('entity_edit_mode', kwargs={'entity_id': self.entity.id})response = self.client.get(url)# View should respond (may be 500 due to manager initialization issues)@@ -478,14 +716,14 @@ class TestEntityDetailsView(SyncViewTestCase):def test_nonexistent_entity_returns_404(self):"""Test that accessing nonexistent entity returns 404."""- url = reverse('entity_details', kwargs={'entity_id': 99999})+ url = reverse('entity_edit_mode', kwargs={'entity_id': 99999})response = self.client.get(url)self.assertEqual(response.status_code, 404)def test_post_not_allowed(self):"""Test that POST requests are not allowed."""- url = reverse('entity_details', kwargs={'entity_id': self.entity.id})+ url = reverse('entity_edit_mode', kwargs={'entity_id': self.entity.id})response = self.client.post(url)# May return 500 due to view processing issues before method check@@ -506,14 +744,14 @@ class TestEntityAttributeHistoryView(DualModeViewTestCase):integration_id='test.entity',integration_name='test_integration',name='Test Entity',- entity_type_str='LIGHT'+ entity_type_str=str(EntityType.LIGHT))# Create test attributeself.attribute = EntityAttribute.objects.create(entity=self.entity,name='brightness',value='100',- attribute_type_str='TEXT'+ attribute_type_str=str(AttributeValueType.TEXT))def test_get_history_sync(self):@@ -604,14 +842,14 @@ class TestEntityAttributeRestoreView(SyncViewTestCase):integration_id='test.entity',integration_name='test_integration',name='Test Entity',- entity_type_str='LIGHT'+ entity_type_str=str(EntityType.LIGHT))# Create test attributeself.attribute = EntityAttribute.objects.create(entity=self.entity,name='brightness',value='100',- attribute_type_str='TEXT'+ attribute_type_str=str(AttributeValueType.TEXT))@patch.object(EntityAttribute, '_get_history_model_class')@@ -678,3 +916,258 @@ class TestEntityAttributeRestoreView(SyncViewTestCase):response = self.client.get(url)self.assertEqual(response.status_code, 405)+++class TestEntityEditViewFileUploadIntegration(DualModeViewTestCase):+ """Integration tests for EntityEditView file upload flows.++ These tests verify the complete file upload workflow including:+ - File upload through EntityAttributeUploadView+ - DOM fragment updates via antinode responses+ - File management within EntityEditView+ - Error handling for invalid files+ """++ def setUp(self):+ super().setUp()+ self.entity = EntityAttributeSyntheticData.create_test_entity(+ name='File Upload Test Entity',+ entity_type_str=str(EntityType.CAMERA)+ )++ def test_file_upload_creates_attribute_and_updates_dom(self):+ """Test complete file upload flow from upload to DOM update."""+ # First verify entity has no files+ self.assertEqual(self.entity.attributes.filter(value_type_str=str(AttributeValueType.FILE)).count(), 0)++ # Upload a file+ test_file = EntityAttributeSyntheticData.create_test_image_file()+ upload_url = reverse('entity_attribute_upload', kwargs={'entity_id': self.entity.id})++ response = self.client.post(upload_url, {+ 'file_value': test_file+ })++ self.assertSuccessResponse(response)+ self.assertJsonResponse(response)++ # Verify file attribute was created+ file_attrs = self.entity.attributes.filter(value_type_str=str(AttributeValueType.FILE))+ self.assertEqual(file_attrs.count(), 1)++ file_attr = file_attrs.first()+ self.assertEqual(file_attr.name, 'test_image.jpg')+ self.assertEqual(file_attr.file_mime_type, 'image/jpeg')++ # Verify DOM update response structure+ data = response.json()+ self.assertIn('append', data)+ self.assertIn('scrollTo', data)++ def test_file_upload_error_handling(self):+ """Test file upload error handling and DOM error display."""+ upload_url = reverse('entity_attribute_upload', kwargs={'entity_id': self.entity.id})++ # Submit without file+ response = self.client.post(upload_url, {})++ # Should return error response+ self.assertEqual(response.status_code, 400)+ self.assertJsonResponse(response)++ # Verify error DOM update structure+ data = response.json()+ self.assertIn('insert', data)++ # Verify no file was created+ self.assertEqual(self.entity.attributes.filter(value_type_str=str(AttributeValueType.FILE)).count(), 0)++ def test_entity_edit_view_shows_uploaded_files(self):+ """Test that EntityEditView properly displays uploaded files."""+ # Create file attributes+ file1 = EntityAttributeSyntheticData.create_test_file_attribute(+ entity=self.entity,+ name='document1'+ )+ file2 = EntityAttributeSyntheticData.create_test_file_attribute(+ entity=self.entity,+ name='image1',+ file_value=EntityAttributeSyntheticData.create_test_image_file()+ )++ edit_url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})+ response = self.client.get(edit_url)++ self.assertSuccessResponse(response)++ # Verify file attributes are in context+ file_attributes = response.context['file_attributes']+ self.assertEqual(len(file_attributes), 2)++ file_attr_ids = [attr.id for attr in file_attributes]+ self.assertIn(file1.id, file_attr_ids)+ self.assertIn(file2.id, file_attr_ids)++ def test_file_deletion_through_entity_edit(self):+ """Test deleting files through EntityEditView."""+ # Create file attribute+ file_attr = EntityAttributeSyntheticData.create_test_file_attribute(+ entity=self.entity,+ name='test_delete_file'+ )++ edit_url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})++ # Submit deletion request+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(+ entity=self.entity+ )++ # Add file deletion data+ form_data.update(+ EntityAttributeSyntheticData.create_file_deletion_data([file_attr])+ )++ response = self.client.post(edit_url, form_data)++ self.assertSuccessResponse(response)++ # Verify file was deleted+ self.assertFalse(+ EntityAttribute.objects.filter(id=file_attr.id).exists()+ )++ def test_file_title_update_through_entity_edit(self):+ """Test updating file titles through EntityEditView."""+ # Create file attribute+ file_attr = EntityAttributeSyntheticData.create_test_file_attribute(+ entity=self.entity,+ name='original_file',+ value='Original Title'+ )++ edit_url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})++ # Submit title update+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(+ entity=self.entity+ )++ # Add file title update data+ form_data.update(+ EntityAttributeSyntheticData.create_file_title_update_data(+ entity=self.entity,+ file_attributes=[file_attr]+ )+ )++ response = self.client.post(edit_url, form_data)++ self.assertSuccessResponse(response)++ # Verify title was updated+ file_attr.refresh_from_db()+ self.assertEqual(file_attr.value, 'Updated original_file')++ def test_multiple_file_operations_in_single_request(self):+ """Test handling multiple file operations in one EntityEditView submission."""+ # Create test files+ file_to_delete = EntityAttributeSyntheticData.create_test_file_attribute(+ entity=self.entity,+ name='delete_me'+ )+ file_to_update = EntityAttributeSyntheticData.create_test_file_attribute(+ entity=self.entity,+ name='update_me',+ value='Old Title'+ )++ edit_url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})++ # Submit both deletion and title update+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(+ entity=self.entity+ )++ # Add both operations+ form_data.update(+ EntityAttributeSyntheticData.create_file_deletion_data([file_to_delete])+ )+ form_data.update(+ EntityAttributeSyntheticData.create_file_title_update_data(+ entity=self.entity,+ file_attributes=[file_to_update]+ )+ )++ response = self.client.post(edit_url, form_data)++ self.assertSuccessResponse(response)++ # Verify deletion occurred+ self.assertFalse(+ EntityAttribute.objects.filter(id=file_to_delete.id).exists()+ )++ # Verify title update occurred+ file_to_update.refresh_from_db()+ self.assertEqual(file_to_update.value, 'Updated update_me')++ def test_large_file_upload_handling(self):+ """Test handling of large file uploads."""+ large_file = EntityAttributeSyntheticData.create_large_text_file()+ upload_url = reverse('entity_attribute_upload', kwargs={'entity_id': self.entity.id})++ response = self.client.post(upload_url, {+ 'file_value': large_file+ })++ self.assertSuccessResponse(response)++ # Verify large file was handled correctly+ file_attrs = self.entity.attributes.filter(value_type_str=str(AttributeValueType.FILE))+ self.assertEqual(file_attrs.count(), 1)++ file_attr = file_attrs.first()+ self.assertEqual(file_attr.name, 'large_file.txt')+ self.assertEqual(file_attr.file_mime_type, 'text/plain')++ def test_pdf_file_upload_handling(self):+ """Test handling of PDF file uploads."""+ pdf_file = EntityAttributeSyntheticData.create_test_pdf_file()+ upload_url = reverse('entity_attribute_upload', kwargs={'entity_id': self.entity.id})++ response = self.client.post(upload_url, {+ 'file_value': pdf_file+ })++ self.assertSuccessResponse(response)++ # Verify PDF was handled correctly+ file_attrs = self.entity.attributes.filter(value_type_str=str(AttributeValueType.FILE))+ self.assertEqual(file_attrs.count(), 1)++ file_attr = file_attrs.first()+ self.assertEqual(file_attr.name, 'test_document.pdf')+ self.assertEqual(file_attr.file_mime_type, 'application/pdf')++ def test_file_upload_transaction_rollback_on_error(self):+ """Test that file upload transactions roll back properly on errors."""+ upload_url = reverse('entity_attribute_upload', kwargs={'entity_id': self.entity.id})++ # Create a scenario that might cause database errors+ with patch('hi.apps.entity.models.EntityAttribute.save') as mock_save:+ mock_save.side_effect = Exception("Simulated database error")++ test_file = EntityAttributeSyntheticData.create_test_image_file()++ # This should return an error response (500) but not raise an exception+ response = self.client.post(upload_url, {+ 'file_value': test_file+ })++ # Should return server error due to the exception+ self.assertEqual(response.status_code, 500)++ # Verify no file attributes were created due to transaction rollback+ self.assertEqual(self.entity.attributes.filter(value_type_str=str(AttributeValueType.FILE)).count(), 0)diff --git a/src/hi/apps/entity/transient_models.py b/src/hi/apps/entity/transient_models.pyindex 541a0fc4..2a968b77 100644--- a/src/hi/apps/entity/transient_models.py+++ b/src/hi/apps/entity/transient_models.py@@ -6,11 +6,7 @@ from hi.apps.entity.edit.forms import EntityPositionFormfrom hi.apps.sense.models import Sensor, SensorHistoryfrom .enums import EntityGroupType, EntityPairingType, VideoStreamType-from .forms import (- EntityAttributeFormSet,- EntityForm,- EntityAttributeUploadForm,-)+from .forms import EntityFormfrom .models import Entity@@ -59,62 +55,30 @@ class EntityPairing:@dataclass-class EntityEditData:- """ Data needed for editing the entity object and its attributes."""-- entity : Entity- entity_form : EntityForm = None- entity_attribute_formset : EntityAttributeFormSet = None- entity_attribute_upload_form : EntityAttributeUploadForm = None+class EntityEditModeData:+ """+ All the data needed about an entity to display in side bar during edit+ mode.+ """- def __post_init__(self):+ entity : Entity+ entity_form : EntityForm = None+ entity_position_form : EntityPositionForm = None+ entity_pairing_list : List[ EntityPairing ] = None+ def __post_init__(self):if not self.entity_form:self.entity_form = EntityForm(instance = self.entity,)- if not self.entity_attribute_formset:- self.entity_attribute_formset = EntityAttributeFormSet(- instance = self.entity,- prefix = f'entity-{self.entity.id}',- form_kwargs = {- 'show_as_editable': True,- },- )- if not self.entity_attribute_upload_form:- self.entity_attribute_upload_form = EntityAttributeUploadForm()-- returndef to_template_context(self):return {'entity': self.entity,'entity_form': self.entity_form,- 'entity_attribute_formset': self.entity_attribute_formset,- 'entity_attribute_upload_form': self.entity_attribute_upload_form,- 'history_url_name': 'entity_attribute_history',- 'restore_url_name': 'entity_attribute_restore',- }---@dataclass-class EntityDetailsData:- """- All the data needed about an entity to display in side bar during edit- mode.- """-- entity_edit_data : EntityEditData- entity_position_form : EntityPositionForm = None- entity_pairing_list : List[ EntityPairing ] = None-- def to_template_context(self):- context = {'entity_position_form': self.entity_position_form,'entity_pairing_list': self.entity_pairing_list,}- context.update( self.entity_edit_data.to_template_context() )- return context@dataclassdiff --git a/src/hi/apps/entity/urls.py b/src/hi/apps/entity/urls.pyindex 57c7ccc1..bfb84c60 100644--- a/src/hi/apps/entity/urls.py+++ b/src/hi/apps/entity/urls.py@@ -21,9 +21,9 @@ urlpatterns = [views.EntityStateHistoryView.as_view(),name='entity_state_history' ),- re_path( r'^details/(?P<entity_id>\d+)$',- views.EntityDetailsView.as_view(),- name='entity_details' ),+ re_path( r'^edit_mode/(?P<entity_id>\d+)$',+ views.EntityEditModeView.as_view(),+ name='entity_edit_mode' ),re_path( r'^attribute/upload/(?P<entity_id>\d+)$',views.EntityAttributeUploadView.as_view(),@@ -37,6 +37,14 @@ urlpatterns = [views.EntityAttributeRestoreView.as_view(),name='entity_attribute_restore'),+ re_path( r'^entity/(?P<entity_id>\d+)/attribute/(?P<attribute_id>\d+)/history/inline/$',+ views.EntityAttributeHistoryInlineView.as_view(),+ name='entity_attribute_history_inline'),++ re_path( r'^entity/(?P<entity_id>\d+)/attribute/(?P<attribute_id>\d+)/restore/inline/(?P<history_id>\d+)/$',+ views.EntityAttributeRestoreInlineView.as_view(),+ name='entity_attribute_restore_inline'),+re_path( r'^edit/', include('hi.apps.entity.edit.urls' )),]diff --git a/src/hi/apps/entity/view_mixins.py b/src/hi/apps/entity/view_mixins.pyindex 68264cc9..b50a26ec 100644--- a/src/hi/apps/entity/view_mixins.py+++ b/src/hi/apps/entity/view_mixins.py@@ -1,12 +1,7 @@from django.core.exceptions import BadRequest-from django.http import Http404, HttpRequest-from django.template.loader import get_template+from django.http import Http404-import hi.apps.common.antinode as antinodefrom hi.apps.entity.models import Entity-from hi.apps.entity.transient_models import EntityEditData--from hi.constants import DIVIDclass EntityViewMixin:@@ -21,30 +16,3 @@ class EntityViewMixin:return Entity.objects.get( id = entity_id )except Entity.DoesNotExist:raise Http404( request )-- 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()- 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.pyindex fc983ad0..2f369883 100644--- a/src/hi/apps/entity/views.py+++ b/src/hi/apps/entity/views.py@@ -1,161 +1,163 @@import logging+from typing import Any, Dict, Optional, TYPE_CHECKINGfrom django.db import transaction+from django.http import HttpRequest, HttpResponse+from django.shortcuts import render+from django.template.loader import get_template, render_to_stringfrom django.views.generic import View+from hi.apps.attribute.views import BaseAttributeHistoryView, BaseAttributeRestoreViewimport hi.apps.common.antinode as antinodefrom hi.apps.control.controller_history_manager import ControllerHistoryManagerfrom hi.apps.location.location_manager import LocationManagerfrom hi.apps.monitor.status_display_manager import StatusDisplayManagerfrom hi.apps.sense.sensor_history_manager import SensorHistoryMixin+from hi.views import page_not_found_responsefrom hi.hi_async_view import HiModalView, HiSideView-from hi.apps.attribute.views import BaseAttributeHistoryView, BaseAttributeRestoreView+from hi.constants import DIVID++from .entity_edit_form_handler import EntityEditFormHandler+from .entity_edit_response_renderer import EntityEditResponseRendererfrom .entity_manager import EntityManager+from .entity_type_transition_handler import EntityTypeTransitionHandlerfrom . import forms-from .models import EntityAttribute-from .transient_models import EntityEditData, EntityStateHistoryData+from .models import Entity, EntityAttribute+from .transient_models import EntityStateHistoryDatafrom .view_mixins import EntityViewMixin+if TYPE_CHECKING:+ from hi.apps.location.models import LocationView+logger = logging.getLogger(__name__)-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+class EntityStatusView( HiModalView, EntityViewMixin ):++ def get_template_name( self ) -> str:+ return 'entity/modals/entity_status.html'++ def get( self,+ request : HttpRequest,+ *args : Any,+ **kwargs: Any ) -> HttpResponse:+ entity: Entity = self.get_entity( request, *args, **kwargs )++ entity_status_data = StatusDisplayManager().get_entity_status_data( entity = entity )+ if not entity_status_data.entity_state_status_data_list:+ return EntityEditView().get( request, *args, **kwargs )- transition_response = None+ context: Dict[str, Any] = entity_status_data.to_template_context()+ return self.modal_response( request, context )+++class EntityEditView(HiModalView, EntityViewMixin):+ """Entity attribute editing modal with redesigned interface.++ This view uses a dual response pattern:+ - get(): Returns full modal using standard modal_response()+ - post(): Returns antinode fragments for async DOM updates++ Business logic is delegated to specialized handler classes following+ the "keep views simple" design philosophy.+ """++ def get_template_name(self) -> str:+ return 'entity/modals/entity_edit.html'++ def get( self,+ request : HttpRequest,+ *args : Any,+ **kwargs: Any ) -> HttpResponse:+ entity: Entity = self.get_entity(request, *args, **kwargs)- 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)+ # Delegate form creation and context building to handler+ form_handler: EntityEditFormHandler = EntityEditFormHandler()+ context: Dict[str, Any] = form_handler.create_initial_context(entity)- return transition_response+ return self.modal_response(request, context)- 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 post( self,+ request : HttpRequest,+ *args : Any,+ **kwargs: Any ) -> HttpResponse:+ entity: Entity = self.get_entity(request, *args, **kwargs)++ # Delegate form handling to specialized handlers+ form_handler: EntityEditFormHandler = EntityEditFormHandler()+ renderer: EntityEditResponseRenderer = EntityEditResponseRenderer()++ # Create forms with POST data+ entity_form, file_attributes, regular_attributes_formset = form_handler.create_entity_forms(+ entity, request.POST)-- 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++ if form_handler.validate_forms(entity_form, regular_attributes_formset):+ # Save forms and process files+ form_handler.save_forms(entity_form, regular_attributes_formset, request, entity)- except Exception as e:- logger.warning(f'EntityType transition failed: {e}, falling back to page refresh')- return antinode.refresh_response()+ # Return success response+ return renderer.render_success_response(request, entity)+ else:+ # Return error response+ return renderer.render_error_response(request, entity, entity_form, regular_attributes_formset)- 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+ def get_success_url_name(self) -> str:+ return 'entity_edit'++class EntityEditModeView( HiSideView, EntityViewMixin ):-class EntityEditView( BaseEntityEditMixin, View, EntityViewMixin ):- """Handle full entity editing including attributes - used by modal"""+ def get_template_name( self ) -> str:+ return 'entity/edit/panes/entity_edit_mode_panel.html'- def get( self, request, *args, **kwargs ):- entity = self.get_entity( request, *args, **kwargs )- entity_edit_data = EntityEditData( entity = entity )- return self.entity_modal_response(- request = request,- entity_edit_data = entity_edit_data,- )+ def should_push_url( self ) -> bool:+ return True- 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+ def get_template_context( self,+ request : HttpRequest,+ *args : Any,+ **kwargs: Any ) -> Dict[str, Any]:+ entity: Entity = self.get_entity( request, *args, **kwargs )- entity_form = forms.EntityForm( request.POST, instance = entity )- entity_attribute_formset = forms.EntityAttributeFormSet(- request.POST,- request.FILES,- instance = entity,- prefix = f'entity-{entity.id}',- )-- 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- )-- # Now that transaction is committed, handle any transition response- if transition_response is not None:- return transition_response-- # Recreate formset to preserve "max" to show new form- entity_attribute_formset = self._recreate_fresh_formset(entity)- status_code = 200- else:- status_code = 400-- entity_edit_data = EntityEditData(+ current_location_view: Optional['LocationView'] = None+ if request.view_parameters.view_type.is_location_view:+ current_location_view = LocationManager().get_default_location_view( request = request )++ entity_edit_mode_data = EntityManager().get_entity_edit_mode_data(entity = entity,- entity_form = entity_form,- entity_attribute_formset = entity_attribute_formset,- )- return self.entity_modal_response(- request = request,- entity_edit_data = entity_edit_data,- status_code = status_code,+ location_view = current_location_view,+ is_editing = request.view_parameters.is_editing,)+ return entity_edit_mode_data.to_template_context()--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 )++class EntityPropertiesEditView( View, EntityViewMixin ):+ """Handle entity properties editing (name, type) only - used by sidebar.++ Business logic is delegated to EntityTypeTransitionHandler following+ the "keep views simple" design philosophy.+ """++ def post( self,+ request : HttpRequest,+ *args : Any,+ **kwargs: Any ) -> HttpResponse:+ entity: Entity = self.get_entity( request, *args, **kwargs )# Store original entity_type_str to detect changes- original_entity_type_str = entity.entity_type_str+ original_entity_type_str: str = entity.entity_type_str- entity_form = forms.EntityForm( request.POST, instance = entity )- form_valid = entity_form.is_valid()+ entity_form: forms.EntityForm = forms.EntityForm( request.POST, instance = entity )+ form_valid: bool = entity_form.is_valid()if form_valid:- transition_response = self._handle_entity_form_save(+ # Delegate transition handling to specialized handler+ transition_handler = EntityTypeTransitionHandler()++ transition_response: Optional[HttpResponse] = transition_handler.handle_entity_form_save(request, entity, entity_form, None, original_entity_type_str)@@ -163,68 +165,24 @@ class EntityPropertiesEditView( BaseEntityEditMixin, View, EntityViewMixin ):if transition_response is not None:return transition_response- status_code = 200+ status_code: int = 200else:- status_code = 400-- # 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 ):-- def post( self, request, *args, **kwargs ):- entity = self.get_entity( request, *args, **kwargs )- entity_attribute = EntityAttribute( entity = entity )- entity_attribute_upload_form = forms.EntityAttributeUploadForm(- request.POST,- request.FILES,- instance = entity_attribute,+ status_code: int = 400++ context: Dict[str, Any] = {+ 'entity': entity,+ 'entity_form': entity_form,+ }+ template = get_template( 'entity/edit/panes/entity_properties_edit.html' )+ content: str = template.render( context, request = request )+ return antinode.response(+ insert_map = {+ DIVID['ENTITY_PROPERTIES_PANE']: content,+ },+ status = status_code,)-- if entity_attribute_upload_form.is_valid():- with transaction.atomic():- entity_attribute_upload_form.save()- status_code = 200- else:- status_code = 400-- entity_edit_data = EntityEditData(- entity = entity,- entity_attribute_upload_form = entity_attribute_upload_form,- )- return self.entity_modal_response(- request = request,- entity_edit_data = entity_edit_data,- status_code = status_code,- )--class EntityStatusView( HiModalView, EntityViewMixin ):-- def get_template_name( self ) -> str:- return 'entity/modals/entity_status.html'-- def get( self, request, *args, **kwargs ):- entity = self.get_entity( request, *args, **kwargs )-- entity_status_data = StatusDisplayManager().get_entity_status_data( entity = entity )- if not entity_status_data.entity_state_status_data_list:- return EntityEditView().get( request, *args, **kwargs )- context = entity_status_data.to_template_context()- return self.modal_response( request, context )--class EntityStateHistoryView( HiModalView, EntityViewMixin, SensorHistoryMixin ):ENTITY_STATE_HISTORY_ITEM_MAX = 5@@ -232,8 +190,11 @@ class EntityStateHistoryView( HiModalView, EntityViewMixin, SensorHistoryMixin )def get_template_name( self ) -> str:return 'entity/modals/entity_state_history.html'- def get( self, request, *args, **kwargs ):- entity = self.get_entity( request, *args, **kwargs )+ def get( self,+ request : HttpRequest,+ *args : Any,+ **kwargs: Any ) -> HttpResponse:+ entity: Entity = self.get_entity( request, *args, **kwargs )sensor_history_list_map = self.sensor_history_manager().get_latest_entity_sensor_history(entity = entity,max_items = self.ENTITY_STATE_HISTORY_ITEM_MAX,@@ -247,33 +208,59 @@ class EntityStateHistoryView( HiModalView, EntityViewMixin, SensorHistoryMixin )sensor_history_list_map = sensor_history_list_map,controller_history_list_map = controller_history_list_map,)- context = entity_state_history_data.to_template_context()+ context: Dict[str, Any] = entity_state_history_data.to_template_context()return self.modal_response( request, context )-class EntityDetailsView( HiSideView, EntityViewMixin ):-- def get_template_name( self ) -> str:- return 'entity/edit/panes/entity_edit_mode_panel.html'-- def should_push_url( self ):- return True-- def get_template_context( self, request, *args, **kwargs ):- entity = self.get_entity( request, *args, **kwargs )-- current_location_view = None- if request.view_parameters.view_type.is_location_view:- current_location_view = LocationManager().get_default_location_view( request = request )+class EntityAttributeUploadView( View, EntityViewMixin ):- entity_details_data = EntityManager().get_entity_details_data(- entity = entity,- location_view = current_location_view,- is_editing = request.view_parameters.is_editing,+ def post( self,+ request : HttpRequest,+ *args : Any,+ **kwargs: Any ) -> HttpResponse:+ entity: Entity = self.get_entity( request, *args, **kwargs )+ entity_attribute: EntityAttribute = EntityAttribute( entity = entity )+ entity_attribute_upload_form: forms.EntityAttributeUploadForm = forms.EntityAttributeUploadForm(+ request.POST,+ request.FILES,+ instance = entity_attribute,)- return entity_details_data.to_template_context()-++ if entity_attribute_upload_form.is_valid():+ with transaction.atomic():+ entity_attribute_upload_form.save()++ # Render new file card HTML to append to file grid+ file_card_html: str = render_to_string(+ 'attribute/components/file_card.html',+ {'attribute': entity_attribute, 'entity': entity},+ request=request+ )++ return antinode.response(+ append_map={+ DIVID['ATTR_V2_FILE_GRID']: file_card_html+ },+ scroll_to=DIVID['ATTR_V2_FILE_GRID']+ )+ else:+ # Render error message to status area+ error_html: str = render_to_string(+ 'attribute/components/status_message.html',+ {+ 'error_message': 'File upload failed. Please check the file and try again.',+ 'form_errors': entity_attribute_upload_form.errors+ }+ )++ return antinode.response(+ insert_map={+ DIVID['ATTR_V2_STATUS_MSG']: error_html+ },+ status=400+ )+class EntityAttributeHistoryView(BaseAttributeHistoryView):"""View for displaying EntityAttribute history in a modal."""@@ -292,3 +279,97 @@ class EntityAttributeRestoreView(BaseAttributeRestoreView):def get_attribute_model_class(self):return EntityAttribute+++class EntityAttributeHistoryInlineView(BaseAttributeHistoryView):+ """View for displaying EntityAttribute history inline within the edit modal."""++ ATTRIBUTE_HISTORY_VIEW_LIMIT = 50++ def get_template_name(self):+ return 'attribute/components/attribute_history_inline.html'++ def get_attribute_model_class(self):+ return EntityAttribute++ def get_history_url_name(self):+ return 'entity_attribute_history_inline'++ def get_restore_url_name(self):+ return 'entity_attribute_restore_inline'++ def get( self,+ request : HttpRequest,+ entity_id : int,+ attribute_id : int,+ *args : Any,+ **kwargs : Any ) -> HttpResponse:+ # Validate that the attribute belongs to this entity for security+ try:+ attribute: EntityAttribute = EntityAttribute.objects.get(pk=attribute_id, entity_id=entity_id)+ except EntityAttribute.DoesNotExist:+ return page_not_found_response(request, "Attribute not found.")++ # Get history records for this attribute+ history_model_class = attribute._get_history_model_class()+ if history_model_class:+ history_records = history_model_class.objects.filter(+ attribute=attribute+ ).order_by('-changed_datetime')[:self.ATTRIBUTE_HISTORY_VIEW_LIMIT] # Limit for inline display+ else:+ history_records = []++ context: Dict[str, Any] = {+ 'entity': attribute.entity,+ 'attribute': attribute,+ 'history_records': history_records,+ 'history_url_name': self.get_history_url_name(),+ 'restore_url_name': self.get_restore_url_name(),+ }++ # Use Django render shortcut+ return render(request, self.get_template_name(), context)+++class EntityAttributeRestoreInlineView(BaseAttributeRestoreView):+ """View for restoring EntityAttribute values from history within the edit modal."""++ def get_attribute_model_class(self):+ return EntityAttribute++ def get( self,+ request : HttpRequest,+ entity_id : int,+ attribute_id : int,+ history_id : int,+ *args : Any,+ **kwargs : Any ) -> HttpResponse:+ # Validate that the attribute belongs to this entity for security+ try:+ attribute: EntityAttribute = EntityAttribute.objects.get(pk=attribute_id, entity_id=entity_id)+ except EntityAttribute.DoesNotExist:+ return page_not_found_response(request, "Attribute not found.")++ # Get the history record to restore from+ history_model_class = attribute._get_history_model_class()+ if not history_model_class:+ return page_not_found_response(request, "No history available for this attribute type.")++ try:+ history_record = history_model_class.objects.get(pk=history_id, attribute=attribute)+ except history_model_class.DoesNotExist:+ return page_not_found_response(request, "History record not found.")++ # Restore the value from the history record+ attribute.value = history_record.value+ attribute.save() # This will create a new history record++ # Delegate to EntityEditView logic to return updated modal content+ entity: Entity = attribute.entity++ # Use EntityEditView's _render_success_response logic+ entity_edit_view: EntityEditView = EntityEditView()+ return entity_edit_view._render_success_response(+ request = request,+ entity = entity,+ )diff --git a/src/hi/apps/event/edit/tests/__init__.py b/src/hi/apps/event/edit/tests/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/apps/location/edit/tests/__init__.py b/src/hi/apps/location/edit/tests/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/apps/location/edit/tests/test_views.py b/src/hi/apps/location/edit/tests/test_views.pyindex 389d960d..b0ce0c27 100644--- a/src/hi/apps/location/edit/tests/test_views.py+++ b/src/hi/apps/location/edit/tests/test_views.py@@ -1,16 +1,14 @@-import jsonimport logging-from unittest.mock import Mock, patch-from django.core.exceptions import BadRequest+from django.core.files.uploadedfile import SimpleUploadedFilefrom django.urls import reversefrom hi.apps.collection.collection_manager import CollectionManager-from hi.apps.collection.models import Collectionfrom hi.apps.entity.entity_manager import EntityManager-from hi.apps.entity.models import Entity+from hi.apps.entity.enums import EntityTypefrom hi.apps.location.location_manager import LocationManagerfrom hi.apps.location.models import Location, LocationView+from hi.apps.location.tests.synthetic_data import LocationSyntheticDatafrom hi.enums import ItemType, ViewModefrom hi.testing.view_test_base import SyncViewTestCase, DualModeViewTestCase@@ -28,6 +26,23 @@ class TestLocationAddView(DualModeViewTestCase):# Set edit mode (required by decorator)self.setSessionViewMode(ViewMode.EDIT)+ def tearDown(self):+ """Clean up singletons when using real objects instead of mocks."""+ # Reset singleton managers to ensure clean state between tests+ try:+ LocationManager._instance = None+ except ImportError:+ pass+ try:+ CollectionManager._instance = None+ except ImportError:+ pass+ try:+ EntityManager._instance = None+ except ImportError:+ pass+ super().tearDown()+def test_get_location_add_form(self):"""Test getting location add form."""url = reverse('location_edit_location_add')@@ -114,23 +129,22 @@ class TestLocationAddView(DualModeViewTestCase):self.assertEqual(len(location_views), 1)self.assertEqual(location_views[0].location, new_location)- @patch.object(LocationManager, 'create_location')- @patch('hi.apps.location.edit.forms.LocationAddForm')- def test_post_create_location_error(self, mock_form_class, mock_create_location):- """Test POST request when location creation fails."""- # Mock valid form- mock_form = Mock()- mock_form.is_valid.return_value = True- mock_form.cleaned_data = {'name': 'Test Location'}- mock_form_class.return_value = mock_form-- # Mock location manager raising error- mock_create_location.side_effect = ValueError("Invalid SVG")-+ def test_post_create_location_error(self):+ """Test POST request when location creation fails due to invalid data."""url = reverse('location_edit_location_add')- response = self.client.post(url, {'name': 'Test Location'})++ # Provide invalid data that should cause form validation to fail+ response = self.client.post(url, {+ 'name': '', # Empty name should cause validation error+ # Missing required fields like SVG file+ })- self.assertEqual(response.status_code, 400)+ # Should return error response (400 or form validation error)+ # The exact status code depends on how the view handles validation errors+ self.assertIn(response.status_code, [200, 400]) # 200 if form errors shown, 400 if bad request++ # Verify no location was created when form validation fails+ self.assertEqual(Location.objects.filter(name='').count(), 0)class TestLocationAddFirstView(DualModeViewTestCase):@@ -146,7 +160,7 @@ class TestLocationAddFirstView(DualModeViewTestCase):def test_get_location_add_first_form(self):"""Test getting first location add form."""- url = reverse('location_add_first')+ url = reverse('location_edit_location_add_first')response = self.client.get(url)self.assertSuccessResponse(response)@@ -179,7 +193,7 @@ class TestLocationSvgReplaceView(DualModeViewTestCase):def test_get_svg_replace_form(self):"""Test getting SVG replace form."""- url = reverse('location_svg_replace', kwargs={'location_id': self.location.id})+ url = reverse('location_edit_svg_replace', kwargs={'location_id': self.location.id})response = self.client.get(url)self.assertSuccessResponse(response)@@ -190,7 +204,7 @@ class TestLocationSvgReplaceView(DualModeViewTestCase):def test_get_svg_replace_form_async(self):"""Test getting SVG replace form with AJAX request."""- url = reverse('location_svg_replace', kwargs={'location_id': self.location.id})+ url = reverse('location_edit_svg_replace', kwargs={'location_id': self.location.id})response = self.async_get(url)self.assertSuccessResponse(response)@@ -200,65 +214,63 @@ class TestLocationSvgReplaceView(DualModeViewTestCase):data = response.json()self.assertIn('modal', data)- @patch('hi.apps.location.edit.forms.LocationSvgReplaceForm')- def test_post_invalid_form(self, mock_form_class):+ def test_post_invalid_form(self):"""Test POST request with invalid form data."""- # Mock invalid form- mock_form = Mock()- mock_form.is_valid.return_value = False- mock_form_class.return_value = mock_form-- url = reverse('location_svg_replace', kwargs={'location_id': self.location.id})- response = self.client.post(url, {})+ url = reverse('location_edit_svg_replace', kwargs={'location_id': self.location.id})+ response = self.client.post(url, {+ # No SVG file provided - should cause form validation to fail+ })+ # Should return success but with form errorsself.assertSuccessResponse(response)- # Should render form with errors- self.assertEqual(response.context['location_svg_file_form'], mock_form)+ # Should render form with validation errors+ form = response.context['location_svg_file_form']+ self.assertFalse(form.is_valid())- @patch.object(LocationManager, 'update_location_svg')- @patch.object(LocationManager, 'get_location')- @patch('hi.apps.location.edit.forms.LocationSvgReplaceForm')- @patch('hi.apps.common.antinode.redirect_response')- def test_post_valid_form(self, mock_redirect, mock_form_class, mock_get_location, mock_update_svg):+ def test_post_valid_form(self):"""Test POST request with valid form data."""- # Mock get_location- mock_get_location.return_value = self.location-- # Mock valid form- mock_form = Mock()- mock_form.is_valid.return_value = True- mock_form.cleaned_data = {- 'svg_fragment_filename': 'new.svg',- 'svg_fragment_content': '<svg>new</svg>',- 'svg_viewbox': '0 0 200 200'- }- mock_form_class.return_value = mock_form-- # Mock SVG update- mock_update_svg.return_value = self.location- mock_redirect.return_value = 'redirect_response'-- url = reverse('location_svg_replace', kwargs={'location_id': self.location.id})- _ = self.client.post(url, {})-- # Should update SVG and redirect- mock_update_svg.assert_called_once_with(- location=self.location,- svg_fragment_filename='new.svg',- svg_fragment_content='<svg>new</svg>',- svg_viewbox='0 0 200 200'+ # Create a simple SVG file for upload+ svg_content = b'<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"><rect width="200" height="200" fill="blue"/></svg>'+ svg_file = SimpleUploadedFile(+ 'new_location.svg',+ svg_content,+ content_type='image/svg+xml')++ # Store original values to verify change+ original_filename = self.location.svg_fragment_filename+ original_viewbox = self.location.svg_view_box_str++ url = reverse('location_edit_svg_replace', kwargs={'location_id': self.location.id})+ response = self.client.post(url, {+ 'svg_file': svg_file,+ 'remove_dangerous_svg_items': False,+ 'has_dangerous_svg_items': 'false'+ })- def test_post_invalid_location_id(self):- """Test POST request with invalid location ID."""- url = reverse('location_svg_replace', kwargs={'location_id': 'invalid'})- response = self.client.post(url, {})-- self.assertEqual(response.status_code, 400)+ # Should return redirect response for antinode.js+ self.assertSuccessResponse(response)+ self.assertJsonResponse(response)++ # Verify the response contains the redirect+ response_data = response.json()+ expected_url = reverse('home')+ self.assertEqual(response_data['location'], expected_url)++ # Refresh from database to get updated values+ self.location.refresh_from_db()++ # Verify the location's SVG was updated+ self.assertNotEqual(self.location.svg_fragment_filename, original_filename)+ # The viewbox might be normalized to include decimals+ self.assertIn('200', self.location.svg_view_box_str)+ self.assertNotEqual(self.location.svg_view_box_str, original_viewbox)+ # The filename should contain 'new_location' from our uploaded file+ self.assertIn('new_location', self.location.svg_fragment_filename)def test_nonexistent_location_returns_404(self):"""Test that accessing nonexistent location returns 404."""- url = reverse('location_svg_replace', kwargs={'location_id': 99999})+ url = reverse('location_edit_svg_replace', kwargs={'location_id': 99999})response = self.client.get(url)self.assertEqual(response.status_code, 404)@@ -272,8 +284,8 @@ class TestLocationEditView(SyncViewTestCase):def setUp(self):super().setUp()- # Create test location- self.location = Location.objects.create(+ # Create test location using synthetic data+ self.location = LocationSyntheticData.create_test_location(name='Test Location',svg_fragment_filename='test.svg',svg_view_box_str='0 0 100 100'@@ -281,78 +293,85 @@ class TestLocationEditView(SyncViewTestCase):def test_get_location_edit(self):"""Test GET request for location edit."""- url = reverse('location_edit', kwargs={'location_id': self.location.id})+ url = reverse('location_edit_location_edit', kwargs={'location_id': self.location.id})response = self.client.get(url)self.assertSuccessResponse(response)- self.assertHtmlResponse(response)+ self.assertJsonResponse(response) # LocationEditView returns JSON modal- @patch('hi.apps.location.edit.forms.LocationEditForm')- @patch('hi.apps.location.edit.forms.LocationAttributeFormSet')- @patch('hi.apps.common.antinode.refresh_response')- def test_post_valid_edit_with_changes(self, mock_refresh, mock_formset_class, mock_form_class):+ def test_post_valid_edit_with_changes(self):"""Test POST request with valid edit data that has changes."""- # Mock valid forms with changes- mock_form = Mock()- mock_form.is_valid.return_value = True- mock_form.has_changed.return_value = True- mock_form_class.return_value = mock_form-- mock_formset = Mock()- mock_formset.is_valid.return_value = True- mock_formset_class.return_value = mock_formset-- mock_refresh.return_value = 'refresh_response'-- url = reverse('location_edit', kwargs={'location_id': self.location.id})- _ = self.client.post(url, {'name': 'Updated Location'})+ original_name = self.location.name++ url = reverse('location_edit_location_edit', kwargs={'location_id': self.location.id})+ formset_prefix = f'location-{self.location.id}'+ response = self.client.post(url, {+ 'name': 'Updated Location Name',+ 'order_id': '0', # Required field+ 'svg_view_box_str': self.location.svg_view_box_str, # Keep original+ # Add formset management form fields with correct prefix+ f'{formset_prefix}-TOTAL_FORMS': '0',+ f'{formset_prefix}-INITIAL_FORMS': '0',+ f'{formset_prefix}-MIN_NUM_FORMS': '0',+ f'{formset_prefix}-MAX_NUM_FORMS': '1000',+ })- mock_form.save.assert_called_once()- mock_formset.save.assert_called_once()- mock_refresh.assert_called_once()+ # Expect antinode.js response (200 with JSON)+ self.assertEqual(response.status_code, 200)++ # Verify the location was actually updated+ updated_location = Location.objects.get(id=self.location.id)+ self.assertEqual(updated_location.name, 'Updated Location Name')+ self.assertNotEqual(updated_location.name, original_name)- @patch('hi.apps.location.edit.forms.LocationEditForm')- @patch('hi.apps.location.edit.forms.LocationAttributeFormSet')- def test_post_valid_edit_without_changes(self, mock_formset_class, mock_form_class):+ def test_post_valid_edit_without_changes(self):"""Test POST request with valid edit data that has no changes."""- # Mock valid forms without changes- mock_form = Mock()- mock_form.is_valid.return_value = True- mock_form.has_changed.return_value = False- mock_form_class.return_value = mock_form-- mock_formset = Mock()- mock_formset.is_valid.return_value = True- mock_formset_class.return_value = mock_formset-- url = reverse('location_edit', kwargs={'location_id': self.location.id})- response = self.client.post(url, {'name': 'Same Name'})+ # Submit the same data that already exists (no changes)+ url = reverse('location_edit_location_edit', kwargs={'location_id': self.location.id})+ formset_prefix = f'location-{self.location.id}'+ response = self.client.post(url, {+ 'name': self.location.name, # Same name - no change+ 'order_id': '0', # Required field+ 'svg_view_box_str': self.location.svg_view_box_str, # Same viewbox+ # Add formset management form fields with correct prefix+ f'{formset_prefix}-TOTAL_FORMS': '0',+ f'{formset_prefix}-INITIAL_FORMS': '0',+ f'{formset_prefix}-MIN_NUM_FORMS': '0',+ f'{formset_prefix}-MAX_NUM_FORMS': '1000',+ })- self.assertSuccessResponse(response)- # Should not refresh if no changes+ # Expect antinode.js response (200 with JSON)+ self.assertEqual(response.status_code, 200)++ # Verify location was not changed (same name)+ unchanged_location = Location.objects.get(id=self.location.id)+ self.assertEqual(unchanged_location.name, self.location.name)- @patch('hi.apps.location.edit.forms.LocationEditForm')- @patch('hi.apps.location.edit.forms.LocationAttributeFormSet')- def test_post_invalid_edit(self, mock_formset_class, mock_form_class):+ def test_post_invalid_edit(self):"""Test POST request with invalid edit data."""- # Mock invalid forms- mock_form = Mock()- mock_form.is_valid.return_value = False- mock_form_class.return_value = mock_form-- mock_formset = Mock()- mock_formset.is_valid.return_value = True- mock_formset_class.return_value = mock_formset-- url = reverse('location_edit', kwargs={'location_id': self.location.id})- response = self.client.post(url, {'name': ''})+ url = reverse('location_edit_location_edit', kwargs={'location_id': self.location.id})+ formset_prefix = f'location-{self.location.id}'+ response = self.client.post(url, {+ 'name': '', # Empty name should cause validation error+ 'order_id': '0', # Required field+ 'svg_view_box_str': self.location.svg_view_box_str,+ # Add formset management fields (even though the form has errors)+ f'{formset_prefix}-TOTAL_FORMS': '0',+ f'{formset_prefix}-INITIAL_FORMS': '0',+ f'{formset_prefix}-MIN_NUM_FORMS': '0',+ f'{formset_prefix}-MAX_NUM_FORMS': '1000',+ })- self.assertEqual(response.status_code, 400)- mock_form.save.assert_not_called()+ # Should return 200 with form errors displayed+ self.assertEqual(response.status_code, 200)++ # Verify location was not changed+ unchanged_location = Location.objects.get(id=self.location.id)+ self.assertEqual(unchanged_location.name, self.location.name) # Should remain unchangeddef test_nonexistent_location_returns_404(self):"""Test that accessing nonexistent location returns 404."""- url = reverse('location_edit', kwargs={'location_id': 99999})+ url = reverse('location_edit_location_edit', kwargs={'location_id': 99999})response = self.client.get(url)self.assertEqual(response.status_code, 404)@@ -417,40 +436,67 @@ class TestLocationAttributeUploadView(SyncViewTestCase):def setUp(self):super().setUp()- # Create test location- self.location = Location.objects.create(+ # Create test location using synthetic data+ self.location = LocationSyntheticData.create_test_location(name='Test Location',svg_fragment_filename='test.svg',svg_view_box_str='0 0 100 100')- @patch('hi.apps.location.edit.forms.LocationAttributeUploadForm')- def test_post_valid_upload(self, mock_form_class):+ def test_post_valid_upload(self):"""Test POST request with valid upload data."""- # Mock valid form- mock_form = Mock()- mock_form.is_valid.return_value = True- mock_form_class.return_value = mock_form-url = reverse('location_attribute_upload', kwargs={'location_id': self.location.id})- response = self.client.post(url, {})-++ # Create test file+ test_file = SimpleUploadedFile(+ 'test_document.pdf',+ b'fake pdf content for testing',+ content_type='application/pdf'+ )++ # Post with file_value field+ response = self.client.post(url, {'file_value': test_file})+self.assertSuccessResponse(response)- mock_form.save.assert_called_once()+ self.assertJsonResponse(response)++ # Verify the attribute was created with name from filename+ from hi.apps.location.models import LocationAttribute+ uploaded_attr = LocationAttribute.objects.filter(+ location=self.location,+ name='test_document.pdf' # Full filename is used as name+ ).first()+ self.assertIsNotNone(uploaded_attr)+ # File uploads don't have a text value, they have file_value+ self.assertTrue(uploaded_attr.file_value)- @patch('hi.apps.location.edit.forms.LocationAttributeUploadForm')- def test_post_invalid_upload(self, mock_form_class):+ def test_post_invalid_upload(self):"""Test POST request with invalid upload data."""- # Mock invalid form- mock_form = Mock()- mock_form.is_valid.return_value = False- mock_form_class.return_value = mock_form-url = reverse('location_attribute_upload', kwargs={'location_id': self.location.id})- response = self.client.post(url, {})-- self.assertEqual(response.status_code, 400)- mock_form.save.assert_not_called()++ # Send invalid data - missing required file_value+ test_data = {}+ # No files provided - file_value is required++ response = self.client.post(url, data=test_data)++ # Form is invalid but view returns 200 with modal containing form errors+ self.assertSuccessResponse(response)+ self.assertJsonResponse(response)++ # Verify response contains modal with form+ data = response.json()+ self.assertIn('modal', data)+ modal_content = data['modal']+ self.assertIn('file_value', modal_content) # Form field should be present++ # Verify no attribute was created+ from hi.apps.location.models import LocationAttribute+ uploaded_attrs = LocationAttribute.objects.filter(+ location=self.location,+ name='test_document'+ )+ self.assertEqual(uploaded_attrs.count(), 0)def test_nonexistent_location_returns_404(self):"""Test that accessing nonexistent location returns 404."""@@ -478,8 +524,8 @@ class TestLocationDeleteView(DualModeViewTestCase):# Set edit mode (required by decorator)self.setSessionViewMode(ViewMode.EDIT)- # Create test location- self.location = Location.objects.create(+ # Create test location using synthetic data+ self.location = LocationSyntheticData.create_test_location(name='Test Location',svg_fragment_filename='test.svg',svg_view_box_str='0 0 100 100'@@ -487,7 +533,7 @@ class TestLocationDeleteView(DualModeViewTestCase):def test_get_location_delete_confirmation(self):"""Test getting location delete confirmation."""- url = reverse('location_delete', kwargs={'location_id': self.location.id})+ url = reverse('location_edit_location_delete', kwargs={'location_id': self.location.id})response = self.client.get(url)self.assertSuccessResponse(response)@@ -497,7 +543,7 @@ class TestLocationDeleteView(DualModeViewTestCase):def test_get_location_delete_async(self):"""Test getting location delete confirmation with AJAX request."""- url = reverse('location_delete', kwargs={'location_id': self.location.id})+ url = reverse('location_edit_location_delete', kwargs={'location_id': self.location.id})response = self.async_get(url)self.assertSuccessResponse(response)@@ -509,29 +555,29 @@ class TestLocationDeleteView(DualModeViewTestCase):def test_post_delete_without_confirmation(self):"""Test POST request without confirmation."""- url = reverse('location_delete', kwargs={'location_id': self.location.id})+ url = reverse('location_edit_location_delete', kwargs={'location_id': self.location.id})response = self.client.post(url, {})self.assertEqual(response.status_code, 400)def test_post_delete_with_wrong_confirmation(self):"""Test POST request with wrong confirmation value."""- url = reverse('location_delete', kwargs={'location_id': self.location.id})+ url = reverse('location_edit_location_delete', kwargs={'location_id': self.location.id})response = self.client.post(url, {'action': 'cancel'})self.assertEqual(response.status_code, 400)- @patch.object(LocationManager, 'get_location')- def test_post_delete_with_confirmation(self, mock_get_location):+ def test_post_delete_with_confirmation(self):"""Test POST request with proper confirmation."""- mock_get_location.return_value = self.location-- url = reverse('location_delete', kwargs={'location_id': self.location.id})+ url = reverse('location_edit_location_delete', kwargs={'location_id': self.location.id})response = self.client.post(url, {'action': 'confirm'})- self.assertEqual(response.status_code, 302)+ # HiModalView returns JSON redirect response for antinode.js+ self.assertEqual(response.status_code, 200)+ self.assertJsonResponse(response)+ response_data = response.json()expected_url = reverse('home')- self.assertEqual(response.url, expected_url)+ self.assertEqual(response_data['location'], expected_url)# Location should be deletedwith self.assertRaises(Location.DoesNotExist):@@ -539,14 +585,16 @@ class TestLocationDeleteView(DualModeViewTestCase):def test_post_invalid_location_id(self):"""Test POST request with invalid location ID."""- url = reverse('location_delete', kwargs={'location_id': 'invalid'})+ # Can't use 'invalid' as location_id in URL - pattern expects digits+ # So we'll test with a nonexistent numeric ID+ url = reverse('location_edit_location_delete', kwargs={'location_id': 99999})response = self.client.post(url, {'action': 'confirm'})- self.assertEqual(response.status_code, 400)+ self.assertEqual(response.status_code, 404)def test_nonexistent_location_returns_404(self):"""Test that accessing nonexistent location returns 404."""- url = reverse('location_delete', kwargs={'location_id': 99999})+ url = reverse('location_edit_location_delete', kwargs={'location_id': 99999})response = self.client.get(url)self.assertEqual(response.status_code, 404)@@ -563,19 +611,19 @@ class TestLocationViewAddView(DualModeViewTestCase):# Set edit mode (required by decorator)self.setSessionViewMode(ViewMode.EDIT)- # Create test location- self.location = Location.objects.create(+ # Create test location using synthetic data+ self.location = LocationSyntheticData.create_test_location(name='Test Location',svg_fragment_filename='test.svg',svg_view_box_str='0 0 100 100')- @patch.object(LocationManager, 'get_default_location')- def test_get_location_view_add_form(self, mock_get_location):+ def test_get_location_view_add_form(self):"""Test getting location view add form."""- mock_get_location.return_value = self.location-- url = reverse('location_view_add')+ # Make this location the default by ensuring it's the only one+ Location.objects.exclude(id=self.location.id).delete()++ url = reverse('location_edit_location_view_add')response = self.client.get(url)self.assertSuccessResponse(response)@@ -584,64 +632,60 @@ class TestLocationViewAddView(DualModeViewTestCase):self.assertEqual(response.context['location'], self.location)self.assertIn('location_view_add_form', response.context)- @patch.object(LocationManager, 'get_default_location')- def test_get_location_view_add_no_location(self, mock_get_location):+ def test_get_location_view_add_no_location(self):"""Test getting location view add form when no location exists."""- mock_get_location.side_effect = Location.DoesNotExist()+ # Delete all locations to test error case+ Location.objects.all().delete()- url = reverse('location_view_add')+ url = reverse('location_edit_location_view_add')response = self.client.get(url)self.assertEqual(response.status_code, 400)- @patch.object(LocationManager, 'create_location_view')- @patch.object(LocationManager, 'get_default_location')- @patch('hi.apps.location.edit.forms.LocationViewAddForm')- def test_post_valid_form(self, mock_form_class, mock_get_location, mock_create_view):+ def test_post_valid_form(self):"""Test POST request with valid form data."""- mock_get_location.return_value = self.location+ # Make this location the default by ensuring it's the only one+ Location.objects.exclude(id=self.location.id).delete()- # Mock valid form- mock_form = Mock()- mock_form.is_valid.return_value = True- mock_form.cleaned_data = {'name': 'New View'}- mock_form_class.return_value = mock_form-- # Mock location view creation- mock_location_view = Mock()- mock_location_view.id = 1- mock_create_view.return_value = mock_location_view-- url = reverse('location_view_add')+ url = reverse('location_edit_location_view_add')response = self.client.post(url, {'name': 'New View'})- self.assertEqual(response.status_code, 302)+ # Expect JSON response for antinode.js+ self.assertEqual(response.status_code, 200)+ self.assertJsonResponse(response)+ response_data = response.json()expected_url = reverse('home')- self.assertEqual(response.url, expected_url)+ self.assertEqual(response_data['location'], expected_url)- # Should create location view- mock_create_view.assert_called_once_with(+ # Verify location view was created+ from hi.apps.location.models import LocationView+ new_view = LocationView.objects.filter(location=self.location,name='New View'- )+ ).first()+ self.assertIsNotNone(new_view)+ self.assertEqual(new_view.name, 'New View')- @patch.object(LocationManager, 'get_default_location')- @patch('hi.apps.location.edit.forms.LocationViewAddForm')- def test_post_invalid_form(self, mock_form_class, mock_get_location):+ def test_post_invalid_form(self):"""Test POST request with invalid form data."""- mock_get_location.return_value = self.location+ # Make this location the default by ensuring it's the only one+ Location.objects.exclude(id=self.location.id).delete()- # Mock invalid form- mock_form = Mock()- mock_form.is_valid.return_value = False- mock_form_class.return_value = mock_form-- url = reverse('location_view_add')- response = self.client.post(url, {})+ url = reverse('location_edit_location_view_add')+ response = self.client.post(url, {}) # Missing required name fieldself.assertSuccessResponse(response)+ self.assertHtmlResponse(response)+# Should render form with errors- self.assertEqual(response.context['location_view_add_form'], mock_form)+ form = response.context.get('location_view_add_form')+ self.assertIsNotNone(form)+ self.assertFalse(form.is_valid())++ # Verify no location view was created+ from hi.apps.location.models import LocationView+ views = LocationView.objects.filter(location=self.location)+ self.assertEqual(views.count(), 0)class TestLocationViewDeleteView(DualModeViewTestCase):@@ -671,7 +715,7 @@ class TestLocationViewDeleteView(DualModeViewTestCase):def test_get_location_view_delete_confirmation(self):"""Test getting location view delete confirmation."""- url = reverse('location_view_delete', kwargs={'location_view_id': self.location_view.id})+ url = reverse('location_edit_location_view_delete', kwargs={'location_view_id': self.location_view.id})response = self.client.get(url)self.assertSuccessResponse(response)@@ -681,19 +725,23 @@ class TestLocationViewDeleteView(DualModeViewTestCase):def test_post_delete_without_confirmation(self):"""Test POST request without confirmation."""- url = reverse('location_view_delete', kwargs={'location_view_id': self.location_view.id})+ url = reverse('location_edit_location_view_delete', kwargs={'location_view_id': self.location_view.id})response = self.client.post(url, {})self.assertEqual(response.status_code, 400)def test_post_delete_with_confirmation(self):"""Test POST request with proper confirmation."""- url = reverse('location_view_delete', kwargs={'location_view_id': self.location_view.id})+ url = reverse('location_edit_location_view_delete',+ kwargs={'location_view_id': self.location_view.id})response = self.client.post(url, {'action': 'confirm'})- self.assertEqual(response.status_code, 302)+ # Expect JSON response for antinode.js+ self.assertEqual(response.status_code, 200)+ self.assertJsonResponse(response)+ response_data = response.json()expected_url = reverse('home')- self.assertEqual(response.url, expected_url)+ self.assertEqual(response_data['location'], expected_url)# Location view should be deletedwith self.assertRaises(LocationView.DoesNotExist):@@ -701,13 +749,13 @@ class TestLocationViewDeleteView(DualModeViewTestCase):def test_nonexistent_location_view_returns_404(self):"""Test that accessing nonexistent location view returns 404."""- url = reverse('location_view_delete', kwargs={'location_view_id': 99999})+ url = reverse('location_edit_location_view_delete', kwargs={'location_view_id': 99999})response = self.client.get(url)self.assertEqual(response.status_code, 404)-class TestLocationViewEditView(SyncViewTestCase):+class TestLocationViewEditView(DualModeViewTestCase):"""Tests for LocationViewEditView - demonstrates location view editing testing.This view handles location view property updates.@@ -715,63 +763,68 @@ class TestLocationViewEditView(SyncViewTestCase):def setUp(self):super().setUp()- # Create test location and location view- self.location = Location.objects.create(+ # Set edit mode (required by decorator)+ self.setSessionViewMode(ViewMode.EDIT)++ # Create test location and location view using synthetic data+ self.location = LocationSyntheticData.create_test_location(name='Test Location',svg_fragment_filename='test.svg',svg_view_box_str='0 0 100 100')- self.location_view = LocationView.objects.create(+ self.location_view = LocationSyntheticData.create_test_location_view(location=self.location,name='Test View',- location_view_type_str='MAIN',- svg_view_box_str='0 0 100 100',- svg_rotate=0.0+ svg_view_box_str='0 0 100 100')- @patch('hi.apps.location.edit.forms.LocationViewEditForm')- @patch('hi.apps.common.antinode.refresh_response')- def test_post_valid_edit(self, mock_refresh, mock_form_class):+ def test_post_valid_edit(self):"""Test POST request with valid edit data."""- # Mock valid form- mock_form = Mock()- mock_form.is_valid.return_value = True- mock_form_class.return_value = mock_form-- mock_refresh.return_value = 'refresh_response'-- url = reverse('location_view_edit', kwargs={'location_view_id': self.location_view.id})- _ = self.client.post(url, {'name': 'Updated View'})+ url = reverse('location_edit_location_view_edit', kwargs={'location_view_id': self.location_view.id})+ response = self.async_post(url, {+ 'name': 'Updated View',+ 'location_view_type_str': self.location_view.location_view_type_str,+ 'svg_style_name_str': 'color',+ 'svg_view_box_str': self.location_view.svg_view_box_str,+ 'svg_rotate': str(self.location_view.svg_rotate),+ 'order_id': str(self.location_view.order_id)+ })- mock_form.save.assert_called_once()- mock_refresh.assert_called_once()+ # Should return success (200 with JSON for antinode.js)+ self.assertSuccessResponse(response)+ self.assertJsonResponse(response)++ # Verify the location view was updated+ self.location_view.refresh_from_db()+ self.assertEqual(self.location_view.name, 'Updated View')- @patch('hi.apps.location.edit.forms.LocationViewEditForm')- def test_post_invalid_edit(self, mock_form_class):+ def test_post_invalid_edit(self):"""Test POST request with invalid edit data."""- # Mock invalid form- mock_form = Mock()- mock_form.is_valid.return_value = False- mock_form_class.return_value = mock_form-- url = reverse('location_view_edit', kwargs={'location_view_id': self.location_view.id})- response = self.client.post(url, {'name': ''})+ url = reverse('location_edit_location_view_edit', kwargs={'location_view_id': self.location_view.id})+ response = self.async_post(url, {'name': ''}) # Empty name should be invalid+ # Should return 400 for invalid form dataself.assertEqual(response.status_code, 400)- mock_form.save.assert_not_called()+ self.assertJsonResponse(response)++ # Verify the location view was not updated+ self.location_view.refresh_from_db()+ self.assertEqual(self.location_view.name, 'Test View') # Original name unchangeddef test_nonexistent_location_view_returns_404(self):"""Test that accessing nonexistent location view returns 404."""- url = reverse('location_view_edit', kwargs={'location_view_id': 99999})- response = self.client.post(url, {'name': 'Test'})+ url = reverse('location_edit_location_view_edit', kwargs={'location_view_id': 99999})+ response = self.async_post(url, {'name': 'Test'})+ # Should return 404 for nonexistent location viewself.assertEqual(response.status_code, 404)def test_get_not_allowed(self):"""Test that GET requests are not allowed."""- url = reverse('location_view_edit', kwargs={'location_view_id': self.location_view.id})- response = self.client.get(url)+ url = reverse('location_edit_location_view_edit', kwargs={'location_view_id': self.location_view.id})+ response = self.async_get(url)+ # View doesn't have GET method - returns 405self.assertEqual(response.status_code, 405)@@ -786,124 +839,39 @@ class TestLocationViewManageItemsView(SyncViewTestCase):# Set edit mode (required by decorator)self.setSessionViewMode(ViewMode.EDIT)- # Create test location and location view- self.location = Location.objects.create(+ # Create test location and location view using synthetic data+ self.location = LocationSyntheticData.create_test_location(name='Test Location',svg_fragment_filename='test.svg',svg_view_box_str='0 0 100 100')- self.location_view = LocationView.objects.create(+ self.location_view = LocationSyntheticData.create_test_location_view(location=self.location,name='Test View',- location_view_type_str='MAIN',- svg_view_box_str='0 0 100 100',- svg_rotate=0.0+ svg_view_box_str='0 0 100 100')- @patch.object(CollectionManager, 'create_location_collection_view_group')- @patch.object(EntityManager, 'create_location_entity_view_group_list')- @patch.object(LocationManager, 'get_default_location_view')- def test_get_manage_items_view(self, mock_get_location_view, mock_create_entity_groups,- mock_create_collection_group):+ def test_get_manage_items_view(self):"""Test getting location view manage items view."""- mock_get_location_view.return_value = self.location_view- mock_entity_groups = ['entity_group1', 'entity_group2']- mock_create_entity_groups.return_value = mock_entity_groups- mock_collection_group = 'collection_group'- mock_create_collection_group.return_value = mock_collection_group+ # Make this location view the default by ensuring no others exist+ from hi.apps.location.models import LocationView+ LocationView.objects.exclude(id=self.location_view.id).delete()+ Location.objects.exclude(id=self.location.id).delete()- url = reverse('location_view_manage_items')+ url = reverse('location_edit_location_view_manage_items')response = self.client.get(url)self.assertSuccessResponse(response)- self.assertHtmlResponse(response)+ self.assertJsonResponse(response)self.assertTemplateRendered(response, 'location/edit/panes/location_view_manage_items.html')self.assertEqual(response.context['location_view'], self.location_view)- self.assertEqual(response.context['entity_view_group_list'], mock_entity_groups)- self.assertEqual(response.context['collection_view_group'], mock_collection_group)-- def test_post_not_allowed(self):- """Test that POST requests are not allowed."""- url = reverse('location_view_manage_items')- response = self.client.post(url)-- self.assertEqual(response.status_code, 405)---class TestLocationViewReorder(SyncViewTestCase):- """- Tests for LocationViewReorder - demonstrates location view reordering testing.- This view handles reordering location views.- """-- def setUp(self):- super().setUp()- # Set edit mode (required by decorator)- self.setSessionViewMode(ViewMode.EDIT)-- # Create test location and location views- self.location = Location.objects.create(- name='Test Location',- svg_fragment_filename='test.svg',- svg_view_box_str='0 0 100 100'- )- self.location_view1 = LocationView.objects.create(- location=self.location,- name='View 1',- location_view_type_str='MAIN',- svg_view_box_str='0 0 100 100',- svg_rotate=0.0- )- self.location_view2 = LocationView.objects.create(- location=self.location,- name='View 2',- location_view_type_str='DETAIL',- svg_view_box_str='0 0 100 100',- svg_rotate=0.0- )-- @patch.object(LocationManager, 'set_location_view_order')- @patch('hi.apps.common.antinode.response')- def test_post_valid_reorder(self, mock_antinode_response, mock_set_order):- """Test POST request with valid reorder data."""- mock_antinode_response.return_value = 'success_response'-- location_view_id_list = [self.location_view2.id, self.location_view1.id]- url = reverse('location_view_reorder', kwargs={- 'location_view_id_list': json.dumps(location_view_id_list)- })- _ = self.client.post(url)-- mock_set_order.assert_called_once_with(location_view_id_list=location_view_id_list)- mock_antinode_response.assert_called_once_with(main_content='OK')-- def test_post_invalid_json(self):- """Test POST request with invalid JSON data."""- url = reverse('location_view_reorder', kwargs={- 'location_view_id_list': 'invalid-json'- })- response = self.client.post(url)-- self.assertEqual(response.status_code, 400)-- def test_post_empty_location_view_list(self):- """Test POST request with empty location view list."""- url = reverse('location_view_reorder', kwargs={- 'location_view_id_list': json.dumps([])- })- response = self.client.post(url)-- self.assertEqual(response.status_code, 400)-- def test_get_not_allowed(self):- """Test that GET requests are not allowed."""- url = reverse('location_view_reorder', kwargs={- 'location_view_id_list': json.dumps([1, 2])- })- response = self.client.get(url)-- self.assertEqual(response.status_code, 405)+ # Verify context contains expected data structures (lists/groups)+ self.assertIn('entity_view_group_list', response.context)+ self.assertIn('collection_view_group', response.context)+ # Groups should be lists/objects (not mocks)+ self.assertIsNotNone(response.context['entity_view_group_list'])+ self.assertIsNotNone(response.context['collection_view_group'])class TestLocationItemPositionView(SyncViewTestCase):@@ -917,56 +885,102 @@ class TestLocationItemPositionView(SyncViewTestCase):# Set edit mode (required by decorator)self.setSessionViewMode(ViewMode.EDIT)- # Create test data- self.entity = Entity.objects.create(+ # Create test data using synthetic data helpers+ from hi.apps.entity.tests.synthetic_data import EntityAttributeSyntheticData+ self.entity = EntityAttributeSyntheticData.create_test_entity(name='Test Entity',- entity_type_str='LIGHT'+ entity_type_str=str(EntityType.LIGHT))- self.collection = Collection.objects.create(- name='Test Collection',- collection_type_str='ROOM',- collection_view_type_str='MAIN'++ from hi.apps.collection.tests.synthetic_data import CollectionSyntheticData+ self.collection = CollectionSyntheticData.create_test_collection(+ name='Test Collection')- @patch('hi.apps.location.edit.views.EntityPositionEditView')- def test_post_entity_position(self, mock_view_class):+ def test_post_entity_position(self):"""Test POST request for entity position."""- mock_view = mock_view_class.return_value- mock_view.post.return_value = 'entity_response'+ # Create a location with the entity positioned on it+ location = LocationSyntheticData.create_test_location()+ entity_with_position = LocationSyntheticData.create_test_entity_with_position(+ location=location,+ name='Test Entity',+ entity_type_str=str(EntityType.LIGHT),+ svg_x=100.0,+ svg_y=100.0,+ svg_rotate=0.0,+ svg_scale=1.0+ )- url = reverse('location_item_position', kwargs={- 'item_type': 'entity',- 'item_id': self.entity.id+ # Create HTML ID for the entity+ html_id = ItemType.ENTITY.html_id(entity_with_position.id)+ url = reverse('location_edit_location_item_position', kwargs={+ 'html_id': html_id+ })++ # Post new position data+ response = self.client.post(url, {+ 'svg_x': 200.0,+ 'svg_y': 150.0,+ 'svg_rotate': 90.0,+ 'svg_scale': 1.5})- _ = self.client.post(url, {})- # Should delegate to EntityPositionEditView- mock_view.post.assert_called_once()- call_kwargs = mock_view.post.call_args[1]- self.assertEqual(call_kwargs['entity_id'], self.entity.id)+ # Should delegate to EntityPositionEditView and succeed+ self.assertSuccessResponse(response)++ # Verify position was updated in database+ from hi.apps.entity.models import EntityPosition+ position = EntityPosition.objects.get(+ entity=entity_with_position,+ location=location+ )+ self.assertEqual(position.svg_x, 200.0)+ self.assertEqual(position.svg_y, 150.0)- @patch('hi.apps.location.edit.views.CollectionPositionEditView')- def test_post_collection_position(self, mock_view_class):+ def test_post_collection_position(self):"""Test POST request for collection position."""- mock_view = mock_view_class.return_value- mock_view.post.return_value = 'collection_response'+ # Create a location with the collection positioned on it+ location = LocationSyntheticData.create_test_location()+ collection_with_position = LocationSyntheticData.create_test_collection_with_position(+ location=location,+ name='Test Collection',+ svg_x=100.0,+ svg_y=100.0,+ svg_rotate=0.0,+ svg_scale=1.0+ )- url = reverse('location_item_position', kwargs={- 'item_type': 'collection',- 'item_id': self.collection.id+ # Create HTML ID for the collection+ html_id = ItemType.COLLECTION.html_id(collection_with_position.id)+ url = reverse('location_edit_location_item_position', kwargs={+ 'html_id': html_id+ })++ # Post new position data+ response = self.client.post(url, {+ 'svg_x': 300.0,+ 'svg_y': 250.0,+ 'svg_rotate': 45.0,+ 'svg_scale': 2.0})- _ = self.client.post(url, {})- # Should delegate to CollectionPositionEditView- mock_view.post.assert_called_once()- call_kwargs = mock_view.post.call_args[1]- self.assertEqual(call_kwargs['collection_id'], self.collection.id)+ # Should delegate to CollectionPositionEditView and succeed+ self.assertSuccessResponse(response)++ # Verify position was updated in database+ from hi.apps.collection.models import CollectionPosition+ position = CollectionPosition.objects.get(+ collection=collection_with_position,+ location=location+ )+ self.assertEqual(position.svg_x, 300.0)+ self.assertEqual(position.svg_y, 250.0)def test_post_unknown_item_type(self):"""Test POST request with unknown item type."""- url = reverse('location_item_position', kwargs={- 'item_type': 'unknown',- 'item_id': 1+ # Use an invalid HTML ID format+ url = reverse('location_edit_location_item_position', kwargs={+ 'html_id': 'hi-invalid-1'})response = self.client.post(url, {})@@ -974,16 +988,20 @@ class TestLocationItemPositionView(SyncViewTestCase):def test_post_invalid_item_id(self):"""Test POST request with invalid item ID."""- # This would typically be caught by ItemType.parse_from_dict- with self.assertRaises(BadRequest):- # Simulate what happens in the view with invalid data- ItemType.parse_from_dict({'item_type': 'entity', 'item_id': 'invalid'})+ # Use an HTML ID with non-existent item+ html_id = ItemType.ENTITY.html_id(99999)+ url = reverse('location_edit_location_item_position', kwargs={+ 'html_id': html_id+ })+ response = self.client.post(url, {})++ self.assertEqual(response.status_code, 404)def test_get_not_allowed(self):"""Test that GET requests are not allowed."""- url = reverse('location_item_position', kwargs={- 'item_type': 'entity',- 'item_id': self.entity.id+ html_id = ItemType.ENTITY.html_id(self.entity.id)+ url = reverse('location_edit_location_item_position', kwargs={+ 'html_id': html_id})response = self.client.get(url)@@ -1001,71 +1019,79 @@ class TestLocationItemPathView(SyncViewTestCase):# Set edit mode (required by decorator)self.setSessionViewMode(ViewMode.EDIT)- # Create test data- self.location = Location.objects.create(+ # Create test data using synthetic data+ self.location = LocationSyntheticData.create_test_location(name='Test Location',svg_fragment_filename='test.svg',svg_view_box_str='0 0 100 100')- self.entity = Entity.objects.create(++ from hi.apps.entity.tests.synthetic_data import EntityAttributeSyntheticData+ self.entity = EntityAttributeSyntheticData.create_test_entity(name='Test Entity',- entity_type_str='LIGHT'+ entity_type_str=str(EntityType.LIGHT))- self.collection = Collection.objects.create(- name='Test Collection',- collection_type_str='ROOM',- collection_view_type_str='MAIN'++ from hi.apps.collection.tests.synthetic_data import CollectionSyntheticData+ self.collection = CollectionSyntheticData.create_test_collection(+ name='Test Collection')- @patch.object(EntityManager, 'set_entity_path')- @patch.object(LocationManager, 'get_default_location')- @patch('hi.apps.common.antinode.response')- def test_post_entity_path(self, mock_antinode_response, mock_get_location, mock_set_path):+ def test_post_entity_path(self):"""Test POST request to set entity SVG path."""- mock_get_location.return_value = self.location- mock_antinode_response.return_value = 'success_response'-- url = reverse('location_item_path', kwargs={- 'item_type': 'entity',- 'item_id': self.entity.id+ # Make this location the default by ensuring it's the only one+ Location.objects.exclude(id=self.location.id).delete()++ html_id = ItemType.ENTITY.html_id(self.entity.id)+ url = reverse('location_edit_location_item_path', kwargs={+ 'html_id': html_id})- _ = self.client.post(url, {'svg_path': 'M 10 10 L 20 20'})+ response = self.client.post(url, {'svg_path': 'M 10 10 L 20 20'})- mock_set_path.assert_called_once_with(- entity_id=self.entity.id,- location=self.location,- svg_path_str='M 10 10 L 20 20'- )- mock_antinode_response.assert_called_once_with(main_content='OK')-- @patch.object(CollectionManager, 'set_collection_path')- @patch.object(CollectionManager, 'get_collection')- @patch.object(LocationManager, 'get_default_location')- @patch('hi.apps.common.antinode.response')- def test_post_collection_path(self, mock_antinode_response, mock_get_location,- mock_get_collection, mock_set_path):+ # Should return success (200 with JSON for antinode.js)+ self.assertSuccessResponse(response)+ self.assertJsonResponse(response)++ # Verify entity path was set in the database+ # Check if EntityPath model exists to verify path was saved+ from hi.apps.entity.models import EntityPath+ entity_path = EntityPath.objects.filter(+ entity=self.entity,+ location=self.location+ ).first()+ self.assertIsNotNone(entity_path)+ self.assertEqual(entity_path.svg_path, 'M 10 10 L 20 20')++ def test_post_collection_path(self):"""Test POST request to set collection SVG path."""- mock_get_location.return_value = self.location- mock_get_collection.return_value = self.collection- mock_antinode_response.return_value = 'success_response'-- url = reverse('location_item_path', kwargs={- 'item_type': 'collection',- 'item_id': self.collection.id+ # Make this location the default by ensuring it's the only one+ Location.objects.exclude(id=self.location.id).delete()++ html_id = ItemType.COLLECTION.html_id(self.collection.id)+ url = reverse('location_edit_location_item_path', kwargs={+ 'html_id': html_id})- _ = self.client.post(url, {'svg_path': 'M 30 30 L 40 40'})-- mock_set_path.assert_called_once_with(+ response = self.client.post(url, {'svg_path': 'M 30 30 L 40 40'})++ # Should return success (200 with JSON for antinode.js)+ self.assertSuccessResponse(response)+ self.assertJsonResponse(response)++ # Verify collection path was set in the database+ # Check if CollectionPath model exists to verify path was saved+ from hi.apps.collection.models import CollectionPath+ collection_path = CollectionPath.objects.filter(collection=self.collection,- location=self.location,- svg_path_str='M 30 30 L 40 40'- )+ location=self.location+ ).first()+ self.assertIsNotNone(collection_path)+ self.assertEqual(collection_path.svg_path, 'M 30 30 L 40 40')def test_post_missing_svg_path(self):"""Test POST request without SVG path."""- url = reverse('location_item_path', kwargs={- 'item_type': 'entity',- 'item_id': self.entity.id+ html_id = ItemType.ENTITY.html_id(self.entity.id)+ url = reverse('location_edit_location_item_path', kwargs={+ 'html_id': html_id})response = self.client.post(url, {})@@ -1073,19 +1099,19 @@ class TestLocationItemPathView(SyncViewTestCase):def test_post_unknown_item_type(self):"""Test POST request with unknown item type."""- url = reverse('location_item_path', kwargs={- 'item_type': 'unknown',- 'item_id': 1+ html_id = 'hi-bogus-5'+ url = reverse('location_edit_location_item_path', kwargs={+ 'html_id': html_id})response = self.client.post(url, {'svg_path': 'M 0 0 L 1 1'})-+self.assertEqual(response.status_code, 400)def test_get_not_allowed(self):"""Test that GET requests are not allowed."""- url = reverse('location_item_path', kwargs={- 'item_type': 'entity',- 'item_id': self.entity.id+ html_id = ItemType.ENTITY.html_id(self.entity.id)+ url = reverse('location_edit_location_item_path', kwargs={+ 'html_id': html_id})response = self.client.get(url)diff --git a/src/hi/apps/location/edit/urls.py b/src/hi/apps/location/edit/urls.pyindex 6e44f007..17f36bec 100644--- a/src/hi/apps/location/edit/urls.py+++ b/src/hi/apps/location/edit/urls.py@@ -5,7 +5,7 @@ from . import viewsurlpatterns = [- re_path( r'^location/add$',+ re_path( r'^location/add/first$',views.LocationAddFirstView.as_view(),name='location_edit_location_add_first'),diff --git a/src/hi/apps/location/edit/views.py b/src/hi/apps/location/edit/views.pyindex 5f9870b9..684b799d 100644--- a/src/hi/apps/location/edit/views.py+++ b/src/hi/apps/location/edit/views.py@@ -372,7 +372,7 @@ class LocationViewEditView( View, LocationViewMixin, LocationEditViewMixin ):def post( self, request, *args, **kwargs ):location_view = self.get_location_view( request, *args, **kwargs )location_view_edit_form = forms.LocationViewEditForm( request.POST, instance = location_view )-+if not location_view_edit_form.is_valid():location_view_edit_data = LocationViewEditData(location_view = location_view,@@ -425,7 +425,7 @@ class LocationViewManageItemsView( HiSideView ):return 'location/edit/panes/location_view_manage_items.html'def get_template_context( self, request, *args, **kwargs ):-+location_view = LocationManager().get_default_location_view( request = request )entity_view_group_list = EntityManager().create_location_entity_view_group_list(location_view = location_view,@@ -583,7 +583,6 @@ class LocationItemPositionView( View ):class LocationItemPathView( View ):def post(self, request, *args, **kwargs):-try:( item_type, item_id ) = ItemType.parse_from_dict( kwargs )except ValueError:diff --git a/src/hi/apps/location/svg_item_factory.py b/src/hi/apps/location/svg_item_factory.pyindex 4a208401..d3f066f1 100644--- a/src/hi/apps/location/svg_item_factory.py+++ b/src/hi/apps/location/svg_item_factory.py@@ -51,7 +51,7 @@ class SvgItemFactory( Singleton ):viewbox = EntityStyle.get_svg_icon_viewbox( entity_type = item.entity_type )else:template_name = ItemStyle.get_default_svg_icon_template_name()- viewbox = ItemStyle.ItemStyle.get_default_svg_icon_viewbox()+ viewbox = ItemStyle.get_default_svg_icon_viewbox()return SvgIconItem(html_id = item.html_id,diff --git a/src/hi/apps/location/tests/synthetic_data.py b/src/hi/apps/location/tests/synthetic_data.pynew file mode 100644index 00000000..b5303594--- /dev/null+++ b/src/hi/apps/location/tests/synthetic_data.py@@ -0,0 +1,110 @@+"""+Synthetic data generators for Location and LocationView testing.++Provides centralized, reusable test data creation following the project's+synthetic data pattern documented in test-data-management.md.+"""+import uuid+from typing import Optional++from hi.apps.location.models import Location, LocationView+from hi.apps.entity.models import Entity, EntityPosition+from hi.apps.collection.models import Collection, CollectionPosition+from hi.apps.entity.enums import EntityType+from hi.apps.collection.enums import CollectionType, CollectionViewType+from hi.apps.location.enums import LocationViewType+++class LocationSyntheticData:+ """Centralized synthetic data generators for location testing."""++ @staticmethod+ def create_test_location(**kwargs) -> Location:+ """Create a test location with reasonable defaults."""+ unique_id = str(uuid.uuid4())[:8]+ defaults = {+ 'name': f'Test Location {unique_id}',+ 'svg_fragment_filename': f'test-location-{unique_id}.svg',+ 'svg_view_box_str': '0 0 800 600',+ }+ defaults.update(kwargs)+ return Location.objects.create(**defaults)++ @staticmethod+ def create_test_location_view(location: Optional[Location] = None, **kwargs) -> LocationView:+ """Create a test location view with reasonable defaults."""+ if location is None:+ location = LocationSyntheticData.create_test_location()++ unique_id = str(uuid.uuid4())[:8]+ defaults = {+ 'location': location,+ 'name': f'Test View {unique_id}',+ 'location_view_type_str': str(LocationViewType.DEFAULT),+ 'svg_view_box_str': '0 0 800 600',+ 'order_id': 0,+ 'svg_rotate': 0.0,+ }+ defaults.update(kwargs)+ return LocationView.objects.create(**defaults)++ @staticmethod+ def create_test_entity_with_position(location: Optional[Location] = None, **kwargs) -> Entity:+ """Create a test entity with position on a location."""+ if location is None:+ location = LocationSyntheticData.create_test_location()++ unique_id = str(uuid.uuid4())[:8]+ entity_defaults = {+ 'name': f'Test Entity {unique_id}',+ 'integration_id': f'test.entity.{unique_id}',+ 'integration_name': 'test_integration',+ 'entity_type_str': str(EntityType.LIGHT),+ }+ # Extract position-specific kwargs+ position_kwargs = {+ 'svg_x': kwargs.pop('svg_x', 100.0),+ 'svg_y': kwargs.pop('svg_y', 100.0),+ 'svg_rotate': kwargs.pop('svg_rotate', 0.0),+ 'svg_scale': kwargs.pop('svg_scale', 1.0),+ }+ entity_defaults.update(kwargs)+ entity = Entity.objects.create(**entity_defaults)++ # Create position+ EntityPosition.objects.create(+ entity=entity,+ location=location,+ **position_kwargs+ )+ return entity++ @staticmethod+ def create_test_collection_with_position(location: Optional[Location] = None, **kwargs) -> Collection:+ """Create a test collection with position on a location."""+ if location is None:+ location = LocationSyntheticData.create_test_location()++ unique_id = str(uuid.uuid4())[:8]+ collection_defaults = {+ 'name': f'Test Collection {unique_id}',+ 'collection_type_str': str(CollectionType.OTHER),+ 'collection_view_type_str': str(CollectionViewType.LIST),+ }+ # Extract position-specific kwargs+ position_kwargs = {+ 'svg_x': kwargs.pop('svg_x', 200.0),+ 'svg_y': kwargs.pop('svg_y', 200.0),+ 'svg_rotate': kwargs.pop('svg_rotate', 0.0),+ 'svg_scale': kwargs.pop('svg_scale', 1.0),+ }+ collection_defaults.update(kwargs)+ collection = Collection.objects.create(**collection_defaults)++ # Create position+ CollectionPosition.objects.create(+ collection=collection,+ location=location,+ **position_kwargs+ )+ return collectiondiff --git a/src/hi/apps/location/tests/test_views.py b/src/hi/apps/location/tests/test_views.pyindex 4b436e69..3ffc8b33 100644--- a/src/hi/apps/location/tests/test_views.py+++ b/src/hi/apps/location/tests/test_views.py@@ -502,15 +502,15 @@ class TestLocationItemDetailsView(SyncViewTestCase):collection_view_type_str='MAIN')- def test_entity_details_redirect(self):- """Test redirecting to entity details for entity items."""+ def test_entity_edit_mode_redirect(self):+ """Test redirecting to entity edit mode for entity items."""from hi.enums import ItemTypehtml_id = ItemType.ENTITY.html_id(self.entity.id)url = reverse('location_item_details', kwargs={'html_id': html_id})response = self.client.get(url)self.assertEqual(response.status_code, 302)- expected_url = reverse('entity_details', kwargs={'entity_id': self.entity.id})+ expected_url = reverse('entity_edit_mode', kwargs={'entity_id': self.entity.id})self.assertEqual(response.url, expected_url)def test_collection_details_redirect(self):diff --git a/src/hi/apps/location/views.py b/src/hi/apps/location/views.pyindex 5e89a61e..72fb5343 100644--- a/src/hi/apps/location/views.py+++ b/src/hi/apps/location/views.py@@ -155,7 +155,7 @@ class LocationItemDetailsView( View ):raise BadRequest( 'Bad item id.' )if item_type == ItemType.ENTITY:- redirect_url = reverse( 'entity_details', kwargs = { 'entity_id': item_id } )+ redirect_url = reverse( 'entity_edit_mode', kwargs = { 'entity_id': item_id } )return HttpResponseRedirect( redirect_url )if item_type == ItemType.COLLECTION:diff --git a/src/hi/constants.py b/src/hi/constants.pyindex 9f4eea1d..965a7a76 100644--- a/src/hi/constants.py+++ b/src/hi/constants.py@@ -60,4 +60,36 @@ DIVID = {'WEATHER_ALERTS': 'hi-weather-alerts','CONSOLE_LOCK_BUTTON': 'hi-console-lock-button',++ # Entity Attribute Editing V2+ 'ATTR_V2_FORM': 'attr-v2-form',+ 'ATTR_V2_CONTENT': 'attr-v2-content',+ 'ATTR_V2_UPLOAD_FORM_CONTAINER': 'attr-v2-upload-form-container',+ 'ATTR_V2_FILE_GRID': 'attr-v2-file-grid',+ 'ATTR_V2_STATUS_MSG': 'attr-v2-status-msg',+ 'ATTR_V2_DIRTY_MESSAGE': 'attr-v2-dirty-message',+ 'ATTR_V2_UPDATE_BTN': 'attr-v2-update-btn',+ 'ATTR_V2_MESSAGES': 'attr-v2-messages',+ 'ATTR_V2_MODAL_CLASS': 'attr-v2-modal',+ 'ATTR_V2_ATTRIBUTE_CARD_CLASS': 'attr-v2-attribute-card',+ 'ATTR_V2_NEW_ATTRIBUTE_CLASS': 'attr-v2-new-attribute',+ 'ATTR_V2_FILE_TITLE_INPUT_CLASS': 'attr-v2-file-title-input',+ 'ATTR_V2_FILE_INFO_CLASS': 'attr-v2-file-info',+ 'ATTR_V2_FIELD_DIRTY_CLASS': 'attr-v2-field-dirty',+ 'ATTR_V2_DIRTY_INDICATOR_CLASS': 'attr-v2-dirty-indicator',+ 'ATTR_V2_ATTRIBUTE_NAME_CLASS': 'attr-v2-attribute-name',+ 'ATTR_V2_DELETE_BTN_CLASS': 'attr-v2-delete-btn',+ 'ATTR_V2_UNDO_BTN_CLASS': 'attr-v2-undo-btn',+ 'ATTR_V2_FILE_CARD_CLASS': 'attr-v2-file-card',+ 'ATTR_V2_FILE_NAME_CLASS': 'attr-v2-file-filename',+ 'ATTR_V2_SECRET_INPUT_WRAPPER_CLASS': 'attr-v2-secret-input-wrapper',+ 'ATTR_V2_SECRET_INPUT_CLASS': 'attr-v2-secret-input',+ 'ATTR_V2_ICON_SHOW_CLASS': 'attr-v2-icon-show',+ 'ATTR_V2_ICON_HIDE_CLASS': 'attr-v2-icon-hide',+ 'ATTR_V2_TEXTAREA_CLASS': 'attr-v2-textarea',+ 'ATTR_V2_TEXT_VALUE_WRAPPER_CLASS': 'attr-v2-text-value-wrapper',+ 'ATTR_V2_EXPAND_CONTROLS_CLASS': 'attr-v2-expand-controls',+ 'ATTR_V2_FILE_INPUT': 'attr-v2-file-input',+ 'ATTR_V2_ADD_ATTRIBUTE_BTN': 'attr-v2-add-attribute-btn',+ 'ATTR_V2_SCROLLABLE_CONTENT': 'attr-v2-scrollable-content',}diff --git a/src/hi/exceptions.py b/src/hi/exceptions.pyindex 7a0547f9..67f7f3b3 100644--- a/src/hi/exceptions.py+++ b/src/hi/exceptions.py@@ -1,3 +1,7 @@+class MethodNotAllowedError( Exception ):+ pass++class ForceRedirectException( Exception ):def __init__(self, url, message = 'Force redirect' ):diff --git a/src/hi/hi_async_view.py b/src/hi/hi_async_view.pyindex 1166b21c..e8f04d06 100644--- a/src/hi/hi_async_view.py+++ b/src/hi/hi_async_view.py@@ -10,6 +10,7 @@ import hi.apps.common.antinode as antinodefrom hi.apps.common.utils import is_ajaxfrom hi.constants import DIVID+from hi.exceptions import MethodNotAllowedErrorlogger = logging.getLogger(__name__)@@ -44,7 +45,7 @@ class HiAsyncView( View ):def post_template_context( self, request, *args, **kwargs ) -> Dict[ str, str ]:""" Can raise exceptions like BadRequest, Http404, etc. """- raise NotImplementedError('Subclasses must override this method.')+ raise MethodNotAllowedError()def post_content( self, request, *args, **kwargs ) -> str:template_name = self.get_template_name()diff --git a/src/hi/middleware.py b/src/hi/middleware.pyindex d6c93586..0ceca396 100644--- a/src/hi/middleware.py+++ b/src/hi/middleware.py@@ -16,6 +16,7 @@ from django.http import (HttpResponseServerError,)+from .exceptions import MethodNotAllowedErrorfrom .view_parameters import ViewParametersfrom . import views@@ -67,6 +68,8 @@ class ExceptionMiddleware(object):return views.not_authorized_response(request, message=str(exception))if isinstance( exception, Http404 ):return views.page_not_found_response(request, message=str(exception))+ if isinstance( exception, MethodNotAllowedError ):+ return views.method_not_allowed_response(request, message=str(exception))logger.exception( f'Exception caught in middleware: {exception}' )return views.internal_error_response(request, message=str(exception) )diff --git a/src/hi/settings/base.py b/src/hi/settings/base.pyindex ee3b84c4..f3797713 100644--- a/src/hi/settings/base.py+++ b/src/hi/settings/base.py@@ -249,6 +249,8 @@ PIPELINE = {'js/audio.js','js/attribute-changes.js','js/video-timeline.js',+ 'js/attr-v2-modal.js',+ 'js/attr-v2-dirty-tracking.js',),'output_filename': 'js/js_before_content.js',},diff --git a/src/hi/static/css/main.css b/src/hi/static/css/main.cssindex 93d5439b..420112eb 100644--- a/src/hi/static/css/main.css+++ b/src/hi/static/css/main.css@@ -16,6 +16,7 @@--secondary-highlight-color: #7e7e81;--success-color: #177219;--on-success-color: #ffffff;+ --success-bg-light: #e8f5e8;--warning-color: #ECA500;--on-warning-color: #ffffff;--error-color: #721817;@@ -341,1213 +342,2724 @@ a.clickable-card:active {.hi-modal-dialog-600 {max-width: 600px;}+.hi-modal-dialog-700 {+ max-width: 700px;+}.hi-modal-dialog-800 {max-width: 800px;}-.btn-control {- width: 100%;+.modal-title-image img {+ max-height: 48px;+}+.modal-title {white-space: nowrap;- font-size: 0.75rem;- font-weight: bold;+ overflow: hidden;+ text-overflow: ellipsis;+ width: 100%;}-input[type="number"] {- max-width: 8rem;++/* Attribute V2 System Styles - Fresh Start */++/* Modal Structure */+.attr-v2-modal {+ /* Remove default form margins for better layout control */+ margin: 0;}-.hi-location-view {- justify-content: center;- align-items: center;- height: calc(100vh - var(--top-buttons-height) - var(--bottom-buttons-height) );- touch-action: none;+/* Sticky Panel (Entity Info + Action Bar - Always Visible) */+.attr-v2-sticky-panel {+ position: sticky;+ top: 0;+ z-index: 10;+ background-color: var(--white);+ border-bottom: 1px solid var(--line-color);+ padding-bottom: 0.75rem;}-.hi-location-view-svg {- max-height: calc(100vh - var(--top-buttons-height) - var(--bottom-buttons-height) );- width: auto;- height: auto;- display: block;- cursor: pointer;-}-#hi-integration-settings nav {- border-right: 1px solid #888888;- height: calc( 100vh - var(--top-buttons-height) - var(--bottom-buttons-height) - 6rem);- overflow-y: auto;+/* Entity Info Section (Minimal - Name/Type) */+.attr-v2-entity-info {+ padding: 0.5rem 0 0.25rem 0;}-#hi-integration-settings nav hr {- flex: 0 0 auto; /* Prevent shrinking or growing */- width: 100%;- border-top: 1px solid #202020;++/* Action Bar */+.attr-v2-action-bar {+ padding: 0.25rem 0;+ background-color: var(--white);}-.drag-over {- border: 2px dashed #888888;++.attr-v2-action-bar-content {+ display: flex;+ justify-content: space-between;+ align-items: center;+ gap: 1rem;}-.form-group label {- color: #060606 !important;+#attr-v2-update-btn {+ min-height: 44px; /* Touch-friendly primary action */+ min-width: 80px;+ padding: 0.75rem 1.5rem;}-.input-group-text {- color: var(--black);- background-color: #f0f0f0;++.attr-v2-action-buttons {+ display: flex;+ gap: 0.5rem;+ align-items: center;}-select,-textarea,-input[type="text"],-input[type="password"],-.dropdown-menu {- color: var(--black) !important;- background-color: #f8f8f8 !important;++.attr-v2-action-buttons button {+ min-height: 44px; /* Touch-friendly minimum */+ padding: 0.375rem 0.75rem;+ font-size: 0.875rem;+ border-radius: 0.25rem;}-.hi-custom-select .input-group-text {- height: calc(1.5em + 0.75rem + 2px);- line-height: 1.5;++.attr-v2-status-message {+ font-size: 0.875rem;+ color: var(--secondary-text-color);+ font-style: italic;}-.plus-icon {- font-size: 1.5rem;- color: var(--on-primary-color);- background-color: var(--primary-color);- padding: 0 0.25rem 0 0.25rem;++/* Status message variants */+.attr-v2-status-message.success {+ color: var(--success-color, #28a745);+ background-color: var(--success-bg-light);+ padding: 0.25rem 0.5rem;+ border-radius: 0.25rem;+ font-style: normal;+ font-weight: 500;+ display: flex;+ align-items: center;+ gap: 0.25rem;}-#hi-server-error-msg {- position: fixed;- display: none;- top: 50%;- left: 50%;- transform: translate(-50%, -50%);- padding: 1rem;- z-index: 1060;- text-align: center;- font-size: 2rem;++.attr-v2-status-message.success::before {+ content: '✓';font-weight: bold;- color: var(--warning-color);- background-color: #282425;- border-radius: 0.8rem;- border: 0.1rem solid #282425;- box-shadow: 0 0 1rem rgba(0, 0, 0, 0.5);+ color: var(--success-color, #28a745);}-#hi-server-error-msg > div {- margin-top: 1rem;- padding: 3rem;- width: 36rem;- height: 14rem;- color: #282425;- font-size: 4rem;- background-color: var(--warning-color);- border-bottom-left-radius: 0.8rem;- border-bottom-right-radius: 0.8rem;- text-align: center;+/* Scrollable Content Area (Natural Scrolling) */+.attr-v2-scrollable-content {+ padding: 1rem 0;+ /* Natural scrolling - no height restrictions or overflow settings */}-svg[action-state="move"] {- cursor: move;+/* Touch-friendly Form Controls - Consistent heights */+.attr-v2-modal input,+.attr-v2-modal select,+.attr-v2-modal textarea {+ min-height: 44px; /* Touch-friendly minimum for form inputs */+ padding: 0.75rem;+ font-size: 0.875rem;+ border-radius: 0.375rem;}-svg[action-state="rotate"] {- cursor: url('/static/css/cursor-rotate.png') 16 16, auto;++.attr-v2-modal input[type="text"],+.attr-v2-modal input[type="email"],+.attr-v2-modal input[type="url"],+.attr-v2-modal select {+ height: 44px; /* Exact height for single-line inputs */}-svg[action-state="scale"] {- cursor: url('/static/css/cursor-scale.png') 16 16, auto;++.attr-v2-modal textarea {+ min-height: 44px;+ resize: vertical;}-svg .highlighted {- filter: drop-shadow(0 0 10px var(--status-highlighted-color));+/* Section Titles - Reduced size to match mockup */+.attr-v2-section-title {+ font-size: 0.875rem;+ font-weight: 600;+ color: var(--secondary-text-color);+ margin-bottom: 0.5rem;+ padding-bottom: 0.25rem;+ text-transform: uppercase;+ letter-spacing: 0.025em;+ border-bottom: 1px solid var(--line-color);}-g.hi-icon {- pointer-events: all;+/* File Grid Layout */+.attr-v2-file-section {+ margin-bottom: 2rem;}-path.hi-path-closed[hover] {++.attr-v2-file-grid {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: 1rem;+ margin-top: 0.75rem;}-path.hover-target {- stroke: none;- stroke-width: 10;- fill: none;- pointer-events: all;++.attr-v2-file-card {+ /* No border or padding on main card - components handle their own styling */+ border-radius: 0.375rem;+ background: transparent;+ transition: all 0.2s ease;+ display: flex;+ flex-direction: column;+ overflow: hidden; /* Maintain rounded corners */}-path.hi-path-closed[hover] {- stroke: var(--status-hover-color);- stroke-width: 4;++.attr-v2-file-thumbnail {+ position: relative;+ display: flex;+ flex-direction: column;+ align-items: center;+ padding: 1rem;+ /* Diagonal hatch pattern background */+ background: repeating-linear-gradient(+ 45deg,+ #f8f9fa,+ #f8f9fa 10px,+ #e9ecef 10px,+ #e9ecef 20px+ );+ border-radius: 0.375rem 0.375rem 0 0; /* Rounded top corners only */+ cursor: pointer;}-path.hover-target[hover] + path.hi-path-open {- stroke: var(--status-hover-color);- stroke-width: 5;- filter: drop-shadow(0 0 5px var(--status-hover-color));++.attr-v2-file-type-label {+ font-size: 0.8rem;+ font-weight: 700;+ color: var(--text-color);+ margin-top: 0.5rem;+ text-transform: uppercase;+ letter-spacing: 0.05em;}-g[status="active"] {- outline: 2px solid var(--status-active-color);- filter: drop-shadow(0 0 5px var(--status-active-color));+.attr-v2-file-info {+ flex-grow: 1;+ background: var(--white);+ border: 1px solid var(--line-color);+ border-top: none; /* No border on top - seamless with thumbnail */+ border-radius: 0 0 0.375rem 0.375rem; /* Rounded bottom corners only */+ padding: 0.75rem;}-g[status="recent"] {- outline: 2px solid var(--status-recent-color);- filter: drop-shadow(0 0 5px var(--status-recent-color));++.attr-v2-file-name {+ font-size: 0.875rem;+ font-weight: 500;+ margin-bottom: 0.25rem;+ word-break: break-word;}-g[status="past"] {- outline: 2px solid var(--status-past-color);- filter: drop-shadow(0 0 5px var(--status-past-color));++/* File title input - styled to appear like text initially */+.attr-v2-file-title-input {+ font-size: 0.875rem;+ font-weight: 500;+ margin-bottom: 0.25rem;+ word-break: break-word;++ /* Minimal styling - appears like text */+ border: 1px solid transparent;+ background: transparent;+ padding: 2px 4px;+ border-radius: 3px;+ width: 100%;+ transition: all 0.2s ease;++ /* Inherit text color and font */+ color: inherit;+ font-family: inherit;+ line-height: inherit;}-g[status="off"] path.hi-state-bg {- fill: var(--status-off-color);+/* Focused and activated state - stronger input appearance */+.attr-v2-file-title-input:focus,+.attr-v2-file-title-input.activated {+ border-color: var(--primary-color, #007bff);+ background: var(--white, #ffffff);+ box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);+ outline: none;}-div[status="off"] {- color: var(--on-status-off-color);- background-color: var(--status-off-color);++/* Hover state - subtle indication it's interactive */+.attr-v2-file-title-input:hover:not(:focus) {+ border-color: var(--line-color, #dee2e6);+ background: rgba(0, 0, 0, 0.02);}-g[status="on"] {- filter: drop-shadow(0 0 5px var(--status-on-color));++.attr-v2-file-filename {+ font-size: 0.75rem;+ color: var(--muted-color);+ word-break: break-word;}-g[status="on"] path.hi-state-bg {- fill: var(--status-on-color);++.attr-v2-file-actions {+ display: flex;+ gap: 0.25rem;+ justify-content: center;+ margin-top: 0.75rem;+ padding-top: 0.75rem;+ border-top: 1px solid var(--line-color);}-div[status="on"] {- color: var(--on-status-on-color);- background-color: var(--status-on-color);++.attr-v2-file-actions button {+ min-height: 44px; /* Touch-friendly minimum */+ min-width: 44px;+ padding: 0.375rem;+ font-size: 0.875rem;+ border-radius: 0.25rem;}-g[status="open"] {- filter: drop-shadow(0 0 5px var(--status-bad-color));+/* Reorder Controls - Overlay in upper right of thumbnail */+.attr-v2-reorder-controls {+ position: absolute;+ top: 4px;+ right: 4px;+ display: flex;+ flex-direction: row;+ gap: 1px;+ background: rgba(255, 255, 255, 0.9);+ border-radius: 0.25rem;+ padding: 2px;+ z-index: 1;}-g[status="connected"] {- filter: drop-shadow(0 0 5px var(--status-ok-color));++/* Disable thumbnail hover when hovering over reorder controls */+.attr-v2-file-thumbnail:hover:has(.attr-v2-reorder-controls:hover) {+ background-color: var(--background-color) !important;+ transform: none !important;}-g[status="disconnected"] {- filter: drop-shadow(0 0 5px var(--status-bad-color));++/* Enhance reorder controls hover state */+.attr-v2-reorder-controls:hover {+ background: rgba(255, 255, 255, 1);+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);}-g[status="high"] {- filter: drop-shadow(0 0 5px var(--status-ok-color));++/* Ensure buttons within controls maintain their hover states */+.attr-v2-reorder-controls button:hover {+ background-color: var(--background-color);+ border-color: var(--line-color);}-g[status="low"] {- filter: drop-shadow(0 0 5px var(--status-bad-color));++/* JavaScript-based hover state override */+.attr-v2-file-thumbnail.reorder-hover:hover {+ background-color: var(--background-color) !important;+ transform: none !important;}-div[status] {- color: var(--black);- background-color: var(--white);- border-color: var(--black);- border-style: solid;- border-width: 2px;- border-radius: 8px;+/* Fallback for browsers that don't support :has() - JavaScript handles it */+@supports not selector(:has(*)) {+ .attr-v2-file-thumbnail:hover:has(.attr-v2-reorder-controls:hover) {+ /* This won't work in unsupported browsers, JS handles it instead */+ }}-div[status="active"] {- color: var(--on-status-active-color);- background-color: var(--status-active-color);++.attr-v2-reorder-controls button {+ /* Touch-friendly size with small visual appearance */+ min-width: 24px;+ min-height: 24px;+ padding: 6px;+ font-size: 10px;+ line-height: 1;+ border-radius: 0.25rem;+ position: relative;+ /* Center the small chevron icon within the larger touch area */+ display: flex;+ align-items: center;+ justify-content: center;}-div[status="idle"] {- color: var(--on-status-ok-color);- background-color: var(--status-ok-color);++.attr-v2-reorder-controls button:disabled {+ opacity: 0.3;+ cursor: not-allowed;+ background-color: var(--background-color);+ border-color: var(--line-color);+ color: var(--muted-color);}-div[status="recent"] {- color: var(--on-status-recent-color);- background-color: var(--status-recent-color);++.attr-v2-reorder-controls button:disabled:hover {+ transform: none;+ box-shadow: none;}-div[status="past"] {- color: var(--on-status-past-color);- background-color: var(--status-past-color);++/* Attribute List Layout */+.attr-v2-attribute-section {+ margin-bottom: 2rem;}-div[status="open"] {- color: var(--on-status-bad-color);- background-color: var(--status-bad-color);++.attr-v2-attribute-list {+ display: flex;+ flex-direction: column;+ gap: 0.75rem;}-div[status="closed"] {- color: var(--on-status-idle-color);- background-color: var(--status-idle-color);++.attr-v2-attribute-card {+ border: 1px solid var(--line-color);+ border-radius: 0.375rem;+ padding: 0.75rem;+ background: var(--white);+ transition: all 0.2s ease;}-div[status="RAID_OK"],-div[status="connected"] {- color: var(--on-status-ok-color);- background-color: var(--status-ok-color);++.attr-v2-attribute-header {+ display: flex;+ justify-content: space-between;+ align-items: flex-start;+ margin-bottom: 0.5rem;}-div[status="disconnected"] {- color: var(--on-status-bad-color);- background-color: var(--status-bad-color);++.attr-v2-attribute-name {+ font-size: 0.875rem;+ font-weight: 500;+ margin: 0;+ display: flex;+ align-items: center;+ gap: 0.5rem;}-div[status="high"] {- color: var(--on-status-ok-color);- background-color: var(--status-ok-color);++.attr-v2-attribute-actions {+ display: flex;+ gap: 0.25rem;}-div[status="low"] {- color: var(--on-status-bad-color);- background-color: var(--status-bad-color);++.attr-v2-attribute-actions button {+ padding: 0.375rem;+ min-width: 44px; /* Touch-friendly minimum */+ min-height: 44px; /* Touch-friendly minimum */+ border: none;+ background: transparent;+ color: var(--secondary-text-color);+ border-radius: 0.25rem;+ font-size: 0.875rem;}-g[hover] {- filter: drop-shadow(0 0 10px var(--status-hover-color)) !important;+.attr-v2-attribute-actions button:hover {+ background: var(--background-color);+ color: var(--text-color);}-.display-only-svg-icon {- width: 2rem;- height: auto;+.attr-v2-attribute-value {+ margin-top: 0.5rem;}-.switch {- position: relative;- display: inline-block;- width: 50px;- height: 24px;+/* Comprehensive Visual State System */+++/* Error State (validation failures) */+.attr-v2-file-card.error,+.attr-v2-attribute-card.error {+ border-left: 3px solid var(--danger-color);+ background-color: rgba(220, 53, 69, 0.1);+ box-shadow: 0 2px 4px rgba(220, 53, 69, 0.1);}-.switch input {- opacity: 0;- width: 0;- height: 0;++.attr-v2-error-message {+ color: var(--danger-color);+ font-size: 0.875rem;+ margin-top: 0.25rem;+ display: flex;+ align-items: center;+ gap: 0.25rem;}-.slider {++/* Loading State (during operations) */+.attr-v2-file-card.loading,+.attr-v2-attribute-card.loading {+ opacity: 0.7;+ pointer-events: none;+ position: relative;+}++.attr-v2-loading-overlay {position: absolute;- cursor: pointer;top: 0;left: 0;right: 0;bottom: 0;- background-color: #ccc;- transition: 0.4s;- border-radius: 24px;+ background: rgba(255, 255, 255, 0.8);+ display: flex;+ align-items: center;+ justify-content: center;+ border-radius: 0.25rem;}-.slider:before {- position: absolute;- content: "";- height: 18px;- width: 18px;- left: 3px;- bottom: 3px;- background-color: white;- transition: 0.4s;++.attr-v2-loading-spinner {+ width: 20px;+ height: 20px;+ border: 2px solid var(--line-color);+ border-top: 2px solid var(--primary-color);border-radius: 50%;-}-.switch input:checked + .slider {- background-color: var(--success-color);-}-.switch input:checked + .slider:before {- transform: translateX(26px);+ animation: spin 1s linear infinite;}-#hi-alert-banner-container {+/* Success State (after successful operations) */+.attr-v2-file-card.success,+.attr-v2-attribute-card.success {+ border-left: 3px solid var(--success-color);+ background-color: var(--success-bg-light);+ transition: all 0.3s ease;}-.hi-alarm-level-info {- color: var(--on-success-color);- background-color: var(--success-color);++.attr-v2-success-message {+ color: var(--success-color);+ font-size: 0.875rem;+ margin-top: 0.25rem;+ display: flex;+ align-items: center;+ gap: 0.25rem;}-.hi-alarm-level-warning {- color: var(--on-warning-color);- background-color: var(--warning-color);++.attr-v2-undo-delete {+ margin-top: 0.5rem;+ padding: 0.5rem;+ background: rgba(255, 193, 7, 0.1);+ border: 1px solid var(--warning-color);+ border-radius: 0.25rem;}-.hi-alarm-level-critical {- color: var(--on-error-color);- background-color: var(--error-color);+.attr-v2-undo-delete button {+ min-height: 32px;+ padding: 0.25rem 0.75rem;}-#hi-sleep-overlay {- position: fixed;- display: none;- top: 0;- left: 0;- width: 100%;- height: 100%;- background-color: black;- z-index: 9999;- transition: opacity 0.3s ease;+/* Animation Keyframes */+@keyframes pulse {+ 0% { opacity: 1; }+ 50% { opacity: 0.5; }+ 100% { opacity: 1; }}-.scroll-container {- overflow-x: auto;- white-space: nowrap;- adding-bottom: 10px;+@keyframes spin {+ 0% { transform: rotate(0deg); }+ 100% { transform: rotate(360deg); }}-.row.flex-nowrap {- flex-wrap: nowrap;+@keyframes fadeIn {+ 0% { opacity: 0; transform: translateY(-10px); }+ 100% { opacity: 1; transform: translateY(0); }}-.weather-forecast-daily-col {- min-width: 100px;++@keyframes slideUp {+ 0% { opacity: 1; transform: translateY(0); }+ 100% { opacity: 0; transform: translateY(-10px); }}+/* Smooth Transitions for All Interactive Elements */-.details-popup-wrapper {- position: relative;-}-.details-popup-summary {- cursor: pointer;-}-.details-popup-content {- display: none;- position: absolute;- top: 100%;- left: 0;- z-index: 10;- background: white;- border: 1px solid #ccc;- padding: 1em;- width: 100%;- box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);- cursor: pointer;+/* Card State Transitions */+.attr-v2-file-card,+.attr-v2-attribute-card {+ transition: all 0.2s ease-in-out;}-/* Camera button status styling */-.btn-camera[status="active"] {- color: var(--on-status-active-color) !important;- background-color: var(--status-active-color) !important;- border-color: var(--status-active-color) !important;- box-shadow: 0 0 5px var(--status-active-color);+.attr-v2-file-card:hover,+.attr-v2-attribute-card:hover {+ transform: translateY(-1px);+ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);}-.btn-camera[status="recent"] {- color: var(--on-status-recent-color) !important;- background-color: var(--status-recent-color) !important;- border-color: var(--status-recent-color) !important;- box-shadow: 0 0 3px var(--status-recent-color);+/* Button Transitions */+.attr-v2-action-buttons button,+.attr-v2-file-actions button,+.attr-v2-attribute-actions button,+.attr-v2-reorder-controls button,+#attr-v2-update-btn {+ transition: all 0.15s ease;}-.btn-camera[status="past"] {- color: var(--on-status-past-color) !important;- background-color: var(--status-past-color) !important;- border-color: var(--status-past-color) !important;+.attr-v2-action-buttons button:hover,+.attr-v2-file-actions button:hover,+.attr-v2-attribute-actions button:hover,+.attr-v2-reorder-controls button:hover:not(:disabled),+#attr-v2-update-btn:hover {+ transform: translateY(-1px);+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);}-.btn-camera[status="idle"] {- /* Default button styling - no changes needed */+/* Form Element Transitions */+.attr-v2-modal input,+.attr-v2-modal select,+.attr-v2-modal textarea {+ transition: border-color 0.15s ease, box-shadow 0.15s ease;}-/* Auto-view indicator styling */-/* Auto-view transient state styling */-.auto-view-active {- border: 3px solid var(--warning-color) !important;- border-radius: 4px;- box-shadow: 0 0 0 1px rgba(236, 165, 0, 0.3);- transition: all 0.3s ease-in-out;+.attr-v2-modal input:focus,+.attr-v2-modal select:focus,+.attr-v2-modal textarea:focus {+ border-color: var(--primary-color);+ box-shadow: 0 0 0 0.2rem rgba(23, 112, 114, 0.25);+ outline: none;}-.auto-view-corner-badge {- background-color: var(--warning-color);- color: var(--on-warning-color);- padding: 6px 12px;- border-radius: 0;- font-size: 12px;- font-weight: 500;- display: flex;- align-items: center;- gap: 4px;- box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.15);- width: auto;- min-width: fit-content;- backdrop-filter: blur(5px);- pointer-events: none;- border-top: 1px solid rgba(236, 165, 0, 0.3);- border-left: 1px solid rgba(236, 165, 0, 0.3);+/* Enhanced focus states for buttons and interactive elements */+.attr-v2-action-buttons button:focus,+.attr-v2-file-actions button:focus,+.attr-v2-attribute-actions button:focus,+.attr-v2-reorder-controls button:focus,+#attr-v2-update-btn:focus {+ outline: 2px solid var(--primary-color);+ outline-offset: 2px;+ box-shadow: 0 0 0 0.2rem rgba(23, 112, 114, 0.25);}-.auto-view-badge-icon {- font-size: 14px;- opacity: 0.9;+.attr-v2-reorder-controls button:focus:disabled {+ outline-color: var(--muted-color);+ box-shadow: 0 0 0 0.2rem rgba(126, 126, 129, 0.25);}-.auto-view-badge-text {- white-space: nowrap;- overflow: hidden;- text-overflow: ellipsis;+/* Card focus states for keyboard navigation */+.attr-v2-file-card:focus-within,+.attr-v2-attribute-card:focus-within {+ outline: 2px solid var(--primary-color);+ outline-offset: 2px;}-/* Removed pulse animation as requested */+/* Add form focus enhancement */+.attr-v2-add-form:focus-within {+ box-shadow: 0 4px 12px rgba(23, 112, 114, 0.15);+}-/* Responsive adjustments for smaller screens */-@media (max-width: 768px) {- .auto-view-corner-badge {- font-size: 11px;- padding: 4px 8px;- }-- .auto-view-badge-icon {- font-size: 12px;- }+/* Add Form Animation */+.attr-v2-add-form {+ transition: all 0.3s ease;+ animation: fadeIn 0.3s ease when visible;}-/* ===== ATTRIBUTE CHANGE INDICATORS ===== */+.attr-v2-add-form.collapsed {+ display: none;+}-/* Visual indicator for modified attribute fields */-.attribute-modified {- border: 2px solid var(--warning-color) !important;- background-color: rgba(236, 165, 0, 0.05);- transition: border-color 0.2s ease-in-out, background-color 0.2s ease-in-out;+.attr-v2-add-form:not(.collapsed) {+ animation: fadeIn 0.3s ease;}-/* Asterisk indicator for modified fields */-.attribute-modified-indicator {- color: var(--warning-color);- font-weight: bold;- font-size: 1.1em;- margin-left: 4px;+/* Modal Overlay Transitions */+.attr-v2-modal-overlay {+ transition: opacity 0.3s ease;}+.attr-v2-overlay-content {+ transition: transform 0.3s ease;+ transform: scale(0.9);+}-/* Focus states for modified fields */-.attribute-modified:focus {- border-color: var(--warning-color);- box-shadow: 0 0 0 0.2rem rgba(236, 165, 0, 0.25);+.attr-v2-modal-overlay:not([style*="display: none"]) .attr-v2-overlay-content {+ transform: scale(1);}-/* Dirty form styling - submit button enhancement */-form[data-dirty] .btn-primary[type="submit"] {- background-color: var(--warning-color) !important;- border-color: var(--warning-color) !important;- color: var(--on-warning-color) !important;+/* Status Message Transitions */+.attr-v2-status-message {+ transition: opacity 0.25s ease, color 0.25s ease;}-form[data-dirty] button[type="submit"]:hover {- background-color: #d39e00 !important; /* Darker shade of warning color */- border-color: #d39e00 !important;+/* Thumbnail Hover Effect */+.attr-v2-file-thumbnail {+ transition: background-color 0.15s ease, transform 0.15s ease;}-/* Dirty form styling - subtle form background */-form[data-dirty] {- background-color: rgba(236, 165, 0, 0.2) !important;- border-radius: 4px;- transition: background-color 0.2s ease-in-out;+.attr-v2-file-thumbnail:hover {+ background-color: var(--primary-color-light, #e7f3ff);+ transform: scale(1.02);}-/* History icon styling - matches plus-icon pattern */-.history-icon {- font-size: 1rem;- color: var(--primary-color);- padding: 0 0.25rem;+/* Responsive Design - Mobile First with Tablet Primary */++/* Small screens - 2 columns for very narrow widths */+@media (max-width: 575px) {+ /* Adjust modal for very small screens */+ .hi-modal-dialog-700 {+ max-width: 95%;+ margin: 0.5rem;+ }++ /* File grid: 2 columns on very small screens */+ .attr-v2-file-grid {+ grid-template-columns: repeat(2, 1fr);+ gap: 0.75rem;+ }}-/* ==========================================- Video Interface - Camera Event History- ========================================== */+/* Mobile Landscape (576px to 1023px) - Keep 3 columns */+@media (min-width: 576px) and (max-width: 1023px) {+ /* File grid maintains 3 columns */+ .attr-v2-file-grid {+ grid-template-columns: repeat(3, 1fr);+ gap: 0.875rem;+ }++ /* Action bar may stack buttons vertically on very small landscape */+ .attr-v2-action-bar-content {+ flex-direction: column;+ gap: 0.75rem;+ align-items: stretch;+ }++ .attr-v2-action-buttons {+ justify-content: center;+ flex-wrap: wrap;+ }++ /* Attrribute actions stack vertically */+ .attr-v2-attribute-actions {+ flex-direction: column;+ gap: 0.25rem;+ align-items: flex-end;+ }+}-/* Timeline Container */-.timeline-container {- max-height: 600px;- overflow-y: auto;+/* Tablet Landscape (1024px+) - PRIMARY TARGET */+@media (min-width: 1024px) {+ /* Optimal layout - all features at full capacity */+ .hi-modal-dialog-700 {+ max-width: 700px;+ }++ /* File grid: 3 columns optimal */+ .attr-v2-file-grid {+ grid-template-columns: repeat(3, 1fr);+ gap: 1rem;+ }++ /* Action bar horizontal layout */+ .attr-v2-action-bar-content {+ flex-direction: row;+ justify-content: space-between;+ align-items: center;+ }++ /* Enhanced hover effects for mouse/trackpad */+ .attr-v2-file-card:hover,+ .attr-v2-attribute-card:hover {+ transform: translateY(-2px);+ box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);+ }++ /* Better button spacing */+ .attr-v2-attribute-actions {+ flex-direction: row;+ gap: 0.25rem;+ }+}++/* Desktop (1200px+) - SECONDARY TARGET */+@media (min-width: 1200px) {+ /* Enhanced layout with more space - maintain 3 columns */+ .attr-v2-file-grid {+ grid-template-columns: repeat(3, 1fr);+ gap: 1.25rem;+ }++ /* More generous spacing */+ .attr-v2-scrollable-content {+ padding: 1.5rem 0;+ }++ .attr-v2-attribute-list {+ gap: 1rem;+ }++ /* Enhanced hover effects */+ .attr-v2-file-card:hover,+ .attr-v2-attribute-card:hover {+ transform: translateY(-3px);+ box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15);+ }++ /* Larger touch targets can be more refined */+ .attr-v2-reorder-controls button,+ .attr-v2-attribute-actions button {+ min-width: 32px;+ min-height: 32px;+ padding: 8px;+ }+}++/* High DPI / Retina Displays */+@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {+ /* Sharper borders and shadows */+ .attr-v2-file-card,+ .attr-v2-attribute-card {+ border-width: 0.5px;+ }++ .attr-v2-sticky-panel {+ border-bottom-width: 0.5px;+ }+}++/* Touch Device Optimizations */+@media (hover: none) and (pointer: coarse) {+ /* Touch-only devices: remove hover effects, ensure touch targets */+ .attr-v2-file-card:hover,+ .attr-v2-attribute-card:hover,+ .attr-v2-file-thumbnail:hover,+ .attr-v2-action-buttons button:hover,+ .attr-v2-file-actions button:hover,+ .attr-v2-attribute-actions button:hover {+ transform: none;+ box-shadow: none;+ background-color: initial;+ }++ /* Ensure all touch targets are adequate */+ .attr-v2-attribute-actions button,+ .attr-v2-file-actions button,+ .attr-v2-reorder-controls button {+ min-height: 44px; /* Touch-friendly standard */+ min-width: 44px;+ padding: 10px;+ }+}++/* Reduced Motion Preference */+@media (prefers-reduced-motion: reduce) {+ /* Disable animations for users who prefer reduced motion */+ .attr-v2-file-card,+ .attr-v2-attribute-card,+ .attr-v2-action-buttons button,+ .attr-v2-file-actions button,+ .attr-v2-attribute-actions button,+ .attr-v2-reorder-controls button,+ .attr-v2-modal input,+ .attr-v2-modal select,+ .attr-v2-modal textarea,+ .attr-v2-add-form,+ .attr-v2-modal-overlay,+ .attr-v2-overlay-content,+ .attr-v2-file-thumbnail {+ animation: none;+ transition: none;+ }+++ .attr-v2-loading-spinner {+ animation: spin 0.1s linear infinite;+ }+}++/* Add Attrribute Form */+.attr-v2-add-form {+ border: 1px solid var(--line-color);+ border-radius: 0.375rem;+ background: var(--white);+ margin-top: 1rem;+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);+ transition: all 0.3s ease;+ overflow: hidden;+}++.attr-v2-add-form.collapsed {+ display: none;+}++.attr-v2-add-form-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ padding: 0.75rem 1rem;+ border-bottom: 1px solid var(--line-color);+ background: var(--background-color);+}++.attr-v2-add-form-header h6 {+ margin: 0;+ font-size: 0.875rem;+ font-weight: 600;+ color: var(--text-color);+}++.attr-v2-add-form-content {+ padding: 1rem;+}++.attr-v2-add-form-actions {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-top: 1rem;+ padding-top: 1rem;+ border-top: 1px solid var(--line-color);+}++/* Add form field layout improvements */+.attr-v2-add-form-content .row {+ align-items: end;+}++.attr-v2-add-form-content .custom-control {+ padding-top: 0.5rem;+}++/* Modal-over-Modal Overlay Pattern */+.attr-v2-modal-overlay {+ position: fixed;+ top: 0;+ left: 0;+ width: 100%;+ height: 100%;+ background: rgba(0, 0, 0, 0.7);+ z-index: 1055; /* Above Bootstrap modal (1050) */+ display: flex;+ align-items: center;+ justify-content: center;+}++.attr-v2-overlay-content {+ background: var(--white);+ border-radius: 0.5rem;+ max-width: 500px;+ max-height: 70vh;+ width: 90%;+ box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);+ display: flex;+ flex-direction: column;+}++.attr-v2-overlay-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ padding: 1rem;+ border-bottom: 1px solid var(--line-color);+ flex-shrink: 0;+}++.attr-v2-overlay-header h6 {+ margin: 0;+ font-size: 1rem;+ font-weight: 600;+}++.attr-v2-overlay-body {+ padding: 1rem;+ overflow-y: auto;+ flex-grow: 1;+}++.btn-control {+ width: 100%;+ white-space: nowrap;+ font-size: 0.75rem;+ font-weight: bold;+}++input[type="number"] {+ max-width: 8rem;+}+.hi-location-view {+ justify-content: center;+ align-items: center;+ height: calc(100vh - var(--top-buttons-height) - var(--bottom-buttons-height) );+ touch-action: none;++}+.hi-location-view-svg {+ max-height: calc(100vh - var(--top-buttons-height) - var(--bottom-buttons-height) );+ width: auto;+ height: auto;+ display: block;+ cursor: pointer;+}++#hi-integration-settings nav {+ border-right: 1px solid #888888;+ height: calc( 100vh - var(--top-buttons-height) - var(--bottom-buttons-height) - 6rem);+ overflow-y: auto;+}+#hi-integration-settings nav hr {+ flex: 0 0 auto; /* Prevent shrinking or growing */+ width: 100%;+ border-top: 1px solid #202020;+}+.drag-over {+ border: 2px dashed #888888;+}++.form-group label {+ color: #060606 !important;+}+.input-group-text {+ color: var(--black);+ background-color: #f0f0f0;+}+select,+textarea,+input[type="text"],+input[type="password"],+.dropdown-menu {+ color: var(--black) !important;+ background-color: #f8f8f8 !important;+}+.hi-custom-select .input-group-text {+ height: calc(1.5em + 0.75rem + 2px);+ line-height: 1.5;+}+.plus-icon {+ font-size: 1.5rem;+ color: var(--on-primary-color);+ background-color: var(--primary-color);+ padding: 0 0.25rem 0 0.25rem;+}+#hi-server-error-msg {+ position: fixed;+ display: none;+ top: 50%;+ left: 50%;+ transform: translate(-50%, -50%);+ padding: 1rem;+ z-index: 1060;+ text-align: center;+ font-size: 2rem;+ font-weight: bold;+ color: var(--warning-color);+ background-color: #282425;+ border-radius: 0.8rem;+ border: 0.1rem solid #282425;+ box-shadow: 0 0 1rem rgba(0, 0, 0, 0.5);+}++#hi-server-error-msg > div {+ margin-top: 1rem;+ padding: 3rem;+ width: 36rem;+ height: 14rem;+ color: #282425;+ font-size: 4rem;+ background-color: var(--warning-color);+ border-bottom-left-radius: 0.8rem;+ border-bottom-right-radius: 0.8rem;+ text-align: center;+}++svg[action-state="move"] {+ cursor: move;+}+svg[action-state="rotate"] {+ cursor: url('/static/css/cursor-rotate.png') 16 16, auto;+}+svg[action-state="scale"] {+ cursor: url('/static/css/cursor-scale.png') 16 16, auto;+}++svg .highlighted {+ filter: drop-shadow(0 0 10px var(--status-highlighted-color));+}++g.hi-icon {+ pointer-events: all;+}+path.hi-path-closed[hover] {+}+path.hover-target {+ stroke: none;+ stroke-width: 10;+ fill: none;+ pointer-events: all;+}+path.hi-path-closed[hover] {+ stroke: var(--status-hover-color);+ stroke-width: 4;+}+path.hover-target[hover] + path.hi-path-open {+ stroke: var(--status-hover-color);+ stroke-width: 5;+ filter: drop-shadow(0 0 5px var(--status-hover-color));+}++g[status="active"] {+ outline: 2px solid var(--status-active-color);+ filter: drop-shadow(0 0 5px var(--status-active-color));+}+g[status="recent"] {+ outline: 2px solid var(--status-recent-color);+ filter: drop-shadow(0 0 5px var(--status-recent-color));+}+g[status="past"] {+ outline: 2px solid var(--status-past-color);+ filter: drop-shadow(0 0 5px var(--status-past-color));+}++g[status="off"] path.hi-state-bg {+ fill: var(--status-off-color);+}+div[status="off"] {+ color: var(--on-status-off-color);+ background-color: var(--status-off-color);+}+g[status="on"] {+ filter: drop-shadow(0 0 5px var(--status-on-color));+}+g[status="on"] path.hi-state-bg {+ fill: var(--status-on-color);+}+div[status="on"] {+ color: var(--on-status-on-color);+ background-color: var(--status-on-color);+}++g[status="open"] {+ filter: drop-shadow(0 0 5px var(--status-bad-color));+}+g[status="connected"] {+ filter: drop-shadow(0 0 5px var(--status-ok-color));+}+g[status="disconnected"] {+ filter: drop-shadow(0 0 5px var(--status-bad-color));+}+g[status="high"] {+ filter: drop-shadow(0 0 5px var(--status-ok-color));+}+g[status="low"] {+ filter: drop-shadow(0 0 5px var(--status-bad-color));+}++div[status] {+ color: var(--black);+ background-color: var(--white);+ border-color: var(--black);+ border-style: solid;+ border-width: 2px;+ border-radius: 8px;+}+div[status="active"] {+ color: var(--on-status-active-color);+ background-color: var(--status-active-color);+}+div[status="idle"] {+ color: var(--on-status-ok-color);+ background-color: var(--status-ok-color);+}+div[status="recent"] {+ color: var(--on-status-recent-color);+ background-color: var(--status-recent-color);+}+div[status="past"] {+ color: var(--on-status-past-color);+ background-color: var(--status-past-color);+}+div[status="open"] {+ color: var(--on-status-bad-color);+ background-color: var(--status-bad-color);+}+div[status="closed"] {+ color: var(--on-status-idle-color);+ background-color: var(--status-idle-color);+}+div[status="RAID_OK"],+div[status="connected"] {+ color: var(--on-status-ok-color);+ background-color: var(--status-ok-color);+}+div[status="disconnected"] {+ color: var(--on-status-bad-color);+ background-color: var(--status-bad-color);+}+div[status="high"] {+ color: var(--on-status-ok-color);+ background-color: var(--status-ok-color);+}+div[status="low"] {+ color: var(--on-status-bad-color);+ background-color: var(--status-bad-color);+}++g[hover] {+ filter: drop-shadow(0 0 10px var(--status-hover-color)) !important;+}++.display-only-svg-icon {+ width: 2rem;+ height: auto;+}++.switch {+ position: relative;+ display: inline-block;+ width: 50px;+ height: 24px;+}+.switch input {+ opacity: 0;+ width: 0;+ height: 0;+}+.slider {+ position: absolute;+ cursor: pointer;+ top: 0;+ left: 0;+ right: 0;+ bottom: 0;+ background-color: #ccc;+ transition: 0.4s;+ border-radius: 24px;+}+.slider:before {+ position: absolute;+ content: "";+ height: 18px;+ width: 18px;+ left: 3px;+ bottom: 3px;+ background-color: white;+ transition: 0.4s;+ border-radius: 50%;+}+.switch input:checked + .slider {+ background-color: var(--success-color);+}+.switch input:checked + .slider:before {+ transform: translateX(26px);+}++#hi-alert-banner-container {+}+.hi-alarm-level-info {+ color: var(--on-success-color);+ background-color: var(--success-color);+}++.hi-alarm-level-warning {+ color: var(--on-warning-color);+ background-color: var(--warning-color);+}++.hi-alarm-level-critical {+ color: var(--on-error-color);+ background-color: var(--error-color);+}++#hi-sleep-overlay {+ position: fixed;+ display: none;+ top: 0;+ left: 0;+ width: 100%;+ height: 100%;+ background-color: black;+ z-index: 9999;+ transition: opacity 0.3s ease;+}++.scroll-container {+ overflow-x: auto;+ white-space: nowrap;+ adding-bottom: 10px;+}++.row.flex-nowrap {+ flex-wrap: nowrap;+}+.weather-forecast-daily-col {+ min-width: 100px;+}+++.details-popup-wrapper {+ position: relative;+}+.details-popup-summary {+ cursor: pointer;+}+.details-popup-content {+ display: none;+ position: absolute;+ top: 100%;+ left: 0;+ z-index: 10;+ background: white;+ border: 1px solid #ccc;+ padding: 1em;+ width: 100%;+ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);+ cursor: pointer;+}++/* Camera button status styling */+.btn-camera[status="active"] {+ color: var(--on-status-active-color) !important;+ background-color: var(--status-active-color) !important;+ border-color: var(--status-active-color) !important;+ box-shadow: 0 0 5px var(--status-active-color);+}++.btn-camera[status="recent"] {+ color: var(--on-status-recent-color) !important;+ background-color: var(--status-recent-color) !important;+ border-color: var(--status-recent-color) !important;+ box-shadow: 0 0 3px var(--status-recent-color);+}++.btn-camera[status="past"] {+ color: var(--on-status-past-color) !important;+ background-color: var(--status-past-color) !important;+ border-color: var(--status-past-color) !important;+}++.btn-camera[status="idle"] {+ /* Default button styling - no changes needed */+}++/* Auto-view indicator styling */+/* Auto-view transient state styling */+.auto-view-active {+ border: 3px solid var(--warning-color) !important;+ border-radius: 4px;+ box-shadow: 0 0 0 1px rgba(236, 165, 0, 0.3);+ transition: all 0.3s ease-in-out;+}++.auto-view-corner-badge {+ background-color: var(--warning-color);+ color: var(--on-warning-color);+ padding: 6px 12px;+ border-radius: 0;+ font-size: 12px;+ font-weight: 500;+ display: flex;+ align-items: center;+ gap: 4px;+ box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.15);+ width: auto;+ min-width: fit-content;+ backdrop-filter: blur(5px);+ pointer-events: none;+ border-top: 1px solid rgba(236, 165, 0, 0.3);+ border-left: 1px solid rgba(236, 165, 0, 0.3);+}++.auto-view-badge-icon {+ font-size: 14px;+ opacity: 0.9;+}++.auto-view-badge-text {+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++/* Removed pulse animation as requested */++/* Responsive adjustments for smaller screens */+@media (max-width: 768px) {+ .auto-view-corner-badge {+ font-size: 11px;+ padding: 4px 8px;+ }++ .auto-view-badge-icon {+ font-size: 12px;+ }+}++/* ===== ATTRIBUTE CHANGE INDICATORS ===== */++/* Visual indicator for modified attribute fields */+.attribute-modified {+ border: 2px solid var(--warning-color) !important;+ background-color: rgba(236, 165, 0, 0.05);+ transition: border-color 0.2s ease-in-out, background-color 0.2s ease-in-out;+}++/* Asterisk indicator for modified fields */+.attribute-modified-indicator {+ color: var(--warning-color);+ font-weight: bold;+ font-size: 1.1em;+ margin-left: 4px;+}+++/* Focus states for modified fields */+.attribute-modified:focus {+ border-color: var(--warning-color);+ box-shadow: 0 0 0 0.2rem rgba(236, 165, 0, 0.25);+}+++/* History icon styling - matches plus-icon pattern */+.history-icon {+ font-size: 1rem;+ color: var(--primary-color);+ padding: 0 0.25rem;+}++/* ==========================================+ Video Interface - Camera Event History+ ========================================== */++/* Timeline Container */+.timeline-container {+ max-height: 600px;+ overflow-y: auto;background-color: var(--white);border-right: 1px solid var(--line-color);padding-right: 1rem;}-/* Timeline Groups */-.timeline-group-label {+/* Timeline Groups */+.timeline-group-label {+ color: var(--primary-color);+ padding: 8px 0;+ border-bottom: 2px solid var(--primary-color);+ margin-bottom: 12px;+ font-weight: 600;+ font-size: 0.875rem;+ text-transform: uppercase;+ letter-spacing: 0.5px;+}++/* Timeline Items */+.timeline-item {+ padding: 10px;+ margin-bottom: 6px;+ border-left: 3px solid var(--line-color);+ transition: all 0.2s ease;+ border-radius: 0 4px 4px 0;+}++.timeline-item:hover {+ background-color: var(--edit-primary-bg-color);+ border-left-color: var(--primary-highlight-color);+ transform: translateX(2px);+}++.timeline-item.active {+ background-color: var(--edit-primary-bg-color);+ border-left-color: var(--secondary-color);+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);+}++.timeline-item .time {+ font-weight: 500;+ color: var(--black);+}++.timeline-item.active .time {+ color: var(--primary-color);+}++/* Video Container */+.video-container {+ border: 2px solid var(--line-color);+ border-radius: 8px;+ overflow: hidden;+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);+ background-color: var(--black);+}++.video-container img {+ display: block;+ width: 100%;+ height: auto;+}++/* Event Header */+.response-header {+ border-bottom: 1px solid var(--line-color);+ padding-bottom: 0.75rem;+}++.response-header h6 {+ color: var(--primary-color);+ font-weight: 600;+ margin-bottom: 0.25rem;+}++/* Event Details Expansion Bar */+.response-details-bar {+ border-top: 1px solid var(--line-color);+ margin-top: 1.5rem;+}++.details-expander {+ display: flex;+ justify-content: space-between;+ align-items: center;+ padding: 0.75rem 1rem;+ background: linear-gradient(to bottom, #f8f9fa, #f1f3f5);+ text-decoration: none;+ color: #6c757d;+ transition: all 0.2s ease;+ cursor: pointer;+}++.details-expander:hover {+ background: #e9ecef;+ text-decoration: none;+ color: #495057;+}++.details-expander:focus {+ outline: 2px solid var(--primary-color);+ outline-offset: -2px;+ text-decoration: none;+}++.details-label {+ font-size: 0.9rem;+ font-weight: 500;+ letter-spacing: 0.5px;+ text-transform: uppercase;+}++.details-chevron {+ font-size: 0.8rem;+ transition: transform 0.2s ease;+}++.details-expander[aria-expanded="true"] .details-chevron {+ transform: rotate(180deg);+}++.details-content {+ padding: 1rem;+ background-color: #f8f9fa;+ border-top: 1px solid #e9ecef;+}++.detail-row {+ display: grid;+ grid-template-columns: minmax(120px, 1fr) 2fr;+ gap: 1rem;+ padding: 0.5rem 0;+ border-bottom: 1px solid #e9ecef;+}++.detail-row:last-child {+ border-bottom: none;+}++.detail-label {+ font-size: 0.85rem;+ color: #6c757d;+ font-weight: 500;+}++.detail-value {+ font-size: 0.85rem;+ color: #212529;+ word-break: break-word;+}++/* Timeline Pagination */+.timeline-pagination-top,+.timeline-pagination-bottom {+ padding: 0.25rem;+}++.timeline-pagination-top .btn,+.timeline-pagination-bottom .btn {+ font-size: 0.8rem;+ padding: 0.4rem;+ transition: all 0.2s ease;+ border-color: var(--primary-color);+ color: var(--primary-color);+}++.timeline-pagination-top .btn:hover,+.timeline-pagination-bottom .btn:hover {+ transform: translateY(-1px);+ background-color: var(--primary-color);+ color: var(--on-primary-color);+}+++/* ==========================================+ Loading States & Error Handling+ ========================================== */++/* Video Placeholder/Error State */+.video-placeholder {+ min-height: 400px;+ background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);+ border-radius: 8px;+ position: relative;+}++.video-placeholder-icon {+ color: var(--primary-color);+ opacity: 0.5;+}++.video-placeholder h5 {+ color: var(--primary-color);+ font-weight: 600;+}++.video-placeholder p {+ color: var(--black);+ opacity: 0.8;+}++/* Loading Animation for Video */+.video-container.loading {+ position: relative;+ min-height: 400px;+}++.video-container.loading::before {+ content: '';+ position: absolute;+ top: 0;+ left: 0;+ right: 0;+ bottom: 0;+ background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);+ background-size: 200% 100%;+ animation: loading 1.5s infinite;+ border-radius: 8px;+}++.video-container.loading::after {+ content: 'Loading video stream...';+ position: absolute;+ top: 50%;+ left: 50%;+ transform: translate(-50%, -50%);+ color: var(--primary-color);+ font-weight: 500;+}++@keyframes loading {+ 0% {+ background-position: 200% 0;+ }+ 100% {+ background-position: -200% 0;+ }+}++/* Error State for Timeline */+.timeline-container.error {+ background-color: var(--edit-secondary-bg-color);+ padding: 1rem;+ text-align: center;+}++.timeline-container.error::before {+ content: '⚠ Unable to load event history';+ color: var(--error-color);+ font-weight: 600;+}++/* ==========================================+ Accessibility & Keyboard Navigation+ ========================================== */++/* Focus indicators for keyboard navigation */+.timeline-item a:focus {+ outline: 2px solid var(--secondary-color);+ outline-offset: 2px;+ border-radius: 4px;+}+++/* High contrast mode support */+@media (prefers-contrast: high) {+ .timeline-item.active {+ border-left-width: 4px;+ font-weight: bold;+ }++ .timeline-group-label {+ border-bottom-width: 3px;+ }+}++/* Reduced motion support */+@media (prefers-reduced-motion: reduce) {+ .timeline-item,+ .video-container.loading::before {+ transition: none;+ animation: none;+ }+}++/* Screen reader only content */+.sr-only {+ position: absolute;+ width: 1px;+ height: 1px;+ padding: 0;+ margin: -1px;+ overflow: hidden;+ clip: rect(0, 0, 0, 0);+ white-space: nowrap;+ border: 0;+}++/* ==========================================+ Responsive Design - Landscape Optimized+ ========================================== */++/* Small landscape devices (landscape phones, 568px and up) */+@media (min-width: 568px) and (orientation: landscape) {+ .timeline-container {+ max-height: 400px; /* Reduce height for smaller landscape screens */+ }+}++/* Medium landscape devices (tablets, 768px and up) */+@media (min-width: 768px) and (orientation: landscape) {+ .timeline-container {+ max-height: 500px;+ }++ /* Optimize column widths for landscape tablets */+ .entity-video-sensor-history .col-md-3 {+ flex: 0 0 25%;+ max-width: 25%;+ }++ .entity-video-sensor-history .col-md-9 {+ flex: 0 0 75%;+ max-width: 75%;+ }+}++/* Large landscape devices (laptops/desktops, 992px and up) */+@media (min-width: 992px) and (orientation: landscape) {+ .timeline-container {+ max-height: 600px;+ }++ /* Wider timeline on larger screens */+ .entity-video-sensor-history .col-md-3 {+ flex: 0 0 20%;+ max-width: 20%;+ }++ .entity-video-sensor-history .col-md-9 {+ flex: 0 0 80%;+ max-width: 80%;+ }+}++/* Extra large landscape devices (large desktops, 1200px and up) */+@media (min-width: 1200px) {+ .video-container {+ max-width: 1000px; /* Limit video size on very large screens */+ margin: 0 auto;+ }+}++/* Landscape-specific optimizations */+@media (orientation: landscape) {+ /* Compact timeline items for landscape */+ .timeline-item {+ padding: 8px;+ margin-bottom: 4px;+ }++ .timeline-group-label {+ padding: 6px 0;+ margin-bottom: 8px;+ }+++ /* Compact details bar in landscape */+ .details-expander {+ padding: 0.5rem 0.75rem;+ }++ .details-content {+ padding: 0.75rem;+ }+}++/* Handle small screens that don't meet minimum requirements */+@media (max-width: 767px) {+ /* Stack detail rows on mobile */+ .detail-row {+ grid-template-columns: 1fr;+ gap: 0.25rem;+ }++ .detail-label {+ font-weight: 600;+ color: #495057;+ }++ .details-expander {+ padding: 0.6rem 0.75rem;+ }++ .details-label {+ font-size: 0.85rem;+ }+ /* Stack layout vertically on very small screens */+ .entity-video-sensor-history .row {+ flex-direction: column;+ }++ .entity-video-sensor-history .col-md-3,+ .entity-video-sensor-history .col-md-9 {+ max-width: 100%;+ width: 100%;+ }++ .timeline-container {+ max-height: 200px;+ margin-bottom: 1rem;+ border-right: none;+ border-bottom: 1px solid var(--line-color);+ }+}++/* Video Interface Header Styles */+.video-interface-header {+ border-bottom: 2px solid #e9ecef;+ padding: 0.75rem;+ margin: -0.75rem -0.75rem 0.75rem -0.75rem;+ border-radius: 0.5rem 0.5rem 0 0;+}++/* Page-specific header backgrounds */+.video-interface-header.current-stream {+ background-color: var(--secondary-color);+ color: var(--on-secondary-color);+ border-bottom-color: var(--secondary-color);+}++.video-interface-header.event-history {+ background-color: var(--tertiary-color);+ color: var(--on-tertiary-color);+ border-bottom-color: var(--tertiary-color);+}++.entity-title {+ color: #343a40;+ font-weight: 600;+ font-size: 1.1rem;+}++.video-interface-header.current-stream .entity-title,+.video-interface-header.event-history .entity-title {+ color: inherit;+}++.last-activity-badge {+ font-size: 0.85rem;+ padding: 0.25rem 0.5rem;+ background-color: #f8f9fa;+ border-radius: 12px;+ border: 1px solid #e9ecef;+}++.video-interface-header.current-stream .last-activity-badge {+ background-color: rgba(255, 255, 255, 0.2);+ border-color: rgba(255, 255, 255, 0.3);+ color: inherit;+}++.video-interface-header.event-history .last-activity-badge {+ background-color: rgba(255, 255, 255, 0.1);+ border-color: rgba(255, 255, 255, 0.2);+ color: inherit;+}++.video-nav-tabs {+ display: flex;+ gap: 0;+}++.video-nav-tab {+ padding: 0.5rem 1rem;+ text-decoration: none;+ color: #6c757d;+ border: 1px solid #dee2e6;+ background-color: #f8f9fa;+ transition: all 0.15s ease-in-out;+ position: relative;+ font-size: 0.9rem;+ font-weight: 500;+ cursor: pointer;+}++.video-nav-tab:first-child {+ border-top-left-radius: 0.375rem;+ border-bottom-left-radius: 0.375rem;+}++.video-nav-tab:last-child {+ border-top-right-radius: 0.375rem;+ border-bottom-right-radius: 0.375rem;+ border-left: none;+}++.video-nav-tab:not(:first-child):not(:last-child) {+ border-left: none;+}++.video-nav-tab:hover:not(.disabled):not(.active) {+ color: #495057;+ background-color: #e9ecef;+ text-decoration: none;+}++.video-nav-tab.active {+ color: #fff;+ background-color: #007bff;+ border-color: #007bff;+ z-index: 1;+}++/* Active tab styling for colored headers */+.video-interface-header.current-stream .video-nav-tab.active {+ background-color: rgba(255, 255, 255, 0.9);+ color: var(--secondary-color);+ border-color: rgba(255, 255, 255, 0.9);+}++.video-interface-header.event-history .video-nav-tab.active {+ background-color: rgba(255, 255, 255, 0.9);+ color: var(--tertiary-color);+ border-color: rgba(255, 255, 255, 0.9);+}++/* Inactive tab styling for colored headers */+.video-interface-header.current-stream .video-nav-tab:not(.active):not(.disabled),+.video-interface-header.event-history .video-nav-tab:not(.active):not(.disabled) {+ background-color: rgba(255, 255, 255, 0.1);+ color: rgba(255, 255, 255, 0.8);+ border-color: rgba(255, 255, 255, 0.2);+}++.video-interface-header.current-stream .video-nav-tab:hover:not(.disabled):not(.active),+.video-interface-header.event-history .video-nav-tab:hover:not(.disabled):not(.active) {+ background-color: rgba(255, 255, 255, 0.2);+ color: rgba(255, 255, 255, 1);+ border-color: rgba(255, 255, 255, 0.3);+}++.video-nav-tab.disabled {+ color: #6c757d;+ background-color: #f8f9fa;+ border-color: #dee2e6;+ cursor: not-allowed;+ opacity: 0.6;+}++/* Responsive adjustments */+@media (max-width: 768px) {+ .video-interface-header .d-flex {+ flex-direction: column;+ align-items: flex-start !important;+ gap: 0.75rem;+ }++ .video-nav-tabs {+ width: 100%;+ justify-content: center;+ }++ .video-nav-tab {+ flex: 1;+ text-align: center;+ font-size: 0.85rem;+ padding: 0.4rem 0.6rem;+ }++ .entity-title {+ font-size: 1rem;+ }++ .last-activity-badge {+ font-size: 0.8rem;+ }+}++@media (max-width: 480px) {+ .video-nav-tab i {+ display: none; /* Hide icons on very small screens */+ }++ .video-nav-tab {+ padding: 0.4rem 0.5rem;+ font-size: 0.8rem;+ }+}++/* ===== ICON SYSTEM ===== */++/* Base icon class */+.hi-icon {+ display: inline-block;+ vertical-align: middle;+ fill: currentColor;+ stroke: currentColor;+ flex-shrink: 0;+}++/* Icon sizes */+.hi-icon-sm {+ width: 0.875rem;+ height: 0.875rem;+}++.hi-icon-md {+ width: 1rem;+ height: 1rem;+}++.hi-icon-lg {+ width: 1.25rem;+ height: 1.25rem;+}++.hi-icon-xl {+ width: 1.5rem;+ height: 1.5rem;+}++/* Semantic icon colors using existing CSS variables */+.hi-icon-primary {color: var(--primary-color);- padding: 8px 0;- border-bottom: 2px solid var(--primary-color);- margin-bottom: 12px;- font-weight: 600;- font-size: 0.875rem;- text-transform: uppercase;- letter-spacing: 0.5px;}-/* Timeline Items */-.timeline-item {- padding: 10px;- margin-bottom: 6px;- border-left: 3px solid var(--line-color);- transition: all 0.2s ease;- border-radius: 0 4px 4px 0;+.hi-icon-secondary {+ color: var(--secondary-color);}-.timeline-item:hover {- background-color: var(--edit-primary-bg-color);- border-left-color: var(--primary-highlight-color);- transform: translateX(2px);+.hi-icon-success {+ color: var(--success-color);}-.timeline-item.active {- background-color: var(--edit-primary-bg-color);- border-left-color: var(--secondary-color);- box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);+.hi-icon-warning {+ color: var(--warning-color);}-.timeline-item .time {- font-weight: 500;- color: var(--black);+.hi-icon-error {+ color: var(--error-color);}-.timeline-item.active .time {- color: var(--primary-color);+.hi-icon-muted {+ color: var(--muted-color);}-/* Video Container */-.video-container {- border: 2px solid var(--line-color);- border-radius: 8px;- overflow: hidden;- box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);- background-color: var(--black);+/* Icon spacing utilities */+.hi-icon-left {+ margin-right: 0.375rem;}-.video-container img {- display: block;- width: 100%;- height: auto;+.hi-icon-right {+ margin-left: 0.375rem;}-/* Event Header */-.response-header {- border-bottom: 1px solid var(--line-color);- padding-bottom: 0.75rem;+/* Icon button integration */+.btn .hi-icon {+ vertical-align: text-top;}-.response-header h6 {- color: var(--primary-color);- font-weight: 600;- margin-bottom: 0.25rem;+/* Enhanced icon alignment for V2 components */+.attr-v2-action-buttons .hi-icon-left,+.attr-v2-file-actions .hi-icon,+.attr-v2-attribute-actions .hi-icon {+ vertical-align: middle;}-/* Event Details Expansion Bar */-.response-details-bar {- border-top: 1px solid var(--line-color);- margin-top: 1.5rem;+.attr-v2-action-buttons button .hi-icon-left {+ margin-right: 0.5rem;}--.details-expander {- display: flex;- justify-content: space-between;- align-items: center;- padding: 0.75rem 1rem;- background: linear-gradient(to bottom, #f8f9fa, #f1f3f5);- text-decoration: none;- color: #6c757d;- transition: all 0.2s ease;- cursor: pointer;}-.details-expander:hover {- background: #e9ecef;- text-decoration: none;- color: #495057;+/* Ensure icons work well in different contexts */+.card-header .hi-icon,+.card-title .hi-icon {+ margin-right: 0.375rem;}-.details-expander:focus {- outline: 2px solid var(--primary-color);- outline-offset: -2px;- text-decoration: none;+.alert .hi-icon {+ margin-right: 0.5rem;}-.details-label {- font-size: 0.9rem;- font-weight: 500;- letter-spacing: 0.5px;- text-transform: uppercase;+/* Legacy icon class deprecation helpers */+.plus-icon,+.history-icon {+ /* These classes are deprecated. Use {% icon %} template tag instead */+ opacity: 0.7;}-.details-chevron {- font-size: 0.8rem;- transition: transform 0.2s ease;+/* High contrast mode support */+@media (prefers-contrast: high) {+ .hi-icon {+ stroke-width: 2;+ }}-.details-expander[aria-expanded="true"] .details-chevron {- transform: rotate(180deg);+/* Reduced motion support */+@media (prefers-reduced-motion: reduce) {+ .hi-icon {+ transition: none;+ }}-.details-content {- padding: 1rem;- background-color: #f8f9fa;- border-top: 1px solid #e9ecef;+/* Pagination styling overrides for app theming */+.pagination-lg .page-link {+ color: var(--primary-color) !important;+ border-color: #dee2e6 !important;+ /* Force consistent height for all pagination buttons */+ height: 3rem !important;+ min-height: 3rem !important;+ display: flex !important;+ align-items: center !important;+ justify-content: center !important;+ padding: 0.5rem 0.75rem !important;+ box-sizing: border-box !important;+ line-height: 1.2 !important;}-.detail-row {- display: grid;- grid-template-columns: minmax(120px, 1fr) 2fr;- gap: 1rem;- padding: 0.5rem 0;- border-bottom: 1px solid #e9ecef;+/* Ensure spans inside page-links don't affect height and are properly centered */+.pagination-lg .page-link span {+ display: flex !important;+ align-items: center !important;+ justify-content: center !important;+ height: 100% !important;}-.detail-row:last-child {- border-bottom: none;+.pagination-lg .page-link:hover {+ color: var(--primary-highlight-color) !important;+ background-color: #e9ecef !important;+ border-color: #dee2e6 !important;}-.detail-label {- font-size: 0.85rem;- color: #6c757d;- font-weight: 500;+.pagination-lg .page-item.active .page-link {+ background-color: var(--primary-color) !important;+ border-color: var(--primary-color) !important;+ color: var(--on-primary-color) !important;}-.detail-value {- font-size: 0.85rem;- color: #212529;- word-break: break-word;+.pagination-lg .page-item.disabled .page-link {+ color: #6c757d !important;+ background-color: #fff !important;+ border-color: #dee2e6 !important;}-/* Timeline Pagination */-.timeline-pagination-top,-.timeline-pagination-bottom {- padding: 0.25rem;+/* ====================================================================== */+/* SECRET FIELD STYLING */+/* ====================================================================== */++.attr-v2-secret-field {+ position: relative;}-.timeline-pagination-top .btn,-.timeline-pagination-bottom .btn {- font-size: 0.8rem;- padding: 0.4rem;- transition: all 0.2s ease;- border-color: var(--primary-color);- color: var(--primary-color);+.attr-v2-secret-input-wrapper {+ position: relative;+ display: flex;+ align-items: stretch;}-.timeline-pagination-top .btn:hover,-.timeline-pagination-bottom .btn:hover {- transform: translateY(-1px);- background-color: var(--primary-color);- color: var(--on-primary-color);+.attr-v2-secret-input-wrapper input,+.attr-v2-secret-input-wrapper textarea {+ flex: 1;+ padding-right: 44px; /* Space for toggle button */}+.attr-v2-secret-toggle {+ position: absolute;+ right: 4px;+ top: 50%;+ transform: translateY(-50%);+ z-index: 1;+ min-width: 36px;+ height: 36px;+ border: 1px solid #ced4da;+ background: var(--background-color);+ padding: 6px;+ display: flex;+ align-items: center;+ justify-content: center;+}-/* ==========================================- Loading States & Error Handling- ========================================== */+.attr-v2-secret-toggle:hover {+ background: var(--hover-background-color);+ border-color: #adb5bd;+}-/* Video Placeholder/Error State */-.video-placeholder {- min-height: 400px;- background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);- border-radius: 8px;- position: relative;+.attr-v2-secret-toggle:focus {+ outline: 2px solid var(--primary-color);+ outline-offset: 2px;+ border-color: var(--primary-color);}-.video-placeholder-icon {- color: var(--primary-color);- opacity: 0.5;+/* Secret field in hidden state */+.attr-v2-secret-field.hidden input,+.attr-v2-secret-field.hidden textarea {+ -webkit-text-security: disc;+ font-family: 'Courier New', monospace;+ letter-spacing: 0.1em;}-.video-placeholder h5 {- color: var(--primary-color);- font-weight: 600;+/* Fallback for browsers that don't support text-security */+.attr-v2-secret-field.hidden input:not([type="password"]),+.attr-v2-secret-field.hidden textarea {+ color: transparent;+ text-shadow: 0 0 0 #495057;}-.video-placeholder p {- color: var(--black);- opacity: 0.8;+/* Touch device optimizations */+@media (max-width: 768px) {+ .attr-v2-secret-toggle {+ min-width: 44px;+ height: 44px;+ }}-/* Loading Animation for Video */-.video-container.loading {- position: relative;- min-height: 400px;+/* Secret field readonly visual indicators */+.attr-v2-secret-input[readonly] {+ background-color: #f8f9fa;+ cursor: default;+ border-color: #dee2e6;}-.video-container.loading::before {- content: '';- position: absolute;- top: 0;- left: 0;- right: 0;- bottom: 0;- background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);- background-size: 200% 100%;- animation: loading 1.5s infinite;- border-radius: 8px;+.attr-v2-secret-input[readonly]:focus {+ background-color: #f8f9fa;+ border-color: #dee2e6;+ box-shadow: none;}-.video-container.loading::after {- content: 'Loading video stream...';- position: absolute;- top: 50%;- left: 50%;- transform: translate(-50%, -50%);- color: var(--primary-color);- font-weight: 500;+/* When secret field is editable (shown), give it normal input styling */+.attr-v2-secret-input[type="text"]:not([readonly]) {+ background-color: #ffffff;+ cursor: text;+}++.attr-v2-secret-input[type="text"]:not([readonly]):focus {+ border-color: var(--primary-color);+ box-shadow: 0 0 0 0.2rem rgba(23, 112, 114, 0.25);}-@keyframes loading {- 0% {- background-position: 200% 0;- }- 100% {- background-position: -200% 0;- }+/* Secret checkbox positioning and alignment */+.attr-v2-secret-checkbox {+ margin-top: 0.75rem;+ margin-bottom: 0.5rem;}-/* Error State for Timeline */-.timeline-container.error {- background-color: var(--edit-secondary-bg-color);- padding: 1rem;- text-align: center;+.attr-v2-secret-checkbox .custom-control {+ display: flex;+ align-items: center;}-.timeline-container.error::before {- content: '⚠ Unable to load event history';- color: var(--error-color);- font-weight: 600;+.attr-v2-secret-checkbox .custom-control-label {+ line-height: 1;+ padding-top: 0;+ margin-bottom: 0;+ font-size: 0.875rem;}-/* ==========================================- Accessibility & Keyboard Navigation- ========================================== */+/* ====================================================================== */+/* V2 DIRTY STATE TRACKING STYLING */+/* ====================================================================== */-/* Focus indicators for keyboard navigation */-.timeline-item a:focus {- outline: 2px solid var(--secondary-color);- outline-offset: 2px;- border-radius: 4px;+/* Dirty message area in sticky panel */+.attr-v2-dirty-message {+ font-size: 0.875rem;+ color: transparent;+ transition: color 0.2s ease-in-out;+ min-width: 120px;}+.attr-v2-dirty-message.active {+ color: var(--warning-color);+ font-weight: 500;+}-/* High contrast mode support */-@media (prefers-contrast: high) {- .timeline-item.active {- border-left-width: 4px;- font-weight: bold;- }-- .timeline-group-label {- border-bottom-width: 3px;- }+/* Field-level dirty indicators */+.attr-v2-field-dirty {+ border-left: 3px solid var(--warning-color) !important;+ background-color: rgba(255, 193, 7, 0.05) !important;+ transition: border-color 0.2s ease-in-out, background-color 0.2s ease-in-out;}-/* Reduced motion support */-@media (prefers-reduced-motion: reduce) {- .timeline-item,- .video-container.loading::before {- transition: none;- animation: none;- }+.attr-v2-field-dirty:focus {+ border-left-color: var(--primary-color) !important;+ box-shadow: -3px 0 0 0 var(--primary-color), 0 0 0 0.2rem rgba(23, 112, 114, 0.25);}-/* Screen reader only content */-.sr-only {- position: absolute;- width: 1px;- height: 1px;- padding: 0;- margin: -1px;- overflow: hidden;- clip: rect(0, 0, 0, 0);- white-space: nowrap;- border: 0;+/* Dirty indicator dot */+.attr-v2-dirty-indicator {+ display: inline-block;+ margin-left: 0.5rem;+ color: var(--warning-color);+ font-size: 0.75rem;+ font-weight: bold;+ opacity: 0.8;+ animation: pulse 2s infinite;}-/* ==========================================- Responsive Design - Landscape Optimized- ========================================== */+/* Attrribute name dirty styling - fallback approach for broader browser support */+.attr-v2-attribute-name.has-dirty-indicator {+ font-weight: 600;+ color: var(--warning-color);+}-/* Small landscape devices (landscape phones, 568px and up) */-@media (min-width: 568px) and (orientation: landscape) {- .timeline-container {- max-height: 400px; /* Reduce height for smaller landscape screens */- }+/* Entity name dirty styling - fallback approach */+.form-group.has-dirty-field small {+ color: var(--warning-color);+ font-weight: 500;}-/* Medium landscape devices (tablets, 768px and up) */-@media (min-width: 768px) and (orientation: landscape) {- .timeline-container {- max-height: 500px;+/* Modern browser support with :has() */+@supports selector(:has(*)) {+ .attr-v2-attribute-name:has(.attr-v2-dirty-indicator) {+ font-weight: 600;+ color: var(--warning-color);}- /* Optimize column widths for landscape tablets */- .entity-video-sensor-history .col-md-3 {- flex: 0 0 25%;- max-width: 25%;+ .form-group:has(.attr-v2-field-dirty) small {+ color: var(--warning-color);+ font-weight: 500;}- .entity-video-sensor-history .col-md-9 {- flex: 0 0 75%;- max-width: 75%;+ .attr-v2-new-attribute .attr-v2-attribute-name:has(.attr-v2-dirty-indicator) {+ color: var(--primary-color);}}-/* Large landscape devices (laptops/desktops, 992px and up) */-@media (min-width: 992px) and (orientation: landscape) {- .timeline-container {- max-height: 600px;- }-- /* Wider timeline on larger screens */- .entity-video-sensor-history .col-md-3 {- flex: 0 0 20%;- max-width: 20%;- }-- .entity-video-sensor-history .col-md-9 {- flex: 0 0 80%;- max-width: 80%;- }+/* New attribute form dirty state - different styling */+.attr-v2-new-attribute .attr-v2-field-dirty {+ border-left-color: var(--primary-color) !important;+ background-color: rgba(23, 112, 114, 0.08) !important;}-/* Extra large landscape devices (large desktops, 1200px and up) */-@media (min-width: 1200px) {- .video-container {- max-width: 1000px; /* Limit video size on very large screens */- margin: 0 auto;- }+.attr-v2-new-attribute .attr-v2-dirty-indicator {+ color: var(--primary-color);}-/* Landscape-specific optimizations */-@media (orientation: landscape) {- /* Compact timeline items for landscape */- .timeline-item {- padding: 8px;- margin-bottom: 4px;- }-- .timeline-group-label {- padding: 6px 0;- margin-bottom: 8px;- }--- /* Compact details bar in landscape */- .details-expander {- padding: 0.5rem 0.75rem;- }-- .details-content {- padding: 0.75rem;- }+.attr-v2-new-attribute .attr-v2-attribute-name.has-dirty-indicator {+ color: var(--primary-color);}-/* Handle small screens that don't meet minimum requirements */-@media (max-width: 767px) {- /* Stack detail rows on mobile */- .detail-row {- grid-template-columns: 1fr;- gap: 0.25rem;- }-- .detail-label {- font-weight: 600;- color: #495057;- }-- .details-expander {- padding: 0.6rem 0.75rem;- }-- .details-label {- font-size: 0.85rem;- }- /* Stack layout vertically on very small screens */- .entity-video-sensor-history .row {- flex-direction: column;- }-- .entity-video-sensor-history .col-md-3,- .entity-video-sensor-history .col-md-9 {- max-width: 100%;- width: 100%;+/* Reduce motion for accessibility */+@media (prefers-reduced-motion: reduce) {+ .attr-v2-dirty-indicator {+ animation: none;+ opacity: 1;}- .timeline-container {- max-height: 200px;- margin-bottom: 1rem;- border-right: none;- border-bottom: 1px solid var(--line-color);+ .attr-v2-field-dirty,+ .attr-v2-dirty-message {+ transition: none;}}-/* Video Interface Header Styles */-.video-interface-header {- border-bottom: 2px solid #e9ecef;- padding: 0.75rem;- margin: -0.75rem -0.75rem 0.75rem -0.75rem;- border-radius: 0.5rem 0.5rem 0 0;+/* ====================================================================== */+/* ADD ATTRIBUTE FORM STYLING */+/* ====================================================================== */++.attr-v2-add-form {+ border: 1px solid #dee2e6;+ border-radius: 0.375rem;+ background: var(--background-color);+ margin-bottom: 1rem;+ overflow: hidden;+ transition: all 0.3s ease;}-/* Page-specific header backgrounds */-.video-interface-header.current-stream {- background-color: var(--secondary-color);- color: var(--on-secondary-color);- border-bottom-color: var(--secondary-color);+.attr-v2-add-form.collapsed {+ display: none;}-.video-interface-header.event-history {- background-color: var(--tertiary-color);- color: var(--on-tertiary-color);- border-bottom-color: var(--tertiary-color);+.attr-v2-add-form-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ padding: 0.75rem 1rem;+ background: var(--highlight-background-color);+ border-bottom: 1px solid #dee2e6;}-.entity-title {- color: #343a40;+.attr-v2-add-form-header h6 {+ margin: 0;font-weight: 600;- font-size: 1.1rem;+ color: var(--text-color);}-.video-interface-header.current-stream .entity-title,-.video-interface-header.event-history .entity-title {- color: inherit;+.attr-v2-add-form-content {+ padding: 1rem;}-.last-activity-badge {- font-size: 0.85rem;- padding: 0.25rem 0.5rem;- background-color: #f8f9fa;- border-radius: 12px;- border: 1px solid #e9ecef;+.attr-v2-add-form-actions {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-top: 1rem;+ padding-top: 1rem;+ border-top: 1px solid #dee2e6;}-.video-interface-header.current-stream .last-activity-badge {- background-color: rgba(255, 255, 255, 0.2);- border-color: rgba(255, 255, 255, 0.3);- color: inherit;+/* ====================================================================== */+/* HISTORY OVERLAY STYLING */+/* ====================================================================== */++.attr-v2-modal-overlay {+ position: fixed;+ top: 0;+ left: 0;+ width: 100%;+ height: 100%;+ background: rgba(0, 0, 0, 0.5);+ display: flex;+ align-items: center;+ justify-content: center;+ z-index: 2000; /* Above the main modal */}-.video-interface-header.event-history .last-activity-badge {- background-color: rgba(255, 255, 255, 0.1);- border-color: rgba(255, 255, 255, 0.2);- color: inherit;+.attr-v2-overlay-content {+ background: var(--background-color);+ border-radius: 0.5rem;+ box-shadow: 0 1rem 3rem rgba(0, 0, 0, 0.175);+ max-width: 500px;+ width: 90%;+ max-height: 80vh;+ display: flex;+ flex-direction: column;}-.video-nav-tabs {+.attr-v2-overlay-header {display: flex;- gap: 0;+ justify-content: space-between;+ align-items: center;+ padding: 1rem 1.5rem;+ border-bottom: 1px solid #dee2e6;}-.video-nav-tab {- padding: 0.5rem 1rem;- text-decoration: none;- color: #6c757d;- border: 1px solid #dee2e6;- background-color: #f8f9fa;- transition: all 0.15s ease-in-out;- position: relative;- font-size: 0.9rem;- font-weight: 500;- cursor: pointer;+.attr-v2-overlay-header h6 {+ margin: 0;+ font-weight: 600;+ color: var(--text-color);+}++.attr-v2-overlay-body {+ padding: 1.5rem;+ overflow-y: auto;+ flex: 1;+}+++/* ====================================================================== */+/* COMPACT BASIC INFO HEADER */+/* ====================================================================== */++.attr-v2-basic-info {+ background: var(--white);+ border: 1px solid var(--line-color);+ border-radius: 0.375rem;+ padding: 0.5rem 0.75rem;+ margin-bottom: 0.5rem;}-.video-nav-tab:first-child {- border-top-left-radius: 0.375rem;- border-bottom-left-radius: 0.375rem;+.attr-v2-basic-info .row {+ margin-left: -0.375rem;+ margin-right: -0.375rem;}-.video-nav-tab:last-child {- border-top-right-radius: 0.375rem;- border-bottom-right-radius: 0.375rem;- border-left: none;+.attr-v2-basic-info [class*="col-"] {+ padding-left: 0.375rem;+ padding-right: 0.375rem;}-.video-nav-tab:not(:first-child):not(:last-child) {- border-left: none;+/* Force block layout for labels - very specific selector */+.attr-v2-basic-info .form-group small,+.attr-v2-basic-info .form-group .text-muted,+.attr-v2-basic-info small,+.attr-v2-basic-info .text-muted {+ display: block !important;+ font-size: 0.75rem !important;+ color: var(--muted-color) !important;+ margin-bottom: 0.25rem !important;+ font-weight: 500 !important;+ text-transform: uppercase !important;+ letter-spacing: 0.5px !important;+ width: 100% !important;+ line-height: 1 !important;+ clear: both !important;}-.video-nav-tab:hover:not(.disabled):not(.active) {- color: #495057;- background-color: #e9ecef;- text-decoration: none;+.attr-v2-basic-info .form-control-sm {+ font-size: 0.875rem;+ padding: 0.375rem 0.5rem;+ height: calc(1.5em + 0.75rem + 2px);+ width: 100%; /* Ensure full width */}-.video-nav-tab.active {- color: #fff;- background-color: #007bff;- border-color: #007bff;- z-index: 1;+.attr-v2-basic-info .form-control {+ width: 100%; /* Ensure full width for all form controls */}-/* Active tab styling for colored headers */-.video-interface-header.current-stream .video-nav-tab.active {- background-color: rgba(255, 255, 255, 0.9);- color: var(--secondary-color);- border-color: rgba(255, 255, 255, 0.9);+.attr-v2-basic-info select.form-control-sm {+ padding-right: 1.75rem;+ background-position: right 0.375rem center;+ background-size: 16px 12px;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;}-.video-interface-header.event-history .video-nav-tab.active {- background-color: rgba(255, 255, 255, 0.9);- color: var(--tertiary-color);- border-color: rgba(255, 255, 255, 0.9);+/* Ensure columns don't break layout */+.attr-v2-basic-info .col-md-8,+.attr-v2-basic-info .col-md-4,+.attr-v2-basic-info .col-sm-6 {+ min-width: 0; /* Allow flex shrinking */}-/* Inactive tab styling for colored headers */-.video-interface-header.current-stream .video-nav-tab:not(.active):not(.disabled),-.video-interface-header.event-history .video-nav-tab:not(.active):not(.disabled) {- background-color: rgba(255, 255, 255, 0.1);- color: rgba(255, 255, 255, 0.8);- border-color: rgba(255, 255, 255, 0.2);+/* Remove bottom margin from form groups in header */+.attr-v2-basic-info .form-group {+ margin-bottom: 0;}-.video-interface-header.current-stream .video-nav-tab:hover:not(.disabled):not(.active),-.video-interface-header.event-history .video-nav-tab:hover:not(.disabled):not(.active) {- background-color: rgba(255, 255, 255, 0.2);- color: rgba(255, 255, 255, 1);- border-color: rgba(255, 255, 255, 0.3);+/* Error state styling */+.attr-v2-basic-info .form-control.is-invalid,+.attr-v2-basic-info .form-control:invalid {+ border-color: var(--danger-color);}-.video-nav-tab.disabled {- color: #6c757d;- background-color: #f8f9fa;- border-color: #dee2e6;- cursor: not-allowed;- opacity: 0.6;+.attr-v2-basic-info .invalid-feedback {+ font-size: 0.75rem;+ margin-top: 0.25rem;}-/* Responsive adjustments */-@media (max-width: 768px) {- .video-interface-header .d-flex {- flex-direction: column;- align-items: flex-start !important;- gap: 0.75rem;- }-- .video-nav-tabs {- width: 100%;- justify-content: center;- }-- .video-nav-tab {- flex: 1;- text-align: center;- font-size: 0.85rem;- padding: 0.4rem 0.6rem;- }-- .entity-title {- font-size: 1rem;- }-- .last-activity-badge {- font-size: 0.8rem;- }+/* ====================================================================== */+/* INLINE HISTORY STYLING */+/* ====================================================================== */++.attr-v2-inline-history {+ margin-top: 0.75rem;}-@media (max-width: 480px) {- .video-nav-tab i {- display: none; /* Hide icons on very small screens */- }-- .video-nav-tab {- padding: 0.4rem 0.5rem;- font-size: 0.8rem;- }+.attr-v2-history-inline-content {+ background: var(--highlight-background-color);+ border: 1px solid var(--line-color);+ border-radius: 0.375rem;+ padding: 0.75rem;+ font-size: 0.875rem;}-/* ===== ICON SYSTEM ===== */+.attr-v2-history-header {+ margin-bottom: 0.5rem;+ padding-bottom: 0.5rem;+ border-bottom: 1px solid var(--line-color);+ display: flex;+ justify-content: space-between;+ align-items: center;+}-/* Base icon class */-.hi-icon {- display: inline-block;- vertical-align: middle;- fill: currentColor;- stroke: currentColor;- flex-shrink: 0;+.attr-v2-history-close {+ color: var(--danger-color);+ text-decoration: none;}-/* Icon sizes */-.hi-icon-sm {- width: 0.875rem;- height: 0.875rem;+.attr-v2-history-close:hover {+ color: var(--danger-color);+ text-decoration: none;}-.hi-icon-md {- width: 1rem;- height: 1rem;+.attr-v2-history-current {+ font-size: 0.8125rem;}-.hi-icon-lg {- width: 1.25rem;- height: 1.25rem;+.attr-v2-history-current .badge-primary {+ background-color: var(--success-color);+ border-color: var(--success-color);}-.hi-icon-xl {- width: 1.5rem;- height: 1.5rem;+.attr-v2-history-toggle .btn-link {+ color: var(--text-color);+ text-decoration: none;}-/* Semantic icon colors using existing CSS variables */-.hi-icon-primary {+.attr-v2-history-toggle .btn-link:hover {color: var(--primary-color);+ text-decoration: underline;}-.hi-icon-secondary {- color: var(--secondary-color);+.attr-v2-history-record {+ padding: 0.375rem 0;+ border-bottom: 1px solid rgba(0,0,0,0.05);}-.hi-icon-success {- color: var(--success-color);+.attr-v2-history-record:last-child {+ border-bottom: none;}-.hi-icon-warning {- color: var(--warning-color);+.attr-v2-history-record .badge {+ font-size: 0.75rem;+ max-width: 300px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ display: inline-block;+ vertical-align: top;}-.hi-icon-error {- color: var(--error-color);+.attr-v2-history-current .badge {+ font-size: 0.75rem;+ max-width: 300px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ display: inline-block;+ vertical-align: top;}-.hi-icon-muted {+.attr-v2-history-record .btn-xs {+ font-size: 0.75rem;+ padding: 0.125rem 0.5rem;+ line-height: 1.2;+}++.attr-v2-history-toggle {+ padding-top: 0.5rem;+ border-top: 1px solid rgba(0,0,0,0.05);+}++.attr-v2-history-empty {+ text-align: center;+ padding: 1rem 0;color: var(--muted-color);}-/* Icon spacing utilities */-.hi-icon-left {- margin-right: 0.25rem;+/* ====================================================================== */+/* DELETION STATES WITH WATERMARKS */+/* ====================================================================== */++/* File Card Deletion Styling */+.attr-v2-file-card.marked-for-deletion {+ opacity: 0.9;+ transition: all 0.3s ease;}-.hi-icon-right {- margin-left: 0.25rem;+.attr-v2-file-card.marked-for-deletion .attr-v2-file-thumbnail {+ position: relative;+ background: linear-gradient(rgba(220, 53, 69, 0.1), rgba(220, 53, 69, 0.1)),+ repeating-linear-gradient(45deg, #f8f9fa, #f8f9fa 10px, #e9ecef 10px, #e9ecef 20px);}-/* Icon button integration */-.btn .hi-icon {- vertical-align: text-top;+.attr-v2-file-card.marked-for-deletion .attr-v2-file-thumbnail::after {+ content: "PENDING DELETION";+ position: absolute;+ top: 50%;+ left: 50%;+ transform: translate(-50%, -50%) rotate(-15deg);+ font-size: 0.875rem;+ font-weight: 600;+ color: var(--danger-color);+ opacity: 0.3;+ text-transform: uppercase;+ letter-spacing: 2px;+ pointer-events: none;+ white-space: nowrap;+ z-index: 10;}-/* Ensure icons work well in different contexts */-.card-header .hi-icon,-.card-title .hi-icon {- margin-right: 0.375rem;+.attr-v2-file-card.marked-for-deletion .attr-v2-file-info {+ border-color: var(--danger-color);+ background: rgba(220, 53, 69, 0.05);}-.alert .hi-icon {- margin-right: 0.5rem;+/* Attrribute Card Deletion Styling */+.attr-v2-attribute-card.marked-for-deletion {+ position: relative;+ background: rgba(220, 53, 69, 0.05);+ border-left: 4px solid var(--danger-color);+ overflow: hidden;+ opacity: 0.9;+ transition: all 0.3s ease;}-/* Legacy icon class deprecation helpers */-.plus-icon,-.history-icon {- /* These classes are deprecated. Use {% icon %} template tag instead */- opacity: 0.7;+.attr-v2-attribute-card.marked-for-deletion::after {+ content: "PENDING DELETION";+ position: absolute;+ top: 50%;+ left: 50%;+ transform: translate(-50%, -50%);+ font-size: 1.5rem;+ font-weight: 700;+ color: var(--danger-color);+ opacity: 0.1;+ text-transform: uppercase;+ letter-spacing: 2px;+ pointer-events: none;+ z-index: 10;+ white-space: nowrap;}-/* High contrast mode support */-@media (prefers-contrast: high) {- .hi-icon {- stroke-width: 2;- }+/* Keep inputs interactive but let watermark show through */+.attr-v2-attribute-card.marked-for-deletion .form-control,+.attr-v2-attribute-card.marked-for-deletion textarea,+.attr-v2-attribute-card.marked-for-deletion input {+ position: relative;+ background-color: rgba(255, 255, 255, 0.9);}-/* Reduced motion support */-@media (prefers-reduced-motion: reduce) {- .hi-icon {- transition: none;- }+/* Undo button visibility when marked for deletion */+.marked-for-deletion .attr-v2-delete-btn {+ display: none !important;}-/* Pagination styling overrides for app theming */-.pagination-lg .page-link {- color: var(--primary-color) !important;- border-color: #dee2e6 !important;- /* Force consistent height for all pagination buttons */- height: 3rem !important;- min-height: 3rem !important;- display: flex !important;- align-items: center !important;- justify-content: center !important;- padding: 0.5rem 0.75rem !important;- box-sizing: border-box !important;- line-height: 1.2 !important;+.marked-for-deletion .attr-v2-undo-btn {+ display: inline-flex !important;}-/* Ensure spans inside page-links don't affect height and are properly centered */-.pagination-lg .page-link span {- display: flex !important;- align-items: center !important;- justify-content: center !important;- height: 100% !important;+/* ====================================================================== */+/* ENTITY EDIT MODAL V2 STYLING IMPROVEMENTS */+/* ====================================================================== */++/* Task 1: Standardize delete icon colors to red */+.attr-v2-attribute-actions .attr-v2-delete-btn {+ color: #dc3545 !important;+ border-color: #dc3545 !important;}-.pagination-lg .page-link:hover {- color: var(--primary-highlight-color) !important;- background-color: #e9ecef !important;- border-color: #dee2e6 !important;+.attr-v2-attribute-actions .attr-v2-delete-btn:hover {+ background-color: #dc3545 !important;+ color: white !important;}-.pagination-lg .page-item.active .page-link {- background-color: var(--primary-color) !important;- border-color: var(--primary-color) !important;- color: var(--on-primary-color) !important;+/* Task 2: Style "Add New Attrribute" form for visual distinction */+.attr-v2-new-attribute {+ background-color: rgba(23, 112, 114, 0.05) !important;+ border: 2px dashed rgba(23, 112, 114, 0.3) !important;+ border-radius: 8px;}-.pagination-lg .page-item.disabled .page-link {- color: #6c757d !important;- background-color: #fff !important;- border-color: #dee2e6 !important;+.attr-v2-new-attribute .attr-v2-attribute-header h6 {+ color: var(--primary-color);+ font-weight: 600;+ font-style: italic;+}+++/* Task 3: Make Add File and Add Attrribute buttons consistent size */+.attr-v2-action-buttons label.btn {+ min-height: 44px;+ padding: 0.375rem 0.75rem;+ font-size: 0.875rem;+ border-radius: 0.25rem;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ line-height: 1.5;+ cursor: pointer;+}++/* Task 4: Make attribute name/labels more prominent than values */+.attr-v2-attribute-name {+ font-size: 0.9rem !important;+ font-weight: 600 !important;+ color: var(--primary-text-color) !important;+ margin-bottom: 0.5rem;+ letter-spacing: 0.5px;+}++/* Touch device optimizations */+@media (max-width: 768px) {+ .attr-v2-overlay-content {+ width: 95%;+ max-height: 90vh;+ }++ .attr-v2-add-form-actions {+ flex-direction: column;+ gap: 0.75rem;+ align-items: stretch;+ }}diff --git a/src/hi/static/js/antinode.js b/src/hi/static/js/antinode.jsindex 9ec12793..d2304c02 100644--- a/src/hi/static/js/antinode.js+++ b/src/hi/static/js/antinode.js@@ -73,7 +73,8 @@// "setAttributes": {"id1": {...}}, // Set element attributes// "modal": "<div>...</div>", // Create and show modal// "pushUrl": "/new/url", // Update browser URL without reload-// "resetScrollbar": true // Reset to top of page+// "resetScrollbar": true, // Reset to top of page+// "scrollTo": "element-id" // Scroll to specified element ID// }// ====================@@ -272,7 +273,9 @@}}});- }+ },++ addAfterAsyncRenderFunction: addAfterAsyncRenderFunction}window.AN = AN;@@ -671,6 +674,22 @@ function asyncUpdateDataFromJson( $target, $mode, json ) {window.scrollTo(0, 0);}+ // Scroll to specified element after DOM updates are complete+ if ( 'scrollTo' in json ) {+ let targetId = json['scrollTo'];+ let targetElement = $("#" + targetId);+ if ( targetElement.length > 0 ) {+ // Use smooth scrolling for better user experience+ targetElement[0].scrollIntoView({+ behavior: 'smooth',+ block: 'nearest',+ inline: 'nearest'+ });+ } else {+ console.warn('AntiNode scrollTo: Target element not found:', targetId);+ }+ }+if ( typeof handlePostAsyncUpdate === "function") {handlePostAsyncUpdate();}diff --git a/src/hi/static/js/attr-v2-dirty-tracking.js b/src/hi/static/js/attr-v2-dirty-tracking.jsnew file mode 100644index 00000000..38d6e68d--- /dev/null+++ b/src/hi/static/js/attr-v2-dirty-tracking.js@@ -0,0 +1,401 @@+/*+ * Home Information - Attribute V2 Dirty State Tracking+ * Comprehensive dirty state tracking for V2 entity attribute editing modal+ * Handles field-level changes with proper V2 pattern support+ */++(function() {+ 'use strict';++ // Create namespace+ window.attrV2 = window.attrV2 || {};+ window.attrV2.DirtyTracking = {++ // Configuration+ config: {+ formSelector: Hi.ATTR_V2_FORM_SELECTOR,+ messageContainerSelector: Hi.ATTR_V2_DIRTY_MESSAGE_SELECTOR,+ debounceDelay: 300,+ dirtyFieldClass: Hi.ATTR_V2_FIELD_DIRTY_CLASS,+ dirtyIndicatorClass: Hi.ATTR_V2_DIRTY_INDICATOR_CLASS+ },++ // State+ state: {+ originalValues: new Map(),+ dirtyFields: new Set(),+ debounceTimers: new Map(),+ isInitialized: false+ },++ // Initialize the dirty tracking system+ init: function() {+ if (this.state.isInitialized) {+ return;+ }++ const form = document.querySelector(this.config.formSelector);+ if (!form) {+ return;+ }++ this.captureOriginalValues();+ this.bindEvents();+ this.state.isInitialized = true;+ },++ // Capture original values for all form fields+ captureOriginalValues: function() {+ const form = document.querySelector(this.config.formSelector);+ if (!form) return;++ // Entity name field+ const entityNameField = form.querySelector('input[name$="name"]:not([name*="-"])');+ if (entityNameField) {+ this.captureFieldValue(entityNameField);+ }++ // Attribute form fields+ const attributeFields = form.querySelectorAll(`${Hi.ATTR_V2_ATTRIBUTE_CARD_SELECTOR} input, ${Hi.ATTR_V2_ATTRIBUTE_CARD_SELECTOR} textarea, ${Hi.ATTR_V2_ATTRIBUTE_CARD_SELECTOR} select`);+ attributeFields.forEach(field => {+ // Skip hidden management form fields+ if (field.type === 'hidden' && field.name.includes('_')) return;+ this.captureFieldValue(field);+ });++ // File title input fields+ const fileTitleFields = form.querySelectorAll(Hi.ATTR_V2_FILE_TITLE_INPUT_SELECTOR);+ fileTitleFields.forEach(field => {+ this.captureFieldValue(field);+ });+ },++ // Capture individual field value+ captureFieldValue: function(field) {+ if (!field.name || !field.id) return;++ let originalValue = this.getFieldValue(field);+ this.state.originalValues.set(field.id, originalValue);+ field.setAttribute('data-original-value', originalValue);+ },++ // Get normalized field value+ getFieldValue: function(field) {+ if (field.type === 'checkbox') {+ return field.checked ? 'true' : 'false';+ } else if (field.tagName.toLowerCase() === 'select') {+ return field.value || '';+ } else {+ return (field.value || '').trim();+ }+ },++ // Check if field has changed+ hasFieldChanged: function(field) {+ const originalValue = this.state.originalValues.get(field.id);+ const currentValue = this.getFieldValue(field);++ // Special handling for new attribute forms - consider them dirty if they have content+ const isNewAttributeField = field.closest(Hi.ATTR_V2_NEW_ATTRIBUTE_SELECTOR);+ if (isNewAttributeField && field.name.includes('-name') && currentValue.length > 0) {+ return true;+ }++ return originalValue !== currentValue;+ },++ // Bind event listeners+ bindEvents: function() {+ const form = document.querySelector(this.config.formSelector);+ if (!form) return;++ // Text input changes with debouncing+ this.bindDebouncedEvents(form, 'input[type="text"], input[type="password"], textarea', 'input');++ // Immediate changes for selects and checkboxes+ this.bindImmediateEvents(form, 'select, input[type="checkbox"]', 'change');++ // Form submission handling+ form.addEventListener('submit', this.handleFormSubmission.bind(this));++ // Handle file title input activation (persistent styling on first interaction)+ form.addEventListener('focus', (e) => {+ if (e.target.classList.contains(Hi.ATTR_V2_FILE_TITLE_INPUT_CLASS)) {+ e.target.classList.add('activated');+ }+ }, true); // Use capture phase to ensure we catch the event++ // Handle successful form submission (antinode.js pattern)+ document.addEventListener('an:success', this.handleFormSuccess.bind(this));+ },++ // Bind debounced events for text inputs+ bindDebouncedEvents: function(form, selector, eventType) {+ form.addEventListener(eventType, (e) => {+ if (!e.target.matches(selector)) return;++ const field = e.target;+ const fieldId = field.id;++ if (!fieldId) return;++ // Clear existing timer+ if (this.state.debounceTimers.has(fieldId)) {+ clearTimeout(this.state.debounceTimers.get(fieldId));+ }++ // Set new timer+ const timer = setTimeout(() => {+ this.handleFieldChange(field);+ this.state.debounceTimers.delete(fieldId);+ }, this.config.debounceDelay);++ this.state.debounceTimers.set(fieldId, timer);+ });+ },++ // Bind immediate events for selects and checkboxes+ bindImmediateEvents: function(form, selector, eventType) {+ form.addEventListener(eventType, (e) => {+ if (!e.target.matches(selector)) return;+ this.handleFieldChange(e.target);+ });+ },++ // Handle individual field change+ handleFieldChange: function(field) {+ const hasChanged = this.hasFieldChanged(field);++ if (hasChanged) {+ this.markFieldDirty(field);+ this.state.dirtyFields.add(field.id);+ } else {+ this.clearFieldDirty(field);+ this.state.dirtyFields.delete(field.id);+ }++ this.updateMessageArea();+ },++ // Mark field as dirty with visual indicators+ markFieldDirty: function(field) {+ field.classList.add(this.config.dirtyFieldClass);++ // For file title inputs, add activated class for persistent styling+ if (field.classList.contains(Hi.ATTR_V2_FILE_TITLE_INPUT_CLASS)) {+ field.classList.add('activated');+ }++ // Add indicator to field container+ const container = this.getFieldContainer(field);+ if (container && !container.querySelector('.' + this.config.dirtyIndicatorClass)) {+ const indicator = this.createDirtyIndicator();+ this.insertDirtyIndicator(container, indicator);++ // Add fallback CSS classes for browsers without :has() support+ this.addFallbackClasses(container, field);+ }+ },++ // Clear dirty state from field+ clearFieldDirty: function(field) {+ field.classList.remove(this.config.dirtyFieldClass);++ // Remove indicator+ const container = this.getFieldContainer(field);+ if (container) {+ const indicator = container.querySelector('.' + this.config.dirtyIndicatorClass);+ if (indicator) {+ indicator.remove();+ }++ // Remove fallback CSS classes+ this.removeFallbackClasses(container, field);+ }+ },++ // Get appropriate container for field indicator+ getFieldContainer: function(field) {+ // For file title inputs, use the file info container+ if (field.classList.contains(Hi.ATTR_V2_FILE_TITLE_INPUT_CLASS)) {+ const fileInfo = field.closest(Hi.ATTR_V2_FILE_INFO_SELECTOR);+ if (fileInfo) {+ return field; // Use the input itself as container for positioning+ }+ }++ // For attribute cards, use the attribute header+ const attributeCard = field.closest(Hi.ATTR_V2_ATTRIBUTE_CARD_SELECTOR);+ if (attributeCard) {+ return attributeCard.querySelector(Hi.ATTR_V2_ATTRIBUTE_NAME_SELECTOR);+ }++ // For entity name, use the form group+ const formGroup = field.closest('.form-group');+ if (formGroup) {+ return formGroup.querySelector('small, label') || formGroup;+ }++ return field.parentElement;+ },++ // Create dirty indicator element+ createDirtyIndicator: function() {+ const indicator = document.createElement('span');+ indicator.className = this.config.dirtyIndicatorClass;+ indicator.innerHTML = '●'; // Simple dot indicator+ indicator.title = 'This field has been modified';+ return indicator;+ },++ // Insert dirty indicator in appropriate position+ insertDirtyIndicator: function(container, indicator) {+ // For attribute names, append to the end+ if (container.classList.contains(Hi.ATTR_V2_ATTRIBUTE_NAME_CLASS)) {+ container.appendChild(indicator);+ } else {+ // For other containers, insert at the end+ container.appendChild(indicator);+ }+ },++ // Add fallback CSS classes for browsers without :has() support+ addFallbackClasses: function(container, field) {+ // For attribute names+ if (container.classList.contains(Hi.ATTR_V2_ATTRIBUTE_NAME_CLASS)) {+ container.classList.add('has-dirty-indicator');+ }++ // For form groups (entity name)+ const formGroup = field.closest('.form-group');+ if (formGroup) {+ formGroup.classList.add('has-dirty-field');+ }+ },++ // Remove fallback CSS classes+ removeFallbackClasses: function(container, field) {+ // For attribute names+ if (container.classList.contains(Hi.ATTR_V2_ATTRIBUTE_NAME_CLASS)) {+ container.classList.remove('has-dirty-indicator');+ }++ // For form groups (entity name)+ const formGroup = field.closest('.form-group');+ if (formGroup) {+ formGroup.classList.remove('has-dirty-field');+ }+ },++ // Update message area with current dirty state+ updateMessageArea: function() {+ const messageContainer = document.querySelector(this.config.messageContainerSelector);+ if (!messageContainer) return;++ const dirtyCount = this.state.dirtyFields.size;++ if (dirtyCount === 0) {+ messageContainer.textContent = '';+ messageContainer.className = Hi.ATTR_V2_DIRTY_MESSAGE_CLASS;+ } else {+ const message = dirtyCount === 1+ ? '1 field modified'+ : `${dirtyCount} fields modified`;+ messageContainer.textContent = message;+ messageContainer.className = Hi.ATTR_V2_DIRTY_MESSAGE_CLASS + ' active';+ }+ },++ // Handle form submission+ handleFormSubmission: function(e) {+ // Handle textarea sync for truncated/hidden field pattern+ this.syncDisplayToHiddenFields();+ },++ // Sync display fields to hidden fields before submission+ syncDisplayToHiddenFields: function() {+ const form = document.querySelector(this.config.formSelector);+ if (!form) return;++ const displayFields = form.querySelectorAll('.display-field');+ displayFields.forEach(displayField => {+ const hiddenFieldId = displayField.getAttribute('data-hidden-field');+ const hiddenField = hiddenFieldId ? document.getElementById(hiddenFieldId) : null;++ if (hiddenField && !displayField.readOnly && !displayField.classList.contains('truncated')) {+ hiddenField.value = displayField.value;+ }+ });+ },++ // Handle successful form submission+ handleFormSuccess: function(e) {+ this.clearAllDirtyState();+ },++ // Clear all dirty state+ clearAllDirtyState: function() {+ // Clear visual indicators+ const form = document.querySelector(this.config.formSelector);+ if (form) {+ form.querySelectorAll('.' + this.config.dirtyFieldClass).forEach(field => {+ field.classList.remove(this.config.dirtyFieldClass);+ });++ form.querySelectorAll('.' + this.config.dirtyIndicatorClass).forEach(indicator => {+ indicator.remove();+ });++ // Clear fallback classes+ form.querySelectorAll('.has-dirty-indicator').forEach(element => {+ element.classList.remove('has-dirty-indicator');+ });++ form.querySelectorAll('.has-dirty-field').forEach(element => {+ element.classList.remove('has-dirty-field');+ });+ }++ // Clear state+ this.state.dirtyFields.clear();++ // Clear timers+ this.state.debounceTimers.forEach(timer => clearTimeout(timer));+ this.state.debounceTimers.clear();++ // Clear message+ this.updateMessageArea();+ },++ // Reinitialize for dynamic content (called by modal system)+ reinitialize: function() {+ this.clearAllDirtyState();+ this.state.originalValues.clear();+ this.state.isInitialized = false;+ this.init();+ }+ };++ // Auto-initialize when DOM is ready+ document.addEventListener('DOMContentLoaded', function() {+ window.attrV2.DirtyTracking.init();+ });++ // Initialize after modal shown+ document.addEventListener('shown.bs.modal', function(e) {+ if (document.querySelector(Hi.ATTR_V2_FORM_SELECTOR)) {+ window.attrV2.DirtyTracking.reinitialize();+ }+ });++ // Hook into antinode success to reinitialize+ document.addEventListener('an:success', function(e) {+ if (document.querySelector(Hi.ATTR_V2_FORM_SELECTOR)) {+ // Delay to allow DOM updates+ setTimeout(() => {+ window.attrV2.DirtyTracking.reinitialize();+ }, 100);+ }+ });++})();diff --git a/src/hi/static/js/attr-v2-modal.js b/src/hi/static/js/attr-v2-modal.jsnew file mode 100644index 00000000..f3fab295--- /dev/null+++ b/src/hi/static/js/attr-v2-modal.js@@ -0,0 +1,670 @@+/*+ * Home Information - Attribute V2 Modal JavaScript+ * Enhanced entity attribute editing modal functionality+ * Phase 1a: Basic structure and framework+ */++(function() {+ 'use strict';++ // Create a namespace for V2 modal functions to avoid global pollution+ window.attrV2 = window.attrV2 || {};++ // Initialize the V2 modal when DOM is ready+ document.addEventListener('DOMContentLoaded', function() {+ if ($(Hi.ATTR_V2_FORM_SELECTOR).length) {+ initializeAttrV2();+ }+ });++ // Register with antinode.js to run after any async content is rendered+ if (window.AN && typeof window.AN.addAfterAsyncRenderFunction === 'function') {+ window.AN.addAfterAsyncRenderFunction(function() {+ if ($(Hi.ATTR_V2_FORM_SELECTOR).length) {+ reinitializeAttrV2ForAjax();+ }+ });+ } else {+ console.error('AN.addAfterAsyncRenderFunction not available - this is a bug in antinode.js');+ }++ // Listen for any modal shown events and check if it contains a V2 form+ $(document).on('shown.bs.modal', '.modal', function(e) {+ if ($(Hi.ATTR_V2_FORM_SELECTOR).length) {+ initializeAttrV2();+ e.stopPropagation(); // Prevent bubbling to other handlers+ }+ });++ function initializeAttrV2() {+ // Basic initialization - more functionality will be added in later phases+ setupBasicEventListeners();+ initializeExpandableTextareas(); // Must come BEFORE autosize+ initializeAutosizeTextareas(); // Now only applies to non-truncated+ setupFormSubmissionHandler();++ // Initialize dirty tracking if available+ if (window.attrV2 && window.attrV2.DirtyTracking) {+ window.attrV2.DirtyTracking.reinitialize();+ }+ }++ // Safe reinitialization for AJAX updates - handles both textareas and full setup+ function reinitializeAttrV2ForAjax() {+ // Reinitialize textareas (existing functionality)+ reinitializeTextareas();++ // Reinitialize dirty tracking if available+ if (window.attrV2 && window.attrV2.DirtyTracking) {+ window.attrV2.DirtyTracking.reinitialize();+ }++ // Note: Form event handlers should persist through DOM updates+ // since the form element itself is not replaced, only its content+ }+++ function setupBasicEventListeners() {+ // Try multiple approaches to find the form+ let form = $(Hi.ATTR_V2_FORM_SELECTOR)[0];++ // Also try multiple selectors+ let formAlt = $(`${Hi.ATTR_V2_FORM_SELECTOR}, ${Hi.ATTR_V2_MODAL_CLASS_SELECTOR}, form[data-async]`)[0];++ if (!form && !formAlt) {+ setTimeout(() => {+ form = $(Hi.ATTR_V2_FORM_SELECTOR)[0];+ formAlt = $(`${Hi.ATTR_V2_FORM_SELECTOR}, ${Hi.ATTR_V2_MODAL_CLASS_SELECTOR}, form[data-async]`)[0];++ const finalForm = form || formAlt;+ if (finalForm) {+ attachKeyHandler(finalForm);+ } else {+ console.error('setupBasicEventListeners: No form found after timeout');+ }+ }, 100);+ return;+ }++ const finalForm = form || formAlt;+ attachKeyHandler(finalForm);+ }++ function attachKeyHandler(form) {+ // Handle ENTER key behavior ONLY for V2 form inputs and textareas+ form.addEventListener('keydown', function(event) {+ // IMPORTANT: Only handle events from elements within the V2 form+ if (!event.target.closest(Hi.ATTR_V2_FORM_SELECTOR)) {+ return; // Not our form, don't interfere+ }++ if (event.key === 'Enter' || event.keyCode === 13) {+ if (event.target.tagName === 'TEXTAREA') {+ // For textareas, prevent form submission but allow newline+ event.preventDefault();++ const textarea = event.target;+ const start = textarea.selectionStart;+ const end = textarea.selectionEnd;+ const value = textarea.value;++ // Insert newline at cursor position+ textarea.value = value.substring(0, start) + '\n' + value.substring(end);+ textarea.selectionStart = textarea.selectionEnd = start + 1;++ // Trigger autosize update+ if (window.autosize) {+ autosize.update(textarea);+ }+ event.stopPropagation(); // Don't let this bubble up+ return false;+ }++ // For text inputs, convert to textarea if they want to add newlines+ // BUT only for value fields, not name fields+ if (event.target.tagName === 'INPUT' && event.target.type === 'text') {+ const fieldName = event.target.name || event.target.id || '';++ // Only convert value fields to textarea, never name fields+ if (fieldName.includes('-name') || fieldName.includes('_name')) {+ return false; // Just prevent form submission, don't convert+ }++ // Convert value fields to textarea+ if (fieldName.includes('-value') || fieldName.includes('_value')) {+ const $textarea = convertToTextarea(event.target);+ const currentValue = $textarea.val();+ $textarea.val(currentValue + '\n');++ // Position cursor at end+ const textarea = $textarea[0];+ textarea.setSelectionRange(textarea.value.length, textarea.value.length);+ return false;+ }++ // For other text inputs, just prevent form submission+ return false;+ }++ // For all other elements, just prevent form submission (already done above)+ return false;+ }+ }, false); // Changed from capture phase to bubble phase to be less intrusive++ // Form submission now handled by antinode.js with data-async and data-stay-in-modal+ }++ // Simple add attribute - just show the last (empty) formset form+ window.showAddAttribute = function() {+ // Find the last attribute card (should be the empty extra form)+ const attributeCards = $(Hi.ATTR_V2_ATTRIBUTE_CARD_SELECTOR);++ if (attributeCards.length > 0) {+ const lastCard = attributeCards[attributeCards.length - 1];+ const $lastCard = $(lastCard);++ // Show the card if hidden+ $lastCard.show();++ // Focus on the name field+ const nameField = $lastCard.find('input[name$="-name"]')[0];+ if (nameField) {+ nameField.focus();+ }++ // Initialize autosize on any textarea in the new card+ const textarea = $lastCard.find('textarea')[0];+ if (textarea && !textarea.hasAttribute('data-autosize-initialized')) {+ autosize($(textarea));+ textarea.setAttribute('data-autosize-initialized', 'true');+ }++ // Scroll into view+ lastCard.scrollIntoView({ behavior: 'smooth', block: 'nearest' });+ }+ };++ // Removed dedicated add attribute form functions - using Django formset approach only+++ window.markFileForDeletion = function(attributeId) {+ const $fileCard = $(`${Hi.ATTR_V2_FILE_CARD_SELECTOR}[data-attribute-id="${attributeId}"]`);+ if ($fileCard.length === 0) return;++ // The display "name" for a file is its attribute.value, *not* attribute.name+ const fileValue = $fileCard.find(Hi.ATTR_V2_FILE_TITLE_INPUT_SELECTOR).val().trim();++ // Find and mark the server-rendered DELETE field for deletion+ const $deleteField = $fileCard.find('input[name="delete_file_attribute"]');+ if ($deleteField.length > 0) {+ // Set value to the attribute ID to mark for deletion+ $deleteField.val(attributeId);+ } else {+ console.warn(`DELETE field not found for file attribute ${attributeId}`);+ return;+ }++ // Visual feedback - CSS handles all styling+ $fileCard.addClass('marked-for-deletion');++ // Hide delete button and show undo button (both server-rendered)+ $fileCard.find(Hi.ATTR_V2_DELETE_BTN_SELECTOR).hide();+ $fileCard.find(Hi.ATTR_V2_UNDO_BTN_SELECTOR).show();++ // Show status message+ const $statusMsg = $(Hi.ATTR_V2_STATUS_MSG_SELECTOR);+ if ($statusMsg.length > 0) {+ $statusMsg.text(`"${fileValue}" will be deleted when you save`)+ .attr('class', 'attr-v2-status-message ml-2 text-warning');++ setTimeout(() => {+ $statusMsg.text('').attr('class', 'attr-v2-status-message ml-2');+ }, 5000);+ }+ };++ window.undoFileDeletion = function(attributeId) {+ const $fileCard = $(`${Hi.ATTR_V2_FILE_CARD_SELECTOR}[data-attribute-id="${attributeId}"]`);+ if ($fileCard.length === 0) return;++ // The display "name" for a file is its attribute.value, *not* attribute.name+ const fileValue = $fileCard.find(Hi.ATTR_V2_FILE_TITLE_INPUT_SELECTOR).val().trim();++ // Unmark the DELETE field+ const $deleteField = $fileCard.find('input[name="delete_file_attribute"]');+ if ($deleteField.length > 0) {+ $deleteField.val("");+ }++ // Remove visual feedback - CSS handles all styling+ $fileCard.removeClass('marked-for-deletion');++ // Show delete button and hide undo button (both server-rendered)+ $fileCard.find(Hi.ATTR_V2_DELETE_BTN_SELECTOR).show();+ $fileCard.find(Hi.ATTR_V2_UNDO_BTN_SELECTOR).hide();++ // Show status message+ const $statusMsg = $(Hi.ATTR_V2_STATUS_MSG_SELECTOR);+ if ($statusMsg.length > 0) {+ $statusMsg.text(`Deletion of "${fileValue}" cancelled`)+ .attr('class', 'attr-v2-status-message ml-2 text-success');++ setTimeout(() => {+ $statusMsg.text('').attr('class', 'attr-v2-status-message ml-2');+ }, 3000);+ }+ };++ // History functionality now handled by antinode async pattern+ // History button uses data-async to load content, no JavaScript needed++ window.markAttributeForDeletion = function(attributeId) {+ const $attributeCard = $(`[data-attribute-id="${attributeId}"]`);+ if ($attributeCard.length === 0) return;++ const attributeName = $attributeCard.find(Hi.ATTR_V2_ATTRIBUTE_NAME_SELECTOR).text().trim().replace('•', '').trim();++ // Find and mark the server-rendered DELETE field for deletion+ const $deleteField = $attributeCard.find('input[name$="-DELETE"]');+ if ($deleteField.length > 0) {+ // For hidden fields, set value to "on" (what browsers send for checked checkboxes)+ $deleteField.val("on");+ } else {+ console.warn(`DELETE field not found for attribute ${attributeId}`);+ return;+ }++ // Visual feedback - CSS handles all styling+ $attributeCard.addClass('marked-for-deletion');++ // Hide delete button and show undo button (both server-rendered)+ $attributeCard.find(Hi.ATTR_V2_DELETE_BTN_SELECTOR).hide();+ $attributeCard.find(Hi.ATTR_V2_UNDO_BTN_SELECTOR).show();++ // Show status message+ const $statusMsg = $(Hi.ATTR_V2_STATUS_MSG_SELECTOR);+ if ($statusMsg.length > 0) {+ $statusMsg.text(`"${attributeName}" will be deleted when you save`)+ .attr('class', 'attr-v2-status-message ml-2 text-warning');++ setTimeout(() => {+ $statusMsg.text('').attr('class', 'attr-v2-status-message ml-2');+ }, 5000);+ }+ };++ window.undoAttributeDeletion = function(attributeId) {+ const $attributeCard = $(`[data-attribute-id="${attributeId}"]`);+ if ($attributeCard.length === 0) return;++ const attributeName = $attributeCard.find(Hi.ATTR_V2_ATTRIBUTE_NAME_SELECTOR).text().trim().replace('•', '').trim();++ // Unmark the DELETE field+ const $deleteField = $attributeCard.find('input[name$="-DELETE"]');+ if ($deleteField.length > 0) {+ $deleteField.val("");+ }++ // Remove visual feedback - CSS handles all styling+ $attributeCard.removeClass('marked-for-deletion');++ // Show delete button and hide undo button (both server-rendered)+ $attributeCard.find(Hi.ATTR_V2_DELETE_BTN_SELECTOR).show();+ $attributeCard.find(Hi.ATTR_V2_UNDO_BTN_SELECTOR).hide();++ // Show status message+ const $statusMsg = $(Hi.ATTR_V2_STATUS_MSG_SELECTOR);+ if ($statusMsg.length > 0) {+ $statusMsg.text(`Deletion of "${attributeName}" cancelled`)+ .attr('class', 'attr-v2-status-message ml-2 text-success');++ setTimeout(() => {+ $statusMsg.text('').attr('class', 'attr-v2-status-message ml-2');+ }, 3000);+ }+ };++ window.attrV2.toggleSecretField = function(button) {+ const $button = $(button);+ const $input = $button.closest(Hi.ATTR_V2_SECRET_INPUT_WRAPPER_SELECTOR).find(Hi.ATTR_V2_SECRET_INPUT_SELECTOR);+ const $showIcon = $button.find(Hi.ATTR_V2_ICON_SHOW_SELECTOR);+ const $hideIcon = $button.find(Hi.ATTR_V2_ICON_HIDE_SELECTOR);+ const isPassword = $input.attr('type') === 'password';++ // Check if field is disabled (non-editable attributes should stay disabled)+ const isDisabled = $input.prop('disabled');++ if (isPassword) {+ // Currently hidden - show as text and make editable+ $input.attr('type', 'text');+ $button.attr('title', 'Hide value');++ // Remove readonly to allow editing, but only if not disabled+ if (!isDisabled) {+ $input.prop('readonly', false);+ $input.removeAttr('readonly');+ }++ // Show hide icon, hide show icon+ $showIcon.hide();+ $hideIcon.show();+ } else {+ // Currently showing - hide as password and make readonly+ $input.attr('type', 'password');+ $button.attr('title', 'Show value');++ // Set readonly to prevent editing obfuscated text+ if (!isDisabled) {+ $input.prop('readonly', true);+ $input.attr('readonly', 'readonly');+ }++ // Show show icon, hide hide icon+ $showIcon.show();+ $hideIcon.hide();+ }+ };+++++++ // Initialize autosize for all textareas in the modal+ function initializeAutosizeTextareas() {+ // Initialize autosize for existing textareas, but exclude truncated ones+ const textareas = $(Hi.ATTR_V2_TEXTAREA_SELECTOR).not('.truncated');+ if (textareas.length > 0) {+ autosize(textareas);++ // Update when modal is shown (in case of display issues)+ $('.modal').on('shown.bs.modal', function () {+ autosize.update(textareas);+ });+ }+ }++ // Lightweight reinitialization for ajax content updates+ function reinitializeTextareas() {+ // Find all textareas that need initialization+ const textareas = $(Hi.ATTR_V2_TEXTAREA_SELECTOR);++ // Remove any previous autosize instances to avoid duplicates+ textareas.each(function() {+ if (this._autosize) {+ autosize.destroy($(this));+ }+ });++ // Initialize overflow state based on server-rendered attributes+ textareas.each(function() {+ const textarea = $(this);+ const wrapper = textarea.closest(Hi.ATTR_V2_TEXT_VALUE_WRAPPER_SELECTOR);+ const isOverflowing = wrapper.attr('data-overflow') === 'true';++ // Check if this is a display field (new pattern) or legacy textarea+ const hiddenFieldId = textarea.attr('data-hidden-field');+ const hiddenField = hiddenFieldId ? $('#' + hiddenFieldId) : null;++ if (isOverflowing) {+ if (hiddenField && hiddenField.length > 0) {+ applyTruncationFromHidden(textarea, hiddenField);+ } else {+ applyTruncation(textarea);+ }+ }+ });++ // THEN: Apply autosize only to editable, non-truncated textareas+ // (readonly textareas don't need dynamic resizing)+ const editableTextareas = $(Hi.ATTR_V2_TEXTAREA_SELECTOR).not('.truncated').not('[readonly]');+ if (editableTextareas.length > 0) {+ autosize(editableTextareas);+ }++ // Trigger autosize update for editable textareas only+ if (editableTextareas.length > 0) {+ autosize.update(editableTextareas);+ }+ }++ // Update overflow state based on current content+ function updateOverflowState(textarea) {+ const content = textarea.val() || '';+ const lineCount = (content.match(/\n/g) || []).length + 1;+ const overflows = lineCount > 4;++ const wrapper = textarea.closest(Hi.ATTR_V2_TEXT_VALUE_WRAPPER_SELECTOR);+ wrapper.attr('data-overflow', overflows ? 'true' : 'false');+ wrapper.attr('data-line-count', lineCount);++ return { lineCount, overflows };+ }++ // Apply truncation using hidden field as source (new pattern)+ function applyTruncationFromHidden(displayField, hiddenField) {+ const fullValue = hiddenField.val() || '';++ // Destroy autosize first to prevent height override+ if (window.autosize && displayField[0]._autosize) {+ autosize.destroy(displayField);+ }++ const lines = fullValue.split('\n');+ const truncatedValue = lines.slice(0, 4).join('\n');++ // Apply truncated display+ displayField.val(truncatedValue + '...');+ // Clear any explicit height style that might override rows+ displayField.css('height', '');+ displayField.attr('rows', 4);+ displayField.attr('readonly', 'readonly');+ displayField.prop('readonly', true);+ displayField.addClass('truncated');++ // Show expand controls+ const wrapper = displayField.closest(Hi.ATTR_V2_TEXT_VALUE_WRAPPER_SELECTOR);+ const expandControls = wrapper.find(Hi.ATTR_V2_EXPAND_CONTROLS_SELECTOR);+ expandControls.show();+ }++ // Legacy function - kept for compatibility with reinitializeTextareas+ function applyTruncation(textarea) {+ const value = textarea.val() || '';++ // Destroy autosize first to prevent height override+ if (window.autosize && textarea[0]._autosize) {+ autosize.destroy(textarea);+ }++ const lines = value.split('\n');+ const truncatedValue = lines.slice(0, 4).join('\n');++ // Store full value and show truncated+ textarea.data('full-value', value);+ textarea.data('truncated-value', truncatedValue);+ textarea.val(truncatedValue + '...');+ // Clear any explicit height style that might override rows+ textarea.css('height', '');+ textarea.attr('rows', 4);+ textarea.attr('readonly', 'readonly');+ textarea.prop('readonly', true);+ textarea.addClass('truncated');++ // Show expand controls+ const wrapper = textarea.closest(Hi.ATTR_V2_TEXT_VALUE_WRAPPER_SELECTOR);+ const expandControls = wrapper.find(Hi.ATTR_V2_EXPAND_CONTROLS_SELECTOR);+ expandControls.show();+ }++ function initializeExpandableTextareas() {+ // Initialize based on server-rendered overflow state using hidden field pattern+ const displayTextareas = $('.display-field');++ displayTextareas.each(function() {+ const displayField = $(this);+ const isOverflowing = displayField.attr('data-overflow') === 'true';+ const hiddenFieldId = displayField.attr('data-hidden-field');+ const hiddenField = $('#' + hiddenFieldId);++ if (isOverflowing && hiddenField.length > 0) {+ // Apply truncation using hidden field as source+ applyTruncationFromHidden(displayField, hiddenField);+ }+ // For non-overflowing content, display field already has correct content from server+ });+ }++ // Global function for expand/collapse button (namespaced) - enhanced for hidden field pattern+ window.attrV2.toggleExpandedView = function(button) {+ const $button = $(button);+ const wrapper = $button.closest(Hi.ATTR_V2_TEXT_VALUE_WRAPPER_SELECTOR);+ const displayField = wrapper.find('.display-field, ' + Hi.ATTR_V2_TEXTAREA_SELECTOR); // Support both new and legacy+ const showMoreText = $button.find('.show-more-text');+ const showLessText = $button.find('.show-less-text');++ // Get hidden field if using new pattern+ const hiddenFieldId = displayField.attr('data-hidden-field');+ const hiddenField = hiddenFieldId ? $('#' + hiddenFieldId) : null;++ if (displayField.prop('readonly')) {+ // Currently collapsed - expand it (Show More)+ let fullValue;+ if (hiddenField && hiddenField.length > 0) {+ // New pattern: Get from hidden field+ fullValue = hiddenField.val() || '';+ } else {+ // Legacy pattern: Get from stored data+ fullValue = displayField.data('full-value') || '';+ }++ const lineCount = (fullValue.match(/\n/g) || []).length + 1;++ displayField.val(fullValue);+ displayField.attr('rows', Math.max(lineCount, 5));+ displayField.prop('readonly', false);+ displayField.attr('readonly', false); // Remove readonly attribute+ displayField.removeClass('truncated');++ showMoreText.hide();+ showLessText.show();++ // Apply autosize now that display field is editable+ if (window.autosize) {+ autosize(displayField);+ autosize.update(displayField);+ }++ // Set up listener to track content changes+ displayField.off('input.overflow').on('input.overflow', function() {+ updateOverflowState($(this));+ });+ } else {+ // Currently expanded - check if we should collapse (Show Less)+ const { lineCount, overflows } = updateOverflowState(displayField);++ if (!overflows) {+ // Content now fits in 4 lines - remove truncation UI+ displayField.attr('rows', lineCount);+ displayField.prop('readonly', false);+ displayField.removeClass('truncated');+ wrapper.find('.attr-v2-expand-controls').hide();++ // Update wrapper state+ wrapper.attr('data-overflow', 'false');++ // Sync to hidden field if using new pattern+ if (hiddenField && hiddenField.length > 0) {+ hiddenField.val(displayField.val());+ }+ } else {+ // Still overflows - apply truncation with hidden field sync+ const currentValue = displayField.val();++ // Sync current content to hidden field before truncating display+ if (hiddenField && hiddenField.length > 0) {+ hiddenField.val(currentValue);++ // Apply truncation using hidden field+ applyTruncationFromHidden(displayField, hiddenField);+ } else {+ // Legacy pattern+ applyTruncation(displayField);+ }++ showMoreText.show();+ showLessText.hide();+ }++ // Remove the input listener+ displayField.off('input.overflow');+ }+ }++ // Pre-save handler with truncation protection for hidden field pattern+ function setupFormSubmissionHandler() {+ const form = $(Hi.ATTR_V2_FORM_SELECTOR)[0];+ if (!form) return;++ form.addEventListener('submit', function(e) {+ // Process all display fields using the new hidden field pattern+ $('.display-field').each(function() {+ const displayField = $(this);+ const hiddenFieldId = displayField.attr('data-hidden-field');+ const hiddenField = hiddenFieldId ? $('#' + hiddenFieldId) : null;++ if (hiddenField && hiddenField.length > 0) {+ // Only sync if display field is NOT showing truncated data+ if (!displayField.prop('readonly') && !displayField.hasClass('truncated')) {+ // Display field contains user's edits - copy to hidden field+ const displayValue = displayField.val();+ hiddenField.val(displayValue);+ }+ // Display field is readonly/truncated - hidden field already has correct full content+ }+ });++ // Legacy support: restore full values to any remaining old-pattern truncated textareas+ $(Hi.ATTR_V2_TEXTAREA_SELECTOR + '.truncated').not('.display-field').each(function() {+ const textarea = $(this);+ const fullValue = textarea.data('full-value');+ if (fullValue !== undefined) {+ textarea.val(fullValue);+ textarea.prop('readonly', false);+ }+ });+ }, true); // Use capture phase to ensure this runs early+ }++ // Convert single-line input to textarea when user adds newlines+ function convertToTextarea(inputElement) {+ const $input = $(inputElement);+ const value = $input.val();++ // Create textarea element+ const $textarea = $('<textarea>', {+ rows: 1,+ id: $input.attr('id'),+ name: $input.attr('name'),+ class: $input.attr('class') + ' ' + Hi.ATTR_V2_TEXTAREA_CLASS,+ 'data-original-value': $input.attr('data-original-value')+ });++ // Copy attributes+ if ($input.is(':disabled')) {+ $textarea.prop('disabled', true);+ }++ // Set value and replace input+ $textarea.val(value);+ $input.replaceWith($textarea);++ // Initialize autosize+ autosize($textarea);+ $textarea.focus();++ return $textarea;+ }+++})();diff --git a/src/hi/static/js/main.js b/src/hi/static/js/main.jsindex 7ee19e70..0e315583 100644--- a/src/hi/static/js/main.js+++ b/src/hi/static/js/main.js@@ -62,7 +62,72 @@},displayElementInfo: function( label, element ) {return _displayElementInfo( label, element );- }+ },++ // Entity Attribute Editing V2 - IDs and Classes+ ATTR_V2_FORM_ID: 'attr-v2-form',+ ATTR_V2_CONTENT_ID: 'attr-v2-content',+ ATTR_V2_UPLOAD_FORM_CONTAINER_ID: 'attr-v2-upload-form-container',+ ATTR_V2_FILE_GRID_ID: 'attr-v2-file-grid',+ ATTR_V2_STATUS_MSG_ID: 'attr-v2-status-msg',+ ATTR_V2_DIRTY_MESSAGE_ID: 'attr-v2-dirty-message',+ ATTR_V2_UPDATE_BTN_ID: 'attr-v2-update-btn',+ ATTR_V2_MESSAGES_ID: 'attr-v2-messages',+ ATTR_V2_FILE_INPUT_ID: 'attr-v2-file-input',+ ATTR_V2_ADD_ATTRIBUTE_BTN_ID: 'attr-v2-add-attribute-btn',+ ATTR_V2_SCROLLABLE_CONTENT_ID: 'attr-v2-scrollable-content',+ ATTR_V2_MODAL_CLASS: 'attr-v2-modal',+ ATTR_V2_ATTRIBUTE_CARD_CLASS: 'attr-v2-attribute-card',+ ATTR_V2_NEW_ATTRIBUTE_CLASS: 'attr-v2-new-attribute',+ ATTR_V2_FILE_TITLE_INPUT_CLASS: 'attr-v2-file-title-input',+ ATTR_V2_FILE_INFO_CLASS: 'attr-v2-file-info',+ ATTR_V2_FIELD_DIRTY_CLASS: 'attr-v2-field-dirty',+ ATTR_V2_DIRTY_INDICATOR_CLASS: 'attr-v2-dirty-indicator',+ ATTR_V2_DIRTY_MESSAGE_CLASS: 'attr-v2-dirty-message',+ ATTR_V2_ATTRIBUTE_NAME_CLASS: 'attr-v2-attribute-name',+ ATTR_V2_DELETE_BTN_CLASS: 'attr-v2-delete-btn',+ ATTR_V2_UNDO_BTN_CLASS: 'attr-v2-undo-btn',+ ATTR_V2_FILE_CARD_CLASS: 'attr-v2-file-card',+ ATTR_V2_FILE_NAME_CLASS: 'attr-v2-file-filename',+ ATTR_V2_SECRET_INPUT_WRAPPER_CLASS: 'attr-v2-secret-input-wrapper',+ ATTR_V2_SECRET_INPUT_CLASS: 'attr-v2-secret-input',+ ATTR_V2_ICON_SHOW_CLASS: 'attr-v2-icon-show',+ ATTR_V2_ICON_HIDE_CLASS: 'attr-v2-icon-hide',+ ATTR_V2_TEXTAREA_CLASS: 'attr-v2-textarea',+ ATTR_V2_TEXT_VALUE_WRAPPER_CLASS: 'attr-v2-text-value-wrapper',+ ATTR_V2_EXPAND_CONTROLS_CLASS: 'attr-v2-expand-controls',++ // Ready-to-use jQuery selectors+ ATTR_V2_FORM_SELECTOR: '#attr-v2-form',+ ATTR_V2_CONTENT_SELECTOR: '#attr-v2-content',+ ATTR_V2_UPLOAD_FORM_CONTAINER_SELECTOR: '#attr-v2-upload-form-container',+ ATTR_V2_FILE_GRID_SELECTOR: '#attr-v2-file-grid',+ ATTR_V2_STATUS_MSG_SELECTOR: '#attr-v2-status-msg',+ ATTR_V2_DIRTY_MESSAGE_SELECTOR: '#attr-v2-dirty-message',+ ATTR_V2_UPDATE_BTN_SELECTOR: '#attr-v2-update-btn',+ ATTR_V2_MESSAGES_SELECTOR: '#attr-v2-messages',+ ATTR_V2_FILE_INPUT_SELECTOR: '#attr-v2-file-input',+ ATTR_V2_ADD_ATTRIBUTE_BTN_SELECTOR: '#attr-v2-add-attribute-btn',+ ATTR_V2_SCROLLABLE_CONTENT_SELECTOR: '#attr-v2-scrollable-content',+ ATTR_V2_MODAL_SELECTOR: '.attr-v2-modal',+ ATTR_V2_ATTRIBUTE_CARD_SELECTOR: '.attr-v2-attribute-card',+ ATTR_V2_NEW_ATTRIBUTE_SELECTOR: '.attr-v2-new-attribute',+ ATTR_V2_FILE_TITLE_INPUT_SELECTOR: '.attr-v2-file-title-input',+ ATTR_V2_FILE_INFO_SELECTOR: '.attr-v2-file-info',+ ATTR_V2_FIELD_DIRTY_SELECTOR: '.attr-v2-field-dirty',+ ATTR_V2_DIRTY_INDICATOR_SELECTOR: '.attr-v2-dirty-indicator',+ ATTR_V2_ATTRIBUTE_NAME_SELECTOR: '.attr-v2-attribute-name',+ ATTR_V2_DELETE_BTN_SELECTOR: '.attr-v2-delete-btn',+ ATTR_V2_UNDO_BTN_SELECTOR: '.attr-v2-undo-btn',+ ATTR_V2_FILE_CARD_SELECTOR: '.attr-v2-file-card',+ ATTR_V2_FILE_NAME_SELECTOR: '.attr-v2-file-filename',+ ATTR_V2_SECRET_INPUT_WRAPPER_SELECTOR: '.attr-v2-secret-input-wrapper',+ ATTR_V2_SECRET_INPUT_SELECTOR: '.attr-v2-secret-input',+ ATTR_V2_ICON_SHOW_SELECTOR: '.attr-v2-icon-show',+ ATTR_V2_ICON_HIDE_SELECTOR: '.attr-v2-icon-hide',+ ATTR_V2_TEXTAREA_SELECTOR: '.attr-v2-textarea',+ ATTR_V2_TEXT_VALUE_WRAPPER_SELECTOR: '.attr-v2-text-value-wrapper',+ ATTR_V2_EXPAND_CONTROLS_SELECTOR: '.attr-v2-expand-controls'};@@ -111,8 +176,16 @@}function _toggleDetails( elementId ) {+ if (!elementId || elementId.trim() === '') {+ console.warn('_toggleDetails called with empty elementId');+ return;+ }const el = document.getElementById(elementId);- $(el).toggle();+ if (el) {+ $(el).toggle();+ } else {+ console.warn('_toggleDetails: Element not found with ID:', elementId);+ }}function _setEntityStateValueSelect( valueFieldId, instanceName, instanceId ) {diff --git a/src/hi/templates/icons/eye-off.html b/src/hi/templates/icons/eye-off.htmlnew file mode 100644index 00000000..eedf4592--- /dev/null+++ b/src/hi/templates/icons/eye-off.html@@ -0,0 +1,3 @@+<svg class="{{ class_attr }}" viewBox="0 0 24 24" fill="currentColor" {{ accessibility_attrs }}>+ <path d="M12 7c2.76 0 5 2.24 5 5 0 .65-.13 1.26-.36 1.83l2.92 2.92c1.51-1.26 2.7-2.89 3.43-4.75-1.73-4.39-6-7.5-11-7.5-1.4 0-2.74.25-3.98.7l2.16 2.16C10.74 7.13 11.35 7 12 7zM2 4.27l2.28 2.28.46.46C3.08 8.3 1.78 10.02 1 12c1.73 4.39 6 7.5 11 7.5 1.55 0 3.03-.3 4.38-.84l.42.42L19.73 22 21 20.73 3.27 3 2 4.27zM7.53 9.8l1.55 1.55c-.05.21-.08.43-.08.65 0 1.66 1.34 3 3 3 .22 0 .44-.03.65-.08l1.55 1.55c-.67.33-1.41.53-2.2.53-2.76 0-5-2.24-5-5 0-.79.2-1.53.53-2.2zm4.31-.78l3.15 3.15.02-.16c0-1.66-1.34-3-3-3l-.17.01z"/>+</svg>\ No newline at end of filediff --git a/src/hi/templates/icons/eye.html b/src/hi/templates/icons/eye.htmlnew file mode 100644index 00000000..06951ea2--- /dev/null+++ b/src/hi/templates/icons/eye.html@@ -0,0 +1,3 @@+<svg class="{{ class_attr }}" viewBox="0 0 24 24" fill="currentColor" {{ accessibility_attrs }}>+ <path d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/>+</svg>\ No newline at end of filediff --git a/src/hi/templates/modals/base.html b/src/hi/templates/modals/base.htmlindex 5e80e9bd..7eec55ac 100644--- a/src/hi/templates/modals/base.html+++ b/src/hi/templates/modals/base.html@@ -5,14 +5,14 @@<div class="modal-content"><div class="modal-title"><div class="row {% block header_class %}bg-secondary{% endblock %} m-0 py-2">- <div class="col-md-2 col-3 align-self-center text-center">+ <div class="col-md-2 col-3 align-self-center text-center modal-title-image">{% block title_image %}<img class="img-fluid"src="{% static 'img/hi-icon-196x196.png' %}"alt="HI Logo" \>{% endblock %}</div>- <div class="col-md-9 col-8 align-self-center h4 m-0 px-1">+ <div class="col-md-9 col-8 align-self-center h4 m-0 px-1 modal-title">{% block title_text %}{% endblock %}</div>diff --git a/src/hi/view_parameters.py b/src/hi/view_parameters.pyindex b3c416eb..6fc8d7e1 100644--- a/src/hi/view_parameters.py+++ b/src/hi/view_parameters.py@@ -54,12 +54,16 @@ class ViewParameters:def location_view(self) -> LocationView:if self._location_view:return self._location_view- if self.location_view_id is None:- return Nonetry:- self._location_view = LocationView.objects.select_related('location').get(- id = self.location_view_id,- )+ queryset = LocationView.objects.select_related('location')+ if self.location_view_id is None:+ self._location_view = queryset.order_by( 'order_id' ).first()+ if not self._location_view:+ raise LocationView.DoesNotExist()+ else:+ self._location_view = queryset.get( id = self.location_view_id )++ self.location_view_id = self._location_view.idself._location = self._location_view.locationreturn self._location_viewexcept LocationView.DoesNotExist: