Skip to content

Home Information - Your home, your data, organized.

Python

Configuration Settings Redesign with Attribute Framework Integration (#142)

Tony Caacb0b5bbfea
diff --git a/docs/dev/backend/attribute-editing-integration-guide.md b/docs/dev/backend/attribute-editing-integration-guide.md
index 7f86d78e..ad77513c 100644
--- a/docs/dev/backend/attribute-editing-integration-guide.md
+++ b/docs/dev/backend/attribute-editing-integration-guide.md
@@ -56,397 +56,59 @@ Your implementation needs:
## Step-by-Step Implementation
-### Step 1: Create AttributeEditContext Subclass
+### Step 1: Create AttributeItemEditContext Subclass
Create `yourapp/yourmodel_attribute_edit_context.py`:
-```python
-"""
-YourModelAttributeEditContext - YourModel-specific context for attribute editing templates.
-"""
-from typing import Any
-from hi.apps.attribute.edit_context import AttributeEditContext
-from .models import YourModel
-
-class YourModelAttributeEditContext(AttributeEditContext):
- """YourModel-specific context provider for attribute editing templates."""
-
- def __init__(self, your_model: YourModel) -> None:
- """Initialize context for YourModel attribute editing."""
- super().__init__(your_model, 'yourmodel') # 'yourmodel' must match URL patterns
-
- @property
- def your_model(self) -> YourModel:
- """Get the YourModel instance (typed accessor)."""
- return self.owner
+See the following existing integrations:
```
+# Single instance/formset
+src/hi/apps/entity/entity_attribute_edit_context.py
+src/hi/apps/location/location_attribute_edit_context.py
-### Step 2: Create Form Handler Class
-
-Create `yourapp/yourmodel_edit_form_handler.py`:
-
-```python
-"""
-YourModelEditFormHandler - Handles form creation, validation, and processing.
-"""
-import logging
-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 YourModel, YourModelAttribute
-from .forms import YourModelForm, YourModelAttributeRegularFormSet
-from .yourmodel_attribute_edit_context import YourModelAttributeEditContext
-
-logger = logging.getLogger(__name__)
-
-class YourModelEditFormHandler:
- """Handles form creation, validation, and processing for yourmodel editing."""
-
- @staticmethod
- def get_formset_prefix(your_model: YourModel) -> str:
- """Get the formset prefix for regular attributes formset."""
- return f'yourmodel-{your_model.id}'
-
- def create_yourmodel_forms(
- self,
- your_model: YourModel,
- form_data: Optional[Dict[str, Any]] = None
- ) -> Tuple[YourModelForm, QuerySet[YourModelAttribute], YourModelAttributeRegularFormSet]:
- """Create yourmodel forms used by both initial rendering and fragment updates."""
-
- # Create yourmodel form
- yourmodel_form = YourModelForm(form_data, instance=your_model)
-
- # Get file attributes for display
- file_attributes = your_model.attributes.filter(
- value_type_str=str(AttributeValueType.FILE)
- ).order_by('id')
-
- # Regular attributes formset (excludes FILE attributes)
- regular_attributes_formset = YourModelAttributeRegularFormSet(
- form_data,
- instance=your_model,
- prefix=self.get_formset_prefix(your_model),
- form_kwargs={'show_as_editable': True}
- )
-
- return yourmodel_form, file_attributes, regular_attributes_formset
-
- def validate_forms(
- self,
- yourmodel_form: YourModelForm,
- regular_attributes_formset: YourModelAttributeRegularFormSet
- ) -> bool:
- """Validate yourmodel form and attributes formset."""
- return yourmodel_form.is_valid() and regular_attributes_formset.is_valid()
-
- def save_forms(
- self,
- yourmodel_form: YourModelForm,
- regular_attributes_formset: YourModelAttributeRegularFormSet,
- request: HttpRequest,
- your_model: YourModel
- ) -> None:
- """Save forms and process file operations within a transaction."""
- with transaction.atomic():
- yourmodel_form.save()
- regular_attributes_formset.save()
- # Add any custom file processing here
-
- def create_initial_context(self, your_model: YourModel) -> Dict[str, Any]:
- """Create initial template context for yourmodel editing form."""
- yourmodel_form, file_attributes, regular_attributes_formset = self.create_yourmodel_forms(your_model)
-
- # Create the attribute edit context for template generalization
- attr_context = YourModelAttributeEditContext(your_model)
-
- # Build context with both old and new patterns for compatibility
- context = {
- 'your_model': your_model,
- 'yourmodel_form': yourmodel_form,
- 'owner_form': yourmodel_form, # Generic alias for templates
- 'file_attributes': file_attributes,
- 'regular_attributes_formset': regular_attributes_formset,
- }
-
- # Merge in the context variables from AttributeEditContext
- context.update(attr_context.to_template_context())
-
- return context
+# Multipla instance/formset
+src/hi/apps/config/subsystem_attribute_edit_context.py
```
-### Step 3: Create Response Renderer Class
-
-Create `yourapp/yourmodel_edit_response_renderer.py`:
-
-```python
-"""
-YourModelEditResponseRenderer - Handles template rendering and response generation.
-"""
-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 .yourmodel_edit_form_handler import YourModelEditFormHandler
-from .models import YourModel, YourModelAttribute
-from .forms import YourModelForm, YourModelAttributeRegularFormSet
-from .yourmodel_attribute_edit_context import YourModelAttributeEditContext
-
-class YourModelEditResponseRenderer:
- """Handles template rendering and response generation for yourmodel editing."""
-
- def __init__(self) -> None:
- self.form_handler = YourModelEditFormHandler()
-
- def build_template_context(
- self,
- your_model: YourModel,
- yourmodel_form: YourModelForm,
- file_attributes: QuerySet[YourModelAttribute],
- regular_attributes_formset: YourModelAttributeRegularFormSet,
- success_message: Optional[str] = None,
- error_message: Optional[str] = None,
- has_errors: bool = False
- ) -> Dict[str, Any]:
- """Build context dictionary for template rendering."""
-
- # Create the attribute edit context for template generalization
- attr_context = YourModelAttributeEditContext(your_model)
-
- # Build context with both old and new patterns for compatibility
- context = {
- 'your_model': your_model,
- 'yourmodel_form': yourmodel_form,
- 'owner_form': yourmodel_form, # Generic alias for templates
- 'file_attributes': file_attributes,
- 'regular_attributes_formset': regular_attributes_formset,
- 'success_message': success_message,
- 'error_message': error_message,
- 'has_errors': has_errors,
- }
-
- # Merge in the context variables from AttributeEditContext
- context.update(attr_context.to_template_context())
-
- return context
-
- def render_success_response(
- self,
- request: HttpRequest,
- your_model: YourModel
- ) -> 'antinode.Response':
- """Render success response using antinode helpers."""
- # Re-render content with fresh forms
- yourmodel_form, file_attributes, regular_attributes_formset = self.form_handler.create_yourmodel_forms(your_model)
-
- context = self.build_template_context(
- your_model, yourmodel_form, file_attributes, regular_attributes_formset,
- success_message="Changes saved successfully"
- )
-
- # Render content body
- content_body = render_to_string('yourapp/panes/yourmodel_edit_content_body.html', context, request=request)
-
- # Render upload form
- file_upload_url = reverse('yourmodel_attribute_upload', kwargs={'yourmodel_id': your_model.id})
- upload_form = render_to_string(
- 'attribute/components/upload_form.html',
- {'file_upload_url': file_upload_url},
- request=request
- )
-
- return antinode.response(
- insert_map={
- DIVID['ATTR_V2_CONTENT']: content_body,
- DIVID['ATTR_V2_UPLOAD_FORM_CONTAINER']: upload_form
- }
- )
-```
+### Step 2: Create the needed views.
-### Step 4: Create Content Body Template
+- Pick whether you need a single or multiple instance implementation
+- Single instance view will include the mixin AttributeEditViewMixin
+- Multiple instance views will include the mixin AttributeMultiEditViewMixin
+- Your views get() method can render any sort of page or modal.
+- The get() method must get its template comntext from the mixin
+- The page or modal template must include a "content body" template (see below)
+- The post always goes though a mixin method and returns custom JSON for front-end (attr.js)
-Create `yourapp/templates/yourapp/panes/yourmodel_edit_content_body.html`:
+The full set of views include:
+- Main editing entry
+- File upload handling (optional)
+- Attribute History
+- Atribute Value restore
-```django
-{% extends "attribute/components/edit_content_body.html" %}
-{% comment %}
-YourModel V2 Content Body Fragment
-Extends the generic attribute edit content body with yourmodel-specific field layout.
-{% endcomment %}
+### Step 3: Create Content Body Template
-{% block owner_fields %}
-<!-- YourModel-specific fields for modal editing -->
-<div class="row">
- <div class="col-md-12">
- <div class="form-group mb-0">
- <small class="text-muted">Name</small>
- <input type="text"
- id="{{ owner_form.name.id_for_label }}"
- name="{{ owner_form.name.html_name }}"
- value="{{ owner_form.name.value|default:'' }}"
- class="form-control form-control-sm"
- {% if owner_form.name.field.required %}required{% endif %}>
- {% if owner_form.name.errors %}
- <div class="invalid-feedback d-block">
- {{ owner_form.name.errors }}
- </div>
- {% endif %}
- </div>
- </div>
- <!-- Add additional yourmodel-specific fields here -->
-</div>
-{% endblock %}
-```
-
-### Step 5: Update Views to Use Handler/Renderer Pattern
-
-Update your main edit view:
-
-```python
-from .yourmodel_edit_form_handler import YourModelEditFormHandler
-from .yourmodel_edit_response_renderer import YourModelEditResponseRenderer
-
-class YourModelEditView(HiModalView, YourModelViewMixin):
- """YourModel attribute editing modal with redesigned interface."""
-
- def get_template_name(self) -> str:
- return 'yourapp/modals/yourmodel_edit.html'
-
- def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
- your_model = self.get_yourmodel(request, *args, **kwargs)
-
- # Delegate form creation and context building to handler
- form_handler = YourModelEditFormHandler()
- context = form_handler.create_initial_context(your_model)
-
- return self.modal_response(request, context)
-
- def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
- your_model = self.get_yourmodel(request, *args, **kwargs)
-
- # Delegate form handling to specialized handlers
- form_handler = YourModelEditFormHandler()
- renderer = YourModelEditResponseRenderer()
-
- # Create forms with POST data
- yourmodel_form, file_attributes, regular_attributes_formset = form_handler.create_yourmodel_forms(
- your_model, request.POST
- )
-
- if form_handler.validate_forms(yourmodel_form, regular_attributes_formset):
- # Save forms and process files
- form_handler.save_forms(yourmodel_form, regular_attributes_formset, request, your_model)
-
- # Return success response
- return renderer.render_success_response(request, your_model)
- else:
- # Return error response
- return renderer.render_error_response(request, your_model, yourmodel_form, regular_attributes_formset)
-```
+- Create `yourapp/templates/yourapp/panes/yourmodel_edit_content_body.html`:
+- This template must extend `attribute/components/edit_content_body.html`
+- Override content blocks as needed.
-### Step 6: Update Upload and History Views
-
-Update your upload view:
-
-```python
-def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
- your_model = self.get_yourmodel(request, *args, **kwargs)
- # ... upload form validation ...
-
- if upload_form.is_valid():
- with transaction.atomic():
- upload_form.save()
-
- # Render new file card HTML to append to file grid
- attr_context = YourModelAttributeEditContext(your_model)
- context = {'attribute': yourmodel_attribute, 'your_model': your_model}
- context.update(attr_context.to_template_context())
-
- file_card_html = render_to_string(
- 'attribute/components/file_card.html',
- context,
- request=request
- )
- # ... return response ...
+Example:
```
-
-Update your history inline view:
-
-```python
-class YourModelAttributeHistoryInlineView(BaseAttributeHistoryView):
- """View for displaying YourModelAttribute history inline within the edit modal."""
-
- def get_template_name(self):
- return 'attribute/components/attribute_history_inline.html'
-
- def get(self, request: HttpRequest, yourmodel_id: int, attribute_id: int, *args, **kwargs) -> HttpResponse:
- # ... validation and history retrieval ...
-
- # Create the attribute edit context for template generalization
- attr_context = YourModelAttributeEditContext(attribute.your_model)
-
- context = {
- 'your_model': attribute.your_model,
- 'attribute': attribute,
- 'history_records': history_records,
- 'history_url_name': self.get_history_url_name(),
- 'restore_url_name': self.get_restore_url_name(),
- }
-
- # Merge in the context variables from AttributeEditContext
- context.update(attr_context.to_template_context())
-
- return render(request, self.get_template_name(), context)
-```
-
-### Step 7: Add URL Patterns
-
-Add URL patterns for history and restore functionality:
-
-```python
-# yourapp/urls.py
-urlpatterns = [
- # ... existing patterns ...
-
- # Attribute history and restore (inline)
- re_path(r'^yourmodel/(?P<yourmodel_id>\d+)/attribute/(?P<attribute_id>\d+)/history/inline/$',
- views.YourModelAttributeHistoryInlineView.as_view(),
- name='yourmodel_attribute_history_inline'),
-
- re_path(r'^yourmodel/(?P<yourmodel_id>\d+)/attribute/(?P<attribute_id>\d+)/restore/inline/(?P<history_id>\d+)/$',
- views.YourModelAttributeRestoreInlineView.as_view(),
- name='yourmodel_attribute_restore_inline'),
-
- # File upload
- re_path(r'^yourmodel/(?P<yourmodel_id>\d+)/attribute/upload/$',
- views.YourModelAttributeUploadView.as_view(),
- name='yourmodel_attribute_upload'),
-]
+src/hi/apps/config/templates/config/panes/subsystem_edit_content_body.html
+src/hi/apps/entity/templates/entity/panes/entity_edit_content_body.html
+src/hi/apps/location/templates/location/panes/location_edit_content_body.html
```
-## Template Integration Details
+### Step 4: Add URL Patterns
-### Using Template Filters and Tags
+- Add URL patterns for the views.
+- Follow the naming convenions in the attribute edit context classes or override them if needed
-The generic templates use specialized filters and tags for dynamic functionality. Make sure to load them:
-
-```django
-{% load attribute_extras %}
-
-<!-- Dynamic URL generation -->
-{% attr_history_url attr_context attribute.id %}
-{% attr_restore_url attr_context attribute.id history_record.pk %}
-
-<!-- Dynamic field names -->
-{{ attr_context|file_title_field_name:attribute.id }}
-{{ attr_context|history_target_id:attribute.id }}
+See:
+```
+src/hi/apps/entity/urls.py
+src/hi/apps/location/urls.py
+src/hi/apps/config/urls.py
```
### Customizing Owner Fields
@@ -466,41 +128,6 @@ Override the `owner_fields` block to define model-specific fields:
{% endblock %}
```
-## Testing Integration
-
-### Required Test Coverage
-
-1. **Form Handler Tests**: Test form creation, validation, and saving
-2. **Response Renderer Tests**: Test template context building and response generation
-3. **View Tests**: Test GET/POST behavior with proper context
-4. **Template Tests**: Verify template rendering with context variables
-5. **Upload/History Tests**: Test file upload and history functionality
-
-### Example Test Structure
-
-```python
-class TestYourModelEditFormHandler(BaseTestCase):
- def test_create_initial_context(self):
- """Test that initial context includes AttributeEditContext variables."""
- your_model = self.create_test_yourmodel()
- form_handler = YourModelEditFormHandler()
-
- context = form_handler.create_initial_context(your_model)
-
- self.assertIn('attr_context', context)
- self.assertIn('owner_form', context)
- self.assertEqual(context['your_model'], your_model)
-```
-
-## Troubleshooting
-
-### Common Issues
-
-1. **Template Not Found**: Ensure template paths match your app structure
-2. **Context Variables Missing**: Verify `attr_context.to_template_context()` is called
-3. **URL Pattern Mismatch**: Check that `owner_type` in context matches URL pattern names
-4. **Form Validation Errors**: Ensure formset prefixes are unique and consistent
-
### Template Debugging
Add this to templates for debugging context variables:
@@ -518,12 +145,9 @@ Add this to templates for debugging context variables:
Verify these key context variables are available:
-- `attr_context` - The AttributeEditContext instance
+- `attr_owner_context` - The AttributeEditContext instance
+- `attr_item_context` - The AttributeEditContext instance
- `owner_form` - Generic alias for model-specific form
- `your_model` - Your specific model instance
- `file_attributes` - QuerySet of file attributes
- `regular_attributes_formset` - Formset for non-file attributes
-
-## Conclusion
-
-Following this guide ensures your new model integrates seamlessly with the established attribute editing patterns, providing consistent UI/UX while maintaining code reuse and type safety. The pattern scales well and provides a solid foundation for future attribute-owning models.
\ No newline at end of file
diff --git a/src/hi/apps/attribute/edit_context.py b/src/hi/apps/attribute/edit_context.py
index 830f61c3..66f96d13 100644
--- a/src/hi/apps/attribute/edit_context.py
+++ b/src/hi/apps/attribute/edit_context.py
@@ -1,37 +1,53 @@
"""
-AttributeEditContext - Generic context provider for attribute editing templates.
+Attribute Edit Contexts - Generic context provider for attribute editing templates.
-This class provides a clean abstraction that allows attribute editing templates
+These classes provide a clean abstraction that allows attribute editing templates
to work generically across different owner types (Entity, Location, etc.) while
maintaining type safety and clear URL routing patterns.
+
+Usage:
+
+- You have a Django model that extends AttributeModel and adds a foreign key
+- The owner object need to be a Django Model that serves as a foreign key into the AttributeModel subclass
+- You need to defined subclasses of AttributePageEditContext and AttributeItemEditContext.
+- In your view, you need to define one AttributePageEditContext instance
+- In your view, you need to define one or more AttributeItemEditContext instances
+
+Two Use Cases:
+
+1) Single Instance Editing (Entity, Location, modals)
+
+ Has one AttributeItemEditContext instance and that can be also be used for AttributePageEditContext.
+
+2) Multiple Instance Editing (Subsystem, special case)
+
+ Has multiple AttributeItemEditContext instance and a separate AttributePageEditContext.
+
"""
-from typing import Any, Dict
+from typing import Any, Dict, Optional, Type
+from django.forms import ModelForm, BaseInlineFormSet
+from django.db.models import Model
-class AttributeEditContext:
- """
- Context provider for attribute editing templates that abstracts away
- owner-specific details (entity vs location vs future types).
-
- This allows templates to be completely generic while providing
- type-safe access to owner information, URLs, and DOM identifiers.
- """
+from hi.constants import DIVID
+
+from .forms import AttributeUploadForm
+from .models import AttributeModel
+
+
+class AttributePageEditContext:
- def __init__(self, owner: Any, owner_type: str) -> None:
- """
- Initialize context for attribute editing.
-
- Args:
- owner: The model instance that owns the attributes (Entity, Location, etc.)
- owner_type: String identifier for the owner type ("entity", "location", etc.)
- """
- self.owner = owner
+ def __init__(self, owner_type: str, owner: Model = None ) -> None:
self.owner_type = owner_type.lower()
-
+ self.owner = owner
+ return
+
@property
def owner_id(self) -> int:
"""Get the owner's primary key ID."""
- return self.owner.id
+ if self.owner:
+ return self.owner.id
+ return None
@property
def owner_id_param_name(self) -> str:
@@ -39,20 +55,123 @@ class AttributeEditContext:
return f'{self.owner_type}_id'
@property
- def owner_name(self) -> str:
- """Get the owner's display name."""
- return self.owner.name
+ def id_suffix(self) -> str:
+ """
+ Get the suffix to append to DIVID constants for unique element IDs.
+
+ This creates namespaced IDs that prevent conflicts when multiple
+ attribute editing contexts exist on the same page.
+
+ Returns:
+ str: Suffix like '-entity-123' or '-location-456', '-subsystem''
+ """
+ if self.owner:
+ return f'-{self.owner_type}-{self.owner_id}'
+ return f'-{self.owner_type}'
+
+ @property
+ def content_body_template_name(self):
+ """ This should be a template that extends attribute/components/edit_content_body.html """
+ raise NotImplementedError('Subclasses must override this method')
@property
def history_url_name(self) -> str:
- """Get the URL name for inline attribute history view."""
+ """ Should be a view that uses AttributeEditViewMixin.get_history() """
return f'{self.owner_type}_attribute_history_inline'
@property
def restore_url_name(self) -> str:
- """Get the URL name for inline attribute restore view."""
+ """ Should be a view that uses AttributeEditViewMixin.post_restore() """
return f'{self.owner_type}_attribute_restore_inline'
+
+ @property
+ def container_html_id(self) -> str:
+ return f"{DIVID['ATTR_V2_CONTAINER_ID']}{self.id_suffix}"
+
+ @property
+ def content_html_id(self) -> str:
+ return f"{DIVID['ATTR_V2_CONTENT_ID']}{self.id_suffix}"
+
+ @property
+ def dirty_msg_html_id(self) -> str:
+ return f"{DIVID['ATTR_V2_DIRTY_MESSAGE_ID']}{self.id_suffix}"
+
+ @property
+ def form_html_id(self) -> str:
+ return f"{DIVID['ATTR_V2_FORM_ID']}{self.id_suffix}"
+
+ @property
+ def scrollable_content_html_id(self) -> str:
+ return f"{DIVID['ATTR_V2_SCROLLABLE_CONTENT_ID']}{self.id_suffix}"
+
+ @property
+ def status_msg_html_id(self) -> str:
+ return f"{DIVID['ATTR_V2_STATUS_MESSAGE_ID']}{self.id_suffix}"
+ @property
+ def update_button_html_id(self) -> str:
+ return f"{DIVID['ATTR_V2_UPDATE_BTN_ID']}{self.id_suffix}"
+
+ def to_template_context(self) -> Dict[str, Any]:
+ return {
+ "attr_page_context": self,
+ }
+
+
+class AttributeItemEditContext( AttributePageEditContext ):
+ """
+ Context provider for attribute editing templates that abstracts away
+ owner-specific details (entity vs location vs future types).
+
+ This allows templates to be completely generic while providing
+ type-safe access to owner information, URLs, and DOM identifiers.
+ """
+
+ def __init__(self, owner: Model, owner_type: str) -> None:
+ super().__init__( owner_type = owner_type, owner = owner )
+ return
+
+ @property
+ def attribute_model_subclass(self) -> Type[AttributeModel]:
+ raise NotImplementedError('Subclasses must override this method')
+
+ @property
+ def formset_prefix(self) -> str:
+ return f'{self.owner_type}-{self.owner.id}'
+
+ def create_owner_form( self, form_data : Optional[ Dict[str, Any] ] = None ) -> ModelForm:
+ """ Subclasses can override this if there are model properties of the owner model itself
+ that should be included in the attribute editing interface."""
+ return None
+
+ def create_attribute_model( self ) -> AttributeModel:
+ raise NotImplementedError('Subclasses must override this method')
+
+ def create_regular_attributes_formset(
+ self, form_data : Optional[ Dict[str, Any] ] = None ) -> BaseInlineFormSet:
+ """ Formset should extend BaseInlineFormSet. (should exclude FILE attributes) """
+ raise NotImplementedError('Subclasses must override this method')
+
+ def attributes_queryset(self):
+ """ Default is that AttributeModel suibclass has 'attributes' as the related name for
+ the owner model. """
+ return self.owner.attributes.all()
+
+ @property
+ def attribute_upload_form_class(self) -> Type[AttributeUploadForm]:
+ return None
+
+ @property
+ def file_upload_url(self) -> str:
+ """ File uploads are Optional.
+ Subclasses should use a view that uses AttributeEditViewMixin.post_upload() """
+ return None
+
+ @property
+ def uses_file_uploads(self):
+ return bool( not (( self.attribute_upload_form_class is None )
+ or self.file_upload_url is None ))
+
def history_target_id(self, attribute_id: int) -> str:
"""
Get the DOM ID for the attribute history container.
@@ -89,17 +208,30 @@ class AttributeEditContext:
"""
return f'file_title_{self.owner_id}_{attribute_id}'
+ @property
+ def file_input_html_id(self) -> str:
+ return f"{DIVID['ATTR_V2_FILE_INPUT_ID']}{self.id_suffix}"
+
+ @property
+ def file_grid_html_id(self) -> str:
+ return f"{DIVID['ATTR_V2_FILE_GRID_ID']}{self.id_suffix}"
+
+ @property
+ def upload_form_container_html_id(self) -> str:
+ return f"{DIVID['ATTR_V2_UPLOAD_FORM_CONTAINER_ID']}{self.id_suffix}"
+
+ @property
+ def add_attribute_button_html_id(self) -> str:
+ return f"{DIVID['ATTR_V2_ADD_ATTRIBUTE_BTN_ID']}{self.id_suffix}"
+
def to_template_context(self) -> Dict[str, Any]:
- """
- Convert this context to a dictionary suitable for template rendering.
-
- Returns:
- dict: Template context variables
- """
- return {
- 'attr_context': self,
- # Provide the owner under both generic and specific names for compatibility
- 'owner': self.owner,
- self.owner_type: self.owner, # e.g., 'entity': self.owner or 'location': self.owner
- }
+ template_context = super().to_template_context()
+ template_context.update({
+ "owner": self.owner,
+ "attr_item_context": self,
+
+ # Duplicate with explicit naming for convenience.
+ self.owner_type: self.owner, # e.g., "entity": self.owner or "location": self.owner
+ })
+ return template_context
diff --git a/src/hi/apps/attribute/edit_form_handler.py b/src/hi/apps/attribute/edit_form_handler.py
new file mode 100644
index 00000000..7d7f8c37
--- /dev/null
+++ b/src/hi/apps/attribute/edit_form_handler.py
@@ -0,0 +1,282 @@
+import logging
+import re
+from typing import Any, Dict, List, Optional
+
+from django.conf import settings
+from django.db import transaction
+from django.db.models import QuerySet
+from django.http import HttpRequest
+
+from hi.constants import DIVID
+from hi.testing.dev_overrides import DevOverrideManager
+
+from .forms import AttributeUploadForm
+from .edit_context import AttributeItemEditContext
+from .enums import AttributeValueType
+from .models import AttributeModel
+from .transient_models import AttributeEditFormData, AttributeMultiEditFormData
+
+logger = logging.getLogger(__name__)
+
+
+class AttributeEditFormHandler:
+
+ def create_edit_form_data(
+ self,
+ attr_item_context : AttributeItemEditContext,
+ form_data : Optional[ Dict[str, Any] ] = None ) -> AttributeEditFormData:
+ """
+ Args:
+ form_data: POST data for bound forms, None for unbound forms
+ """
+ owner_form = attr_item_context.create_owner_form( form_data )
+
+ # Get file attributes for display (not a formset, just for template rendering)
+ file_attributes: QuerySet[AttributeModel] = attr_item_context.attributes_queryset().filter(
+ value_type_str = str( AttributeValueType.FILE )
+ ).order_by('id')
+
+ # Regular attributes formset (should exclude FILE attributes)
+ regular_attributes_formset = attr_item_context.create_regular_attributes_formset(
+ form_data = form_data,
+ )
+ return AttributeEditFormData(
+ owner_form = owner_form,
+ file_attributes = file_attributes,
+ regular_attributes_formset = regular_attributes_formset,
+ )
+
+ def validate_forms(self, edit_form_data: AttributeEditFormData) -> bool:
+ """
+ Returns:
+ bool: True if both forms are valid, False otherwise
+ """
+ if settings.DEBUG and settings.DEBUG_INJECT_ATTRIBUTE_FORM_ERRORS:
+ return DevOverrideManager.validate_forms( edit_form_data )
+
+ # Normal validation
+ if edit_form_data.owner_form and not edit_form_data.owner_form.is_valid():
+ return False
+ return edit_form_data.regular_attributes_formset.is_valid()
+
+ def save_forms( self,
+ attr_item_context : AttributeItemEditContext,
+ edit_form_data : AttributeEditFormData,
+ request : HttpRequest ) -> None:
+
+ with transaction.atomic():
+ if edit_form_data.owner_form:
+ edit_form_data.owner_form.save()
+ edit_form_data.regular_attributes_formset.save()
+
+ self.process_file_title_updates(
+ attr_item_context = attr_item_context,
+ request = request,
+ )
+ self.process_file_deletions(
+ attr_item_context = attr_item_context,
+ request = request,
+ )
+ return
+
+ def process_file_deletions( self,
+ attr_item_context : AttributeItemEditContext,
+ request : HttpRequest ) -> None:
+ file_deletes: List[str] = request.POST.getlist( DIVID['ATTR_V2_DELETE_FILE_ATTR'] )
+ if not file_deletes:
+ return
+
+ AttributeModelClass = attr_item_context.attribute_model_subclass
+
+ for attr_id in file_deletes:
+ if not attr_id: # Skip empty values
+ continue
+ try:
+ file_attribute = AttributeModelClass.objects.get(
+ id = attr_id,
+ value_type_str = str(AttributeValueType.FILE)
+ )
+ # Verify permission to delete
+ if file_attribute.attribute_type.can_delete:
+ file_attribute.delete()
+ except AttributeModelClass.DoesNotExist:
+ pass
+ continue
+ return
+
+ def process_file_title_updates( self,
+ attr_item_context : AttributeItemEditContext,
+ request : HttpRequest ) -> None:
+ """Process file_title_* fields from POST data to update file attribute values."""
+ # Pattern to match file_title_{owner_id}_{attribute_id}
+ file_title_pattern = re.compile(r'^file_title_(\d+)_(\d+)$')
+
+ AttributeModelClass = attr_item_context.attribute_model_subclass
+
+ for field_name, new_title in request.POST.items():
+ match = file_title_pattern.match(field_name)
+ if not match:
+ continue
+
+ owner_id_str: str
+ attribute_id_str: str
+ owner_id_str, attribute_id_str = match.groups()
+
+ # Validate owner_id matches current owner
+ if int(owner_id_str) != attr_item_context.owner.id:
+ logger.warning(f'File title field {field_name} has mismatched owner ID')
+ continue
+
+ try:
+ attribute_id: int = int(attribute_id_str)
+ attribute = AttributeModelClass.objects.get(
+ id = attribute_id,
+ 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 also create a history record
+
+ except (ValueError) as e:
+ logger.warning(f'Invalid file title field {field_name}: {e}')
+ except (AttributeModelClass.DoesNotExist) as e:
+ logger.warning(f'File attribute not found {field_name}: {e}')
+
+ def collect_form_errors(self, edit_form_data: AttributeEditFormData) -> List[str]:
+ """
+ Collect errors for central display and count all form errors (as side efffect).
+
+ Note: Individual form.non_field_errors() are NOT collected in the return list
+ They should be displayed inline with the specific forms/fields
+ """
+
+ non_form_errors = []
+ total_error_count = 0
+
+ if edit_form_data.owner_form:
+ owner_form = edit_form_data.owner_form
+ total_error_count += len( owner_form.non_field_errors() )
+ for field_name in owner_form.fields:
+ total_error_count += len( owner_form[field_name].errors )
+ continue
+
+ if edit_form_data.regular_attributes_formset:
+ formset = edit_form_data.regular_attributes_formset
+ try:
+ # Accessing management_form will raise ValidationError if data is missing
+ formset.management_form
+ except Exception:
+ # Management form missing - count as one system error
+ total_error_count += 1
+ non_form_errors.append(
+ "Form data is missing or incomplete."
+ )
+ else:
+ # Count formset-level errors
+ formset_non_form_errors = formset.non_form_errors()
+ if formset_non_form_errors:
+ total_error_count += len(formset_non_form_errors)
+ non_form_errors.extend(
+ [f"Properties: {error}" for error in formset_non_form_errors]
+ )
+
+ # Count individual form errors (field and non-field)
+ for form in formset.forms:
+ # Count field errors for each form using standard API
+ total_error_count += len( form.non_field_errors() )
+ for field_name in form.fields:
+ total_error_count += len( form[field_name].errors )
+ continue
+
+ edit_form_data.error_count = total_error_count
+ return non_form_errors
+
+ def create_upload_form( self,
+ attr_item_context : AttributeItemEditContext,
+ request : HttpRequest ) -> AttributeUploadForm:
+ assert attr_item_context.uses_file_uploads
+
+ AttributeUploadFormClass = attr_item_context.attribute_upload_form_class
+ owner_attribute = attr_item_context.create_attribute_model()
+ return AttributeUploadFormClass(
+ request.POST,
+ request.FILES,
+ instance = owner_attribute,
+ )
+
+ def validate_upload_form( self, attribute_upload_form : AttributeUploadForm ) -> bool:
+ return attribute_upload_form.is_valid()
+
+ def save_upload_form( self, attribute_upload_form : AttributeUploadForm ) -> None:
+ with transaction.atomic():
+ attribute_upload_form.save()
+ return
+
+ def create_multi_edit_form_data(
+ self,
+ attr_item_context_list : List[AttributeItemEditContext],
+ form_data : Optional[ Dict[str, Any] ] = None ) -> List[AttributeMultiEditFormData]:
+
+ multi_edit_form_data_list = list()
+ for attr_item_context in attr_item_context_list:
+ edit_form_data = self.create_edit_form_data(
+ attr_item_context = attr_item_context,
+ form_data = form_data,
+ )
+ multi_edit_form_data = AttributeMultiEditFormData(
+ attr_item_context = attr_item_context,
+ edit_form_data = edit_form_data,
+ )
+ multi_edit_form_data_list.append( multi_edit_form_data )
+ continue
+ return multi_edit_form_data_list
+
+ def validate_forms_multi(
+ self,
+ multi_edit_form_data_list : List[AttributeMultiEditFormData] ) -> bool:
+
+ if settings.DEBUG and settings.DEBUG_INJECT_ATTRIBUTE_FORM_ERRORS:
+ for multi_edit_form_data in multi_edit_form_data_list:
+ self.validate_forms( edit_form_data = multi_edit_form_data.edit_form_data )
+ continue
+ return False
+
+ for multi_edit_form_data in multi_edit_form_data_list:
+ if not self.validate_forms( edit_form_data = multi_edit_form_data.edit_form_data ):
+ return False
+ continue
+ return True
+
+ def save_forms_multi(
+ self,
+ multi_edit_form_data_list : List[AttributeMultiEditFormData],
+ request : HttpRequest ) -> None:
+ for multi_edit_form_data in multi_edit_form_data_list:
+ self.save_forms(
+ attr_item_context = multi_edit_form_data.attr_item_context,
+ edit_form_data = multi_edit_form_data.edit_form_data,
+ request = request,
+ )
+ continue
+ return True
+
+ def collect_form_errors_multi(
+ self,
+ multi_edit_form_data_list : List[AttributeMultiEditFormData] ) -> List[str]:
+
+ non_form_errors = list()
+ for multi_edit_form_data in multi_edit_form_data_list:
+ errors = self.collect_form_errors(
+ edit_form_data = multi_edit_form_data.edit_form_data,
+ )
+ non_form_errors.extend( errors )
+ continue
+
+ return non_form_errors
diff --git a/src/hi/apps/attribute/edit_response_renderer.py b/src/hi/apps/attribute/edit_response_renderer.py
new file mode 100644
index 00000000..4166b94d
--- /dev/null
+++ b/src/hi/apps/attribute/edit_response_renderer.py
@@ -0,0 +1,409 @@
+import logging
+from typing import List, Optional
+
+from django.http import HttpRequest, HttpResponse
+from django.template.loader import render_to_string
+
+from .edit_context import AttributeItemEditContext, AttributePageEditContext
+from .edit_form_handler import AttributeEditFormHandler
+from .edit_template_context_builder import AttributeEditTemplateContextBuilder
+from .forms import AttributeUploadForm
+from .models import AttributeModel, AttributeValueHistoryModel
+from .response_helpers import AttributeResponseBuilder, UpdateMode
+from .response_constants import DefaultMessages
+from .transient_models import AttributeEditFormData, AttributeMultiEditFormData
+
+logger = logging.getLogger(__name__)
+
+
+class AttributeEditResponseRenderer:
+ """
+ Handles template rendering and response generation for attribute 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 = AttributeEditFormHandler()
+ self.template_context_builder = AttributeEditTemplateContextBuilder()
+ return
+
+ def render_form_success_response(
+ self,
+ attr_item_context : AttributeItemEditContext,
+ request : HttpRequest,
+ message : DefaultMessages.SAVE_SUCCESS ) -> HttpResponse:
+ """Render success response using custom JSON format - multiple target replacement.
+ Returns:
+ HttpResponse: Success response with JSON format for custom Ajax handling
+ """
+ # Re-render both content body and upload form with fresh forms
+ content_body = self.render_update_content_body(
+ attr_item_context = attr_item_context,
+ request = request,
+ success_message = DefaultMessages.SAVE_SUCCESS
+ )
+ response_builder = (
+ AttributeResponseBuilder()
+ .success()
+ .add_update(
+ target = f"#{attr_item_context.content_html_id}",
+ html = content_body,
+ mode = UpdateMode.REPLACE
+ )
+ )
+ if attr_item_context.uses_file_uploads:
+ upload_form = self.render_upload_form(
+ attr_item_context = attr_item_context,
+ request = request,
+ )
+ response_builder.add_update(
+ target = f"#{attr_item_context.upload_form_container_html_id}",
+ html = upload_form,
+ mode = UpdateMode.REPLACE
+ )
+
+ return (
+ response_builder
+ .with_message(message)
+ .build_http_response()
+ )
+
+ def render_form_error_response(
+ self,
+ attr_item_context : AttributeItemEditContext,
+ edit_form_data : AttributeEditFormData,
+ request : HttpRequest ) -> HttpResponse:
+ """Render error response using custom JSON format - multiple target replacement.
+ Returns:
+ HttpResponse: Error response with JSON format for custom Ajax handling
+ """
+ # Re-render both content body and upload form with form errors
+ content_body = self.render_update_content_body(
+ attr_item_context = attr_item_context,
+ request = request,
+ edit_form_data = edit_form_data,
+ error_message = DefaultMessages.SAVE_ERROR,
+ has_errors = True,
+ )
+ response_builder = (
+ AttributeResponseBuilder()
+ .error()
+ .add_update(
+ target = f"#{attr_item_context.content_html_id}",
+ html = content_body,
+ mode = UpdateMode.REPLACE
+ )
+ )
+ if attr_item_context.uses_file_uploads:
+ upload_form = self.render_upload_form(
+ attr_item_context = attr_item_context,
+ request = request,
+ )
+ response_builder.add_update(
+ target = f"#{attr_item_context.upload_form_container_html_id}",
+ html = upload_form,
+ mode = UpdateMode.REPLACE
+ )
+
+ return (
+ response_builder
+ .with_message(DefaultMessages.SAVE_ERROR)
+ .build_http_response()
+ )
+
+ def render_update_content_body(
+ self,
+ attr_item_context : AttributeItemEditContext,
+ request : HttpRequest,
+ edit_form_data : AttributeEditFormData = None,
+ success_message : Optional[str] = None,
+ error_message : Optional[str] = None,
+ has_errors : bool = False ) -> str:
+
+ # If forms not provided, create fresh ones (for success case)
+ updated_form_data = self.get_updated_form_data(
+ attr_item_context = attr_item_context,
+ edit_form_data = edit_form_data,
+ )
+ template_context = self.template_context_builder.build_response_template_context(
+ attr_item_context = attr_item_context,
+ edit_form_data = updated_form_data,
+ success_message = success_message,
+ error_message = error_message,
+ has_errors= has_errors,
+ )
+ return render_to_string(
+ attr_item_context.content_body_template_name,
+ template_context,
+ request = request, # Needed for context processors (CSRF, DIVID, etc.)
+ )
+
+ def get_updated_form_data(
+ self,
+ attr_item_context : AttributeItemEditContext,
+ edit_form_data : AttributeEditFormData = None ) -> str:
+
+ fresh_form_data = self.form_handler.create_edit_form_data(
+ attr_item_context= attr_item_context,
+ )
+ if not edit_form_data:
+ return fresh_form_data
+
+ if edit_form_data.owner_form is None:
+ edit_form_data.owner_form = fresh_form_data.owner_form
+ if edit_form_data.regular_attributes_formset is None:
+ edit_form_data.regular_attributes_formset = fresh_form_data.regular_attributes_formset
+ if edit_form_data.file_attributes is None:
+ edit_form_data.file_attributes = fresh_form_data.file_attributes
+ return edit_form_data
+
+ def render_upload_form(
+ self,
+ attr_item_context : AttributeItemEditContext,
+ request : HttpRequest ) -> str:
+ assert attr_item_context.uses_file_uploads
+
+ return render_to_string(
+ 'attribute/components/upload_form.html',
+ {
+ 'file_upload_url': attr_item_context.file_upload_url,
+ 'attr_item_context': attr_item_context
+ },
+ request = request, # Needed for context processors (CSRF, DIVID, etc.)
+ )
+
+ def render_upload_success_response(
+ self,
+ attr_item_context : AttributeItemEditContext,
+ attribute_upload_form : AttributeUploadForm,
+ request : HttpRequest ) -> HttpResponse:
+
+ context = {'attribute': attribute_upload_form.instance }
+ context.update( attr_item_context.to_template_context() )
+
+ file_card_html = render_to_string(
+ 'attribute/components/file_card.html',
+ context,
+ request = request,
+ )
+ return (
+ AttributeResponseBuilder()
+ .success()
+ .add_update(
+ target = f"#{attr_item_context.file_grid_html_id}",
+ html = file_card_html,
+ mode = UpdateMode.APPEND,
+ )
+ .with_message(DefaultMessages.UPLOAD_SUCCESS)
+ .build_http_response()
+ )
+
+ def render_upload_error_response( self,
+ attr_item_context : AttributeItemEditContext,
+ attribute_upload_form : AttributeUploadForm,
+ request : HttpRequest ) -> HttpResponse:
+ error_html: str = render_to_string(
+ 'attribute/components/status_message.html',
+ {
+ 'error_message': DefaultMessages.UPLOAD_ERROR,
+ 'form_errors': attribute_upload_form.errors,
+ }
+ )
+ return (
+ AttributeResponseBuilder()
+ .error()
+ .add_update(
+ target=f'#{attr_item_context.status_msg_html_id}',
+ html=error_html,
+ mode=UpdateMode.REPLACE
+ )
+ .with_message(DefaultMessages.UPLOAD_ERROR)
+ .build_http_response()
+ )
+
+ def render_history_response( self,
+ attr_item_context : AttributeItemEditContext,
+ attribute : AttributeModel,
+ history_records : List[AttributeValueHistoryModel],
+ request : HttpRequest ) -> HttpResponse:
+ context = {
+ 'attribute': attribute,
+ 'history_records': history_records,
+ 'history_url_name': attr_item_context.history_url_name,
+ 'restore_url_name': attr_item_context.restore_url_name,
+ }
+ context.update(attr_item_context.to_template_context())
+
+ html_content = render_to_string(
+ template_name = 'attribute/components/attribute_history_inline.html',
+ context = context,
+ request = request
+ )
+
+ # Build JSON response with target selector for history content
+ return (
+ AttributeResponseBuilder()
+ .success()
+ .add_update(
+ target=f"#{attr_item_context.history_target_id(attribute.id)}",
+ html=html_content,
+ mode=UpdateMode.REPLACE
+ )
+ .with_message(f"History for {attribute.name}")
+ .build_http_response()
+ )
+
+ def render_restore_success_response(
+ self,
+ attr_item_context : AttributeItemEditContext,
+ request : HttpRequest ) -> HttpResponse:
+
+ return self.render_form_success_response(
+ attr_item_context = attr_item_context,
+ request = request,
+ message = DefaultMessages.RESTORE_SUCCESS,
+ )
+
+ def render_restore_error_response( self, message : str ) -> HttpResponse:
+ return (
+ AttributeResponseBuilder()
+ .error()
+ .with_message(DefaultMessages.RESTORE_ERROR)
+ .build_http_response()
+ )
+
+ def render_form_success_response_multi(
+ self,
+ attr_page_context : AttributePageEditContext,
+ multi_edit_form_data_list : List[AttributeMultiEditFormData],
+ request : HttpRequest,
+ message : DefaultMessages.SAVE_SUCCESS ) -> HttpResponse:
+
+ content_body = self.render_update_content_body_multi(
+ attr_page_context = attr_page_context,
+ multi_edit_form_data_list = multi_edit_form_data_list,
+ request = request,
+ success_message = DefaultMessages.SAVE_SUCCESS
+ )
+ response_builder = (
+ AttributeResponseBuilder()
+ .success()
+ .add_update(
+ target = f"#{attr_page_context.content_html_id}",
+ html = content_body,
+ mode = UpdateMode.REPLACE,
+ )
+ )
+ self.build_upload_forms_multi(
+ response_builder = response_builder,
+ multi_edit_form_data_list = multi_edit_form_data_list,
+ request = request,
+ )
+ return (
+ response_builder
+ .with_message( message )
+ .build_http_response()
+ )
+
+ def render_form_error_response_multi(
+ self,
+ attr_page_context : AttributePageEditContext,
+ multi_edit_form_data_list : List[AttributeMultiEditFormData],
+ request : HttpRequest ) -> HttpResponse:
+
+ content_body = self.render_update_content_body_multi(
+ attr_page_context = attr_page_context,
+ multi_edit_form_data_list = multi_edit_form_data_list,
+ request = request,
+ error_message = DefaultMessages.SAVE_ERROR,
+ has_errors = True,
+ )
+ response_builder = (
+ AttributeResponseBuilder()
+ .error()
+ .add_update(
+ target = f"#{attr_page_context.content_html_id}",
+ html = content_body,
+ mode = UpdateMode.REPLACE
+ )
+ )
+ self.build_upload_forms_multi(
+ response_builder = response_builder,
+ multi_edit_form_data_list = multi_edit_form_data_list,
+ request = request,
+ )
+ return (
+ response_builder
+ .with_message(DefaultMessages.SAVE_ERROR)
+ .build_http_response()
+ )
+
+ def render_restore_success_response_multi(
+ self,
+ attr_page_context : AttributePageEditContext,
+ multi_edit_form_data_list : List[AttributeMultiEditFormData],
+ request : HttpRequest ) -> HttpResponse:
+
+ return self.render_form_success_response_multi(
+ attr_page_context = attr_page_context,
+ multi_edit_form_data_list = multi_edit_form_data_list,
+ request = request,
+ message = DefaultMessages.RESTORE_SUCCESS,
+ )
+
+ def build_upload_forms_multi(
+ self,
+ response_builder : AttributeResponseBuilder,
+ multi_edit_form_data_list : List[AttributeMultiEditFormData],
+ request : HttpRequest ) -> HttpResponse:
+
+ for multi_edit_form_data in multi_edit_form_data_list:
+ attr_item_context = multi_edit_form_data.attr_item_context
+ if not attr_item_context.uses_file_uploads:
+ continue
+ upload_form = self.render_upload_form(
+ attr_item_context = attr_item_context,
+ request = request,
+ )
+ response_builder.add_update(
+ target = f"#{attr_item_context.upload_form_container_html_id}",
+ html = upload_form,
+ mode = UpdateMode.REPLACE,
+ )
+ continue
+ return
+
+ def render_update_content_body_multi(
+ self,
+ attr_page_context : AttributePageEditContext,
+ multi_edit_form_data_list : List[AttributeMultiEditFormData],
+ request : HttpRequest,
+ success_message : Optional[str] = None,
+ error_message : Optional[str] = None,
+ has_errors : bool = False ) -> HttpResponse:
+
+ for multi_edit_form_data in multi_edit_form_data_list:
+ updated_form_data = self.get_updated_form_data(
+ attr_item_context = multi_edit_form_data.attr_item_context,
+ edit_form_data = multi_edit_form_data.edit_form_data,
+ )
+ multi_edit_form_data.edit_form_data = updated_form_data
+ continue
+
+ template_context = self.template_context_builder.build_response_template_context_multi(
+ attr_page_context = attr_page_context,
+ multi_edit_form_data_list = multi_edit_form_data_list,
+ success_message = success_message,
+ error_message = error_message,
+ has_errors = has_errors,
+ )
+ return render_to_string(
+ attr_page_context.content_body_template_name,
+ template_context,
+ request = request, # Needed for context processors (CSRF, DIVID, etc.)
+ )
+
diff --git a/src/hi/apps/attribute/edit_template_context_builder.py b/src/hi/apps/attribute/edit_template_context_builder.py
new file mode 100644
index 00000000..feb52534
--- /dev/null
+++ b/src/hi/apps/attribute/edit_template_context_builder.py
@@ -0,0 +1,108 @@
+import logging
+from typing import Any, Dict, List, Optional
+
+from .edit_context import AttributeItemEditContext, AttributePageEditContext
+from .edit_form_handler import AttributeEditFormHandler
+from .transient_models import AttributeEditFormData, AttributeMultiEditFormData
+
+logger = logging.getLogger(__name__)
+
+
+class AttributeEditTemplateContextBuilder:
+
+ def __init__(self) -> None:
+ self.form_handler = AttributeEditFormHandler()
+ return
+
+ def build_initial_template_context(
+ self,
+ attr_item_context : AttributeItemEditContext ) -> Dict[str, Any]:
+
+ form_handler = AttributeEditFormHandler()
+ edit_form_data = form_handler.create_edit_form_data(
+ attr_item_context = attr_item_context,
+ )
+ context = {
+ 'owner_form': edit_form_data.owner_form,
+ 'file_attributes': edit_form_data.file_attributes,
+ 'regular_attributes_formset': edit_form_data.regular_attributes_formset,
+
+ # Duplicate with explicit naming for convenience.
+ f'{attr_item_context.owner_type}_form': edit_form_data.owner_form,
+ }
+
+ # Merge in the context variables from AttributeItemEditContext
+ context.update( attr_item_context.to_template_context() )
+ return context
+
+ def build_response_template_context(
+ self,
+ attr_item_context : AttributeItemEditContext,
+ edit_form_data : AttributeEditFormData,
+ success_message : Optional[str] = None,
+ error_message : Optional[str] = None,
+ has_errors : bool = False ) -> Dict[str, Any]:
+ """
+ Returns:
+ dict: Template context with all required variables
+ """
+ non_form_errors = self.form_handler.collect_form_errors(
+ edit_form_data = edit_form_data,
+ )
+
+ # Build context with both old and new patterns for compatibility
+ context = {
+ 'owner_form': edit_form_data.owner_form,
+ 'file_attributes': edit_form_data.file_attributes,
+ 'regular_attributes_formset': edit_form_data.regular_attributes_formset,
+ 'success_message': success_message,
+ 'error_message': error_message,
+ 'has_errors': has_errors,
+ 'non_form_errors': non_form_errors,
+ }
+
+ # Merge in the context variables from AttributeItemEditContext
+ context.update( attr_item_context.to_template_context() )
+
+ return context
+
+ def build_initial_template_context_multi(
+ self,
+ attr_page_context : AttributePageEditContext,
+ attr_item_context_list : List[AttributeItemEditContext] ) -> Dict[str, Any]:
+
+ form_handler = AttributeEditFormHandler()
+
+ multi_edit_form_data_list = form_handler.create_multi_edit_form_data(
+ attr_item_context_list = attr_item_context_list,
+ )
+ context = {
+ 'multi_edit_form_data_list': multi_edit_form_data_list,
+ }
+ # Merge in the context variables from AttributeItemEditContext
+ context.update( attr_page_context.to_template_context() )
+ return context
+
+ def build_response_template_context_multi(
+ self,
+ attr_page_context : AttributePageEditContext,
+ multi_edit_form_data_list : List[AttributeMultiEditFormData],
+ success_message : Optional[str] = None,
+ error_message : Optional[str] = None,
+ has_errors : bool = False ) -> Dict[str, Any]:
+
+ non_form_errors = self.form_handler.collect_form_errors_multi(
+ multi_edit_form_data_list = multi_edit_form_data_list,
+ )
+ context = {
+ 'multi_edit_form_data_list': multi_edit_form_data_list,
+ 'success_message': success_message,
+ 'error_message': error_message,
+ 'has_errors': has_errors,
+ 'non_form_errors': non_form_errors,
+ }
+
+ # Merge in the context variables from AttributePageEditContext
+ context.update( attr_page_context.to_template_context() )
+
+ return context
diff --git a/src/hi/apps/attribute/forms.py b/src/hi/apps/attribute/forms.py
index 2316f58d..4c4b7788 100644
--- a/src/hi/apps/attribute/forms.py
+++ b/src/hi/apps/attribute/forms.py
@@ -38,16 +38,20 @@ class AttributeForm( forms.ModelForm ):
@property
def show_as_editable(self):
return self._show_as_editable
+
+ @property
+ def allow_reordering(self):
+ return self._allow_reordering
def __init__(self, *args, **kwargs):
self._show_as_editable = kwargs.pop( 'show_as_editable', True )
- super().__init__(*args, **kwargs)
-
- # Access the instance's value_type field
+ self._allow_reordering = kwargs.pop( 'allow_reordering', True )
instance = kwargs.get('instance')
+ super().__init__(*args, **kwargs)
+ # For boolean attributes, keep string field but set initial as string consistently
if instance and instance.value_type.is_boolean:
- self.initial['value'] = str_to_bool( instance.value )
+ self.initial['value'] = str(str_to_bool(instance.value))
for field in self.fields.values():
if self._show_as_editable or ( instance and instance.is_editable ):
diff --git a/src/hi/apps/attribute/models.py b/src/hi/apps/attribute/models.py
index 0c0d5a6a..fd56ed85 100644
--- a/src/hi/apps/attribute/models.py
+++ b/src/hi/apps/attribute/models.py
@@ -211,14 +211,14 @@ class AttributeModel(models.Model):
if self.file_value:
try:
- if default_storage.exists( self.file_value ):
- default_storage.delete( self.file_value )
- logger.debug( f'Deleted Attribute file: {self.file_value}' )
+ if default_storage.exists( self.file_value.name ):
+ default_storage.delete( self.file_value.name )
+ logger.debug( f'Deleted Attribute file: {self.file_value.name}' )
else:
- logger.warn( f'Attribute file not found: {self.file_value}' )
+ logger.warn( f'Attribute file not found: {self.file_value.name}' )
except Exception as e:
# Log the error or handle it accordingly
- logger.warn( f'Error deleting Attribute file {self.file_value}: {e}' )
+ logger.warn( f'Error deleting Attribute file {self.file_value.name}: {e}' )
super().delete( *args, **kwargs )
return
diff --git a/src/hi/apps/attribute/response_constants.py b/src/hi/apps/attribute/response_constants.py
new file mode 100644
index 00000000..81d2a834
--- /dev/null
+++ b/src/hi/apps/attribute/response_constants.py
@@ -0,0 +1,53 @@
+"""
+Constants and enums for attribute response handling.
+
+This module defines all constants used in the client-server communication
+for attribute editing operations, ensuring consistency and type safety.
+"""
+from enum import Enum
+
+
+class UpdateMode(Enum):
+ """DOM update modes for client-side operations."""
+ REPLACE = "replace"
+ APPEND = "append"
+ PREPEND = "prepend"
+
+
+class ResponseStatus(Enum):
+ """Response status types."""
+ SUCCESS = "success"
+ ERROR = "error"
+
+
+# JSON Response Field Names
+class ResponseFields:
+ """Field names used in JSON responses."""
+ SUCCESS = "success"
+ UPDATES = "updates"
+ MESSAGE = "message"
+ TARGET = "target"
+ HTML = "html"
+ MODE = "mode"
+
+
+# HTTP Headers
+class HTTPHeaders:
+ """HTTP headers used in AJAX requests/responses."""
+ X_REQUESTED_WITH = "X-Requested-With"
+ XML_HTTP_REQUEST = "XMLHttpRequest"
+ CONTENT_TYPE = "Content-Type"
+ APPLICATION_JSON = "application/json"
+
+
+# Default Messages
+class DefaultMessages:
+ """Default status messages for common operations."""
+ SAVE_SUCCESS = "Changes saved successfully"
+ SAVE_ERROR = "Please correct the errors below"
+ UPLOAD_SUCCESS = "File uploaded successfully"
+ UPLOAD_ERROR = "File upload failed. Please check the file and try again."
+ DELETE_PENDING = '"{}" will be deleted when you save'
+ DELETE_CANCELLED = 'Deletion of "{}" cancelled'
+ RESTORE_SUCCESS = "Value restored from history"
+ RESTORE_ERROR = "Value could not be restored from history."
diff --git a/src/hi/apps/attribute/response_helpers.py b/src/hi/apps/attribute/response_helpers.py
new file mode 100644
index 00000000..536f7963
--- /dev/null
+++ b/src/hi/apps/attribute/response_helpers.py
@@ -0,0 +1,163 @@
+"""
+Response helper classes for attribute editing operations.
+
+This module provides a reusable builder pattern for constructing
+consistent JSON responses across all attribute editing views.
+"""
+import json
+from dataclasses import dataclass, field
+from typing import Any, Dict, List, Optional
+
+from django.http import HttpResponse
+
+from .response_constants import (
+ DefaultMessages,
+ HTTPHeaders,
+ ResponseFields,
+ UpdateMode,
+)
+
+
+@dataclass
+class DOMUpdate:
+ """Represents a single DOM update instruction."""
+ target: str # jQuery selector (e.g., "#element-id")
+ html: str # HTML content to insert
+ mode: UpdateMode = UpdateMode.REPLACE
+
+ def to_dict(self) -> Dict[str, str]:
+ """Convert to dictionary for JSON serialization."""
+ return {
+ ResponseFields.TARGET: self.target,
+ ResponseFields.HTML: self.html,
+ ResponseFields.MODE: self.mode.value,
+ }
+
+
+@dataclass
+class AttributeResponse:
+ """Represents a complete attribute operation response."""
+ success: bool
+ updates: List[DOMUpdate] = field(default_factory=list)
+ message: Optional[str] = None
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Convert to dictionary for JSON serialization."""
+ result = {
+ ResponseFields.SUCCESS: self.success,
+ ResponseFields.UPDATES: [update.to_dict() for update in self.updates],
+ }
+ if self.message:
+ result[ResponseFields.MESSAGE] = self.message
+ return result
+
+ def to_http_response(self, status_code: int = 200) -> HttpResponse:
+ """Convert to Django HttpResponse with proper JSON formatting."""
+ return HttpResponse(
+ json.dumps(self.to_dict()),
+ content_type=HTTPHeaders.APPLICATION_JSON,
+ status=status_code,
+ )
+
+
+class AttributeResponseBuilder:
+ """
+ Builder pattern for constructing attribute responses.
+
+ Usage:
+ response = (AttributeResponseBuilder()
+ .success()
+ .add_update("#content", html_content)
+ .with_message("Saved successfully")
+ .build())
+ """
+
+ def __init__(self):
+ self._success: bool = True
+ self._updates: List[DOMUpdate] = []
+ self._message: Optional[str] = None
+
+ def success(self, message: Optional[str] = None) -> "AttributeResponseBuilder":
+ """Set response as successful."""
+ self._success = True
+ if message:
+ self._message = message
+ return self
+
+ def error(self, message: Optional[str] = None) -> "AttributeResponseBuilder":
+ """Set response as error."""
+ self._success = False
+ if message:
+ self._message = message
+ return self
+
+ def add_update(
+ self,
+ target: str,
+ html: str,
+ mode: UpdateMode = UpdateMode.REPLACE
+ ) -> "AttributeResponseBuilder":
+ """Add a DOM update instruction."""
+ self._updates.append( DOMUpdate(target=target, html=html, mode=mode) )
+ return self
+
+ def with_message(self, message: str) -> "AttributeResponseBuilder":
+ """Set the response message."""
+ self._message = message
+ return self
+
+ def build(self) -> AttributeResponse:
+ """Build the final AttributeResponse object."""
+ return AttributeResponse(
+ success=self._success,
+ updates=self._updates,
+ message=self._message,
+ )
+
+ def build_http_response(self, status_code: Optional[int] = None) -> HttpResponse:
+ """Build and return as Django HttpResponse."""
+ if status_code is None:
+ status_code = 200 if self._success else 400
+ return self.build().to_http_response(status_code)
+
+ # Convenience class methods for common patterns
+
+ @classmethod
+ def create_success_response(
+ cls,
+ updates: List[DOMUpdate],
+ message: str = DefaultMessages.SAVE_SUCCESS,
+ status_code: int = 200
+ ) -> HttpResponse:
+ """Create a standard success response."""
+ builder = cls().success().with_message(message)
+ for update in updates:
+ builder._updates.append(update)
+ return builder.build_http_response(status_code)
+
+ @classmethod
+ def create_error_response(
+ cls,
+ updates: List[DOMUpdate],
+ message: str = DefaultMessages.SAVE_ERROR,
+ status_code: int = 400
+ ) -> HttpResponse:
+ """Create a standard error response."""
+ builder = cls().error().with_message(message)
+ for update in updates:
+ builder._updates.append(update)
+ return builder.build_http_response(status_code)
+
+ @classmethod
+ def create_upload_success_response(
+ cls,
+ target_selector: str,
+ file_card_html: str,
+ message: str = DefaultMessages.UPLOAD_SUCCESS
+ ) -> HttpResponse:
+ """Create a response for successful file upload."""
+ return (cls()
+ .success()
+ .add_update(target_selector, file_card_html, UpdateMode.APPEND)
+ .with_message(message)
+ .build_http_response())
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.html
index 852edaab..2d7bb2c8 100644
--- a/src/hi/apps/attribute/templates/attribute/components/attribute_history_inline.html
+++ b/src/hi/apps/attribute/templates/attribute/components/attribute_history_inline.html
@@ -6,32 +6,32 @@ Inline Attribute History Component
Compact history display that loads into attribute cards
{% endcomment %}
-<div class="attr-v2-history-inline-content">
+<div class="{{ DIVID.ATTR_V2_HISTORY_INLINE_CONTENT_CLASS }}">
<!-- History Header -->
- <div class="attr-v2-history-header">
+ <div class="{{ DIVID.ATTR_V2_HISTORY_HEADER_CLASS }}">
<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="$('#{{ attr_context|history_target_id:attribute.id }}').empty();"
+ class="btn btn-sm btn-link p-0 {{ DIVID.ATTR_V2_HISTORY_CLOSE_CLASS }}"
+ onclick="$('#{{ attr_item_context|history_target_id:attribute.id }}').empty();"
title="Close history">
{% icon "close" size="sm" %}
</button>
</div>
<!-- Current Value -->
- <div class="attr-v2-history-current mb-2">
+ <div class="{{ DIVID.ATTR_V2_HISTORY_CURRENT_CLASS }} 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">
+ <div class="{{ DIVID.ATTR_V2_HISTORY_RECORDS_CLASS }}">
{% for record in history_records %}
- <div class="attr-v2-history-record {% if forloop.counter > 3 %}collapse{% endif %}"
- {% if forloop.counter > 3 %}id="{{ attr_context|history_toggle_id:attribute.id }}"{% endif %}>
+ <div class="{{ DIVID.ATTR_V2_HISTORY_RECORD_CLASS }} {% if forloop.counter > 3 %}collapse{% endif %}"
+ {% if forloop.counter > 3 %}id="{{ attr_item_context|history_toggle_id:attribute.id }}"{% endif %}>
<div class="d-flex justify-content-between align-items-center">
<div>
<small class="text-muted">{{ record.changed_datetime|naturaltime }}</small>
@@ -39,10 +39,8 @@ Compact history display that loads into attribute cards
</div>
<div>
{% if record.value != attribute.value %}
- <a href="{% attr_restore_url attr_context attribute.id record.pk %}"
- data-async="true"
- data-stay-in-modal="true"
- class="btn btn-xs btn-outline-primary"
+ <a href="{% attr_restore_url attr_item_context attribute.id record.pk %}"
+ class="btn btn-xs btn-outline-primary {{ DIVID.ATTR_V2_RESTORE_LINK_CLASS }}"
title="Restore this value">
Restore
</a>
@@ -56,21 +54,21 @@ Compact history display that loads into attribute cards
<!-- Show More/Less Toggle -->
{% if history_records|length > 3 %}
- <div class="attr-v2-history-toggle mt-2">
+ <div class="{{ DIVID.ATTR_V2_HISTORY_TOGGLE_CLASS }} mt-2">
<button type="button"
class="btn btn-sm btn-link p-0"
data-toggle="collapse"
- data-target="#{{ attr_context|history_toggle_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>
+ data-target="#{{ attr_item_context|history_toggle_id:attribute.id }}"
+ onclick="$(this).find('.show-more-history, .show-less-history').toggle();">
+ <small class="show-more-history">Show {{ history_records|length|add:'-3' }} more...</small>
+ <small class="show-less-history" style="display: none;">Show less</small>
</button>
</div>
{% endif %}
</div>
{% else %}
<!-- No History -->
- <div class="attr-v2-history-empty">
+ <div class="{{ DIVID.ATTR_V2_HISTORY_EMPTY_CLASS }}">
<small class="text-muted">No previous values recorded.</small>
</div>
{% endif %}
diff --git a/src/hi/apps/attribute/templates/attribute/components/edit_content_body.html b/src/hi/apps/attribute/templates/attribute/components/edit_content_body.html
index e22ca74b..fc2b4f1a 100644
--- a/src/hi/apps/attribute/templates/attribute/components/edit_content_body.html
+++ b/src/hi/apps/attribute/templates/attribute/components/edit_content_body.html
@@ -5,89 +5,84 @@ Contains the main content area - used by both initial load and antinode updates
Includes: owner info (when provided), action bar, and scrollable content
This template works generically for Entity, Location, and future attribute-owning models
-by using the AttributeEditContext pattern.
+by using the AttributeItemEditContext pattern.
{% endcomment %}
<!-- Sticky Panel: Owner Info + Action Bar (always visible) -->
-<div class="attr-v2-sticky-panel">
+<div class="{{ DIVID.ATTR_V2_STICKY_PANEL_CLASS }}">
<!-- Basic Owner Information (minimal) - only if owner_form provided -->
{% if owner_form %}
+ {% if owner_form.non_field_errors %}
+ <div class="attr-v2-non-field-errors">
+ {% for err in owner_form.non_field_errors %}
+ <div class="attr-v2-error-item">{{ err }}</div>
+ {% endfor %}
+ </div>
+ {% endif %}
+
<div class="attr-v2-entity-info">
{% block basic_info %}
- <div class="attr-v2-basic-info">
+ <div class="{{ DIVID.ATTR_V2_BASIC_INFO_CLASS }}">
{% block owner_fields %}
<!-- Subclasses should override this block to provide owner-specific fields -->
- <div class="row">
- <div class="col-md-12">
- <div class="form-group mb-0">
- <small class="text-muted">Name</small>
- <input type="text"
- id="{{ owner_form.name.id_for_label }}"
- name="{{ owner_form.name.html_name }}"
- value="{{ owner_form.name.value|default:'' }}"
- class="form-control form-control-sm"
- {% if owner_form.name.field.required %}required{% endif %}>
- {% if owner_form.name.errors %}
- <div class="invalid-feedback d-block">
- {{ owner_form.name.errors }}
- </div>
- {% endif %}
- </div>
- </div>
- </div>
{% endblock %}
</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 }}"
+ <div class="{{ DIVID.ATTR_V2_ACTION_BAR_CLASS }}">
+ <div class="{{ DIVID.ATTR_V2_ACTION_BAR_CONTENT_CLASS }}">
+ <!-- Left Side: UPDATE button and vertically stacked message areas -->
+ <div class="attr-v2-action-bar-left">
+ <button id="{{ attr_page_context.update_button_html_id }}"
type="submit"
- class="btn btn-primary"
+ class="btn btn-primary {{ DIVID.ATTR_V2_UPDATE_BTN_CLASS }}"
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 %}
+ <!-- Vertically stacked message areas -->
+ <div class="attr-v2-message-stack">
+ <div id="{{ attr_page_context.dirty_msg_html_id }}"
+ class="{{ DIVID.ATTR_V2_DIRTY_MESSAGE_CLASS }}">
+ </div>
+ <div id="{{ attr_page_context.status_msg_html_id }}"
+ class="{{ DIVID.ATTR_V2_STATUS_MESSAGE_CLASS }}">
+ {% if success_message %}
<span class="text-success">{{ success_message }}</span>
- {% elif error_message %}
+ {% 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>
</div>
-
- <div class="attr-v2-action-buttons">
+ <!-- Right Side: Action buttons -->
+ <div class="{{ DIVID.ATTR_V2_ACTION_BUTTONS_CLASS }}">
{% block additional_actions %}
{% endblock %}
- <label for="{{ DIVID.ATTR_V2_FILE_INPUT }}"
+ {% block file_upload_button %}
+ <label for="{{ attr_item_context.file_input_html_id }}"
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 }}"
+ {% endblock %}
+ {% block add_attribute_button %}
+ <button id="{{ attr_item_context.add_attribute_button_html_id }}"
type="button"
class="btn btn-sm btn-outline-primary"
- onclick="showAddAttribute();">
+ onclick="window.Hi.attr.showAddAttribute('#{{ attr_page_context.container_html_id }}');">
{% icon "plus" size="sm" css_class="hi-icon-left" %}Add Info
</button>
+ {% endblock %}
</div>
</div>
</div>
</div>
<!-- Scrollable Content Area (below sticky panel) -->
-<div id="{{ DIVID.ATTR_V2_SCROLLABLE_CONTENT }}" class="attr-v2-scrollable-content">
+<div id="{{ attr_page_context.scrollable_content_html_id }}"
+ class="{{ DIVID.ATTR_V2_SCROLLABLE_CONTENT_CLASS }}">
<!-- Files Section -->
{% block files_section %}
@@ -96,14 +91,11 @@ by using the AttributeEditContext pattern.
<!-- 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 %}
+ {% include "attribute/components/regular_attribute_list.html" with regular_attributes_formset=regular_attributes_formset %}
{% endblock %}
<!-- Additional Sections -->
{% block additional_sections %}
{% endblock %}
-</div>
\ No newline at end of file
+</div>
diff --git a/src/hi/apps/attribute/templates/attribute/components/file_card.html b/src/hi/apps/attribute/templates/attribute/components/file_card.html
index 57dbd142..9a58c102 100644
--- a/src/hi/apps/attribute/templates/attribute/components/file_card.html
+++ b/src/hi/apps/attribute/templates/attribute/components/file_card.html
@@ -14,7 +14,7 @@ Individual file attribute card with preview, actions, and metadata
<!-- Hidden field for deletion marking -->
<input type="hidden"
- name="delete_file_attribute"
+ name="{{ DIVID.ATTR_V2_DELETE_FILE_ATTR }}"
value=""
data-attribute-id="{{ attribute.id }}">
@@ -65,8 +65,8 @@ Individual file attribute card with preview, actions, and metadata
<!-- File Info -->
<div class="{{ DIVID.ATTR_V2_FILE_INFO_CLASS }}">
<input type="text"
- id="{{ attr_context|file_title_field_name:attribute.id }}"
- name="{{ attr_context|file_title_field_name:attribute.id }}"
+ id="{{ attr_item_context|file_title_field_name:attribute.id }}"
+ name="{{ attr_item_context|file_title_field_name:attribute.id }}"
value="{{ attribute.value }}"
class="{{ DIVID.ATTR_V2_FILE_TITLE_INPUT_CLASS }}"
placeholder="Enter file title"
@@ -85,13 +85,13 @@ Individual file attribute card with preview, actions, and metadata
{% 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 }}')"
+ onclick="markFileForDeletion('{{ attribute.id }}', '#{{ attr_page_context.container_html_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 }}')"
+ onclick="undoFileDeletion('{{ attribute.id }}', '#{{ attr_page_context.container_html_id }}')"
title="Undo deletion"
style="display: none;">
Undo
diff --git a/src/hi/apps/attribute/templates/attribute/components/file_grid.html b/src/hi/apps/attribute/templates/attribute/components/file_grid.html
index 9e6b0d85..6cb210d3 100644
--- a/src/hi/apps/attribute/templates/attribute/components/file_grid.html
+++ b/src/hi/apps/attribute/templates/attribute/components/file_grid.html
@@ -5,8 +5,8 @@ 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">
+ <div id="{{ attr_item_context.file_grid_html_id }}"
+ class="{{ DIVID.ATTR_V2_FILE_GRID_CLASS }}">
{% for attribute in file_attributes %}
{% include "attribute/components/file_card.html" with attribute=attribute %}
{% endfor %}
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.html
index 94748eb4..e89f24e6 100644
--- a/src/hi/apps/attribute/templates/attribute/components/regular_attribute_card.html
+++ b/src/hi/apps/attribute/templates/attribute/components/regular_attribute_card.html
@@ -22,7 +22,7 @@ Individual attribute attribute card with value editing and actions
{% endif %}
<!-- Attribute Header -->
- <div class="attr-v2-attribute-header">
+ <div class="{{ DIVID.ATTR_V2_ATTRIBUTE_HEADER_CLASS }}">
<h6 class="{{ DIVID.ATTR_V2_ATTRIBUTE_NAME_CLASS }}">
{% if attribute_form.instance.pk %}
{{ attribute_form.instance.name }}
@@ -30,10 +30,18 @@ Individual attribute attribute card with value editing and actions
{% icon "plus" size="sm" css_class="hi-icon-left" %}Add New
{% endif %}
</h6>
+
+ {% if attribute_form.non_field_errors %}
+ <div class="attr-v2-non-field-errors">
+ {% for err in attribute_form.non_field_errors %}
+ <div class="attr-v2-error-item">{{ err }}</div>
+ {% endfor %}
+ </div>
+ {% endif %}
- <div class="attr-v2-attribute-actions">
- <!-- Reorder Controls (disabled until Issue #80) -->
- {% if attribute_form.instance.pk %}
+ <div class="{{ DIVID.ATTR_V2_ATTRIBUTE_ACTIONS_CLASS }}">
+ <!-- Reorder Controls (disabled until Issue #80, hidden if allow_reordering is False) -->
+ {% if attribute_form.instance.pk and attribute_form.allow_reordering %}
<button type="button"
class="btn btn-sm btn-outline-secondary"
disabled
@@ -51,10 +59,8 @@ Individual attribute attribute card with value editing and actions
{% endif %}
{% if attribute_form.instance.pk %}
- <a href="{% attr_history_url attr_context attribute_form.instance.pk %}"
- data-async="#{{ attr_context|history_target_id:attribute_form.instance.pk }}"
- data-stay-in-modal="true"
- class="btn btn-sm btn-outline-secondary"
+ <a href="{% attr_history_url attr_item_context attribute_form.instance.pk %}"
+ class="btn btn-sm btn-outline-secondary {{ DIVID.ATTR_V2_HISTORY_LINK_CLASS }}"
title="View history">
{% icon "history" size="sm" %}
</a>
@@ -64,13 +70,13 @@ Individual attribute attribute card with value editing and actions
<button type="button"
class="{{ DIVID.ATTR_V2_DELETE_BTN_CLASS }}"
title="Delete attribute"
- onclick="markAttributeForDeletion('{{ attribute_form.instance.pk }}')">
+ onclick="markAttributeForDeletion('{{ attribute_form.instance.pk }}', '#{{ attr_page_context.container_html_id }}')" >
{% 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 }}')"
+ onclick="undoAttributeDeletion('{{ attribute_form.instance.pk }}', '#{{ attr_page_context.container_html_id }}')"
style="display: none;">
↶ Undo
</button>
@@ -79,7 +85,7 @@ Individual attribute attribute card with value editing and actions
</div>
<!-- Attribute Value -->
- <div class="attr-v2-attribute-value">
+ <div class="{{ DIVID.ATTR_V2_ATTRIBUTE_VALUE_CLASS }}">
{% if attribute_form.instance.pk %}
<!-- Existing attribute - include hidden name field -->
<input type="hidden"
@@ -92,101 +98,43 @@ Individual attribute attribute card with value editing and actions
{{ attribute_form.name.label_tag }}
{{ attribute_form.name }}
{% if attribute_form.name.errors %}
- <div class="invalid-feedback d-block">
- {{ attribute_form.name.errors }}
+ <div class="attr-v2-field-errors">
+ {% for error in attribute_form.name.errors %}
+ <div class="attr-v2-error-text">{{ error }}</div>
+ {% endfor %}
</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>
+ {% if attribute_form.instance.pk %}
+ <!-- Existing attribute - route by value_type -->
+ {% if attribute_form.instance.value_type.is_boolean %}
+ {% include "attribute/components/value_types/attribute_value_boolean.html" %}
+ {% elif attribute_form.instance.value_type.is_enum %}
+ {% include "attribute/components/value_types/attribute_value_enum.html" %}
+ {% elif attribute_form.instance.value_type.is_integer %}
+ {% include "attribute/components/value_types/attribute_value_integer.html" %}
+ {% elif attribute_form.instance.value_type.is_float %}
+ {% include "attribute/components/value_types/attribute_value_float.html" %}
+ {% elif attribute_form.instance.value_type.is_secret %}
+ {% include "attribute/components/value_types/attribute_value_secret.html" %}
+ {% else %}
+ <!-- TEXT and other types use textarea -->
+ <div class="{{ DIVID.ATTR_V2_TEXT_VALUE_CLASS }}">
+ {% include "attribute/components/value_types/attribute_value_text.html" %}
+ </div>
+ {% endif %}
{% 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 %}
+ <!-- New attribute - always use textarea (TEXT behavior) -->
+ <div class="{{ DIVID.ATTR_V2_TEXT_VALUE_CLASS }}">
+ {% include "attribute/components/value_types/attribute_value_text.html" %}
</div>
{% endif %}
<!-- Secret checkbox for new properties -->
{% if not attribute_form.instance.pk %}
- <div class="attr-v2-secret-checkbox">
+ <div class="{{ DIVID.ATTR_V2_SECRET_CHECKBOX_CLASS }}">
<div class="custom-control custom-checkbox">
{{ attribute_form.secret }}
<label class="custom-control-label" for="{{ attribute_form.secret.id_for_label }}">
@@ -199,8 +147,8 @@ Individual attribute attribute card with value editing and actions
<!-- Inline History Target (empty until populated) -->
{% if attribute_form.instance.pk %}
- <div id="{{ attr_context|history_target_id:attribute_form.instance.pk }}"
- class="attr-v2-inline-history">
+ <div id="{{ attr_item_context|history_target_id:attribute_form.instance.pk }}"
+ class="{{ DIVID.ATTR_V2_INLINE_HISTORY_CLASS }}">
</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.html
index 3c8ce5b4..76167771 100644
--- a/src/hi/apps/attribute/templates/attribute/components/regular_attribute_list.html
+++ b/src/hi/apps/attribute/templates/attribute/components/regular_attribute_list.html
@@ -1,11 +1,17 @@
-{% comment %}
-V2 Property List Component
-Displays attribute attributes in a list layout
-{% endcomment %}
-
{% if regular_attributes_formset %}
+{{ regular_attributes_formset.management_form }}
<div class="attr-v2-attribute-section">
- <h6 class="attr-v2-section-title">Properties</h6>
+ {% if title %}
+ <h6 class="attr-v2-section-title">{{ title }}</h6>
+ {% endif %}
+ {% if regular_attributes_formset.non_form_errors %}
+ <div class="attr-v2-formset-errors">
+ {% for err in regular_attributes_formset.non_form_errors %}
+ <div class="attr-v2-error-item">{{ err }}</div>
+ {% endfor %}
+ </div>
+ {% endif %}
+
<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 %}
diff --git a/src/hi/apps/attribute/templates/attribute/components/upload_form.html b/src/hi/apps/attribute/templates/attribute/components/upload_form.html
index a502f3b0..8782ab68 100644
--- a/src/hi/apps/attribute/templates/attribute/components/upload_form.html
+++ b/src/hi/apps/attribute/templates/attribute/components/upload_form.html
@@ -2,12 +2,10 @@
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);">
+ id="{{ attr_item_context.file_input_html_id }}"
+ class="{{ DIVID.ATTR_V2_FILE_INPUT_CLASS }}"
+ name="file_value">
</form>
diff --git a/src/hi/apps/attribute/templates/attribute/components/value_types/attribute_value_boolean.html b/src/hi/apps/attribute/templates/attribute/components/value_types/attribute_value_boolean.html
new file mode 100644
index 00000000..7a9ce6be
--- /dev/null
+++ b/src/hi/apps/attribute/templates/attribute/components/value_types/attribute_value_boolean.html
@@ -0,0 +1,33 @@
+{% comment %}
+Boolean Attribute Value Component
+Renders a checkbox input for boolean attributes
+{% endcomment %}
+
+<div class="attr-v2-boolean-value">
+ <!-- Hidden field with actual string value for form submission -->
+ <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:'False' }}">
+
+ <!-- Checkbox for UI interaction (no name = not submitted) -->
+ <div class="custom-control custom-checkbox">
+ <input type="checkbox"
+ id="{{ attribute_form.value.id_for_label }}"
+ class="custom-control-input attr-v2-boolean-checkbox"
+ data-hidden-field="hidden-{{ attribute_form.value.id_for_label }}"
+ {% if attribute_form.value.value == "True" or attribute_form.value.value == True %}checked{% endif %}
+ {% if attribute_form.instance and not attribute_form.instance.is_editable %}disabled="true"{% endif %}
+ onchange="Hi.attr.updateBooleanHiddenField(this)" />
+ <label class="custom-control-label" for="{{ attribute_form.value.id_for_label }}">
+ {{ attribute_form.instance.name }}
+ </label>
+ </div>
+ {% if attribute_form.value.errors %}
+ <div class="attr-v2-field-errors">
+ {% for error in attribute_form.value.errors %}
+ <div class="attr-v2-error-text">{{ error }}</div>
+ {% endfor %}
+ </div>
+ {% endif %}
+</div>
\ No newline at end of file
diff --git a/src/hi/apps/attribute/templates/attribute/components/value_types/attribute_value_enum.html b/src/hi/apps/attribute/templates/attribute/components/value_types/attribute_value_enum.html
new file mode 100644
index 00000000..55fef597
--- /dev/null
+++ b/src/hi/apps/attribute/templates/attribute/components/value_types/attribute_value_enum.html
@@ -0,0 +1,25 @@
+{% comment %}
+Enum Attribute Value Component
+Renders a select dropdown for enum attributes using the attribute's choices
+{% endcomment %}
+
+<div class="attr-v2-enum-value">
+ <select id="{{ attribute_form.value.id_for_label }}"
+ name="{{ attribute_form.value.html_name }}"
+ class="form-control"
+ {% if attribute_form.instance and not attribute_form.instance.is_editable %}disabled="true"{% endif %}>
+ {% for choice_value, choice_label in attribute_form.instance.choices %}
+ <option value="{{ choice_value }}"
+ {% if choice_value == attribute_form.value.value %}selected{% endif %}>
+ {{ choice_label }}
+ </option>
+ {% endfor %}
+ </select>
+ {% if attribute_form.value.errors %}
+ <div class="attr-v2-field-errors">
+ {% for error in attribute_form.value.errors %}
+ <div class="attr-v2-error-text">{{ error }}</div>
+ {% endfor %}
+ </div>
+ {% endif %}
+</div>
\ No newline at end of file
diff --git a/src/hi/apps/attribute/templates/attribute/components/value_types/attribute_value_float.html b/src/hi/apps/attribute/templates/attribute/components/value_types/attribute_value_float.html
new file mode 100644
index 00000000..a98a6562
--- /dev/null
+++ b/src/hi/apps/attribute/templates/attribute/components/value_types/attribute_value_float.html
@@ -0,0 +1,21 @@
+{% comment %}
+Float Attribute Value Component
+Renders a number input for float attributes
+{% endcomment %}
+
+<div class="attr-v2-float-value">
+ <input type="number"
+ id="{{ attribute_form.value.id_for_label }}"
+ name="{{ attribute_form.value.html_name }}"
+ class="form-control"
+ value="{{ attribute_form.value.value|default_if_none:'' }}"
+ step="any"
+ {% if attribute_form.instance and not attribute_form.instance.is_editable %}disabled="true"{% endif %} />
+ {% if attribute_form.value.errors %}
+ <div class="attr-v2-field-errors">
+ {% for error in attribute_form.value.errors %}
+ <div class="attr-v2-error-text">{{ error }}</div>
+ {% endfor %}
+ </div>
+ {% endif %}
+</div>
\ No newline at end of file
diff --git a/src/hi/apps/attribute/templates/attribute/components/value_types/attribute_value_integer.html b/src/hi/apps/attribute/templates/attribute/components/value_types/attribute_value_integer.html
new file mode 100644
index 00000000..1adb5ab0
--- /dev/null
+++ b/src/hi/apps/attribute/templates/attribute/components/value_types/attribute_value_integer.html
@@ -0,0 +1,21 @@
+{% comment %}
+Integer Attribute Value Component
+Renders a number input for integer attributes
+{% endcomment %}
+
+<div class="attr-v2-integer-value">
+ <input type="number"
+ id="{{ attribute_form.value.id_for_label }}"
+ name="{{ attribute_form.value.html_name }}"
+ class="form-control"
+ value="{{ attribute_form.value.value|default_if_none:'' }}"
+ step="1"
+ {% if attribute_form.instance and not attribute_form.instance.is_editable %}disabled="true"{% endif %} />
+ {% if attribute_form.value.errors %}
+ <div class="attr-v2-field-errors">
+ {% for error in attribute_form.value.errors %}
+ <div class="attr-v2-error-text">{{ error }}</div>
+ {% endfor %}
+ </div>
+ {% endif %}
+</div>
\ No newline at end of file
diff --git a/src/hi/apps/attribute/templates/attribute/components/value_types/attribute_value_secret.html b/src/hi/apps/attribute/templates/attribute/components/value_types/attribute_value_secret.html
new file mode 100644
index 00000000..d5c2b4e1
--- /dev/null
+++ b/src/hi/apps/attribute/templates/attribute/components/value_types/attribute_value_secret.html
@@ -0,0 +1,44 @@
+{% load icons %}
+{% comment %}
+Secret Attribute Value Component
+Renders a password input with show/hide toggle for existing secret attributes
+
+UI Interactions:
+
+When adding a new secret attribute, it looks exactly the same as adding a
+text attribute. There is a checkbox they use to indicate if it is secret.
+Secrets are limited to a single line of text, which is enforced on form
+submission. The new attribute value textarea allows any text, so it is a
+form validation error for them to add multi-line text and choose the "Mark
+as Secret" box. Once created, a SECRET is a text input, not a text area
+and there is no ability to change a secret into a non-secret or vice
+versa. Thus, there is no checkbox on existing attributes to control if it
+is a secret: that only appears on the new attribute form.
+{% endcomment %}
+
+<div class="attr-v2-secret-field">
+ <div class="{{ DIVID.ATTR_V2_SECRET_INPUT_WRAPPER_CLASS }}">
+ <!-- Secret field as password input -->
+ <input type="password"
+ id="{{ attribute_form.value.id_for_label }}"
+ name="{{ attribute_form.value.html_name }}"
+ class="form-control {{ DIVID.ATTR_V2_SECRET_INPUT_CLASS }}"
+ value="{{ attribute_form.value.value|default_if_none:'' }}"
+ readonly="readonly"
+ {% if attribute_form.instance and not attribute_form.instance.is_editable %}disabled="true"{% endif %} />
+ <button type="button"
+ class="btn btn-sm btn-outline-secondary attr-v2-secret-toggle"
+ onclick="Hi.attr.toggleSecretField(this)"
+ title="Show value">
+ <span class="{{ DIVID.ATTR_V2_ICON_SHOW_CLASS }}">{% icon "eye" size="sm" %}</span>
+ <span class="{{ DIVID.ATTR_V2_ICON_HIDE_CLASS }}" style="display: none;">{% icon "eye-off" size="sm" %}</span>
+ </button>
+ </div>
+ {% if attribute_form.value.errors %}
+ <div class="attr-v2-field-errors">
+ {% for error in attribute_form.value.errors %}
+ <div class="attr-v2-error-text">{{ error }}</div>
+ {% endfor %}
+ </div>
+ {% endif %}
+</div>
diff --git a/src/hi/apps/attribute/templates/attribute/components/value_types/attribute_value_text.html b/src/hi/apps/attribute/templates/attribute/components/value_types/attribute_value_text.html
new file mode 100644
index 00000000..17a1c82c
--- /dev/null
+++ b/src/hi/apps/attribute/templates/attribute/components/value_types/attribute_value_text.html
@@ -0,0 +1,50 @@
+{% load common_template_helpers %}
+{% comment %}
+Text Attribute Value Component
+Renders textarea with special handling (hidden input + display textarea) for text attributes
+This component handles the auto-sizing and expand/collapse functionality
+{% endcomment %}
+
+<!-- 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="{{ DIVID.ATTR_V2_TEXT_VALUE_WRAPPER_CLASS }}"
+ 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 {{ DIVID.ATTR_V2_TEXTAREA_CLASS }} {{ DIVID.ATTR_V2_DISPLAY_FIELD_CLASS }}"
+ 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="attr-v2-field-errors">
+ {% for error in attribute_form.value.errors %}
+ <div class="attr-v2-error-text">{{ error }}</div>
+ {% endfor %}
+ </div>
+ {% endif %}
+ {% if overflows > 0 %}
+ <div class="{{ DIVID.ATTR_V2_EXPAND_CONTROLS_CLASS }}" style="display: block;">
+ <button type="button" class="btn btn-sm btn-link" onclick="Hi.attr.toggleExpandedView(this)">
+ <span class="{{ DIVID.ATTR_V2_SHOW_MORE_TEXT_CLASS }}">Show more...</span>
+ <span class="{{ DIVID.ATTR_V2_SHOW_LESS_TEXT_CLASS }}" style="display: none;">Show less</span>
+ </button>
+ </div>
+ {% endif %}
+</div>
+{% endwith %}
+{% endwith %}
+{% endwith %}
+{% endwith %}
diff --git a/src/hi/apps/attribute/templatetags/attribute_extras.py b/src/hi/apps/attribute/templatetags/attribute_extras.py
index bcddd3f0..2493b147 100644
--- a/src/hi/apps/attribute/templatetags/attribute_extras.py
+++ b/src/hi/apps/attribute/templatetags/attribute_extras.py
@@ -52,88 +52,88 @@ def attribute_preview(value, max_chars=60):
@register.filter
-def file_title_field_name(attr_context, attribute_id):
+def file_title_field_name(attr_item_context, attribute_id):
"""
Generate the form field name for file title editing.
- Usage in template: {{ attr_context|file_title_field_name:attribute.id }}
+ Usage in template: {{ attr_item_context|file_title_field_name:attribute.id }}
Args:
- attr_context: AttributeEditContext instance
+ attr_item_context: AttributeItemEditContext instance
attribute_id: The attribute's ID
Returns:
str: Form field name like 'file_title_1_23'
"""
- return attr_context.file_title_field_name(attribute_id)
+ return attr_item_context.file_title_field_name(attribute_id)
@register.filter
-def history_target_id(attr_context, attribute_id):
+def history_target_id(attr_item_context, attribute_id):
"""
Generate the DOM ID for attribute history container.
- Usage in template: {{ attr_context|history_target_id:attribute.id }}
+ Usage in template: {{ attr_item_context|history_target_id:attribute.id }}
Args:
- attr_context: AttributeEditContext instance
+ attr_item_context: AttributeItemEditContext instance
attribute_id: The attribute's ID
Returns:
str: DOM ID like 'hi-entity-attr-history-1-23'
"""
- return attr_context.history_target_id(attribute_id)
+ return attr_item_context.history_target_id(attribute_id)
@register.filter
-def history_toggle_id(attr_context, attribute_id):
+def history_toggle_id(attr_item_context, attribute_id):
"""
Generate the DOM ID for history toggle/collapse target.
- Usage in template: {{ attr_context|history_toggle_id:attribute.id }}
+ Usage in template: {{ attr_item_context|history_toggle_id:attribute.id }}
Args:
- attr_context: AttributeEditContext instance
+ attr_item_context: AttributeItemEditContext instance
attribute_id: The attribute's ID
Returns:
str: DOM ID like 'history-extra-1-23'
"""
- return attr_context.history_toggle_id(attribute_id)
+ return attr_item_context.history_toggle_id(attribute_id)
@register.simple_tag
-def attr_history_url(attr_context, attribute_id):
+def attr_history_url(attr_item_context, attribute_id):
"""
Generate URL for attribute history view with correct parameter names.
- Usage in template: {% attr_history_url attr_context attribute.id %}
+ Usage in template: {% attr_history_url attr_item_context attribute.id %}
Args:
- attr_context: AttributeEditContext instance
+ attr_item_context: AttributeItemEditContext instance
attribute_id: The attribute's ID
Returns:
str: URL for history view
"""
from django.urls import reverse
- url_name = attr_context.history_url_name
+ url_name = attr_item_context.history_url_name
params = {
- attr_context.owner_id_param_name: attr_context.owner_id,
+ attr_item_context.owner_id_param_name: attr_item_context.owner_id,
'attribute_id': attribute_id
}
return reverse(url_name, kwargs=params)
@register.simple_tag
-def attr_restore_url(attr_context, attribute_id, history_id):
+def attr_restore_url(attr_item_context, attribute_id, history_id):
"""
Generate URL for attribute restore view with correct parameter names.
- Usage in template: {% attr_restore_url attr_context attribute.id history_record.pk %}
+ Usage in template: {% attr_restore_url attr_item_context attribute.id history_record.pk %}
Args:
- attr_context: AttributeEditContext instance
+ attr_item_context: AttributeItemEditContext instance
attribute_id: The attribute's ID
history_id: The history record's ID
@@ -141,9 +141,9 @@ def attr_restore_url(attr_context, attribute_id, history_id):
str: URL for restore view
"""
from django.urls import reverse
- url_name = attr_context.restore_url_name
+ url_name = attr_item_context.restore_url_name
params = {
- attr_context.owner_id_param_name: attr_context.owner_id,
+ attr_item_context.owner_id_param_name: attr_item_context.owner_id,
'attribute_id': attribute_id,
'history_id': history_id
}
diff --git a/src/hi/apps/attribute/tests/attribute_framework_test_base.py b/src/hi/apps/attribute/tests/attribute_framework_test_base.py
new file mode 100644
index 00000000..4e75abb4
--- /dev/null
+++ b/src/hi/apps/attribute/tests/attribute_framework_test_base.py
@@ -0,0 +1,702 @@
+"""
+Abstract base test classes for attribute editing framework components.
+
+These abstract test classes define comprehensive test methods for the core
+attribute framework components. Module-specific tests inherit from these
+bases and provide concrete implementations to exercise the framework.
+
+Following project testing guidelines:
+- No mocked objects, use real database operations
+- Focus on high-value business logic and integration points
+- Use synthetic data pattern for test data generation
+- Test meaningful edge cases and error handling scenarios
+"""
+import logging
+from abc import ABC, abstractmethod
+from typing import Any, Dict
+
+from django.core.files.uploadedfile import SimpleUploadedFile
+from django.test import RequestFactory
+from django.http import QueryDict
+
+from hi.testing.base_test_case import MockRequest, MockSession
+from hi.apps.attribute.edit_context import AttributeItemEditContext
+from hi.apps.attribute.edit_form_handler import AttributeEditFormHandler
+from hi.apps.attribute.edit_response_renderer import AttributeEditResponseRenderer
+from hi.apps.attribute.edit_template_context_builder import AttributeEditTemplateContextBuilder
+from hi.apps.attribute.models import AttributeModel
+from hi.apps.attribute.enums import AttributeType, AttributeValueType
+
+logging.disable(logging.CRITICAL)
+
+
+class AttributeFrameworkTestMixin(ABC):
+ """
+ Mixin providing common setup and abstract methods for attribute framework testing.
+
+ Subclasses must implement methods to create concrete instances of:
+ - Owner models (Entity, Location, Subsystem)
+ - AttributeModel subclasses
+ - AttributeItemEditContext subclasses
+ - Test data scenarios
+ """
+
+ def setUp(self):
+ super().setUp()
+ self.factory = RequestFactory()
+
+ @abstractmethod
+ def create_owner_instance(self, **kwargs):
+ """Create a concrete owner instance (Entity, Location, Subsystem)."""
+ pass
+
+ @abstractmethod
+ def create_attribute_instance(self, owner, **kwargs) -> AttributeModel:
+ """Create a concrete AttributeModel subclass instance."""
+ pass
+
+ @abstractmethod
+ def create_item_edit_context(self, owner) -> AttributeItemEditContext:
+ """Create a concrete AttributeItemEditContext subclass."""
+ pass
+
+ @abstractmethod
+ def create_valid_form_data(self, owner, **overrides) -> Dict[str, Any]:
+ """Create valid form data for the owner and its attributes."""
+ pass
+
+ @abstractmethod
+ def create_invalid_form_data(self, owner) -> Dict[str, Any]:
+ """Create invalid form data to test error handling."""
+ pass
+
+
+class AttributeEditFormHandlerTestMixin(AttributeFrameworkTestMixin, ABC):
+ """
+ Abstract base for testing AttributeEditFormHandler functionality.
+
+ Tests form creation, validation, saving, and file operations.
+ Focuses on business logic integration points and error handling.
+ """
+
+ def test_create_edit_form_data_basic_workflow(self):
+ """Test basic form data creation - core framework functionality."""
+ owner = self.create_owner_instance(name="Test Owner")
+ context = self.create_item_edit_context(owner)
+ handler = AttributeEditFormHandler()
+
+ # Test unbound forms (GET request scenario)
+ form_data = handler.create_edit_form_data(
+ attr_item_context=context
+ )
+
+ # Should create proper form data structure
+ self.assertIsNotNone(form_data.regular_attributes_formset)
+ self.assertIsNotNone(form_data.file_attributes)
+
+ # Owner form may be None for some contexts (like Subsystem)
+ if context.create_owner_form():
+ self.assertIsNotNone(form_data.owner_form)
+
+ def test_create_edit_form_data_with_post_data(self):
+ """Test form data creation with POST data - bound form scenario."""
+ owner = self.create_owner_instance(name="Test Owner")
+ context = self.create_item_edit_context(owner)
+ handler = AttributeEditFormHandler()
+
+ # Create valid POST data
+ post_data = self.create_valid_form_data(owner, name="Updated Owner")
+
+ form_data = handler.create_edit_form_data(
+ attr_item_context=context,
+ form_data=post_data
+ )
+
+ # Forms should be bound with data
+ self.assertIsNotNone(form_data.regular_attributes_formset)
+ self.assertTrue(hasattr(form_data.regular_attributes_formset, 'data'))
+
+ def test_validate_forms_with_valid_data_success(self):
+ """Test form validation with valid data - success path validation."""
+ owner = self.create_owner_instance(name="Test Owner")
+ # Create some attributes to validate
+ self.create_attribute_instance(
+ owner=owner,
+ name="test_attr",
+ value="test_value",
+ attribute_type_str=str(AttributeType.CUSTOM)
+ )
+
+ context = self.create_item_edit_context(owner)
+ handler = AttributeEditFormHandler()
+
+ # Create valid form data
+ post_data = self.create_valid_form_data(owner, name="Valid Updated Name")
+ form_data = handler.create_edit_form_data(
+ attr_item_context=context,
+ form_data=post_data
+ )
+
+ # Validation should succeed
+ is_valid = handler.validate_forms(edit_form_data=form_data)
+ self.assertTrue(is_valid)
+
+ def test_validate_forms_with_invalid_data_failure(self):
+ """Test form validation with invalid data - error path validation."""
+ owner = self.create_owner_instance(name="Test Owner")
+ context = self.create_item_edit_context(owner)
+ handler = AttributeEditFormHandler()
+
+ # Create invalid form data
+ invalid_data = self.create_invalid_form_data(owner)
+ form_data = handler.create_edit_form_data(
+ attr_item_context=context,
+ form_data=invalid_data
+ )
+
+ # Validation should fail
+ is_valid = handler.validate_forms(edit_form_data=form_data)
+ self.assertFalse(is_valid)
+
+ def test_save_forms_database_integration(self):
+ """Test form saving creates/updates database records - database integration."""
+ owner = self.create_owner_instance(name="Original Name")
+ # Create an existing attribute to update
+ self.create_attribute_instance(
+ owner=owner,
+ name="existing_attr",
+ value="original_value"
+ )
+
+ context = self.create_item_edit_context(owner)
+ handler = AttributeEditFormHandler()
+
+ # Check if this context supports owner form editing
+ temp_form_data = handler.create_edit_form_data(attr_item_context=context)
+
+ # Create form data with updates - let each module handle its own update format
+ form_data_kwargs = {}
+ if temp_form_data.owner_form is not None:
+ form_data_kwargs["name"] = "Updated Owner Name"
+
+ post_data = self.create_valid_form_data(owner, **form_data_kwargs)
+
+ form_data = handler.create_edit_form_data(
+ attr_item_context=context,
+ form_data=post_data
+ )
+
+ # Create mock request for save operation
+ request = MockRequest()
+ # Create QueryDict from post_data to simulate Django POST behavior
+ query_dict = QueryDict(mutable=True)
+ for key, value in post_data.items():
+ query_dict[key] = value
+ request.POST = query_dict
+ request.session = MockSession()
+
+ # Save should succeed with valid data
+ self.assertTrue(handler.validate_forms(edit_form_data=form_data))
+ handler.save_forms(
+ attr_item_context=context,
+ edit_form_data=form_data,
+ request=request
+ )
+
+ # Verify database changes
+ owner.refresh_from_db()
+
+ # Only test owner changes if owner form exists and we sent owner data
+ if temp_form_data.owner_form is not None:
+ self.assertEqual(owner.name, "Updated Owner Name")
+
+ # The main point of this test is that forms validate and save without errors
+ # Specific attribute change testing is left to module-specific tests
+
+ def test_file_deletion_workflow(self):
+ """Test file deletion processing - file operation integration."""
+ owner = self.create_owner_instance(name="Test Owner")
+
+ # Create file attribute if supported by this context
+ context = self.create_item_edit_context(owner)
+ if not context.attribute_upload_form_class:
+ self.skipTest("File uploads not supported by this context")
+
+ file_attr = self.create_attribute_instance(
+ owner=owner,
+ name="test_file",
+ value="Test File Title",
+ value_type_str=str(AttributeValueType.FILE)
+ )
+
+ handler = AttributeEditFormHandler()
+
+ # Create request with file deletion data
+ request = MockRequest()
+ # Create QueryDict to simulate Django POST behavior
+ from hi.constants import DIVID
+ query_dict = QueryDict(mutable=True)
+ query_dict.setlist(DIVID['ATTR_V2_DELETE_FILE_ATTR'], [str(file_attr.id)])
+ request.POST = query_dict
+ request.session = MockSession()
+
+ # Process file deletions
+ initial_count = context.attribute_model_subclass.objects.count()
+ handler.process_file_deletions(
+ attr_item_context=context,
+ request=request
+ )
+
+ # File attribute should be deleted
+ final_count = context.attribute_model_subclass.objects.count()
+ self.assertEqual(final_count, initial_count - 1)
+ self.assertFalse(
+ context.attribute_model_subclass.objects.filter(id=file_attr.id).exists()
+ )
+
+ def test_file_title_update_workflow(self):
+ """Test file title updates - file metadata management."""
+ owner = self.create_owner_instance(name="Test Owner")
+
+ context = self.create_item_edit_context(owner)
+ if not context.attribute_upload_form_class:
+ self.skipTest("File uploads not supported by this context")
+
+ file_attr = self.create_attribute_instance(
+ owner=owner,
+ name="document",
+ value="Original Title",
+ value_type_str=str(AttributeValueType.FILE)
+ )
+
+ handler = AttributeEditFormHandler()
+
+ # Create request with file title update
+ field_name = context.file_title_field_name(file_attr.id)
+ request = MockRequest()
+ # Create QueryDict to simulate Django POST behavior
+ query_dict = QueryDict(mutable=True)
+ query_dict[field_name] = "Updated File Title"
+ request.POST = query_dict
+ request.session = MockSession()
+
+ handler.process_file_title_updates(
+ attr_item_context=context,
+ request=request
+ )
+
+ # File title should be updated
+ file_attr.refresh_from_db()
+ self.assertEqual(file_attr.value, "Updated File Title")
+
+ def test_concurrent_modification_handling(self):
+ """Test handling of concurrent modifications - data consistency."""
+ owner = self.create_owner_instance(name="Original")
+ attr = self.create_attribute_instance(owner=owner, name="test", value="original")
+
+ context = self.create_item_edit_context(owner)
+ handler = AttributeEditFormHandler()
+
+ # Create form data
+ post_data = self.create_valid_form_data(owner, name="User Update")
+ form_data = handler.create_edit_form_data(
+ attr_item_context=context,
+ form_data=post_data
+ )
+
+ # Simulate external modification
+ attr.value = "External Update"
+ attr.save()
+
+ # Form save should still succeed (last write wins)
+ request = MockRequest()
+ # Create QueryDict to simulate Django POST behavior
+ query_dict = QueryDict(mutable=True)
+ for key, value in post_data.items():
+ query_dict[key] = value
+ request.POST = query_dict
+ request.session = MockSession()
+
+ if handler.validate_forms(edit_form_data=form_data):
+ handler.save_forms(
+ attr_item_context=context,
+ edit_form_data=form_data,
+ request=request
+ )
+
+ # Should handle gracefully without exceptions
+ self.assertTrue(True) # Test passes if no exception raised
+
+
+class AttributeEditResponseRendererTestMixin(AttributeFrameworkTestMixin, ABC):
+ """
+ Abstract base for testing AttributeEditResponseRenderer functionality.
+
+ Tests response generation, template context building, and success/error handling.
+ Focuses on HTMX integration and antinode response patterns.
+ """
+
+ def test_render_form_success_response_structure(self):
+ """Test success response structure - antinode response format."""
+ owner = self.create_owner_instance(name="Test Owner")
+ context = self.create_item_edit_context(owner)
+ renderer = AttributeEditResponseRenderer()
+
+ request = self.factory.post('/test/')
+ request.session = MockSession()
+
+ response = renderer.render_form_success_response(
+ attr_item_context=context,
+ request=request,
+ message=None # Use default message
+ )
+
+ # Should return JSON response for HTMX
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(response['Content-Type'], 'application/json')
+
+ # Response should contain antinode structure
+ import json
+ data = json.loads(response.content)
+ self.assertIsInstance(data, dict)
+ self.assertTrue(len(data) > 0)
+
+ def test_render_form_error_response_with_validation_errors(self):
+ """Test error response with form validation errors - error handling."""
+ owner = self.create_owner_instance(name="Test Owner")
+ context = self.create_item_edit_context(owner)
+ renderer = AttributeEditResponseRenderer()
+ handler = AttributeEditFormHandler()
+
+ # Create invalid form data
+ invalid_data = self.create_invalid_form_data(owner)
+ form_data = handler.create_edit_form_data(
+ attr_item_context=context,
+ form_data=invalid_data
+ )
+
+ # Ensure forms have validation errors
+ is_valid = handler.validate_forms(edit_form_data=form_data)
+ self.assertFalse(is_valid)
+
+ request = self.factory.post('/test/')
+ request.session = MockSession()
+
+ response = renderer.render_form_error_response(
+ attr_item_context=context,
+ edit_form_data=form_data,
+ request=request
+ )
+
+ # Should return error response
+ self.assertEqual(response.status_code, 400)
+ self.assertEqual(response['Content-Type'], 'application/json')
+
+ def test_render_history_response_data_structure(self):
+ """Test history response rendering - history display functionality."""
+ owner = self.create_owner_instance(name="Test Owner")
+ attribute = self.create_attribute_instance(
+ owner=owner,
+ name="test_attr",
+ value="current_value"
+ )
+ context = self.create_item_edit_context(owner)
+ renderer = AttributeEditResponseRenderer()
+
+ request = self.factory.get('/test/')
+ request.session = MockSession()
+
+ # Create mock history records
+ history_records = []
+
+ response = renderer.render_history_response(
+ attr_item_context=context,
+ attribute=attribute,
+ history_records=history_records,
+ request=request
+ )
+
+ # Should return HTML response for history content
+ self.assertEqual(response.status_code, 200)
+ # Content type depends on implementation - could be HTML or JSON
+
+ def test_render_restore_success_response_workflow(self):
+ """Test attribute restoration success response - restore functionality."""
+ owner = self.create_owner_instance(name="Test Owner")
+ context = self.create_item_edit_context(owner)
+ renderer = AttributeEditResponseRenderer()
+
+ request = self.factory.post('/test/')
+ request.session = MockSession()
+
+ response = renderer.render_restore_success_response(
+ attr_item_context=context,
+ request=request
+ )
+
+ # Should return success response
+ self.assertEqual(response.status_code, 200)
+
+ def test_render_restore_error_response_handling(self):
+ """Test attribute restoration error response - error recovery."""
+ renderer = AttributeEditResponseRenderer()
+
+ error_message = "Test error during restore"
+ response = renderer.render_restore_error_response(error_message)
+
+ # Should return error response with message
+ self.assertEqual(response.status_code, 400)
+
+
+class AttributeEditTemplateContextBuilderTestMixin(AttributeFrameworkTestMixin, ABC):
+ """
+ Abstract base for testing AttributeEditTemplateContextBuilder functionality.
+
+ Tests template context assembly for both single and multi-edit scenarios.
+ Focuses on proper context structure and data flow to templates.
+ """
+
+ def test_build_initial_template_context_structure(self):
+ """Test initial template context building - context assembly."""
+ owner = self.create_owner_instance(name="Test Owner")
+ context = self.create_item_edit_context(owner)
+ builder = AttributeEditTemplateContextBuilder()
+
+ template_context = builder.build_initial_template_context(
+ attr_item_context=context
+ )
+
+ # Should contain all required context keys
+ self.assertIn('owner_form', template_context)
+ self.assertIn('file_attributes', template_context)
+ self.assertIn('regular_attributes_formset', template_context)
+ self.assertIn('attr_item_context', template_context)
+
+ # Should contain owner-specific context
+ self.assertIn(context.owner_type, template_context)
+ self.assertIs(template_context[context.owner_type], owner)
+
+ def test_build_response_template_context_with_success_message(self):
+ """Test response context with success message - success state handling."""
+ owner = self.create_owner_instance(name="Test Owner")
+ context = self.create_item_edit_context(owner)
+ builder = AttributeEditTemplateContextBuilder()
+ handler = AttributeEditFormHandler()
+
+ # Create valid form data
+ form_data = handler.create_edit_form_data(attr_item_context=context)
+
+ template_context = builder.build_response_template_context(
+ attr_item_context=context,
+ edit_form_data=form_data,
+ success_message="Operation completed successfully"
+ )
+
+ # Should contain success context
+ self.assertIn('success_message', template_context)
+ self.assertEqual(template_context['success_message'], "Operation completed successfully")
+ self.assertFalse(template_context.get('has_errors', True))
+
+ def test_build_response_template_context_with_form_errors(self):
+ """Test response context with form errors - error state handling."""
+ owner = self.create_owner_instance(name="Test Owner")
+ context = self.create_item_edit_context(owner)
+ builder = AttributeEditTemplateContextBuilder()
+ handler = AttributeEditFormHandler()
+
+ # Create invalid form data to trigger errors
+ invalid_data = self.create_invalid_form_data(owner)
+ form_data = handler.create_edit_form_data(
+ attr_item_context=context,
+ form_data=invalid_data
+ )
+
+ # Trigger validation to create errors
+ handler.validate_forms(edit_form_data=form_data)
+
+ template_context = builder.build_response_template_context(
+ attr_item_context=context,
+ edit_form_data=form_data,
+ error_message="Validation failed",
+ has_errors=True
+ )
+
+ # Should contain error context
+ self.assertIn('error_message', template_context)
+ self.assertEqual(template_context['error_message'], "Validation failed")
+ self.assertTrue(template_context.get('has_errors', False))
+ self.assertIn('non_form_errors', template_context)
+
+ def test_template_context_owner_integration(self):
+ """Test template context includes proper owner integration - owner context."""
+ owner = self.create_owner_instance(name="Integration Test Owner")
+ context = self.create_item_edit_context(owner)
+ builder = AttributeEditTemplateContextBuilder()
+
+ template_context = builder.build_initial_template_context(
+ attr_item_context=context
+ )
+
+ # Should provide multiple ways to access owner in templates
+ self.assertIn('owner', template_context)
+ self.assertIs(template_context['owner'], owner)
+
+ # Should provide owner-type specific access
+ self.assertIn(context.owner_type, template_context)
+ self.assertIs(template_context[context.owner_type], owner)
+
+ # Should include context object itself
+ self.assertIn('attr_item_context', template_context)
+ self.assertIs(template_context['attr_item_context'], context)
+
+
+class AttributeViewMixinTestMixin(AttributeFrameworkTestMixin, ABC):
+ """
+ Abstract base for testing AttributeEditViewMixin functionality.
+
+ Note: Cannot test mixins directly due to abstract nature.
+ This provides test methods that concrete implementations should call.
+ Tests view-level integration and HTTP request/response handling.
+ """
+
+ @abstractmethod
+ def create_test_view_instance(self):
+ """Create a concrete view instance that uses AttributeEditViewMixin."""
+ pass
+
+ def test_post_attribute_form_success_workflow(self):
+ """Test successful form POST handling - view integration success path."""
+ owner = self.create_owner_instance(name="Test Owner")
+ context = self.create_item_edit_context(owner)
+ view = self.create_test_view_instance()
+
+ # Create valid POST data
+ post_data = self.create_valid_form_data(owner, name="Updated via View")
+ request = self.factory.post('/test/', post_data)
+ request.session = MockSession()
+
+ response = view.post_attribute_form(
+ request=request,
+ attr_item_context=context
+ )
+
+ # Should return success response
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(response['Content-Type'], 'application/json')
+
+ def test_post_attribute_form_validation_failure(self):
+ """Test form POST with validation errors - view integration error path."""
+ owner = self.create_owner_instance(name="Test Owner")
+ context = self.create_item_edit_context(owner)
+ view = self.create_test_view_instance()
+
+ # Create invalid POST data
+ invalid_data = self.create_invalid_form_data(owner)
+ request = self.factory.post('/test/', invalid_data)
+ request.session = MockSession()
+
+ response = view.post_attribute_form(
+ request=request,
+ attr_item_context=context
+ )
+
+ # Should return error response
+ self.assertEqual(response.status_code, 400)
+
+ def test_create_initial_template_context_view_integration(self):
+ """Test initial template context creation via view - view context integration."""
+ owner = self.create_owner_instance(name="Test Owner")
+ context = self.create_item_edit_context(owner)
+ view = self.create_test_view_instance()
+
+ template_context = view.create_initial_template_context(
+ attr_item_context=context
+ )
+
+ # Should return proper template context structure
+ self.assertIsInstance(template_context, dict)
+ self.assertIn('attr_item_context', template_context)
+ self.assertIs(template_context['attr_item_context'], context)
+
+ def test_post_upload_file_operation_workflow(self):
+ """Test file upload POST handling - file operation view integration."""
+ owner = self.create_owner_instance(name="Test Owner")
+ context = self.create_item_edit_context(owner)
+
+ if not context.attribute_upload_form_class:
+ self.skipTest("File uploads not supported by this context")
+
+ view = self.create_test_view_instance()
+
+ # Create file upload request
+ test_file = SimpleUploadedFile(
+ "test.txt",
+ b"test file content",
+ content_type="text/plain"
+ )
+
+ request = self.factory.post('/test/', {
+ 'file_value': test_file,
+ 'name': 'uploaded_document',
+ 'value': 'Test Document'
+ })
+ request.session = MockSession()
+
+ response = view.post_upload(
+ request=request,
+ attr_item_context=context
+ )
+
+ # Should handle file upload
+ self.assertIn(response.status_code, [200, 400]) # Success or validation error
+
+ def test_get_history_display_workflow(self):
+ """Test attribute history display - history view integration."""
+ owner = self.create_owner_instance(name="Test Owner")
+ attribute = self.create_attribute_instance(
+ owner=owner,
+ name="history_test",
+ value="current_value"
+ )
+ context = self.create_item_edit_context(owner)
+ view = self.create_test_view_instance()
+
+ request = self.factory.get('/test/')
+ request.session = MockSession()
+
+ response = view.get_history(
+ request=request,
+ attribute=attribute,
+ attr_item_context=context
+ )
+
+ # Should return history response
+ self.assertEqual(response.status_code, 200)
+
+ def test_post_restore_attribute_workflow(self):
+ """Test attribute restoration - restore view integration."""
+ owner = self.create_owner_instance(name="Test Owner")
+ attribute = self.create_attribute_instance(
+ owner=owner,
+ name="restore_test",
+ value="current_value"
+ )
+ context = self.create_item_edit_context(owner)
+ view = self.create_test_view_instance()
+
+ # Mock history record ID
+ history_id = 1
+
+ request = self.factory.post('/test/')
+ request.session = MockSession()
+
+ response = view.post_restore(
+ request=request,
+ attribute=attribute,
+ history_id=history_id,
+ attr_item_context=context
+ )
+
+ # Should return response (may be error if no history exists)
+ self.assertIn(response.status_code, [200, 400])
+
diff --git a/src/hi/apps/attribute/tests/attribute_multi_framework_test_base.py b/src/hi/apps/attribute/tests/attribute_multi_framework_test_base.py
new file mode 100644
index 00000000..42fdb9ff
--- /dev/null
+++ b/src/hi/apps/attribute/tests/attribute_multi_framework_test_base.py
@@ -0,0 +1,360 @@
+"""
+Abstract base test classes for multi-instance attribute editing framework.
+
+These test classes are designed specifically for the multi-edit architecture used
+by the config module, where multiple subsystems are edited simultaneously using
+AttributeMultiEditViewMixin and page-level contexts.
+"""
+from abc import ABC, abstractmethod
+from typing import List, Dict, Any
+
+from django.test import RequestFactory
+from django.http import QueryDict
+
+from hi.testing.base_test_case import MockRequest, MockSession
+from hi.apps.attribute.edit_context import AttributePageEditContext, AttributeItemEditContext
+from hi.apps.attribute.edit_form_handler import AttributeEditFormHandler
+from hi.apps.attribute.edit_response_renderer import AttributeEditResponseRenderer
+from hi.apps.attribute.edit_template_context_builder import AttributeEditTemplateContextBuilder
+from hi.apps.attribute.models import AttributeModel
+
+
+class AttributeMultiFrameworkTestMixin(ABC):
+ """Base mixin providing common setup for multi-edit attribute framework testing."""
+
+ def setUp(self):
+ super().setUp()
+ self.factory = RequestFactory()
+
+ @abstractmethod
+ def create_owner_instance_list(self, **kwargs) -> List[Any]:
+ """Create a list of owner instances (e.g., multiple Subsystems) for multi-edit testing."""
+ pass
+
+ @abstractmethod
+ def create_attribute_instance(self, owner, **kwargs) -> AttributeModel:
+ """Create an attribute instance for testing."""
+ pass
+
+ @abstractmethod
+ def create_item_edit_context(self, owner) -> AttributeItemEditContext:
+ """Create item edit context for testing."""
+ pass
+
+ @abstractmethod
+ def create_page_edit_context(self, owner_list: List[Any]) -> AttributePageEditContext:
+ """Create page edit context for multi-edit testing."""
+ pass
+
+ @abstractmethod
+ def create_multi_valid_form_data(self, owner_list: List[Any], **overrides) -> Dict[str, Any]:
+ """Create valid form data for multi-edit scenarios."""
+ pass
+
+ @abstractmethod
+ def create_multi_invalid_form_data(self, owner_list: List[Any]) -> Dict[str, Any]:
+ """Create invalid form data for multi-edit scenarios."""
+ pass
+
+
+class AttributeMultiEditFormHandlerTestMixin(AttributeMultiFrameworkTestMixin, ABC):
+ """Abstract base test mixin for testing AttributeEditFormHandler multi-edit functionality."""
+
+ def test_create_multi_edit_form_data_basic_workflow(self):
+ """Test basic multi-edit form data creation - core framework functionality."""
+ owner_list = self.create_owner_instance_list()
+ item_context_list = [self.create_item_edit_context(owner) for owner in owner_list]
+ handler = AttributeEditFormHandler()
+
+ multi_edit_form_data_list = handler.create_multi_edit_form_data(
+ attr_item_context_list=item_context_list
+ )
+
+ # Should create form data for each owner
+ self.assertEqual(len(multi_edit_form_data_list), len(owner_list))
+
+ # Each form data should have the required components
+ for form_data in multi_edit_form_data_list:
+ self.assertIsNotNone(form_data.regular_attributes_formset)
+ # Owner forms may or may not exist depending on the module
+
+ def test_create_multi_edit_form_data_with_post_data(self):
+ """Test multi-edit form data creation with POST data - bound form scenario."""
+ owner_list = self.create_owner_instance_list()
+ item_context_list = [self.create_item_edit_context(owner) for owner in owner_list]
+ handler = AttributeEditFormHandler()
+
+ post_data = QueryDict(mutable=True)
+ form_data_dict = self.create_multi_valid_form_data(owner_list)
+ for key, value in form_data_dict.items():
+ if isinstance(value, list):
+ post_data.setlist(key, value)
+ else:
+ post_data[key] = value
+
+ multi_edit_form_data_list = handler.create_multi_edit_form_data(
+ attr_item_context_list=item_context_list,
+ form_data=post_data
+ )
+
+ # Should create bound forms
+ self.assertEqual(len(multi_edit_form_data_list), len(owner_list))
+ for form_data in multi_edit_form_data_list:
+ self.assertTrue(form_data.regular_attributes_formset.is_bound)
+
+ def test_validate_forms_multi_with_valid_data_success(self):
+ """Test multi-edit form validation with valid data - success path validation."""
+ owner_list = self.create_owner_instance_list()
+ item_context_list = [self.create_item_edit_context(owner) for owner in owner_list]
+ handler = AttributeEditFormHandler()
+
+ post_data = QueryDict(mutable=True)
+ form_data_dict = self.create_multi_valid_form_data(owner_list)
+ for key, value in form_data_dict.items():
+ if isinstance(value, list):
+ post_data.setlist(key, value)
+ else:
+ post_data[key] = value
+
+ multi_edit_form_data_list = handler.create_multi_edit_form_data(
+ attr_item_context_list=item_context_list,
+ form_data=post_data
+ )
+
+ is_valid = handler.validate_forms_multi(multi_edit_form_data_list=multi_edit_form_data_list)
+ self.assertTrue(is_valid)
+
+ def test_validate_forms_multi_with_invalid_data_failure(self):
+ """Test multi-edit form validation with invalid data - error path validation."""
+ owner_list = self.create_owner_instance_list()
+ item_context_list = [self.create_item_edit_context(owner) for owner in owner_list]
+ handler = AttributeEditFormHandler()
+
+ post_data = QueryDict(mutable=True)
+ form_data_dict = self.create_multi_invalid_form_data(owner_list)
+ for key, value in form_data_dict.items():
+ if isinstance(value, list):
+ post_data.setlist(key, value)
+ else:
+ post_data[key] = value
+
+ multi_edit_form_data_list = handler.create_multi_edit_form_data(
+ attr_item_context_list=item_context_list,
+ form_data=post_data
+ )
+
+ is_valid = handler.validate_forms_multi(multi_edit_form_data_list=multi_edit_form_data_list)
+ self.assertFalse(is_valid)
+
+ def test_save_forms_multi_database_integration(self):
+ """Test multi-edit form saving creates/updates database records - database integration."""
+ owner_list = self.create_owner_instance_list()
+ item_context_list = [self.create_item_edit_context(owner) for owner in owner_list]
+ handler = AttributeEditFormHandler()
+
+ post_data = QueryDict(mutable=True)
+ form_data_dict = self.create_multi_valid_form_data(owner_list)
+ for key, value in form_data_dict.items():
+ if isinstance(value, list):
+ post_data.setlist(key, value)
+ else:
+ post_data[key] = value
+
+ multi_edit_form_data_list = handler.create_multi_edit_form_data(
+ attr_item_context_list=item_context_list,
+ form_data=post_data
+ )
+
+ # Ensure forms are valid before saving
+ self.assertTrue(handler.validate_forms_multi(multi_edit_form_data_list=multi_edit_form_data_list))
+
+ # Save forms
+ request = MockRequest()
+ request.POST = post_data
+ handler.save_forms_multi(
+ multi_edit_form_data_list=multi_edit_form_data_list,
+ request=request
+ )
+
+ # Verify data was saved - this will be module-specific
+ # Subclasses can add specific assertions
+
+
+class AttributeMultiEditResponseRendererTestMixin(AttributeMultiFrameworkTestMixin, ABC):
+ """Abstract base test mixin for testing AttributeEditResponseRenderer multi-edit functionality."""
+
+ def test_render_form_success_response_multi_structure(self):
+ """Test multi-edit success response structure - page response format."""
+ owner_list = self.create_owner_instance_list()
+ item_context_list = [self.create_item_edit_context(owner) for owner in owner_list]
+ page_context = self.create_page_edit_context(owner_list)
+
+ handler = AttributeEditFormHandler()
+ renderer = AttributeEditResponseRenderer()
+
+ multi_edit_form_data_list = handler.create_multi_edit_form_data(
+ attr_item_context_list=item_context_list
+ )
+
+ request = MockRequest()
+ request.session = MockSession()
+
+ response = renderer.render_form_success_response_multi(
+ attr_page_context=page_context,
+ multi_edit_form_data_list=multi_edit_form_data_list,
+ request=request,
+ message=None # Use default message
+ )
+
+ # Should return JSON response for HTMX
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(response['Content-Type'], 'application/json')
+
+ # Response should contain page-level update structure
+ import json
+ data = json.loads(response.content)
+ self.assertIsInstance(data, dict)
+ self.assertTrue(len(data) > 0)
+
+ def test_render_form_error_response_multi_with_validation_errors(self):
+ """Test multi-edit error response with form validation errors - error handling."""
+ owner_list = self.create_owner_instance_list()
+ item_context_list = [self.create_item_edit_context(owner) for owner in owner_list]
+ page_context = self.create_page_edit_context(owner_list)
+
+ handler = AttributeEditFormHandler()
+ renderer = AttributeEditResponseRenderer()
+
+ post_data = QueryDict(mutable=True)
+ form_data_dict = self.create_multi_invalid_form_data(owner_list)
+ for key, value in form_data_dict.items():
+ if isinstance(value, list):
+ post_data.setlist(key, value)
+ else:
+ post_data[key] = value
+
+ multi_edit_form_data_list = handler.create_multi_edit_form_data(
+ attr_item_context_list=item_context_list,
+ form_data=post_data
+ )
+
+ # Ensure forms are invalid
+ is_valid = handler.validate_forms_multi(multi_edit_form_data_list=multi_edit_form_data_list)
+ self.assertFalse(is_valid)
+
+ request = MockRequest()
+ request.POST = post_data
+ request.session = MockSession()
+
+ response = renderer.render_form_error_response_multi(
+ attr_page_context=page_context,
+ multi_edit_form_data_list=multi_edit_form_data_list,
+ request=request
+ )
+
+ # Should return error response
+ self.assertEqual(response.status_code, 400)
+ self.assertEqual(response['Content-Type'], 'application/json')
+
+
+class AttributeMultiEditTemplateContextBuilderTestMixin(AttributeMultiFrameworkTestMixin, ABC):
+ """Abstract base test mixin for testing AttributeEditTemplateContextBuilder multi-edit functionality."""
+
+ def test_build_multi_edit_template_context_structure(self):
+ """Test multi-edit template context building - context assembly."""
+ owner_list = self.create_owner_instance_list()
+ item_context_list = [self.create_item_edit_context(owner) for owner in owner_list]
+ page_context = self.create_page_edit_context(owner_list)
+
+ handler = AttributeEditFormHandler()
+ builder = AttributeEditTemplateContextBuilder()
+
+ multi_edit_form_data_list = handler.create_multi_edit_form_data(
+ attr_item_context_list=item_context_list
+ )
+
+ template_context = builder.build_response_template_context_multi(
+ attr_page_context=page_context,
+ multi_edit_form_data_list=multi_edit_form_data_list
+ )
+
+ # Should contain multi-edit context keys
+ self.assertIsInstance(template_context, dict)
+ self.assertIn('multi_edit_form_data_list', template_context)
+ self.assertIn('attr_page_context', template_context)
+
+ # Should have form data for each owner
+ multi_edit_data = template_context['multi_edit_form_data_list']
+ self.assertEqual(len(multi_edit_data), len(owner_list))
+
+
+class AttributeMultiEditViewMixinTestMixin(AttributeMultiFrameworkTestMixin, ABC):
+ """Abstract base test mixin for testing AttributeMultiEditViewMixin functionality."""
+
+ @abstractmethod
+ def create_view_instance(self):
+ """Create a view instance that uses AttributeMultiEditViewMixin."""
+ pass
+
+ def test_post_attribute_form_multi_success_workflow(self):
+ """Test successful multi-edit form POST handling - view integration success path."""
+ owner_list = self.create_owner_instance_list()
+ item_context_list = [self.create_item_edit_context(owner) for owner in owner_list]
+ page_context = self.create_page_edit_context(owner_list)
+
+ view = self.create_view_instance()
+
+ # Create valid POST data
+ post_data = QueryDict(mutable=True)
+ form_data_dict = self.create_multi_valid_form_data(owner_list)
+ for key, value in form_data_dict.items():
+ if isinstance(value, list):
+ post_data.setlist(key, value)
+ else:
+ post_data[key] = value
+
+ request = MockRequest()
+ request.POST = post_data
+ request.session = MockSession()
+
+ response = view.post_attribute_form(
+ request=request,
+ attr_page_context=page_context,
+ attr_item_context_list=item_context_list
+ )
+
+ # Should return success response
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(response['Content-Type'], 'application/json')
+
+ def test_post_attribute_form_multi_validation_failure(self):
+ """Test multi-edit form POST with validation errors - view integration error path."""
+ owner_list = self.create_owner_instance_list()
+ item_context_list = [self.create_item_edit_context(owner) for owner in owner_list]
+ page_context = self.create_page_edit_context(owner_list)
+
+ view = self.create_view_instance()
+
+ # Create invalid POST data
+ post_data = QueryDict(mutable=True)
+ form_data_dict = self.create_multi_invalid_form_data(owner_list)
+ for key, value in form_data_dict.items():
+ if isinstance(value, list):
+ post_data.setlist(key, value)
+ else:
+ post_data[key] = value
+
+ request = MockRequest()
+ request.POST = post_data
+ request.session = MockSession()
+
+ response = view.post_attribute_form(
+ request=request,
+ attr_page_context=page_context,
+ attr_item_context_list=item_context_list
+ )
+
+ # Should return error response
+ self.assertEqual(response.status_code, 400)
+ self.assertEqual(response['Content-Type'], 'application/json')
+
diff --git a/src/hi/apps/attribute/tests/test_edit_context.py b/src/hi/apps/attribute/tests/test_edit_context.py
index 21f72060..101aa1f1 100644
--- a/src/hi/apps/attribute/tests/test_edit_context.py
+++ b/src/hi/apps/attribute/tests/test_edit_context.py
@@ -1,44 +1,43 @@
"""
-Tests for AttributeEditContext base class.
+Tests for AttributeItemEditContext base class.
Focuses on high-value business logic: property computation, DOM ID generation,
URL parameter construction, and template context assembly.
"""
import logging
-from hi.apps.attribute.edit_context import AttributeEditContext
+from hi.apps.attribute.edit_context import AttributeItemEditContext
from hi.testing.base_test_case import BaseTestCase
logging.disable(logging.CRITICAL)
class MockOwner:
- """Simple mock owner for testing AttributeEditContext without Django model dependencies."""
+ """Simple mock owner for testing AttributeItemEditContext without Django model dependencies."""
def __init__(self, id, name):
self.id = id
self.name = name
-class TestAttributeEditContext(BaseTestCase):
+class TestAttributeItemEditContext(BaseTestCase):
def setUp(self):
super().setUp()
self.mock_owner = MockOwner(id=123, name="Test Owner")
- self.context = AttributeEditContext(self.mock_owner, "entity")
+ self.context = AttributeItemEditContext(self.mock_owner, "entity")
def test_property_computation_basic_cases(self):
"""Test basic property computation - critical URL and DOM ID generation logic."""
# Test basic property access
self.assertEqual(self.context.owner_id, 123)
- self.assertEqual(self.context.owner_name, "Test Owner")
self.assertEqual(self.context.owner_type, "entity")
self.assertEqual(self.context.owner_id_param_name, "entity_id")
def test_property_computation_case_normalization(self):
"""Test owner type case normalization - critical for consistent URL patterns."""
# Test case normalization
- context_upper = AttributeEditContext(self.mock_owner, "ENTITY")
- context_mixed = AttributeEditContext(self.mock_owner, "EnTiTy")
+ context_upper = AttributeItemEditContext(self.mock_owner, "ENTITY")
+ context_mixed = AttributeItemEditContext(self.mock_owner, "EnTiTy")
self.assertEqual(context_upper.owner_type, "entity")
self.assertEqual(context_mixed.owner_type, "entity")
@@ -52,7 +51,7 @@ class TestAttributeEditContext(BaseTestCase):
self.assertEqual(self.context.restore_url_name, "entity_attribute_restore_inline")
# Test with location owner type
- location_context = AttributeEditContext(self.mock_owner, "location")
+ location_context = AttributeItemEditContext(self.mock_owner, "location")
self.assertEqual(location_context.history_url_name, "location_attribute_history_inline")
self.assertEqual(location_context.restore_url_name, "location_attribute_restore_inline")
@@ -71,7 +70,7 @@ class TestAttributeEditContext(BaseTestCase):
def test_dom_id_generation_with_different_owner_types(self):
"""Test DOM ID generation varies correctly by owner type."""
attribute_id = 789
- location_context = AttributeEditContext(self.mock_owner, "location")
+ location_context = AttributeItemEditContext(self.mock_owner, "location")
# Should include owner type in ID
history_id = location_context.history_target_id(attribute_id)
@@ -92,9 +91,9 @@ class TestAttributeEditContext(BaseTestCase):
"""Test template context assembly - critical for template rendering."""
template_context = self.context.to_template_context()
- # Should include attr_context key
- self.assertIn('attr_context', template_context)
- self.assertIs(template_context['attr_context'], self.context)
+ # Should include attr_item_context key
+ self.assertIn('attr_item_context', template_context)
+ self.assertIs(template_context['attr_item_context'], self.context)
# Should include generic owner key
self.assertIn('owner', template_context)
@@ -106,7 +105,7 @@ class TestAttributeEditContext(BaseTestCase):
def test_template_context_assembly_multiple_owner_types(self):
"""Test template context includes correct owner-specific keys."""
- location_context = AttributeEditContext(self.mock_owner, "location")
+ location_context = AttributeItemEditContext(self.mock_owner, "location")
template_context = location_context.to_template_context()
# Should include location-specific key, not entity key
@@ -116,15 +115,12 @@ class TestAttributeEditContext(BaseTestCase):
# Generic keys should still be present
self.assertIn('owner', template_context)
- self.assertIn('attr_context', template_context)
+ self.assertIn('attr_item_context', template_context)
def test_edge_case_special_characters_in_owner_name(self):
"""Test handling of special characters in owner names - edge case robustness."""
special_owner = MockOwner(id=999, name="Owner with spaces & symbols!")
- context = AttributeEditContext(special_owner, "entity")
-
- # Should handle special characters gracefully
- self.assertEqual(context.owner_name, "Owner with spaces & symbols!")
+ context = AttributeItemEditContext(special_owner, "entity")
# DOM IDs should still be generated (special chars in name shouldn't break ID generation)
history_id = context.history_target_id(123)
@@ -135,8 +131,8 @@ class TestAttributeEditContext(BaseTestCase):
zero_owner = MockOwner(id=0, name="Zero ID Owner")
negative_owner = MockOwner(id=-1, name="Negative ID Owner")
- zero_context = AttributeEditContext(zero_owner, "entity")
- negative_context = AttributeEditContext(negative_owner, "entity")
+ zero_context = AttributeItemEditContext(zero_owner, "entity")
+ negative_context = AttributeItemEditContext(negative_owner, "entity")
# Should handle zero ID
self.assertEqual(zero_context.owner_id, 0)
@@ -148,7 +144,7 @@ class TestAttributeEditContext(BaseTestCase):
def test_edge_case_empty_owner_type(self):
"""Test handling of empty owner type - error case handling."""
- empty_context = AttributeEditContext(self.mock_owner, "")
+ empty_context = AttributeItemEditContext(self.mock_owner, "")
# Empty string should be normalized but might cause issues in URL patterns
self.assertEqual(empty_context.owner_type, "")
@@ -157,7 +153,7 @@ class TestAttributeEditContext(BaseTestCase):
def test_edge_case_whitespace_owner_type(self):
"""Test handling of whitespace in owner type - normalization logic."""
- whitespace_context = AttributeEditContext(self.mock_owner, " entity ")
+ whitespace_context = AttributeItemEditContext(self.mock_owner, " entity ")
# Should strip whitespace during normalization
self.assertEqual(whitespace_context.owner_type, " entity ") # Current implementation preserves whitespace
@@ -167,7 +163,6 @@ class TestAttributeEditContext(BaseTestCase):
"""Test that context properties are computed from constructor args - consistency testing."""
# Modifying owner after context creation shouldn't affect context
original_id = self.context.owner_id
- original_name = self.context.owner_name
# Modify the mock owner
self.mock_owner.id = 999
@@ -175,11 +170,9 @@ class TestAttributeEditContext(BaseTestCase):
# Context should reflect the modified owner (it holds a reference, so it's not immutable)
self.assertEqual(self.context.owner_id, 999)
- self.assertEqual(self.context.owner_name, "Modified Name")
# Verify the change actually happened
self.assertNotEqual(self.context.owner_id, original_id)
- self.assertNotEqual(self.context.owner_name, original_name)
# But owner_type should remain the same (set at construction)
self.assertEqual(self.context.owner_type, "entity")
diff --git a/src/hi/apps/attribute/tests/test_models.py b/src/hi/apps/attribute/tests/test_models.py
index 00316b8c..2c140984 100644
--- a/src/hi/apps/attribute/tests/test_models.py
+++ b/src/hi/apps/attribute/tests/test_models.py
@@ -149,36 +149,6 @@ class TestAttributeModel(BaseTestCase):
self.assertEqual(attr.file_value.field.upload_to, 'test_attributes/')
return
- @patch('hi.apps.attribute.models.default_storage')
- def test_attribute_model_file_deletion_cleanup(self, mock_storage):
- """Test file deletion cleanup - critical for storage management."""
- mock_storage.exists.return_value = True
- mock_storage.delete.return_value = None
-
- # Create attribute with file
- test_file = SimpleUploadedFile(
- name='test_file.txt',
- content=b'test content',
- content_type='text/plain'
- )
-
- attr = ConcreteAttributeModel(
- name='test_attr',
- value_type_str='FILE',
- attribute_type_str='CUSTOM'
- )
- attr.file_value = test_file
- attr.pk = 1 # Set a fake primary key
-
- # Mock the delete operation to avoid database issues
- with patch('django.db.models.Model.delete'):
- attr.delete()
-
- # Should check and delete file
- mock_storage.exists.assert_called_once_with(test_file)
- mock_storage.delete.assert_called_once_with(test_file)
- return
-
@patch('hi.apps.attribute.models.default_storage')
def test_attribute_model_file_deletion_missing_file(self, mock_storage):
"""Test file deletion when file doesn't exist - error handling."""
diff --git a/src/hi/apps/attribute/tests/test_response_helpers.py b/src/hi/apps/attribute/tests/test_response_helpers.py
new file mode 100644
index 00000000..abec0b3e
--- /dev/null
+++ b/src/hi/apps/attribute/tests/test_response_helpers.py
@@ -0,0 +1,460 @@
+"""
+Tests for AttributeResponse and AttributeResponseBuilder classes.
+
+Focuses on high-value business logic: response data structure creation,
+JSON serialization, HTTP response generation, and builder pattern functionality.
+These are critical for client-server communication consistency.
+"""
+import json
+import logging
+from django.http import HttpResponse
+from django.test import TestCase
+
+from hi.apps.attribute.response_helpers import (
+ AttributeResponse,
+ AttributeResponseBuilder,
+ DOMUpdate,
+)
+from hi.apps.attribute.response_constants import (
+ DefaultMessages,
+ HTTPHeaders,
+ ResponseFields,
+ UpdateMode,
+)
+
+logging.disable(logging.CRITICAL)
+
+
+class TestDOMUpdate(TestCase):
+ """Test DOMUpdate dataclass - critical for DOM manipulation instructions."""
+
+ def test_dom_update_basic_creation(self):
+ """Test basic DOMUpdate creation and property access."""
+ update = DOMUpdate(
+ target="#test-element",
+ html="<div>Test Content</div>",
+ mode=UpdateMode.REPLACE
+ )
+
+ self.assertEqual(update.target, "#test-element")
+ self.assertEqual(update.html, "<div>Test Content</div>")
+ self.assertEqual(update.mode, UpdateMode.REPLACE)
+
+ def test_dom_update_default_mode(self):
+ """Test DOMUpdate uses REPLACE as default mode."""
+ update = DOMUpdate(
+ target="#test-element",
+ html="<div>Test Content</div>"
+ )
+
+ self.assertEqual(update.mode, UpdateMode.REPLACE)
+
+ def test_dom_update_to_dict_conversion(self):
+ """Test DOMUpdate serialization to dictionary - critical for JSON response."""
+ update = DOMUpdate(
+ target="#test-element",
+ html="<div>Test Content</div>",
+ mode=UpdateMode.APPEND
+ )
+
+ result = update.to_dict()
+ expected = {
+ ResponseFields.TARGET: "#test-element",
+ ResponseFields.HTML: "<div>Test Content</div>",
+ ResponseFields.MODE: "append",
+ }
+
+ self.assertEqual(result, expected)
+
+ def test_dom_update_all_mode_types(self):
+ """Test DOMUpdate works with all update modes - enum consistency."""
+ modes_and_values = [
+ (UpdateMode.REPLACE, "replace"),
+ (UpdateMode.APPEND, "append"),
+ (UpdateMode.PREPEND, "prepend"),
+ ]
+
+ for mode_enum, mode_value in modes_and_values:
+ update = DOMUpdate(
+ target="#test",
+ html="<div>test</div>",
+ mode=mode_enum
+ )
+ result = update.to_dict()
+ self.assertEqual(result[ResponseFields.MODE], mode_value)
+
+
+class TestAttributeResponse(TestCase):
+ """Test AttributeResponse dataclass - critical for response structure."""
+
+ def test_attribute_response_success_basic(self):
+ """Test basic successful AttributeResponse creation."""
+ response = AttributeResponse(
+ success=True,
+ message="Operation completed"
+ )
+
+ self.assertTrue(response.success)
+ self.assertEqual(response.message, "Operation completed")
+ self.assertEqual(len(response.updates), 0)
+
+ def test_attribute_response_error_basic(self):
+ """Test basic error AttributeResponse creation."""
+ response = AttributeResponse(
+ success=False,
+ message="Validation failed"
+ )
+
+ self.assertFalse(response.success)
+ self.assertEqual(response.message, "Validation failed")
+
+ def test_attribute_response_with_updates(self):
+ """Test AttributeResponse with DOM updates - complex data structure."""
+ update1 = DOMUpdate("#element1", "<div>Content 1</div>", UpdateMode.REPLACE)
+ update2 = DOMUpdate("#element2", "<div>Content 2</div>", UpdateMode.APPEND)
+
+ response = AttributeResponse(
+ success=True,
+ updates=[update1, update2],
+ message="Multiple updates applied"
+ )
+
+ self.assertTrue(response.success)
+ self.assertEqual(len(response.updates), 2)
+ self.assertEqual(response.updates[0], update1)
+ self.assertEqual(response.updates[1], update2)
+
+ def test_attribute_response_to_dict_complete(self):
+ """Test complete AttributeResponse dictionary serialization."""
+ update = DOMUpdate("#test-element", "<div>Test</div>", UpdateMode.REPLACE)
+ response = AttributeResponse(
+ success=True,
+ updates=[update],
+ message="Test message"
+ )
+
+ result = response.to_dict()
+ expected = {
+ ResponseFields.SUCCESS: True,
+ ResponseFields.UPDATES: [
+ {
+ ResponseFields.TARGET: "#test-element",
+ ResponseFields.HTML: "<div>Test</div>",
+ ResponseFields.MODE: "replace"
+ }
+ ],
+ ResponseFields.MESSAGE: "Test message"
+ }
+
+ self.assertEqual(result, expected)
+
+ def test_attribute_response_to_dict_no_message(self):
+ """Test AttributeResponse serialization without message - optional field handling."""
+ response = AttributeResponse(success=True, updates=[])
+ result = response.to_dict()
+
+ self.assertIn(ResponseFields.SUCCESS, result)
+ self.assertIn(ResponseFields.UPDATES, result)
+ self.assertNotIn(ResponseFields.MESSAGE, result)
+
+ def test_attribute_response_to_http_response_success(self):
+ """Test HTTP response generation - critical for Django integration."""
+ response = AttributeResponse(
+ success=True,
+ message="Success"
+ )
+
+ http_response = response.to_http_response()
+
+ self.assertIsInstance(http_response, HttpResponse)
+ self.assertEqual(http_response.status_code, 200)
+ self.assertEqual(http_response['Content-Type'], HTTPHeaders.APPLICATION_JSON)
+
+ # Verify JSON content
+ response_data = json.loads(http_response.content)
+ self.assertTrue(response_data[ResponseFields.SUCCESS])
+ self.assertEqual(response_data[ResponseFields.MESSAGE], "Success")
+
+ def test_attribute_response_to_http_response_custom_status(self):
+ """Test HTTP response with custom status code."""
+ response = AttributeResponse(success=False)
+ http_response = response.to_http_response(status_code=400)
+
+ self.assertEqual(http_response.status_code, 400)
+
+ def test_attribute_response_json_serialization_edge_cases(self):
+ """Test JSON serialization handles edge cases - robustness testing."""
+ # Empty updates list
+ response = AttributeResponse(success=True, updates=[])
+ result = response.to_dict()
+ self.assertEqual(result[ResponseFields.UPDATES], [])
+
+ # Special characters in HTML
+ update = DOMUpdate("#test", "<div class=\"special-class\">Content</div>")
+ response = AttributeResponse(success=True, updates=[update])
+ result = response.to_dict()
+ expected_html = "<div class=\"special-class\">Content</div>"
+ self.assertEqual(result[ResponseFields.UPDATES][0][ResponseFields.HTML], expected_html)
+
+
+class TestAttributeResponseBuilder(TestCase):
+ """Test AttributeResponseBuilder - critical for fluent API pattern."""
+
+ def test_builder_success_basic(self):
+ """Test basic success response building."""
+ builder = AttributeResponseBuilder()
+ response = builder.success().build()
+
+ self.assertIsInstance(response, AttributeResponse)
+ self.assertTrue(response.success)
+ self.assertEqual(len(response.updates), 0)
+ self.assertIsNone(response.message)
+
+ def test_builder_error_basic(self):
+ """Test basic error response building."""
+ builder = AttributeResponseBuilder()
+ response = builder.error().build()
+
+ self.assertIsInstance(response, AttributeResponse)
+ self.assertFalse(response.success)
+
+ def test_builder_fluent_interface_chaining(self):
+ """Test builder method chaining - fluent interface functionality."""
+ builder = AttributeResponseBuilder()
+ result = (builder
+ .success()
+ .with_message("Test message")
+ .add_update("#element", "<div>content</div>", UpdateMode.REPLACE))
+
+ # Verify chaining returns the same builder instance
+ self.assertIs(result, builder)
+
+ response = result.build()
+ self.assertTrue(response.success)
+ self.assertEqual(response.message, "Test message")
+ self.assertEqual(len(response.updates), 1)
+
+ def test_builder_add_multiple_updates(self):
+ """Test builder can accumulate multiple updates."""
+ response = (AttributeResponseBuilder()
+ .success()
+ .add_update("#element1", "<div>Content 1</div>", UpdateMode.REPLACE)
+ .add_update("#element2", "<div>Content 2</div>", UpdateMode.APPEND)
+ .add_update("#element3", "<div>Content 3</div>", UpdateMode.PREPEND)
+ .build())
+
+ self.assertEqual(len(response.updates), 3)
+ self.assertEqual(response.updates[0].target, "#element1")
+ self.assertEqual(response.updates[0].mode, UpdateMode.REPLACE)
+ self.assertEqual(response.updates[1].target, "#element2")
+ self.assertEqual(response.updates[1].mode, UpdateMode.APPEND)
+ self.assertEqual(response.updates[2].target, "#element3")
+ self.assertEqual(response.updates[2].mode, UpdateMode.PREPEND)
+
+ def test_builder_message_override_behavior(self):
+ """Test builder message can be set and overridden."""
+ response = (AttributeResponseBuilder()
+ .success("First message")
+ .with_message("Second message")
+ .build())
+
+ self.assertEqual(response.message, "Second message")
+
+ def test_builder_success_error_state_switching(self):
+ """Test builder can switch between success and error states."""
+ builder = AttributeResponseBuilder()
+
+ # Start as success, switch to error
+ response1 = builder.success().error().build()
+ self.assertFalse(response1.success)
+
+ # Switch back to success
+ response2 = builder.success().build()
+ self.assertTrue(response2.success)
+
+ def test_builder_build_http_response_default_status(self):
+ """Test builder HTTP response generation with default status codes."""
+ # Success response defaults to 200
+ success_response = (AttributeResponseBuilder()
+ .success()
+ .build_http_response())
+ self.assertEqual(success_response.status_code, 200)
+
+ # Error response defaults to 400
+ error_response = (AttributeResponseBuilder()
+ .error()
+ .build_http_response())
+ self.assertEqual(error_response.status_code, 400)
+
+ def test_builder_build_http_response_custom_status(self):
+ """Test builder HTTP response with custom status code."""
+ response = (AttributeResponseBuilder()
+ .success()
+ .build_http_response(status_code=201))
+
+ self.assertEqual(response.status_code, 201)
+
+ def test_builder_build_http_response_json_content(self):
+ """Test builder HTTP response contains valid JSON - integration testing."""
+ http_response = (AttributeResponseBuilder()
+ .success()
+ .add_update("#test", "<div>Test</div>")
+ .with_message("Test message")
+ .build_http_response())
+
+ # Verify response structure
+ self.assertEqual(http_response['Content-Type'], HTTPHeaders.APPLICATION_JSON)
+
+ # Verify JSON parsing and content
+ response_data = json.loads(http_response.content)
+ self.assertTrue(response_data[ResponseFields.SUCCESS])
+ self.assertEqual(response_data[ResponseFields.MESSAGE], "Test message")
+ self.assertEqual(len(response_data[ResponseFields.UPDATES]), 1)
+ self.assertEqual(response_data[ResponseFields.UPDATES][0][ResponseFields.TARGET], "#test")
+
+ def test_builder_create_success_response_class_method(self):
+ """Test convenience class method for success responses."""
+ update1 = DOMUpdate("#element1", "<div>Content 1</div>", UpdateMode.REPLACE)
+ update2 = DOMUpdate("#element2", "<div>Content 2</div>", UpdateMode.APPEND)
+
+ http_response = AttributeResponseBuilder.create_success_response(
+ updates=[update1, update2],
+ message="Custom success message",
+ status_code=201
+ )
+
+ self.assertIsInstance(http_response, HttpResponse)
+ self.assertEqual(http_response.status_code, 201)
+
+ response_data = json.loads(http_response.content)
+ self.assertTrue(response_data[ResponseFields.SUCCESS])
+ self.assertEqual(response_data[ResponseFields.MESSAGE], "Custom success message")
+ self.assertEqual(len(response_data[ResponseFields.UPDATES]), 2)
+
+ def test_builder_create_success_response_default_message(self):
+ """Test success response class method uses default message."""
+ http_response = AttributeResponseBuilder.create_success_response(updates=[])
+
+ response_data = json.loads(http_response.content)
+ self.assertEqual(response_data[ResponseFields.MESSAGE], DefaultMessages.SAVE_SUCCESS)
+
+ def test_builder_create_error_response_class_method(self):
+ """Test convenience class method for error responses."""
+ update = DOMUpdate("#error-element", "<div>Error content</div>", UpdateMode.REPLACE)
+
+ http_response = AttributeResponseBuilder.create_error_response(
+ updates=[update],
+ message="Custom error message",
+ status_code=422
+ )
+
+ self.assertIsInstance(http_response, HttpResponse)
+ self.assertEqual(http_response.status_code, 422)
+
+ response_data = json.loads(http_response.content)
+ self.assertFalse(response_data[ResponseFields.SUCCESS])
+ self.assertEqual(response_data[ResponseFields.MESSAGE], "Custom error message")
+
+ def test_builder_create_error_response_default_message(self):
+ """Test error response class method uses default message."""
+ http_response = AttributeResponseBuilder.create_error_response(updates=[])
+
+ response_data = json.loads(http_response.content)
+ self.assertEqual(response_data[ResponseFields.MESSAGE], DefaultMessages.SAVE_ERROR)
+
+ def test_builder_create_upload_success_response_class_method(self):
+ """Test convenience class method for file upload success."""
+ http_response = AttributeResponseBuilder.create_upload_success_response(
+ target_selector="#file-grid",
+ file_card_html="<div class='file-card'>New File</div>",
+ message="Custom upload message"
+ )
+
+ self.assertIsInstance(http_response, HttpResponse)
+ self.assertEqual(http_response.status_code, 200)
+
+ response_data = json.loads(http_response.content)
+ self.assertTrue(response_data[ResponseFields.SUCCESS])
+ self.assertEqual(response_data[ResponseFields.MESSAGE], "Custom upload message")
+ self.assertEqual(len(response_data[ResponseFields.UPDATES]), 1)
+ self.assertEqual(response_data[ResponseFields.UPDATES][0][ResponseFields.TARGET], "#file-grid")
+ self.assertEqual(response_data[ResponseFields.UPDATES][0][ResponseFields.MODE], "append")
+
+ def test_builder_create_upload_success_response_default_message(self):
+ """Test upload success response uses default message."""
+ http_response = AttributeResponseBuilder.create_upload_success_response(
+ target_selector="#file-grid",
+ file_card_html="<div class='file-card'>File</div>"
+ )
+
+ response_data = json.loads(http_response.content)
+ self.assertEqual(response_data[ResponseFields.MESSAGE], DefaultMessages.UPLOAD_SUCCESS)
+
+
+class TestResponseHelpersEdgeCases(TestCase):
+ """Test edge cases and error conditions - robustness testing."""
+
+ def test_dom_update_empty_strings(self):
+ """Test DOMUpdate handles empty strings gracefully."""
+ update = DOMUpdate(target="", html="", mode=UpdateMode.REPLACE)
+ result = update.to_dict()
+
+ self.assertEqual(result[ResponseFields.TARGET], "")
+ self.assertEqual(result[ResponseFields.HTML], "")
+
+ def test_attribute_response_empty_message_serialization(self):
+ """Test AttributeResponse handles empty message correctly."""
+ response = AttributeResponse(success=True, message="")
+ result = response.to_dict()
+
+ # Empty message should be excluded (falsy values are filtered out)
+ self.assertNotIn(ResponseFields.MESSAGE, result)
+
+ def test_builder_multiple_build_calls_isolation(self):
+ """Test builder builds independent response objects."""
+ builder = AttributeResponseBuilder().success().with_message("Test")
+
+ response1 = builder.build()
+ response2 = builder.build()
+
+ # Should be different objects
+ self.assertIsNot(response1, response2)
+ # But with same content
+ self.assertEqual(response1.success, response2.success)
+ self.assertEqual(response1.message, response2.message)
+
+ def test_builder_state_persistence_across_builds(self):
+ """Test builder state persists across multiple builds."""
+ builder = (AttributeResponseBuilder()
+ .success()
+ .add_update("#element", "<div>content</div>")
+ .with_message("Persistent message"))
+
+ response1 = builder.build()
+ response2 = builder.build()
+
+ # Both responses should have the same configuration
+ self.assertTrue(response1.success)
+ self.assertTrue(response2.success)
+ self.assertEqual(response1.message, response2.message)
+ self.assertEqual(len(response1.updates), 1)
+ self.assertEqual(len(response2.updates), 1)
+
+ def test_response_json_special_characters(self):
+ """Test response handles JSON special characters correctly."""
+ update = DOMUpdate(
+ target="#test-element",
+ html="<div>Content with \"quotes\" and 'apostrophes' and \\ backslashes</div>"
+ )
+ response = AttributeResponse(success=True, updates=[update])
+
+ # Should not raise exception during serialization
+ http_response = response.to_http_response()
+
+ # Should be valid JSON
+ response_data = json.loads(http_response.content)
+ expected_html = "<div>Content with \"quotes\" and 'apostrophes' and \\ backslashes</div>"
+ self.assertEqual(
+ response_data[ResponseFields.UPDATES][0][ResponseFields.HTML],
+ expected_html
+ )
diff --git a/src/hi/apps/attribute/tests/test_templatetags.py b/src/hi/apps/attribute/tests/test_templatetags.py
index 6bee2a00..7962f78b 100644
--- a/src/hi/apps/attribute/tests/test_templatetags.py
+++ b/src/hi/apps/attribute/tests/test_templatetags.py
@@ -13,7 +13,7 @@ from hi.apps.attribute.templatetags.attribute_extras import (
attribute_preview, file_title_field_name, history_target_id,
history_toggle_id, attr_history_url, attr_restore_url
)
-from hi.apps.attribute.edit_context import AttributeEditContext
+from hi.apps.attribute.edit_context import AttributeItemEditContext
logging.disable(logging.CRITICAL)
@@ -119,11 +119,11 @@ class TestAttributePreviewFilter(TestCase):
class TestAttributeContextFilters(TestCase):
- """Test filters that work with AttributeEditContext objects."""
+ """Test filters that work with AttributeItemEditContext objects."""
def setUp(self):
self.mock_owner = MockOwner(id=123, name="Test Owner")
- self.context = AttributeEditContext(self.mock_owner, "entity")
+ self.context = AttributeItemEditContext(self.mock_owner, "entity")
self.attribute_id = 456
def test_file_title_field_name_filter(self):
@@ -153,7 +153,7 @@ class TestAttributeUrlTags(TestCase):
def setUp(self):
self.mock_owner = MockOwner(id=123, name="Test Owner")
- self.context = AttributeEditContext(self.mock_owner, "entity")
+ self.context = AttributeItemEditContext(self.mock_owner, "entity")
self.attribute_id = 456
self.history_id = 789
@@ -195,7 +195,7 @@ class TestAttributeUrlTags(TestCase):
@patch('django.urls.reverse')
def test_attr_history_url_tag_different_owner_types(self, mock_reverse):
"""Test URL tags work correctly with different owner types."""
- location_context = AttributeEditContext(self.mock_owner, "location")
+ location_context = AttributeItemEditContext(self.mock_owner, "location")
mock_reverse.return_value = "/location/123/attribute/456/history/"
result = attr_history_url(location_context, self.attribute_id)
@@ -229,7 +229,7 @@ class TestTemplateIntegration(TestCase):
def setUp(self):
self.mock_owner = MockOwner(id=123, name="Test Owner")
- self.context = AttributeEditContext(self.mock_owner, "entity")
+ self.context = AttributeItemEditContext(self.mock_owner, "entity")
def test_attribute_preview_filter_in_template(self):
"""Test attribute_preview filter works in actual template rendering."""
@@ -251,17 +251,17 @@ class TestTemplateIntegration(TestCase):
self.assertIn("lines", rendered)
def test_context_filters_in_template(self):
- """Test AttributeEditContext filters work in template rendering."""
+ """Test AttributeItemEditContext filters work in template rendering."""
template_str = """
{% load attribute_extras %}
- Field: {{ attr_context|file_title_field_name:attribute_id }}
- Target: {{ attr_context|history_target_id:attribute_id }}
- Toggle: {{ attr_context|history_toggle_id:attribute_id }}
+ Field: {{ attr_item_context|file_title_field_name:attribute_id }}
+ Target: {{ attr_item_context|history_target_id:attribute_id }}
+ Toggle: {{ attr_item_context|history_toggle_id:attribute_id }}
"""
template = Template(template_str)
context = Context({
- 'attr_context': self.context,
+ 'attr_item_context': self.context,
'attribute_id': 456
})
@@ -277,13 +277,13 @@ class TestTemplateIntegration(TestCase):
template_str = """
{% load attribute_extras %}
- History: {% attr_history_url attr_context attribute_id %}
- Restore: {% attr_restore_url attr_context attribute_id history_id %}
+ History: {% attr_history_url attr_item_context attribute_id %}
+ Restore: {% attr_restore_url attr_item_context attribute_id history_id %}
"""
template = Template(template_str)
context = Context({
- 'attr_context': self.context,
+ 'attr_item_context': self.context,
'attribute_id': 456,
'history_id': 789
})
diff --git a/src/hi/apps/attribute/transient_models.py b/src/hi/apps/attribute/transient_models.py
new file mode 100644
index 00000000..5eefbb6b
--- /dev/null
+++ b/src/hi/apps/attribute/transient_models.py
@@ -0,0 +1,51 @@
+from dataclasses import dataclass
+
+from django.db.models import Model
+from django.forms import ModelForm, BaseInlineFormSet
+from django.db.models import QuerySet
+
+from .edit_context import AttributeItemEditContext
+from .models import AttributeModel
+
+
+@dataclass
+class AttributeEditFormData:
+ owner_form : ModelForm
+ file_attributes : QuerySet[AttributeModel]
+ regular_attributes_formset : BaseInlineFormSet
+ error_count : int = 0
+
+
+@dataclass
+class AttributeMultiEditFormData:
+ attr_item_context : AttributeItemEditContext
+ edit_form_data : AttributeEditFormData
+
+ @property
+ def owner(self) -> Model:
+ return self.attr_item_context.owner
+
+ @property
+ def owner_form(self) -> ModelForm:
+ return self.edit_form_data.owner_form
+
+ @property
+ def file_attributes(self) -> QuerySet[AttributeModel]:
+ return self.edit_form_data.file_attributes
+
+ @property
+ def context(self):
+ return self.attr_item_context
+
+ @property
+ def regular_attributes_formset(self):
+ return self.edit_form_data.regular_attributes_formset
+
+ @property
+ def formset(self):
+ return self.edit_form_data.regular_attributes_formset
+
+ @property
+ def error_count(self):
+ return self.edit_form_data.error_count
+
diff --git a/src/hi/apps/attribute/view_mixins.py b/src/hi/apps/attribute/view_mixins.py
new file mode 100644
index 00000000..b5866108
--- /dev/null
+++ b/src/hi/apps/attribute/view_mixins.py
@@ -0,0 +1,224 @@
+import logging
+from typing import Any, Dict, List
+
+from django.http import HttpRequest, HttpResponse
+
+
+from .edit_context import AttributeItemEditContext, AttributePageEditContext
+from .edit_form_handler import AttributeEditFormHandler
+from .edit_response_renderer import AttributeEditResponseRenderer
+from .edit_template_context_builder import AttributeEditTemplateContextBuilder
+from .models import AttributeModel
+
+logger = logging.getLogger(__name__)
+
+
+class AttributeEditCommonMixin:
+ """ Common mixins are those where we only deal with a single attribuet at a time.
+ Thus, it does not depend if we are using a single item or mutliple item views.
+ """
+
+ ATTRIBUTE_HISTORY_VIEW_LIMIT = 50
+
+ def post_upload( self,
+ request : HttpRequest,
+ attr_item_context : AttributeItemEditContext ) -> HttpResponse:
+
+ form_handler = AttributeEditFormHandler()
+ renderer = AttributeEditResponseRenderer()
+
+ attribute_upload_form = form_handler.create_upload_form(
+ attr_item_context = attr_item_context,
+ request = request,
+ )
+ if form_handler.validate_upload_form( attribute_upload_form ):
+ form_handler.save_upload_form( attribute_upload_form )
+ return renderer.render_upload_success_response(
+ attr_item_context = attr_item_context,
+ attribute_upload_form = attribute_upload_form,
+ request = request,
+ )
+ else:
+ return renderer.render_upload_error_response(
+ attr_item_context = attr_item_context,
+ attribute_upload_form = attribute_upload_form,
+ request = request,
+ )
+
+ def get_history( self,
+ request : HttpRequest,
+ attribute : AttributeModel,
+ attr_item_context : AttributeItemEditContext ) -> HttpResponse:
+
+ renderer = AttributeEditResponseRenderer()
+
+ # 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 = []
+
+ return renderer.render_history_response(
+ attr_item_context = attr_item_context,
+ attribute = attribute,
+ history_records = history_records,
+ request= request,
+ )
+
+ def do_restore( self,
+ attribute : AttributeModel,
+ history_id : int ):
+ """ Caller should catch exceptions """
+
+ history_model_class = attribute._get_history_model_class()
+ if not history_model_class:
+ raise NotImplementedError("No history available for this attribute type.")
+
+ # May raise: history_model_class.DoesNotExist
+ history_record = history_model_class.objects.get(
+ pk = history_id,
+ attribute = attribute
+ )
+
+ attribute.value = history_record.value
+ attribute.save() # This will create a new history record too
+ return
+
+
+class AttributeEditViewMixin( AttributeEditCommonMixin ):
+
+ def post_attribute_form( self,
+ request : HttpRequest,
+ attr_item_context : AttributeItemEditContext ) -> HttpResponse:
+
+ form_handler = AttributeEditFormHandler()
+ renderer = AttributeEditResponseRenderer()
+
+ edit_form_data = form_handler.create_edit_form_data(
+ attr_item_context = attr_item_context,
+ form_data = request.POST,
+ )
+
+ if form_handler.validate_forms( edit_form_data = edit_form_data ):
+ form_handler.save_forms(
+ attr_item_context = attr_item_context,
+ edit_form_data = edit_form_data,
+ request = request,
+ )
+ return renderer.render_form_success_response(
+ attr_item_context = attr_item_context,
+ request = request,
+ message = None, # Use default message
+ )
+ else:
+ return renderer.render_form_error_response(
+ attr_item_context = attr_item_context,
+ edit_form_data = edit_form_data,
+ request = request,
+ )
+
+ def create_initial_template_context(
+ self,
+ attr_item_context : AttributeItemEditContext ) -> Dict[str, Any]:
+
+ template_context_builder = AttributeEditTemplateContextBuilder()
+ return template_context_builder.build_initial_template_context(
+ attr_item_context = attr_item_context,
+ )
+
+ def post_restore( self,
+ request : HttpRequest,
+ attribute : AttributeModel,
+ history_id : int,
+ attr_item_context : AttributeItemEditContext ) -> HttpResponse:
+
+ renderer = AttributeEditResponseRenderer()
+
+ try:
+ self.do_restore(
+ attribute = attribute,
+ history_id = history_id,
+ )
+ return renderer.render_restore_success_response(
+ attr_item_context = attr_item_context,
+ request = request,
+ )
+ except Exception as e:
+ return renderer.render_restore_error_response( str(e) )
+
+
+class AttributeMultiEditViewMixin( AttributeEditCommonMixin ):
+
+ def post_attribute_form(
+ self,
+ request : HttpRequest,
+ attr_page_context : AttributePageEditContext,
+ attr_item_context_list : List[AttributeItemEditContext] ) -> HttpResponse:
+
+ form_handler = AttributeEditFormHandler()
+ renderer = AttributeEditResponseRenderer()
+
+ multi_edit_form_data_list = form_handler.create_multi_edit_form_data(
+ attr_item_context_list = attr_item_context_list,
+ form_data = request.POST,
+ )
+
+ if form_handler.validate_forms_multi( multi_edit_form_data_list = multi_edit_form_data_list ):
+ form_handler.save_forms_multi(
+ multi_edit_form_data_list = multi_edit_form_data_list,
+ request = request,
+ )
+ return renderer.render_form_success_response_multi(
+ attr_page_context = attr_page_context,
+ multi_edit_form_data_list = multi_edit_form_data_list,
+ request = request,
+ message = None, # Use default message
+ )
+ else:
+ return renderer.render_form_error_response_multi(
+ attr_page_context = attr_page_context,
+ multi_edit_form_data_list = multi_edit_form_data_list,
+ request = request,
+ )
+
+ def create_initial_template_context(
+ self,
+ attr_page_context : AttributePageEditContext,
+ attr_item_context_list : List[AttributeItemEditContext] ) -> Dict[str, Any]:
+
+ template_context_builder = AttributeEditTemplateContextBuilder()
+ return template_context_builder.build_initial_template_context_multi(
+ attr_page_context = attr_page_context,
+ attr_item_context_list = attr_item_context_list,
+ )
+
+ def post_restore( self,
+ request : HttpRequest,
+ attribute : AttributeModel,
+ history_id : int,
+ attr_page_context : AttributePageEditContext,
+ attr_item_context_list : List[AttributeItemEditContext] ) -> HttpResponse:
+
+ form_handler = AttributeEditFormHandler()
+ renderer = AttributeEditResponseRenderer()
+
+ try:
+ self.do_restore(
+ attribute = attribute,
+ history_id = history_id,
+ )
+ except Exception as e:
+ return renderer.render_restore_error_response( str(e) )
+
+ multi_edit_form_data_list = form_handler.create_multi_edit_form_data(
+ attr_item_context_list = attr_item_context_list,
+ )
+ return renderer.render_restore_success_response_multi(
+ attr_page_context = attr_page_context,
+ multi_edit_form_data_list = multi_edit_form_data_list,
+ request = request,
+ )
+
diff --git a/src/hi/apps/config/enums.py b/src/hi/apps/config/enums.py
index 19c1170d..04cb32c1 100644
--- a/src/hi/apps/config/enums.py
+++ b/src/hi/apps/config/enums.py
@@ -20,5 +20,6 @@ class ConfigPageType(LabeledEnum):
EVENTS = ('Triggers' , '' , 'event_definitions' )
INTEGRATIONS = ('Integrations' , '' , 'integrations_home' )
- def default(self):
- return ConfigPageType.SETTINGS
+ @classmethod
+ def default(cls):
+ return cls.SETTINGS
diff --git a/src/hi/apps/config/settings_manager.py b/src/hi/apps/config/settings_manager.py
index 41853f5f..924dd765 100644
--- a/src/hi/apps/config/settings_manager.py
+++ b/src/hi/apps/config/settings_manager.py
@@ -75,6 +75,13 @@ class SettingsManager( Singleton ):
def get_server_start_datetime( self ) -> datetime:
return self._server_start_datetime
+ def get_subsystem( self, subsystem_id : int ) -> List[ Subsystem ]:
+ for subsystem in self._subsystem_list:
+ if subsystem.id == subsystem_id:
+ return subsystem
+ continue
+ raise Subsystem.DoesNotExist()
+
def get_subsystems(self) -> List[ Subsystem ]:
return self._subsystem_list
diff --git a/src/hi/apps/config/settings_mixins.py b/src/hi/apps/config/settings_mixins.py
index 538beb91..a2e7b9db 100644
--- a/src/hi/apps/config/settings_mixins.py
+++ b/src/hi/apps/config/settings_mixins.py
@@ -1,8 +1,14 @@
from asgiref.sync import sync_to_async
import asyncio
import logging
+from typing import List
+from django.core.exceptions import BadRequest
+from django.http import Http404
+
+from .models import Subsystem
from .settings_manager import SettingsManager
+from .subsystem_attribute_edit_context import SubsystemAttributeItemEditContext
logger = logging.getLogger(__name__)
@@ -31,3 +37,27 @@ class SettingsMixin:
return None
return self._settings_manager
+
+ def get_subsystem( self, request, *args, **kwargs ) -> Subsystem:
+ """ Assumes there is a required subsystem_id in kwargs """
+ try:
+ subsystem_id = int( kwargs.get( 'subsystem_id' ))
+ except (TypeError, ValueError):
+ raise BadRequest( 'Invalid subsystem id.' )
+ try:
+ return Subsystem.objects.get( id = subsystem_id )
+ except Subsystem.DoesNotExist:
+ raise Http404( request )
+
+
+class SubsystemAttributeMixin( SettingsMixin ):
+
+ def _create_attr_item_context_list( self ) -> List[SubsystemAttributeItemEditContext]:
+ attr_item_context_list = list()
+ subsystem_list = self.settings_manager().get_subsystems()
+ for subsystem in subsystem_list:
+ attr_item_context = SubsystemAttributeItemEditContext( subsystem = subsystem )
+ attr_item_context_list.append(attr_item_context )
+ continue
+ return attr_item_context_list
+
diff --git a/src/hi/apps/config/subsystem_attribute_edit_context.py b/src/hi/apps/config/subsystem_attribute_edit_context.py
new file mode 100644
index 00000000..a08f2d6f
--- /dev/null
+++ b/src/hi/apps/config/subsystem_attribute_edit_context.py
@@ -0,0 +1,86 @@
+"""
+Subsystem Attribute Edit Context - Subsystem-specific context for attribute editing templates.
+"""
+from typing import Any, Dict, Optional, Type
+
+from django.forms import ModelForm, BaseInlineFormSet
+
+from hi.apps.attribute.edit_context import AttributeItemEditContext, AttributePageEditContext
+from hi.apps.attribute.forms import AttributeUploadForm
+from hi.apps.attribute.models import AttributeModel
+
+from .forms import SubsystemAttributeFormSet
+
+from .models import Subsystem, SubsystemAttribute
+
+
+class SubsystemAttributePageEditContext(AttributePageEditContext):
+
+ def __init__( self, selected_subsystem_id : str ) -> None:
+ """Initialize context for Subsystem attribute editing."""
+ # Use 'subsystem' as owner_type to match URL patterns
+ super().__init__( owner_type = 'subsystem' )
+ self.selected_subsystem_id = selected_subsystem_id
+ return
+
+ @property
+ def content_body_template_name(self):
+ return 'config/panes/subsystem_edit_content_body.html'
+
+ def to_template_context(self) -> Dict[str, Any]:
+ template_context = super().to_template_context()
+ template_context.update({
+ "selected_subsystem_id": self.selected_subsystem_id,
+ })
+ return template_context
+
+
+class SubsystemAttributeItemEditContext(AttributeItemEditContext):
+
+ def __init__( self, subsystem: Subsystem ) -> None:
+ """Initialize context for Subsystem attribute editing."""
+ # Use 'subsystem' as owner_type to match URL patterns
+ super().__init__( owner_type = 'subsystem', owner = subsystem )
+ return
+
+ @property
+ def subsystem(self) -> Subsystem:
+ """Get the Subsystem instance (typed accessor)."""
+ return self.owner
+
+ @property
+ def content_body_template_name(self):
+ return 'config/panes/subsystem_edit_content_body.html'
+
+ @property
+ def attribute_model_subclass(self) -> Type[AttributeModel]:
+ return SubsystemAttribute
+
+ def create_owner_form( self, form_data : Optional[ Dict[str, Any] ] = None ) -> ModelForm:
+ # No viewable/editable Subsystem properties.
+ return None
+
+ def create_attribute_model( self ) -> AttributeModel:
+ return SubsystemAttribute( subsystem = self.subsystem )
+
+ def create_regular_attributes_formset(
+ self, form_data : Optional[ Dict[str, Any] ] = None ) -> BaseInlineFormSet:
+ return SubsystemAttributeFormSet(
+ form_data,
+ instance = self.subsystem,
+ prefix = self.formset_prefix,
+ form_kwargs={
+ 'show_as_editable': True,
+ 'allow_reordering': False, # Disable reordering for system-defined attributes
+ }
+ )
+
+ @property
+ def attribute_upload_form_class(self) -> Type[AttributeUploadForm]:
+ # No file uploads for Subsystem attributes (as of yet)
+ return None
+
+ @property
+ def file_upload_url(self) -> str:
+ # No file uploads for Subsystem attributes (as of yet)
+ return None
diff --git a/src/hi/apps/config/templates/config/pages/config_base.html b/src/hi/apps/config/templates/config/pages/config_base.html
index 7c1474da..0fedd3ec 100644
--- a/src/hi/apps/config/templates/config/pages/config_base.html
+++ b/src/hi/apps/config/templates/config/pages/config_base.html
@@ -1,13 +1,11 @@
<div class="hi-administration-content">
- <div class="h1 text-primary py-1">Administration</div>
-
<ul id="hi-config-tab" class="nav nav-tabs" role="tablist">
{% for config_page_type in request.config_page_type_list %}
<li class="nav-item">
<a id="hi-config-tab-{{ config_page_type }}" role="tab"
- class="nav-link {% if request.current_config_page_type == config_page_type %}active{% endif %}"
- href="{% url config_page_type.url_name %}"
- data-async="true">{{ config_page_type.label }}</a>
+ class="nav-link {% if request.current_config_page_type == config_page_type %}active{% endif %}"
+ href="{% url config_page_type.url_name %}"
+ data-async="true">{{ config_page_type.label }}</a>
</li>
{% endfor %}
</ul>
diff --git a/src/hi/apps/config/templates/config/panes/settings_form.html b/src/hi/apps/config/templates/config/panes/settings_form.html
deleted file mode 100644
index 715b9ab5..00000000
--- a/src/hi/apps/config/templates/config/panes/settings_form.html
+++ /dev/null
@@ -1,31 +0,0 @@
-<div id="hi-config-settings-form">
- <div>
- <form action="{% url 'config_settings' %}" method="post"
- class="form" data-async="#hi-config-settings-form" data-mode="replace">
- {% csrf_token %}
-
- <div class="d-flex justify-content-start my-2">
- <div class="align-self-center h3">System Settings</div>
- <div class="align-self-center h3 ml-4">
- <button id="hi-config-setting-button" type="submit" class="btn btn-primary"
- name="action" value="update">
- UPDATE
- </button>
- </div>
- </div>
-
- {% for subsystem_attribute_formset in subsystem_attribute_formset_list %}
- <div class="h5">{{ subsystem_attribute_formset.instance.name }}</div>
- {% include "attribute/panes/attribute_form.html" with attribute_formset=subsystem_attribute_formset %}
- <hr />
- {% endfor %}
-
- <div class="my-2">
- <button id="hi-config-setting-button" type="submit" class="btn btn-primary"
- name="action" value="update">
- UPDATE
- </button>
- </div>
- </form>
- </div>
-</div>
diff --git a/src/hi/apps/config/templates/config/panes/subsystem_edit_content_body.html b/src/hi/apps/config/templates/config/panes/subsystem_edit_content_body.html
new file mode 100644
index 00000000..ce452d40
--- /dev/null
+++ b/src/hi/apps/config/templates/config/panes/subsystem_edit_content_body.html
@@ -0,0 +1,66 @@
+{% extends "attribute/components/edit_content_body.html" %}
+{% load icons %}
+{% load attribute_extras %}
+{% comment %}
+Config Settings Content Body Fragment
+Contains the main content area - used by both initial load and antinode updates
+This is what gets replaced on form submission
+{% endcomment %}
+
+{% block additional_actions %}
+<h4 class="mb-0 text-muted">System Settings</h4>
+{% endblock %}
+
+{% block file_upload_button %}{% endblock %}
+
+{% block add_attribute_button %}{% endblock %}
+
+{% block files_section %}{% endblock %}
+
+{% block properties_section %}
+
+<!-- Vertical Tabbed Subsystem Interface -->
+<div class="d-flex mt-3">
+ <!-- Left Column: Vertical Navigation -->
+ <div class="flex-column">
+ <nav class="nav flex-column" id="subsystemTabs" role="tablist">
+ {% for multi_edit_form_data in multi_edit_form_data_list %}
+ <a class="nav-link {% if selected_subsystem_id == multi_edit_form_data.owner.id|stringformat:'s' %}active{% endif %}"
+ id="subsystem-{{ multi_edit_form_data.owner.id }}-tab"
+ data-toggle="tab"
+ data-subsystem-id="{{ multi_edit_form_data.owner.id }}"
+ data-config-settings-url="{% url 'config_settings' %}"
+ href="#subsystem-{{ multi_edit_form_data.owner.id }}-panel"
+ role="tab"
+ aria-controls="subsystem-{{ multi_edit_form_data.owner.id }}-panel"
+ aria-selected="{% if selected_subsystem_id == multi_edit_form_data.owner.id|stringformat:'s' %}true{% else %}false{% endif %}"
+ onclick="window.Hi.attr.updateFormAction('{% url 'config_settings' subsystem_id=multi_edit_form_data.owner.id %}', '{{ attr_page_context.container_html_id }}')">
+ {{ multi_edit_form_data.owner.name }}
+ {% if multi_edit_form_data.error_count > 0 %}
+ <span class="badge badge-danger ml-1">{{ multi_edit_form_data.error_count }}</span>
+ {% endif %}
+ </a>
+ {% endfor %}
+ </nav>
+ </div>
+
+ <!-- Right Column: Tab Content -->
+ <div class="flex-column flex-grow-1">
+ <div class="tab-content" id="subsystemTabContent">
+ {% for multi_edit_form_data in multi_edit_form_data_list %}
+ <div class="tab-pane fade {% if selected_subsystem_id == multi_edit_form_data.owner.id|stringformat:'s' %}show active{% endif %}"
+ id="subsystem-{{ multi_edit_form_data.owner.id }}-panel"
+ role="tabpanel"
+ aria-labelledby="subsystem-{{ multi_edit_form_data.owner.id }}-tab">
+
+ <!-- Subsystem content using existing attribute editing components -->
+ <div class="py-3">
+ {% include "attribute/components/regular_attribute_list.html" with regular_attributes_formset=multi_edit_form_data.formset attr_item_context=multi_edit_form_data.context title=multi_edit_form_data.owner.name%}
+ </div>
+
+ </div>
+ {% endfor %}
+ </div>
+ </div>
+</div>
+{% endblock %}
diff --git a/src/hi/apps/config/templates/config/panes/system_settings.html b/src/hi/apps/config/templates/config/panes/system_settings.html
index 1fb393df..8e8b986f 100644
--- a/src/hi/apps/config/templates/config/panes/system_settings.html
+++ b/src/hi/apps/config/templates/config/panes/system_settings.html
@@ -1 +1,32 @@
-{% include "config/panes/settings_form.html" %}
+{% comment %}
+Container-based wrapper with unique IDs for multi-instance support.
+Uses existing attr-v2-* components for consistency with Entity/Location editing.
+{% endcomment %}
+
+<!-- Root container for this attribute editing context -->
+<div id="{{ attr_page_context.container_html_id }}"
+ class="{{ DIVID.ATTR_V2_CONTAINER_CLASS }}">
+
+ <div class="{{ DIVID.ATTR_V2_FORM_CLASS }}">
+ <form id="{{ attr_page_context.form_html_id }}"
+ action="{% if selected_subsystem_id %}{% url 'config_settings' subsystem_id=selected_subsystem_id %}{% else %}{% url 'config_settings' %}{% endif %}"
+ method="post"
+ class="{{ DIVID.ATTR_V2_FORM_CLASS }} form">
+ {% csrf_token %}
+
+ <!-- Main content wrapper for antinode updates -->
+ <div id="{{ attr_page_context.content_html_id }}"
+ class="{{ DIVID.ATTR_V2_CONTENT_CLASS }}">
+ {% include "config/panes/subsystem_edit_content_body.html" %}
+ </div>
+ </form>
+ </div>
+
+</div>
+
+<script>
+// Initialize this specific container (for async-loaded content)
+if (window.Hi && window.Hi.attr && window.Hi.attr.initializeContainer) {
+ window.Hi.attr.initializeContainer('#{{ attr_page_context.container_html_id }}');
+}
+</script>
diff --git a/src/hi/apps/config/tests/synthetic_data.py b/src/hi/apps/config/tests/synthetic_data.py
new file mode 100644
index 00000000..d105bfe2
--- /dev/null
+++ b/src/hi/apps/config/tests/synthetic_data.py
@@ -0,0 +1,295 @@
+"""
+Synthetic data generators for Subsystem and SubsystemAttribute 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.config.models import Subsystem, SubsystemAttribute
+
+
+class SubsystemAttributeSyntheticData:
+ """Centralized synthetic data generators for subsystem attribute testing."""
+
+ @staticmethod
+ def create_test_subsystem(**kwargs) -> Subsystem:
+ """Create a test subsystem with reasonable defaults."""
+ # Generate unique name and key to avoid constraint violations
+ unique_id = str(uuid.uuid4())[:8]
+ defaults = {
+ 'name': f'Test Subsystem {unique_id}',
+ 'subsystem_key': f'test_subsystem_{unique_id}',
+ }
+ defaults.update(kwargs)
+ return Subsystem.objects.create(**defaults)
+
+ @staticmethod
+ def create_test_text_attribute(subsystem: Optional[Subsystem] = None, **kwargs) -> SubsystemAttribute:
+ """Create a text attribute with reasonable defaults."""
+ if subsystem is None:
+ subsystem = SubsystemAttributeSyntheticData.create_test_subsystem()
+
+ defaults = {
+ 'subsystem': subsystem,
+ 'name': 'test_property',
+ 'value': 'test value',
+ 'attribute_type_str': str(AttributeType.PREDEFINED), # Subsystems typically use PREDEFINED attributes
+ 'value_type_str': str(AttributeValueType.TEXT),
+ 'setting_key': 'test.property.key',
+ }
+ defaults.update(kwargs)
+ return SubsystemAttribute.objects.create(**defaults)
+
+ @staticmethod
+ def create_test_secret_attribute(subsystem: Optional[Subsystem] = None, **kwargs) -> SubsystemAttribute:
+ """Create a secret attribute with reasonable defaults."""
+ if subsystem is None:
+ subsystem = SubsystemAttributeSyntheticData.create_test_subsystem()
+
+ defaults = {
+ 'subsystem': subsystem,
+ 'name': 'api_key',
+ 'value': 'secret_api_key_12345',
+ 'attribute_type_str': str(AttributeType.PREDEFINED),
+ 'value_type_str': str(AttributeValueType.SECRET),
+ 'setting_key': 'api.key.secret',
+ }
+ defaults.update(kwargs)
+ return SubsystemAttribute.objects.create(**defaults)
+
+ @staticmethod
+ def create_test_config_attribute(subsystem: Optional[Subsystem] = None, **kwargs) -> SubsystemAttribute:
+ """Create a configuration attribute with reasonable defaults."""
+ if subsystem is None:
+ subsystem = SubsystemAttributeSyntheticData.create_test_subsystem()
+
+ defaults = {
+ 'subsystem': subsystem,
+ 'name': 'polling_interval',
+ 'value': '300',
+ 'attribute_type_str': str(AttributeType.PREDEFINED),
+ 'value_type_str': str(AttributeValueType.TEXT),
+ 'setting_key': 'polling.interval.config',
+ }
+ defaults.update(kwargs)
+ return SubsystemAttribute.objects.create(**defaults)
+
+ @staticmethod
+ def create_subsystem_with_mixed_attributes(**subsystem_kwargs) -> Subsystem:
+ """Create a subsystem with a variety of attribute types for comprehensive testing."""
+ subsystem = SubsystemAttributeSyntheticData.create_test_subsystem(**subsystem_kwargs)
+
+ # Create various attribute types typical for subsystems
+ SubsystemAttributeSyntheticData.create_test_text_attribute(
+ subsystem=subsystem, name='endpoint_url', value='https://api.test.com',
+ setting_key='endpoint.url.setting'
+ )
+ SubsystemAttributeSyntheticData.create_test_secret_attribute(
+ subsystem=subsystem, name='auth_token', value='super_secret_token',
+ setting_key='auth.token.setting'
+ )
+ SubsystemAttributeSyntheticData.create_test_config_attribute(
+ subsystem=subsystem, name='timeout', value='30',
+ setting_key='timeout.config.setting'
+ )
+
+ return subsystem
+
+ @staticmethod
+ def create_multiple_subsystems_scenario() -> List[Subsystem]:
+ """Create multiple subsystems for multi-editing scenario testing."""
+ subsystems = []
+
+ # Weather subsystem
+ weather = SubsystemAttributeSyntheticData.create_test_subsystem(
+ name="Weather Service",
+ subsystem_key="weather_service"
+ )
+ SubsystemAttributeSyntheticData.create_test_text_attribute(
+ subsystem=weather, name='api_url', value='https://weather.api.com',
+ setting_key='weather.api.url'
+ )
+ SubsystemAttributeSyntheticData.create_test_secret_attribute(
+ subsystem=weather, name='api_key', value='weather_api_key',
+ setting_key='weather.api.key'
+ )
+ subsystems.append(weather)
+
+ # Another subsystem
+ other = SubsystemAttributeSyntheticData.create_test_subsystem(
+ name="Other Service",
+ subsystem_key="other_service"
+ )
+ SubsystemAttributeSyntheticData.create_test_config_attribute(
+ subsystem=other, name='refresh_rate', value='60',
+ setting_key='other.refresh.rate'
+ )
+ subsystems.append(other)
+
+ return subsystems
+
+ @staticmethod
+ def create_form_data_for_subsystem_multi_edit(subsystem_list: List[Subsystem], **overrides) -> Dict[str, Any]:
+ """Create complete form data dictionary for multi-subsystem editing form submissions.
+
+ This handles the complex multi-formset scenario unique to config module.
+ """
+ form_data = {}
+
+ # Add data for each subsystem
+ for subsystem in subsystem_list:
+ # Get attributes for this subsystem (non-file attributes)
+ regular_attributes = list(subsystem.attributes.exclude(
+ value_type_str=str(AttributeValueType.FILE)
+ ).order_by('id'))
+
+ # Use subsystem-specific prefix
+ prefix = f'subsystem-{subsystem.id}'
+
+ # Formset management form data for this subsystem
+ subsystem_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 this subsystem
+ for i, attr in enumerate(regular_attributes):
+ subsystem_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(subsystem_formset_data)
+
+ # Apply any overrides
+ form_data.update(overrides)
+ return form_data
+
+ @staticmethod
+ def create_form_data_for_single_subsystem_edit(subsystem: Subsystem, **overrides) -> Dict[str, Any]:
+ """Create form data for single subsystem editing (simpler scenario)."""
+ # Get attributes for this subsystem (non-file attributes)
+ regular_attributes = list(subsystem.attributes.exclude(
+ value_type_str=str(AttributeValueType.FILE)
+ ).order_by('id'))
+
+ # Use subsystem-specific prefix
+ prefix = f'subsystem-{subsystem.id}'
+
+ # Formset management form data
+ form_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):
+ form_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,
+ })
+
+ # Apply any overrides
+ form_data.update(overrides)
+ return form_data
+
+ @staticmethod
+ def create_formset_data_for_attributes(attributes: List[SubsystemAttribute], subsystem: Subsystem) -> Dict[str, Any]:
+ """Create formset data dictionary for attribute formset submissions."""
+ prefix = f'subsystem-{subsystem.id}'
+ 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_invalid_form_data_multi_subsystem(subsystem_list: List[Subsystem]) -> Dict[str, Any]:
+ """Create invalid form data for multi-subsystem testing."""
+ form_data = SubsystemAttributeSyntheticData.create_form_data_for_subsystem_multi_edit(
+ subsystem_list
+ )
+
+ # Make first subsystem's first attribute have invalid data
+ if subsystem_list:
+ first_subsystem = subsystem_list[0]
+ prefix = f'subsystem-{first_subsystem.id}'
+ # Set empty name which should be invalid
+ form_data[f'{prefix}-0-name'] = ''
+
+ return form_data
+
+ @staticmethod
+ def create_system_configuration_scenario() -> Subsystem:
+ """Create a realistic system configuration scenario for testing."""
+ subsystem = SubsystemAttributeSyntheticData.create_test_subsystem(
+ name="System Configuration",
+ subsystem_key="system_config"
+ )
+
+ # Create system-level configuration attributes
+ SubsystemAttributeSyntheticData.create_test_text_attribute(
+ subsystem=subsystem,
+ name='system_name',
+ value='Home Automation System',
+ attribute_type_str=str(AttributeType.PREDEFINED),
+ setting_key='system.name.config'
+ )
+
+ SubsystemAttributeSyntheticData.create_test_config_attribute(
+ subsystem=subsystem,
+ name='log_level',
+ value='INFO',
+ setting_key='system.log.level'
+ )
+
+ SubsystemAttributeSyntheticData.create_test_secret_attribute(
+ subsystem=subsystem,
+ name='encryption_key',
+ value='system_encryption_key_123',
+ setting_key='system.encryption.key'
+ )
+
+ return subsystem
+
+ @staticmethod
+ def create_test_image_file() -> SimpleUploadedFile:
+ """Create a test image file for file upload testing."""
+ return SimpleUploadedFile(
+ "test_config_image.jpg",
+ b"fake jpeg image content for testing",
+ content_type="image/jpeg"
+ )
+
+ @staticmethod
+ def create_test_config_file() -> SimpleUploadedFile:
+ """Create a test configuration file for file upload testing."""
+ return SimpleUploadedFile(
+ "config.json",
+ b'{"test": "configuration", "enabled": true}',
+ content_type="application/json"
+ )
+
diff --git a/src/hi/apps/config/tests/test_config_attribute_framework.py b/src/hi/apps/config/tests/test_config_attribute_framework.py
new file mode 100644
index 00000000..9bab7dbe
--- /dev/null
+++ b/src/hi/apps/config/tests/test_config_attribute_framework.py
@@ -0,0 +1,456 @@
+"""
+Concrete test implementations for Subsystem attribute editing framework.
+
+These tests extend the abstract base classes to provide comprehensive testing
+of the attribute framework as implemented for Subsystem models. Tests both the
+framework components and Subsystem-specific customizations, including the unique
+multi-formset scenario.
+
+Following project testing guidelines:
+- No mocked objects, use real Subsystem and SubsystemAttribute models
+- Focus on high-value business logic and integration points
+- Use SubsystemAttributeSyntheticData for test data generation
+- Test meaningful Subsystem-specific edge cases and multi-editing workflows
+"""
+import logging
+
+from hi.apps.attribute.tests.attribute_framework_test_base import (
+ AttributeEditFormHandlerTestMixin,
+ AttributeEditResponseRendererTestMixin,
+ AttributeEditTemplateContextBuilderTestMixin,
+)
+from hi.testing.base_test_case import BaseTestCase
+from hi.apps.attribute.enums import AttributeType, AttributeValueType
+from hi.apps.attribute.models import AttributeModel
+from hi.apps.config.subsystem_attribute_edit_context import (
+ SubsystemAttributeItemEditContext,
+ SubsystemAttributePageEditContext
+)
+from hi.apps.config.models import SubsystemAttribute
+from hi.apps.config.tests.synthetic_data import SubsystemAttributeSyntheticData
+
+logging.disable(logging.CRITICAL)
+
+
+class SubsystemAttributeEditFormHandlerTest(AttributeEditFormHandlerTestMixin, BaseTestCase):
+ """Test AttributeEditFormHandler with Subsystem-specific implementations."""
+
+ def create_owner_instance(self, **kwargs):
+ """Create Subsystem instance for testing."""
+ return SubsystemAttributeSyntheticData.create_test_subsystem(**kwargs)
+
+ def create_attribute_instance(self, owner, **kwargs) -> AttributeModel:
+ """Create SubsystemAttribute instance for testing."""
+ defaults = {
+ 'subsystem': owner,
+ 'name': 'test_attribute',
+ 'value': 'test_value',
+ 'attribute_type_str': str(AttributeType.PREDEFINED), # Subsystems use SYSTEM attributes
+ 'value_type_str': kwargs.pop('value_type_str', str(AttributeValueType.TEXT)),
+ }
+ defaults.update(kwargs)
+ return SubsystemAttribute.objects.create(**defaults)
+
+ def create_item_edit_context(self, owner):
+ """Create SubsystemAttributeItemEditContext for testing."""
+ return SubsystemAttributeItemEditContext(subsystem=owner)
+
+ def create_valid_form_data(self, owner, **overrides):
+ """Create valid form data for Subsystem editing."""
+ return SubsystemAttributeSyntheticData.create_form_data_for_single_subsystem_edit(
+ owner, **overrides
+ )
+
+ def create_invalid_form_data(self, owner):
+ """Create invalid form data for Subsystem editing."""
+ form_data = SubsystemAttributeSyntheticData.create_form_data_for_single_subsystem_edit(owner)
+ prefix = f'subsystem-{owner.id}'
+
+ # Create a scenario that will actually fail validation:
+ # Try to change the name of a PREDEFINED attribute, which is not allowed
+ if f'{prefix}-0-id' in form_data:
+ # Change the name of an existing PREDEFINED attribute (this should fail validation)
+ form_data[f'{prefix}-0-name'] = 'invalid_changed_name'
+ # Ensure it has a value to trigger validation
+ form_data[f'{prefix}-0-value'] = 'some value'
+ else:
+ # Fallback: create malformed formset data
+ form_data[f'{prefix}-TOTAL_FORMS'] = 'invalid_number'
+
+ return form_data
+
+ def test_subsystem_no_owner_form_behavior(self):
+ """Test Subsystem-specific no owner form behavior - Subsystem owner form logic."""
+ subsystem = self.create_owner_instance(name="No Owner Form Test")
+ context = self.create_item_edit_context(subsystem)
+ handler = self._get_handler()
+
+ form_data = handler.create_edit_form_data(attr_item_context=context)
+
+ # Subsystem should not have owner form (no editable properties on Subsystem itself)
+ self.assertIsNone(form_data.owner_form)
+ self.assertIsNotNone(form_data.regular_attributes_formset)
+
+ def test_subsystem_system_attribute_validation(self):
+ """Test Subsystem SYSTEM attribute type validation - Subsystem attribute validation."""
+ subsystem = self.create_owner_instance(name="System Attribute Test")
+
+ # Create SYSTEM type attribute
+ self.create_attribute_instance(
+ subsystem,
+ name="system_config",
+ value="config_value",
+ attribute_type_str=str(AttributeType.PREDEFINED)
+ )
+
+ context = self.create_item_edit_context(subsystem)
+ handler = self._get_handler()
+
+ # Test valid system attribute data
+ valid_data = self.create_valid_form_data(subsystem)
+ form_data = handler.create_edit_form_data(
+ attr_item_context=context,
+ form_data=valid_data
+ )
+
+ is_valid = handler.validate_forms(edit_form_data=form_data)
+ self.assertTrue(is_valid)
+
+ def test_subsystem_attribute_formset_patterns(self):
+ """Test Subsystem-specific formset patterns - Subsystem formset logic."""
+ subsystem = self.create_owner_instance(name="Formset Test Subsystem")
+
+ # Create system configuration attributes
+ self.create_attribute_instance(
+ subsystem, name="endpoint", value="https://api.system.com",
+ attribute_type_str=str(AttributeType.PREDEFINED)
+ )
+ self.create_attribute_instance(
+ subsystem, name="secret_key", value="secret123",
+ value_type_str=str(AttributeValueType.SECRET),
+ attribute_type_str=str(AttributeType.PREDEFINED)
+ )
+
+ context = self.create_item_edit_context(subsystem)
+ handler = self._get_handler()
+
+ form_data = handler.create_edit_form_data(attr_item_context=context)
+
+ # All attributes should be in regular formset (no file separation for subsystems)
+ # Check if formset has initial data or get from the formset's queryset
+ if form_data.regular_attributes_formset.initial:
+ formset_data = list(form_data.regular_attributes_formset.initial)
+ formset_names = [attr.get('name') for attr in formset_data]
+ else:
+ # Get names from the formset's queryset
+ formset_names = [attr.name for attr in form_data.regular_attributes_formset.queryset]
+
+ self.assertIn("endpoint", formset_names)
+ self.assertIn("secret_key", formset_names)
+
+ # No file attributes expected for subsystems
+ self.assertEqual(form_data.file_attributes.count(), 0)
+
+ def test_subsystem_no_file_upload_support(self):
+ """Test Subsystem file upload handling - Subsystem file operations."""
+ subsystem = self.create_owner_instance(name="No File Upload Subsystem")
+ context = self.create_item_edit_context(subsystem)
+
+ # Subsystem should not support file uploads
+ self.assertIsNone(context.attribute_upload_form_class)
+ self.assertFalse(context.uses_file_uploads)
+ self.assertIsNone(context.file_upload_url)
+
+ def test_subsystem_multi_formset_workflow(self):
+ """Test Subsystem multi-formset workflow - unique to config module."""
+ # Create multiple subsystems for multi-editing scenario
+ subsystem_list = SubsystemAttributeSyntheticData.create_multiple_subsystems_scenario()
+
+ handler = self._get_handler()
+
+ # Create multi-edit form data
+ SubsystemAttributeSyntheticData.create_form_data_for_subsystem_multi_edit(
+ subsystem_list
+ )
+
+ # Test multi-edit form data creation (would be used by multi-edit views)
+ item_context_list = [
+ SubsystemAttributeItemEditContext(subsystem=sub) for sub in subsystem_list
+ ]
+
+ multi_edit_form_data_list = handler.create_multi_edit_form_data(
+ attr_item_context_list=item_context_list
+ )
+
+ # Should create form data for each subsystem
+ self.assertEqual(len(multi_edit_form_data_list), len(subsystem_list))
+
+ # Each should have appropriate structure
+ for form_data in multi_edit_form_data_list:
+ self.assertIsNotNone(form_data.regular_attributes_formset)
+ self.assertIsNone(form_data.owner_form) # No owner forms for subsystems
+
+ def test_subsystem_system_level_configuration(self):
+ """Test system-level configuration scenarios - Subsystem system config."""
+ subsystem = SubsystemAttributeSyntheticData.create_system_configuration_scenario()
+ context = self.create_item_edit_context(subsystem)
+ handler = self._get_handler()
+
+ # Test form creation with system configuration
+ form_data = handler.create_edit_form_data(attr_item_context=context)
+
+ # Should handle system attributes properly
+ self.assertIsNotNone(form_data.regular_attributes_formset)
+
+ # Test validation of system configuration
+ valid_data = self.create_valid_form_data(subsystem)
+ bound_form_data = handler.create_edit_form_data(
+ attr_item_context=context,
+ form_data=valid_data
+ )
+
+ is_valid = handler.validate_forms(edit_form_data=bound_form_data)
+ self.assertTrue(is_valid)
+
+ def _get_handler(self):
+ """Get handler instance for testing."""
+ from hi.apps.attribute.edit_form_handler import AttributeEditFormHandler
+ return AttributeEditFormHandler()
+
+
+class SubsystemAttributeEditResponseRendererTest(AttributeEditResponseRendererTestMixin, BaseTestCase):
+ """Test AttributeEditResponseRenderer with Subsystem-specific implementations."""
+
+ def create_owner_instance(self, **kwargs):
+ """Create Subsystem instance for testing."""
+ return SubsystemAttributeSyntheticData.create_test_subsystem(**kwargs)
+
+ def create_attribute_instance(self, owner, **kwargs) -> AttributeModel:
+ """Create SubsystemAttribute instance for testing."""
+ defaults = {
+ 'subsystem': owner,
+ 'name': 'test_attribute',
+ 'value': 'test_value',
+ 'attribute_type_str': str(AttributeType.PREDEFINED),
+ 'value_type_str': str(AttributeValueType.TEXT),
+ }
+ defaults.update(kwargs)
+ return SubsystemAttribute.objects.create(**defaults)
+
+ def create_item_edit_context(self, owner):
+ """Create SubsystemAttributeItemEditContext for testing."""
+ return SubsystemAttributeItemEditContext(subsystem=owner)
+
+ def create_valid_form_data(self, owner, **overrides):
+ """Create valid form data for Subsystem editing."""
+ return SubsystemAttributeSyntheticData.create_form_data_for_single_subsystem_edit(
+ owner, **overrides
+ )
+
+ def create_invalid_form_data(self, owner):
+ """Create invalid form data for Subsystem editing."""
+ form_data = SubsystemAttributeSyntheticData.create_form_data_for_single_subsystem_edit(owner)
+ prefix = f'subsystem-{owner.id}'
+
+ # Create a scenario that will actually fail validation:
+ # Try to change the name of a PREDEFINED attribute, which is not allowed
+ if f'{prefix}-0-id' in form_data:
+ # Change the name of an existing PREDEFINED attribute (this should fail validation)
+ form_data[f'{prefix}-0-name'] = 'invalid_changed_name'
+ # Ensure it has a value to trigger validation
+ form_data[f'{prefix}-0-value'] = 'some value'
+ else:
+ # Fallback: create malformed formset data
+ form_data[f'{prefix}-TOTAL_FORMS'] = 'invalid_number'
+
+ return form_data
+
+ def test_subsystem_specific_response_content(self):
+ """Test Subsystem-specific response content and templates - Subsystem response handling."""
+ subsystem = self.create_owner_instance(name="Response Test Subsystem")
+ context = self.create_item_edit_context(subsystem)
+ renderer = self._get_renderer()
+
+ request = self.factory.post('/config/subsystem/test/')
+ request.session = self._get_mock_session()
+
+ response = renderer.render_form_success_response(
+ attr_item_context=context,
+ request=request,
+ message=None # Use default message
+ )
+
+ # Should use Subsystem-specific template context
+ self.assertEqual(response.status_code, 200)
+
+ # Verify response contains Subsystem-specific data
+ import json
+ data = json.loads(response.content)
+ self.assertIsInstance(data, dict)
+
+ def test_subsystem_multi_edit_response_patterns(self):
+ """Test Subsystem multi-edit response patterns - unique to config module."""
+ subsystem_list = SubsystemAttributeSyntheticData.create_multiple_subsystems_scenario()
+ page_context = SubsystemAttributePageEditContext("test_subsystem")
+ item_context_list = [
+ SubsystemAttributeItemEditContext(subsystem=sub) for sub in subsystem_list
+ ]
+
+ renderer = self._get_renderer()
+ handler = self._get_handler()
+
+ # Create multi-edit form data list
+ multi_edit_form_data_list = handler.create_multi_edit_form_data(
+ attr_item_context_list=item_context_list
+ )
+
+ request = self.factory.post('/config/subsystem/multi/test/')
+ request.session = self._get_mock_session()
+
+ response = renderer.render_form_success_response_multi(
+ attr_page_context=page_context,
+ multi_edit_form_data_list=multi_edit_form_data_list,
+ request=request,
+ message=None # Use default message
+ )
+
+ # Should handle multi-edit success response
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(response['Content-Type'], 'application/json')
+
+ def test_subsystem_no_file_upload_response(self):
+ """Test Subsystem file upload response handling - no file support."""
+ subsystem = self.create_owner_instance(name="No File Response Subsystem")
+ context = self.create_item_edit_context(subsystem)
+
+ # Subsystem contexts don't support file uploads
+ self.assertIsNone(context.attribute_upload_form_class)
+ self.skipTest("File uploads not supported by Subsystem context")
+
+ def _get_renderer(self):
+ """Get renderer instance for testing."""
+ from hi.apps.attribute.edit_response_renderer import AttributeEditResponseRenderer
+ return AttributeEditResponseRenderer()
+
+ def _get_handler(self):
+ """Get handler instance for testing."""
+ from hi.apps.attribute.edit_form_handler import AttributeEditFormHandler
+ return AttributeEditFormHandler()
+
+ def _get_mock_session(self):
+ """Get mock session for testing."""
+ from hi.testing.base_test_case import MockSession
+ return MockSession()
+
+
+class SubsystemAttributeEditTemplateContextBuilderTest(AttributeEditTemplateContextBuilderTestMixin, BaseTestCase):
+ """Test AttributeEditTemplateContextBuilder with Subsystem-specific implementations."""
+
+ def create_owner_instance(self, **kwargs):
+ """Create Subsystem instance for testing."""
+ return SubsystemAttributeSyntheticData.create_test_subsystem(**kwargs)
+
+ def create_attribute_instance(self, owner, **kwargs) -> AttributeModel:
+ """Create SubsystemAttribute instance for testing."""
+ defaults = {
+ 'subsystem': owner,
+ 'name': 'test_attribute',
+ 'value': 'test_value',
+ 'attribute_type_str': str(AttributeType.PREDEFINED),
+ 'value_type_str': str(AttributeValueType.TEXT),
+ }
+ defaults.update(kwargs)
+ return SubsystemAttribute.objects.create(**defaults)
+
+ def create_item_edit_context(self, owner):
+ """Create SubsystemAttributeItemEditContext for testing."""
+ return SubsystemAttributeItemEditContext(subsystem=owner)
+
+ def create_valid_form_data(self, owner, **overrides):
+ """Create valid form data for Subsystem editing."""
+ return SubsystemAttributeSyntheticData.create_form_data_for_single_subsystem_edit(
+ owner, **overrides
+ )
+
+ def create_invalid_form_data(self, owner):
+ """Create invalid form data for Subsystem editing."""
+ form_data = SubsystemAttributeSyntheticData.create_form_data_for_single_subsystem_edit(owner)
+ prefix = f'subsystem-{owner.id}'
+ form_data[f'{prefix}-0-name'] = ''
+ return form_data
+
+ def test_subsystem_specific_template_context_keys(self):
+ """Test Subsystem-specific template context keys - Subsystem template integration."""
+ subsystem = self.create_owner_instance(name="Template Context Subsystem")
+ context = self.create_item_edit_context(subsystem)
+ builder = self._get_builder()
+
+ template_context = builder.build_initial_template_context(
+ attr_item_context=context
+ )
+
+ # Should include Subsystem-specific keys
+ self.assertIn('subsystem', template_context)
+ self.assertIs(template_context['subsystem'], subsystem)
+
+ # Should NOT include owner form (Subsystem has no editable properties)
+ self.assertIsNone(template_context.get('owner_form'))
+ self.assertIsNone(template_context.get('subsystem_form'))
+
+ # Should include generic keys
+ self.assertIn('attr_item_context', template_context)
+ self.assertIn('regular_attributes_formset', template_context)
+
+ def test_subsystem_multi_edit_template_context(self):
+ """Test Subsystem multi-edit template context - unique to config module."""
+ subsystem_list = SubsystemAttributeSyntheticData.create_multiple_subsystems_scenario()
+ page_context = SubsystemAttributePageEditContext("test_subsystem")
+ item_context_list = [
+ SubsystemAttributeItemEditContext(subsystem=sub) for sub in subsystem_list
+ ]
+
+ builder = self._get_builder()
+
+ template_context = builder.build_initial_template_context_multi(
+ attr_page_context=page_context,
+ attr_item_context_list=item_context_list
+ )
+
+ # Should include multi-edit context
+ self.assertIn('multi_edit_form_data_list', template_context)
+ self.assertIn('attr_page_context', template_context)
+
+ # Should have form data for each subsystem
+ multi_edit_data = template_context['multi_edit_form_data_list']
+ self.assertEqual(len(multi_edit_data), len(subsystem_list))
+
+ def test_subsystem_system_attribute_context_assembly(self):
+ """Test Subsystem system attribute context assembly - system attribute handling."""
+ subsystem = SubsystemAttributeSyntheticData.create_system_configuration_scenario()
+ context = self.create_item_edit_context(subsystem)
+ builder = self._get_builder()
+
+ template_context = builder.build_initial_template_context(
+ attr_item_context=context
+ )
+
+ # Should properly handle system attributes
+ formset = template_context['regular_attributes_formset']
+ self.assertIsNotNone(formset)
+
+ # Should include subsystem in context
+ self.assertIn('subsystem', template_context)
+ self.assertEqual(template_context['subsystem'].name, "System Configuration")
+
+ def _get_builder(self):
+ """Get builder instance for testing."""
+ from hi.apps.attribute.edit_template_context_builder import AttributeEditTemplateContextBuilder
+ return AttributeEditTemplateContextBuilder()
+
+ def _get_handler(self):
+ """Get handler instance for testing."""
+ from hi.apps.attribute.edit_form_handler import AttributeEditFormHandler
+ return AttributeEditFormHandler()
+
+
+
diff --git a/src/hi/apps/config/tests/test_config_multi_attribute_framework.py b/src/hi/apps/config/tests/test_config_multi_attribute_framework.py
new file mode 100644
index 00000000..67adf4b6
--- /dev/null
+++ b/src/hi/apps/config/tests/test_config_multi_attribute_framework.py
@@ -0,0 +1,366 @@
+"""
+Multi-instance attribute editing framework tests for config module.
+
+These tests are specifically designed for the config module's multi-edit architecture,
+where multiple subsystems are edited simultaneously.
+"""
+from typing import List, Dict, Any
+
+from hi.testing.base_test_case import MockRequest, MockSession
+from django.http import QueryDict
+
+from hi.testing.base_test_case import BaseTestCase
+from hi.apps.attribute.tests.attribute_multi_framework_test_base import (
+ AttributeMultiEditFormHandlerTestMixin,
+ AttributeMultiEditResponseRendererTestMixin,
+ AttributeMultiEditTemplateContextBuilderTestMixin,
+ AttributeMultiEditViewMixinTestMixin,
+)
+
+from hi.apps.attribute.enums import AttributeType, AttributeValueType
+from hi.apps.attribute.models import AttributeModel
+from hi.apps.attribute.edit_form_handler import AttributeEditFormHandler
+from hi.apps.attribute.edit_response_renderer import AttributeEditResponseRenderer
+from hi.apps.attribute.edit_template_context_builder import AttributeEditTemplateContextBuilder
+from hi.apps.attribute.view_mixins import AttributeMultiEditViewMixin
+
+from hi.apps.config.models import Subsystem, SubsystemAttribute
+from hi.apps.config.subsystem_attribute_edit_context import (
+ SubsystemAttributeItemEditContext,
+ SubsystemAttributePageEditContext,
+)
+from hi.apps.config.tests.synthetic_data import SubsystemAttributeSyntheticData
+
+
+class SubsystemMultiAttributeEditFormHandlerTest(AttributeMultiEditFormHandlerTestMixin, BaseTestCase):
+ """Test AttributeEditFormHandler with Subsystem-specific multi-edit implementations."""
+
+ def create_owner_instance_list(self, **kwargs) -> List[Subsystem]:
+ """Create multiple Subsystem instances for multi-edit testing."""
+ return SubsystemAttributeSyntheticData.create_multiple_subsystems_scenario()
+
+ def create_attribute_instance(self, owner: Subsystem, **kwargs) -> AttributeModel:
+ """Create SubsystemAttribute instance for testing."""
+ defaults = {
+ 'subsystem': owner,
+ 'name': 'test_attribute',
+ 'value': 'test_value',
+ 'attribute_type_str': str(AttributeType.PREDEFINED),
+ 'value_type_str': kwargs.pop('value_type_str', str(AttributeValueType.TEXT)),
+ 'setting_key': 'test.setting.key',
+ }
+ defaults.update(kwargs)
+ return SubsystemAttribute.objects.create(**defaults)
+
+ def create_item_edit_context(self, owner: Subsystem) -> SubsystemAttributeItemEditContext:
+ """Create SubsystemAttributeItemEditContext for testing."""
+ return SubsystemAttributeItemEditContext(subsystem=owner)
+
+ def create_page_edit_context(self, owner_list: List[Subsystem]) -> SubsystemAttributePageEditContext:
+ """Create SubsystemAttributePageEditContext for multi-edit testing."""
+ # Page context only needs selected_subsystem_id, not the full list
+ selected_subsystem_id = str(owner_list[0].id) if owner_list else None
+ return SubsystemAttributePageEditContext(selected_subsystem_id=selected_subsystem_id)
+
+ def create_multi_valid_form_data(self, owner_list: List[Subsystem], **overrides) -> Dict[str, Any]:
+ """Create valid form data for multi-edit scenarios."""
+ return SubsystemAttributeSyntheticData.create_form_data_for_subsystem_multi_edit(
+ owner_list, **overrides
+ )
+
+ def create_multi_invalid_form_data(self, owner_list: List[Subsystem]) -> Dict[str, Any]:
+ """Create invalid form data for multi-edit scenarios."""
+ return SubsystemAttributeSyntheticData.create_invalid_form_data_multi_subsystem(owner_list)
+
+ def test_subsystem_multi_edit_formset_patterns(self):
+ """Test Subsystem-specific multi-edit formset patterns - Subsystem multi formset logic."""
+ owner_list = self.create_owner_instance_list()
+ item_context_list = [self.create_item_edit_context(owner) for owner in owner_list]
+
+ handler = AttributeEditFormHandler()
+ multi_edit_form_data_list = handler.create_multi_edit_form_data(
+ attr_item_context_list=item_context_list
+ )
+
+ # Should create form data for each subsystem
+ self.assertEqual(len(multi_edit_form_data_list), len(owner_list))
+
+ # Each subsystem should have its own formset
+ for i, form_data in enumerate(multi_edit_form_data_list):
+ self.assertIsNotNone(form_data.regular_attributes_formset)
+ # Subsystems don't have owner forms
+ self.assertIsNone(form_data.owner_form)
+
+ # Check formset prefix matches subsystem ID
+ expected_prefix = f'subsystem-{owner_list[i].id}'
+ self.assertEqual(form_data.regular_attributes_formset.prefix, expected_prefix)
+
+ def test_subsystem_multi_edit_system_attributes(self):
+ """Test Subsystem multi-edit with PREDEFINED attribute types - system attribute handling."""
+ # Create subsystems with PREDEFINED attributes
+ subsystem1 = SubsystemAttributeSyntheticData.create_test_subsystem(
+ name="System Config 1", subsystem_key="system_config_1"
+ )
+ SubsystemAttributeSyntheticData.create_test_text_attribute(
+ subsystem=subsystem1,
+ name='system_name',
+ value='Config System 1',
+ attribute_type_str=str(AttributeType.PREDEFINED)
+ )
+
+ subsystem2 = SubsystemAttributeSyntheticData.create_test_subsystem(
+ name="System Config 2", subsystem_key="system_config_2"
+ )
+ SubsystemAttributeSyntheticData.create_test_text_attribute(
+ subsystem=subsystem2,
+ name='system_name',
+ value='Config System 2',
+ attribute_type_str=str(AttributeType.PREDEFINED)
+ )
+
+ owner_list = [subsystem1, subsystem2]
+ item_context_list = [self.create_item_edit_context(owner) for owner in owner_list]
+
+ handler = AttributeEditFormHandler()
+ multi_edit_form_data_list = handler.create_multi_edit_form_data(
+ attr_item_context_list=item_context_list
+ )
+
+ # Should handle PREDEFINED attributes properly
+ for form_data in multi_edit_form_data_list:
+ formset = form_data.regular_attributes_formset
+ # Should have forms for existing attributes
+ self.assertGreater(len(formset.forms), 0)
+
+
+class SubsystemMultiAttributeEditResponseRendererTest(AttributeMultiEditResponseRendererTestMixin, BaseTestCase):
+ """Test AttributeEditResponseRenderer with Subsystem-specific multi-edit implementations."""
+
+ def create_owner_instance_list(self, **kwargs) -> List[Subsystem]:
+ """Create multiple Subsystem instances for multi-edit testing."""
+ return SubsystemAttributeSyntheticData.create_multiple_subsystems_scenario()
+
+ def create_attribute_instance(self, owner: Subsystem, **kwargs) -> AttributeModel:
+ """Create SubsystemAttribute instance for testing."""
+ defaults = {
+ 'subsystem': owner,
+ 'name': 'test_attribute',
+ 'value': 'test_value',
+ 'attribute_type_str': str(AttributeType.PREDEFINED),
+ 'value_type_str': kwargs.pop('value_type_str', str(AttributeValueType.TEXT)),
+ 'setting_key': 'test.setting.key',
+ }
+ defaults.update(kwargs)
+ return SubsystemAttribute.objects.create(**defaults)
+
+ def create_item_edit_context(self, owner: Subsystem) -> SubsystemAttributeItemEditContext:
+ """Create SubsystemAttributeItemEditContext for testing."""
+ return SubsystemAttributeItemEditContext(subsystem=owner)
+
+ def create_page_edit_context(self, owner_list: List[Subsystem]) -> SubsystemAttributePageEditContext:
+ """Create SubsystemAttributePageEditContext for multi-edit testing."""
+ # Page context only needs selected_subsystem_id, not the full list
+ selected_subsystem_id = str(owner_list[0].id) if owner_list else None
+ return SubsystemAttributePageEditContext(selected_subsystem_id=selected_subsystem_id)
+
+ def create_multi_valid_form_data(self, owner_list: List[Subsystem], **overrides) -> Dict[str, Any]:
+ """Create valid form data for multi-edit scenarios."""
+ return SubsystemAttributeSyntheticData.create_form_data_for_subsystem_multi_edit(
+ owner_list, **overrides
+ )
+
+ def create_multi_invalid_form_data(self, owner_list: List[Subsystem]) -> Dict[str, Any]:
+ """Create invalid form data for multi-edit scenarios."""
+ return SubsystemAttributeSyntheticData.create_invalid_form_data_multi_subsystem(owner_list)
+
+ def test_subsystem_multi_edit_response_content(self):
+ """Test Subsystem-specific multi-edit response content - Subsystem response handling."""
+ owner_list = self.create_owner_instance_list()
+ item_context_list = [self.create_item_edit_context(owner) for owner in owner_list]
+ page_context = self.create_page_edit_context(owner_list)
+
+ handler = AttributeEditFormHandler()
+ renderer = AttributeEditResponseRenderer()
+
+ multi_edit_form_data_list = handler.create_multi_edit_form_data(
+ attr_item_context_list=item_context_list
+ )
+
+ request = MockRequest()
+ request.session = MockSession()
+
+ response = renderer.render_form_success_response_multi(
+ attr_page_context=page_context,
+ multi_edit_form_data_list=multi_edit_form_data_list,
+ request=request,
+ message=None # Use default message
+ )
+
+ # Should use Subsystem-specific template context
+ self.assertEqual(response.status_code, 200)
+
+ # Verify response contains Subsystem-specific data
+ import json
+ data = json.loads(response.content)
+ self.assertIsInstance(data, dict)
+
+ # Should contain updates for multiple subsystems
+ self.assertTrue(len(data) > 0)
+
+
+class SubsystemMultiAttributeEditTemplateContextBuilderTest(AttributeMultiEditTemplateContextBuilderTestMixin, BaseTestCase):
+ """Test AttributeEditTemplateContextBuilder with Subsystem-specific multi-edit implementations."""
+
+ def create_owner_instance_list(self, **kwargs) -> List[Subsystem]:
+ """Create multiple Subsystem instances for multi-edit testing."""
+ return SubsystemAttributeSyntheticData.create_multiple_subsystems_scenario()
+
+ def create_attribute_instance(self, owner: Subsystem, **kwargs) -> AttributeModel:
+ """Create SubsystemAttribute instance for testing."""
+ defaults = {
+ 'subsystem': owner,
+ 'name': 'test_attribute',
+ 'value': 'test_value',
+ 'attribute_type_str': str(AttributeType.PREDEFINED),
+ 'value_type_str': kwargs.pop('value_type_str', str(AttributeValueType.TEXT)),
+ 'setting_key': 'test.setting.key',
+ }
+ defaults.update(kwargs)
+ return SubsystemAttribute.objects.create(**defaults)
+
+ def create_item_edit_context(self, owner: Subsystem) -> SubsystemAttributeItemEditContext:
+ """Create SubsystemAttributeItemEditContext for testing."""
+ return SubsystemAttributeItemEditContext(subsystem=owner)
+
+ def create_page_edit_context(self, owner_list: List[Subsystem]) -> SubsystemAttributePageEditContext:
+ """Create SubsystemAttributePageEditContext for multi-edit testing."""
+ # Page context only needs selected_subsystem_id, not the full list
+ selected_subsystem_id = str(owner_list[0].id) if owner_list else None
+ return SubsystemAttributePageEditContext(selected_subsystem_id=selected_subsystem_id)
+
+ def create_multi_valid_form_data(self, owner_list: List[Subsystem], **overrides) -> Dict[str, Any]:
+ """Create valid form data for multi-edit scenarios."""
+ return SubsystemAttributeSyntheticData.create_form_data_for_subsystem_multi_edit(
+ owner_list, **overrides
+ )
+
+ def create_multi_invalid_form_data(self, owner_list: List[Subsystem]) -> Dict[str, Any]:
+ """Create invalid form data for multi-edit scenarios."""
+ return SubsystemAttributeSyntheticData.create_invalid_form_data_multi_subsystem(owner_list)
+
+ def test_subsystem_multi_edit_template_context_assembly(self):
+ """Test Subsystem multi-edit template context assembly - multi subsystem context handling."""
+ owner_list = self.create_owner_instance_list()
+ item_context_list = [self.create_item_edit_context(owner) for owner in owner_list]
+ page_context = self.create_page_edit_context(owner_list)
+
+ handler = AttributeEditFormHandler()
+ builder = AttributeEditTemplateContextBuilder()
+
+ multi_edit_form_data_list = handler.create_multi_edit_form_data(
+ attr_item_context_list=item_context_list
+ )
+
+ template_context = builder.build_response_template_context_multi(
+ attr_page_context=page_context,
+ multi_edit_form_data_list=multi_edit_form_data_list
+ )
+
+ # Should include multi-edit context
+ self.assertIn('multi_edit_form_data_list', template_context)
+ self.assertIn('attr_page_context', template_context)
+
+ # Should have form data for each subsystem
+ multi_edit_data = template_context['multi_edit_form_data_list']
+ self.assertEqual(len(multi_edit_data), len(owner_list))
+
+ # Should include selected subsystem ID in page context
+ page_ctx = template_context['attr_page_context']
+ self.assertIsNotNone(page_ctx.selected_subsystem_id)
+
+
+class MockConfigMultiEditView(AttributeMultiEditViewMixin):
+ """Mock view for testing AttributeMultiEditViewMixin with config context."""
+ pass
+
+
+class SubsystemMultiAttributeViewMixinTest(AttributeMultiEditViewMixinTestMixin, BaseTestCase):
+ """Test AttributeMultiEditViewMixin with Subsystem-specific view implementations."""
+
+ def create_owner_instance_list(self, **kwargs) -> List[Subsystem]:
+ """Create multiple Subsystem instances for multi-edit testing."""
+ return SubsystemAttributeSyntheticData.create_multiple_subsystems_scenario()
+
+ def create_attribute_instance(self, owner: Subsystem, **kwargs) -> AttributeModel:
+ """Create SubsystemAttribute instance for testing."""
+ defaults = {
+ 'subsystem': owner,
+ 'name': 'test_attribute',
+ 'value': 'test_value',
+ 'attribute_type_str': str(AttributeType.PREDEFINED),
+ 'value_type_str': kwargs.pop('value_type_str', str(AttributeValueType.TEXT)),
+ 'setting_key': 'test.setting.key',
+ }
+ defaults.update(kwargs)
+ return SubsystemAttribute.objects.create(**defaults)
+
+ def create_item_edit_context(self, owner: Subsystem) -> SubsystemAttributeItemEditContext:
+ """Create SubsystemAttributeItemEditContext for testing."""
+ return SubsystemAttributeItemEditContext(subsystem=owner)
+
+ def create_page_edit_context(self, owner_list: List[Subsystem]) -> SubsystemAttributePageEditContext:
+ """Create SubsystemAttributePageEditContext for multi-edit testing."""
+ # Page context only needs selected_subsystem_id, not the full list
+ selected_subsystem_id = str(owner_list[0].id) if owner_list else None
+ return SubsystemAttributePageEditContext(selected_subsystem_id=selected_subsystem_id)
+
+ def create_multi_valid_form_data(self, owner_list: List[Subsystem], **overrides) -> Dict[str, Any]:
+ """Create valid form data for multi-edit scenarios."""
+ return SubsystemAttributeSyntheticData.create_form_data_for_subsystem_multi_edit(
+ owner_list, **overrides
+ )
+
+ def create_multi_invalid_form_data(self, owner_list: List[Subsystem]) -> Dict[str, Any]:
+ """Create invalid form data for multi-edit scenarios."""
+ return SubsystemAttributeSyntheticData.create_invalid_form_data_multi_subsystem(owner_list)
+
+ def create_view_instance(self):
+ """Create a view instance that uses AttributeMultiEditViewMixin."""
+ return MockConfigMultiEditView()
+
+ def test_subsystem_multi_edit_view_integration_workflow(self):
+ """Test complete Subsystem multi-edit view integration - unique multi-edit scenario."""
+ owner_list = self.create_owner_instance_list()
+ item_context_list = [self.create_item_edit_context(owner) for owner in owner_list]
+ page_context = self.create_page_edit_context(owner_list)
+
+ view = self.create_view_instance()
+
+ # Create valid POST data for multiple subsystems
+ post_data = QueryDict(mutable=True)
+ form_data_dict = self.create_multi_valid_form_data(owner_list)
+ for key, value in form_data_dict.items():
+ if isinstance(value, list):
+ post_data.setlist(key, value)
+ else:
+ post_data[key] = value
+
+ request = MockRequest()
+ request.POST = post_data
+ request.session = MockSession()
+
+ # Test the multi-edit view workflow
+ response = view.post_attribute_form(
+ request=request,
+ attr_page_context=page_context,
+ attr_item_context_list=item_context_list
+ )
+
+ # Should successfully handle multi-subsystem editing
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(response['Content-Type'], 'application/json')
+
+ # Verify attributes were saved (basic check)
+ for owner in owner_list:
+ # Should have at least one attribute after processing
+ self.assertTrue(owner.attributes.exists())
diff --git a/src/hi/apps/config/tests/test_integration.py b/src/hi/apps/config/tests/test_integration.py
index 6c0f602c..4817eef1 100644
--- a/src/hi/apps/config/tests/test_integration.py
+++ b/src/hi/apps/config/tests/test_integration.py
@@ -36,6 +36,11 @@ class IntegrationTestSettings(SettingEnum):
class TestConfigIntegration(BaseTestCase):
"""Integration tests for config module components working together in real workflows."""
+ def setUp(self):
+ super().setUp()
+ # Reset SettingsManager singleton for proper test isolation
+ SettingsManager._instance = None
+
def test_complete_settings_discovery_workflow(self):
"""Test complete workflow from module discovery to setting value access."""
# Create test module with settings
diff --git a/src/hi/apps/config/tests/test_settings_manager.py b/src/hi/apps/config/tests/test_settings_manager.py
index b1a062e9..080b00f6 100644
--- a/src/hi/apps/config/tests/test_settings_manager.py
+++ b/src/hi/apps/config/tests/test_settings_manager.py
@@ -25,6 +25,11 @@ class TestSetting(SettingEnum):
class TestSettingsManager(BaseTestCase):
+ def setUp(self):
+ super().setUp()
+ # Reset SettingsManager singleton for proper test isolation
+ SettingsManager._instance = None
+
def test_singleton_behavior(self):
"""Test SettingsManager singleton pattern - critical for system consistency."""
manager1 = SettingsManager()
diff --git a/src/hi/apps/config/tests/test_views.py b/src/hi/apps/config/tests/test_views.py
index c4a21501..276ef8fd 100644
--- a/src/hi/apps/config/tests/test_views.py
+++ b/src/hi/apps/config/tests/test_views.py
@@ -19,6 +19,10 @@ class TestConfigSettingsView(DualModeViewTestCase):
def setUp(self):
super().setUp()
+ # Reset SettingsManager singleton for proper test isolation
+ from hi.apps.config.settings_manager import SettingsManager
+ SettingsManager._instance = None
+
# Create test subsystem and attributes
self.subsystem = Subsystem.objects.create(
name='Test Subsystem',
@@ -77,16 +81,38 @@ class TestConfigSettingsView(DualModeViewTestCase):
def test_post_settings_valid_data(self):
"""Test posting valid settings data."""
url = reverse('config_settings')
- post_data = {
- f'subsystem-{self.subsystem.id}-TOTAL_FORMS': '2',
- f'subsystem-{self.subsystem.id}-INITIAL_FORMS': '2',
- f'subsystem-{self.subsystem.id}-MIN_NUM_FORMS': '0',
- f'subsystem-{self.subsystem.id}-MAX_NUM_FORMS': '1000',
- f'subsystem-{self.subsystem.id}-0-id': str(self.attribute1.id),
- f'subsystem-{self.subsystem.id}-0-value': 'updated_value_1',
- f'subsystem-{self.subsystem.id}-1-id': str(self.attribute2.id),
- f'subsystem-{self.subsystem.id}-1-value': 'updated_value_2',
- }
+
+ # Build formset data for all existing subsystems (after SettingsManager reset)
+ post_data = {}
+ all_subsystems = Subsystem.objects.all()
+
+ for subsystem in all_subsystems:
+ attributes = subsystem.attributes.all()
+
+ # Add management form data for this subsystem
+ post_data.update({
+ f'subsystem-{subsystem.id}-TOTAL_FORMS': str(len(attributes)),
+ f'subsystem-{subsystem.id}-INITIAL_FORMS': str(len(attributes)),
+ f'subsystem-{subsystem.id}-MIN_NUM_FORMS': '0',
+ f'subsystem-{subsystem.id}-MAX_NUM_FORMS': '1000',
+ })
+
+ # Add individual attribute form data
+ for i, attr in enumerate(attributes):
+ # Only modify the test attributes we created, leave others unchanged
+ if attr == self.attribute1:
+ value = 'updated_value_1'
+ elif attr == self.attribute2:
+ value = 'updated_value_2'
+ else:
+ value = attr.value # Keep original value
+
+ post_data.update({
+ f'subsystem-{subsystem.id}-{i}-id': str(attr.id),
+ f'subsystem-{subsystem.id}-{i}-name': attr.name,
+ f'subsystem-{subsystem.id}-{i}-value': value,
+ f'subsystem-{subsystem.id}-{i}-attribute_type_str': attr.attribute_type_str,
+ })
response = self.client.post(url, data=post_data)
@@ -111,8 +137,8 @@ class TestConfigSettingsView(DualModeViewTestCase):
response = self.client.post(url, data=post_data)
# Should return form with errors
- self.assertSuccessResponse(response)
- self.assertTemplateRendered(response, 'config/panes/settings_form.html')
+ self.assertErrorResponse(response)
+ self.assertTemplateRendered(response, 'config/panes/subsystem_edit_content_body.html')
def test_subsystems_in_context(self):
"""Test that subsystems are properly passed to template context."""
@@ -120,10 +146,10 @@ class TestConfigSettingsView(DualModeViewTestCase):
response = self.client.get(url)
self.assertSuccessResponse(response)
- self.assertIn('subsystem_attribute_formset_list', response.context)
- formset_list = response.context['subsystem_attribute_formset_list']
+ self.assertIn('multi_edit_form_data_list', response.context)
+ form_data_list = response.context['multi_edit_form_data_list']
# There may be default system subsystems in addition to our test subsystem
- self.assertGreaterEqual(len(formset_list), 1) # At least our test subsystem
+ self.assertGreaterEqual(len(form_data_list), 1) # At least our test subsystem
class TestConfigInternalView(SyncViewTestCase):
diff --git a/src/hi/apps/config/urls.py b/src/hi/apps/config/urls.py
index f2f6b293..e4641400 100644
--- a/src/hi/apps/config/urls.py
+++ b/src/hi/apps/config/urls.py
@@ -5,20 +5,24 @@ from . import views
urlpatterns = [
- re_path( r'^settings$',
+ re_path( r'^$',
+ views.ConfigHomeView.as_view(),
+ name='config_home' ),
+
+ re_path( r'^settings(?:/(?P<subsystem_id>\d+))?$',
views.ConfigSettingsView.as_view(),
name='config_settings' ),
re_path( r'^internal$',
views.ConfigInternalView.as_view(),
name='config_internal' ),
+
+ re_path( r'^attribute/history/(?P<subsystem_id>\d+)/(?P<attribute_id>\d+)/$',
+ views.SubsystemAttributeHistoryInlineView.as_view(),
+ name='subsystem_attribute_history_inline'),
- re_path( r'^attribute/history/(?P<attribute_id>\d+)$',
- views.ConfigAttributeHistoryView.as_view(),
- name='config_attribute_history'),
-
- re_path( r'^attribute/restore/(?P<attribute_id>\d+)$',
- views.ConfigAttributeRestoreView.as_view(),
- name='config_attribute_restore'),
+ re_path( r'^attribute/restore/(?P<subsystem_id>\d+)/(?P<attribute_id>\d+)/(?P<history_id>\d+)/$',
+ views.SubsystemAttributeRestoreInlineView.as_view(),
+ name='subsystem_attribute_restore_inline'),
]
diff --git a/src/hi/apps/config/views.py b/src/hi/apps/config/views.py
index 6b45826c..ce2f5f1d 100644
--- a/src/hi/apps/config/views.py
+++ b/src/hi/apps/config/views.py
@@ -1,26 +1,35 @@
import logging
-from django.db import transaction
-from django.shortcuts import render
-
from django.conf import settings
-from django.http import JsonResponse
+from django.http import JsonResponse, HttpResponseRedirect
+from django.urls import reverse
from django.views.generic import View
import hi.apps.common.antinode as antinode
+from hi.views import page_not_found_response
from hi.enums import ViewMode, ViewType
from hi.hi_grid_view import HiGridView
-from hi.apps.attribute.views import BaseAttributeHistoryView, BaseAttributeRestoreView
+from hi.apps.attribute.view_mixins import AttributeMultiEditViewMixin
from .enums import ConfigPageType
-from .forms import SubsystemAttributeFormSet
from .models import SubsystemAttribute
-from .settings_mixins import SettingsMixin
+from .settings_mixins import SubsystemAttributeMixin
+from .subsystem_attribute_edit_context import (
+ SubsystemAttributeItemEditContext,
+ SubsystemAttributePageEditContext,
+)
logger = logging.getLogger('__name__')
+class ConfigHomeView( View ):
+
+ def get( self, request, *args, **kwargs ):
+ redirect_url = reverse( ConfigPageType.default().url_name )
+ return HttpResponseRedirect( redirect_url )
+
+
class ConfigPageView( HiGridView ):
"""
The app's config/admin page is shown in the main area of the HiGridView
@@ -73,74 +82,6 @@ class ConfigPageView( HiGridView ):
raise NotImplementedError('Subclasses must override this method.')
-class ConfigSettingsView( ConfigPageView, SettingsMixin ):
-
- @property
- def config_page_type(self) -> ConfigPageType:
- return ConfigPageType.SETTINGS
-
- def get_main_template_name( self ) -> str:
- return 'config/panes/settings.html'
-
- def get_main_template_context( self, request, *args, **kwargs ):
-
- subsystem_list = self.settings_manager().get_subsystems()
-
- subsystem_attribute_formset_list = list()
- for subsystem in subsystem_list:
- subsystem_attribute_formset = SubsystemAttributeFormSet(
- instance = subsystem,
- prefix = f'subsystem-{subsystem.id}',
- form_kwargs = {
- 'show_as_editable': True,
- },
- )
- subsystem_attribute_formset_list.append( subsystem_attribute_formset )
- continue
-
- return {
- 'subsystem_attribute_formset_list': subsystem_attribute_formset_list,
- 'history_url_name': 'config_attribute_history',
- 'restore_url_name': 'config_attribute_restore',
- }
-
- def post( self, request, *args, **kwargs ):
-
- subsystem_list = self.settings_manager().get_subsystems()
-
- all_valid = True
- subsystem_attribute_formset_list = list()
- for subsystem in subsystem_list:
- subsystem_attribute_formset = SubsystemAttributeFormSet(
- request.POST,
- request.FILES,
- instance = subsystem,
- prefix = f'subsystem-{subsystem.id}',
- )
- if not subsystem_attribute_formset.is_valid():
- all_valid = False
- subsystem_attribute_formset_list.append( subsystem_attribute_formset )
- continue
-
- if not all_valid:
- context = {
- 'subsystem_attribute_formset_list': subsystem_attribute_formset_list,
- 'history_url_name': 'config_attribute_history',
- 'restore_url_name': 'config_attribute_restore',
- }
- return render( request, 'config/panes/settings_form.html', context )
-
- with transaction.atomic():
- for subsystem_attribute_formset in subsystem_attribute_formset_list:
- subsystem_attribute_formset.save()
- continue
-
- # Some settings (e.g., audio files) define what gets loaded into
- # the initial HTML, so refresh the page to ensure they get updated.
- #
- return antinode.refresh_response()
-
-
class ConfigInternalView( View ):
@classmethod
@@ -174,22 +115,95 @@ class ConfigInternalView( View ):
data = self.get_config_data()
return JsonResponse( data, safe = False )
-
-class ConfigAttributeHistoryView(BaseAttributeHistoryView):
- """View for displaying SubsystemAttribute history in a modal."""
-
- def get_attribute_model_class(self):
- return SubsystemAttribute
- def get_history_url_name(self):
- return 'config_attribute_history'
+class ConfigSettingsView( ConfigPageView,
+ SubsystemAttributeMixin,
+ AttributeMultiEditViewMixin ):
+
+ @property
+ def config_page_type(self) -> ConfigPageType:
+ return ConfigPageType.SETTINGS
- def get_restore_url_name(self):
- return 'config_attribute_restore'
+ def get_main_template_name( self ) -> str:
+ return 'config/panes/settings.html'
+
+ def get_main_template_context( self, request, *args, **kwargs ):
+
+ attr_item_context_list = self._create_attr_item_context_list()
+
+ selected_subsystem_id = kwargs.get('subsystem_id')
+ if not selected_subsystem_id and attr_item_context_list:
+ selected_subsystem_id = str(attr_item_context_list[0].owner_id)
+ attr_page_context = SubsystemAttributePageEditContext(
+ selected_subsystem_id = selected_subsystem_id,
+ )
+ return self.create_initial_template_context(
+ attr_page_context = attr_page_context,
+ attr_item_context_list = attr_item_context_list,
+ )
+
+ def post( self, request, *args, **kwargs ):
-class ConfigAttributeRestoreView(BaseAttributeRestoreView):
- """View for restoring SubsystemAttribute values from history."""
+ attr_item_context_list = self._create_attr_item_context_list()
+
+ selected_subsystem_id = kwargs.get('subsystem_id')
+ if not selected_subsystem_id and attr_item_context_list:
+ selected_subsystem_id = str(attr_item_context_list[0].owner_id)
+
+ attr_page_context = SubsystemAttributePageEditContext(
+ selected_subsystem_id = selected_subsystem_id,
+ )
+
+ return self.post_attribute_form(
+ request = request,
+ attr_page_context = attr_page_context,
+ attr_item_context_list = attr_item_context_list,
+ )
+
+
+class SubsystemAttributeHistoryInlineView( View, AttributeMultiEditViewMixin ):
+
+ def get(self, request, subsystem_id, attribute_id, *args, **kwargs):
+ # Validate that the attribute belongs to this entity for security
+ try:
+ attribute = SubsystemAttribute.objects.select_related('subsystem').get(
+ pk = attribute_id, subsystem_id = subsystem_id )
+ except SubsystemAttribute.DoesNotExist:
+ return page_not_found_response(request, "Attribute not found.")
+
+ attr_item_context = SubsystemAttributeItemEditContext(
+ subsystem = attribute.subsystem,
+ )
+ return self.get_history(
+ request = request,
+ attribute = attribute,
+ attr_item_context = attr_item_context,
+ )
+
+
+class SubsystemAttributeRestoreInlineView( View,
+ SubsystemAttributeMixin,
+ AttributeMultiEditViewMixin ):
+ """View for restoring SubsystemAttribute values from history inline."""
- def get_attribute_model_class(self):
- return SubsystemAttribute
+ def get(self, request, subsystem_id, attribute_id, history_id, *args, **kwargs):
+ try:
+ attribute = SubsystemAttribute.objects.select_related('subsystem').get(
+ pk = attribute_id, subsystem_id = subsystem_id
+ )
+ except SubsystemAttribute.DoesNotExist:
+ return page_not_found_response(request, "Attribute not found.")
+
+ attr_page_context = SubsystemAttributePageEditContext(
+ selected_subsystem_id = subsystem_id,
+ )
+ attr_item_context_list = self._create_attr_item_context_list()
+
+ return self.post_restore(
+ request = request,
+ attribute = attribute,
+ history_id = history_id,
+ attr_page_context = attr_page_context,
+ attr_item_context_list = attr_item_context_list,
+ )
diff --git a/src/hi/apps/entity/edit/tests/test_entity_type_transition_handler.py b/src/hi/apps/entity/edit/tests/test_entity_type_transition_handler.py
index c6285d30..d6208ba0 100644
--- a/src/hi/apps/entity/edit/tests/test_entity_type_transition_handler.py
+++ b/src/hi/apps/entity/edit/tests/test_entity_type_transition_handler.py
@@ -9,10 +9,9 @@ from unittest.mock import patch
from django.http import HttpResponse
from django.test import RequestFactory
-from hi.apps.entity.entity_edit_form_handler import EntityEditFormHandler
from hi.apps.entity.edit.entity_type_transition_handler import EntityTypeTransitionHandler
from hi.apps.entity.enums import EntityType, EntityTransitionType
-from hi.apps.entity.forms import EntityForm, EntityAttributeRegularFormSet
+from hi.apps.entity.forms import EntityForm
from hi.testing.base_test_case import BaseTestCase
from hi.apps.entity.tests.synthetic_data import EntityAttributeSyntheticData
from hi.apps.location.tests.synthetic_data import LocationSyntheticData
@@ -119,46 +118,6 @@ class TestEntityTypeTransitionHandlerFormSaving(BaseTestCase):
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
@@ -406,60 +365,6 @@ class TestEntityTypeTransitionHandlerIntegration(BaseTestCase):
self.assertIsNotNone(result)
self.assertIsInstance(result, HttpResponse)
- @patch('hi.apps.entity.edit.entity_type_transition_handler.EntityManager')
- def test_entity_type_change_with_attributes_formset(self, mock_entity_mgr):
- """Test entity type change with simultaneous attribute changes using real objects."""
- 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 only the entity manager's complex transition logic
- mock_entity_mgr.return_value.handle_entity_type_transition.return_value = (True, EntityTransitionType.PATH_TO_PATH)
-
- 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 with real database transactions
- 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')
-
- # Verify transition was attempted with real location view
- mock_entity_mgr.return_value.handle_entity_type_transition.assert_called_once_with(
- entity=entity,
- location_view=self.location_view
- )
-
- # path_to_path transition should not require full page refresh
- self.assertIsNone(result)
-
@patch('hi.apps.entity.edit.entity_type_transition_handler.EntityManager')
def test_transaction_rollback_on_transition_failure(self, mock_entity_mgr):
"""Test that transaction is properly managed even if transition fails using real objects."""
diff --git a/src/hi/apps/entity/entity_attribute_edit_context.py b/src/hi/apps/entity/entity_attribute_edit_context.py
index af59f201..98c0819b 100644
--- a/src/hi/apps/entity/entity_attribute_edit_context.py
+++ b/src/hi/apps/entity/entity_attribute_edit_context.py
@@ -1,15 +1,24 @@
"""
-EntityAttributeEditContext - Entity-specific context for attribute editing templates.
+Entity Attribute Edit Context - Entity-specific context for attribute editing templates.
-This module contains Entity-specific implementations of the AttributeEditContext
+This module contains Entity-specific implementations of the AttributeItemEditContext
pattern, encapsulating entity-specific domain knowledge while maintaining
the generic template interface.
"""
-from hi.apps.attribute.edit_context import AttributeEditContext
-from .models import Entity
+from typing import Any, Dict, Optional, Type
+from django.forms import ModelForm, BaseInlineFormSet
+from django.urls import reverse
-class EntityAttributeEditContext(AttributeEditContext):
+from hi.apps.attribute.edit_context import AttributeItemEditContext
+from hi.apps.attribute.forms import AttributeUploadForm
+from hi.apps.attribute.models import AttributeModel
+
+from .forms import EntityForm, EntityAttributeRegularFormSet, EntityAttributeUploadForm
+from .models import Entity, EntityAttribute
+
+
+class EntityAttributeItemEditContext(AttributeItemEditContext):
"""
Entity-specific context provider for attribute editing templates.
@@ -24,10 +33,41 @@ class EntityAttributeEditContext(AttributeEditContext):
Args:
entity: The Entity instance that owns the attributes
"""
- super().__init__(entity, 'entity')
+ super().__init__( owner_type = 'entity', owner = entity )
+ return
@property
def entity(self) -> Entity:
"""Get the Entity instance (typed accessor)."""
return self.owner
+ @property
+ def attribute_model_subclass(self) -> Type[AttributeModel]:
+ return EntityAttribute
+
+ @property
+ def attribute_upload_form_class(self) -> Type[AttributeUploadForm]:
+ return EntityAttributeUploadForm
+
+ def create_owner_form( self, form_data : Optional[ Dict[str, Any] ] = None ) -> ModelForm:
+ return EntityForm( form_data, instance = self.entity )
+
+ def create_attribute_model( self ) -> AttributeModel:
+ return EntityAttribute( entity = self.entity )
+
+ def create_regular_attributes_formset(
+ self, form_data : Optional[ Dict[str, Any] ] = None ) -> BaseInlineFormSet:
+ return EntityAttributeRegularFormSet(
+ form_data,
+ instance = self.entity,
+ prefix = self.formset_prefix,
+ )
+
+ @property
+ def content_body_template_name(self):
+ return 'entity/panes/entity_edit_content_body.html'
+
+ @property
+ def file_upload_url(self) -> str:
+ return reverse( 'entity_attribute_upload',
+ kwargs = { 'entity_id': self.entity.id })
diff --git a/src/hi/apps/entity/entity_edit_form_handler.py b/src/hi/apps/entity/entity_edit_form_handler.py
deleted file mode 100644
index 51ea1f90..00000000
--- a/src/hi/apps/entity/entity_edit_form_handler.py
+++ /dev/null
@@ -1,246 +0,0 @@
-"""
-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
-from .entity_attribute_edit_context import EntityAttributeEditContext
-
-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)
-
- # Create the attribute edit context for template generalization
- attr_context = EntityAttributeEditContext(entity)
-
- # Build context with both old and new patterns for compatibility
- context = {
- 'entity': entity,
- 'entity_form': entity_form,
- 'owner_form': entity_form, # Generic alias for templates
- 'file_attributes': file_attributes,
- 'regular_attributes_formset': regular_attributes_formset,
- }
-
- # Merge in the context variables from AttributeEditContext
- context.update(attr_context.to_template_context())
-
- return context
diff --git a/src/hi/apps/entity/entity_edit_response_renderer.py b/src/hi/apps/entity/entity_edit_response_renderer.py
deleted file mode 100644
index e17a667b..00000000
--- a/src/hi/apps/entity/entity_edit_response_renderer.py
+++ /dev/null
@@ -1,215 +0,0 @@
-"""
-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
-from .entity_attribute_edit_context import EntityAttributeEditContext
-
-
-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)
-
- # Create the attribute edit context for template generalization
- attr_context = EntityAttributeEditContext(entity)
-
- # Build context with both old and new patterns for compatibility
- context = {
- 'entity': entity,
- 'entity_form': entity_form,
- 'owner_form': entity_form, # Generic alias for templates
- '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,
- }
-
- # Merge in the context variables from AttributeEditContext
- context.update(attr_context.to_template_context())
-
- return context
-
- 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/forms.py b/src/hi/apps/entity/forms.py
index 997d96c8..82e81cdf 100644
--- a/src/hi/apps/entity/forms.py
+++ b/src/hi/apps/entity/forms.py
@@ -32,6 +32,11 @@ class EntityAttributeForm( AttributeForm ):
class RegularAttributeBaseFormSet(forms.BaseInlineFormSet):
"""Base formset that automatically excludes FILE attributes for regular attribute editing"""
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ # Apply filtering after parent initialization
+ self.queryset = self.queryset.exclude(value_type_str=str(AttributeValueType.FILE))
+
def get_queryset(self):
"""Override to automatically filter out FILE attributes"""
queryset = super().get_queryset()
diff --git a/src/hi/apps/entity/templates/entity/modals/entity_edit.html b/src/hi/apps/entity/templates/entity/modals/entity_edit.html
index f6970017..5e90316c 100644
--- a/src/hi/apps/entity/templates/entity/modals/entity_edit.html
+++ b/src/hi/apps/entity/templates/entity/modals/entity_edit.html
@@ -5,40 +5,46 @@
{% block title_text %}{{ entity.name }}{% endblock %}
{% block body %}
-<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 %}
+<!-- Root container for this attribute editing context -->
+<div id="{{ attr_page_context.container_html_id }}"
+ class="{{ DIVID.ATTR_V2_CONTAINER_CLASS }}">
-<!-- Main content wrapper for antinode updates -->
-<div id="{{ DIVID.ATTR_V2_CONTENT }}">
- {% include "entity/panes/entity_edit_content_body.html" %}
-</div>
-</form>
-
-<!-- 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>
-
-<!-- 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">&times;</span>
- </button>
+ <div class="{{ DIVID.ATTR_V2_FORM_CLASS }}">
+ <form id="{{ attr_page_context.form_html_id }}"
+ action="{% url 'entity_edit' entity_id=entity.id %}"
+ method="post"
+ class="{{ DIVID.ATTR_V2_FORM_CLASS }} form"
+ enctype="multipart/form-data">
+ {% csrf_token %}
+
+ <!-- Main content wrapper for antinode updates -->
+ <div id="{{ attr_page_context.content_html_id }}"
+ class="{{ DIVID.ATTR_V2_CONTENT_CLASS }}">
+ {% include "entity/panes/entity_edit_content_body.html" %}
</div>
- {% endfor %}
+ </form>
</div>
-{% endif %}
+
+ <!-- File Upload Form Container (separate from main form to avoid nesting) -->
+ <div id="{{ attr_item_context.upload_form_container_html_id }}">
+ {% 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>
+
+ <!-- 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">&times;</span>
+ </button>
+ </div>
+ {% endfor %}
+ </div>
+ {% endif %}
+</div>
<!-- JavaScript for V2 functionality loaded via Django Pipeline js_before_content bundle -->
diff --git a/src/hi/apps/entity/tests/synthetic_data.py b/src/hi/apps/entity/tests/synthetic_data.py
index 68c466dd..3c4f2e09 100644
--- a/src/hi/apps/entity/tests/synthetic_data.py
+++ b/src/hi/apps/entity/tests/synthetic_data.py
@@ -8,10 +8,10 @@ import uuid
from django.core.files.uploadedfile import SimpleUploadedFile
from typing import Optional, Dict, Any, List
+from hi.constants import DIVID
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
@@ -165,7 +165,7 @@ class EntityAttributeSyntheticData:
).order_by('id'))
# Use EntityEditFormHandler as the single source of truth for prefix logic
- prefix = EntityEditFormHandler.get_formset_prefix(entity)
+ prefix = f'entity-{entity.id}'
# Formset management form data
formset_data = {
@@ -190,7 +190,7 @@ class EntityAttributeSyntheticData:
@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)
+ prefix = f'entity-{entity.id}'
data = {
f'{prefix}-TOTAL_FORMS': str(len(attributes) + 1), # +1 for empty form
f'{prefix}-INITIAL_FORMS': str(len(attributes)),
@@ -221,6 +221,6 @@ class EntityAttributeSyntheticData:
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]
+ DIVID['ATTR_V2_DELETE_FILE_ATTR']: [str(attr.id) for attr in file_attributes]
}
diff --git a/src/hi/apps/entity/tests/test_attribute_view_integration.py b/src/hi/apps/entity/tests/test_attribute_view_integration.py
index 798fe5e9..9863519c 100644
--- a/src/hi/apps/entity/tests/test_attribute_view_integration.py
+++ b/src/hi/apps/entity/tests/test_attribute_view_integration.py
@@ -63,13 +63,13 @@ class TestEntityAttributeViewIntegration(DualModeViewTestCase):
self.assertIn('regular_attributes_formset', response.context)
self.assertIn('file_attributes', response.context)
- # Should have AttributeEditContext integration
- self.assertIn('attr_context', response.context)
- attr_context = response.context['attr_context']
+ # Should have AttributeItemEditContext integration
+ self.assertIn('attr_item_context', response.context)
+ attr_item_context = response.context['attr_item_context']
- from hi.apps.entity.entity_attribute_edit_context import EntityAttributeEditContext
- self.assertIsInstance(attr_context, EntityAttributeEditContext)
- self.assertEqual(attr_context.entity, self.entity)
+ from hi.apps.entity.entity_attribute_edit_context import EntityAttributeItemEditContext
+ self.assertIsInstance(attr_item_context, EntityAttributeItemEditContext)
+ self.assertEqual(attr_item_context.entity, self.entity)
def test_entity_edit_view_ajax_get_request(self):
"""Test AJAX GET request returns JSON response - async rendering."""
@@ -242,24 +242,24 @@ class TestEntityAttributeViewIntegration(DualModeViewTestCase):
self.assertIsInstance(response.status_code, int)
def test_attribute_context_template_integration(self):
- """Test AttributeEditContext integration with actual templates - template rendering."""
+ """Test AttributeItemEditContext integration with actual templates - template rendering."""
url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})
response = self.client.get(url)
self.assertSuccessResponse(response)
- # Response should include AttributeEditContext data
+ # Response should include AttributeItemEditContext data
context = response.context
- self.assertIn('attr_context', context)
+ self.assertIn('attr_item_context', context)
- attr_context = context['attr_context']
+ attr_item_context = context['attr_item_context']
# Should provide all the template functionality
- self.assertEqual(attr_context.owner_type, 'entity')
- self.assertEqual(attr_context.owner_id, self.entity.id)
+ self.assertEqual(attr_item_context.owner_type, 'entity')
+ self.assertEqual(attr_item_context.owner_id, self.entity.id)
# Template should be able to use these patterns
- history_id = attr_context.history_target_id(123)
+ history_id = attr_item_context.history_target_id(123)
self.assertIn('hi-entity-attr-history', history_id)
def test_error_handling_integration(self):
diff --git a/src/hi/apps/entity/tests/test_entity_attribute_framework.py b/src/hi/apps/entity/tests/test_entity_attribute_framework.py
new file mode 100644
index 00000000..6c23f247
--- /dev/null
+++ b/src/hi/apps/entity/tests/test_entity_attribute_framework.py
@@ -0,0 +1,456 @@
+"""
+Concrete test implementations for Entity attribute editing framework.
+
+These tests extend the abstract base classes to provide comprehensive testing
+of the attribute framework as implemented for Entity models. Tests both the
+framework components and Entity-specific customizations.
+
+Following project testing guidelines:
+- No mocked objects, use real Entity and EntityAttribute models
+- Focus on high-value business logic and integration points
+- Use EntityAttributeSyntheticData for test data generation
+- Test meaningful Entity-specific edge cases and workflows
+"""
+import logging
+
+from django.core.files.uploadedfile import SimpleUploadedFile
+
+from hi.apps.attribute.tests.attribute_framework_test_base import (
+ AttributeEditFormHandlerTestMixin,
+ AttributeEditResponseRendererTestMixin,
+ AttributeEditTemplateContextBuilderTestMixin,
+ AttributeViewMixinTestMixin,
+)
+from hi.testing.base_test_case import BaseTestCase
+from hi.apps.attribute.enums import AttributeType, AttributeValueType
+from hi.apps.attribute.models import AttributeModel
+from hi.apps.entity.entity_attribute_edit_context import EntityAttributeItemEditContext
+from hi.apps.entity.models import EntityAttribute
+from hi.apps.entity.tests.synthetic_data import EntityAttributeSyntheticData
+from hi.apps.entity.views import EntityEditView
+
+logging.disable(logging.CRITICAL)
+
+
+class EntityAttributeEditFormHandlerTest(AttributeEditFormHandlerTestMixin, BaseTestCase):
+ """Test AttributeEditFormHandler with Entity-specific implementations."""
+
+ def create_owner_instance(self, **kwargs):
+ """Create Entity instance for testing."""
+ return EntityAttributeSyntheticData.create_test_entity(**kwargs)
+
+ def create_attribute_instance(self, owner, **kwargs) -> AttributeModel:
+ """Create EntityAttribute instance for testing."""
+ value_type = kwargs.get('value_type_str', str(AttributeValueType.TEXT))
+
+ # Use synthetic data method for file attributes to ensure proper file handling
+ if value_type == str(AttributeValueType.FILE):
+ return EntityAttributeSyntheticData.create_test_file_attribute(entity=owner, **kwargs)
+
+ # For non-file attributes, use direct creation
+ defaults = {
+ 'entity': owner,
+ 'name': 'test_attribute',
+ 'value': 'test_value',
+ 'attribute_type_str': str(AttributeType.CUSTOM),
+ 'value_type_str': value_type,
+ }
+ defaults.update(kwargs)
+ return EntityAttribute.objects.create(**defaults)
+
+ def create_item_edit_context(self, owner):
+ """Create EntityAttributeItemEditContext for testing."""
+ return EntityAttributeItemEditContext(entity=owner)
+
+ def create_valid_form_data(self, owner, **overrides):
+ """Create valid form data for Entity editing."""
+ return EntityAttributeSyntheticData.create_form_data_for_entity_edit(
+ owner, **overrides
+ )
+
+ def create_invalid_form_data(self, owner):
+ """Create invalid form data for Entity editing - empty name."""
+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(owner)
+ form_data['name'] = '' # Invalid empty name
+ return form_data
+
+ def test_entity_specific_form_validation_business_logic(self):
+ """Test Entity-specific form validation rules - business logic validation."""
+ entity = self.create_owner_instance(name="Entity Validation Test")
+ context = self.create_item_edit_context(entity)
+ handler = self._get_handler()
+
+ # Test entity name validation
+ invalid_data = self.create_valid_form_data(entity)
+ invalid_data['name'] = '' # Entity requires name
+
+ form_data = handler.create_edit_form_data(
+ attr_item_context=context,
+ form_data=invalid_data
+ )
+
+ is_valid = handler.validate_forms(edit_form_data=form_data)
+ self.assertFalse(is_valid)
+
+ # Entity form should have name error
+ if form_data.owner_form:
+ self.assertIn('name', form_data.owner_form.errors)
+
+ def test_entity_attribute_formset_creation_patterns(self):
+ """Test Entity-specific formset creation patterns - Entity formset logic."""
+ entity = self.create_owner_instance(name="Formset Test Entity")
+
+ # Create mixed attribute types
+ self.create_attribute_instance(
+ entity, name="text_prop", value="text_value",
+ value_type_str=str(AttributeValueType.TEXT)
+ )
+ self.create_attribute_instance(
+ entity, name="file_prop", value="File Title",
+ value_type_str=str(AttributeValueType.FILE)
+ )
+
+ context = self.create_item_edit_context(entity)
+ handler = self._get_handler()
+
+ form_data = handler.create_edit_form_data(attr_item_context=context)
+
+ # File attributes should be excluded from regular formset
+ # Check if formset has initial data or get from the formset's queryset
+ if form_data.regular_attributes_formset.initial:
+ formset_data = list(form_data.regular_attributes_formset.initial)
+ formset_names = [attr.get('name') for attr in formset_data]
+ else:
+ # Get names from the formset's queryset
+ formset_names = [attr.name for attr in form_data.regular_attributes_formset.queryset]
+
+ self.assertIn("text_prop", formset_names)
+ self.assertNotIn("file_prop", formset_names)
+
+ # File attributes should be in separate queryset
+ file_attr_names = [attr.name for attr in form_data.file_attributes]
+ self.assertIn("file_prop", file_attr_names)
+ self.assertNotIn("text_prop", file_attr_names)
+
+ def test_entity_file_upload_integration(self):
+ """Test Entity file upload handling - Entity file operations."""
+ entity = self.create_owner_instance(name="File Upload Entity")
+ context = self.create_item_edit_context(entity)
+
+ # Entity should support file uploads
+ self.assertIsNotNone(context.attribute_upload_form_class)
+ self.assertTrue(context.uses_file_uploads)
+
+ # Test file creation through form handler
+ test_file = SimpleUploadedFile(
+ "entity_test.txt",
+ b"Entity test file content",
+ content_type="text/plain"
+ )
+
+ from hi.testing.base_test_case import MockRequest, MockSession
+ request = MockRequest()
+ request.POST = {
+ 'name': 'entity_document',
+ 'value': 'Entity Test Document'
+ }
+ request.FILES = {'file_value': test_file}
+ request.session = MockSession()
+
+ # Should handle file upload processing
+
+ # File handling is tested at the view level, but we can test the context setup
+ self.assertIsNotNone(context.file_upload_url)
+
+ def _get_handler(self):
+ """Get handler instance for testing."""
+ from hi.apps.attribute.edit_form_handler import AttributeEditFormHandler
+ return AttributeEditFormHandler()
+
+
+class EntityAttributeEditResponseRendererTest(AttributeEditResponseRendererTestMixin, BaseTestCase):
+ """Test AttributeEditResponseRenderer with Entity-specific implementations."""
+
+ def create_owner_instance(self, **kwargs):
+ """Create Entity instance for testing."""
+ return EntityAttributeSyntheticData.create_test_entity(**kwargs)
+
+ def create_attribute_instance(self, owner, **kwargs) -> AttributeModel:
+ """Create EntityAttribute instance for testing."""
+ defaults = {
+ 'entity': owner,
+ 'name': 'test_attribute',
+ 'value': 'test_value',
+ 'attribute_type_str': str(AttributeType.CUSTOM),
+ 'value_type_str': str(AttributeValueType.TEXT),
+ }
+ defaults.update(kwargs)
+ return EntityAttribute.objects.create(**defaults)
+
+ def create_item_edit_context(self, owner):
+ """Create EntityAttributeItemEditContext for testing."""
+ return EntityAttributeItemEditContext(entity=owner)
+
+ def create_valid_form_data(self, owner, **overrides):
+ """Create valid form data for Entity editing."""
+ return EntityAttributeSyntheticData.create_form_data_for_entity_edit(
+ owner, **overrides
+ )
+
+ def create_invalid_form_data(self, owner):
+ """Create invalid form data for Entity editing."""
+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(owner)
+ form_data['name'] = '' # Invalid empty name
+ return form_data
+
+ def test_entity_specific_response_content(self):
+ """Test Entity-specific response content and templates - Entity response handling."""
+ entity = self.create_owner_instance(name="Response Test Entity")
+ context = self.create_item_edit_context(entity)
+ renderer = self._get_renderer()
+
+ request = self.factory.post('/entity/test/')
+ request.session = self._get_mock_session()
+
+ response = renderer.render_form_success_response(
+ attr_item_context=context,
+ request=request,
+ message=None # Use default message
+ )
+
+ # Should use Entity-specific template context
+ self.assertEqual(response.status_code, 200)
+
+ # Verify response contains Entity-specific data
+ import json
+ data = json.loads(response.content)
+ self.assertIsInstance(data, dict)
+
+ def _get_renderer(self):
+ """Get renderer instance for testing."""
+ from hi.apps.attribute.edit_response_renderer import AttributeEditResponseRenderer
+ return AttributeEditResponseRenderer()
+
+ def _get_mock_session(self):
+ """Get mock session for testing."""
+ from hi.testing.base_test_case import MockSession
+ return MockSession()
+
+
+class EntityAttributeEditTemplateContextBuilderTest(AttributeEditTemplateContextBuilderTestMixin, BaseTestCase):
+ """Test AttributeEditTemplateContextBuilder with Entity-specific implementations."""
+
+ def create_owner_instance(self, **kwargs):
+ """Create Entity instance for testing."""
+ return EntityAttributeSyntheticData.create_test_entity(**kwargs)
+
+ def create_attribute_instance(self, owner, **kwargs) -> AttributeModel:
+ """Create EntityAttribute instance for testing."""
+ defaults = {
+ 'entity': owner,
+ 'name': 'test_attribute',
+ 'value': 'test_value',
+ 'attribute_type_str': str(AttributeType.CUSTOM),
+ 'value_type_str': str(AttributeValueType.TEXT),
+ }
+ defaults.update(kwargs)
+ return EntityAttribute.objects.create(**defaults)
+
+ def create_item_edit_context(self, owner):
+ """Create EntityAttributeItemEditContext for testing."""
+ return EntityAttributeItemEditContext(entity=owner)
+
+ def create_valid_form_data(self, owner, **overrides):
+ """Create valid form data for Entity editing."""
+ return EntityAttributeSyntheticData.create_form_data_for_entity_edit(
+ owner, **overrides
+ )
+
+ def create_invalid_form_data(self, owner):
+ """Create invalid form data for Entity editing."""
+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(owner)
+ form_data['name'] = ''
+ return form_data
+
+ def test_entity_specific_template_context_keys(self):
+ """Test Entity-specific template context keys - Entity template integration."""
+ entity = self.create_owner_instance(name="Template Context Entity")
+ context = self.create_item_edit_context(entity)
+ builder = self._get_builder()
+
+ template_context = builder.build_initial_template_context(
+ attr_item_context=context
+ )
+
+ # Should include Entity-specific keys
+ self.assertIn('entity', template_context)
+ self.assertIs(template_context['entity'], entity)
+ self.assertIn('entity_form', template_context)
+
+ # Should include generic keys
+ self.assertIn('owner', template_context)
+ self.assertIn('attr_item_context', template_context)
+
+ def test_entity_form_error_context_assembly(self):
+ """Test Entity form error context assembly - Entity error handling."""
+ entity = self.create_owner_instance(name="Error Context Entity")
+ context = self.create_item_edit_context(entity)
+ builder = self._get_builder()
+ handler = self._get_handler()
+
+ # Create form with errors
+ invalid_data = self.create_invalid_form_data(entity)
+ form_data = handler.create_edit_form_data(
+ attr_item_context=context,
+ form_data=invalid_data
+ )
+
+ # Trigger validation to create errors
+ handler.validate_forms(edit_form_data=form_data)
+
+ template_context = builder.build_response_template_context(
+ attr_item_context=context,
+ edit_form_data=form_data,
+ error_message="Entity validation failed",
+ has_errors=True
+ )
+
+ # Should properly handle Entity form errors
+ self.assertTrue(template_context.get('has_errors', False))
+ self.assertIn('error_message', template_context)
+
+ # Entity form should be available with errors
+ if template_context.get('owner_form'):
+ entity_form = template_context['owner_form']
+ self.assertTrue(hasattr(entity_form, 'errors'))
+
+ def _get_builder(self):
+ """Get builder instance for testing."""
+ from hi.apps.attribute.edit_template_context_builder import AttributeEditTemplateContextBuilder
+ return AttributeEditTemplateContextBuilder()
+
+ def _get_handler(self):
+ """Get handler instance for testing."""
+ from hi.apps.attribute.edit_form_handler import AttributeEditFormHandler
+ return AttributeEditFormHandler()
+
+
+class EntityAttributeViewMixinTest(AttributeViewMixinTestMixin, BaseTestCase):
+ """Test AttributeEditViewMixin with Entity-specific view implementations."""
+
+ def create_owner_instance(self, **kwargs):
+ """Create Entity instance for testing."""
+ return EntityAttributeSyntheticData.create_test_entity(**kwargs)
+
+ def create_attribute_instance(self, owner, **kwargs) -> AttributeModel:
+ """Create EntityAttribute instance for testing."""
+ defaults = {
+ 'entity': owner,
+ 'name': 'test_attribute',
+ 'value': 'test_value',
+ 'attribute_type_str': str(AttributeType.CUSTOM),
+ 'value_type_str': str(AttributeValueType.TEXT),
+ }
+ defaults.update(kwargs)
+ return EntityAttribute.objects.create(**defaults)
+
+ def create_item_edit_context(self, owner):
+ """Create EntityAttributeItemEditContext for testing."""
+ return EntityAttributeItemEditContext(entity=owner)
+
+ def create_valid_form_data(self, owner, **overrides):
+ """Create valid form data for Entity editing."""
+ return EntityAttributeSyntheticData.create_form_data_for_entity_edit(
+ owner, **overrides
+ )
+
+ def create_invalid_form_data(self, owner):
+ """Create invalid form data for Entity editing."""
+ form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(owner)
+ form_data['name'] = ''
+ return form_data
+
+ def create_test_view_instance(self):
+ """Create EntityEditView instance for testing."""
+ return EntityEditView()
+
+ def test_entity_edit_view_integration_workflow(self):
+ """Test complete EntityEditView integration - Entity view integration."""
+ entity = self.create_owner_instance(name="View Integration Entity")
+
+ # Create attributes for comprehensive testing
+ self.create_attribute_instance(
+ entity, name="description", value="Original description"
+ )
+
+ view = self.create_test_view_instance()
+ context = self.create_item_edit_context(entity)
+
+ # Test GET request (initial template context)
+ get_request = self.factory.get(f'/entity/{entity.id}/edit/')
+ get_request.session = self._get_mock_session()
+
+ template_context = view.create_initial_template_context(
+ attr_item_context=context
+ )
+
+ # Should provide complete Entity editing context
+ self.assertIn('entity', template_context)
+ self.assertIn('entity_form', template_context)
+ self.assertIn('regular_attributes_formset', template_context)
+
+ def test_entity_attribute_history_view_integration(self):
+ """Test Entity attribute history integration - Entity history functionality."""
+ entity = self.create_owner_instance(name="History Integration Entity")
+ attribute = self.create_attribute_instance(
+ entity, name="history_attr", value="current_value"
+ )
+
+ view = self.create_test_view_instance()
+ context = self.create_item_edit_context(entity)
+
+ request = self.factory.get(f'/entity/{entity.id}/attr/{attribute.id}/history/')
+ request.session = self._get_mock_session()
+
+ response = view.get_history(
+ request=request,
+ attribute=attribute,
+ attr_item_context=context
+ )
+
+ # Should handle Entity attribute history
+ self.assertEqual(response.status_code, 200)
+
+ def test_entity_concurrent_editing_workflow(self):
+ """Test Entity concurrent editing scenarios - Entity concurrency handling."""
+ entity = self.create_owner_instance(name="Concurrent Test Entity")
+ self.create_attribute_instance(
+ entity, name="concurrent_attr", value="original"
+ )
+
+ view = self.create_test_view_instance()
+ context = self.create_item_edit_context(entity)
+
+ # Simulate form submission while entity is modified externally
+ form_data = self.create_valid_form_data(entity, name="Form Update")
+
+ # External modification
+ entity.name = "External Update"
+ entity.save()
+
+ request = self.factory.post(f'/entity/{entity.id}/edit/', form_data)
+ request.session = self._get_mock_session()
+
+ response = view.post_attribute_form(
+ request=request,
+ attr_item_context=context
+ )
+
+ # Should handle gracefully (may succeed or fail depending on validation)
+ self.assertIn(response.status_code, [200, 400])
+
+ def _get_mock_session(self):
+ """Get mock session for testing."""
+ from hi.testing.base_test_case import MockSession
+ return MockSession()
+
diff --git a/src/hi/apps/entity/tests/test_entity_edit_form_handler.py b/src/hi/apps/entity/tests/test_entity_edit_form_handler.py
deleted file mode 100644
index 71550524..00000000
--- a/src/hi/apps/entity/tests/test_entity_edit_form_handler.py
+++ /dev/null
@@ -1,654 +0,0 @@
-"""
-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.py
deleted file mode 100644
index f8645b06..00000000
--- a/src/hi/apps/entity/tests/test_entity_edit_response_renderer.py
+++ /dev/null
@@ -1,556 +0,0 @@
-"""
-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_file_upload_integration.py b/src/hi/apps/entity/tests/test_file_upload_integration.py
index fd407928..a5f5451d 100644
--- a/src/hi/apps/entity/tests/test_file_upload_integration.py
+++ b/src/hi/apps/entity/tests/test_file_upload_integration.py
@@ -2,7 +2,7 @@
File upload context integration tests.
Tests file storage patterns, upload path generation, file cleanup operations,
-and cross-owner file handling consistency using AttributeEditContext pattern.
+and cross-owner file handling consistency using AttributeItemEditContext pattern.
"""
import logging
from django.core.files.uploadedfile import SimpleUploadedFile
@@ -16,7 +16,7 @@ logging.disable(logging.CRITICAL)
class TestFileUploadContextIntegration(BaseTestCase):
- """Test file upload operations with AttributeEditContext integration."""
+ """Test file upload operations with AttributeItemEditContext integration."""
def setUp(self):
super().setUp()
@@ -38,9 +38,9 @@ class TestFileUploadContextIntegration(BaseTestCase):
file_value=test_file
)
- # Test AttributeEditContext integration
- from hi.apps.entity.entity_attribute_edit_context import EntityAttributeEditContext
- context = EntityAttributeEditContext(self.entity)
+ # Test AttributeItemEditContext integration
+ from hi.apps.entity.entity_attribute_edit_context import EntityAttributeItemEditContext
+ context = EntityAttributeItemEditContext(self.entity)
# Context should provide file-related functionality
file_title_field = context.file_title_field_name(file_attr.id)
@@ -76,8 +76,8 @@ class TestFileUploadContextIntegration(BaseTestCase):
self.assertTrue(hasattr(entity_pdf, 'file_value'))
# Context should handle both file types consistently
- from hi.apps.entity.entity_attribute_edit_context import EntityAttributeEditContext
- context = EntityAttributeEditContext(self.entity)
+ from hi.apps.entity.entity_attribute_edit_context import EntityAttributeItemEditContext
+ context = EntityAttributeItemEditContext(self.entity)
image_field = context.file_title_field_name(entity_image.id)
pdf_field = context.file_title_field_name(entity_pdf.id)
@@ -87,7 +87,7 @@ class TestFileUploadContextIntegration(BaseTestCase):
self.assertRegex(pdf_field, r'^file_title_\d+_\d+$')
def test_file_deletion_context_integration(self):
- """Test file deletion with AttributeEditContext - cleanup workflow integration."""
+ """Test file deletion with AttributeItemEditContext - cleanup workflow integration."""
test_file = SimpleUploadedFile(
"test_delete.txt",
b"content to be deleted",
@@ -103,8 +103,8 @@ class TestFileUploadContextIntegration(BaseTestCase):
file_value=test_file
)
- from hi.apps.entity.entity_attribute_edit_context import EntityAttributeEditContext
- context = EntityAttributeEditContext(self.entity)
+ from hi.apps.entity.entity_attribute_edit_context import EntityAttributeItemEditContext
+ context = EntityAttributeItemEditContext(self.entity)
# Context should provide deletion-related functionality
self.assertEqual(context.owner_id, self.entity.id)
@@ -134,8 +134,8 @@ class TestFileUploadContextIntegration(BaseTestCase):
file_value=test_file
)
- from hi.apps.entity.entity_attribute_edit_context import EntityAttributeEditContext
- context = EntityAttributeEditContext(self.entity)
+ from hi.apps.entity.entity_attribute_edit_context import EntityAttributeItemEditContext
+ context = EntityAttributeItemEditContext(self.entity)
# Get field name that would be used in form
field_name = context.file_title_field_name(file_attr.id)
@@ -155,7 +155,7 @@ class TestFileUploadContextIntegration(BaseTestCase):
"""Test file operations work consistently across Entity and Location - cross-owner compatibility."""
from hi.apps.location.tests.synthetic_data import LocationSyntheticData
from hi.apps.location.models import LocationAttribute
- from hi.apps.location.location_attribute_edit_context import LocationAttributeEditContext
+ from hi.apps.location.location_attribute_edit_context import LocationAttributeItemEditContext
# Create location for comparison
location = LocationSyntheticData.create_test_location(name="File Test Location")
@@ -183,9 +183,9 @@ class TestFileUploadContextIntegration(BaseTestCase):
)
# Create contexts
- from hi.apps.entity.entity_attribute_edit_context import EntityAttributeEditContext
- entity_context = EntityAttributeEditContext(self.entity)
- location_context = LocationAttributeEditContext(location)
+ from hi.apps.entity.entity_attribute_edit_context import EntityAttributeItemEditContext
+ entity_context = EntityAttributeItemEditContext(self.entity)
+ location_context = LocationAttributeItemEditContext(location)
# File field naming should follow same pattern
entity_field = entity_context.file_title_field_name(entity_attr.id)
@@ -199,9 +199,9 @@ class TestFileUploadContextIntegration(BaseTestCase):
entity_template_ctx = entity_context.to_template_context()
location_template_ctx = location_context.to_template_context()
- # Both should have attr_context for template usage
- self.assertIn('attr_context', entity_template_ctx)
- self.assertIn('attr_context', location_template_ctx)
+ # Both should have attr_item_context for template usage
+ self.assertIn('attr_item_context', entity_template_ctx)
+ self.assertIn('attr_item_context', location_template_ctx)
def test_file_mime_type_detection_integration(self):
"""Test MIME type detection works with context integration - file type handling."""
@@ -240,8 +240,8 @@ class TestFileUploadContextIntegration(BaseTestCase):
)
# Context should work with all file types
- from hi.apps.entity.entity_attribute_edit_context import EntityAttributeEditContext
- context = EntityAttributeEditContext(self.entity)
+ from hi.apps.entity.entity_attribute_edit_context import EntityAttributeItemEditContext
+ context = EntityAttributeItemEditContext(self.entity)
# Should generate consistent field names regardless of MIME type
image_field = context.file_title_field_name(image_attr.id)
@@ -264,8 +264,8 @@ class TestFileUploadContextIntegration(BaseTestCase):
file_value=large_file
)
- from hi.apps.entity.entity_attribute_edit_context import EntityAttributeEditContext
- context = EntityAttributeEditContext(self.entity)
+ from hi.apps.entity.entity_attribute_edit_context import EntityAttributeItemEditContext
+ context = EntityAttributeItemEditContext(self.entity)
# Context operations should work efficiently with large files
field_name = context.file_title_field_name(large_attr.id)
@@ -277,27 +277,27 @@ class TestFileUploadContextIntegration(BaseTestCase):
def test_file_upload_form_context_integration(self):
"""Test file upload form integration with context - upload workflow."""
- from hi.apps.entity.entity_attribute_edit_context import EntityAttributeEditContext
- context = EntityAttributeEditContext(self.entity)
+ from hi.apps.entity.entity_attribute_edit_context import EntityAttributeItemEditContext
+ context = EntityAttributeItemEditContext(self.entity)
# Context should provide template integration data
template_ctx = context.to_template_context()
# Should have context data needed for upload forms
- self.assertIn('attr_context', template_ctx)
+ self.assertIn('attr_item_context', template_ctx)
self.assertIn('owner', template_ctx)
self.assertIn('entity', template_ctx)
# Upload form would use these for generating correct field names and URLs
- attr_context = template_ctx['attr_context']
- self.assertEqual(attr_context.owner_type, 'entity')
- self.assertEqual(attr_context.owner_id, self.entity.id)
+ attr_item_context = template_ctx['attr_item_context']
+ self.assertEqual(attr_item_context.owner_type, 'entity')
+ self.assertEqual(attr_item_context.owner_id, self.entity.id)
def test_file_error_handling_context_integration(self):
"""Test file error handling with context integration - error resilience."""
# Test with invalid file operations
- from hi.apps.entity.entity_attribute_edit_context import EntityAttributeEditContext
- context = EntityAttributeEditContext(self.entity)
+ from hi.apps.entity.entity_attribute_edit_context import EntityAttributeItemEditContext
+ context = EntityAttributeItemEditContext(self.entity)
# Context should handle edge cases gracefully
invalid_attr_id = 999999
@@ -337,8 +337,8 @@ class TestFileUploadContextIntegration(BaseTestCase):
file_value=predefined_file
)
- from hi.apps.entity.entity_attribute_edit_context import EntityAttributeEditContext
- context = EntityAttributeEditContext(self.entity)
+ from hi.apps.entity.entity_attribute_edit_context import EntityAttributeItemEditContext
+ context = EntityAttributeItemEditContext(self.entity)
# Context should work with both permission levels
custom_field = context.file_title_field_name(custom_attr.id)
@@ -365,8 +365,8 @@ class TestFileUploadContextIntegration(BaseTestCase):
file_value=test_file
)
- from hi.apps.entity.entity_attribute_edit_context import EntityAttributeEditContext
- context = EntityAttributeEditContext(self.entity)
+ from hi.apps.entity.entity_attribute_edit_context import EntityAttributeItemEditContext
+ context = EntityAttributeItemEditContext(self.entity)
# Context should provide history-related functionality
history_target = context.history_target_id(file_attr.id)
diff --git a/src/hi/apps/entity/tests/test_template_compatibility.py b/src/hi/apps/entity/tests/test_template_compatibility.py
index e83e71a6..98eb25fa 100644
--- a/src/hi/apps/entity/tests/test_template_compatibility.py
+++ b/src/hi/apps/entity/tests/test_template_compatibility.py
@@ -1,13 +1,13 @@
"""
Cross-owner template compatibility tests.
-Verifies that Entity and Location AttributeEditContext implementations work
+Verifies that Entity and Location AttributeItemEditContext implementations work
identically with the same generic templates, ensuring true template generalization.
"""
import logging
from unittest.mock import patch
-from hi.apps.entity.entity_attribute_edit_context import EntityAttributeEditContext
-from hi.apps.location.location_attribute_edit_context import LocationAttributeEditContext
+from hi.apps.entity.entity_attribute_edit_context import EntityAttributeItemEditContext
+from hi.apps.location.location_attribute_edit_context import LocationAttributeItemEditContext
from hi.apps.entity.tests.synthetic_data import EntityAttributeSyntheticData
from hi.apps.location.tests.synthetic_data import LocationSyntheticData
from hi.testing.base_test_case import BaseTestCase
@@ -25,8 +25,8 @@ class TestCrossOwnerTemplateCompatibility(BaseTestCase):
self.location = LocationSyntheticData.create_test_location(name="Test Location")
# Create corresponding contexts
- self.entity_context = EntityAttributeEditContext(self.entity)
- self.location_context = LocationAttributeEditContext(self.location)
+ self.entity_context = EntityAttributeItemEditContext(self.entity)
+ self.location_context = LocationAttributeItemEditContext(self.location)
def test_context_interface_consistency(self):
"""Test both contexts provide identical interface - API compatibility."""
@@ -107,7 +107,7 @@ class TestCrossOwnerTemplateCompatibility(BaseTestCase):
location_keys = set(location_context.keys())
# Common keys that both should have
- common_keys = {'attr_context', 'owner'}
+ common_keys = {'attr_item_context', 'owner'}
self.assertTrue(common_keys.issubset(entity_keys))
self.assertTrue(common_keys.issubset(location_keys))
@@ -127,9 +127,9 @@ class TestCrossOwnerTemplateCompatibility(BaseTestCase):
self.assertIs(entity_context['owner'], self.entity)
self.assertIs(location_context['owner'], self.location)
- # attr_context should be the context instance itself
- self.assertIs(entity_context['attr_context'], self.entity_context)
- self.assertIs(location_context['attr_context'], self.location_context)
+ # attr_item_context should be the context instance itself
+ self.assertIs(entity_context['attr_item_context'], self.entity_context)
+ self.assertIs(location_context['attr_item_context'], self.location_context)
def test_cross_owner_template_filter_compatibility(self):
"""Test template filters work identically with both contexts - filter compatibility."""
@@ -243,13 +243,13 @@ class TestCrossOwnerTemplateCompatibility(BaseTestCase):
def test_inheritance_hierarchy_consistency(self):
"""Test both contexts inherit from same base class - inheritance compatibility."""
- from hi.apps.attribute.edit_context import AttributeEditContext
+ from hi.apps.attribute.edit_context import AttributeItemEditContext
- self.assertIsInstance(self.entity_context, AttributeEditContext)
- self.assertIsInstance(self.location_context, AttributeEditContext)
+ self.assertIsInstance(self.entity_context, AttributeItemEditContext)
+ self.assertIsInstance(self.location_context, AttributeItemEditContext)
# Both should inherit all base methods
- base_methods = [m for m in dir(AttributeEditContext) if not m.startswith('_')]
+ base_methods = [m for m in dir(AttributeItemEditContext) if not m.startswith('_')]
for method in base_methods:
with self.subTest(method=method):
@@ -280,12 +280,8 @@ class TestCrossOwnerTemplateCompatibility(BaseTestCase):
name="Location with & symbols!"
)
- entity_ctx = EntityAttributeEditContext(special_entity)
- location_ctx = LocationAttributeEditContext(special_location)
-
- # Both should handle special characters in names
- self.assertEqual(entity_ctx.owner_name, "Entity with & symbols!")
- self.assertEqual(location_ctx.owner_name, "Location with & symbols!")
+ entity_ctx = EntityAttributeItemEditContext(special_entity)
+ location_ctx = LocationAttributeItemEditContext(special_location)
# DOM IDs should still be generated properly
entity_id = entity_ctx.history_target_id(1)
@@ -303,19 +299,19 @@ class TestCrossOwnerTemplateCompatibility(BaseTestCase):
location_template_ctx = self.location_context.to_template_context()
# Both contexts should allow the same template operations
- # Template would access: {{ owner.name }}, {{ attr_context.owner_id }}, etc.
+ # Template would access: {{ owner.name }}, {{ attr_item_context.owner_id }}, etc.
# Generic owner access
self.assertEqual(entity_template_ctx['owner'].name, "Test Entity")
self.assertEqual(location_template_ctx['owner'].name, "Test Location")
# Context property access
- self.assertIsInstance(entity_template_ctx['attr_context'].owner_id, int)
- self.assertIsInstance(location_template_ctx['attr_context'].owner_id, int)
+ self.assertIsInstance(entity_template_ctx['attr_item_context'].owner_id, int)
+ self.assertIsInstance(location_template_ctx['attr_item_context'].owner_id, int)
# URL parameter access
- self.assertEqual(entity_template_ctx['attr_context'].owner_id_param_name, "entity_id")
- self.assertEqual(location_template_ctx['attr_context'].owner_id_param_name, "location_id")
+ self.assertEqual(entity_template_ctx['attr_item_context'].owner_id_param_name, "entity_id")
+ self.assertEqual(location_template_ctx['attr_item_context'].owner_id_param_name, "location_id")
# This demonstrates that a template using these patterns would work identically
# with both Entity and Location contexts, achieving true generalization
diff --git a/src/hi/apps/entity/tests/test_views.py b/src/hi/apps/entity/tests/test_views.py
index e59a29b1..0fc1d340 100644
--- a/src/hi/apps/entity/tests/test_views.py
+++ b/src/hi/apps/entity/tests/test_views.py
@@ -8,7 +8,6 @@ from django.urls import reverse
from hi.apps.attribute.enums import AttributeValueType
from 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 EntityEditFormHandler
from hi.apps.entity.models import Entity, EntityAttribute
from hi.apps.location.models import Location, LocationView
from hi.apps.location.enums import LocationViewType
@@ -119,7 +118,7 @@ class TestEntityEditView(DualModeViewTestCase):
)
# Modify attribute values
- prefix = EntityEditFormHandler.get_formset_prefix(self.entity)
+ prefix = f'entity-{self.entity.id}'
for i, attr in enumerate(attributes):
if attr == self.text_attr:
formset_data[f'{prefix}-{i}-value'] = 'Updated brightness value'
@@ -200,7 +199,7 @@ class TestEntityEditView(DualModeViewTestCase):
self.entity.refresh_from_db()
self.assertNotEqual(self.entity.name, '')
- def test_post_htmx_response_format(self):
+ def test_post_html_response_format(self):
"""Test that POST responses use correct HTMX/antinode format."""
url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})
@@ -219,11 +218,12 @@ class TestEntityEditView(DualModeViewTestCase):
self.assertSuccessResponse(response)
self.assertJsonResponse(response)
+ self.assertTemplateRendered(response, 'attribute/components/file_card.html')
# Check antinode response structure
data = response.json()
self.assertTrue(
- any(key in data for key in ['insert', 'append', 'modal', 'refresh'])
+ any(key in data for key in ['updates', 'message'])
)
def test_post_with_new_attribute_creation(self):
@@ -236,7 +236,7 @@ class TestEntityEditView(DualModeViewTestCase):
# 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)
+ prefix = f'entity-{self.entity.id}'
formset_data = {
f'{prefix}-TOTAL_FORMS': str(len(existing_attrs) + 2), # +1 existing +1 new
f'{prefix}-INITIAL_FORMS': str(len(existing_attrs)),
@@ -443,7 +443,7 @@ class TestEntityAttributeUploadView(SyncViewTestCase):
# (may return 200 with form errors, or 400, depending on implementation)
self.assertIn(response.status_code, [200, 400]) # Accept either valid response
- @patch('hi.apps.entity.views.transaction.atomic')
+ @patch('hi.apps.attribute.edit_form_handler.transaction.atomic')
def test_upload_uses_transaction(self, mock_atomic):
"""Test that file upload uses database transaction."""
# Configure the mock to return the real transaction atomic context manager
@@ -763,6 +763,8 @@ class TestEntityEditViewFileUploadIntegration(DualModeViewTestCase):
self.assertSuccessResponse(response)
self.assertJsonResponse(response)
+
+ self.assertTemplateRendered(response, 'attribute/components/file_card.html')
# Verify file attribute was created
file_attrs = self.entity.attributes.filter(value_type_str=str(AttributeValueType.FILE))
@@ -771,11 +773,10 @@ class TestEntityEditViewFileUploadIntegration(DualModeViewTestCase):
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)
+ self.assertIn('updates', data)
def test_file_upload_error_handling(self):
"""Test file upload error handling and DOM error display."""
@@ -788,9 +789,15 @@ class TestEntityEditViewFileUploadIntegration(DualModeViewTestCase):
self.assertEqual(response.status_code, 400)
self.assertJsonResponse(response)
- # Verify error DOM update structure
+ # Verify error DOM update structure
data = response.json()
- self.assertIn('insert', data)
+ self.assertIn('updates', data)
+ self.assertFalse(data['success'])
+
+ # Should have error update with replace mode
+ updates = data['updates']
+ self.assertTrue(len(updates) > 0)
+ self.assertEqual(updates[0]['mode'], 'replace')
# Verify no file was created
self.assertEqual(self.entity.attributes.filter(value_type_str=str(AttributeValueType.FILE)).count(), 0)
diff --git a/src/hi/apps/entity/views.py b/src/hi/apps/entity/views.py
index c89b4c01..3d2c6b75 100644
--- a/src/hi/apps/entity/views.py
+++ b/src/hi/apps/entity/views.py
@@ -1,14 +1,10 @@
import logging
from typing import Any, Dict
-from django.db import transaction
from django.http import HttpRequest, HttpResponse
-from django.shortcuts import render
-from django.template.loader import render_to_string
from django.views.generic import View
-from hi.apps.attribute.views import BaseAttributeHistoryView, BaseAttributeRestoreView
-import hi.apps.common.antinode as antinode
+from hi.apps.attribute.view_mixins import AttributeEditViewMixin
from hi.apps.control.controller_history_manager import ControllerHistoryManager
from hi.apps.monitor.status_display_manager import StatusDisplayManager
from hi.apps.sense.sensor_history_manager import SensorHistoryMixin
@@ -16,15 +12,10 @@ from hi.apps.sense.sensor_history_manager import SensorHistoryMixin
from hi.views import page_not_found_response
from hi.hi_async_view import HiModalView
-from hi.constants import DIVID
-
-from .entity_edit_form_handler import EntityEditFormHandler
-from .entity_edit_response_renderer import EntityEditResponseRenderer
-from . import forms
from .models import Entity, EntityAttribute
from .transient_models import EntityStateHistoryData
from .view_mixins import EntityViewMixin
-from .entity_attribute_edit_context import EntityAttributeEditContext
+from .entity_attribute_edit_context import EntityAttributeItemEditContext
logger = logging.getLogger(__name__)
@@ -49,61 +40,6 @@ class EntityStatusView( HiModalView, EntityViewMixin ):
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)
-
- # Delegate form creation and context building to handler
- form_handler: EntityEditFormHandler = EntityEditFormHandler()
- context: Dict[str, Any] = form_handler.create_initial_context(entity)
-
- return self.modal_response(request, context)
-
- 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
- )
-
- 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)
-
- # 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 get_success_url_name(self) -> str:
- return 'entity_edit'
-
-
class EntityStateHistoryView( HiModalView, EntityViewMixin, SensorHistoryMixin ):
ENTITY_STATE_HISTORY_ITEM_MAX = 5
@@ -111,10 +47,7 @@ class EntityStateHistoryView( HiModalView, EntityViewMixin, SensorHistoryMixin )
def get_template_name( self ) -> str:
return 'entity/modals/entity_state_history.html'
- def get( self,
- request : HttpRequest,
- *args : Any,
- **kwargs: Any ) -> HttpResponse:
+ def get( self, request,*args, **kwargs ):
entity: Entity = self.get_entity( request, *args, **kwargs )
sensor_history_list_map = self.sensor_history_manager().get_latest_entity_sensor_history(
entity = entity,
@@ -133,76 +66,47 @@ class EntityStateHistoryView( HiModalView, EntityViewMixin, SensorHistoryMixin )
return self.modal_response( request, context )
-class EntityAttributeUploadView( View, EntityViewMixin ):
+class EntityEditView( HiModalView, EntityViewMixin, AttributeEditViewMixin ):
+ """
+ This view uses a dual response pattern:
+ - get(): Returns full modal using standard modal_response()
+ - post(): Returns custom JSON response with HTML fragments for async DOM updates
+ """
+
+ def get_template_name(self) -> str:
+ return 'entity/modals/entity_edit.html'
+
+ def get( self, request,*args, **kwargs ):
+ entity = self.get_entity(request, *args, **kwargs)
+ attr_item_context = EntityAttributeItemEditContext( entity = entity )
+ template_context = self.create_initial_template_context(
+ attr_item_context= attr_item_context,
+ )
+ return self.modal_response( request, template_context )
+
+ def post( self, request,*args, **kwargs ):
+ entity = self.get_entity(request, *args, **kwargs)
+ attr_item_context = EntityAttributeItemEditContext( entity = entity )
+ return self.post_attribute_form(
+ request = request,
+ attr_item_context = attr_item_context,
+ )
+
+
+class EntityAttributeUploadView( View, EntityViewMixin, AttributeEditViewMixin ):
- 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,
+ def post( self, request,*args, **kwargs ):
+ entity = self.get_entity( request, *args, **kwargs )
+ attr_item_context = EntityAttributeItemEditContext(entity)
+ return self.post_upload(
+ request = request,
+ attr_item_context = attr_item_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
- attr_context = EntityAttributeEditContext(entity)
- context = {'attribute': entity_attribute, 'entity': entity}
- context.update(attr_context.to_template_context())
-
- file_card_html: str = render_to_string(
- 'attribute/components/file_card.html',
- context,
- 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 EntityAttributeHistoryInlineView(BaseAttributeHistoryView):
+class EntityAttributeHistoryInlineView( View, AttributeEditViewMixin ):
"""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,
@@ -211,43 +115,22 @@ class EntityAttributeHistoryInlineView(BaseAttributeHistoryView):
**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)
+ attribute = EntityAttribute.objects.select_related('entity').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 = []
-
- # Create the attribute edit context for template generalization
- attr_context = EntityAttributeEditContext(attribute.entity)
-
- 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(),
- }
-
- # Merge in the context variables from AttributeEditContext
- context.update(attr_context.to_template_context())
-
- # Use Django render shortcut
- return render(request, self.get_template_name(), context)
+
+ attr_item_context = EntityAttributeItemEditContext( entity = attribute.entity )
+ return self.get_history(
+ request = request,
+ attribute = attribute,
+ attr_item_context = attr_item_context,
+ )
-class EntityAttributeRestoreInlineView(BaseAttributeRestoreView):
+class EntityAttributeRestoreInlineView( View, AttributeEditViewMixin ):
"""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,
@@ -255,33 +138,18 @@ class EntityAttributeRestoreInlineView(BaseAttributeRestoreView):
history_id : int,
*args : Any,
**kwargs : Any ) -> HttpResponse:
- # Validate that the attribute belongs to this entity for security
+ """ Need to do restore in a GET since nested in main form and cannot have a form in a form """
+
try:
- attribute: EntityAttribute = EntityAttribute.objects.get(pk=attribute_id, entity_id=entity_id)
+ attribute = EntityAttribute.objects.select_related('entity').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 EntityEditResponseRenderer to return updated modal content
- from .entity_edit_response_renderer import EntityEditResponseRenderer
- renderer: EntityEditResponseRenderer = EntityEditResponseRenderer()
- return renderer.render_success_response(
+
+ attr_item_context = EntityAttributeItemEditContext( entity = attribute.entity )
+ return self.post_restore(
request = request,
- entity = entity,
+ attribute = attribute,
+ history_id = history_id,
+ attr_item_context = attr_item_context,
)
diff --git a/src/hi/apps/location/forms.py b/src/hi/apps/location/forms.py
index 4f73861f..caaa1288 100644
--- a/src/hi/apps/location/forms.py
+++ b/src/hi/apps/location/forms.py
@@ -14,6 +14,11 @@ class LocationAttributeForm( AttributeForm ):
class RegularAttributeBaseFormSet(forms.BaseInlineFormSet):
"""Base formset that automatically excludes FILE attributes for regular attribute editing"""
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ # Apply filtering after parent initialization
+ self.queryset = self.queryset.exclude(value_type_str=str(AttributeValueType.FILE))
+
def get_queryset(self):
"""Override to automatically filter out FILE attributes"""
queryset = super().get_queryset()
@@ -32,7 +37,7 @@ LocationAttributeRegularFormSet = forms.inlineformset_factory(
)
-class LocationModalEditForm( forms.ModelForm ):
+class LocationForm( forms.ModelForm ):
"""
Location edit form for modal - only includes name field.
Geometry fields (svg_view_box_str, order_id) are edited separately.
diff --git a/src/hi/apps/location/location_attribute_edit_context.py b/src/hi/apps/location/location_attribute_edit_context.py
index 31382734..0d4aa7f8 100644
--- a/src/hi/apps/location/location_attribute_edit_context.py
+++ b/src/hi/apps/location/location_attribute_edit_context.py
@@ -1,15 +1,24 @@
"""
-LocationAttributeEditContext - Location-specific context for attribute editing templates.
+LocationAttributeItemEditContext - Location-specific context for attribute editing templates.
-This module contains Location-specific implementations of the AttributeEditContext
+This module contains Location-specific implementations of the AttributeItemEditContext
pattern, encapsulating location-specific domain knowledge while maintaining
the generic template interface.
"""
-from hi.apps.attribute.edit_context import AttributeEditContext
-from .models import Location
+from typing import Any, Dict, Optional, Type
+from django.forms import ModelForm, BaseInlineFormSet
+from django.urls import reverse
-class LocationAttributeEditContext(AttributeEditContext):
+from hi.apps.attribute.edit_context import AttributeItemEditContext
+from hi.apps.attribute.forms import AttributeUploadForm
+from hi.apps.attribute.models import AttributeModel
+
+from .forms import LocationForm, LocationAttributeRegularFormSet, LocationAttributeUploadForm
+from .models import Location, LocationAttribute
+
+
+class LocationAttributeItemEditContext( AttributeItemEditContext ):
"""
Location-specific context provider for attribute editing templates.
@@ -17,17 +26,49 @@ class LocationAttributeEditContext(AttributeEditContext):
the generic interface expected by attribute editing templates.
"""
- def __init__(self, location: Location) -> None:
+ def __init__(self, location: Location ) -> None:
"""
Initialize context for Location attribute editing.
Args:
location: The Location instance that owns the attributes
"""
- super().__init__(location, 'location')
+ super().__init__( owner_type = 'location', owner = location)
+ return
@property
def location(self) -> Location:
"""Get the Location instance (typed accessor)."""
return self.owner
+ @property
+ def attribute_model_subclass(self) -> Type[AttributeModel]:
+ return LocationAttribute
+
+ @property
+ def attribute_upload_form_class(self) -> Type[AttributeUploadForm]:
+ return LocationAttributeUploadForm
+
+ def create_owner_form( self, form_data : Optional[ Dict[str, Any] ] = None ) -> ModelForm:
+ return LocationForm( form_data, instance = self.location )
+
+ def create_attribute_model( self ) -> AttributeModel:
+ return LocationAttribute( location = self.location )
+
+ def create_regular_attributes_formset(
+ self, form_data : Optional[ Dict[str, Any] ] = None ) -> BaseInlineFormSet:
+ return LocationAttributeRegularFormSet(
+ form_data,
+ instance = self.location,
+ prefix = self.formset_prefix,
+ )
+
+ @property
+ def content_body_template_name(self):
+ return 'location/panes/location_edit_content_body.html'
+
+ @property
+ def file_upload_url(self) -> str:
+ return reverse( 'location_attribute_upload',
+ kwargs = { 'location_id': self.location.id })
+
diff --git a/src/hi/apps/location/location_edit_form_handler.py b/src/hi/apps/location/location_edit_form_handler.py
deleted file mode 100644
index 1abc5bd7..00000000
--- a/src/hi/apps/location/location_edit_form_handler.py
+++ /dev/null
@@ -1,250 +0,0 @@
-"""
-LocationEditFormHandler - Handles form creation, validation, and file processing for location editing.
-
-This class follows the same pattern as EntityEditFormHandler, encapsulating the complex
-form-handling business logic that was previously embedded in LocationEditView, 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 Location, LocationAttribute
-from .forms import LocationAttributeRegularFormSet, LocationModalEditForm
-from .location_attribute_edit_context import LocationAttributeEditContext
-
-logger = logging.getLogger(__name__)
-
-
-class LocationEditFormHandler:
- """
- Handles form creation, validation, and file processing for location editing.
-
- This class encapsulates business logic for:
- - Creating and managing location forms and formsets
- - Processing file deletions and title updates
- - Collecting and formatting form validation errors
- """
-
- @staticmethod
- def get_formset_prefix(location: Location) -> 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:
- location: Location instance
-
- Returns:
- str: The prefix to use for the regular attributes formset
- """
- return f'location-{location.id}'
-
- def create_location_forms(
- self,
- location : Location,
- form_data : Optional[Dict[str, Any]] = None
- ) -> Tuple[LocationModalEditForm, QuerySet[LocationAttribute], LocationAttributeRegularFormSet]:
- """Create location forms used by both initial rendering and fragment updates.
-
- Args:
- location: Location instance
- form_data: POST data for bound forms, None for unbound forms
-
- Returns:
- tuple: (location_form, file_attributes, regular_attributes_formset)
- """
- # Create location form (only name field for this modal)
- location_form: LocationModalEditForm = LocationModalEditForm(form_data, instance=location)
-
- # Get file attributes for display (not a formset, just for template rendering)
- file_attributes: QuerySet[LocationAttribute] = location.attributes.filter(
- value_type_str=str(AttributeValueType.FILE)
- ).order_by('id')
-
- # Regular attributes formset (automatically excludes FILE attributes)
- regular_attributes_formset: LocationAttributeRegularFormSet = LocationAttributeRegularFormSet(
- form_data,
- instance=location,
- prefix=self.get_formset_prefix(location),
- form_kwargs={
- 'show_as_editable': True,
- }
- )
-
- return location_form, file_attributes, regular_attributes_formset
-
- def validate_forms( self,
- location_form : LocationModalEditForm,
- regular_attributes_formset : LocationAttributeRegularFormSet ) -> bool:
- """
- Validate location form and property attributes formset.
-
- Args:
- location_form: LocationModalEditForm instance
- regular_attributes_formset: LocationAttributeRegularFormSet instance
-
- Returns:
- bool: True if both forms are valid, False otherwise
- """
- return location_form.is_valid() and regular_attributes_formset.is_valid()
-
- def save_forms( self,
- location_form : LocationModalEditForm,
- regular_attributes_formset : LocationAttributeRegularFormSet,
- request : HttpRequest,
- location : Location ) -> None:
- """
- Save forms and process file operations within a transaction.
-
- Args:
- location_form: LocationModalEditForm instance
- regular_attributes_formset: LocationAttributeRegularFormSet instance
- request: HTTP request object
- location: Location instance
- """
- with transaction.atomic():
- location_form.save()
- regular_attributes_formset.save()
-
- # Process file deletions
- self.process_file_deletions(request, location)
-
- # Process file title updates
- self.process_file_title_updates(request, location)
-
- def process_file_deletions( self,
- request : HttpRequest,
- location : Location ) -> 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: LocationAttribute = LocationAttribute.objects.get(
- id=attr_id,
- location=location,
- value_type_str=str(AttributeValueType.FILE)
- )
- # Verify permission to delete
- if file_attribute.attribute_type.can_delete:
- file_attribute.delete()
- except LocationAttribute.DoesNotExist:
- pass
-
- def process_file_title_updates( self,
- request : HttpRequest,
- location : Location ) -> None:
- """Process file_title_* fields from POST data to update file attribute values."""
- # Pattern to match file_title_{location_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
-
- location_id_str: str
- attribute_id_str: str
- location_id_str, attribute_id_str = match.groups()
-
- # Validate location_id matches current location
- if int(location_id_str) != location.id:
- logger.warning(f'File title field {field_name} has mismatched location ID')
- continue
-
- try:
- attribute_id: int = int(attribute_id_str)
- attribute: LocationAttribute = LocationAttribute.objects.get(
- pk=attribute_id,
- location=location,
- 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, LocationAttribute.DoesNotExist) as e:
- logger.warning(f'Invalid file title field {field_name}: {e}')
-
- def collect_form_errors( self,
- location_form : LocationModalEditForm,
- regular_attributes_formset : LocationAttributeRegularFormSet ) -> List[str]:
- """Collect non-field errors from forms for enhanced error messaging.
-
- Args:
- location_form: LocationModalEditForm instance
- regular_attributes_formset: LocationAttributeRegularFormSet instance
-
- Returns:
- list: Formatted error messages with context prefixes
- """
- non_field_errors: List[str] = []
-
- # Location form non-field errors
- if ( location_form
- and hasattr(location_form, 'non_field_errors')
- and location_form.non_field_errors() ):
- non_field_errors.extend([f"Location: {error}"
- for error in location_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,
- location : Location ) -> Dict[str, Any]:
- """Create initial template context for location editing form.
-
- Args:
- location: Location instance
-
- Returns:
- dict: Template context for initial form display
- """
- location_form, file_attributes, regular_attributes_formset = self.create_location_forms(location)
-
- # Create the attribute edit context for template generalization
- attr_context = LocationAttributeEditContext(location)
-
- # Build context with both old and new patterns for compatibility
- context = {
- 'location': location,
- 'location_form': location_form,
- 'owner_form': location_form, # Generic alias for templates
- 'file_attributes': file_attributes,
- 'regular_attributes_formset': regular_attributes_formset,
- }
-
- # Merge in the context variables from AttributeEditContext
- context.update(attr_context.to_template_context())
-
- return context
diff --git a/src/hi/apps/location/location_edit_response_renderer.py b/src/hi/apps/location/location_edit_response_renderer.py
deleted file mode 100644
index f3ef2dbd..00000000
--- a/src/hi/apps/location/location_edit_response_renderer.py
+++ /dev/null
@@ -1,215 +0,0 @@
-"""
-LocationEditResponseRenderer - Handles template rendering and response generation for location editing.
-
-This class follows the same pattern as EntityEditResponseRenderer, encapsulating the complex
-rendering and response logic that was previously embedded in LocationEditView, 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 .location_edit_form_handler import LocationEditFormHandler
-from .models import Location, LocationAttribute
-from .forms import LocationAttributeRegularFormSet, LocationModalEditForm
-from .location_attribute_edit_context import LocationAttributeEditContext
-
-
-class LocationEditResponseRenderer:
- """
- Handles template rendering and response generation for location 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: LocationEditFormHandler = LocationEditFormHandler()
-
- def build_template_context( self,
- location : Location,
- location_form : LocationModalEditForm,
- file_attributes : QuerySet[LocationAttribute],
- regular_attributes_formset : LocationAttributeRegularFormSet,
- success_message : Optional[str] = None,
- error_message : Optional[str] = None,
- has_errors : bool = False ) -> Dict[str, Any]:
- """Build context dictionary for template rendering.
-
- Args:
- location: Location instance
- location_form: LocationModalEditForm instance
- file_attributes: QuerySet of file attributes
- regular_attributes_formset: LocationAttributeRegularFormSet 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(location_form, regular_attributes_formset)
-
- # Create the attribute edit context for template generalization
- attr_context = LocationAttributeEditContext(location)
-
- # Build context with both old and new patterns for compatibility
- context = {
- 'location': location,
- 'location_form': location_form,
- 'owner_form': location_form, # Generic alias for templates
- '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,
- }
-
- # Merge in the context variables from AttributeEditContext
- context.update(attr_context.to_template_context())
-
- return context
-
- def render_update_fragments( self,
- request : HttpRequest,
- location : Location,
- location_form : Optional[LocationModalEditForm] = None,
- regular_attributes_formset : Optional[LocationAttributeRegularFormSet] = 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
- location: Location instance
- location_form: Optional location 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 location_form is None or regular_attributes_formset is None:
- fresh_location_form, file_attributes, fresh_property_formset = self.form_handler.create_location_forms(location)
- if location_form is None:
- location_form = fresh_location_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_location_forms(location)
-
- # Build template context
- context: Dict[str, Any] = self.build_template_context(
- location, location_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,
- location=location,
- )
-
- def render_content_fragments( self,
- request : HttpRequest,
- context : Dict[str, Any],
- location : Location ) -> Tuple[str, str]:
- """Render both content body and upload form fragments.
-
- Args:
- request: HTTP request object
- context: Template context dictionary
- location: Location instance
-
- Returns:
- tuple: (content_body_html, upload_form_html)
- """
- # Render both fragments
- content_body: str = render_to_string('location/panes/location_edit_content_body.html', context, request=request)
-
- # Upload form needs to be specific to location
- file_upload_url: str = reverse('location_attribute_upload',
- kwargs={'location_id': location.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,
- location : Location ) -> 'antinode.Response':
- """Render success response using antinode helpers - multiple target replacement.
-
- Args:
- request: HTTP request object
- location: Location 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,
- location=location,
- 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,
- location : Location,
- location_form : LocationModalEditForm,
- regular_attributes_formset : LocationAttributeRegularFormSet ) -> 'antinode.Response':
- """Render error response using antinode helpers - multiple target replacement.
-
- Args:
- request: HTTP request object
- location: Location instance
- location_form: LocationModalEditForm 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,
- location=location,
- location_form=location_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/location/templates/location/modals/location_edit.html b/src/hi/apps/location/templates/location/modals/location_edit.html
index 1ed36555..c3cb3add 100644
--- a/src/hi/apps/location/templates/location/modals/location_edit.html
+++ b/src/hi/apps/location/templates/location/modals/location_edit.html
@@ -5,40 +5,46 @@
{% block title_text %}{{ location.name }}{% endblock %}
{% block body %}
-<form id="{{ DIVID.ATTR_V2_FORM }}"
- action="{% url 'location_edit_location_edit' location_id=location.id %}"
- method="post"
- class="form {{ DIVID.ATTR_V2_MODAL_CLASS }}"
- data-async="true"
- data-stay-in-modal="true"
- enctype="multipart/form-data">
- {% csrf_token %}
+<!-- Root container for this attribute editing context -->
+<div id="{{ attr_page_context.container_html_id }}"
+ class="{{ DIVID.ATTR_V2_CONTAINER_CLASS }}" >
-<!-- Main content wrapper for antinode updates -->
-<div id="{{ DIVID.ATTR_V2_CONTENT }}">
- {% include "location/panes/location_edit_content_body.html" %}
-</div>
-</form>
-
-<!-- File Upload Form Container (separate from main form to avoid nesting) -->
-<div id="{{ DIVID.ATTR_V2_UPLOAD_FORM_CONTAINER }}">
- {% url 'location_attribute_upload' location_id=location.id as file_upload_url %}
- {% include "attribute/components/upload_form.html" with file_upload_url=file_upload_url %}
-</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">&times;</span>
- </button>
+ <div class="{{ DIVID.ATTR_V2_FORM_CLASS }}">
+ <form id="{{ attr_page_context.form_html_id }}"
+ action="{% url 'location_edit_location_edit' location_id=location.id %}"
+ method="post"
+ class="{{ DIVID.ATTR_V2_FORM_CLASS }} form"
+ enctype="multipart/form-data">
+ {% csrf_token %}
+
+ <!-- Main content wrapper for antinode updates -->
+ <div id="{{ attr_page_context.content_html_id }}"
+ class="{{ DIVID.ATTR_V2_CONTENT_CLASS }}">
+ {% include "location/panes/location_edit_content_body.html" %}
</div>
- {% endfor %}
+ </form>
</div>
-{% endif %}
+
+ <!-- File Upload Form Container (separate from main form to avoid nesting) -->
+ <div id="{{ attr_item_context.upload_form_container_html_id }}">
+ {% url 'location_attribute_upload' location_id=location.id as file_upload_url %}
+ {% include "attribute/components/upload_form.html" with file_upload_url=file_upload_url %}
+ </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">&times;</span>
+ </button>
+ </div>
+ {% endfor %}
+ </div>
+ {% endif %}
+</div>
<!-- JavaScript for V2 functionality loaded via Django Pipeline js_before_content bundle -->
diff --git a/src/hi/apps/location/tests/synthetic_data.py b/src/hi/apps/location/tests/synthetic_data.py
index b5303594..bebb0c9e 100644
--- a/src/hi/apps/location/tests/synthetic_data.py
+++ b/src/hi/apps/location/tests/synthetic_data.py
@@ -5,9 +5,12 @@ 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 typing import Optional, Dict, Any, List
+from django.core.files.uploadedfile import SimpleUploadedFile
-from hi.apps.location.models import Location, LocationView
+from hi.constants import DIVID
+from hi.apps.attribute.enums import AttributeType, AttributeValueType
+from hi.apps.location.models import Location, LocationView, LocationAttribute
from hi.apps.entity.models import Entity, EntityPosition
from hi.apps.collection.models import Collection, CollectionPosition
from hi.apps.entity.enums import EntityType
@@ -108,3 +111,202 @@ class LocationSyntheticData:
**position_kwargs
)
return collection
+
+
+class LocationAttributeSyntheticData:
+ """Centralized synthetic data generators for location attribute testing."""
+
+ @staticmethod
+ def create_test_location(**kwargs) -> Location:
+ """Create a test location with reasonable defaults."""
+ # Generate unique name to avoid constraint violations
+ 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_text_attribute(location: Optional[Location] = None, **kwargs) -> LocationAttribute:
+ """Create a text attribute with reasonable defaults."""
+ if location is None:
+ location = LocationAttributeSyntheticData.create_test_location()
+
+ defaults = {
+ 'location': location,
+ 'name': 'test_property',
+ 'value': 'test value',
+ 'attribute_type_str': str(AttributeType.CUSTOM),
+ 'value_type_str': str(AttributeValueType.TEXT),
+ }
+ defaults.update(kwargs)
+ return LocationAttribute.objects.create(**defaults)
+
+ @staticmethod
+ def create_test_file_attribute(location: Optional[Location] = None, **kwargs) -> LocationAttribute:
+ """Create a file attribute with reasonable defaults."""
+ if location is None:
+ location = LocationAttributeSyntheticData.create_test_location()
+
+ # 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 = {
+ 'location': location,
+ 'name': 'test_document',
+ 'value': 'Test Document Title',
+ 'attribute_type_str': str(AttributeType.CUSTOM),
+ 'value_type_str': str(AttributeValueType.FILE),
+ }
+ defaults.update(kwargs)
+ return LocationAttribute.objects.create(**defaults)
+
+ @staticmethod
+ def create_test_secret_attribute(location: Optional[Location] = None, **kwargs) -> LocationAttribute:
+ """Create a secret attribute with reasonable defaults."""
+ if location is None:
+ location = LocationAttributeSyntheticData.create_test_location()
+
+ defaults = {
+ 'location': location,
+ 'name': 'api_key',
+ 'value': 'secret_api_key_12345',
+ 'attribute_type_str': str(AttributeType.CUSTOM),
+ 'value_type_str': str(AttributeValueType.SECRET),
+ }
+ defaults.update(kwargs)
+ return LocationAttribute.objects.create(**defaults)
+
+ @staticmethod
+ def create_location_with_mixed_attributes(**location_kwargs) -> Location:
+ """Create a location with a variety of attribute types for comprehensive testing."""
+ location = LocationAttributeSyntheticData.create_test_location(**location_kwargs)
+
+ # Create various attribute types
+ LocationAttributeSyntheticData.create_test_text_attribute(
+ location=location, name='description', value='Test location for mixed testing'
+ )
+ LocationAttributeSyntheticData.create_test_secret_attribute(
+ location=location, name='access_code', value='super_secret_code'
+ )
+ LocationAttributeSyntheticData.create_test_file_attribute(
+ location=location, name='floor_plan', value='Floor Plan Document'
+ )
+
+ return location
+
+ @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_location_edit(location: Location, **overrides) -> Dict[str, Any]:
+ """Create complete form data dictionary for location editing form submissions.
+
+ Includes both location form data and formset data for regular attributes.
+ """
+ # Location form data
+ form_data = {
+ 'name': location.name,
+ 'svg_fragment_filename': location.svg_fragment_filename,
+ 'svg_view_box_str': location.svg_view_box_str,
+ }
+ form_data.update(overrides)
+
+ # Add formset data for regular attributes (non-file attributes)
+ regular_attributes = list(location.attributes.exclude(
+ value_type_str=str(AttributeValueType.FILE)
+ ).order_by('id'))
+
+ # Use LocationEditFormHandler as the single source of truth for prefix logic
+ prefix = f'location-{location.id}'
+
+ # 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[LocationAttribute], location: Location) -> Dict[str, Any]:
+ """Create formset data dictionary for attribute formset submissions."""
+ prefix = f'location-{location.id}'
+ 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(location: Location, file_attributes: List[LocationAttribute]) -> Dict[str, str]:
+ """Create POST data for file title updates."""
+ data = {}
+ for attr in file_attributes:
+ field_name = f'file_title_{location.id}_{attr.id}'
+ data[field_name] = f'Updated {attr.name}'
+ return data
+
+ @staticmethod
+ def create_file_deletion_data(file_attributes: List[LocationAttribute]) -> Dict[str, List[str]]:
+ """Create POST data for file deletions."""
+ return {
+ DIVID['ATTR_V2_DELETE_FILE_ATTR']: [str(attr.id) for attr in file_attributes]
+ }
diff --git a/src/hi/apps/location/tests/test_location_attribute_edit_context.py b/src/hi/apps/location/tests/test_location_attribute_edit_context.py
index fd75004d..46cdd601 100644
--- a/src/hi/apps/location/tests/test_location_attribute_edit_context.py
+++ b/src/hi/apps/location/tests/test_location_attribute_edit_context.py
@@ -1,19 +1,19 @@
"""
-Tests for LocationAttributeEditContext.
+Tests for LocationAttributeItemEditContext.
Focuses on Location-specific context generation, URL patterns, and integration
with LocationAttribute model relationships.
"""
import logging
-from hi.apps.location.location_attribute_edit_context import LocationAttributeEditContext
+from hi.apps.location.location_attribute_edit_context import LocationAttributeItemEditContext
from hi.apps.location.tests.synthetic_data import LocationSyntheticData
from hi.testing.base_test_case import BaseTestCase
logging.disable(logging.CRITICAL)
-class TestLocationAttributeEditContext(BaseTestCase):
- """Test LocationAttributeEditContext location-specific functionality."""
+class TestLocationAttributeItemEditContext(BaseTestCase):
+ """Test LocationAttributeItemEditContext location-specific functionality."""
def setUp(self):
super().setUp()
@@ -21,14 +21,13 @@ class TestLocationAttributeEditContext(BaseTestCase):
name="Test Location",
svg_fragment_filename="test-location.svg"
)
- self.context = LocationAttributeEditContext(self.location)
+ self.context = LocationAttributeItemEditContext(self.location)
def test_location_context_initialization(self):
- """Test LocationAttributeEditContext initializes with correct owner type."""
+ """Test LocationAttributeItemEditContext initializes with correct owner type."""
self.assertEqual(self.context.owner_type, "location")
self.assertEqual(self.context.owner, self.location)
self.assertEqual(self.context.owner_id, self.location.id)
- self.assertEqual(self.context.owner_name, self.location.name)
def test_location_property_accessor(self):
"""Test typed location property accessor - provides type safety."""
@@ -57,7 +56,7 @@ class TestLocationAttributeEditContext(BaseTestCase):
template_context = self.context.to_template_context()
# Should include generic keys
- self.assertIn('attr_context', template_context)
+ self.assertIn('attr_item_context', template_context)
self.assertIn('owner', template_context)
# Should include location-specific key
@@ -73,11 +72,10 @@ class TestLocationAttributeEditContext(BaseTestCase):
name="Another Location",
svg_fragment_filename="another-location.svg"
)
- context2 = LocationAttributeEditContext(location2)
+ context2 = LocationAttributeItemEditContext(location2)
# Should have different IDs and names
self.assertNotEqual(self.context.owner_id, context2.owner_id)
- self.assertNotEqual(self.context.owner_name, context2.owner_name)
# But same URL patterns
self.assertEqual(self.context.history_url_name, context2.history_url_name)
@@ -113,10 +111,9 @@ class TestLocationAttributeEditContext(BaseTestCase):
self.assertIn(location_id_str, field_name)
def test_location_context_inheritance_behavior(self):
- """Test LocationAttributeEditContext properly inherits base functionality."""
+ """Test LocationAttributeItemEditContext properly inherits base functionality."""
# Should inherit all base class methods
self.assertTrue(hasattr(self.context, 'owner_id'))
- self.assertTrue(hasattr(self.context, 'owner_name'))
self.assertTrue(hasattr(self.context, 'owner_id_param_name'))
self.assertTrue(hasattr(self.context, 'history_url_name'))
self.assertTrue(hasattr(self.context, 'restore_url_name'))
@@ -132,9 +129,7 @@ class TestLocationAttributeEditContext(BaseTestCase):
name="Location with & special chars!",
svg_fragment_filename="special-location.svg"
)
- special_context = LocationAttributeEditContext(special_location)
-
- self.assertEqual(special_context.owner_name, "Location with & special chars!")
+ special_context = LocationAttributeItemEditContext(special_location)
# DOM IDs should still be generated properly
history_id = special_context.history_target_id(123)
@@ -148,7 +143,7 @@ class TestLocationAttributeEditContext(BaseTestCase):
name="Location with Attributes"
)
- context = LocationAttributeEditContext(location_with_attrs)
+ context = LocationAttributeItemEditContext(location_with_attrs)
# Context should work with the location regardless of attribute count
self.assertEqual(context.location, location_with_attrs)
@@ -159,24 +154,18 @@ class TestLocationAttributeEditContext(BaseTestCase):
self.assertIs(template_ctx['location'], location_with_attrs)
def test_location_context_multiple_instances_isolation(self):
- """Test multiple LocationAttributeEditContext instances don't interfere - instance isolation."""
+ """Test multiple LocationAttributeItemEditContext instances don't interfere - instance isolation."""
location1 = LocationSyntheticData.create_test_location(name="Location 1")
location2 = LocationSyntheticData.create_test_location(name="Location 2")
- context1 = LocationAttributeEditContext(location1)
- context2 = LocationAttributeEditContext(location2)
+ context1 = LocationAttributeItemEditContext(location1)
+ context2 = LocationAttributeItemEditContext(location2)
# Contexts should be independent
self.assertNotEqual(context1.owner_id, context2.owner_id)
- self.assertNotEqual(context1.owner_name, context2.owner_name)
-
- # Modifying one location shouldn't affect the other context
- location1.name = "Modified Location 1"
- self.assertEqual(context1.owner_name, "Modified Location 1")
- self.assertEqual(context2.owner_name, "Location 2") # Should be unchanged
-
+
def test_location_context_type_consistency(self):
- """Test LocationAttributeEditContext maintains type consistency - type safety."""
+ """Test LocationAttributeItemEditContext maintains type consistency - type safety."""
# owner_type should always be 'location'
self.assertEqual(self.context.owner_type, "location")
diff --git a/src/hi/apps/location/tests/test_location_attribute_framework.py b/src/hi/apps/location/tests/test_location_attribute_framework.py
new file mode 100644
index 00000000..3ce806ed
--- /dev/null
+++ b/src/hi/apps/location/tests/test_location_attribute_framework.py
@@ -0,0 +1,531 @@
+"""
+Concrete test implementations for Location attribute editing framework.
+
+These tests extend the abstract base classes to provide comprehensive testing
+of the attribute framework as implemented for Location models. Tests both the
+framework components and Location-specific customizations.
+
+Following project testing guidelines:
+- No mocked objects, use real Location and LocationAttribute models
+- Focus on high-value business logic and integration points
+- Use LocationAttributeSyntheticData for test data generation
+- Test meaningful Location-specific edge cases and workflows
+"""
+import logging
+
+from django.core.files.uploadedfile import SimpleUploadedFile
+
+from hi.apps.attribute.tests.attribute_framework_test_base import (
+ AttributeEditFormHandlerTestMixin,
+ AttributeEditResponseRendererTestMixin,
+ AttributeEditTemplateContextBuilderTestMixin,
+ AttributeViewMixinTestMixin,
+)
+from hi.testing.base_test_case import BaseTestCase
+from hi.apps.attribute.enums import AttributeType, AttributeValueType
+from hi.apps.attribute.models import AttributeModel
+from hi.apps.location.location_attribute_edit_context import LocationAttributeItemEditContext
+from hi.apps.location.models import LocationAttribute
+from hi.apps.location.tests.synthetic_data import LocationAttributeSyntheticData
+from hi.apps.location.views import LocationEditView
+
+logging.disable(logging.CRITICAL)
+
+
+class LocationAttributeEditFormHandlerTest(AttributeEditFormHandlerTestMixin, BaseTestCase):
+ """Test AttributeEditFormHandler with Location-specific implementations."""
+
+ def create_owner_instance(self, **kwargs):
+ """Create Location instance for testing."""
+ return LocationAttributeSyntheticData.create_test_location(**kwargs)
+
+ def create_attribute_instance(self, owner, **kwargs) -> AttributeModel:
+ """Create LocationAttribute instance for testing."""
+ value_type = kwargs.get('value_type_str', str(AttributeValueType.TEXT))
+
+ # Use synthetic data method for file attributes to ensure proper file handling
+ if value_type == str(AttributeValueType.FILE):
+ return LocationAttributeSyntheticData.create_test_file_attribute(location=owner, **kwargs)
+
+ # For non-file attributes, use direct creation
+ defaults = {
+ 'location': owner,
+ 'name': 'test_attribute',
+ 'value': 'test_value',
+ 'attribute_type_str': str(AttributeType.CUSTOM),
+ 'value_type_str': value_type,
+ }
+ defaults.update(kwargs)
+ return LocationAttribute.objects.create(**defaults)
+
+ def create_item_edit_context(self, owner):
+ """Create LocationAttributeItemEditContext for testing."""
+ return LocationAttributeItemEditContext(location=owner)
+
+ def create_valid_form_data(self, owner, **overrides):
+ """Create valid form data for Location editing."""
+ return LocationAttributeSyntheticData.create_form_data_for_location_edit(
+ owner, **overrides
+ )
+
+ def create_invalid_form_data(self, owner):
+ """Create invalid form data for Location editing - empty name."""
+ form_data = LocationAttributeSyntheticData.create_form_data_for_location_edit(owner)
+ form_data['name'] = '' # Invalid empty name
+ return form_data
+
+ def test_location_specific_form_validation_business_logic(self):
+ """Test Location-specific form validation rules - business logic validation."""
+ location = self.create_owner_instance(name="Location Validation Test")
+ context = self.create_item_edit_context(location)
+ handler = self._get_handler()
+
+ # Test location name validation
+ invalid_data = self.create_valid_form_data(location)
+ invalid_data['name'] = '' # Location requires name
+
+ form_data = handler.create_edit_form_data(
+ attr_item_context=context,
+ form_data=invalid_data
+ )
+
+ is_valid = handler.validate_forms(edit_form_data=form_data)
+ self.assertFalse(is_valid)
+
+ # Location form should have name error
+ if form_data.owner_form:
+ self.assertIn('name', form_data.owner_form.errors)
+
+ def test_location_svg_field_validation(self):
+ """Test Location SVG field validation - Location-specific validation."""
+ location = self.create_owner_instance(name="SVG Validation Test")
+ context = self.create_item_edit_context(location)
+ handler = self._get_handler()
+
+ # Test invalid SVG viewBox format
+ invalid_data = self.create_valid_form_data(location)
+ invalid_data['svg_view_box_str'] = 'invalid viewbox format'
+
+ form_data = handler.create_edit_form_data(
+ attr_item_context=context,
+ form_data=invalid_data
+ )
+
+ is_valid = handler.validate_forms(edit_form_data=form_data)
+ # May be valid or invalid depending on form validation rules
+ self.assertIsInstance(is_valid, bool)
+
+ def test_location_attribute_formset_creation_patterns(self):
+ """Test Location-specific formset creation patterns - Location formset logic."""
+ location = self.create_owner_instance(name="Formset Test Location")
+
+ # Create mixed attribute types
+ self.create_attribute_instance(
+ location, name="description", value="location description",
+ value_type_str=str(AttributeValueType.TEXT)
+ )
+ self.create_attribute_instance(
+ location, name="floor_plan", value="Floor Plan",
+ value_type_str=str(AttributeValueType.FILE)
+ )
+
+ context = self.create_item_edit_context(location)
+ handler = self._get_handler()
+
+ form_data = handler.create_edit_form_data(attr_item_context=context)
+
+ # File attributes should be excluded from regular formset
+ # Check if formset has initial data or get from the formset's queryset
+ if form_data.regular_attributes_formset.initial:
+ formset_data = list(form_data.regular_attributes_formset.initial)
+ formset_names = [attr.get('name') for attr in formset_data]
+ else:
+ # Get names from the formset's queryset
+ formset_names = [attr.name for attr in form_data.regular_attributes_formset.queryset]
+
+ self.assertIn("description", formset_names)
+ self.assertNotIn("floor_plan", formset_names)
+
+ # File attributes should be in separate queryset
+ file_attr_names = [attr.name for attr in form_data.file_attributes]
+ self.assertIn("floor_plan", file_attr_names)
+ self.assertNotIn("description", file_attr_names)
+
+ def test_location_file_upload_integration(self):
+ """Test Location file upload handling - Location file operations."""
+ location = self.create_owner_instance(name="File Upload Location")
+ context = self.create_item_edit_context(location)
+
+ # Location should support file uploads
+ self.assertIsNotNone(context.attribute_upload_form_class)
+ self.assertTrue(context.uses_file_uploads)
+
+ # Test file context setup
+ self.assertIsNotNone(context.file_upload_url)
+
+ # Test file handling patterns
+ test_file = SimpleUploadedFile(
+ "location_plan.pdf",
+ b"Location test file content",
+ content_type="application/pdf"
+ )
+
+ from hi.testing.base_test_case import MockRequest, MockSession
+ request = MockRequest()
+ request.POST = {
+ 'name': 'location_document',
+ 'value': 'Location Test Document'
+ }
+ request.FILES = {'file_value': test_file}
+ request.session = MockSession()
+
+ # Should handle file upload processing context
+ initial_count = LocationAttribute.objects.filter(
+ location=location,
+ value_type_str=str(AttributeValueType.FILE)
+ ).count()
+
+ # File handling workflow tested at view level
+ self.assertIsInstance(initial_count, int)
+
+ def test_location_specific_edge_cases(self):
+ """Test Location-specific edge cases - Location edge case handling."""
+ location = self.create_owner_instance(
+ name="Edge Case Location",
+ svg_view_box_str="0 0 1000 1000" # Different dimensions
+ )
+ context = self.create_item_edit_context(location)
+ handler = self._get_handler()
+
+ # Test with very long location name
+ long_name = "A" * 200
+ form_data = self.create_valid_form_data(location, name=long_name)
+
+ edit_form_data = handler.create_edit_form_data(
+ attr_item_context=context,
+ form_data=form_data
+ )
+
+ # Should handle long names according to model constraints
+ is_valid = handler.validate_forms(edit_form_data=edit_form_data)
+ self.assertIsInstance(is_valid, bool)
+
+ def _get_handler(self):
+ """Get handler instance for testing."""
+ from hi.apps.attribute.edit_form_handler import AttributeEditFormHandler
+ return AttributeEditFormHandler()
+
+
+class LocationAttributeEditResponseRendererTest(AttributeEditResponseRendererTestMixin, BaseTestCase):
+ """Test AttributeEditResponseRenderer with Location-specific implementations."""
+
+ def create_owner_instance(self, **kwargs):
+ """Create Location instance for testing."""
+ return LocationAttributeSyntheticData.create_test_location(**kwargs)
+
+ def create_attribute_instance(self, owner, **kwargs) -> AttributeModel:
+ """Create LocationAttribute instance for testing."""
+ defaults = {
+ 'location': owner,
+ 'name': 'test_attribute',
+ 'value': 'test_value',
+ 'attribute_type_str': str(AttributeType.CUSTOM),
+ 'value_type_str': str(AttributeValueType.TEXT),
+ }
+ defaults.update(kwargs)
+ return LocationAttribute.objects.create(**defaults)
+
+ def create_item_edit_context(self, owner):
+ """Create LocationAttributeItemEditContext for testing."""
+ return LocationAttributeItemEditContext(location=owner)
+
+ def create_valid_form_data(self, owner, **overrides):
+ """Create valid form data for Location editing."""
+ return LocationAttributeSyntheticData.create_form_data_for_location_edit(
+ owner, **overrides
+ )
+
+ def create_invalid_form_data(self, owner):
+ """Create invalid form data for Location editing."""
+ form_data = LocationAttributeSyntheticData.create_form_data_for_location_edit(owner)
+ form_data['name'] = '' # Invalid empty name
+ return form_data
+
+ def test_location_specific_response_content(self):
+ """Test Location-specific response content and templates - Location response handling."""
+ location = self.create_owner_instance(name="Response Test Location")
+ context = self.create_item_edit_context(location)
+ renderer = self._get_renderer()
+
+ request = self.factory.post('/location/test/')
+ request.session = self._get_mock_session()
+
+ response = renderer.render_form_success_response(
+ attr_item_context=context,
+ request=request,
+ message=None # Use default message
+ )
+
+ # Should use Location-specific template context
+ self.assertEqual(response.status_code, 200)
+
+ # Verify response contains Location-specific data
+ import json
+ data = json.loads(response.content)
+ self.assertIsInstance(data, dict)
+
+ def test_location_template_context_integration(self):
+ """Test Location template context integration - Location template handling."""
+ location = self.create_owner_instance(
+ name="Template Context Location",
+ svg_view_box_str="0 0 1200 800"
+ )
+ context = self.create_item_edit_context(location)
+
+ # Location context should provide SVG-related properties
+ self.assertEqual(context.owner_type, 'location')
+ self.assertEqual(context.location, location)
+
+ # Template context should include location-specific data
+ template_context = context.to_template_context()
+ self.assertIn('location', template_context)
+ self.assertIs(template_context['location'], location)
+
+ def _get_renderer(self):
+ """Get renderer instance for testing."""
+ from hi.apps.attribute.edit_response_renderer import AttributeEditResponseRenderer
+ return AttributeEditResponseRenderer()
+
+ def _get_mock_session(self):
+ """Get mock session for testing."""
+ from hi.testing.base_test_case import MockSession
+ return MockSession()
+
+
+class LocationAttributeEditTemplateContextBuilderTest(AttributeEditTemplateContextBuilderTestMixin, BaseTestCase):
+ """Test AttributeEditTemplateContextBuilder with Location-specific implementations."""
+
+ def create_owner_instance(self, **kwargs):
+ """Create Location instance for testing."""
+ return LocationAttributeSyntheticData.create_test_location(**kwargs)
+
+ def create_attribute_instance(self, owner, **kwargs) -> AttributeModel:
+ """Create LocationAttribute instance for testing."""
+ defaults = {
+ 'location': owner,
+ 'name': 'test_attribute',
+ 'value': 'test_value',
+ 'attribute_type_str': str(AttributeType.CUSTOM),
+ 'value_type_str': str(AttributeValueType.TEXT),
+ }
+ defaults.update(kwargs)
+ return LocationAttribute.objects.create(**defaults)
+
+ def create_item_edit_context(self, owner):
+ """Create LocationAttributeItemEditContext for testing."""
+ return LocationAttributeItemEditContext(location=owner)
+
+ def create_valid_form_data(self, owner, **overrides):
+ """Create valid form data for Location editing."""
+ return LocationAttributeSyntheticData.create_form_data_for_location_edit(
+ owner, **overrides
+ )
+
+ def create_invalid_form_data(self, owner):
+ """Create invalid form data for Location editing."""
+ form_data = LocationAttributeSyntheticData.create_form_data_for_location_edit(owner)
+ form_data['name'] = ''
+ return form_data
+
+ def test_location_specific_template_context_keys(self):
+ """Test Location-specific template context keys - Location template integration."""
+ location = self.create_owner_instance(name="Template Context Location")
+ context = self.create_item_edit_context(location)
+ builder = self._get_builder()
+
+ template_context = builder.build_initial_template_context(
+ attr_item_context=context
+ )
+
+ # Should include Location-specific keys
+ self.assertIn('location', template_context)
+ self.assertIs(template_context['location'], location)
+ self.assertIn('location_form', template_context)
+
+ # Should include generic keys
+ self.assertIn('owner', template_context)
+ self.assertIn('attr_item_context', template_context)
+
+ def test_location_svg_context_assembly(self):
+ """Test Location SVG-specific context assembly - Location SVG handling."""
+ location = self.create_owner_instance(
+ name="SVG Context Location",
+ svg_view_box_str="0 0 1600 1200",
+ svg_fragment_filename="custom-layout.svg"
+ )
+ context = self.create_item_edit_context(location)
+ builder = self._get_builder()
+
+ template_context = builder.build_initial_template_context(
+ attr_item_context=context
+ )
+
+ # Location should be accessible in template context
+ location_in_context = template_context['location']
+ self.assertEqual(location_in_context.svg_view_box_str, "0 0 1600 1200")
+ self.assertEqual(location_in_context.svg_fragment_filename, "custom-layout.svg")
+
+ def test_location_form_error_context_assembly(self):
+ """Test Location form error context assembly - Location error handling."""
+ location = self.create_owner_instance(name="Error Context Location")
+ context = self.create_item_edit_context(location)
+ builder = self._get_builder()
+ handler = self._get_handler()
+
+ # Create form with errors
+ invalid_data = self.create_invalid_form_data(location)
+ form_data = handler.create_edit_form_data(
+ attr_item_context=context,
+ form_data=invalid_data
+ )
+
+ # Trigger validation to create errors
+ handler.validate_forms(edit_form_data=form_data)
+
+ template_context = builder.build_response_template_context(
+ attr_item_context=context,
+ edit_form_data=form_data,
+ error_message="Location validation failed",
+ has_errors=True
+ )
+
+ # Should properly handle Location form errors
+ self.assertTrue(template_context.get('has_errors', False))
+ self.assertIn('error_message', template_context)
+
+ # Location form should be available with errors
+ if template_context.get('owner_form'):
+ location_form = template_context['owner_form']
+ self.assertTrue(hasattr(location_form, 'errors'))
+
+ def _get_builder(self):
+ """Get builder instance for testing."""
+ from hi.apps.attribute.edit_template_context_builder import AttributeEditTemplateContextBuilder
+ return AttributeEditTemplateContextBuilder()
+
+ def _get_handler(self):
+ """Get handler instance for testing."""
+ from hi.apps.attribute.edit_form_handler import AttributeEditFormHandler
+ return AttributeEditFormHandler()
+
+
+class LocationAttributeViewMixinTest(AttributeViewMixinTestMixin, BaseTestCase):
+ """Test AttributeEditViewMixin with Location-specific view implementations."""
+
+ def create_owner_instance(self, **kwargs):
+ """Create Location instance for testing."""
+ return LocationAttributeSyntheticData.create_test_location(**kwargs)
+
+ def create_attribute_instance(self, owner, **kwargs) -> AttributeModel:
+ """Create LocationAttribute instance for testing."""
+ defaults = {
+ 'location': owner,
+ 'name': 'test_attribute',
+ 'value': 'test_value',
+ 'attribute_type_str': str(AttributeType.CUSTOM),
+ 'value_type_str': str(AttributeValueType.TEXT),
+ }
+ defaults.update(kwargs)
+ return LocationAttribute.objects.create(**defaults)
+
+ def create_item_edit_context(self, owner):
+ """Create LocationAttributeItemEditContext for testing."""
+ return LocationAttributeItemEditContext(location=owner)
+
+ def create_valid_form_data(self, owner, **overrides):
+ """Create valid form data for Location editing."""
+ return LocationAttributeSyntheticData.create_form_data_for_location_edit(
+ owner, **overrides
+ )
+
+ def create_invalid_form_data(self, owner):
+ """Create invalid form data for Location editing."""
+ form_data = LocationAttributeSyntheticData.create_form_data_for_location_edit(owner)
+ form_data['name'] = ''
+ return form_data
+
+ def create_test_view_instance(self):
+ """Create LocationEditView instance for testing."""
+ return LocationEditView()
+
+ def test_location_edit_view_integration_workflow(self):
+ """Test complete LocationEditView integration - Location view integration."""
+ location = self.create_owner_instance(name="View Integration Location")
+
+ # Create attributes for comprehensive testing
+ self.create_attribute_instance(
+ location, name="description", value="Original description"
+ )
+
+ view = self.create_test_view_instance()
+ context = self.create_item_edit_context(location)
+
+ # Test GET request (initial template context)
+ get_request = self.factory.get(f'/location/{location.id}/edit/')
+ get_request.session = self._get_mock_session()
+
+ template_context = view.create_initial_template_context(
+ attr_item_context=context
+ )
+
+ # Should provide complete Location editing context
+ self.assertIn('location', template_context)
+ self.assertIn('location_form', template_context)
+ self.assertIn('regular_attributes_formset', template_context)
+
+ def test_location_attribute_history_view_integration(self):
+ """Test Location attribute history integration - Location history functionality."""
+ location = self.create_owner_instance(name="History Integration Location")
+ attribute = self.create_attribute_instance(
+ location, name="history_attr", value="current_value"
+ )
+
+ view = self.create_test_view_instance()
+ context = self.create_item_edit_context(location)
+
+ request = self.factory.get(f'/location/{location.id}/attr/{attribute.id}/history/')
+ request.session = self._get_mock_session()
+
+ response = view.get_history(
+ request=request,
+ attribute=attribute,
+ attr_item_context=context
+ )
+
+ # Should handle Location attribute history
+ self.assertEqual(response.status_code, 200)
+
+ def test_location_svg_integration_workflow(self):
+ """Test Location SVG-related integration - Location SVG functionality."""
+ location = self.create_owner_instance(
+ name="SVG Integration Location",
+ svg_view_box_str="0 0 2000 1500",
+ svg_fragment_filename="integration-test.svg"
+ )
+
+ context = self.create_item_edit_context(location)
+
+ # Location context should handle SVG properties
+ self.assertEqual(context.location.svg_view_box_str, "0 0 2000 1500")
+ self.assertEqual(context.location.svg_fragment_filename, "integration-test.svg")
+
+ # Template context should provide SVG data
+ template_context = context.to_template_context()
+ location_in_context = template_context['location']
+ self.assertEqual(location_in_context.svg_view_box_str, "0 0 2000 1500")
+
+ def _get_mock_session(self):
+ """Get mock session for testing."""
+ from hi.testing.base_test_case import MockSession
+ return MockSession()
+
diff --git a/src/hi/apps/location/tests/test_location_edit_form_handler.py b/src/hi/apps/location/tests/test_location_edit_form_handler.py
deleted file mode 100644
index 904f5122..00000000
--- a/src/hi/apps/location/tests/test_location_edit_form_handler.py
+++ /dev/null
@@ -1,372 +0,0 @@
-"""
-Tests for LocationEditFormHandler business logic.
-
-Focuses on high-value form processing logic: formset creation, file operations,
-validation orchestration, and error collection patterns.
-"""
-import logging
-import re
-from django.test import RequestFactory
-
-from hi.apps.location.location_edit_form_handler import LocationEditFormHandler
-from hi.apps.location.models import LocationAttribute
-from hi.apps.location.tests.synthetic_data import LocationSyntheticData
-from hi.apps.attribute.enums import AttributeType, AttributeValueType
-from hi.testing.base_test_case import BaseTestCase
-
-logging.disable(logging.CRITICAL)
-
-
-class TestLocationEditFormHandler(BaseTestCase):
- """Test LocationEditFormHandler business logic - form processing and file operations."""
-
- def setUp(self):
- super().setUp()
- self.location = LocationSyntheticData.create_test_location(
- name="Test Location Handler"
- )
- self.handler = LocationEditFormHandler()
- self.request_factory = RequestFactory()
-
- def test_formset_prefix_generation_consistency(self):
- """Test formset prefix follows expected pattern - critical for form processing."""
- prefix = LocationEditFormHandler.get_formset_prefix(self.location)
- expected = f"location-{self.location.id}"
- self.assertEqual(prefix, expected)
-
- # Test with different location
- location2 = LocationSyntheticData.create_test_location(name="Another Location")
- prefix2 = LocationEditFormHandler.get_formset_prefix(location2)
- expected2 = f"location-{location2.id}"
- self.assertEqual(prefix2, expected2)
- self.assertNotEqual(prefix, prefix2)
-
- def test_create_location_forms_unbound(self):
- """Test creating unbound forms for initial display - form initialization logic."""
- location_form, file_attributes, regular_formset = self.handler.create_location_forms(self.location)
-
- # Location form should be unbound
- self.assertFalse(location_form.is_bound)
- self.assertEqual(location_form.instance, self.location)
-
- # File attributes should be queryset of FILE type attributes
- self.assertEqual(list(file_attributes), list(self.location.attributes.filter(
- value_type_str=str(AttributeValueType.FILE)
- ).order_by('id')))
-
- # Regular formset should be unbound and exclude FILE attributes
- self.assertFalse(regular_formset.is_bound)
- self.assertEqual(regular_formset.instance, self.location)
-
- def test_create_location_forms_bound_with_data(self):
- """Test creating bound forms with POST data - form binding logic."""
- form_data = {
- 'name': 'Updated Location Name',
- # Add formset management form data
- f'location-{self.location.id}-TOTAL_FORMS': '1',
- f'location-{self.location.id}-INITIAL_FORMS': '0',
- f'location-{self.location.id}-MIN_NUM_FORMS': '0',
- f'location-{self.location.id}-MAX_NUM_FORMS': '1000',
- }
-
- location_form, file_attributes, regular_formset = self.handler.create_location_forms(
- self.location, form_data
- )
-
- # Forms should be bound with data
- self.assertTrue(location_form.is_bound)
- self.assertTrue(regular_formset.is_bound)
-
- # Formset should use correct prefix
- expected_prefix = LocationEditFormHandler.get_formset_prefix(self.location)
- self.assertEqual(regular_formset.prefix, expected_prefix)
-
- def test_validate_forms_both_valid(self):
- """Test form validation when both forms are valid - success path."""
- # Create valid form data
- form_data = {
- 'name': 'Valid Location Name',
- f'location-{self.location.id}-TOTAL_FORMS': '0',
- f'location-{self.location.id}-INITIAL_FORMS': '0',
- f'location-{self.location.id}-MIN_NUM_FORMS': '0',
- f'location-{self.location.id}-MAX_NUM_FORMS': '1000',
- }
-
- location_form, _, regular_formset = self.handler.create_location_forms(
- self.location, form_data
- )
-
- is_valid = self.handler.validate_forms(location_form, regular_formset)
- self.assertTrue(is_valid)
-
- def test_validate_forms_location_invalid(self):
- """Test form validation when location form is invalid - error handling."""
- # Create invalid form data (empty name)
- form_data = {
- 'name': '', # Invalid empty name
- f'location-{self.location.id}-TOTAL_FORMS': '0',
- f'location-{self.location.id}-INITIAL_FORMS': '0',
- f'location-{self.location.id}-MIN_NUM_FORMS': '0',
- f'location-{self.location.id}-MAX_NUM_FORMS': '1000',
- }
-
- location_form, _, regular_formset = self.handler.create_location_forms(
- self.location, form_data
- )
-
- is_valid = self.handler.validate_forms(location_form, regular_formset)
- self.assertFalse(is_valid)
-
- def test_validate_forms_formset_invalid(self):
- """Test form validation when formset is invalid - error handling."""
- # Create form data with invalid formset (will depend on actual form validation rules)
- form_data = {
- 'name': 'Valid Location Name',
- f'location-{self.location.id}-TOTAL_FORMS': '1',
- f'location-{self.location.id}-INITIAL_FORMS': '0',
- f'location-{self.location.id}-MIN_NUM_FORMS': '0',
- f'location-{self.location.id}-MAX_NUM_FORMS': '1000',
- # Add invalid attribute data
- f'location-{self.location.id}-0-name': '', # Empty name might be invalid
- f'location-{self.location.id}-0-value': 'some value',
- }
-
- location_form, _, regular_formset = self.handler.create_location_forms(
- self.location, form_data
- )
-
- is_valid = self.handler.validate_forms(location_form, regular_formset)
- # Result depends on actual validation rules, but testing the validation orchestration
- self.assertIsInstance(is_valid, bool)
-
- def test_process_file_deletions_valid_file_attributes(self):
- """Test file deletion processing with valid file attributes - file management logic."""
- # Create file attribute
- file_attr = LocationAttribute.objects.create(
- location=self.location,
- name='test_file',
- value='Test File',
- value_type_str=str(AttributeValueType.FILE),
- attribute_type_str=str(AttributeType.CUSTOM), # Can be deleted
- )
-
- # Create request with file deletion
- post_data = {
- 'delete_file_attribute': [str(file_attr.id)]
- }
- request = self.request_factory.post('/', post_data)
-
- # Should delete the file attribute
- self.handler.process_file_deletions(request, self.location)
-
- # Attribute should be deleted
- self.assertFalse(LocationAttribute.objects.filter(id=file_attr.id).exists())
-
- def test_process_file_deletions_non_deletable_attribute(self):
- """Test file deletion processing skips non-deletable attributes - permission logic."""
- # Create non-deletable file attribute
- file_attr = LocationAttribute.objects.create(
- location=self.location,
- name='predefined_file',
- value='Predefined File',
- value_type_str=str(AttributeValueType.FILE),
- attribute_type_str=str(AttributeType.PREDEFINED), # Cannot be deleted
- )
-
- post_data = {
- 'delete_file_attribute': [str(file_attr.id)]
- }
- request = self.request_factory.post('/', post_data)
-
- # Should not delete the file attribute
- self.handler.process_file_deletions(request, self.location)
-
- # Attribute should still exist
- self.assertTrue(LocationAttribute.objects.filter(id=file_attr.id).exists())
-
- def test_process_file_deletions_invalid_attribute_id(self):
- """Test file deletion processing handles invalid attribute IDs gracefully - error handling."""
- post_data = {
- 'delete_file_attribute': ['999999', ''] # Non-existent, empty
- }
- request = self.request_factory.post('/', post_data)
-
- # Should not raise exception
- self.handler.process_file_deletions(request, self.location)
- # No assertions needed - just ensure no exceptions are raised
-
- def test_process_file_title_updates_valid_updates(self):
- """Test file title update processing - file metadata management logic."""
- # Create file attribute
- file_attr = LocationAttribute.objects.create(
- location=self.location,
- name='test_file',
- value='Original Title',
- value_type_str=str(AttributeValueType.FILE),
- attribute_type_str=str(AttributeType.CUSTOM),
- )
-
- # Create request with file title update
- field_name = f'file_title_{self.location.id}_{file_attr.id}'
- post_data = {
- field_name: 'Updated Title'
- }
- request = self.request_factory.post('/', post_data)
-
- self.handler.process_file_title_updates(request, self.location)
-
- # Attribute value should be updated
- file_attr.refresh_from_db()
- self.assertEqual(file_attr.value, 'Updated Title')
-
- def test_process_file_title_updates_pattern_matching(self):
- """Test file title field name pattern matching - field parsing logic."""
- # Create file attribute
- file_attr = LocationAttribute.objects.create(
- location=self.location,
- name='test_file',
- value='Original Title',
- value_type_str=str(AttributeValueType.FILE),
- attribute_type_str=str(AttributeType.CUSTOM),
- )
-
- # Test various field name patterns
- test_cases = [
- (f'file_title_{self.location.id}_{file_attr.id}', 'Valid Pattern', True),
- ('file_title_wrong_format', 'Invalid Pattern', False),
- (f'file_title_{self.location.id + 1}_{file_attr.id}', 'Wrong Location', False),
- (f'file_title_{self.location.id}_999999', 'Non-existent Attr', False),
- ]
-
- for field_name, new_title, should_update in test_cases:
- with self.subTest(field_name=field_name):
- original_title = file_attr.value
-
- post_data = {field_name: new_title}
- request = self.request_factory.post('/', post_data)
-
- self.handler.process_file_title_updates(request, self.location)
-
- file_attr.refresh_from_db()
- if should_update:
- self.assertEqual(file_attr.value, new_title)
- else:
- self.assertEqual(file_attr.value, original_title)
-
- # Reset for next test
- file_attr.value = 'Original Title'
- file_attr.save()
-
- def test_process_file_title_updates_empty_title_handling(self):
- """Test file title update processing handles empty titles - data validation."""
- file_attr = LocationAttribute.objects.create(
- location=self.location,
- name='test_file',
- value='Original Title',
- value_type_str=str(AttributeValueType.FILE),
- attribute_type_str=str(AttributeType.CUSTOM),
- )
-
- # Test empty and whitespace-only titles
- test_cases = ['', ' ', '\t\n']
-
- for empty_title in test_cases:
- with self.subTest(empty_title=repr(empty_title)):
- original_title = file_attr.value
-
- field_name = f'file_title_{self.location.id}_{file_attr.id}'
- post_data = {field_name: empty_title}
- request = self.request_factory.post('/', post_data)
-
- self.handler.process_file_title_updates(request, self.location)
-
- file_attr.refresh_from_db()
- # Title should remain unchanged for empty values
- self.assertEqual(file_attr.value, original_title)
-
- def test_collect_form_errors_multiple_sources(self):
- """Test error collection from multiple form sources - comprehensive error handling."""
- # Create forms with errors
- form_data = {
- 'name': '', # Will cause location form error
- f'location-{self.location.id}-TOTAL_FORMS': '1',
- f'location-{self.location.id}-INITIAL_FORMS': '0',
- f'location-{self.location.id}-MIN_NUM_FORMS': '0',
- f'location-{self.location.id}-MAX_NUM_FORMS': '1000',
- # Invalid attribute data might cause formset errors
- f'location-{self.location.id}-0-name': '',
- f'location-{self.location.id}-0-value': '',
- }
-
- location_form, _, regular_formset = self.handler.create_location_forms(
- self.location, form_data
- )
-
- # Trigger validation to generate errors
- location_form.is_valid()
- regular_formset.is_valid()
-
- errors = self.handler.collect_form_errors(location_form, regular_formset)
-
- # Should return a list of error strings
- self.assertIsInstance(errors, list)
- # Specific error content depends on form validation rules
-
- def test_create_initial_context_structure(self):
- """Test initial context creation includes all required components - template integration."""
- context = self.handler.create_initial_context(self.location)
-
- # Should include all expected keys
- required_keys = [
- 'location', 'location_form', 'owner_form', 'file_attributes',
- 'regular_attributes_formset', 'attr_context', 'owner'
- ]
-
- for key in required_keys:
- with self.subTest(key=key):
- self.assertIn(key, context)
-
- # Generic aliases should point to same objects
- self.assertIs(context['owner_form'], context['location_form'])
- self.assertIs(context['owner'], context['location'])
- self.assertIs(context['location'], self.location)
-
- def test_create_initial_context_attribute_context_integration(self):
- """Test initial context includes AttributeEditContext integration - template generalization."""
- context = self.handler.create_initial_context(self.location)
-
- # Should have attr_context
- self.assertIn('attr_context', context)
- attr_context = context['attr_context']
-
- # attr_context should be LocationAttributeEditContext
- from hi.apps.location.location_attribute_edit_context import LocationAttributeEditContext
- self.assertIsInstance(attr_context, LocationAttributeEditContext)
-
- # Should reference the same location
- self.assertEqual(attr_context.location, self.location)
-
- def test_file_title_pattern_regex_accuracy(self):
- """Test the file title pattern regex matches expected formats - pattern validation."""
- # Access the pattern used in the handler (it's defined in the method)
- pattern = re.compile(r'^file_title_(\d+)_(\d+)$')
-
- test_cases = [
- ('file_title_123_456', True, ('123', '456')),
- ('file_title_0_0', True, ('0', '0')),
- ('file_title_abc_123', False, None),
- ('file_title_123_abc', False, None),
- ('file_title_123', False, None),
- ('prefix_file_title_123_456', False, None),
- ('file_title_123_456_suffix', False, None),
- ]
-
- for field_name, should_match, expected_groups in test_cases:
- with self.subTest(field_name=field_name):
- match = pattern.match(field_name)
- if should_match:
- self.assertIsNotNone(match)
- self.assertEqual(match.groups(), expected_groups)
- else:
- self.assertIsNone(match)
-
diff --git a/src/hi/apps/location/tests/test_location_edit_response_renderer.py b/src/hi/apps/location/tests/test_location_edit_response_renderer.py
deleted file mode 100644
index e9de82fa..00000000
--- a/src/hi/apps/location/tests/test_location_edit_response_renderer.py
+++ /dev/null
@@ -1,379 +0,0 @@
-"""
-Tests for LocationEditResponseRenderer integration logic.
-
-Focuses on high-value template rendering, context assembly, and antinode response
-generation patterns.
-"""
-import logging
-from unittest.mock import Mock, patch
-from django.test import RequestFactory
-
-from hi.apps.location.location_edit_response_renderer import LocationEditResponseRenderer
-from hi.apps.location.tests.synthetic_data import LocationSyntheticData
-from hi.apps.location.models import LocationAttribute
-from hi.apps.attribute.enums import AttributeValueType, AttributeType
-from hi.testing.base_test_case import BaseTestCase
-
-logging.disable(logging.CRITICAL)
-
-
-class TestLocationEditResponseRenderer(BaseTestCase):
- """Test LocationEditResponseRenderer template rendering and response logic."""
-
- def setUp(self):
- super().setUp()
- self.location = LocationSyntheticData.create_test_location(
- name="Test Location Renderer"
- )
- self.renderer = LocationEditResponseRenderer()
- self.request_factory = RequestFactory()
- self.request = self.request_factory.get('/')
-
- def test_renderer_initialization(self):
- """Test renderer initializes with form handler - dependency injection."""
- self.assertIsNotNone(self.renderer.form_handler)
- from hi.apps.location.location_edit_form_handler import LocationEditFormHandler
- self.assertIsInstance(self.renderer.form_handler, LocationEditFormHandler)
-
- def test_build_template_context_basic_structure(self):
- """Test template context building includes all required components - context assembly."""
- # Create forms using form handler
- location_form, file_attributes, regular_formset = self.renderer.form_handler.create_location_forms(
- self.location
- )
-
- context = self.renderer.build_template_context(
- location=self.location,
- location_form=location_form,
- file_attributes=file_attributes,
- regular_attributes_formset=regular_formset,
- success_message="Test success",
- error_message="Test error",
- has_errors=True
- )
-
- # Check all required context keys
- required_keys = [
- 'location', 'location_form', 'owner_form', 'file_attributes',
- 'regular_attributes_formset', 'success_message', 'error_message',
- 'has_errors', 'non_field_errors', 'attr_context', 'owner'
- ]
-
- for key in required_keys:
- with self.subTest(key=key):
- self.assertIn(key, context)
-
- # Check generic aliases
- self.assertIs(context['owner_form'], context['location_form'])
- self.assertIs(context['owner'], context['location'])
-
- def test_build_template_context_attribute_context_integration(self):
- """Test template context includes AttributeEditContext - template generalization."""
- location_form, file_attributes, regular_formset = self.renderer.form_handler.create_location_forms(
- self.location
- )
-
- context = self.renderer.build_template_context(
- location=self.location,
- location_form=location_form,
- file_attributes=file_attributes,
- regular_attributes_formset=regular_formset
- )
-
- # Should have attr_context from LocationAttributeEditContext
- self.assertIn('attr_context', context)
- attr_context = context['attr_context']
-
- from hi.apps.location.location_attribute_edit_context import LocationAttributeEditContext
- self.assertIsInstance(attr_context, LocationAttributeEditContext)
- self.assertEqual(attr_context.location, self.location)
-
- def test_build_template_context_error_collection(self):
- """Test template context collects form errors - error messaging logic."""
- # Create forms with validation errors
- form_data = {
- 'name': '', # Invalid empty name
- f'location-{self.location.id}-TOTAL_FORMS': '0',
- f'location-{self.location.id}-INITIAL_FORMS': '0',
- f'location-{self.location.id}-MIN_NUM_FORMS': '0',
- f'location-{self.location.id}-MAX_NUM_FORMS': '1000',
- }
-
- location_form, file_attributes, regular_formset = self.renderer.form_handler.create_location_forms(
- self.location, form_data
- )
-
- # Trigger validation
- location_form.is_valid()
- regular_formset.is_valid()
-
- context = self.renderer.build_template_context(
- location=self.location,
- location_form=location_form,
- file_attributes=file_attributes,
- regular_attributes_formset=regular_formset,
- has_errors=True
- )
-
- # Should include non_field_errors
- self.assertIn('non_field_errors', context)
- self.assertIsInstance(context['non_field_errors'], list)
-
- @patch('hi.apps.location.location_edit_response_renderer.render_to_string')
- @patch('hi.apps.location.location_edit_response_renderer.reverse')
- def test_render_content_fragments_template_rendering(self, mock_reverse, mock_render):
- """Test content fragment rendering uses correct templates - template integration."""
- mock_reverse.return_value = '/location/123/attribute/upload/'
- mock_render.side_effect = ['<content_body>', '<upload_form>']
-
- context = {'location': self.location, 'test': 'data'}
-
- content_body, upload_form = self.renderer.render_content_fragments(
- request=self.request,
- context=context,
- location=self.location
- )
-
- # Should call render_to_string twice with correct templates
- self.assertEqual(mock_render.call_count, 2)
-
- # First call: content body template
- first_call = mock_render.call_args_list[0]
- self.assertEqual(first_call[0][0], 'location/panes/location_edit_content_body.html')
- self.assertEqual(first_call[0][1], context)
- self.assertEqual(first_call[1]['request'], self.request)
-
- # Second call: upload form template
- 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])
-
- # Should generate upload URL for this location
- mock_reverse.assert_called_once_with(
- 'location_attribute_upload',
- kwargs={'location_id': self.location.id}
- )
-
- self.assertEqual(content_body, '<content_body>')
- self.assertEqual(upload_form, '<upload_form>')
-
- def test_render_update_fragments_with_fresh_forms(self):
- """Test update fragments rendering creates fresh forms when none provided - success case logic."""
- with patch.object(self.renderer, 'render_content_fragments') as mock_render_fragments:
- mock_render_fragments.return_value = ('<content>', '<upload>')
-
- content_body, upload_form = self.renderer.render_update_fragments(
- request=self.request,
- location=self.location,
- success_message="Success!"
- )
-
- # Should call render_content_fragments
- mock_render_fragments.assert_called_once()
- call_args = mock_render_fragments.call_args
-
- # Should have created fresh forms (not None)
- context = call_args[1]['context']
- self.assertIsNotNone(context['location_form'])
- self.assertIsNotNone(context['regular_attributes_formset'])
- self.assertEqual(context['success_message'], "Success!")
-
- def test_render_update_fragments_with_existing_forms(self):
- """Test update fragments rendering uses provided forms - error case logic."""
- # Create forms with errors
- form_data = {
- 'name': '',
- f'location-{self.location.id}-TOTAL_FORMS': '0',
- f'location-{self.location.id}-INITIAL_FORMS': '0',
- f'location-{self.location.id}-MIN_NUM_FORMS': '0',
- f'location-{self.location.id}-MAX_NUM_FORMS': '1000',
- }
-
- location_form, file_attributes, regular_formset = self.renderer.form_handler.create_location_forms(
- self.location, form_data
- )
-
- with patch.object(self.renderer, 'render_content_fragments') as mock_render_fragments:
- mock_render_fragments.return_value = ('<error_content>', '<upload>')
-
- self.renderer.render_update_fragments(
- request=self.request,
- location=self.location,
- location_form=location_form,
- regular_attributes_formset=regular_formset,
- error_message="Error!",
- has_errors=True
- )
-
- # Should use provided forms
- mock_render_fragments.assert_called_once()
- call_args = mock_render_fragments.call_args
- context = call_args[1]['context']
-
- self.assertIs(context['location_form'], location_form)
- self.assertIs(context['regular_attributes_formset'], regular_formset)
- self.assertEqual(context['error_message'], "Error!")
- self.assertTrue(context['has_errors'])
-
- @patch('hi.apps.location.location_edit_response_renderer.antinode')
- def test_render_success_response_antinode_integration(self, mock_antinode):
- """Test success response uses antinode with correct parameters - response generation."""
- mock_response = Mock()
- mock_antinode.response.return_value = mock_response
-
- with patch.object(self.renderer, 'render_update_fragments') as mock_render:
- mock_render.return_value = ('<success_content>', '<success_upload>')
-
- response = self.renderer.render_success_response(self.request, self.location)
-
- # Should call render_update_fragments with success message
- mock_render.assert_called_once()
- call_args = mock_render.call_args
- self.assertEqual(call_args[1]['success_message'], "Changes saved successfully")
-
- # Should create antinode response with insert_map
- mock_antinode.response.assert_called_once()
- response_args = mock_antinode.response.call_args
-
- self.assertIn('insert_map', response_args[1])
- insert_map = response_args[1]['insert_map']
-
- # Should have both content and upload form updates
- from hi.constants import DIVID
- self.assertIn(DIVID['ATTR_V2_CONTENT'], insert_map)
- self.assertIn(DIVID['ATTR_V2_UPLOAD_FORM_CONTAINER'], insert_map)
- self.assertEqual(insert_map[DIVID['ATTR_V2_CONTENT']], '<success_content>')
- self.assertEqual(insert_map[DIVID['ATTR_V2_UPLOAD_FORM_CONTAINER']], '<success_upload>')
-
- self.assertEqual(response, mock_response)
-
- @patch('hi.apps.location.location_edit_response_renderer.antinode')
- def test_render_error_response_antinode_integration(self, mock_antinode):
- """Test error response uses antinode with 400 status - error response generation."""
- mock_response = Mock()
- mock_antinode.response.return_value = mock_response
-
- # Create forms with errors
- location_form, _, regular_formset = self.renderer.form_handler.create_location_forms(self.location)
-
- with patch.object(self.renderer, 'render_update_fragments') as mock_render:
- mock_render.return_value = ('<error_content>', '<error_upload>')
-
- response = self.renderer.render_error_response(
- self.request, self.location, location_form, regular_formset
- )
-
- # Should call render_update_fragments with error parameters
- mock_render.assert_called_once()
- self.assertEqual(response, mock_response)
- call_args = mock_render.call_args
- self.assertEqual(call_args[1]['error_message'], "Please correct the errors below")
- self.assertTrue(call_args[1]['has_errors'])
- self.assertIs(call_args[1]['location_form'], location_form)
- self.assertIs(call_args[1]['regular_attributes_formset'], regular_formset)
-
- # Should create antinode response with 400 status
- mock_antinode.response.assert_called_once()
- response_args = mock_antinode.response.call_args
-
- self.assertEqual(response_args[1]['status'], 400)
- self.assertIn('insert_map', response_args[1])
-
- def test_renderer_with_location_having_file_attributes(self):
- """Test renderer handles locations with file attributes - file attribute integration."""
- # Create location with file attribute
- file_attr = LocationAttribute.objects.create(
- location=self.location,
- name='test_document',
- value='Test Document',
- value_type_str=str(AttributeValueType.FILE),
- attribute_type_str=str(AttributeType.CUSTOM),
- )
-
- # Create forms and context
- location_form, file_attributes, regular_formset = self.renderer.form_handler.create_location_forms(
- self.location
- )
-
- context = self.renderer.build_template_context(
- location=self.location,
- location_form=location_form,
- file_attributes=file_attributes,
- regular_attributes_formset=regular_formset
- )
-
- # File attributes should be included in context
- self.assertIn(file_attr, context['file_attributes'])
-
- def test_renderer_context_consistency_across_operations(self):
- """Test renderer maintains context consistency across different operations - state management."""
- # Test that different operations produce consistent context structure
-
- # Test success case context
- location_form, file_attributes, regular_formset = self.renderer.form_handler.create_location_forms(self.location)
- success_context = self.renderer.build_template_context(
- location=self.location,
- location_form=location_form,
- file_attributes=file_attributes,
- regular_attributes_formset=regular_formset,
- success_message="Success!"
- )
-
- # Test error case context
- error_context = self.renderer.build_template_context(
- location=self.location,
- location_form=location_form,
- file_attributes=file_attributes,
- regular_attributes_formset=regular_formset,
- error_message="Error!",
- has_errors=True
- )
-
- # Test initial case context
- initial_context = self.renderer.form_handler.create_initial_context(self.location)
-
- # All contexts should reference the same location and have attr_context
- for context_name, context in [('success', success_context), ('error', error_context), ('initial', initial_context)]:
- with self.subTest(context=context_name):
- self.assertEqual(context['location'], self.location)
- self.assertIn('attr_context', context)
- # attr_context should be the same type across all operations
- from hi.apps.location.location_attribute_edit_context import LocationAttributeEditContext
- self.assertIsInstance(context['attr_context'], LocationAttributeEditContext)
-
- def test_renderer_template_path_consistency(self):
- """Test renderer uses consistent template paths - template organization."""
- with patch('hi.apps.location.location_edit_response_renderer.render_to_string') as mock_render:
- mock_render.return_value = '<rendered>'
-
- context = {'test': 'data'}
- self.renderer.render_content_fragments(self.request, context, self.location)
-
- # Should use location-specific content template
- content_call = mock_render.call_args_list[0]
- self.assertEqual(content_call[0][0], 'location/panes/location_edit_content_body.html')
-
- # Should use generic upload form template
- upload_call = mock_render.call_args_list[1]
- self.assertEqual(upload_call[0][0], 'attribute/components/upload_form.html')
-
- def test_renderer_error_handling_robustness(self):
- """Test renderer handles various error conditions gracefully - error resilience."""
- # Test with None values
- with patch.object(self.renderer.form_handler, 'collect_form_errors') as mock_collect:
- mock_collect.return_value = []
-
- context = self.renderer.build_template_context(
- location=self.location,
- location_form=None, # Should handle None gracefully
- file_attributes=LocationAttribute.objects.none(),
- regular_attributes_formset=None,
- success_message=None,
- error_message=None,
- has_errors=False
- )
-
- # Should not crash and should include basic required keys
- self.assertEqual(context['location'], self.location)
- self.assertIn('attr_context', context)
-
diff --git a/src/hi/apps/location/views.py b/src/hi/apps/location/views.py
index 7f75f3f6..94ecb5d3 100644
--- a/src/hi/apps/location/views.py
+++ b/src/hi/apps/location/views.py
@@ -1,31 +1,24 @@
import logging
-from typing import Any, Dict
+from typing import Any
-from django.db import transaction
from django.core.exceptions import BadRequest
from django.http import HttpRequest, HttpResponse, HttpResponseRedirect
-from django.shortcuts import render, reverse
-from django.template.loader import render_to_string
+from django.shortcuts import reverse
from django.views.generic import View
-import hi.apps.common.antinode as antinode
from hi.apps.common.utils import is_ajax
-from hi.constants import DIVID
+from hi.apps.attribute.view_mixins import AttributeEditViewMixin
from hi.enums import ItemType, ViewType
from hi.exceptions import ForceSynchronousException
from hi.hi_async_view import HiModalView
from hi.hi_grid_view import HiGridView
-from hi.apps.attribute.views import BaseAttributeHistoryView, BaseAttributeRestoreView
from hi.views import page_not_found_response
-from .forms import LocationAttributeUploadForm
+from .location_attribute_edit_context import LocationAttributeItemEditContext
from .location_manager import LocationManager
-from .models import Location, LocationView, LocationAttribute
+from .models import LocationView, LocationAttribute
from .view_mixins import LocationViewMixin
-from .location_attribute_edit_context import LocationAttributeEditContext
-from .location_edit_form_handler import LocationEditFormHandler
-from .location_edit_response_renderer import LocationEditResponseRenderer
logger = logging.getLogger(__name__)
@@ -117,9 +110,8 @@ class LocationItemStatusView( View ):
raise BadRequest( f'Unknown item type "{item_type}".' )
-class LocationEditView(HiModalView, LocationViewMixin):
- """Location attribute editing modal with redesigned interface.
-
+class LocationEditView( HiModalView, LocationViewMixin, AttributeEditViewMixin ):
+ """
This view uses a dual response pattern:
- get(): Returns full modal using standard modal_response()
- post(): Returns antinode fragments for async DOM updates
@@ -131,124 +123,37 @@ class LocationEditView(HiModalView, LocationViewMixin):
def get_template_name(self) -> str:
return 'location/modals/location_edit.html'
- def get( self,
- request : HttpRequest,
- *args : Any,
- **kwargs: Any ) -> HttpResponse:
- location: Location = self.get_location(request, *args, **kwargs)
-
- # Delegate form creation and context building to handler
- form_handler = LocationEditFormHandler()
- context: Dict[str, Any] = form_handler.create_initial_context(location)
-
- return self.modal_response(request, context)
-
- def post( self,
- request : HttpRequest,
- *args : Any,
- **kwargs: Any ) -> HttpResponse:
- location: Location = self.get_location(request, *args, **kwargs)
-
- # Delegate form handling to specialized handlers
- form_handler = LocationEditFormHandler()
- renderer = LocationEditResponseRenderer()
-
- # Create forms with POST data
- (
- location_form,
- file_attributes,
- regular_attributes_formset,
- ) = form_handler.create_location_forms(
- location, request.POST
+ def get( self, request,*args, **kwargs ):
+ location = self.get_location(request, *args, **kwargs)
+ attr_item_context = LocationAttributeItemEditContext( location = location )
+ template_context = self.create_initial_template_context(
+ attr_item_context= attr_item_context,
)
-
- if form_handler.validate_forms(location_form, regular_attributes_formset):
- # Save forms and process files
- form_handler.save_forms(location_form, regular_attributes_formset, request, location)
-
- # Return success response
- return renderer.render_success_response(request, location)
- else:
- # Return error response
- return renderer.render_error_response(
- request, location, location_form, regular_attributes_formset
- )
+ return self.modal_response( request, template_context )
- def get_success_url_name(self) -> str:
- return 'location_edit'
+ def post( self, request,*args, **kwargs ):
+ location = self.get_location(request, *args, **kwargs)
+ attr_item_context = LocationAttributeItemEditContext( location = location )
+ return self.post_attribute_form(
+ request = request,
+ attr_item_context = attr_item_context,
+ )
-class LocationAttributeUploadView( View, LocationViewMixin ):
+class LocationAttributeUploadView( View, LocationViewMixin, AttributeEditViewMixin ):
- def post( self,
- request : HttpRequest,
- *args : Any,
- **kwargs: Any ) -> HttpResponse:
+ def post( self, request,*args, **kwargs ):
location = self.get_location( request, *args, **kwargs )
- location_attribute = LocationAttribute( location = location )
- location_attribute_upload_form = LocationAttributeUploadForm(
- request.POST,
- request.FILES,
- instance = location_attribute,
+ attr_item_context = LocationAttributeItemEditContext( location = location )
+ return self.post_upload(
+ request = request,
+ attr_item_context = attr_item_context,
)
-
- if location_attribute_upload_form.is_valid():
- with transaction.atomic():
- location_attribute_upload_form.save()
-
- # Render new file card HTML to append to file grid
- from hi.apps.location.location_attribute_edit_context import LocationAttributeEditContext
- attr_context = LocationAttributeEditContext(location)
- context = {'attribute': location_attribute, 'location': location}
- context.update(attr_context.to_template_context())
-
- file_card_html: str = render_to_string(
- 'attribute/components/file_card.html',
- context,
- 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': location_attribute_upload_form.errors
- }
- )
-
- return antinode.response(
- insert_map={
- DIVID['ATTR_V2_STATUS_MSG']: error_html
- },
- status=400
- )
-class LocationAttributeHistoryInlineView(BaseAttributeHistoryView):
+class LocationAttributeHistoryInlineView( View, AttributeEditViewMixin ):
"""View for displaying LocationAttribute 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 LocationAttribute
-
- def get_history_url_name(self):
- return 'location_attribute_history_inline'
-
- def get_restore_url_name(self):
- return 'location_attribute_restore_inline'
-
def get( self,
request : HttpRequest,
location_id : int,
@@ -257,44 +162,23 @@ class LocationAttributeHistoryInlineView(BaseAttributeHistoryView):
**kwargs : Any ) -> HttpResponse:
# Validate that the attribute belongs to this location for security
try:
- attribute: LocationAttribute = LocationAttribute.objects.get(
- pk=attribute_id, location_id=location_id
+ attribute = LocationAttribute.objects.select_related('location').get(
+ pk = attribute_id, location_id = location_id
)
except LocationAttribute.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 = []
-
- # Create the attribute edit context for template generalization
- attr_context = LocationAttributeEditContext(attribute.location)
-
- context: Dict[str, Any] = {
- 'location': attribute.location,
- 'attribute': attribute,
- 'history_records': history_records,
- 'history_url_name': self.get_history_url_name(),
- 'restore_url_name': self.get_restore_url_name(),
- }
-
- # Merge in the context variables from AttributeEditContext
- context.update(attr_context.to_template_context())
-
- # Use Django render shortcut
- return render(request, self.get_template_name(), context)
+ attr_item_context = LocationAttributeItemEditContext( location = attribute.location )
+
+ return self.get_history(
+ request = request,
+ attribute = attribute,
+ attr_item_context = attr_item_context,
+ )
-class LocationAttributeRestoreInlineView(BaseAttributeRestoreView):
- """View for restoring LocationAttribute values from history within the edit modal."""
- def get_attribute_model_class(self):
- return LocationAttribute
+class LocationAttributeRestoreInlineView( View, AttributeEditViewMixin ):
+ """View for restoring LocationAttribute values from history within the edit modal."""
def get( self,
request : HttpRequest,
@@ -303,37 +187,19 @@ class LocationAttributeRestoreInlineView(BaseAttributeRestoreView):
history_id : int,
*args : Any,
**kwargs : Any ) -> HttpResponse:
- # Validate that the attribute belongs to this location for security
+ """ Need to do restore in a GET since nested in main form and cannot have a form in a form """
try:
- attribute: LocationAttribute = LocationAttribute.objects.get(
- pk=attribute_id, location_id=location_id
+ attribute = LocationAttribute.objects.select_related('location').get(
+ pk = attribute_id, location_id = location_id
)
except LocationAttribute.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 LocationEditView logic to return updated modal content
- location: Location = attribute.location
-
- # Use LocationEditView's render_success_response logic
- from .location_edit_response_renderer import LocationEditResponseRenderer
- renderer: LocationEditResponseRenderer = LocationEditResponseRenderer()
- return renderer.render_success_response(
+
+ attr_item_context = LocationAttributeItemEditContext( location = attribute.location )
+
+ return self.post_restore(
request = request,
- location = location,
+ attribute = attribute,
+ history_id = history_id,
+ attr_item_context = attr_item_context,
)
diff --git a/src/hi/constants.py b/src/hi/constants.py
index 965a7a76..84bfab65 100644
--- a/src/hi/constants.py
+++ b/src/hi/constants.py
@@ -61,22 +61,26 @@ DIVID = {
'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',
+ # Attribute Editing
+ 'ATTR_V2_CONTAINER_ID': 'attr-v2-container',
+ 'ATTR_V2_CONTAINER_CLASS': 'attr-v2-container',
+ 'ATTR_V2_FORM_ID': 'attr-v2-form',
+ 'ATTR_V2_FORM_CLASS': 'attr-v2-form',
+ 'ATTR_V2_CONTENT_ID': 'attr-v2-content',
+ 'ATTR_V2_CONTENT_CLASS': '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_FILE_GRID_CLASS': 'attr-v2-file-grid',
+ 'ATTR_V2_STATUS_MESSAGE_ID': 'attr-v2-status-message',
+ 'ATTR_V2_STATUS_MESSAGE_CLASS': 'attr-v2-status-message',
+ 'ATTR_V2_DIRTY_MESSAGE_ID': 'attr-v2-dirty-message',
+ 'ATTR_V2_DIRTY_MESSAGE_CLASS': 'attr-v2-dirty-message',
+ 'ATTR_V2_UPDATE_BTN_ID': 'attr-v2-update-btn',
+ 'ATTR_V2_UPDATE_BTN_CLASS': 'attr-v2-update-btn',
'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',
@@ -89,7 +93,35 @@ DIVID = {
'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',
+ 'ATTR_V2_FILE_INPUT_ID': 'attr-v2-file-input',
+ 'ATTR_V2_FILE_INPUT_CLASS': '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_SCROLLABLE_CONTENT_CLASS': 'attr-v2-scrollable-content',
+ 'ATTR_V2_AUTO_DISMISS_CLASS': 'attr-v2-auto-dismiss',
+ 'ATTR_V2_HISTORY_LINK_CLASS': 'attr-v2-history-link',
+ 'ATTR_V2_RESTORE_LINK_CLASS': 'attr-v2-restore-link',
+ 'ATTR_V2_STICKY_PANEL_CLASS': 'attr-v2-sticky-panel',
+ 'ATTR_V2_BASIC_INFO_CLASS': 'attr-v2-basic-info',
+ 'ATTR_V2_ACTION_BAR_CLASS': 'attr-v2-action-bar',
+ 'ATTR_V2_ACTION_BAR_CONTENT_CLASS': 'attr-v2-action-bar-content',
+ 'ATTR_V2_ACTION_BUTTONS_CLASS': 'attr-v2-action-buttons',
+ 'ATTR_V2_HISTORY_INLINE_CONTENT_CLASS': 'attr-v2-history-inline-content',
+ 'ATTR_V2_HISTORY_HEADER_CLASS': 'attr-v2-history-header',
+ 'ATTR_V2_HISTORY_CLOSE_CLASS': 'attr-v2-history-close',
+ 'ATTR_V2_HISTORY_CURRENT_CLASS': 'attr-v2-history-current',
+ 'ATTR_V2_HISTORY_RECORDS_CLASS': 'attr-v2-history-records',
+ 'ATTR_V2_HISTORY_RECORD_CLASS': 'attr-v2-history-record',
+ 'ATTR_V2_HISTORY_TOGGLE_CLASS': 'attr-v2-history-toggle',
+ 'ATTR_V2_HISTORY_EMPTY_CLASS': 'attr-v2-history-empty',
+ 'ATTR_V2_ATTRIBUTE_HEADER_CLASS': 'attr-v2-attribute-header',
+ 'ATTR_V2_ATTRIBUTE_ACTIONS_CLASS': 'attr-v2-attribute-actions',
+ 'ATTR_V2_ATTRIBUTE_VALUE_CLASS': 'attr-v2-attribute-value',
+ 'ATTR_V2_TEXT_VALUE_CLASS': 'attr-v2-text-value',
+ 'ATTR_V2_SECRET_CHECKBOX_CLASS': 'attr-v2-secret-checkbox',
+ 'ATTR_V2_INLINE_HISTORY_CLASS': 'attr-v2-inline-history',
+ 'ATTR_V2_DISPLAY_FIELD_CLASS': 'display-field',
+ 'ATTR_V2_SHOW_MORE_TEXT_CLASS': 'show-more-text',
+ 'ATTR_V2_SHOW_LESS_TEXT_CLASS': 'show-less-text',
+ 'ATTR_V2_DELETE_FILE_ATTR': 'delete_file_attribute',
}
diff --git a/src/hi/settings/base.py b/src/hi/settings/base.py
index f3797713..cbe53b11 100644
--- a/src/hi/settings/base.py
+++ b/src/hi/settings/base.py
@@ -249,8 +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',
+ 'js/attr.js',
+ 'js/attr-dirty-tracking.js',
),
'output_filename': 'js/js_before_content.js',
},
@@ -368,3 +368,6 @@ SUPPRESS_MONITORS = False
# When enabled in DEBUG mode, allows injecting test data into API responses
# for frontend testing without changing backend state. Never enabled in production.
DEBUG_FORCE_TRANSIENT_VIEW_OVERRIDE = False
+
+# For testing UI error display of the various attribute editing form errors.
+DEBUG_INJECT_ATTRIBUTE_FORM_ERRORS = False
diff --git a/src/hi/settings/development.py b/src/hi/settings/development.py
index 44374fdd..a8bf6066 100644
--- a/src/hi/settings/development.py
+++ b/src/hi/settings/development.py
@@ -67,7 +67,7 @@ LOGGING = {
},
'hi.apps.alert': {
'handlers': ['console' ],
- 'level': 'DEBUG',
+ 'level': 'INFO',
'propagate': False,
},
'hi.apps.control': {
@@ -77,7 +77,7 @@ LOGGING = {
},
'hi.apps.console': {
'handlers': ['console' ],
- 'level': 'DEBUG',
+ 'level': 'INFO',
'propagate': False,
},
'hi.apps.notify': {
@@ -148,3 +148,6 @@ SUPPRESS_MONITORS = False
# Allows injecting transient view data for testing auto-view functionality
DEBUG_FORCE_TRANSIENT_VIEW_OVERRIDE = False # Set to True to enable
+
+# For testing UI error display of the various attribute editing form errors.
+DEBUG_INJECT_ATTRIBUTE_FORM_ERRORS = False
diff --git a/src/hi/static/css/main.css b/src/hi/static/css/main.css
index 420112eb..530b177f 100644
--- a/src/hi/static/css/main.css
+++ b/src/hi/static/css/main.css
@@ -362,8 +362,8 @@ a.clickable-card:active {
/* Attribute V2 System Styles - Fresh Start */
-/* Modal Structure */
-.attr-v2-modal {
+/* Container Structure */
+.attr-v2-container {
/* Remove default form margins for better layout control */
margin: 0;
}
@@ -391,21 +391,39 @@ a.clickable-card:active {
.attr-v2-action-bar-content {
display: flex;
- justify-content: space-between;
align-items: center;
gap: 1rem;
}
-#attr-v2-update-btn {
+/* Left group: button and messages */
+.attr-v2-action-bar-left {
+ display: flex;
+ align-items: center;
+ gap: 1rem;
+ flex: 1; /* Take available space */
+}
+
+/* Message stack */
+.attr-v2-message-stack {
+ display: flex;
+ flex-direction: column;
+ gap: 0.25rem;
+}
+
+.attr-v2-update-btn {
min-height: 44px; /* Touch-friendly primary action */
min-width: 80px;
padding: 0.75rem 1.5rem;
+ flex-shrink: 0; /* Don't shrink button */
}
+/* Right group: action buttons */
.attr-v2-action-buttons {
display: flex;
gap: 0.5rem;
align-items: center;
+ flex-shrink: 0; /* Don't shrink buttons */
+ margin-left: auto; /* Push to right */
}
.attr-v2-action-buttons button {
@@ -447,23 +465,23 @@ a.clickable-card:active {
}
/* Touch-friendly Form Controls - Consistent heights */
-.attr-v2-modal input,
-.attr-v2-modal select,
-.attr-v2-modal textarea {
+.attr-v2-container input,
+.attr-v2-container select,
+.attr-v2-container textarea {
min-height: 44px; /* Touch-friendly minimum for form inputs */
padding: 0.75rem;
font-size: 0.875rem;
border-radius: 0.375rem;
}
-.attr-v2-modal input[type="text"],
-.attr-v2-modal input[type="email"],
-.attr-v2-modal input[type="url"],
-.attr-v2-modal select {
+.attr-v2-container input[type="text"],
+.attr-v2-container input[type="email"],
+.attr-v2-container input[type="url"],
+.attr-v2-container select {
height: 44px; /* Exact height for single-line inputs */
}
-.attr-v2-modal textarea {
+.attr-v2-container textarea {
min-height: 44px;
resize: vertical;
}
@@ -859,7 +877,7 @@ a.clickable-card:active {
.attr-v2-file-actions button,
.attr-v2-attribute-actions button,
.attr-v2-reorder-controls button,
-#attr-v2-update-btn {
+.attr-v2-update-btn {
transition: all 0.15s ease;
}
@@ -867,21 +885,21 @@ a.clickable-card:active {
.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 {
+.attr-v2-update-btn:hover {
transform: translateY(-1px);
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
/* Form Element Transitions */
-.attr-v2-modal input,
-.attr-v2-modal select,
-.attr-v2-modal textarea {
+.attr-v2-container input,
+.attr-v2-container select,
+.attr-v2-container textarea {
transition: border-color 0.15s ease, box-shadow 0.15s ease;
}
-.attr-v2-modal input:focus,
-.attr-v2-modal select:focus,
-.attr-v2-modal textarea:focus {
+.attr-v2-container input:focus,
+.attr-v2-container select:focus,
+.attr-v2-container textarea:focus {
border-color: var(--primary-color);
box-shadow: 0 0 0 0.2rem rgba(23, 112, 114, 0.25);
outline: none;
@@ -892,7 +910,7 @@ a.clickable-card:active {
.attr-v2-file-actions button:focus,
.attr-v2-attribute-actions button:focus,
.attr-v2-reorder-controls button:focus,
-#attr-v2-update-btn: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);
@@ -929,20 +947,6 @@ a.clickable-card:active {
animation: fadeIn 0.3s ease;
}
-/* 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);
-}
-
-.attr-v2-modal-overlay:not([style*="display: none"]) .attr-v2-overlay-content {
- transform: scale(1);
-}
-
/* Status Message Transitions */
.attr-v2-status-message {
transition: opacity 0.25s ease, color 0.25s ease;
@@ -1116,12 +1120,10 @@ a.clickable-card:active {
.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-container input,
+ .attr-v2-container select,
+ .attr-v2-container textarea,
.attr-v2-add-form,
- .attr-v2-modal-overlay,
- .attr-v2-overlay-content,
.attr-v2-file-thumbnail {
animation: none;
transition: none;
@@ -1186,52 +1188,6 @@ a.clickable-card:active {
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;
@@ -2553,12 +2509,16 @@ g[hover] {
.attr-v2-dirty-message {
font-size: 0.875rem;
color: transparent;
- transition: color 0.2s ease-in-out;
+ transition: all 0.2s ease-in-out;
min-width: 120px;
+ padding: 0.25rem 0.5rem;
+ border-radius: 0.25rem;
}
.attr-v2-dirty-message.active {
- color: var(--warning-color);
+ color: #8B4513; /* Darker brown text for better contrast */
+ background-color: #FFF3CD; /* Light warning background */
+ border-left: 3px solid var(--warning-color);
font-weight: 500;
}
@@ -2686,55 +2646,6 @@ g[hover] {
border-top: 1px solid #dee2e6;
}
-/* ====================================================================== */
-/* 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 */
-}
-
-.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;
-}
-
-.attr-v2-overlay-header {
- display: flex;
- justify-content: space-between;
- align-items: center;
- padding: 1rem 1.5rem;
- border-bottom: 1px solid #dee2e6;
-}
-
-.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 */
/* ====================================================================== */
@@ -2817,6 +2728,114 @@ g[hover] {
margin-top: 0.25rem;
}
+/* ====================================================================== */
+/* ERROR MESSAGE STYLING */
+/* ====================================================================== */
+
+/* Non-field errors container - page level (owner form) */
+.attr-v2-sticky-panel .attr-v2-non-field-errors {
+ border-left: 3px solid #dc2626;
+ padding-left: 1rem;
+ margin: 0.5rem 0;
+}
+
+.attr-v2-sticky-panel .attr-v2-non-field-errors .attr-v2-error-item {
+ color: #dc2626;
+ font-size: 0.875rem;
+ margin: 0.25rem 0;
+ display: flex;
+ align-items: flex-start;
+ gap: 0.5rem;
+}
+
+.attr-v2-sticky-panel .attr-v2-non-field-errors .attr-v2-error-item:before {
+ content: "•";
+ color: #dc2626;
+ font-weight: bold;
+ flex-shrink: 0;
+}
+
+/* Formset non-form errors (same style as owner non-field errors) */
+.attr-v2-formset-errors {
+ border-left: 3px solid #dc2626;
+ padding-left: 1rem;
+ margin: 0.5rem 0;
+}
+
+.attr-v2-formset-errors .attr-v2-error-item {
+ color: #dc2626;
+ font-size: 0.875rem;
+ margin: 0.25rem 0;
+ display: flex;
+ align-items: flex-start;
+ gap: 0.5rem;
+}
+
+.attr-v2-formset-errors .attr-v2-error-item:before {
+ content: "•";
+ color: #dc2626;
+ font-weight: bold;
+ flex-shrink: 0;
+}
+
+/* Non-field errors - individual attribute card level (most subtle) */
+.attr-v2-attribute-card .attr-v2-non-field-errors {
+ margin: 0.5rem 0 0 0;
+ padding: 0;
+}
+
+.attr-v2-attribute-card .attr-v2-non-field-errors .attr-v2-error-item {
+ color: #dc2626;
+ font-size: 0.8125rem;
+ margin: 0.25rem 0;
+ display: flex;
+ align-items: flex-start;
+ gap: 0.375rem;
+}
+
+.attr-v2-attribute-card .attr-v2-non-field-errors .attr-v2-error-item:before {
+ content: "•";
+ color: #dc2626;
+ font-weight: bold;
+ flex-shrink: 0;
+}
+
+/* Field-level errors */
+.attr-v2-field-errors {
+ color: #dc2626;
+ font-size: 0.8125rem;
+ margin-top: 0.25rem;
+ display: flex;
+ flex-direction: column;
+ gap: 0.125rem;
+}
+
+.attr-v2-field-errors .attr-v2-error-text {
+ display: flex;
+ align-items: flex-start;
+ gap: 0.375rem;
+}
+
+.attr-v2-field-errors .attr-v2-error-text:before {
+ content: "•";
+ color: #dc2626;
+ font-weight: bold;
+ flex-shrink: 0;
+}
+
+/* Invalid form controls */
+.attr-v2-attribute-card .form-control.is-invalid,
+.attr-v2-basic-info .form-control.is-invalid {
+ border-color: #dc2626;
+ background-image: none;
+}
+
+.attr-v2-attribute-card .form-control.is-invalid:focus,
+.attr-v2-basic-info .form-control.is-invalid:focus {
+ border-color: #dc2626;
+ box-shadow: 0 0 0 0.2rem rgba(220, 38, 38, 0.25);
+}
+
/* ====================================================================== */
/* INLINE HISTORY STYLING */
/* ====================================================================== */
@@ -3052,10 +3071,6 @@ g[hover] {
/* Touch device optimizations */
@media (max-width: 768px) {
- .attr-v2-overlay-content {
- width: 95%;
- max-height: 90vh;
- }
.attr-v2-add-form-actions {
flex-direction: column;
diff --git a/src/hi/static/js/antinode.js b/src/hi/static/js/antinode.js
index d2304c02..9374e12b 100644
--- a/src/hi/static/js/antinode.js
+++ b/src/hi/static/js/antinode.js
@@ -10,6 +10,18 @@
// content loading and DOM manipulation without full page refreshes. It supports
// both declarative (HTML attributes) and programmatic (JavaScript API) usage.
+// ====================
+// APPLICABILITY
+// ====================
+// This module's main use case is to allow ajax and dynamic content udpates
+// without needing to add any javascript. By adding element attributes
+// and/or with server-side payloads, a fairly rich set of common DOM
+// updates can be achieved with zero javascript code. It also has a lot of
+// support for handling bootstrap-style modals.
+//
+// It is generally not applicabl if you need to have custom Javascript
+// for some client-server interactions
+
// ====================
// PREREQUISITES
// ====================
diff --git a/src/hi/static/js/attr-v2-dirty-tracking.js b/src/hi/static/js/attr-dirty-tracking.js
similarity index 68%
rename from src/hi/static/js/attr-v2-dirty-tracking.js
rename to src/hi/static/js/attr-dirty-tracking.js
index 38d6e68d..6249d5eb 100644
--- a/src/hi/static/js/attr-v2-dirty-tracking.js
+++ b/src/hi/static/js/attr-dirty-tracking.js
@@ -1,40 +1,65 @@
/*
- * 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
+ * Home Information - Attribute Dirty State Tracking
+ * Container-aware dirty state tracking for attribute editing
+ * Supports multiple simultaneous editing contexts and visual dirty indicators
*/
(function() {
'use strict';
- // Create namespace
- window.attrV2 = window.attrV2 || {};
- window.attrV2.DirtyTracking = {
-
+ // Internal constants - dirty tracking specific
+ const DIRTY_TRACKING_INTERNAL = {
// Configuration
- config: {
- formSelector: Hi.ATTR_V2_FORM_SELECTOR,
+ DEBOUNCE_DELAY: 300,
+
+ // Messages
+ SINGLE_FIELD_MESSAGE: '1 field modified',
+ MULTIPLE_FIELDS_MESSAGE_TEMPLATE: '{count} fields modified',
+ DIRTY_INDICATOR_CHAR: '●',
+ DIRTY_INDICATOR_TITLE: 'This field has been modified',
+
+ FIELD_DIRTY_CLASS: 'attr-v2-field-dirty',
+ DIRTY_INDICATOR_CLASS: 'attr-v2-dirty-indicator',
+ };
+
+ // Create namespace
+ window.Hi = window.Hi || {};
+ window.Hi.attr = window.Hi.attr || {};
+
+ /**
+ * DirtyTracker Class - Container-specific instance
+ * Each editing context gets its own isolated tracker
+ */
+ function DirtyTracker(containerId) {
+ this.containerId = containerId;
+ this.container = document.getElementById(containerId);
+
+ // Instance-specific configuration
+ this.config = {
+ formSelector: Hi.ATTR_V2_FORM_CLASS_SELECTOR,
messageContainerSelector: Hi.ATTR_V2_DIRTY_MESSAGE_SELECTOR,
- debounceDelay: 300,
- dirtyFieldClass: Hi.ATTR_V2_FIELD_DIRTY_CLASS,
- dirtyIndicatorClass: Hi.ATTR_V2_DIRTY_INDICATOR_CLASS
- },
+ debounceDelay: DIRTY_TRACKING_INTERNAL.DEBOUNCE_DELAY,
+ dirtyFieldClass: DIRTY_TRACKING_INTERNAL.FIELD_DIRTY_CLASS,
+ dirtyIndicatorClass: DIRTY_TRACKING_INTERNAL.DIRTY_INDICATOR_CLASS
+ };
- // State
- state: {
+ // Instance-specific state
+ this.state = {
originalValues: new Map(),
dirtyFields: new Set(),
debounceTimers: new Map(),
isInitialized: false
- },
-
- // Initialize the dirty tracking system
+ };
+ }
+
+ DirtyTracker.prototype = {
+ // Initialize the dirty tracking system for this container
init: function() {
- if (this.state.isInitialized) {
+ if (this.state.isInitialized || !this.container) {
return;
}
- const form = document.querySelector(this.config.formSelector);
+ const form = this.container.querySelector(this.config.formSelector);
if (!form) {
return;
}
@@ -44,15 +69,15 @@
this.state.isInitialized = true;
},
- // Capture original values for all form fields
+ // Capture original values for all form fields in this container
captureOriginalValues: function() {
- const form = document.querySelector(this.config.formSelector);
+ const form = this.container.querySelector(this.config.formSelector);
if (!form) return;
- // Entity name field
- const entityNameField = form.querySelector('input[name$="name"]:not([name*="-"])');
- if (entityNameField) {
- this.captureFieldValue(entityNameField);
+ // Entity/Location name field
+ const nameField = form.querySelector('input[name$="name"]:not([name*="-"])');
+ if (nameField) {
+ this.captureFieldValue(nameField);
}
// Attribute form fields
@@ -104,13 +129,13 @@
return originalValue !== currentValue;
},
- // Bind event listeners
+ // Bind event listeners scoped to this container
bindEvents: function() {
- const form = document.querySelector(this.config.formSelector);
+ const form = this.container.querySelector(this.config.formSelector);
if (!form) return;
// Text input changes with debouncing
- this.bindDebouncedEvents(form, 'input[type="text"], input[type="password"], textarea', 'input');
+ this.bindDebouncedEvents(form, 'input[type="text"], input[type="password"], input[type="number"], textarea', 'input');
// Immediate changes for selects and checkboxes
this.bindImmediateEvents(form, 'select, input[type="checkbox"]', 'change');
@@ -124,9 +149,6 @@
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
@@ -243,8 +265,8 @@
createDirtyIndicator: function() {
const indicator = document.createElement('span');
indicator.className = this.config.dirtyIndicatorClass;
- indicator.innerHTML = '●'; // Simple dot indicator
- indicator.title = 'This field has been modified';
+ indicator.innerHTML = DIRTY_TRACKING_INTERNAL.DIRTY_INDICATOR_CHAR;
+ indicator.title = DIRTY_TRACKING_INTERNAL.DIRTY_INDICATOR_TITLE;
return indicator;
},
@@ -287,9 +309,9 @@
}
},
- // Update message area with current dirty state
+ // Update message area with current dirty state (scoped to this container)
updateMessageArea: function() {
- const messageContainer = document.querySelector(this.config.messageContainerSelector);
+ const messageContainer = this.container.querySelector(this.config.messageContainerSelector);
if (!messageContainer) return;
const dirtyCount = this.state.dirtyFields.size;
@@ -299,10 +321,10 @@
messageContainer.className = Hi.ATTR_V2_DIRTY_MESSAGE_CLASS;
} else {
const message = dirtyCount === 1
- ? '1 field modified'
- : `${dirtyCount} fields modified`;
+ ? DIRTY_TRACKING_INTERNAL.SINGLE_FIELD_MESSAGE
+ : DIRTY_TRACKING_INTERNAL.MULTIPLE_FIELDS_MESSAGE_TEMPLATE.replace('{count}', dirtyCount);
messageContainer.textContent = message;
- messageContainer.className = Hi.ATTR_V2_DIRTY_MESSAGE_CLASS + ' active';
+ messageContainer.className = `${Hi.ATTR_V2_DIRTY_MESSAGE_CLASS} active`;
}
},
@@ -314,10 +336,10 @@
// Sync display fields to hidden fields before submission
syncDisplayToHiddenFields: function() {
- const form = document.querySelector(this.config.formSelector);
+ const form = this.container.querySelector(this.config.formSelector);
if (!form) return;
- const displayFields = form.querySelectorAll('.display-field');
+ const displayFields = form.querySelectorAll(Hi.ATTR_V2_DISPLAY_FIELD_SELECTOR);
displayFields.forEach(displayField => {
const hiddenFieldId = displayField.getAttribute('data-hidden-field');
const hiddenField = hiddenFieldId ? document.getElementById(hiddenFieldId) : null;
@@ -330,13 +352,17 @@
// Handle successful form submission
handleFormSuccess: function(e) {
- this.clearAllDirtyState();
+ // Only clear if the success event is for this container's form
+ const form = this.container.querySelector(this.config.formSelector);
+ if (form && e.target === form) {
+ this.clearAllDirtyState();
+ }
},
- // Clear all dirty state
+ // Clear all dirty state for this container
clearAllDirtyState: function() {
// Clear visual indicators
- const form = document.querySelector(this.config.formSelector);
+ const form = this.container.querySelector(this.config.formSelector);
if (form) {
form.querySelectorAll('.' + this.config.dirtyFieldClass).forEach(field => {
field.classList.remove(this.config.dirtyFieldClass);
@@ -367,7 +393,7 @@
this.updateMessageArea();
},
- // Reinitialize for dynamic content (called by modal system)
+ // Reinitialize for dynamic content
reinitialize: function() {
this.clearAllDirtyState();
this.state.originalValues.clear();
@@ -376,26 +402,85 @@
}
};
+ /**
+ * Private DirtyTracker instance management
+ */
+ const _instances = new Map();
+
+ const HiAttrDirtyTracking = {
+ // Instance Management
+ getInstance: function(containerId) {
+ if (!_instances.has(containerId)) {
+ _instances.set(containerId, new DirtyTracker(containerId));
+ }
+ return _instances.get(containerId);
+ },
+
+ createInstance: function(containerId) {
+ const instance = new DirtyTracker(containerId);
+ _instances.set(containerId, instance);
+ return instance;
+ },
+
+ // Bulk Operations
+ initializeAll: function() {
+ const containers = document.querySelectorAll(Hi.ATTR_V2_CONTAINER_SELECTOR);
+ containers.forEach(container => {
+ if (container.id) {
+ const instance = this.getInstance(container.id);
+ instance.init();
+ }
+ });
+ },
+
+ reinitializeContainer: function(containerId) {
+ const $container = typeof containerId === 'string' ? $(`#${containerId}`) : $(containerId);
+ const id = $container.attr('id');
+ if (!id) {
+ console.warn('DirtyTracking: Container missing ID, skipping initialization');
+ return;
+ }
+
+ const instance = this.getInstance(id);
+ instance.reinitialize();
+ },
+
+ // Event Handling
+ handleFormSuccess: function(event) {
+ const form = event.target.closest(Hi.ATTR_V2_FORM_CLASS_SELECTOR);
+ if (form) {
+ const container = form.closest(Hi.ATTR_V2_CONTAINER_SELECTOR);
+ if (container && container.id) {
+ const instance = this.getInstance(container.id);
+ instance.handleFormSuccess(event);
+ }
+ }
+ },
+
+ // Initialization
+ init: function() {
+ this.initializeAll();
+ }
+ };
+
+ // Export to Hi namespace
+ window.Hi.attr.dirtyTracking = HiAttrDirtyTracking;
+
// Auto-initialize when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
- window.attrV2.DirtyTracking.init();
+ HiAttrDirtyTracking.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);
- }
+ // Look for containers within the modal
+ const modal = e.target;
+ const containers = modal.querySelectorAll(Hi.ATTR_V2_CONTAINER_SELECTOR);
+ containers.forEach(container => {
+ if (container.id) {
+ HiAttrDirtyTracking.reinitializeContainer(container.id);
+ }
+ });
});
})();
diff --git a/src/hi/static/js/attr-v2-modal.js b/src/hi/static/js/attr-v2-modal.js
deleted file mode 100644
index f3fab295..00000000
--- a/src/hi/static/js/attr-v2-modal.js
+++ /dev/null
@@ -1,670 +0,0 @@
-/*
- * 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/attr.js b/src/hi/static/js/attr.js
new file mode 100644
index 00000000..29e156d1
--- /dev/null
+++ b/src/hi/static/js/attr.js
@@ -0,0 +1,1142 @@
+/*
+ * Home Information - Attribute Editing JavaScript
+ * Core attribute editing functionality for entities, locations, and configurations
+ * Provides container-aware form handling, AJAX operations, and UI management
+ */
+
+(function() {
+ 'use strict';
+
+ // Internal constants - JS-only, no server dependency
+ const ATTR_V2_INTERNAL = {
+ // State management data keys (different granularity levels)
+ INITIALIZED_DATA_KEY: 'attr-v2-initialized', // Container-level flag
+ PROCESSED_DATA_KEY: 'attr-v2-processed', // Element-level flag
+
+ // Event namespaces
+ AJAX_EVENT_NAMESPACE: 'attr-v2-ajax',
+ OVERFLOW_EVENT_NAMESPACE: 'input.overflow',
+
+ // HTTP/AJAX constants
+ CSRF_TOKEN_NAME: 'csrfmiddlewaretoken',
+ XML_HTTP_REQUEST_HEADER: 'X-Requested-With',
+ AUTOSIZE_INITIALIZED_ATTR: 'data-autosize-initialized',
+
+ // CSS state classes (JS-managed, not in templates)
+ TRUNCATED_CLASS: 'truncated',
+ MARKED_FOR_DELETION_CLASS: 'marked-for-deletion',
+ ACTIVATED_CLASS: 'activated',
+ HAS_DIRTY_INDICATOR_CLASS: 'has-dirty-indicator',
+ HAS_DIRTY_FIELD_CLASS: 'has-dirty-field',
+ ACTIVE_CLASS: 'active',
+
+ // Form field name patterns
+ NAME_FIELD_SUFFIX: '-name',
+ VALUE_FIELD_SUFFIX: '-value',
+ DELETE_FIELD_SUFFIX: '-DELETE',
+
+ // Status message CSS classes (Bootstrap)
+ STATUS_SUCCESS_CLASS: 'text-success',
+ STATUS_ERROR_CLASS: 'text-danger',
+ STATUS_INFO_CLASS: 'text-info',
+ STATUS_WARNING_CLASS: 'text-warning',
+
+ // Bootstrap/generic classes
+ MODAL_SELECTOR: '.modal',
+ FORM_GROUP_SELECTOR: '.form-group'
+ };
+
+ // Status message type constants - exposed for public use
+ const STATUS_TYPE = {
+ SUCCESS: 'success',
+ ERROR: 'error',
+ WARNING: 'warning',
+ INFO: 'info'
+ };
+
+ // Create the main Hi.attr namespace
+ window.Hi = window.Hi || {};
+
+ const HiAttr = {
+ // Status message types
+ STATUS_TYPE: STATUS_TYPE,
+
+ // Container Management
+ initializeContainer: function(containerSelector) {
+ const $container = $(containerSelector);
+ if ($container.length > 0) {
+ _initializeContainer($container);
+ }
+ },
+
+ reinitializeContainer: function(containerId) {
+ const $container = $(`#${containerId}`);
+ if ($container.length > 0) {
+ _initializeContainer($container);
+ }
+ },
+
+ // Form Operations
+ submitForm: function(form, options = {}) {
+ return _ajax.submitFormWithAjax(form, options);
+ },
+
+ updateFormAction: function(newUrl, containerId) {
+ return _updateFormAction(newUrl, containerId);
+ },
+
+ // Content Management
+ loadContent: function(url, target, options = {}) {
+ return _ajax.loadContentIntoTarget(url, target, options);
+ },
+
+ updateElement: function(selector, html, mode = 'replace') {
+ return _ajax.updateDOMElement(selector, html, mode);
+ },
+
+ // Status & Messages
+ showStatusMessage: function(message, type = 'info', form = null) {
+ return _ajax.showStatusMessage(message, type, form);
+ },
+
+ // UI Actions
+ showAddAttribute: function(containerSelector = null) {
+ return _showAddAttribute(containerSelector);
+ },
+
+ toggleSecretField: function(button) {
+ return _toggleSecretField(button);
+ },
+
+ updateBooleanHiddenField: function(checkbox) {
+ return _updateBooleanHiddenField(checkbox);
+ },
+
+ toggleExpandedView: function(button) {
+ return _toggleExpandedView(button);
+ },
+
+ // Initialization
+ init: function() {
+ _initializeAllContainers();
+ }
+ };
+
+ // Export to Hi namespace
+ window.Hi.attr = HiAttr;
+
+ // Private Ajax Infrastructure
+ const _ajax = {
+ // Submit form with custom Ajax handling
+ submitFormWithAjax: function(form, options = {}) {
+ const $form = $(form);
+
+ // Ensure we have a valid form element
+ if ($form.length === 0 || !$form[0] || $form[0].tagName !== 'FORM') {
+ console.error('DEBUG: Invalid form element passed to submitFormWithAjax:', form);
+ return;
+ }
+
+ // Find the container and sync textarea values to hidden fields before submission
+ const $container = $form.closest(Hi.ATTR_V2_CONTAINER_SELECTOR);
+ if ($container.length > 0) {
+ _syncTextareaValuesToHiddenFields($container);
+ }
+
+ const formData = new FormData($form[0]);
+ const url = $form.attr('action');
+ const method = $form.attr('method') || 'POST';
+
+ // Add CSRF token if not already present
+ if (!formData.has(ATTR_V2_INTERNAL.CSRF_TOKEN_NAME)) {
+ const csrfToken = $(`[name=${ATTR_V2_INTERNAL.CSRF_TOKEN_NAME}]`).val();
+ if (csrfToken) {
+ formData.append(ATTR_V2_INTERNAL.CSRF_TOKEN_NAME, csrfToken);
+ }
+ }
+
+ return $.ajax({
+ url: url,
+ method: method,
+ data: formData,
+ processData: false,
+ contentType: false,
+ headers: {
+ [ATTR_V2_INTERNAL.XML_HTTP_REQUEST_HEADER]: 'XMLHttpRequest'
+ }
+ }).done((response) => {
+ this.handleFormSuccess(response, $form, options);
+ }).fail((xhr) => {
+ this.handleFormError(xhr, $form);
+ });
+ },
+
+ // Load content into target via GET request
+ loadContentIntoTarget: function(url, target, options = {}) {
+ return $.ajax({
+ url: url,
+ method: 'GET',
+ headers: {
+ [ATTR_V2_INTERNAL.XML_HTTP_REQUEST_HEADER]: 'XMLHttpRequest'
+ }
+ }).done((response) => {
+ // Handle response for content loading
+ if (typeof response === 'string') {
+ this.updateDOMElement(target, response, options.mode || 'replace');
+ } else {
+ console.warn('loadContentIntoTarget: Unexpected response type:', typeof response);
+ }
+ }).fail((xhr) => {
+ console.error('Failed to load content:', xhr);
+
+ // Show error message to user if we can find a form context
+ const $target = $(target);
+ const $form = $target.closest('form');
+ if ($form.length > 0) {
+ this.handleFormError(xhr, $form);
+ } else {
+ // Fallback: show error in any available status container
+ // These are transient errors (like history loading), so allow auto-dismiss
+ const errorMessage = this.getErrorMessageForStatus(xhr.status, xhr.statusText);
+ this.showStatusMessage(errorMessage, STATUS_TYPE.ERROR, null, 5000);
+ }
+ });
+ },
+
+ // Handle successful form submission
+ // Parse response data into normalized format
+ parseResponse: function(response) {
+ // Handle null/undefined responses
+ if (!response) {
+ return {};
+ }
+
+ // Handle string responses
+ if (typeof response === 'string') {
+ if (response.trim() === '') {
+ return {};
+ }
+ try {
+ return JSON.parse(response);
+ } catch (e) {
+ console.warn('Failed to parse response as JSON:', e);
+ return { message: response }; // Treat as plain text message
+ }
+ }
+
+ // Handle object responses
+ if (typeof response === 'object') {
+ return response;
+ }
+
+ // Handle other types (number, boolean, etc.)
+ console.warn('Unexpected response type:', typeof response);
+ return { message: String(response) };
+ },
+
+ // Process DOM updates from response data
+ processDOMUpdates: function(data, options = {}) {
+ // Track the last append target for scrolling decision
+ // When scrollToNewContent is requested and multiple updates occur,
+ // we scroll to the LAST appended content. This decision assumes that
+ // in most cases (like file uploads), the last append is the most
+ // relevant/newest content the user wants to see. If different behavior
+ // is needed, the caller should handle scrolling manually.
+ let lastAppendTarget = null;
+
+ if (data.updates && Array.isArray(data.updates)) {
+ data.updates.forEach(update => {
+ if (update.target && update.html) {
+ this.updateDOMElement(update.target, update.html, update.mode || 'replace');
+
+ // Track append operations for potential scrolling
+ if (update.mode === 'append') {
+ lastAppendTarget = update.target;
+ }
+ }
+ });
+ }
+
+ return lastAppendTarget;
+ },
+
+ // Process status message from response data
+ processStatusMessage: function(data, $form, isError = false) {
+
+ // Handle explicit messages from server
+ if (data && data.message) {
+ const messageType = isError ? STATUS_TYPE.ERROR : STATUS_TYPE.SUCCESS;
+
+ // For form validation errors, make them persistent (no auto-dismiss)
+ const timeout = isError ? 0 : null; // 0 = no auto-dismiss for errors, null = default for success
+ this.showStatusMessage(data.message, messageType, $form, timeout);
+ return;
+ }
+
+ // Provide default messages when server doesn't provide one
+ if (!isError) {
+ // Success case with no explicit message
+ this.showStatusMessage('Success', STATUS_TYPE.SUCCESS, $form);
+ } else {
+ // Error case with no explicit message - make persistent
+ this.showStatusMessage('An error occurred while processing your request', STATUS_TYPE.ERROR, $form, 0);
+ }
+ },
+
+ // Unified response handler for both success and error responses
+ handleResponse: function(response, $form, options = {}, isError = false) {
+ // Parse response into normalized format
+ const data = this.parseResponse(response);
+
+ // Process DOM updates first (works for both success and error)
+ const lastAppendTarget = this.processDOMUpdates(data, options);
+
+ // Handle scroll-to-new-content if requested by caller
+ if (options.scrollToNewContent && lastAppendTarget) {
+ const element = document.querySelector(lastAppendTarget);
+ if (element) {
+ // Small delay to ensure DOM is fully updated before scrolling
+ setTimeout(() => {
+ element.scrollIntoView({ behavior: 'smooth', block: 'start' });
+ }, 100);
+ }
+ }
+
+ // Show status message
+ this.processStatusMessage(data, $form, isError);
+
+ // Re-initialize containers after update
+ setTimeout(() => {
+ _initializeAllContainers();
+ }, 50);
+ },
+
+ // Handle successful form submission - now delegates to unified handler
+ handleFormSuccess: function(response, $form, options = {}) {
+ this.handleResponse(response, $form, options, false);
+ },
+
+ // Handle form submission errors - now delegates to unified handler
+ handleFormError: function(xhr, $form) {
+ let response;
+ let hasValidResponse = false;
+
+ // Try to parse error response if we have content
+ if (xhr.responseText && xhr.responseText.trim()) {
+ try {
+ response = JSON.parse(xhr.responseText);
+ hasValidResponse = true;
+ } catch (e) {
+ console.warn('Failed to parse error response JSON:', e);
+ // Continue to create fallback response
+ }
+ }
+
+ // Create fallback error response if parsing fails or no content
+ if (!hasValidResponse) {
+ const fallbackMessage = this.getErrorMessageForStatus(xhr.status, xhr.statusText);
+ response = {
+ success: false,
+ message: fallbackMessage
+ };
+ } else {
+ // If we have a parsed response but no message, add status-based message
+ if (!response.message) {
+ response.message = this.getErrorMessageForStatus(xhr.status, xhr.statusText);
+ }
+ }
+
+ // Ensure response has required structure
+ if (!response.hasOwnProperty('success')) {
+ response.success = false;
+ }
+
+ // Use unified handler to process error response (including DOM updates)
+ this.handleResponse(response, $form, {}, true);
+ },
+
+ // Generate appropriate error message based on HTTP status code
+ getErrorMessageForStatus: function(status, statusText) {
+ switch (status) {
+ case 400:
+ return 'Bad request - please check your input and try again';
+ case 401:
+ return 'Authentication required - please log in and try again';
+ case 403:
+ return 'Access denied - you do not have permission for this action';
+ case 404:
+ return 'The requested resource was not found';
+ case 408:
+ return 'Request timeout - please try again';
+ case 500:
+ return 'Server error occurred - please try again later';
+ case 502:
+ return 'Bad gateway - server is temporarily unavailable';
+ case 503:
+ return 'Service unavailable - please try again later';
+ case 504:
+ return 'Gateway timeout - please try again later';
+ case 0:
+ return 'Network error - please check your connection and try again';
+ default:
+ if (status >= 400 && status < 500) {
+ return `Client error (${status}): ${statusText || 'Please check your request and try again'}`;
+ } else if (status >= 500) {
+ return `Server error (${status}): ${statusText || 'Please try again later'}`;
+ } else {
+ return `Unexpected error (${status}): ${statusText || 'Please try again'}`;
+ }
+ }
+ },
+
+ // Update DOM element with new content
+ updateDOMElement: function(selector, html, mode = 'replace') {
+ const $target = $(selector);
+ if ($target.length === 0) {
+ console.warn('Target element not found:', selector);
+ return;
+ }
+
+ switch (mode) {
+ case 'replace':
+ $target.html(html);
+ break;
+ case 'append':
+ $target.append(html);
+ break;
+ case 'prepend':
+ $target.prepend(html);
+ break;
+ default:
+ $target.html(html);
+ }
+ },
+
+ // Show status message in appropriate container
+ // $element can be the container itself or any element within it
+ showStatusMessage: function(message, type = STATUS_TYPE.INFO, $element = null, timeout = null) {
+ // If $element is provided, find its container (or itself if it IS the container)
+ // Otherwise use the first container on the page
+ const $container = $element ? $($element).closest(Hi.ATTR_V2_CONTAINER_SELECTOR) : $(Hi.ATTR_V2_CONTAINER_SELECTOR).first();
+ const $statusMsg = $container.find(Hi.ATTR_V2_STATUS_MESSAGE_SELECTOR);
+
+ if ($statusMsg.length === 0) return;
+
+ // Map type to CSS class
+ const cssClass = type === STATUS_TYPE.SUCCESS ? ATTR_V2_INTERNAL.STATUS_SUCCESS_CLASS :
+ type === STATUS_TYPE.ERROR ? ATTR_V2_INTERNAL.STATUS_ERROR_CLASS :
+ type === STATUS_TYPE.WARNING ? ATTR_V2_INTERNAL.STATUS_WARNING_CLASS :
+ ATTR_V2_INTERNAL.STATUS_INFO_CLASS;
+
+ // Set default timeout based on type if not provided
+ if (timeout === null) {
+ timeout = type === STATUS_TYPE.SUCCESS ? 3000 : 5000;
+ }
+
+ // Update message with proper styling
+ $statusMsg.text(message)
+ .removeClass(`${ATTR_V2_INTERNAL.STATUS_SUCCESS_CLASS} ${ATTR_V2_INTERNAL.STATUS_ERROR_CLASS} ${ATTR_V2_INTERNAL.STATUS_INFO_CLASS} ${ATTR_V2_INTERNAL.STATUS_WARNING_CLASS}`)
+ .addClass(cssClass + ' ml-2') // ml-2 for consistency with existing usage
+ .show();
+
+ // Auto-dismiss after specified timeout (0 = no auto-dismiss)
+ if (timeout > 0) {
+ setTimeout(() => {
+ $statusMsg.text('')
+ .attr('class', `${Hi.ATTR_V2_STATUS_MESSAGE_CLASS} ml-2`); // Reset to base class
+ }, timeout);
+ }
+ }
+ };
+
+ // Initialize all V2 containers when DOM is ready
+ document.addEventListener('DOMContentLoaded', function() {
+ _initializeAllContainers();
+ });
+
+ // No longer using antinode.js - initialization handled by custom Ajax callbacks
+
+ // Listen for any modal shown events and initialize V2 containers
+ $(document).on('shown.bs.modal', ATTR_V2_INTERNAL.MODAL_SELECTOR, function(e) {
+ _initializeAllContainers();
+ e.stopPropagation(); // Prevent bubbling to other handlers
+ });
+
+ // Container-aware utility function for updating form actions and browser history
+ // This is a generic helper that can be called from template onclick handlers
+ function _updateFormAction(newUrl, containerId) {
+ if (!newUrl || !containerId) {
+ console.warn('Hi.attr.updateFormAction: newUrl and containerId are required');
+ return;
+ }
+
+ // Find the form within the specific container
+ const $container = $(`#${containerId}`);
+ if ($container.length === 0) {
+ console.warn('Hi.attr.updateFormAction: Container not found:', containerId);
+ return;
+ }
+
+ const $form = $container.find(Hi.ATTR_V2_FORM_CLASS_SELECTOR);
+ if ($form.length === 0) {
+ console.warn('Hi.attr.updateFormAction: No form found in container:', containerId);
+ return;
+ }
+
+ // Update form action
+ $form.attr('action', newUrl);
+
+ // Update browser history without page reload
+ history.pushState(null, '', newUrl);
+ };
+
+
+ // Multi-instance container initialization
+ function _initializeAllContainers() {
+ // Initialize all attribute editing containers found on page
+ $(Hi.ATTR_V2_CONTAINER_SELECTOR).each(function() {
+ _initializeContainer($(this));
+ });
+ }
+
+ function _initializeContainer($container) {
+ // Check if this container is already initialized to prevent double-initialization
+ if ($container.data(ATTR_V2_INTERNAL.INITIALIZED_DATA_KEY)) {
+ // Always reprocess AJAX handlers to handle newly loaded content
+ _setupCustomAjaxHandlers($container);
+ // Re-initialize textareas after content updates (DOM may have changed)
+ _reinitializeTextareas($container);
+ // Reinitialize dirty tracking for new content
+ if (window.Hi.attr.dirtyTracking) {
+ window.Hi.attr.dirtyTracking.reinitializeContainer($container.attr('id'));
+ }
+ return;
+ }
+
+ // Full container initialization - don't assume what persists across AJAX updates
+ _setupBasicEventListeners($container);
+ _initializeExpandableTextareas($container); // Must come BEFORE autosize
+ _initializeAutosizeTextareas($container); // Now only applies to non-truncated
+ // Note: Form submission handler removed - textarea sync now handled in Ajax submission
+ _setupCustomAjaxHandlers($container); // NEW: Custom Ajax form handling
+
+ // Reinitialize dirty tracking for this container
+ if (window.Hi && window.Hi.attr && window.Hi.attr.dirtyTracking) {
+ window.Hi.attr.dirtyTracking.reinitializeContainer($container.attr('id'));
+ }
+
+ // Handle auto-dismiss messages for this container
+ _handleAutoDismissMessages($container);
+
+ // Mark this container as initialized
+ $container.data(ATTR_V2_INTERNAL.INITIALIZED_DATA_KEY, true);
+ }
+
+ function _handleAutoDismissMessages($container) {
+ const $statusMsg = $container.find(Hi.ATTR_V2_STATUS_MESSAGE_SELECTOR);
+ const $dismissibleElements = $statusMsg.find(Hi.ATTR_V2_AUTO_DISMISS_SELECTOR);
+ if ($dismissibleElements.length > 0) {
+ setTimeout(() => {
+ $dismissibleElements.remove();
+ // Hide the entire status message container if it's now empty
+ if ($statusMsg.text().trim() === '') {
+ $statusMsg.hide();
+ }
+ }, 5000);
+ }
+ }
+
+ // Setup custom Ajax handlers for forms and links in this container
+ function _setupCustomAjaxHandlers($container) {
+ // Handle main form submissions
+ const $forms = $container.find(`form${Hi.ATTR_V2_FORM_CLASS_SELECTOR}`);
+ $forms.each(function(index) {
+ const form = this;
+ const $form = $(form);
+
+ // Remove any existing handlers to avoid duplicates
+ $form.off(`submit.${ATTR_V2_INTERNAL.AJAX_EVENT_NAMESPACE}`);
+
+ // Add custom Ajax submission handler
+ $form.on(`submit.${ATTR_V2_INTERNAL.AJAX_EVENT_NAMESPACE}`, function(e) {
+ e.preventDefault();
+
+ _ajax.submitFormWithAjax(form);
+ });
+ });
+
+ // Handle history links
+ const $historyLinks = $container.find(Hi.ATTR_V2_HISTORY_LINK_SELECTOR);
+ $historyLinks.each(function() {
+ const $link = $(this);
+
+ // Skip if already processed
+ if ($link.data(ATTR_V2_INTERNAL.PROCESSED_DATA_KEY)) {
+ return;
+ }
+
+ $link.data(ATTR_V2_INTERNAL.PROCESSED_DATA_KEY, true);
+ $link.off(`click.${ATTR_V2_INTERNAL.AJAX_EVENT_NAMESPACE}`);
+
+ $link.on(`click.${ATTR_V2_INTERNAL.AJAX_EVENT_NAMESPACE}`, function(e) {
+ e.preventDefault();
+
+ const url = $link.attr('href');
+
+ // Server will return JSON response with target selector and HTML
+ $.ajax({
+ url: url,
+ method: 'GET',
+ headers: {
+ 'X-Requested-With': 'XMLHttpRequest'
+ }
+ }).done((response) => {
+ _ajax.handleFormSuccess(response, $container.find(Hi.ATTR_V2_FORM_CLASS_SELECTOR));
+ }).fail((xhr) => {
+ _ajax.handleFormError(xhr, $container.find(Hi.ATTR_V2_FORM_CLASS_SELECTOR));
+ });
+ });
+ });
+
+ // Handle value restore links
+ const $restoreLinks = $container.find(Hi.ATTR_V2_RESTORE_LINK_SELECTOR);
+ $restoreLinks.each(function() {
+ const $link = $(this);
+
+ // Skip if already processed
+ if ($link.data(ATTR_V2_INTERNAL.PROCESSED_DATA_KEY)) {
+ return;
+ }
+
+ $link.data(ATTR_V2_INTERNAL.PROCESSED_DATA_KEY, true);
+ $link.off(`click.${ATTR_V2_INTERNAL.AJAX_EVENT_NAMESPACE}`);
+
+ $link.on(`click.${ATTR_V2_INTERNAL.AJAX_EVENT_NAMESPACE}`, function(e) {
+ e.preventDefault();
+
+ const url = $link.attr('href');
+
+ // Server will return JSON response with target selector and HTML
+ $.ajax({
+ url: url,
+ method: 'GET',
+ headers: {
+ 'X-Requested-With': 'XMLHttpRequest'
+ }
+ }).done((response) => {
+ _ajax.handleFormSuccess(response, $container.find(Hi.ATTR_V2_FORM_CLASS_SELECTOR));
+ }).fail((xhr) => {
+ _ajax.handleFormError(xhr, $container.find(Hi.ATTR_V2_FORM_CLASS_SELECTOR));
+ });
+ });
+ });
+
+ // Handle file upload forms - find the context-specific file input
+ const $fileInput = $container.find(Hi.ATTR_V2_FILE_INPUT_SELECTOR);
+
+ if ($fileInput.length > 0) {
+ // Skip if already processed
+ if ($fileInput.data(ATTR_V2_INTERNAL.PROCESSED_DATA_KEY)) {
+ return;
+ }
+
+ $fileInput.data(ATTR_V2_INTERNAL.PROCESSED_DATA_KEY, true);
+ $fileInput.off(`change.${ATTR_V2_INTERNAL.AJAX_EVENT_NAMESPACE}`);
+
+ $fileInput.on(`change.${ATTR_V2_INTERNAL.AJAX_EVENT_NAMESPACE}`, function(e) {
+ const fileInput = this;
+ const $uploadForm = $fileInput.closest('form');
+
+
+ if (fileInput.files && fileInput.files[0] && $uploadForm.length) {
+ // Use our custom Ajax submission with scroll-to-new-content option
+ // File uploads append new content that users want to see
+ _ajax.submitFormWithAjax($uploadForm[0], {
+ scrollToNewContent: true
+ });
+ }
+ });
+ }
+ }
+
+
+
+
+ function _setupBasicEventListeners($container) {
+ // Simple ENTER key prevention for attribute forms - scoped to this container
+ const $forms = $container.find(`form${Hi.ATTR_V2_FORM_CLASS_SELECTOR}`);
+
+ $forms.each(function() {
+ const form = this;
+
+ // Remove any existing keydown handlers to avoid duplicates
+ $(form).off('keydown.attr-v2-enter');
+
+ // Prevent ENTER from submitting forms (except textareas and submit buttons)
+ $(form).on('keydown.attr-v2-enter', function(event) {
+ if (event.key === 'Enter' &&
+ event.target.tagName !== 'TEXTAREA' &&
+ event.target.type !== 'submit') {
+ event.preventDefault();
+ return false;
+ }
+ });
+ });
+ }
+
+ // Simple add attribute - just show the last (empty) formset form
+ function _showAddAttribute(containerSelector = null) {
+ // Find the last attribute card (should be the empty extra form)
+ const scope = containerSelector ? $(containerSelector) : $(document);
+ const attributeCards = scope.find(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, containerSelector = null) {
+ // Find the file card, scoped to container if provided
+ const scope = containerSelector ? $(containerSelector) : $(document);
+ const $fileCard = scope.find(`${Hi.ATTR_V2_FILE_CARD_SELECTOR}[${Hi.DATA_ATTRIBUTE_ID_ATTR}="${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="${Hi.ATTR_V2_DELETE_FILE_ATTR}"]`);
+ 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 (scoped to container)
+ _ajax.showStatusMessage(`"${fileValue}" will be deleted when you save`, STATUS_TYPE.WARNING, scope);
+ };
+
+ window.undoFileDeletion = function(attributeId, containerSelector = null) {
+ // Find the file card, scoped to container if provided
+ const scope = containerSelector ? $(containerSelector) : $(document);
+ const $fileCard = scope.find(`${Hi.ATTR_V2_FILE_CARD_SELECTOR}[${Hi.DATA_ATTRIBUTE_ID_ATTR}="${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="${Hi.ATTR_V2_DELETE_FILE_ATTR}"]`);
+ 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 (scoped to container)
+ _ajax.showStatusMessage(`Deletion of "${fileValue}" cancelled`, STATUS_TYPE.SUCCESS, scope);
+ };
+
+ // History functionality now handled by antinode async pattern
+ // History button uses data-async to load content, no JavaScript needed
+
+ window.markAttributeForDeletion = function(attributeId, containerSelector = null) {
+ // Find the attribute card, scoped to container if provided
+ const scope = containerSelector ? $(containerSelector) : $(document);
+ const $attributeCard = scope.find(`[${Hi.DATA_ATTRIBUTE_ID_ATTR}="${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 (scoped to container)
+ _ajax.showStatusMessage(`"${attributeName}" will be deleted when you save`, STATUS_TYPE.WARNING, scope);
+ };
+
+ window.undoAttributeDeletion = function(attributeId, containerSelector = null) {
+ // Find the attribute card, scoped to container if provided
+ const scope = containerSelector ? $(containerSelector) : $(document);
+ const $attributeCard = scope.find(`[${Hi.DATA_ATTRIBUTE_ID_ATTR}="${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 (scoped to container)
+ _ajax.showStatusMessage(`Deletion of "${attributeName}" cancelled`, STATUS_TYPE.SUCCESS, scope);
+ };
+
+ function _toggleSecretField(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();
+ }
+ };
+
+ // Update hidden field when boolean checkbox changes
+ function _updateBooleanHiddenField(checkbox) {
+ const hiddenFieldId = checkbox.getAttribute(Hi.DATA_HIDDEN_FIELD_ATTR);
+ const hiddenField = document.getElementById(hiddenFieldId);
+
+ if (hiddenField) {
+ // Update hidden field value based on checkbox state
+ hiddenField.value = checkbox.checked ? 'True' : 'False';
+ }
+ };
+
+
+ // 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($container = null) {
+ // Find textareas that need initialization (scoped to container if provided)
+ const textareas = $container ?
+ $container.find(Hi.ATTR_V2_TEXTAREA_SELECTOR) :
+ $(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(Hi.DATA_OVERFLOW_ATTR) === 'true';
+
+ // Check if this is a display field (new pattern) or legacy textarea
+ const hiddenFieldId = textarea.attr(Hi.DATA_HIDDEN_FIELD_ATTR);
+ 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(Hi.DATA_OVERFLOW_ATTR, overflows ? 'true' : 'false');
+ wrapper.attr(Hi.DATA_LINE_COUNT_ATTR, 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(ATTR_V2_INTERNAL.TRUNCATED_CLASS);
+
+ // 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(ATTR_V2_INTERNAL.TRUNCATED_CLASS);
+
+ // 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 = $(Hi.ATTR_V2_DISPLAY_FIELD_SELECTOR);
+
+ displayTextareas.each(function() {
+ const displayField = $(this);
+ const isOverflowing = displayField.attr(Hi.DATA_OVERFLOW_ATTR) === 'true';
+ const hiddenFieldId = displayField.attr(Hi.DATA_HIDDEN_FIELD_ATTR);
+ 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
+ function _toggleExpandedView(button) {
+ const $button = $(button);
+ const wrapper = $button.closest(Hi.ATTR_V2_TEXT_VALUE_WRAPPER_SELECTOR);
+ const displayField = wrapper.find(Hi.ATTR_V2_DISPLAY_FIELD_SELECTOR
+ + ', ' + Hi.ATTR_V2_TEXTAREA_SELECTOR); // Support both new and legacy
+ const showMoreText = $button.find(Hi.ATTR_V2_SHOW_MORE_TEXT_SELECTOR);
+ const showLessText = $button.find(Hi.ATTR_V2_SHOW_LESS_TEXT_SELECTOR);
+
+ // Get hidden field if using new pattern
+ const hiddenFieldId = displayField.attr(Hi.DATA_HIDDEN_FIELD_ATTR);
+ 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(ATTR_V2_INTERNAL.TRUNCATED_CLASS);
+
+ 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(ATTR_V2_INTERNAL.TRUNCATED_CLASS);
+ wrapper.find(Hi.ATTR_V2_EXPAND_CONTROLS_SELECTOR).hide();
+
+ // Update wrapper state
+ wrapper.attr(Hi.DATA_OVERFLOW_ATTR, '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');
+ }
+ }
+
+ // Sync textarea values to hidden fields before form submission
+ function _syncTextareaValuesToHiddenFields($container) {
+ // Process all display fields within this container
+ $container.find(Hi.ATTR_V2_DISPLAY_FIELD_SELECTOR).each(function() {
+ const displayField = $(this);
+ const hiddenFieldId = displayField.attr(Hi.DATA_HIDDEN_FIELD_ATTR);
+ const hiddenField = hiddenFieldId ? $container.find('#' + hiddenFieldId) : null;
+
+ if (hiddenField && hiddenField.length > 0) {
+ // Only sync if display field is NOT showing truncated data
+ if (!displayField.prop('readonly') && !displayField.hasClass(ATTR_V2_INTERNAL.TRUNCATED_CLASS)) {
+ // 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
+ }
+ });
+ }
+
+
+})();
diff --git a/src/hi/static/js/audio.js b/src/hi/static/js/audio.js
index 9aedbe4b..419dd099 100644
--- a/src/hi/static/js/audio.js
+++ b/src/hi/static/js/audio.js
@@ -67,8 +67,6 @@
function checkAudioStatus() {
clearAudioPollingTimer();
try {
- if (Hi.DEBUG) { console.log(`Audio polling check - current: ${gActiveSignalName}`); }
-
Hi.watchdog.ok( AudioPollingWatchdogType );
if ( gActiveSignalName ) {
diff --git a/src/hi/static/js/main.js b/src/hi/static/js/main.js
index 8801555a..c3fed6b4 100644
--- a/src/hi/static/js/main.js
+++ b/src/hi/static/js/main.js
@@ -65,70 +65,49 @@
},
// Entity Attribute Editing V2 - IDs and Classes
- ATTR_V2_FORM_ID: 'attr-v2-form',
- ATTR_V2_CONTENT_ID: 'attr-v2-content',
+ ATTR_V2_CONTENT_CLASS: '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_STATUS_MESSAGE_CLASS: 'attr-v2-status-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_FORM_CLASS_SELECTOR: '.attr-v2-form', // Form class
+ ATTR_V2_CONTAINER_SELECTOR: '.attr-v2-container',
+ ATTR_V2_FILE_INPUT_SELECTOR: '.attr-v2-file-input',
+ ATTR_V2_STATUS_MESSAGE_SELECTOR: '.attr-v2-status-message',
+ ATTR_V2_DIRTY_MESSAGE_SELECTOR: '.attr-v2-dirty-message',
+ ATTR_V2_HISTORY_LINK_SELECTOR: '.attr-v2-history-link',
+ ATTR_V2_RESTORE_LINK_SELECTOR: '.attr-v2-restore-link',
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'
+ ATTR_V2_EXPAND_CONTROLS_SELECTOR: '.attr-v2-expand-controls',
+ ATTR_V2_AUTO_DISMISS_SELECTOR: '.attr-v2-auto-dismiss',
+ ATTR_V2_DISPLAY_FIELD_SELECTOR: '.display-field',
+ ATTR_V2_SHOW_MORE_TEXT_SELECTOR: '.show-more-text',
+ ATTR_V2_SHOW_LESS_TEXT_SELECTOR: '.show-less-text',
+ // Data attributes set by server, read by JS
+ DATA_ATTRIBUTE_ID_ATTR: 'data-attribute-id',
+ DATA_HIDDEN_FIELD_ATTR: 'data-hidden-field',
+ DATA_OVERFLOW_ATTR: 'data-overflow',
+ DATA_LINE_COUNT_ATTR: 'data-line-count',
+ DATA_ORIGINAL_VALUE_ATTR: 'data-original-value',
+ ATTR_V2_DELETE_FILE_ATTR: 'delete_file_attribute'
};
window.Hi = Hi;
diff --git a/src/hi/static/js/status.js b/src/hi/static/js/status.js
index 00d9b317..9b9cf486 100644
--- a/src/hi/static/js/status.js
+++ b/src/hi/static/js/status.js
@@ -168,7 +168,9 @@
}
function handleAlertStatusData( alertStatusData ) {
- if ( Hi.DEBUG ) { console.log('Alert Status Data: ', JSON.stringify(alertStatusData) ); }
+ if ( Hi.DEBUG && alertStatusData.length ) {
+ console.log('Alert Status Data: ', JSON.stringify(alertStatusData) );
+ }
if ( ! alertStatusData ) {
Hi.audio.clearAudibleSignal();
diff --git a/src/hi/templates/panes/bottom_buttons.html b/src/hi/templates/panes/bottom_buttons.html
index fac71dc5..8c3661e5 100644
--- a/src/hi/templates/panes/bottom_buttons.html
+++ b/src/hi/templates/panes/bottom_buttons.html
@@ -4,28 +4,28 @@
<div class="d-flex justify-content-end">
{% if request.view_parameters.is_editing %}
<div class="mx-1">
- <a href="{% url 'edit_help' %}"
- class="btn btn-tertiary btn-control" role="button"
- data-async="true" >
- EDITING HELP
- </a>
+ <a href="{% url 'edit_help' %}"
+ class="btn btn-tertiary btn-control" role="button"
+ data-async="true" >
+ EDITING HELP
+ </a>
</div>
{% else %}
<div class="mx-1">
- {% include "console/panes/audio_control.html" %}
+ {% include "console/panes/audio_control.html" %}
</div>
<div class="mx-1">
- {% include "console/panes/sleep_mode_control.html" %}
+ {% include "console/panes/sleep_mode_control.html" %}
</div>
<div class="mx-1">
- {% include "console/panes/console_lock_button.html" %}
+ {% include "console/panes/console_lock_button.html" %}
</div>
<div class="mx-1">
- <a href="{% url 'config_settings' %}"
- class="btn btn-tertiary btn-control" role="button"
- data-async="true" >
- SETTINGS
- </a>
+ <a href="{% url 'config_home' %}"
+ class="btn btn-tertiary btn-control" role="button"
+ data-async="true" >
+ CONFIGURE
+ </a>
</div>
{% endif %}
</div>
diff --git a/src/hi/testing/dev_overrides.py b/src/hi/testing/dev_overrides.py
new file mode 100644
index 00000000..6e096179
--- /dev/null
+++ b/src/hi/testing/dev_overrides.py
@@ -0,0 +1,100 @@
+import logging
+import random
+
+from django.conf import settings
+from django.forms.utils import ErrorList
+
+from hi.apps.attribute.transient_models import AttributeEditFormData
+
+logger = logging.getLogger(__name__)
+
+
+class DevOverrideManager:
+
+ @classmethod
+ def validate_forms( cls, edit_form_data: AttributeEditFormData ) -> bool:
+ """
+ For: AttributeEditFormHandler.validate()forms)
+
+ Inject simulated errors for UI testing (DEBUG mode only).
+
+ This method simulates all types of form errors to test UI error display:
+ - Owner form field errors
+ - Owner form non-field errors
+ - Formset management errors (simulated by corrupting management form)
+ - Formset non-form errors
+ - Individual form field errors
+ - Individual form non-field errors
+
+ Returns:
+ bool: Always False (simulating validation failure)
+ """
+ assert settings.DEBUG
+
+ error_injection_rate = 1.0
+
+ logger.warning("Injecting test errors for UI validation testing")
+
+ # Inject owner form errors
+ if edit_form_data.owner_form and random.random() <= error_injection_rate:
+ owner_form = edit_form_data.owner_form
+
+ # Inject field errors
+ if random.random() <= error_injection_rate:
+ for field_name in list(owner_form.fields.keys())[:2]: # Limit to first 2 fields
+ if random.random() <= error_injection_rate:
+ if not hasattr(owner_form, '_errors') or not owner_form._errors:
+ owner_form._errors = {}
+ if field_name not in owner_form._errors:
+ owner_form._errors[field_name] = ErrorList()
+ owner_form._errors[field_name].append(f"TEST: {field_name} validation failed")
+
+ # Inject non-field errors
+ if random.random() <= error_injection_rate:
+ if not hasattr(owner_form, '_errors') or not owner_form._errors:
+ owner_form._errors = {}
+ if '__all__' not in owner_form._errors:
+ owner_form._errors['__all__'] = ErrorList()
+ owner_form._errors['__all__'].append("TEST: Owner form validation failed")
+
+ # Inject formset errors
+ if edit_form_data.regular_attributes_formset and random.random() <= error_injection_rate:
+ formset = edit_form_data.regular_attributes_formset
+
+ # Inject formset non-form errors
+ if random.random() <= error_injection_rate:
+ if not hasattr(formset, '_non_form_errors') or not formset._non_form_errors:
+ formset._non_form_errors = ErrorList()
+ formset._non_form_errors.append("TEST: Formset validation constraint failed")
+
+ # Inject individual form errors (only for bound forms)
+ for i, form in enumerate(formset.forms):
+ # Skip non-bound forms (empty extra forms)
+ if not form.is_bound:
+ continue
+
+ if random.random() <= error_injection_rate:
+
+ # Inject field errors
+ if random.random() <= error_injection_rate:
+ field_names = list(form.fields.keys())[:2] # Limit to first 2 fields
+ for field_name in field_names:
+ if random.random() <= error_injection_rate:
+ if not hasattr(form, '_errors') or not form._errors:
+ form._errors = {}
+ if field_name not in form._errors:
+ form._errors[field_name] = ErrorList()
+ form._errors[field_name].append(f"TEST: Form {i} {field_name} invalid")
+
+ # Inject non-field errors
+ if random.random() <= error_injection_rate:
+ if not hasattr(form, '_errors') or not form._errors:
+ form._errors = {}
+ if '__all__' not in form._errors:
+ form._errors['__all__'] = ErrorList()
+ form._errors['__all__'].append(f"TEST: Form {i} validation failed")
+
+ # Always return False to simulate validation failure
+ return False
+
+