Home Information - Your home, your data, organized.
Python
HomeBox placement grouping: Location / Tag / EntityType ordered fallback (#364) (#366)
Tony C40a05fa19ed4
diff --git a/src/hi/apps/entity/entity_placement.py b/src/hi/apps/entity/entity_placement.pyindex 656fc4c3..cb6f828f 100644--- a/src/hi/apps/entity/entity_placement.py+++ b/src/hi/apps/entity/entity_placement.py@@ -107,9 +107,15 @@ class EntityPlacementInput:placement flow. The placement layer does not know what producedits input; suppliers do not know how the dispatcher renders orapplies the result.++ ``heading`` is the column-heading label the modal renders+ above the group list. Suppliers set it to name the grouping+ dimension (e.g., "HomeBox Location" or "Type"). Defaults to+ the generic "Items"."""groups: List[EntityPlacementGroup] = field(default_factory=list)ungrouped_items: List[EntityPlacementItem] = field(default_factory=list)+ heading: str = 'Item Type'def is_empty(self) -> bool:if self.ungrouped_items:diff --git a/src/hi/integrations/placement_stats.py b/src/hi/integrations/placement_stats.pynew file mode 100644index 00000000..2147cc7e--- /dev/null+++ b/src/hi/integrations/placement_stats.py@@ -0,0 +1,129 @@+"""+Statistics + viability scoring over an ``EntityPlacementInput``.++Integrations that have multiple plausible grouping dimensions+(HomeBox: Location, Tag, EntityType) need a way to ask "is this+candidate grouping actually useful, or is it one giant bucket / one+item per bucket?". This module supplies the measurement; the+selection logic stays in the integration so it can compose strategies+however it likes (ordered fallback, score-based, hand-rolled).++Typical use from an integration's ``group_entities_for_placement``::++ candidate = self._group_by_location( entities )+ if compute_grouping_stats( candidate ).is_viable():+ return candidate+ candidate = self._group_by_tag( entities )+ if compute_grouping_stats( candidate ).is_viable():+ return candidate+ return super().group_entities_for_placement( entities )++The integration owns what counts as "in a group": items placed in+``EntityPlacementInput.ungrouped_items`` are treated as+no-signal; items in a labeled fallback group (e.g., "Untagged") are+treated as a normal group because that's how the placement modal+renders them.+"""++from dataclasses import dataclass+import logging+from typing import List++from hi.apps.entity.entity_placement import EntityPlacementInput+++logger = logging.getLogger(__name__)+++# Default viability thresholds. Tuned for the tens-of-items import+# batches the placement modal sees today. Exposed as constants so+# callers can read them and override individual ones per-call.+DEFAULT_MIN_COVERAGE : float = 0.5 # at least half the items must land in a named group+DEFAULT_MIN_GROUP_COUNT : int = 2 # at least two distinct groups+DEFAULT_MAX_GROUP_COUNT : int = 15 # too many groups overwhelms the modal+DEFAULT_MIN_AVG_GROUP_SIZE: float = 2.0 # avoid one-item-per-group sprawl+DEFAULT_MAX_CONCENTRATION : float = 0.9 # a single group holding >90% isn't grouping+++@dataclass(frozen=True)+class PlacementGroupingStats:+ """Single-pass measurements over an ``EntityPlacementInput``.++ "Grouped items" are items in any named group, including a+ fallback group like "Untagged". "Ungrouped items" are items+ in ``EntityPlacementInput.ungrouped_items`` — the items the+ modal renders under its built-in 'Other items' section, which+ by convention means the integration found no signal for them.+ """+ total_items : int+ grouped_items : int+ group_count : int+ largest_group_size : int+ group_sizes : List[int]++ @property+ def coverage(self) -> float:+ """Fraction of total items that landed in a named group."""+ if self.total_items == 0:+ return 0.0+ return self.grouped_items / self.total_items++ @property+ def concentration(self) -> float:+ """Largest group size as a fraction of grouped items. Close+ to 1.0 means one dominant group — the strategy isn't really+ partitioning."""+ if self.grouped_items == 0:+ return 0.0+ return self.largest_group_size / self.grouped_items++ @property+ def avg_group_size(self) -> float:+ if self.group_count == 0:+ return 0.0+ return self.grouped_items / self.group_count++ def is_viable(+ self,+ *,+ min_coverage : float = DEFAULT_MIN_COVERAGE,+ min_group_count : int = DEFAULT_MIN_GROUP_COUNT,+ max_group_count : int = DEFAULT_MAX_GROUP_COUNT,+ min_avg_group_size : float = DEFAULT_MIN_AVG_GROUP_SIZE,+ max_concentration : float = DEFAULT_MAX_CONCENTRATION,+ ) -> bool:+ """Apply viability thresholds. ``max_group_count`` is+ additionally clamped to ``total_items // 2`` so a 6-item+ batch can't show 6 one-item groups even if the configured+ ceiling permits it."""+ if self.total_items == 0:+ return False+ effective_max_groups = min( max_group_count, self.total_items // 2 )+ return (+ self.coverage >= min_coverage+ and self.group_count >= min_group_count+ and self.group_count <= effective_max_groups+ and self.avg_group_size >= min_avg_group_size+ and self.concentration <= max_concentration+ )+++def compute_grouping_stats(+ placement_input : EntityPlacementInput,+) -> PlacementGroupingStats:+ """Single-pass measurement over a candidate ``EntityPlacementInput``.++ The caller has already built the candidate (one+ ``EntityPlacementInput`` per dimension it's considering); this+ function tells them how useful that partitioning is.+ """+ group_sizes = [ len( group.items ) for group in placement_input.groups ]+ grouped_items = sum( group_sizes )+ ungrouped = len( placement_input.ungrouped_items )+ return PlacementGroupingStats(+ total_items = grouped_items + ungrouped,+ grouped_items = grouped_items,+ group_count = len( group_sizes ),+ largest_group_size = max( group_sizes ) if group_sizes else 0,+ group_sizes = group_sizes,+ )diff --git a/src/hi/integrations/templates/integrations/modals/placement.html b/src/hi/integrations/templates/integrations/modals/placement.htmlindex 464e7bef..52f500e7 100644--- a/src/hi/integrations/templates/integrations/modals/placement.html+++ b/src/hi/integrations/templates/integrations/modals/placement.html@@ -28,7 +28,9 @@ multi-Location deployments can disambiguate views with shared namesContext:integration_data : IntegrationData (required)- placement_input : EntityPlacementInput (required)+ placement_input : EntityPlacementInput (required) — including+ ``heading`` (str, defaults to "Items") shown+ above the group list when groups exist.location_view_groups : List[(Location, List[LocationView])] (required)collection_list : List[Collection] (required)top_default_value : str (required) — pre-selected value for@@ -105,6 +107,12 @@ Place new itemslevel 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">diff --git a/src/hi/integrations/tests/test_placement_stats.py b/src/hi/integrations/tests/test_placement_stats.pynew file mode 100644index 00000000..dcd8308b--- /dev/null+++ b/src/hi/integrations/tests/test_placement_stats.py@@ -0,0 +1,142 @@+"""+Coverage for the placement-stats viability helper.++These tests pin the measurement contract integrations rely on when+picking among candidate ``EntityPlacementInput`` partitionings.+Threshold defaults are tested at the boundaries so a future+adjustment that drifts them silently fails loudly.+"""+import logging++from django.test import TestCase++from hi.apps.entity.entity_placement import (+ EntityPlacementGroup,+ EntityPlacementInput,+ EntityPlacementItem,+)+from hi.integrations.placement_stats import (+ compute_grouping_stats,+)+++logging.disable(logging.CRITICAL)+++def _item(key: str) -> EntityPlacementItem:+ """Build a stub item. The stats helper never touches ``entity``,+ so a sentinel is fine."""+ return EntityPlacementItem(key=key, label=key, entity=None)+++def _input(group_sizes, ungrouped=0) -> EntityPlacementInput:+ """Build an EntityPlacementInput with named groups of the+ requested sizes plus ``ungrouped`` ungrouped items. Keys are+ globally unique so the modal-key invariant holds."""+ groups = []+ counter = 0+ for index, size in enumerate(group_sizes):+ items = []+ for _ in range(size):+ items.append(_item(f'k{counter}'))+ counter += 1+ groups.append(EntityPlacementGroup(label=f'g{index}', items=items))+ ungrouped_items = []+ for _ in range(ungrouped):+ ungrouped_items.append(_item(f'k{counter}'))+ counter += 1+ return EntityPlacementInput(groups=groups, ungrouped_items=ungrouped_items)+++class TestComputeGroupingStats(TestCase):++ def test_empty_input_yields_zero_stats(self):+ stats = compute_grouping_stats(EntityPlacementInput())+ self.assertEqual(stats.total_items, 0)+ self.assertEqual(stats.grouped_items, 0)+ self.assertEqual(stats.group_count, 0)+ self.assertEqual(stats.largest_group_size, 0)+ self.assertEqual(stats.coverage, 0.0)+ self.assertEqual(stats.concentration, 0.0)+ self.assertEqual(stats.avg_group_size, 0.0)++ def test_all_grouped_counts_total_and_largest(self):+ stats = compute_grouping_stats(_input([3, 2, 5]))+ self.assertEqual(stats.total_items, 10)+ self.assertEqual(stats.grouped_items, 10)+ self.assertEqual(stats.group_count, 3)+ self.assertEqual(stats.largest_group_size, 5)+ self.assertEqual(stats.coverage, 1.0)+ self.assertAlmostEqual(stats.concentration, 0.5)+ self.assertAlmostEqual(stats.avg_group_size, 10 / 3)++ def test_ungrouped_items_dilute_coverage(self):+ stats = compute_grouping_stats(_input([2, 2], ungrouped=6))+ self.assertEqual(stats.total_items, 10)+ self.assertEqual(stats.grouped_items, 4)+ self.assertEqual(stats.coverage, 0.4)+ self.assertEqual(stats.avg_group_size, 2.0)+++class TestPlacementGroupingStatsIsViable(TestCase):+ """Pin the default-threshold viability decision at boundaries."""++ def test_empty_never_viable(self):+ self.assertFalse(compute_grouping_stats(EntityPlacementInput()).is_viable())++ def test_balanced_multi_group_is_viable(self):+ # 12 items across 4 groups of 3 — coverage 1.0, concentration 0.25,+ # avg 3.0, group_count 4: comfortably viable on every axis.+ self.assertTrue(compute_grouping_stats(_input([3, 3, 3, 3])).is_viable())++ def test_below_coverage_threshold_not_viable(self):+ # 10 items, 4 grouped → coverage 0.4 (< 0.5 default).+ self.assertFalse(compute_grouping_stats(_input([2, 2], ungrouped=6)).is_viable())++ def test_single_group_not_viable(self):+ # group_count 1 falls below min_group_count default of 2.+ self.assertFalse(compute_grouping_stats(_input([10])).is_viable())++ def test_high_concentration_not_viable(self):+ # 12 items: 11 in one group, 1 in another. concentration ≈ 0.92,+ # over the 0.9 default ceiling.+ self.assertFalse(compute_grouping_stats(_input([11, 1])).is_viable())++ def test_one_item_per_group_sprawl_not_viable(self):+ # 10 items each in its own group: avg_group_size 1.0 (< 2.0),+ # AND effective_max_groups clamped to total_items // 2 = 5,+ # so 10 groups is over the ceiling. Either gate disqualifies.+ self.assertFalse(compute_grouping_stats(_input([1] * 10)).is_viable())++ def test_small_batch_clamps_max_group_count(self):+ # Six items in three groups of two: avg 2.0 (at floor), but+ # effective_max_groups = 6 // 2 = 3 — still within bounds.+ self.assertTrue(compute_grouping_stats(_input([2, 2, 2])).is_viable())++ def test_small_batch_above_clamp_not_viable(self):+ # Six items in four groups: effective_max_groups = 6 // 2 = 3,+ # so 4 distinct groups disqualifies even though the avg+ # (1.5) is the bigger fail on its own.+ self.assertFalse(compute_grouping_stats(_input([2, 2, 1, 1])).is_viable())++ def test_custom_thresholds_override_defaults(self):+ # Same shape as test_below_coverage_threshold_not_viable, but+ # lowering ``min_coverage`` to 0.4 lets it through. The+ # avg_group_size (2.0) and group_count (2) need to stay+ # within their defaults too; this batch sits exactly at the+ # avg floor and effective_max_groups (10 // 2 = 5).+ stats = compute_grouping_stats(_input([2, 2], ungrouped=6))+ self.assertTrue(stats.is_viable(min_coverage=0.4))+++class TestEntityPlacementInputHeading(TestCase):+ """The grouping dimension's heading rides on the placement+ input itself so the modal can render it without the supplier+ threading it through a parallel channel."""++ def test_default_heading_is_item_type(self):+ self.assertEqual(EntityPlacementInput().heading, 'Item Type')++ def test_supplier_can_set_dimension_specific_heading(self):+ placement_input = EntityPlacementInput(heading='HomeBox Location')+ self.assertEqual(placement_input.heading, 'HomeBox Location')diff --git a/src/hi/services/homebox/connector/homebox_connector.py b/src/hi/services/homebox/connector/homebox_connector.pyindex 5ff1df6e..8b8ef7c8 100644--- a/src/hi/services/homebox/connector/homebox_connector.py+++ b/src/hi/services/homebox/connector/homebox_connector.py@@ -139,15 +139,6 @@ class HomeBoxConnector( IntegrationConnector, HomeBoxMixin ):result.created_entities = created_entitiesreturn result- # group_entities_for_placement: no override. HomeBox inherits- # the gateway base default (group by EntityType). Today- # ``HbConverter.hb_item_to_entity_type`` stamps every imported- # item as ``EntityType.OTHER``, so the result is a single- # ``Other`` group — functionally equivalent to ungrouped, just- # with an extra label level. A future HomeBox-specific override- # (e.g. by upstream Location, read from ``integration_payload``)- # will replace this default.-def _sync_helper_entities( self,item_list: List[HbItem],result: IntegrationSyncResult ) -> List[Entity]:diff --git a/src/hi/services/homebox/hb_converter.py b/src/hi/services/homebox/hb_converter.pyindex 23b1a2dc..429ad367 100644--- a/src/hi/services/homebox/hb_converter.py+++ b/src/hi/services/homebox/hb_converter.py@@ -260,37 +260,34 @@ class HbConverter:'notes': hb_item.notes,}+ # Location is persisted as a flat string (the location name).+ # No consumer currently needs the full HB location dict; if a+ # future need arises, prefer reading from the live HB API+ # response rather than expanding the payload. If the HomeBox+ # API ever exposes a hierarchy field (treePath / parentId),+ # this is the right place to extract the top-level segment so+ # downstream consumers see consistently-flattened grouping+ # keys.location = hb_item.locationif location is None:logger.warning( f'HomeBox item {hb_item.id} missing location dict' )payload['location'] = Noneelse:- payload['location'] = {- 'id': location.get( 'id' ),- 'name': location.get( 'name' ),- 'description': location.get( 'description' ),- 'createdAt': location.get( 'createdAt' ),- 'updatedAt': location.get( 'updatedAt' ),- }+ payload['location'] = location.get( 'name' )+ # Tags persisted as a flat list of names. No consumer needs+ # the rich tag dicts (color, timestamps, etc.); the live HB+ # API response is the source of truth for those details.tags = hb_item.tagsif tags is None:logger.warning( f'HomeBox item {hb_item.id} missing tags list' )payload['tags'] = []else:- normalized_tags: List[Dict] = []- for tag in tags:- if not isinstance( tag, dict ):- continue- normalized_tags.append({- 'id': tag.get( 'id' ),- 'name': tag.get( 'name' ),- 'description': tag.get( 'description' ),- 'color': tag.get( 'color' ),- 'created_at': tag.get( 'createdAt' ),- 'updated_at': tag.get( 'updatedAt' ),- })- payload['tags'] = normalized_tags+ payload['tags'] = [+ tag.get( 'name' )+ for tag in tags+ if isinstance( tag, dict ) and tag.get( 'name' )+ ]return payloaddiff --git a/src/hi/services/homebox/hb_placement_grouper.py b/src/hi/services/homebox/hb_placement_grouper.pynew file mode 100644index 00000000..f73987e1--- /dev/null+++ b/src/hi/services/homebox/hb_placement_grouper.py@@ -0,0 +1,190 @@+"""+HomeBox-specific placement grouping for the integration placement modal.++HomeBox items carry up to three plausible grouping dimensions:+upstream Location, batch-popular Tag, and the heuristic EntityType+stamped by ``HbConverter.hb_item_to_entity_type``. None is reliably+best on its own — a small batch may have uniform locations, an+import from a flat HomeBox install may have no tags, and a typed+batch may not need the type breakout. The grouper picks among them+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.++Viability for #1 and #2 comes from+``hi.integrations.placement_stats.compute_grouping_stats``. The+EntityType fallback is used unconditionally so a tiny or uniform+batch still gets a sensible heading rather than collapsing to+ungrouped.+"""++from collections import Counter+import logging+from typing import Callable, Dict, List, Optional++from hi.apps.entity.entity_placement import (+ EntityPlacementGroup,+ EntityPlacementInput,+ EntityPlacementItem,+)+from hi.apps.entity.models import Entity++from hi.integrations.placement_stats import compute_grouping_stats+++logger = logging.getLogger(__name__)+++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.+ """++ def __init__(+ self,+ placement_item_key_fn : Callable[[Entity], str],+ ):+ self._placement_item_key_fn = placement_item_key_fn+ return++ def group_entities(+ self, entities: List[Entity],+ ) -> EntityPlacementInput:+ """Ordered-fallback grouping: Location → primary Tag →+ EntityType. First viable wins; EntityType is used+ unconditionally as the final fallback."""+ if not entities:+ return EntityPlacementInput()++ by_location = self._group_by_location( entities = entities )+ if compute_grouping_stats( by_location ).is_viable():+ return by_location++ by_tag = self._group_by_primary_tag( entities = entities )+ if compute_grouping_stats( by_tag ).is_viable():+ return by_tag++ return self._group_by_entity_type( entities = entities )++ def _group_by_location(+ self, entities: List[Entity],+ ) -> EntityPlacementInput:+ return self._build_grouped_input(+ entities = entities,+ label_fn = lambda e: (e.integration_payload or {}).get( 'location' ),+ heading = LOCATION_HEADING,+ fallback_label = LOCATION_FALLBACK_LABEL,+ )++ def _group_by_primary_tag(+ self, entities: List[Entity],+ ) -> EntityPlacementInput:+ primary_tag_lookup = self._compute_primary_tag_lookup(+ entities = entities,+ )+ return self._build_grouped_input(+ entities = entities,+ 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 = '',+ )++ @staticmethod+ def _compute_primary_tag_lookup(+ entities: List[Entity],+ ) -> Dict[int, str]:+ """For each entity, return its primary tag — the tag (from+ its own ``integration_payload['tags']`` list) with the+ highest population across the whole batch. Entities with no+ tags are absent from the returned dict.++ Biasing toward globally-popular tags (over per-item detail+ tags) is what makes the tag dimension produce a small+ number of meaningful buckets rather than one bucket per+ long-tail tag."""+ global_counts: Counter = Counter()+ for entity in entities:+ tags = (entity.integration_payload or {}).get( 'tags' ) or []+ for tag in tags:+ if tag:+ global_counts[ tag ] += 1++ primary_tag_by_entity: Dict[int, str] = {}+ for entity in entities:+ tags = (entity.integration_payload or {}).get( 'tags' ) or []+ candidates = [ tag for tag in tags if tag ]+ if not candidates:+ continue+ # (count, name) tiebreaker keeps tied tags deterministic.+ primary_tag_by_entity[ entity.id ] = max(+ candidates,+ 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/integration.py b/src/hi/services/homebox/integration.pyindex a8db01c0..6e1c87d6 100644--- a/src/hi/services/homebox/integration.py+++ b/src/hi/services/homebox/integration.py@@ -1,6 +1,8 @@import loggingfrom typing import List, Optional+from hi.apps.entity.entity_placement import EntityPlacementInput+from hi.apps.entity.models import Entityfrom hi.apps.system.enums import HealthStatusTypefrom hi.integrations.integration_gateway import IntegrationGateway@@ -15,6 +17,7 @@ from hi.integrations.transient_models import (from hi.services.homebox.hb_manager import HomeBoxManagerfrom hi.services.homebox.hb_metadata import HbMetaData+from hi.services.homebox.hb_placement_grouper import HbPlacementGrouperfrom hi.services.homebox.connector.homebox_connector import HomeBoxConnectorfrom hi.services.homebox.importer.homebox_importer import HomeBoxImporter@@ -73,3 +76,13 @@ class HomeBoxGateway(IntegrationGateway):except Exception as e:logger.exception(f'Error in HomeBox access validation: {e}')return ConnectionTestResult.failure(f'Access validation error: {e}')++ def group_entities_for_placement(+ self, entities: List[Entity],+ ) -> EntityPlacementInput:+ """HomeBox grouping: ordered Location → Tag → EntityType+ fallback. See ``HbPlacementGrouper`` for the policy."""+ grouper = HbPlacementGrouper(+ placement_item_key_fn = self._placement_item_key,+ )+ return grouper.group_entities( entities = entities )diff --git a/src/hi/services/homebox/tests/test_hb_converter.py b/src/hi/services/homebox/tests/test_hb_converter.pyindex 808a3635..8fbc8777 100644--- a/src/hi/services/homebox/tests/test_hb_converter.py+++ b/src/hi/services/homebox/tests/test_hb_converter.py@@ -134,6 +134,60 @@ class TestHbConverterPayloadTimestampOmission(TestCase):)+class TestHbItemToEntityPayloadGroupingFields(TestCase):+ """Pin the flat shape of the location/tags grouping fields.++ These fields feed placement grouping (issue #364). Storing+ them flat — string for location, list of strings for tags —+ keeps payload-diff comparisons stable and avoids leaking HB+ metadata (color, timestamps) that no downstream code reads.+ Live HB API responses remain the source of truth for the rich+ structures."""++ def _mock_item(self, **api_overrides):+ api_dict = {+ 'id': 'item-1',+ 'name': 'Item 1',+ 'description': 'desc',+ 'quantity': 1,+ 'location': {'id': 'loc-1', 'name': 'Garage'},+ 'tags': [+ {'id': 'lab-1', 'name': 'Tools'},+ {'id': 'lab-2', 'name': 'Power'},+ ],+ 'fields': [],+ 'attachments': [],+ }+ api_dict.update(api_overrides)+ return HbItem(api_dict=api_dict, client=Mock())++ def test_location_persists_as_flat_name_string(self):+ payload = HbConverter.hb_item_to_entity_payload(hb_item=self._mock_item())+ self.assertEqual(payload['location'], 'Garage')++ def test_tags_persist_as_flat_name_list(self):+ payload = HbConverter.hb_item_to_entity_payload(hb_item=self._mock_item())+ self.assertEqual(payload['tags'], ['Tools', 'Power'])++ def test_missing_location_yields_none(self):+ payload = HbConverter.hb_item_to_entity_payload(hb_item=self._mock_item(location=None))+ self.assertIsNone(payload['location'])++ def test_missing_tags_yields_empty_list(self):+ payload = HbConverter.hb_item_to_entity_payload(hb_item=self._mock_item(tags=None))+ self.assertEqual(payload['tags'], [])++ def test_tags_without_name_are_skipped(self):+ item = self._mock_item(tags=[+ {'id': 'lab-1', 'name': 'Tools'},+ {'id': 'lab-2'},+ {'id': 'lab-3', 'name': ''},+ {'id': 'lab-4', 'name': 'Power'},+ ])+ payload = HbConverter.hb_item_to_entity_payload(hb_item=item)+ self.assertEqual(payload['tags'], ['Tools', 'Power'])++class TestHbItemToEntityType(TestCase):"""Heuristic EntityType assignment from HomeBox item text fields.diff --git a/src/hi/services/homebox/tests/test_hb_entity_factory.py b/src/hi/services/homebox/tests/test_hb_entity_factory.pyindex b20454d8..fd0df0f3 100644--- a/src/hi/services/homebox/tests/test_hb_entity_factory.py+++ b/src/hi/services/homebox/tests/test_hb_entity_factory.py@@ -50,8 +50,8 @@ class TestHbEntityFactory(TestCase):self.assertFalse(entity.allow_internal_attributes)self.assertTrue(entity.is_external)self.assertNotIn('description', entity.integration_payload)- self.assertEqual(entity.integration_payload.get('location', {}).get('name'), 'Garage')- self.assertEqual(entity.integration_payload.get('tags')[0].get('name'), 'Tools')+ self.assertEqual(entity.integration_payload.get('location'), 'Garage')+ self.assertEqual(entity.integration_payload.get('tags'), ['Tools'])def test_create_models_for_hb_item_creates_entity_import_mode(self):item = self._mock_item(item_id='item-import', name='Drill')@@ -92,7 +92,7 @@ class TestHbEntityFactory(TestCase):self.assertEqual(existing.integration_id, HbMetaData.integration_id)self.assertEqual(existing.integration_name, 'item-reconnect')self.assertEqual(- existing.integration_payload.get('location', {}).get('name'),+ existing.integration_payload.get('location'),'Garage',)diff --git a/src/hi/services/homebox/tests/test_hb_placement_grouper.py b/src/hi/services/homebox/tests/test_hb_placement_grouper.pynew file mode 100644index 00000000..b781c79a--- /dev/null+++ b/src/hi/services/homebox/tests/test_hb_placement_grouper.py@@ -0,0 +1,240 @@+"""+End-to-end coverage for ``HbPlacementGrouper``.++The grouper is the policy implementation behind+``HomeBoxGateway.group_entities_for_placement``. These tests+exercise the ordered-fallback selection against real ``Entity``+rows carrying ``integration_payload`` shapes that match what+``HbConverter.hb_item_to_entity_payload`` produces.+"""+import logging+from typing import List++from django.test import TestCase++from hi.apps.entity.enums import EntityType+from hi.apps.entity.models import Entity++from hi.services.homebox.hb_metadata import HbMetaData+from hi.services.homebox.hb_placement_grouper import (+ HbPlacementGrouper,+ LOCATION_FALLBACK_LABEL,+ LOCATION_HEADING,+ TAG_FALLBACK_LABEL,+ TAG_HEADING,+ TYPE_HEADING,+)+from hi.services.homebox.integration import HomeBoxGateway+++logging.disable(logging.CRITICAL)+++def _create_entity(name: str, entity_type: EntityType, payload: dict) -> Entity:+ return Entity.objects.create(+ name = name,+ entity_type_str = str(entity_type),+ integration_id = HbMetaData.integration_id,+ integration_name = f'hb-{name}',+ integration_payload = payload,+ )+++def _grouper() -> HbPlacementGrouper:+ """Build a grouper wired to the gateway's item-key fn so the+ item keys in produced inputs match production output."""+ return HbPlacementGrouper(+ placement_item_key_fn = HomeBoxGateway()._placement_item_key,+ )+++def _group_label_to_count(placement_input) -> dict:+ return {+ group.label: len(group.items) for group in placement_input.groups+ }+++class TestHbPlacementGrouperEmpty(TestCase):++ def test_empty_returns_empty_input(self):+ result = _grouper().group_entities(entities=[])+ self.assertTrue(result.is_empty())+ # Heading falls back to the dataclass default; we don't+ # care which dimension's heading it lands on for an+ # empty batch, only that nothing renders.+ self.assertEqual(result.groups, [])+ self.assertEqual(result.ungrouped_items, [])+++class TestHbPlacementGrouperLocationStrategy(TestCase):+ """Location-grouped placements are the top of the fallback+ order — confirm they win when locations are well-distributed."""++ def test_well_distributed_locations_win(self):+ entities: List[Entity] = []+ for index, location in enumerate(+ ['Garage', 'Garage', 'Garage',+ 'Office', 'Office', 'Office',+ 'Kitchen', 'Kitchen', 'Kitchen']):+ entities.append(_create_entity(+ name = f'Item {index}',+ entity_type = EntityType.OTHER,+ payload = {'location': location, 'tags': []},+ ))++ result = _grouper().group_entities(entities=entities)++ self.assertEqual(result.heading, LOCATION_HEADING)+ self.assertEqual(+ _group_label_to_count(result),+ {'Garage': 3, 'Kitchen': 3, 'Office': 3},+ )+ self.assertEqual(result.ungrouped_items, [])++ def test_unlocated_items_land_in_fallback_group(self):+ entities = [+ _create_entity('A', EntityType.OTHER, {'location': 'Garage', 'tags': []}),+ _create_entity('B', EntityType.OTHER, {'location': 'Garage', 'tags': []}),+ _create_entity('C', EntityType.OTHER, {'location': 'Garage', 'tags': []}),+ _create_entity('D', EntityType.OTHER, {'location': 'Office', 'tags': []}),+ _create_entity('E', EntityType.OTHER, {'location': 'Office', 'tags': []}),+ _create_entity('F', EntityType.OTHER, {'location': 'Office', 'tags': []}),+ _create_entity('G', EntityType.OTHER, {'location': None, 'tags': []}),+ ]++ result = _grouper().group_entities(entities=entities)++ self.assertEqual(result.heading, LOCATION_HEADING)+ counts = _group_label_to_count(result)+ self.assertEqual(counts.get('Garage'), 3)+ self.assertEqual(counts.get('Office'), 3)+ self.assertEqual(counts.get(LOCATION_FALLBACK_LABEL), 1)+ # Fallback group is appended after the alphabetically-+ # sorted named groups.+ self.assertEqual(result.groups[-1].label, LOCATION_FALLBACK_LABEL)++ def test_single_dominant_location_falls_through(self):+ # 10 of 11 items in 'Garage' → concentration ≈ 0.909,+ # over the 0.9 default ceiling, so Location is not+ # viable and the grouper falls through to another+ # dimension. (9/10 = 0.9 would sit exactly at the+ # threshold; the helper admits it.)+ entities = []+ for i in range(10):+ entities.append(_create_entity(+ f'Item {i}', EntityType.OTHER,+ {'location': 'Garage', 'tags': ['tools']},+ ))+ entities.append(_create_entity(+ 'Lone', EntityType.OTHER,+ {'location': 'Office', 'tags': ['tools']},+ ))++ result = _grouper().group_entities(entities=entities)+ self.assertNotEqual(result.heading, LOCATION_HEADING)+++class TestHbPlacementGrouperTagStrategy(TestCase):+ """Tag becomes the chosen dimension when Location isn't viable+ but Tag is. Verify primary-tag selection picks globally-+ popular tags over per-item detail tags."""++ def test_primary_tag_prefers_globally_popular_over_local(self):+ # Five items share the broadly-popular 'tools' tag. Three+ # of them ALSO carry a unique detail tag. Location is+ # absent everywhere so the location strategy is disqualified.+ # Expected primary-tag-grouping picks 'tools' for items that+ # have it, leaving items without 'tools' for the second group.+ entities = [+ _create_entity('A', EntityType.OTHER, {'location': None, 'tags': ['tools', 'red']}),+ _create_entity('B', EntityType.OTHER, {'location': None, 'tags': ['tools', 'blue']}),+ _create_entity('C', EntityType.OTHER, {'location': None, 'tags': ['tools', 'green']}),+ _create_entity('D', EntityType.OTHER, {'location': None, 'tags': ['tools']}),+ _create_entity('E', EntityType.OTHER, {'location': None, 'tags': ['tools']}),+ _create_entity('F', EntityType.OTHER, {'location': None, 'tags': ['kitchen']}),+ _create_entity('G', EntityType.OTHER, {'location': None, 'tags': ['kitchen']}),+ _create_entity('H', EntityType.OTHER, {'location': None, 'tags': ['kitchen']}),+ ]++ result = _grouper().group_entities(entities=entities)++ self.assertEqual(result.heading, TAG_HEADING)+ counts = _group_label_to_count(result)+ self.assertEqual(counts.get('tools'), 5)+ self.assertEqual(counts.get('kitchen'), 3)++ def test_untagged_items_land_in_fallback_group(self):+ entities = []+ for i in range(4):+ entities.append(_create_entity(+ f'T{i}', EntityType.OTHER,+ {'location': None, 'tags': ['tools']},+ ))+ for i in range(4):+ entities.append(_create_entity(+ f'K{i}', EntityType.OTHER,+ {'location': None, 'tags': ['kitchen']},+ ))+ entities.append(_create_entity(+ 'X', EntityType.OTHER,+ {'location': None, 'tags': []},+ ))+ entities.append(_create_entity(+ 'Y', EntityType.OTHER,+ {'location': None, 'tags': []},+ ))++ result = _grouper().group_entities(entities=entities)++ self.assertEqual(result.heading, TAG_HEADING)+ counts = _group_label_to_count(result)+ self.assertEqual(counts.get('tools'), 4)+ self.assertEqual(counts.get('kitchen'), 4)+ self.assertEqual(counts.get(TAG_FALLBACK_LABEL), 2)+++class TestHbPlacementGrouperTypeFallback(TestCase):+ """EntityType is the unconditional final fallback. Verify it+ runs when neither Location nor Tag is viable AND that its+ heading is overridden from the framework default."""++ 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.+ entities = [+ _create_entity('A', EntityType.LIGHT, {'location': None, 'tags': []}),+ _create_entity('B', EntityType.LIGHT, {'location': None, 'tags': []}),+ _create_entity('C', EntityType.LIGHT, {'location': None, 'tags': []}),+ _create_entity('D', EntityType.CAMERA, {'location': None, 'tags': []}),+ _create_entity('E', EntityType.CAMERA, {'location': None, 'tags': []}),+ _create_entity('F', EntityType.CAMERA, {'location': None, 'tags': []}),+ ]++ result = _grouper().group_entities(entities=entities)++ self.assertEqual(result.heading, TYPE_HEADING)+ labels = {group.label for group in result.groups}+ self.assertIn(EntityType.LIGHT.label, labels)+ self.assertIn(EntityType.CAMERA.label, labels)+++class TestHomeBoxGatewayGroupingIntegration(TestCase):+ """Smoke test the gateway override actually routes through the+ grouper so the wiring (and ``_placement_item_key`` injection)+ stays alive."""++ def test_gateway_override_uses_location_when_viable(self):+ entities = []+ for location in ['Garage', 'Garage', 'Garage',+ 'Office', 'Office', 'Office',+ 'Kitchen', 'Kitchen', 'Kitchen']:+ entities.append(_create_entity(+ f'{location}-Item-{len(entities)}',+ EntityType.OTHER,+ {'location': location, 'tags': []},+ ))++ result = HomeBoxGateway().group_entities_for_placement(entities)++ self.assertEqual(result.heading, LOCATION_HEADING)+ self.assertEqual(len(result.groups), 3)diff --git a/src/hi/simulator/management/commands/seed_sim_profiles.py b/src/hi/simulator/management/commands/seed_sim_profiles.pyindex d13bdc5f..29f741fa 100644--- a/src/hi/simulator/management/commands/seed_sim_profiles.py+++ b/src/hi/simulator/management/commands/seed_sim_profiles.py@@ -455,11 +455,19 @@ class Command(BaseCommand):# shapes for targeted UI coverage (empty, partial, attachments-# only, mixed, fully rich, truncation-toggle). Items 007-025# use modular per-index rules to keep variety reproducible.+ #+ # Locations are distributed across four buckets so the placement+ # grouping heuristic (#364) sees a viable Location strategy. One+ # item is left location-less to exercise the Untagged/Other+ # fallback bucket.+ location_palette = [ 'Garage', 'Office', 'Kitchen', 'Workshop' ]+self._add_homebox_item(profile,'Volume Item 001',item_id = 'volume-item-001',quantity = 1,+ location_name = 'Garage',)self._add_homebox_item(@@ -473,6 +481,7 @@ class Command(BaseCommand):serial_number = 'SN-00002',custom_fields = 'Color=Red',tags = 'tools,power',+ location_name = 'Kitchen',)self._add_homebox_item(@@ -484,6 +493,7 @@ class Command(BaseCommand):AttachmentTemplate.MANUAL.key,AttachmentTemplate.PHOTO.key,]),+ location_name = 'Office',)self._add_homebox_item(@@ -500,6 +510,7 @@ class Command(BaseCommand):AttachmentTemplate.RECEIPT.key,AttachmentTemplate.PHOTO.key,]),+ location_name = 'Workshop',)self._add_homebox_item(@@ -528,6 +539,7 @@ class Command(BaseCommand):AttachmentTemplate.PHOTO.key,AttachmentTemplate.WARRANTY.key,]),+ location_name = 'Garage',)# Item 006: varied-length values to exercise the JS Show@@ -580,6 +592,7 @@ class Command(BaseCommand):AttachmentTemplate.PHOTO_TALL.key,AttachmentTemplate.PHOTO_TALL_X.key,]),+ location_name = 'Office',)custom_field_palette = [@@ -703,6 +716,14 @@ class Command(BaseCommand):if index % 3 == 0:kwargs['tags'] = tag_palette[ index % len( tag_palette ) ]+ # Leave the final item location-less to exercise the+ # Untagged/Other fallback bucket; cycle the rest through+ # the palette so each bucket has multiple items.+ if index < 24:+ kwargs['location_name'] = location_palette[+ index % len( location_palette )+ ]+self._add_homebox_item(profile,palette_name,diff --git a/src/hi/simulator/services/homebox/sim_models.py b/src/hi/simulator/services/homebox/sim_models.pyindex 05bf927e..ca562996 100644--- a/src/hi/simulator/services/homebox/sim_models.py+++ b/src/hi/simulator/services/homebox/sim_models.py@@ -68,6 +68,15 @@ class HomeBoxInventoryItemFields( SimEntityFields ):'help_text': 'CSV of HomeBox tag names.',},)+ location_name : str = dc_field(+ default = '',+ metadata = {+ 'help_text': (+ 'HomeBox location name. When set, the simulator emits a '+ 'location dict on the item; when blank, location is null.'+ ),+ },+ )# Comma-separated wire keys of ``AttachmentTemplate`` members# (``hi.simulator.services.homebox.attachment_catalog``);# unknown keys are dropped silently. The simulator's API@@ -178,6 +187,17 @@ def _parse_tags( csv_value : str ) -> List[ Dict[ str, str ] ]:return tags+def _build_location( location_name : str ):+ name = ( location_name or '' ).strip()+ if not name:+ return None+ slug = '-'.join( name.lower().split() )+ return {+ 'id' : f'loc-{slug}',+ 'name' : name,+ }++def build_item_api_dict( sim_entity_id : int,fields : HomeBoxInventoryItemFields,archived_state : HomeBoxItemArchivedState,@@ -187,11 +207,13 @@ def build_item_api_dict( sim_entity_id : int,Build the HomeBox item JSON shape returned by the simulator's API,matching the fields the integration's HbItem parser consumes.- Location is emitted as null (out of simulator scope). Custom- fields, tags, and attachments are populated from per-item CSV- inputs; the actual attachment bytes are rendered on demand by- the download endpoint when the integration fetches each- attachment. Timestamps come from the persisted ``DbSimEntity``+ Location is emitted as a minimal dict (``{id, name}``) when the+ operator sets ``location_name``, else null. The ``id`` is derived+ deterministically from the name so two items sharing a location+ name share a location id. Custom fields, tags, and attachments+ are populated from per-item CSV inputs; the actual attachment+ bytes are rendered on demand by the download endpoint when the+ integration fetches each attachment. Timestamps come from the persisted ``DbSimEntity``so they're stable across reads — change only when the operatoractually edits the row, matching real HomeBox behavior."""@@ -220,7 +242,7 @@ def build_item_api_dict( sim_entity_id : int,'archived' : archived_state.is_archived,'fields' : _parse_custom_fields( fields.custom_fields ),'attachments' : attachments,- 'location' : None,+ 'location' : _build_location( fields.location_name ),'tags' : _parse_tags( fields.tags ),'createdAt' : created_at.isoformat(),'updatedAt' : updated_at.isoformat(),