Skip to content

Home Information - Your home, your data, organized.

Python

Feature/27 Bulk Adding Entities (#275)

Thiago Trautwein Santos4f5b18cecf38
diff --git a/src/hi/apps/entity/edit/tests/test_views.py b/src/hi/apps/entity/edit/tests/test_views.py
index 2d8dcb94..3c2e6343 100644
--- a/src/hi/apps/entity/edit/tests/test_views.py
+++ b/src/hi/apps/entity/edit/tests/test_views.py
@@ -89,6 +89,20 @@ class TestEntityAddView(DualModeViewTestCase):
data = response.json()
self.assertIn('modal', data)
+ def test_get_entity_add_form_quantity_defaults_to_one(self):
+ """Test quantity field defaults to 1 in add form."""
+ url = reverse('entity_edit_entity_add')
+ response = self.client.get(url)
+
+ self.assertSuccessResponse(response)
+ self.assertHtmlResponse(response)
+ self.assertIn('entity_form', response.context)
+
+ entity_form = response.context['entity_form']
+ self.assertIn('quantity', entity_form.fields)
+ self.assertEqual(entity_form.fields['quantity'].initial, 1)
+ self.assertEqual(entity_form['quantity'].value(), 1)
+
def test_post_invalid_form(self):
"""Test POST request with invalid form data."""
# Submit form with missing required fields
@@ -117,6 +131,112 @@ class TestEntityAddView(DualModeViewTestCase):
# Verify no Entity was created with invalid data
self.assertFalse(Entity.objects.filter(name='').exists())
+ def test_post_invalid_form_quantity_above_max(self):
+ """Test POST request rejects quantity values above 100."""
+ form_data = {
+ 'name': 'Test Entity',
+ 'entity_type_str': str(EntityType.LIGHT),
+ 'quantity': '101',
+ }
+
+ url = reverse('entity_edit_entity_add')
+ response = self.client.post(url, form_data)
+
+ self.assertSuccessResponse(response)
+ self.assertHtmlResponse(response)
+ self.assertIn('entity_form', response.context)
+
+ form = response.context['entity_form']
+ self.assertFalse(form.is_valid())
+ self.assertIn('quantity', form.errors)
+ self.assertEqual(Entity.objects.filter(name='Test Entity').count(), 0)
+
+ def test_post_invalid_form_quantity_below_min(self):
+ """Test POST request rejects quantity values below 1."""
+ form_data = {
+ 'name': 'Test Entity',
+ 'entity_type_str': str(EntityType.LIGHT),
+ 'quantity': '0',
+ }
+
+ url = reverse('entity_edit_entity_add')
+ response = self.client.post(url, form_data)
+
+ self.assertSuccessResponse(response)
+ self.assertHtmlResponse(response)
+ self.assertIn('entity_form', response.context)
+
+ form = response.context['entity_form']
+ self.assertFalse(form.is_valid())
+ self.assertIn('quantity', form.errors)
+ self.assertEqual(Entity.objects.filter(name='Test Entity').count(), 0)
+
+ def test_post_invalid_form_quantity_missing(self):
+ """Test POST request rejects missing quantity."""
+ form_data = {
+ 'name': 'Test Entity',
+ 'entity_type_str': str(EntityType.LIGHT),
+ }
+
+ url = reverse('entity_edit_entity_add')
+ response = self.client.post(url, form_data)
+
+ self.assertSuccessResponse(response)
+ self.assertHtmlResponse(response)
+ self.assertIn('entity_form', response.context)
+
+ form = response.context['entity_form']
+ self.assertFalse(form.is_valid())
+ self.assertIn('quantity', form.errors)
+ self.assertEqual(Entity.objects.filter(name='Test Entity').count(), 0)
+
+ def test_post_invalid_form_quantity_non_numeric(self):
+ """Test POST request rejects non-numeric quantity values."""
+ form_data = {
+ 'name': 'Test Entity',
+ 'entity_type_str': str(EntityType.LIGHT),
+ 'quantity': 'abc',
+ }
+
+ url = reverse('entity_edit_entity_add')
+ response = self.client.post(url, form_data)
+
+ self.assertSuccessResponse(response)
+ self.assertHtmlResponse(response)
+ self.assertIn('entity_form', response.context)
+
+ form = response.context['entity_form']
+ self.assertFalse(form.is_valid())
+ self.assertIn('quantity', form.errors)
+ self.assertEqual(Entity.objects.filter(name='Test Entity').count(), 0)
+
+ def test_post_valid_form(self):
+ """Test POST request with valid form data."""
+ self.setSessionViewType(ViewType.CONFIGURATION)
+
+ form_data = {
+ 'name': 'Test Entity',
+ 'entity_type_str': str(EntityType.LIGHT),
+ 'quantity': '3',
+ }
+
+ initial_entity_count = Entity.objects.count()
+
+ url = reverse('entity_edit_entity_add')
+ response = self.client.post(url, form_data)
+
+ self.assertSuccessResponse(response)
+ self.assertJsonResponse(response)
+ response_data = response.json()
+ self.assertEqual(response_data['location'], reverse('home'))
+
+ self.assertEqual(Entity.objects.count(), initial_entity_count + 3)
+
+ created_entities = Entity.objects.filter(name__startswith='Test Entity')
+ self.assertEqual(created_entities.count(), 3)
+ for entity in created_entities:
+ self.assertEqual(entity.entity_type_str, str(EntityType.LIGHT))
+
def test_post_valid_form_location_view(self):
"""Test POST request with valid form data in location view context."""
# Set location view context
@@ -125,7 +245,8 @@ class TestEntityAddView(DualModeViewTestCase):
# Create comprehensive form data for new entity
form_data = {
'name': 'Test Entity',
- 'entity_type_str': str(EntityType.LIGHT)
+ 'entity_type_str': str(EntityType.LIGHT),
+ 'quantity': '1',
}
# Count existing entities before
@@ -166,7 +287,8 @@ class TestEntityAddView(DualModeViewTestCase):
url = reverse('entity_edit_entity_add')
response = self.client.post(url, {
'name': 'Test Entity Collection',
- 'entity_type_str': str(EntityType.WALL_SWITCH)
+ 'entity_type_str': str(EntityType.WALL_SWITCH),
+ 'quantity': '1',
})
# Expect antinode.js response (200 with JSON redirect)
@@ -195,7 +317,8 @@ class TestEntityAddView(DualModeViewTestCase):
url = reverse('entity_edit_entity_add')
response = self.client.post(url, {
'name': 'Test Entity Configuration',
- 'entity_type_str': str(EntityType.MOTION_SENSOR)
+ 'entity_type_str': str(EntityType.MOTION_SENSOR),
+ 'quantity': '1',
})
# Expect antinode.js response (200 with JSON redirect)
@@ -225,7 +348,8 @@ class TestEntityAddView(DualModeViewTestCase):
url = reverse('entity_edit_entity_add')
response = self.client.post(url, {
'name': 'Test Entity No Location',
- 'entity_type_str': str(EntityType.PRESENCE_SENSOR)
+ 'entity_type_str': str(EntityType.PRESENCE_SENSOR),
+ 'quantity': '1',
})
# Expect antinode.js response (200 with JSON redirect)
diff --git a/src/hi/apps/entity/edit/views.py b/src/hi/apps/entity/edit/views.py
index feff57af..d3cfa68c 100644
--- a/src/hi/apps/entity/edit/views.py
+++ b/src/hi/apps/entity/edit/views.py
@@ -1,6 +1,6 @@
import logging
import re
-from typing import Any, Dict, Optional
+from typing import Any, Dict, List, Optional
from django.core.exceptions import BadRequest, PermissionDenied
from django.db import transaction
@@ -15,7 +15,7 @@ import hi.apps.common.antinode as antinode
from hi.apps.entity.entity_manager import EntityManager
from hi.apps.entity.entity_pairing_manager import EntityPairingManager, EntityPairingError
from hi.apps.entity.edit.entity_type_transition_handler import EntityTypeTransitionHandler
-from hi.apps.entity.forms import EntityForm
+from hi.apps.entity.forms import EntityAddForm, EntityForm
from hi.apps.entity.models import (
ArchivedEntity,
ArchivedEntityAttribute,
@@ -70,12 +70,12 @@ class EntityAddView( HiModalView ):
def get( self, request, *args, **kwargs ):
context = {
- 'entity_form': EntityForm(),
+ 'entity_form': EntityAddForm(),
}
return self.modal_response( request, context )
def post( self, request, *args, **kwargs ):
- entity_form = EntityForm( request.POST )
+ entity_form = EntityAddForm( request.POST )
if not entity_form.is_valid():
context = {
'entity_form': entity_form,
@@ -83,16 +83,45 @@ class EntityAddView( HiModalView ):
return self.modal_response( request, context )
with transaction.atomic():
- entity = entity_form.save()
- self._add_to_current_view_type(
- request = request,
- entity = entity,
- )
+ created_entities = self._create_entities_bulk( entity_form = entity_form )
+ for i, entity in enumerate( created_entities ):
+ self._add_to_current_view_type(
+ request = request,
+ entity = entity,
+ bulk_grid_index = i,
+ bulk_grid_total = len( created_entities ),
+ )
+ continue
redirect_url = reverse('home')
return self.redirect_response( request, redirect_url )
- def _add_to_current_view_type( self, request, entity : Entity ):
+ def _create_entities_bulk(self, entity_form: EntityAddForm) -> List[Entity]:
+ base_name = entity_form.cleaned_data['name']
+ entity_type_str = entity_form.cleaned_data['entity_type_str']
+ quantity = entity_form.cleaned_data['quantity']
+
+ # Use create() in a loop rather than bulk_create() to ensure
+ # save() overrides and post_save signal handlers fire. At the
+ # 100-entity cap this is fast enough and avoids subtle bugs if
+ # save-time side effects are added to Entity in the future.
+ created_entities = []
+ for i in range( 1, quantity + 1 ):
+ entity_name = base_name if quantity == 1 else f'{base_name} ({i})'
+ entity = Entity.objects.create(
+ name=entity_name,
+ entity_type_str=entity_type_str,
+ )
+ created_entities.append(entity)
+ continue
+
+ return created_entities
+
+ def _add_to_current_view_type( self,
+ request,
+ entity : Entity,
+ bulk_grid_index : Optional[int] = None,
+ bulk_grid_total : Optional[int] = None ):
if request.view_parameters.view_type.is_location_view:
try:
@@ -100,6 +129,8 @@ class EntityAddView( HiModalView ):
EntityManager().add_entity_to_view(
entity = entity,
location_view = current_location_view,
+ bulk_grid_index = bulk_grid_index,
+ bulk_grid_total = bulk_grid_total,
)
except LocationView.DoesNotExist:
logger.warning( 'No current location view to add new entity to.')
diff --git a/src/hi/apps/entity/entity_manager.py b/src/hi/apps/entity/entity_manager.py
index aa39f987..4094b8b4 100644
--- a/src/hi/apps/entity/entity_manager.py
+++ b/src/hi/apps/entity/entity_manager.py
@@ -1,7 +1,7 @@
from decimal import Decimal
import logging
from threading import local
-from typing import List, Sequence, Tuple
+from typing import List, Optional, Sequence, Tuple
from django.db import transaction
from django.db.models.signals import post_save, post_delete
@@ -39,6 +39,9 @@ logger = logging.getLogger(__name__)
class EntityManager(Singleton):
DEFAULT_ICON_SIZE_PERCENT_OF_VIEWBOX = 10.0
+ DEFAULT_INITIAL_POSITION_GRID_COLUMNS = 4
+ DEFAULT_INITIAL_POSITION_GRID_SPACING_FRACTION = 0.18
+ DEFAULT_INITIAL_POSITION_VIEWBOX_MARGIN_FRACTION = 0.05
def __init_singleton__(self):
self._change_listeners = list()
@@ -113,7 +116,11 @@ class EntityManager(Singleton):
svg_path = svg_path_str,
)
- def create_entity_view( self, entity : Entity, location_view : LocationView ):
+ def create_entity_view( self,
+ entity : Entity,
+ location_view : LocationView,
+ bulk_grid_index : Optional[int] = None,
+ bulk_grid_total : Optional[int] = None ):
with transaction.atomic():
@@ -129,6 +136,8 @@ class EntityManager(Singleton):
self.add_entity_position_if_needed(
entity = entity,
location_view = location_view,
+ bulk_grid_index = bulk_grid_index,
+ bulk_grid_total = bulk_grid_total,
)
try:
entity_view = EntityView.objects.get(
@@ -152,7 +161,11 @@ class EntityManager(Singleton):
entity_view.delete()
return
- def add_entity_to_view( self, entity : Entity, location_view : LocationView ):
+ def add_entity_to_view( self,
+ entity : Entity,
+ location_view : LocationView,
+ bulk_grid_index : Optional[int] = None,
+ bulk_grid_total : Optional[int] = None ):
with transaction.atomic():
# Only create delegate entities the first time an entity is added to a view.
@@ -168,6 +181,8 @@ class EntityManager(Singleton):
_ = self.create_entity_view(
entity = entity,
location_view = location_view,
+ bulk_grid_index = bulk_grid_index,
+ bulk_grid_total = bulk_grid_total,
)
for delegate_entity in delegate_entity_list:
_ = self.create_entity_view(
@@ -201,7 +216,9 @@ class EntityManager(Singleton):
def add_entity_position_if_needed( self,
entity : Entity,
- location_view : LocationView ) -> EntityPosition:
+ location_view : LocationView,
+ bulk_grid_index : Optional[int] = None,
+ bulk_grid_total : Optional[int] = None ) -> EntityPosition:
try:
_ = EntityPosition.objects.get(
location = location_view.location,
@@ -211,9 +228,17 @@ class EntityManager(Singleton):
except EntityPosition.DoesNotExist:
pass
- # Default display in middle of current view
- svg_x = location_view.svg_view_box.x + ( location_view.svg_view_box.width / 2.0 )
- svg_y = location_view.svg_view_box.y + ( location_view.svg_view_box.height / 2.0 )
+ if bulk_grid_total is not None and bulk_grid_total > 1 and bulk_grid_index is not None:
+ svg_x, svg_y = self._get_bulk_initial_entity_position(
+ location_view = location_view,
+ bulk_grid_index = bulk_grid_index,
+ bulk_grid_total = bulk_grid_total,
+ )
+ else:
+ # Default display in middle of current view
+ svg_x = location_view.svg_view_box.x + ( location_view.svg_view_box.width / 2.0 )
+ svg_y = location_view.svg_view_box.y + ( location_view.svg_view_box.height / 2.0 )
+
svg_scale = self._get_default_icon_scale( entity = entity, location_view = location_view )
entity_position = EntityPosition.objects.create(
@@ -226,6 +251,59 @@ class EntityManager(Singleton):
)
return entity_position
+ def _get_bulk_initial_entity_position( self,
+ location_view : LocationView,
+ bulk_grid_index : int,
+ bulk_grid_total : int ) -> Tuple[float, float]:
+ view_box = location_view.svg_view_box
+ center_x = view_box.x + ( view_box.width / 2.0 )
+ center_y = view_box.y + ( view_box.height / 2.0 )
+
+ if bulk_grid_total <= 1:
+ return center_x, center_y
+
+ columns = min( max( 2, self.DEFAULT_INITIAL_POSITION_GRID_COLUMNS ), bulk_grid_total )
+ rows = ( bulk_grid_total + columns - 1 ) // columns
+
+ column_index = bulk_grid_index % columns
+ row_index = bulk_grid_index // columns
+
+ column_offset = column_index - ( ( columns - 1 ) / 2.0 )
+ row_offset = row_index - ( ( rows - 1 ) / 2.0 )
+
+ spacing_x = view_box.width * self.DEFAULT_INITIAL_POSITION_GRID_SPACING_FRACTION
+ spacing_y = view_box.height * self.DEFAULT_INITIAL_POSITION_GRID_SPACING_FRACTION
+
+ svg_x = center_x + ( column_offset * spacing_x )
+ svg_y = center_y + ( row_offset * spacing_y )
+
+ return self._clamp_point_to_viewbox(
+ svg_x = svg_x,
+ svg_y = svg_y,
+ view_box = view_box,
+ )
+
+ def _clamp_point_to_viewbox( self,
+ svg_x : float,
+ svg_y : float,
+ view_box ) -> Tuple[float, float]:
+ margin_x = view_box.width * self.DEFAULT_INITIAL_POSITION_VIEWBOX_MARGIN_FRACTION
+ margin_y = view_box.height * self.DEFAULT_INITIAL_POSITION_VIEWBOX_MARGIN_FRACTION
+
+ min_x = view_box.x + margin_x
+ max_x = ( view_box.x + view_box.width ) - margin_x
+ min_y = view_box.y + margin_y
+ max_y = ( view_box.y + view_box.height ) - margin_y
+
+ if min_x > max_x:
+ min_x = max_x = view_box.x + ( view_box.width / 2.0 )
+ if min_y > max_y:
+ min_y = max_y = view_box.y + ( view_box.height / 2.0 )
+
+ clamped_x = max( min_x, min( svg_x, max_x ) )
+ clamped_y = max( min_y, min( svg_y, max_y ) )
+ return clamped_x, clamped_y
+
def _get_default_icon_scale( self,
entity : Entity,
location_view : LocationView ) -> Decimal:
diff --git a/src/hi/apps/entity/forms.py b/src/hi/apps/entity/forms.py
index c2dd60b0..4bddd016 100644
--- a/src/hi/apps/entity/forms.py
+++ b/src/hi/apps/entity/forms.py
@@ -22,7 +22,25 @@ class EntityForm( forms.ModelForm ):
widget = forms.Select( attrs = { 'class' : 'custom-select' } ),
)
-
+
+class EntityAddForm( EntityForm ):
+
+ MAX_BULK_ADD_QUANTITY = 100
+
+ quantity = forms.IntegerField(
+ label = 'Quantity',
+ required = True,
+ min_value = 1,
+ max_value = MAX_BULK_ADD_QUANTITY,
+ initial = 1,
+ widget = forms.NumberInput( attrs = {
+ 'min': 1,
+ 'max': MAX_BULK_ADD_QUANTITY,
+ 'step': 1,
+ }),
+ )
+
+
class EntityAttributeForm( AttributeForm ):
class Meta( AttributeForm.Meta ):
model = EntityAttribute
diff --git a/src/hi/apps/entity/templates/entity/edit/modals/entity_add.html b/src/hi/apps/entity/templates/entity/edit/modals/entity_add.html
index 91caa39e..fbc84fbd 100644
--- a/src/hi/apps/entity/templates/entity/edit/modals/entity_add.html
+++ b/src/hi/apps/entity/templates/entity/edit/modals/entity_add.html
@@ -13,7 +13,7 @@ New Item
{% block body %}
<div>
- {% include "entity/edit/panes/entity_form.html" %}
+ {% include "entity/edit/panes/entity_add_form.html" %}
</div>
{% endblock %}
diff --git a/src/hi/apps/entity/templates/entity/edit/panes/entity_add_form.html b/src/hi/apps/entity/templates/entity/edit/panes/entity_add_form.html
new file mode 100644
index 00000000..26dae5f7
--- /dev/null
+++ b/src/hi/apps/entity/templates/entity/edit/panes/entity_add_form.html
@@ -0,0 +1,47 @@
+{% for hidden in entity_form.hidden_fields %}
+{{ hidden }}
+{% endfor %}
+
+{% if entity_form.non_field_errors %}
+<div class="sidebar-form-errors">
+ {% for err in entity_form.non_field_errors %}
+ <p class="sidebar-form-error">ERROR: {{ err }}</p>
+ {% endfor %}
+</div>
+{% endif %}
+
+<div class="sidebar-form-field">
+ <label for="{{ entity_form.name.id_for_label }}" class="sidebar-form-label">{{ entity_form.name.label }}</label>
+ <input type="text" id="{{ entity_form.name.id_for_label }}" name="{{ entity_form.name.name }}" value="{{ entity_form.name.value|default:'' }}" class="sidebar-form-input">
+ {% if entity_form.name.errors %}
+ <div class="sidebar-form-error">{{ entity_form.name.errors }}</div>
+ {% endif %}
+</div>
+
+<div class="sidebar-form-field">
+ <label for="{{ entity_form.entity_type_str.id_for_label }}" class="sidebar-form-label">{{ entity_form.entity_type_str.label }}</label>
+ <select id="{{ entity_form.entity_type_str.id_for_label }}" name="{{ entity_form.entity_type_str.name }}" class="sidebar-form-input">
+ {% for value, label in entity_form.entity_type_str.field.choices %}
+ <option value="{{ value }}"{% if entity_form.entity_type_str.value == value %} selected{% endif %}>{{ label }}</option>
+ {% endfor %}
+ </select>
+ {% if entity_form.entity_type_str.errors %}
+ <div class="sidebar-form-error">{{ entity_form.entity_type_str.errors }}</div>
+ {% endif %}
+</div>
+
+<div class="mt-3">
+ <a class="small" data-toggle="collapse" href="#hi-entity-add-more-options"
+ role="button" aria-expanded="false" aria-controls="hi-entity-add-more-options">
+ More options
+ </a>
+</div>
+<div class="collapse{% if entity_form.quantity.errors %} show{% endif %}" id="hi-entity-add-more-options">
+ <div class="sidebar-form-field mt-2">
+ <label for="{{ entity_form.quantity.id_for_label }}" class="sidebar-form-label">{{ entity_form.quantity.label }}</label>
+ <input type="number" id="{{ entity_form.quantity.id_for_label }}" name="{{ entity_form.quantity.name }}" value="{{ entity_form.quantity.value|default:1 }}" min="{{ entity_form.quantity.field.min_value }}" max="{{ entity_form.quantity.field.max_value }}" step="{{ entity_form.quantity.field.widget.attrs.step|default:1 }}" class="sidebar-form-input">
+ {% if entity_form.quantity.errors %}
+ <div class="sidebar-form-error">{{ entity_form.quantity.errors }}</div>
+ {% endif %}
+ </div>
+</div>
diff --git a/src/hi/apps/entity/templates/entity/edit/panes/entity_form.html b/src/hi/apps/entity/templates/entity/edit/panes/entity_edit_form.html
similarity index 100%
rename from src/hi/apps/entity/templates/entity/edit/panes/entity_form.html
rename to src/hi/apps/entity/templates/entity/edit/panes/entity_edit_form.html
diff --git a/src/hi/apps/entity/templates/entity/edit/panes/entity_properties_edit.html b/src/hi/apps/entity/templates/entity/edit/panes/entity_properties_edit.html
index 8f848270..aeb2a3c2 100644
--- a/src/hi/apps/entity/templates/entity/edit/panes/entity_properties_edit.html
+++ b/src/hi/apps/entity/templates/entity/edit/panes/entity_properties_edit.html
@@ -4,7 +4,7 @@
class="form" data-async="true">
{% csrf_token %}
<div>
- {% include "entity/edit/panes/entity_form.html" %}
+ {% include "entity/edit/panes/entity_edit_form.html" %}
</div>
<div class="text-center" >
diff --git a/src/hi/apps/entity/tests/test_entity_manager.py b/src/hi/apps/entity/tests/test_entity_manager.py
index 98e57298..4b4c6d7f 100644
--- a/src/hi/apps/entity/tests/test_entity_manager.py
+++ b/src/hi/apps/entity/tests/test_entity_manager.py
@@ -441,3 +441,110 @@ class TestEntityManager(BaseTestCase):
self.assertEqual( scale, Decimal( str( location.svg_position_bounds.min_scale ) ) )
return
+ def _create_bulk_position_location_view( self, x, y, width, height ):
+ from hi.apps.common.svg_models import SvgViewBox
+
+ location_view = Mock()
+ location_view.svg_view_box = SvgViewBox(
+ x = x, y = y, width = width, height = height,
+ )
+ return location_view
+
+ def test_bulk_position_single_entity_returns_center(self):
+ """Single entity in a bulk add should be centered in the view."""
+ manager = EntityManager()
+ location_view = self._create_bulk_position_location_view( 0, 0, 1000, 1000 )
+
+ svg_x, svg_y = manager._get_bulk_initial_entity_position(
+ location_view = location_view,
+ bulk_grid_index = 0,
+ bulk_grid_total = 1,
+ )
+ self.assertAlmostEqual( svg_x, 500.0 )
+ self.assertAlmostEqual( svg_y, 500.0 )
+ return
+
+ def test_bulk_position_multiple_entities_distributed_around_center(self):
+ """Multiple entities should be placed symmetrically around the view center."""
+ manager = EntityManager()
+ location_view = self._create_bulk_position_location_view( 0, 0, 1000, 1000 )
+
+ # For 4 entities in a 4-column grid, one row, columns centered at indices
+ # 0..3 with offset from center at (-1.5, -0.5, 0.5, 1.5) * spacing.
+ positions = [
+ manager._get_bulk_initial_entity_position(
+ location_view = location_view,
+ bulk_grid_index = i,
+ bulk_grid_total = 4,
+ )
+ for i in range( 4 )
+ ]
+ x_values = [ p[0] for p in positions ]
+ y_values = [ p[1] for p in positions ]
+
+ # Symmetric around center x=500: first and last should mirror, middle two mirror.
+ self.assertAlmostEqual( x_values[0] + x_values[3], 1000.0 )
+ self.assertAlmostEqual( x_values[1] + x_values[2], 1000.0 )
+ # All in the same row, so y is identical.
+ self.assertEqual( len( set( round( y, 6 ) for y in y_values ) ), 1 )
+ # Single row means y sits at center.
+ self.assertAlmostEqual( y_values[0], 500.0 )
+ return
+
+ def test_bulk_position_viewbox_offset_respects_origin(self):
+ """Grid positioning should be centered on the viewbox center, not origin."""
+ manager = EntityManager()
+ location_view = self._create_bulk_position_location_view( 200, 300, 1000, 1000 )
+
+ svg_x, svg_y = manager._get_bulk_initial_entity_position(
+ location_view = location_view,
+ bulk_grid_index = 0,
+ bulk_grid_total = 1,
+ )
+ # Viewbox center is (200 + 500, 300 + 500) = (700, 800).
+ self.assertAlmostEqual( svg_x, 700.0 )
+ self.assertAlmostEqual( svg_y, 800.0 )
+ return
+
+ def test_bulk_position_grid_wraps_to_multiple_rows(self):
+ """With more entities than columns, indices should wrap into additional rows."""
+ manager = EntityManager()
+ location_view = self._create_bulk_position_location_view( 0, 0, 1000, 1000 )
+
+ # 8 entities with 4-column default = 2 rows. Index 0 is top-left, index 4
+ # is first of second row (same column as index 0).
+ x_0, y_0 = manager._get_bulk_initial_entity_position(
+ location_view = location_view,
+ bulk_grid_index = 0,
+ bulk_grid_total = 8,
+ )
+ x_4, y_4 = manager._get_bulk_initial_entity_position(
+ location_view = location_view,
+ bulk_grid_index = 4,
+ bulk_grid_total = 8,
+ )
+ self.assertAlmostEqual( x_0, x_4 )
+ self.assertLess( y_0, y_4 )
+ return
+
+ def test_bulk_position_clamps_to_viewbox_margin(self):
+ """Grid positions that would exceed viewbox bounds should clamp inside margin."""
+ manager = EntityManager()
+ # Very small viewbox so spacing would push grid cells outside.
+ location_view = self._create_bulk_position_location_view( 0, 0, 100, 100 )
+
+ svg_x, svg_y = manager._get_bulk_initial_entity_position(
+ location_view = location_view,
+ bulk_grid_index = 0,
+ bulk_grid_total = 16,
+ )
+ margin_fraction = manager.DEFAULT_INITIAL_POSITION_VIEWBOX_MARGIN_FRACTION
+ margin_x = 100 * margin_fraction
+ margin_y = 100 * margin_fraction
+
+ self.assertGreaterEqual( svg_x, margin_x )
+ self.assertLessEqual( svg_x, 100 - margin_x )
+ self.assertGreaterEqual( svg_y, margin_y )
+ self.assertLessEqual( svg_y, 100 - margin_y )
+ return
+
diff --git a/src/hi/apps/entity/tests/test_views.py b/src/hi/apps/entity/tests/test_views.py
index d6a7c6a6..f407cd67 100644
--- a/src/hi/apps/entity/tests/test_views.py
+++ b/src/hi/apps/entity/tests/test_views.py
@@ -492,9 +492,28 @@ class TestEntityPropertiesEditView(SyncViewTestCase):
"""Test that GET requests are not allowed (only POST)."""
url = reverse('entity_properties_edit', kwargs={'entity_id': self.entity.id})
response = self.client.get(url)
-
+
self.assertEqual(response.status_code, 405)
+ def test_properties_edit_uses_edit_form_pane_not_add_form_pane(self):
+ """Regression: the properties edit sidebar must include the
+ edit-specific form pane, not the bulk-add form pane. The two used
+ to share a single pane, which caused the add-only 'quantity' field
+ to render in the sidebar and silently ignore its value on save.
+ """
+ url = reverse('entity_properties_edit', kwargs={'entity_id': self.entity.id})
+ form_data = {
+ 'name': self.entity.name,
+ 'entity_type_str': self.entity.entity_type_str,
+ }
+ response = self.client.post(url, form_data)
+
+ self.assertSuccessResponse(response)
+ self.assertTemplateRendered(response, 'entity/edit/panes/entity_properties_edit.html')
+ self.assertTemplateRendered(response, 'entity/edit/panes/entity_edit_form.html')
+ rendered_templates = [t.name for t in response.templates]
+ self.assertNotIn('entity/edit/panes/entity_add_form.html', rendered_templates)
+
class TestEntityAttributeUploadView(SyncViewTestCase):
"""