Home Information - Your home, your data, organized.
Python
Default placement grouping uses EntityGroupType rollup (#368) (#370)
Tony C9199462a3674
diff --git a/src/hi/apps/entity/entity_placement.py b/src/hi/apps/entity/entity_placement.pyindex cb6f828f..bd2555ac 100644--- a/src/hi/apps/entity/entity_placement.py+++ b/src/hi/apps/entity/entity_placement.py@@ -31,12 +31,16 @@ inherits this behavior; revisit when it bites.from dataclasses import dataclass, fieldfrom decimal import Decimalimport logging-from typing import List, Optional, Tuple, Union+from typing import Callable, Dict, List, Optional, Tuple, Unionfrom django.db import transactionfrom hi.apps.entity.edit.forms import EntityPositionForm-from hi.apps.entity.enums import EntityType, EntityTransitionType+from hi.apps.entity.enums import (+ EntityGroupType,+ EntityType,+ EntityTransitionType,+)from hi.apps.location.models import Location, LocationViewfrom hi.apps.location.path_geometry import PathGeometryfrom hi.apps.location.position_geometry import PositionGeometry@@ -53,6 +57,14 @@ from .models import (logger = logging.getLogger(__name__)+# Default heading the placement modal renders above its group list.+# "Type" reads naturally for both leaf EntityType and rollup+# EntityGroupType — they're item types at different resolutions.+# Integrations override on a per-placement-input basis when they+# group by a different dimension (location, tag, etc.).+PLACEMENT_DEFAULT_HEADING = 'Item Type'++@dataclass(frozen=True)class PlacementPoint:"""SVG icon placement: center-of-icon coordinates plus scale."""@@ -111,11 +123,11 @@ class EntityPlacementInput:``heading`` is the column-heading label the modal rendersabove the group list. Suppliers set it to name the groupingdimension (e.g., "HomeBox Location" or "Type"). Defaults to- the generic "Items".+ ``PLACEMENT_DEFAULT_HEADING``."""groups: List[EntityPlacementGroup] = field(default_factory=list)ungrouped_items: List[EntityPlacementItem] = field(default_factory=list)- heading: str = 'Item Type'+ heading: str = PLACEMENT_DEFAULT_HEADINGdef is_empty(self) -> bool:if self.ungrouped_items:@@ -240,6 +252,86 @@ class PlacementOutcome:return result+class PlacementInputBuilder:+ """Reusable bucket-and-group builders for ``EntityPlacementInput``.++ Both the framework default and integration-specific groupers+ (e.g. HomeBox's Location/Tag/Type pipeline) route through here+ so the bucketing semantics — alphabetical group ordering, the+ no-signal handling, the heading wiring — stay in one place.+ """++ @staticmethod+ def by_label_fn(+ entities : List['Entity'],+ item_key_fn : Callable[['Entity'], str],+ label_fn : Callable[['Entity'], Optional[str]],+ heading : str,+ fallback_label : Optional[str] = None,+ ) -> 'EntityPlacementInput':+ """Bucket entities by ``label_fn(entity)``.++ Entities for which ``label_fn`` returns None land in a+ labeled fallback group when ``fallback_label`` is set,+ else in ``ungrouped_items``. Named groups are emitted in+ alphabetical label order; the fallback group is appended+ last when present.+ """+ label_to_items: Dict[str, List[EntityPlacementItem]] = {}+ fallback_items: List[EntityPlacementItem] = []+ ungrouped_items: List[EntityPlacementItem] = []+ for entity in entities:+ item = EntityPlacementItem(+ key = item_key_fn( entity ),+ label = entity.name,+ entity = entity,+ )+ label = label_fn( entity )+ if label is None:+ if fallback_label is not None:+ fallback_items.append( item )+ else:+ ungrouped_items.append( item )+ continue+ label_to_items.setdefault( label, [] ).append( item )++ groups = [+ EntityPlacementGroup( label = label, items = label_to_items[ label ] )+ for label in sorted( label_to_items.keys() )+ ]+ if fallback_items:+ groups.append(+ EntityPlacementGroup(+ label = fallback_label,+ items = fallback_items,+ )+ )+ return EntityPlacementInput(+ groups = groups,+ ungrouped_items = ungrouped_items,+ heading = heading,+ )++ @staticmethod+ def by_entity_type_group(+ entities : List['Entity'],+ item_key_fn : Callable[['Entity'], str],+ heading : str = PLACEMENT_DEFAULT_HEADING,+ ) -> 'EntityPlacementInput':+ """Default placement grouping: bucket entities by their+ ``EntityGroupType`` rollup label. The rollup avoids+ scattering a typical batch across many one- or two-item+ leaf-type buckets."""+ return PlacementInputBuilder.by_label_fn(+ entities = entities,+ item_key_fn = item_key_fn,+ label_fn = lambda e: EntityGroupType.from_entity_type(+ e.entity_type+ ).label,+ heading = heading,+ )++class EntityPlacementService:"""Bulk-placement operations: query candidate entities and applya list of operator placement decisions. Supplier-agnostic; thediff --git a/src/hi/apps/entity/tests/test_entity_placement.py b/src/hi/apps/entity/tests/test_entity_placement.pyindex 0790aae4..5ac5849e 100644--- a/src/hi/apps/entity/tests/test_entity_placement.py+++ b/src/hi/apps/entity/tests/test_entity_placement.py@@ -456,3 +456,85 @@ class EntityPlacementServiceTests(BaseTestCase):self.assertTrue(outcome.primary_summary.is_collection)# Highest-count is Tools (2 entities).self.assertEqual(outcome.primary_summary.collection, tools)+++class TestPlacementInputBuilder(BaseTestCase):+ """The shared bucket-and-group helper used by the framework+ default and any integration-specific grouper. Pins the rollup+ grouping semantics and the no-signal handling."""++ def _entity(self, name, entity_type):+ return Entity.objects.create(+ name=name,+ entity_type_str=str(entity_type),+ )++ def _key(self, entity):+ return f'entity:{entity.id}'++ def test_by_entity_type_group_emits_rollup_labels(self):+ from hi.apps.entity.entity_placement import PlacementInputBuilder+ light = self._entity('Living Room Light', EntityType.LIGHT)+ camera = self._entity('Front Door Camera', EntityType.CAMERA)+ fridge = self._entity('Kitchen Fridge', EntityType.REFRIGERATOR)++ placement_input = PlacementInputBuilder.by_entity_type_group(+ entities=[light, camera, fridge],+ item_key_fn=self._key,+ )++ labels = [g.label for g in placement_input.groups]+ # Alphabetical: Appliances < Automation < Security.+ self.assertEqual(labels, ['Appliances', 'Automation', 'Security'])+ self.assertEqual(placement_input.ungrouped_items, [])++ def test_by_label_fn_routes_none_label_to_fallback_group(self):+ from hi.apps.entity.entity_placement import PlacementInputBuilder+ a = self._entity('Has Tag', EntityType.OTHER)+ b = self._entity('No Tag', EntityType.OTHER)+ placement_input = PlacementInputBuilder.by_label_fn(+ entities=[a, b],+ item_key_fn=self._key,+ label_fn=lambda e: 'tools' if e.name == 'Has Tag' else None,+ heading='Tag',+ fallback_label='Untagged',+ )++ labels = [g.label for g in placement_input.groups]+ self.assertEqual(labels, ['tools', 'Untagged'])+ self.assertEqual(placement_input.ungrouped_items, [])++ def test_by_label_fn_routes_none_to_ungrouped_when_no_fallback(self):+ from hi.apps.entity.entity_placement import PlacementInputBuilder+ a = self._entity('Has Label', EntityType.OTHER)+ b = self._entity('No Label', EntityType.OTHER)+ placement_input = PlacementInputBuilder.by_label_fn(+ entities=[a, b],+ item_key_fn=self._key,+ label_fn=lambda e: 'tools' if e.name == 'Has Label' else None,+ heading='Tag',+ )++ self.assertEqual([g.label for g in placement_input.groups], ['tools'])+ self.assertEqual(len(placement_input.ungrouped_items), 1)+ self.assertEqual(placement_input.ungrouped_items[0].entity, b)++ def test_heading_propagates(self):+ from hi.apps.entity.entity_placement import PlacementInputBuilder+ placement_input = PlacementInputBuilder.by_entity_type_group(+ entities=[self._entity('A', EntityType.LIGHT)],+ item_key_fn=self._key,+ heading='Custom',+ )+ self.assertEqual(placement_input.heading, 'Custom')++ def test_default_heading_is_module_constant(self):+ from hi.apps.entity.entity_placement import (+ PLACEMENT_DEFAULT_HEADING,+ PlacementInputBuilder,+ )+ placement_input = PlacementInputBuilder.by_entity_type_group(+ entities=[self._entity('A', EntityType.LIGHT)],+ item_key_fn=self._key,+ )+ self.assertEqual(placement_input.heading, PLACEMENT_DEFAULT_HEADING)diff --git a/src/hi/integrations/integration_gateway.py b/src/hi/integrations/integration_gateway.pyindex f2507bed..53ef16ab 100644--- a/src/hi/integrations/integration_gateway.py+++ b/src/hi/integrations/integration_gateway.py@@ -1,9 +1,8 @@-from typing import Dict, List, Optional+from typing import List, Optionalfrom hi.apps.entity.entity_placement import (- EntityPlacementGroup,EntityPlacementInput,- EntityPlacementItem,+ PlacementInputBuilder,)from hi.apps.entity.models import Entity@@ -94,27 +93,14 @@ class IntegrationGateway:this same method, so a given integration groups its entitiesthe same way regardless of how they arrived.- Default: group by ``EntityType`` using the humanized type- label as the group name. Sorted alphabetically by label for- stable presentation. Subclasses override when a different- domain grouping makes sense (e.g., ZM/Frigate use a single- static named group for their single-type case)."""- type_label_to_items: Dict[str, List[EntityPlacementItem]] = {}- for entity in entities:- type_label = entity.entity_type.label- type_label_to_items.setdefault( type_label, [] ).append(- EntityPlacementItem(- key = self._placement_item_key( entity = entity ),- label = entity.name,- entity = entity,- )- )- continue- groups = [- EntityPlacementGroup( label = label, items = type_label_to_items[label] )- for label in sorted( type_label_to_items.keys() )- ]- return EntityPlacementInput( groups = groups )+ Default: group by ``EntityGroupType`` rollup using the+ rollup's humanized label as the group name. Subclasses+ override when a different domain grouping makes sense+ (e.g., HomeBox's Location/Tag/Type fallback)."""+ return PlacementInputBuilder.by_entity_type_group(+ entities = entities,+ item_key_fn = self._placement_item_key,+ )def _placement_item_key(self, entity: Entity) -> str:"""Stable per-entity placement key. Prefers the livediff --git a/src/hi/integrations/templates/integrations/modals/placement.html b/src/hi/integrations/templates/integrations/modals/placement.htmlindex 52f500e7..e67066c6 100644--- a/src/hi/integrations/templates/integrations/modals/placement.html+++ b/src/hi/integrations/templates/integrations/modals/placement.html@@ -28,9 +28,12 @@ multi-Location deployments can disambiguate views with shared namesContext:integration_data : IntegrationData (required)- placement_input : EntityPlacementInput (required) — including- ``heading`` (str, defaults to "Items") shown- above the group list when groups exist.+ placement_input : EntityPlacementInput (required)+ grouping_heading : Optional[str] — column-header text shown+ above the group list inside the override+ panel. None when the heading is the+ implicit default ("Item Type"); the+ column header is suppressed in that case.location_view_groups : List[(Location, List[LocationView])] (required)collection_list : List[Collection] (required)top_default_value : str (required) — pre-selected value for@@ -87,7 +90,7 @@ Place new items{% if inventory_preview %}<div class="text-muted small mb-3 hi-placement-preview">- {% for entry in inventory_preview %}{{ entry.count }} {{ entry.label|lower }}{% if not forloop.last %} · {% endif %}{% endfor %}+ {% for entry in inventory_preview %}{{ entry.count }} {{ entry.label }}{% if not forloop.last %} · {% endif %}{% endfor %}</div>{% endif %}@@ -101,77 +104,79 @@ Place new items</div><div class="collapse" id="hi-placement-overrides">- <div class="text-muted small mb-2">- Override the top choice per group, or drill into a group- for per-item placement. Empty selections inherit from the- level above.- </div>+ <div class="hi-placement-overrides-panel">+ <div class="text-muted small mb-3">+ Override the top choice per group, or drill into a group+ for per-item placement. Empty selections inherit from the+ level above.+ </div>- {% if placement_input.groups %}- <div class="text-muted text-uppercase small mb-1 hi-placement-heading">- {{ placement_input.heading }}- </div>- {% endif %}-- {% for group in placement_input.groups %}- {% with forloop.counter0 as group_index %}- <div class="hi-placement-group border-bottom py-2">- <div class="d-flex align-items-center">- <div class="flex-grow-1">- <strong>{{ group.label }}</strong>- <span class="badge badge-light ml-1">{{ group.items|length }}</span>- </div>- <select name="group_view_{{ group_index }}" class="form-control form-control-sm w-auto">- <option value="">Use top choice</option>- <option value="__skip__">Don't place</option>- {% include "integrations/panes/placement_target_options.html" %}- </select>- <a class="btn btn-sm btn-link" data-toggle="collapse"- href="#hi-drill-{{ group_index }}" role="button"- aria-expanded="false" aria-controls="hi-drill-{{ group_index }}">- Per item ▸- </a>+ {% if grouping_heading and placement_input.groups %}+ <div class="hi-placement-column-header text-muted text-uppercase small">+ {{ grouping_heading }}</div>- <div class="collapse mt-2 pl-3" id="hi-drill-{{ group_index }}">- {% for item in group.items %}- <div class="d-flex align-items-center py-1">- <div class="flex-grow-1 small">{{ item.label }}</div>- <select name="group_{{ group_index }}_entity_{{ item.entity.id }}_view"- class="form-control form-control-sm w-auto">- <option value="">Use group choice</option>+ {% endif %}++ {% for group in placement_input.groups %}+ {% with forloop.counter0 as group_index %}+ <div class="hi-placement-group py-3">+ <div class="d-flex align-items-center">+ <div class="flex-grow-1">+ <strong>{{ group.label }}</strong>+ <span class="text-muted small ml-2">({{ group.items|length }})</span>+ </div>+ <select name="group_view_{{ group_index }}" class="form-control form-control-sm w-auto">+ <option value="">Use top choice</option><option value="__skip__">Don't place</option>{% include "integrations/panes/placement_target_options.html" %}</select>+ <a class="btn btn-sm btn-link" data-toggle="collapse"+ href="#hi-drill-{{ group_index }}" role="button"+ aria-expanded="false" aria-controls="hi-drill-{{ group_index }}">+ Per item ▸+ </a></div>- {% endfor %}- </div>- </div>- {% endwith %}- {% endfor %}-- {% if placement_input.ungrouped_items %}- <div class="hi-placement-ungrouped py-2">- <div class="d-flex align-items-center mb-1">- <div class="flex-grow-1">- <strong>Other items</strong>- <span class="badge badge-light ml-1">{{ placement_input.ungrouped_items|length }}</span>+ <div class="collapse mt-2 hi-placement-drill" id="hi-drill-{{ group_index }}">+ {% for item in group.items %}+ <div class="d-flex align-items-center py-2">+ <div class="flex-grow-1 small text-muted">{{ item.label }}</div>+ <select name="group_{{ group_index }}_entity_{{ item.entity.id }}_view"+ class="form-control form-control-sm w-auto">+ <option value="">Use group choice</option>+ <option value="__skip__">Don't place</option>+ {% include "integrations/panes/placement_target_options.html" %}+ </select>+ </div>+ {% endfor %}</div></div>- <div class="pl-3">- {% for item in placement_input.ungrouped_items %}- <div class="d-flex align-items-center py-1">- <div class="flex-grow-1 small">{{ item.label }}</div>- <select name="ungrouped_entity_{{ item.entity.id }}_view"- class="form-control form-control-sm w-auto">- <option value="">Use top choice</option>- <option value="__skip__">Don't place</option>- {% include "integrations/panes/placement_target_options.html" %}- </select>+ {% endwith %}+ {% endfor %}++ {% if placement_input.ungrouped_items %}+ <div class="hi-placement-group hi-placement-ungrouped py-3">+ <div class="d-flex align-items-center mb-1">+ <div class="flex-grow-1">+ <strong>Other items</strong>+ <span class="text-muted small ml-2">({{ placement_input.ungrouped_items|length }})</span>+ </div>+ </div>+ <div class="hi-placement-drill">+ {% for item in placement_input.ungrouped_items %}+ <div class="d-flex align-items-center py-2">+ <div class="flex-grow-1 small text-muted">{{ item.label }}</div>+ <select name="ungrouped_entity_{{ item.entity.id }}_view"+ class="form-control form-control-sm w-auto">+ <option value="">Use top choice</option>+ <option value="__skip__">Don't place</option>+ {% include "integrations/panes/placement_target_options.html" %}+ </select>+ </div>+ {% endfor %}</div>- {% endfor %}</div>+ {% endif %}</div>- {% endif %}</div>{% endif %}diff --git a/src/hi/integrations/tests/test_placement_stats.py b/src/hi/integrations/tests/test_placement_stats.pyindex dcd8308b..3d3f0136 100644--- a/src/hi/integrations/tests/test_placement_stats.py+++ b/src/hi/integrations/tests/test_placement_stats.py@@ -11,6 +11,7 @@ import loggingfrom django.test import TestCasefrom hi.apps.entity.entity_placement import (+ PLACEMENT_DEFAULT_HEADING,EntityPlacementGroup,EntityPlacementInput,EntityPlacementItem,@@ -134,8 +135,12 @@ class TestEntityPlacementInputHeading(TestCase):input itself so the modal can render it without the supplierthreading it through a parallel channel."""- def test_default_heading_is_item_type(self):- self.assertEqual(EntityPlacementInput().heading, 'Item Type')+ def test_default_heading_matches_module_constant(self):+ self.assertEqual(+ EntityPlacementInput().heading,+ PLACEMENT_DEFAULT_HEADING,+ )+ self.assertEqual(PLACEMENT_DEFAULT_HEADING, 'Item Type')def test_supplier_can_set_dimension_specific_heading(self):placement_input = EntityPlacementInput(heading='HomeBox Location')diff --git a/src/hi/integrations/tests/test_views.py b/src/hi/integrations/tests/test_views.pyindex f83f1339..6ed0f873 100644--- a/src/hi/integrations/tests/test_views.py+++ b/src/hi/integrations/tests/test_views.py@@ -1173,9 +1173,9 @@ class PlacementDismissAndShowTests(SyncViewTestCase):self.assertSuccessResponse(response)body = response.content.decode()# The PlacementGetFlow fixture builds a single 'Cameras'- # group with 2 items; the preview line lower-cases the- # label and shows the count.- self.assertIn('2 cameras', body)+ # group with 2 items; the preview line shows the count+ # with the group label rendered verbatim.+ self.assertIn('2 Cameras', body)# Group rows are behind the disclosure (collapsed by# default) — the disclosure affordance is rendered.self.assertIn('Place differently', body)diff --git a/src/hi/integrations/view_mixins.py b/src/hi/integrations/view_mixins.pyindex bfeebbda..c11d51b3 100644--- a/src/hi/integrations/view_mixins.py+++ b/src/hi/integrations/view_mixins.py@@ -7,6 +7,7 @@ from django.urls import reversefrom hi.apps.collection.collection_manager import CollectionManagerfrom hi.apps.collection.models import Collection, CollectionEntity+from hi.apps.entity.entity_placement import PLACEMENT_DEFAULT_HEADINGfrom hi.apps.entity.models import Entity, EntityViewfrom hi.apps.location.location_manager import LocationManagerfrom hi.apps.location.models import Location, LocationView@@ -218,6 +219,15 @@ class IntegrationPlacementViewMixin:inventory_preview = self._build_inventory_preview(placement_input = placement_input,)+ # Suppress the column-header heading when the grouping+ # dimension is the implicit default ("Item Type") — it+ # adds no information. The heading still renders when an+ # integration override conveys context (e.g. "HomeBox Location").+ grouping_heading = (+ placement_input.heading+ if placement_input.heading != PLACEMENT_DEFAULT_HEADING+ else None+ )# The form posts back to the same URL that rendered the# modal — single CBV, GET renders / POST processes.placement_url = reverse(@@ -237,6 +247,7 @@ class IntegrationPlacementViewMixin:'new_view_name': new_view_name,'new_collection_name': new_collection_name,'inventory_preview': inventory_preview,+ 'grouping_heading': grouping_heading,'placement_url': placement_url,'is_initial_connect': is_initial_connect,},diff --git a/src/hi/services/hass/tests/test_hass_connector.py b/src/hi/services/hass/tests/test_hass_connector.pyindex 37bb24e0..e6ea9b27 100644--- a/src/hi/services/hass/tests/test_hass_connector.py+++ b/src/hi/services/hass/tests/test_hass_connector.py@@ -299,8 +299,8 @@ class TestHassConnectorMixinIntegration(TestCase):class TestHassConnectorSyncResultGrouping(TestCase):- """Default-grouping behavior: entities are grouped by EntityType- using the humanized type label. Exercised here against+ """Default-grouping behavior: entities are grouped by their+ ``EntityGroupType`` rollup label. Exercised here againstHassGateway (which uses the framework default) — the samebehavior applies to any integration that doesn't overridegroup_entities_for_placement."""@@ -317,8 +317,9 @@ class TestHassConnectorSyncResultGrouping(TestCase):)return entity- def test_groups_built_by_entity_type_alphabetical(self):- """Group ordering is alphabetical by humanized type label."""+ def test_groups_built_by_entity_group_alphabetical(self):+ """Group ordering is alphabetical by rollup label. LIGHT+ rolls up to AUTOMATION; MOTION_SENSOR to SECURITY."""from hi.apps.entity.enums import EntityTypeentities = [self._entity('Kitchen Light', EntityType.LIGHT, 'light.kitchen'),@@ -330,7 +331,7 @@ class TestHassConnectorSyncResultGrouping(TestCase):self.assertEqual(placement_input.ungrouped_items, [])self.assertEqual([group.label for group in placement_input.groups],- ['Light', 'Motion Sensor'],+ ['Automation', 'Security'],)self.assertEqual([item.label for item in placement_input.groups[0].items],@@ -341,9 +342,9 @@ class TestHassConnectorSyncResultGrouping(TestCase):['Hall Sensor'],)- def test_falls_back_to_other_when_entity_type_unknown(self):- """Entities with an unrecognized entity_type_str fall into- the 'Other' bucket (EntityType.default())."""+ def test_unrecognized_type_falls_back_to_general(self):+ """Entities with an unrecognized entity_type_str resolve to+ EntityType.OTHER, which rolls up to EntityGroupType.GENERAL."""entity = Entity.objects.create(name='Mystery',entity_type_str='UNRECOGNIZED_FUTURE_TYPE',@@ -354,7 +355,7 @@ class TestHassConnectorSyncResultGrouping(TestCase):self.assertEqual(placement_input.ungrouped_items, [])self.assertEqual(len(placement_input.groups), 1)- self.assertEqual(placement_input.groups[0].label, 'Other')+ self.assertEqual(placement_input.groups[0].label, 'General')self.assertEqual(placement_input.groups[0].items[0].entity, entity)def test_empty_input_yields_empty_groups(self):diff --git a/src/hi/services/homebox/hb_placement_grouper.py b/src/hi/services/homebox/hb_placement_grouper.pyindex f73987e1..1282107b 100644--- a/src/hi/services/homebox/hb_placement_grouper.py+++ b/src/hi/services/homebox/hb_placement_grouper.py@@ -11,23 +11,26 @@ with an ordered viability fallback:1. Group by ``integration_payload['location']``.2. Group by each item's globally-most-popular tag.-3. Fall back to the framework's by-EntityType default.+3. Fall back to the framework's by-EntityGroupType default.Viability for #1 and #2 comes from``hi.integrations.placement_stats.compute_grouping_stats``. TheEntityType fallback is used unconditionally so a tiny or uniformbatch still gets a sensible heading rather than collapsing toungrouped.++The bucketing machinery lives in+``hi.apps.entity.entity_placement.PlacementInputBuilder``; this+module just picks dimensions and labels."""from collections import Counterimport logging-from typing import Callable, Dict, List, Optional+from typing import Callable, Dict, Listfrom hi.apps.entity.entity_placement import (- EntityPlacementGroup,EntityPlacementInput,- EntityPlacementItem,+ PlacementInputBuilder,)from hi.apps.entity.models import Entity@@ -41,21 +44,12 @@ LOCATION_HEADING = 'HomeBox Location'LOCATION_FALLBACK_LABEL = 'Other'TAG_HEADING = 'HomeBox Tag'TAG_FALLBACK_LABEL = 'Untagged'-TYPE_HEADING = 'Item Type'---LabelFn = Callable[[Entity], Optional[str]]class HbPlacementGrouper:- """Builds an ``EntityPlacementInput`` for a HomeBox import batch.-- Self-contained — does not delegate to the gateway base class.- The by-EntityType final fallback is implemented inline against- the same internal bucketing helper used by the Location and- Tag passes, so HomeBox's grouping policy stays stable even if- the framework default changes.- """+ """Builds an ``EntityPlacementInput`` for a HomeBox import batch+ via ordered viability fallback across Location, Tag, and the+ framework default by-EntityGroupType pass."""def __init__(self,@@ -68,8 +62,8 @@ class HbPlacementGrouper:self, entities: List[Entity],) -> EntityPlacementInput:"""Ordered-fallback grouping: Location → primary Tag →- EntityType. First viable wins; EntityType is used- unconditionally as the final fallback."""+ EntityGroupType. First viable wins; the by-group default is+ used unconditionally as the final fallback."""if not entities:return EntityPlacementInput()@@ -81,13 +75,17 @@ class HbPlacementGrouper:if compute_grouping_stats( by_tag ).is_viable():return by_tag- return self._group_by_entity_type( entities = entities )+ return PlacementInputBuilder.by_entity_type_group(+ entities = entities,+ item_key_fn = self._placement_item_key_fn,+ )def _group_by_location(self, entities: List[Entity],) -> EntityPlacementInput:- return self._build_grouped_input(+ return PlacementInputBuilder.by_label_fn(entities = entities,+ item_key_fn = self._placement_item_key_fn,label_fn = lambda e: (e.integration_payload or {}).get( 'location' ),heading = LOCATION_HEADING,fallback_label = LOCATION_FALLBACK_LABEL,@@ -99,26 +97,14 @@ class HbPlacementGrouper:primary_tag_lookup = self._compute_primary_tag_lookup(entities = entities,)- return self._build_grouped_input(+ return PlacementInputBuilder.by_label_fn(entities = entities,+ item_key_fn = self._placement_item_key_fn,label_fn = lambda e: primary_tag_lookup.get( e.id ),heading = TAG_HEADING,fallback_label = TAG_FALLBACK_LABEL,)- def _group_by_entity_type(- self, entities: List[Entity],- ) -> EntityPlacementInput:- # ``entity_type.label`` is never None, so the fallback- # group never materializes; the empty label is a never-- # used sentinel rather than a meaningful UI string.- return self._build_grouped_input(- entities = entities,- label_fn = lambda e: e.entity_type.label,- heading = TYPE_HEADING,- fallback_label = '',- )-@staticmethoddef _compute_primary_tag_lookup(entities: List[Entity],@@ -151,40 +137,3 @@ class HbPlacementGrouper:key = lambda tag: ( global_counts[ tag ], tag ),)return primary_tag_by_entity-- def _build_grouped_input(- self,- entities : List[Entity],- label_fn : LabelFn,- heading : str,- fallback_label : str,- ) -> EntityPlacementInput:- """Bucket items by ``label_fn``; items with a None label- land in a labeled fallback group appended last. Named- groups are sorted alphabetically for stable presentation."""- label_to_items: Dict[str, List[EntityPlacementItem]] = {}- fallback_items: List[EntityPlacementItem] = []- for entity in entities:- item = EntityPlacementItem(- key = self._placement_item_key_fn( entity ),- label = entity.name,- entity = entity,- )- label = label_fn( entity )- if label is None:- fallback_items.append( item )- continue- label_to_items.setdefault( label, [] ).append( item )-- groups = [- EntityPlacementGroup( label = label, items = label_to_items[ label ] )- for label in sorted( label_to_items.keys() )- ]- if fallback_items:- groups.append(- EntityPlacementGroup(- label = fallback_label,- items = fallback_items,- )- )- return EntityPlacementInput( groups = groups, heading = heading )diff --git a/src/hi/services/homebox/tests/test_hb_placement_grouper.py b/src/hi/services/homebox/tests/test_hb_placement_grouper.pyindex b781c79a..051d226a 100644--- a/src/hi/services/homebox/tests/test_hb_placement_grouper.py+++ b/src/hi/services/homebox/tests/test_hb_placement_grouper.py@@ -15,6 +15,7 @@ from django.test import TestCasefrom hi.apps.entity.enums import EntityTypefrom hi.apps.entity.models import Entity+from hi.apps.entity.entity_placement import PLACEMENT_DEFAULT_HEADINGfrom hi.services.homebox.hb_metadata import HbMetaDatafrom hi.services.homebox.hb_placement_grouper import (HbPlacementGrouper,@@ -22,7 +23,6 @@ from hi.services.homebox.hb_placement_grouper import (LOCATION_HEADING,TAG_FALLBACK_LABEL,TAG_HEADING,- TYPE_HEADING,)from hi.services.homebox.integration import HomeBoxGateway@@ -200,7 +200,10 @@ class TestHbPlacementGrouperTypeFallback(TestCase):def test_falls_through_to_type_when_neither_dimension_viable(self):# Two items each, location/tags blank — too small and- # too uniform for Location or Tag to be viable.+ # too uniform for Location or Tag to be viable. The final+ # fallback uses the framework default (EntityGroupType rollup),+ # so LIGHT lands in AUTOMATION and CAMERA in SECURITY.+ from hi.apps.entity.enums import EntityGroupTypeentities = [_create_entity('A', EntityType.LIGHT, {'location': None, 'tags': []}),_create_entity('B', EntityType.LIGHT, {'location': None, 'tags': []}),@@ -212,10 +215,10 @@ class TestHbPlacementGrouperTypeFallback(TestCase):result = _grouper().group_entities(entities=entities)- self.assertEqual(result.heading, TYPE_HEADING)+ self.assertEqual(result.heading, PLACEMENT_DEFAULT_HEADING)labels = {group.label for group in result.groups}- self.assertIn(EntityType.LIGHT.label, labels)- self.assertIn(EntityType.CAMERA.label, labels)+ self.assertIn(EntityGroupType.AUTOMATION.label, labels)+ self.assertIn(EntityGroupType.SECURITY.label, labels)class TestHomeBoxGatewayGroupingIntegration(TestCase):diff --git a/src/hi/static/css/main.css b/src/hi/static/css/main.cssindex d8243a8d..48c86b03 100644--- a/src/hi/static/css/main.css+++ b/src/hi/static/css/main.css@@ -2334,3 +2334,35 @@ g[hover] {.event-edit-add {margin: 0.5rem 0;}++/* Placement modal — post-sync "Place new items" dispatcher. */++.hi-placement-overrides-panel {+ background-color: #f8f9fa;+ border: 1px solid #e9ecef;+ border-radius: 4px;+ padding: 1rem;+}++.hi-placement-column-header {+ border-bottom: 1px solid #dee2e6;+ padding-bottom: 0.25rem;+ margin-bottom: 0.25rem;+ letter-spacing: 0.05em;+}++.hi-placement-group {+ border-bottom: 1px solid #e9ecef;+}++.hi-placement-group:last-child {+ border-bottom: none;+}++/* Per-item drill-down inside a group: left rule + indent so the+ item rows read as children of the group above them. */+.hi-placement-drill {+ border-left: 2px solid #ced4da;+ margin-left: 0.5rem;+ padding-left: 0.75rem;+}