Home Information - Your home, your data, organized.
Python
Entity-as-Reference framework with HomeBox Connect integration (#357)
Tony C87762900bce4
diff --git a/src/hi/apps/attribute/edit_context.py b/src/hi/apps/attribute/edit_context.pyindex be3bd7a4..d14798b0 100644--- a/src/hi/apps/attribute/edit_context.py+++ b/src/hi/apps/attribute/edit_context.py@@ -149,6 +149,20 @@ class AttributePageEditContext:(Add File / Add Info). Independent of ``allow_edits``."""return True+ @property+ def allow_internal_attributes(self) -> bool:+ """Whether the HI internal attribute section is rendered at all on+ this surface. When False, the entire section (Files + Properties ++ Deleted attributes + Add buttons) is suppressed; the section does+ not exist. Independent of ``can_add_custom_attributes`` (which only+ gates the Add affordance when the section IS rendered) and+ ``allow_edits`` (which gates UPDATE-button visibility).++ Used by integration-connected entities where the attribute data is+ owned externally and HI does not present a local attribute+ surface."""+ return True+@propertydef add_attribute_disabled_message(self) -> str:return ''diff --git a/src/hi/apps/attribute/templates/attribute/components/edit_content_body.html b/src/hi/apps/attribute/templates/attribute/components/edit_content_body.htmlindex 1b5175f6..d82c909c 100644--- a/src/hi/apps/attribute/templates/attribute/components/edit_content_body.html+++ b/src/hi/apps/attribute/templates/attribute/components/edit_content_body.html@@ -32,7 +32,7 @@ by using the AttributeItemEditContext pattern.</div>{% endif %}- <div class="attr-v2-owner-fields }}">+ <div class="attr-v2-owner-fields">{% block owner_fields %}<!-- Subclasses should override this block to provide owner-specific fields -->{% endblock %}@@ -90,7 +90,7 @@ by using the AttributeItemEditContext pattern.<div class="{{ DIVID.ATTR_V2_ACTION_BUTTONS_CLASS }}">{% block additional_actions %}{% endblock %}- {% if attr_page_context.can_add_custom_attributes %}+ {% if attr_page_context.allow_internal_attributes and attr_page_context.can_add_custom_attributes %}{% block file_upload_button %}<button type="button"class="btn btn-sm btn-outline-primary mb-0"@@ -114,22 +114,34 @@ by using the AttributeItemEditContext pattern.<!-- Scrollable Content Area (below sticky panel) --><div id="{{ attr_page_context.scrollable_content_html_id }}"class="{{ DIVID.ATTR_V2_SCROLLABLE_CONTENT_CLASS }}">-++ {% if attr_page_context.allow_internal_attributes %}+<!-- Files Section -->{% block files_section %}{% include "attribute/components/file_grid.html" with file_attributes=file_attributes %}{% endblock %}-+<!-- Properties Section -->{% block properties_section %}{% include "attribute/components/regular_attribute_list.html" with regular_attributes_formset=regular_attributes_formset %}{% endblock %}-+<!-- Additional Sections -->{% block additional_sections %}{% include "attribute/components/deleted_attribute_list.html" with deleted_attributes=deleted_attributes %}{% endblock %}-++ {% endif %}++ {% block external_view_data %}+ {% if external_view_data %}+ <div class="attr-v2-external-view-data">+ {% include external_view_data.template_name with view_data=external_view_data %}+ </div>+ {% endif %}+ {% endblock %}+</div>diff --git a/src/hi/apps/entity/entity_attribute_edit_context.py b/src/hi/apps/entity/entity_attribute_edit_context.pyindex c6c73385..e361b00c 100644--- a/src/hi/apps/entity/entity_attribute_edit_context.py+++ b/src/hi/apps/entity/entity_attribute_edit_context.py@@ -61,9 +61,6 @@ class EntityAttributeItemEditContext(AttributeItemEditContext):form_data,instance = self.entity,prefix = self.formset_prefix,- form_kwargs = {- 'can_add_custom_attributes': self.can_add_custom_attributes,- },)@property@@ -80,23 +77,5 @@ class EntityAttributeItemEditContext(AttributeItemEditContext):kwargs = { 'entity_id': self.entity.id })@property- def can_add_custom_attributes(self) -> bool:- return self.entity.can_add_custom_attributes-- @property- def allow_edits(self) -> bool:- # Externally managed entities (e.g., HomeBox-imported) are- # fully read-only on this surface — same gate as adding.- return self.entity.can_add_custom_attributes-- @property- def add_attribute_disabled_message(self) -> str:- if self.can_add_custom_attributes:- return ''- return 'New attributes are disabled for externally managed entities.'-- @property- def externally_managed_message(self) -> str:- if self.can_add_custom_attributes:- return ''- return 'Attributes are managed externally and cannot be edited here.'+ def allow_internal_attributes(self) -> bool:+ return self.entity.allow_internal_attributesdiff --git a/src/hi/apps/entity/forms.py b/src/hi/apps/entity/forms.pyindex c3eb75d2..48d7e829 100644--- a/src/hi/apps/entity/forms.py+++ b/src/hi/apps/entity/forms.py@@ -47,36 +47,7 @@ class EntityAttributeForm( AttributeForm ):class EntityAttributeRegularFormSet(RegularAttributeBaseFormSet):-- def clean(self):- super().clean()-- if not self.instance or self.instance.can_add_custom_attributes:- return-- for form in self.forms:- if not hasattr(form, 'cleaned_data'):- continue-- cleaned_data = form.cleaned_data- if not cleaned_data:- continue-- if cleaned_data.get('DELETE', False):- continue-- if form.instance and form.instance.pk:- continue-- has_new_data = bool(- cleaned_data.get('name')- or cleaned_data.get('value')- or cleaned_data.get('secret')- )- if has_new_data:- raise forms.ValidationError(- 'New attributes cannot be added for this item because attributes are managed externally.'- )+ passEntityAttributeRegularFormSet = forms.inlineformset_factory(diff --git a/src/hi/apps/entity/migrations/0020_entity_allow_internal_attributes.py b/src/hi/apps/entity/migrations/0020_entity_allow_internal_attributes.pynew file mode 100644index 00000000..af9a6d10--- /dev/null+++ b/src/hi/apps/entity/migrations/0020_entity_allow_internal_attributes.py@@ -0,0 +1,57 @@+import logging++from django.db import migrations, models+++def delete_homebox_orphan_attributes(apps, schema_editor):+ """Delete EntityAttribute rows for HomeBox-integrated entities.++ ``QuerySet.delete()`` here uses the historical model (field set+ only) — runtime signals and overridden ``delete()`` methods do+ not fire, so any on-disk file referenced by a deleted FILE-type+ row stays on disk."""+ logger = logging.getLogger('hi.apps.entity.migrations.0020')++ Entity = apps.get_model('entity', 'Entity')+ EntityAttribute = apps.get_model('entity', 'EntityAttribute')++ affected_entities = list(+ Entity.objects.filter(integration_id='hb').values_list('id', flat=True)+ )+ if not affected_entities:+ logger.info('HomeBox Connect migration: no HomeBox entities present.')+ return++ deleted_count, _ = EntityAttribute.objects.filter(+ entity_id__in=affected_entities,+ ).delete()++ logger.info(+ f'HomeBox Connect migration: deleted {deleted_count} EntityAttribute '+ f'row(s) across {len(affected_entities)} entit(y/ies). '+ f'Entity ids: {affected_entities}'+ )+++class Migration(migrations.Migration):++ dependencies = [+ ('entity', '0019_entity_video_snapshot_stream_fps'),+ ]++ operations = [+ migrations.RenameField(+ model_name='entity',+ old_name='can_add_custom_attributes',+ new_name='allow_internal_attributes',+ ),+ migrations.AlterField(+ model_name='entity',+ name='allow_internal_attributes',+ field=models.BooleanField(default=True, verbose_name='Allow Internal Attributes?'),+ ),+ migrations.RunPython(+ code=delete_homebox_orphan_attributes,+ reverse_code=migrations.RunPython.noop,+ ),+ ]diff --git a/src/hi/apps/entity/models.py b/src/hi/apps/entity/models.pyindex f42ece8e..3bef5982 100644--- a/src/hi/apps/entity/models.py+++ b/src/hi/apps/entity/models.py@@ -53,8 +53,8 @@ class Entity( IntegrationDetailsModel, LocationItemModelMixin ):'User Delete?',default = True,)- can_add_custom_attributes = models.BooleanField(- 'Can Add Attributes?',+ allow_internal_attributes = models.BooleanField(+ 'Allow Internal Attributes?',default = True,)has_video_stream = models.BooleanField(diff --git a/src/hi/apps/entity/templates/entity/panes/entity_edit_content_body.html b/src/hi/apps/entity/templates/entity/panes/entity_edit_content_body.htmlindex 7ab6fc57..cf7d69ae 100644--- a/src/hi/apps/entity/templates/entity/panes/entity_edit_content_body.html+++ b/src/hi/apps/entity/templates/entity/panes/entity_edit_content_body.html@@ -10,13 +10,12 @@ Extends the generic attribute edit content body with entity-specific field layou<div class="col-md-8"><div class="form-group mb-0"><small class="text-muted">Name</small>- <input type="text"+ <input type="text"id="{{ owner_form.name.id_for_label }}"name="{{ owner_form.name.html_name }}"value="{{ owner_form.name.value|default:'' }}"class="form-control form-control-sm"- {% if owner_form.name.field.required %}required{% endif %}- {% if not attr_item_context.can_add_custom_attributes %}readonly aria-readonly="true" title="{{ attr_item_context.add_attribute_disabled_message }}"{% endif %}>+ {% if owner_form.name.field.required %}required{% endif %}>{% if owner_form.name.errors %}<div class="invalid-feedback d-block">{{ owner_form.name.errors }}diff --git a/src/hi/apps/entity/tests/test_models.py b/src/hi/apps/entity/tests/test_models.pyindex 93064408..c3eb2059 100644--- a/src/hi/apps/entity/tests/test_models.py+++ b/src/hi/apps/entity/tests/test_models.py@@ -20,7 +20,7 @@ class TestEntity(BaseTestCase):integration_name='test_integration',)- self.assertTrue(entity.can_add_custom_attributes)+ self.assertTrue(entity.allow_internal_attributes)returndef test_integration_key_enforces_unique_entity_identification(self):diff --git a/src/hi/apps/entity/tests/test_views.py b/src/hi/apps/entity/tests/test_views.pyindex 3c27e21d..e3ecbd2e 100644--- a/src/hi/apps/entity/tests/test_views.py+++ b/src/hi/apps/entity/tests/test_views.py@@ -1,5 +1,5 @@import logging-from unittest.mock import patch+from unittest.mock import Mock, patchfrom django.core.files.uploadedfile import SimpleUploadedFilefrom django.db import transaction@@ -316,15 +316,16 @@ class TestEntityEditView(DualModeViewTestCase):self.assertIsNotNone(new_attr)self.assertEqual(new_attr.value, 'new value')- def test_get_hides_add_and_update_buttons_when_entity_disallows_custom_attributes(self):- """When the entity is integration-managed (cannot add custom- attributes), the Add File / Add Info / Update buttons are- omitted entirely rather than rendered disabled — disabled-but-- visible affordances were confusing on a fully read-only- surface, and Update was a no-op there.+ def test_get_hides_internal_attribute_section_when_entity_disallows_it(self):+ """When the entity has ``allow_internal_attributes`` False+ (e.g., an integration-managed entity whose attribute data is+ owned externally), the entire HI internal attribute section is+ suppressed: Add File / Add Info buttons, the Files grid, the+ Properties list, and the Deleted attributes list are all+ omitted from the rendered surface."""- self.entity.can_add_custom_attributes = False- self.entity.save(update_fields=['can_add_custom_attributes'])+ self.entity.allow_internal_attributes = False+ self.entity.save(update_fields=['allow_internal_attributes'])url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})response = self.client.get(url)@@ -336,33 +337,6 @@ class TestEntityEditView(DualModeViewTestCase):self.assertNotIn('>Add File<', content)self.assertNotIn('>Add Info<', content)- def test_post_rejects_new_attribute_when_entity_disallows_custom_attributes(self):- self.entity.can_add_custom_attributes = False- self.entity.save(update_fields=['can_add_custom_attributes'])-- url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})- form_data = EntityAttributeSyntheticData.create_form_data_for_entity_edit(entity=self.entity)-- regular_attributes = list(self.entity.attributes.exclude(value_type_str=str(AttributeValueType.FILE)))- prefix = f'entity-{self.entity.id}'- form_data.update({- f'{prefix}-TOTAL_FORMS': str(len(regular_attributes) + 2),- f'{prefix}-INITIAL_FORMS': str(len(regular_attributes)),- f'{prefix}-MIN_NUM_FORMS': '0',- f'{prefix}-MAX_NUM_FORMS': '1000',- f'{prefix}-{len(regular_attributes)}-name': 'blocked_property',- f'{prefix}-{len(regular_attributes)}-value': 'blocked value',- })-- response = self.client.post(url, form_data)-- self.assertErrorResponse(response)- self.assertJsonResponse(response)- self.assertFalse(self.entity.attributes.filter(name='blocked_property').exists())-- content = response.content.decode('utf-8')- self.assertIn('New attributes cannot be added for this item because attributes are managed externally.', content)-def test_entity_with_complex_attribute_mix(self):"""Test editing entity with mixed attribute types (text, file, secret)."""# Create entity with mixed attributes@@ -437,6 +411,280 @@ class TestEntityEditView(DualModeViewTestCase):self.assertEqual(self.entity.name, 'Transaction Test Name')+class TestEntityEditViewExternalViewData(DualModeViewTestCase):+ """Tests for the external-data view dispatch in+ ``EntityEditView.get()``. The external-data region renders only+ when the entity's integration gateway returns a non-None+ ``ExternalViewData`` payload; everything else (native entities,+ unknown integration_id, gateway returns None) suppresses it."""++ def setUp(self):+ super().setUp()+ self.enterContext(self.in_memory_media_storage())+ self.native_entity = EntityAttributeSyntheticData.create_test_entity(+ name='Native Entity',+ integration_id=None,+ integration_name=None,+ )+ self.integration_entity = EntityAttributeSyntheticData.create_test_entity(+ name='Integration Entity',+ integration_id='ext_view_test',+ integration_name='ext_view_test_name',+ )++ def _make_structured_view_data(self):+ from hi.integrations.external_view_data import (+ NameValuePair, AttachmentRef, StructuredViewData,+ )+ return StructuredViewData(+ deep_link_url='https://upstream.example/items/42',+ attributes=[+ NameValuePair(name='Manufacturer', value='Acme'),+ NameValuePair(name='Model', value='WidgetPro'),+ ],+ attachments=[+ AttachmentRef(+ id='att1',+ title='Receipt',+ mime_type='image/png',+ thumbnail_url='https://upstream.example/thumb/att1',+ open_url='https://upstream.example/open/att1',+ ),+ ],+ )++ def _make_minimal_view_data(self):+ from hi.integrations.external_view_data import MinimalViewData+ return MinimalViewData(deep_link_url='https://upstream.example/items/99')++ def test_native_entity_omits_section_and_skips_lookup(self):+ """A native entity (no integration_id) must NOT cause an+ integration-gateway lookup and must render without the+ external-view-data DOM marker."""+ url = reverse('entity_edit', kwargs={'entity_id': self.native_entity.id})++ with patch(+ 'hi.integrations.integration_manager.IntegrationManager.get_integration_gateway'+ ) as mock_lookup:+ response = self.client.get(url)++ self.assertSuccessResponse(response)+ self.assertIsNone(response.context['external_view_data'])+ mock_lookup.assert_not_called()+ self.assertNotIn('attr-v2-external-view-data', response.content.decode('utf-8'))++ def test_integration_entity_hook_returns_none_omits_section(self):+ """Integration entity whose gateway hook returns None: the+ lookup happens but the section is suppressed."""+ url = reverse('entity_edit', kwargs={'entity_id': self.integration_entity.id})++ mock_gateway = Mock()+ mock_gateway.get_external_view_data.return_value = None++ with patch(+ 'hi.integrations.integration_manager.IntegrationManager.get_integration_gateway',+ return_value=mock_gateway,+ ) as mock_lookup:+ response = self.client.get(url)++ self.assertSuccessResponse(response)+ self.assertIsNone(response.context['external_view_data'])+ mock_lookup.assert_called_with('ext_view_test')+ # Confirm the gateway hook was invoked at least once with the+ # right entity. EntityEditView.get() can be re-entered during+ # render (e.g., when the status modal falls back to the edit+ # view for an entity with no state data), so we don't pin the+ # exact call count.+ mock_gateway.get_external_view_data.assert_called_with(self.integration_entity)+ self.assertNotIn('attr-v2-external-view-data', response.content.decode('utf-8'))++ def test_integration_entity_structured_view_data_renders_section(self):+ """``StructuredViewData`` renders the structured partial with+ attribute rows, attachments, and the deep link."""+ url = reverse('entity_edit', kwargs={'entity_id': self.integration_entity.id})++ structured = self._make_structured_view_data()+ mock_gateway = Mock()+ mock_gateway.get_external_view_data.return_value = structured++ with patch(+ 'hi.integrations.integration_manager.IntegrationManager.get_integration_gateway',+ return_value=mock_gateway,+ ):+ response = self.client.get(url)++ self.assertSuccessResponse(response)+ content = response.content.decode('utf-8')+ self.assertIn('attr-v2-external-view-data', content)+ self.assertIn('attr-v2-external-structured', content)+ self.assertIn('Manufacturer', content)+ self.assertIn('Acme', content)+ self.assertIn('WidgetPro', content)+ self.assertIn('https://upstream.example/thumb/att1', content)+ self.assertIn('https://upstream.example/items/42', content)++ def test_integration_entity_minimal_view_data_renders_deep_link_only(self):+ """``MinimalViewData`` renders only the deep link placeholder+ — no structured-partial markers."""+ url = reverse('entity_edit', kwargs={'entity_id': self.integration_entity.id})++ minimal = self._make_minimal_view_data()+ mock_gateway = Mock()+ mock_gateway.get_external_view_data.return_value = minimal++ with patch(+ 'hi.integrations.integration_manager.IntegrationManager.get_integration_gateway',+ return_value=mock_gateway,+ ):+ response = self.client.get(url)++ self.assertSuccessResponse(response)+ content = response.content.decode('utf-8')+ self.assertIn('attr-v2-external-view-data', content)+ self.assertIn('attr-v2-external-minimal', content)+ self.assertIn('https://upstream.example/items/99', content)+ self.assertNotIn('attr-v2-external-structured', content)++ def test_integration_entity_minimal_view_data_surfaces_error_message(self):+ """``MinimalViewData.error_message`` renders in the modal so+ the operator sees the failure reason inline rather than only+ in server logs."""+ from hi.integrations.external_view_data import MinimalViewData++ url = reverse('entity_edit', kwargs={'entity_id': self.integration_entity.id})++ minimal = MinimalViewData(+ deep_link_url='https://upstream.example/items/99',+ error_message='HomeBox upstream unavailable: Connection refused',+ )+ mock_gateway = Mock()+ mock_gateway.get_external_view_data.return_value = minimal++ with patch(+ 'hi.integrations.integration_manager.IntegrationManager.get_integration_gateway',+ return_value=mock_gateway,+ ):+ response = self.client.get(url)++ self.assertSuccessResponse(response)+ content = response.content.decode('utf-8')+ self.assertIn('attr-ext-minimal-error', content)+ self.assertIn('HomeBox upstream unavailable: Connection refused', content)+ # Deep link is still offered alongside the error.+ self.assertIn('https://upstream.example/items/99', content)++ def test_external_view_data_and_internal_attributes_coexist(self):+ """The external-data view and the internal attribute list are+ independently gated: an integration entity with both internal+ attributes AND an external view payload renders both."""+ EntityAttributeSyntheticData.create_test_text_attribute(+ entity=self.integration_entity,+ name='internal_prop',+ value='internal value',+ )+ url = reverse('entity_edit', kwargs={'entity_id': self.integration_entity.id})++ structured = self._make_structured_view_data()+ mock_gateway = Mock()+ mock_gateway.get_external_view_data.return_value = structured++ with patch(+ 'hi.integrations.integration_manager.IntegrationManager.get_integration_gateway',+ return_value=mock_gateway,+ ):+ response = self.client.get(url)++ self.assertSuccessResponse(response)+ content = response.content.decode('utf-8')+ # External-data view marker.+ self.assertIn('attr-v2-external-structured', content)+ # Internal attribute list marker: the internal attribute name+ # appears in the rendered attribute list.+ self.assertIn('internal_prop', content)++ def test_connect_mode_renders_external_view_with_internal_attributes_suppressed(self):+ """``allow_internal_attributes=False`` plus a populated+ ``external_view_data`` payload: external-data view renders;+ internal attribute list does not."""+ self.integration_entity.allow_internal_attributes = False+ self.integration_entity.save(update_fields=['allow_internal_attributes'])++ EntityAttributeSyntheticData.create_test_text_attribute(+ entity=self.integration_entity,+ name='orphan_internal_prop',+ value='should not render',+ )++ url = reverse('entity_edit', kwargs={'entity_id': self.integration_entity.id})++ structured = self._make_structured_view_data()+ mock_gateway = Mock()+ mock_gateway.get_external_view_data.return_value = structured++ with patch(+ 'hi.integrations.integration_manager.IntegrationManager.get_integration_gateway',+ return_value=mock_gateway,+ ):+ response = self.client.get(url)++ self.assertSuccessResponse(response)+ content = response.content.decode('utf-8')+ self.assertIn('attr-v2-external-view-data', content)+ self.assertIn('attr-v2-external-structured', content)+ self.assertNotIn('orphan_internal_prop', content)+ self.assertNotIn('>Add File<', content)+ self.assertNotIn('>Add Info<', content)++ def test_unknown_integration_id_omits_section(self):+ """If ``IntegrationManager.get_integration_gateway`` raises+ ``KeyError`` (e.g., the integration_id is stale or the+ integration was never registered), the view catches the+ exception and suppresses the external-data view — no error+ escapes."""+ url = reverse('entity_edit', kwargs={'entity_id': self.integration_entity.id})++ with patch(+ 'hi.integrations.integration_manager.IntegrationManager.get_integration_gateway',+ side_effect=KeyError('Unknown integration id "ext_view_test".'),+ ):+ response = self.client.get(url)++ self.assertSuccessResponse(response)+ self.assertIsNone(response.context['external_view_data'])+ self.assertNotIn('attr-v2-external-view-data', response.content.decode('utf-8'))++ def test_custom_template_view_data_uses_instance_template_name(self):+ """``CustomTemplateViewData`` is the escape hatch: the+ ``template_name`` set on the instance drives the include. We+ verify the include call site honors the instance attribute by+ pointing at a template that emits a distinctive marker, then+ asserting the marker appears in the rendered output."""+ from hi.integrations.external_view_data import CustomTemplateViewData++ custom = CustomTemplateViewData(+ template_name='integrations/external_data/entity/minimal.html',+ deep_link_url='https://upstream.example/custom/1',+ context={'unused': 'unused'},+ )+ mock_gateway = Mock()+ mock_gateway.get_external_view_data.return_value = custom++ url = reverse('entity_edit', kwargs={'entity_id': self.integration_entity.id})+ with patch(+ 'hi.integrations.integration_manager.IntegrationManager.get_integration_gateway',+ return_value=mock_gateway,+ ):+ response = self.client.get(url)++ self.assertSuccessResponse(response)+ content = response.content.decode('utf-8')+ # The minimal partial is what we asked for via template_name,+ # so its DOM marker must be present even though the instance+ # is a CustomTemplateViewData.+ self.assertIn('attr-v2-external-minimal', content)+ self.assertIn('https://upstream.example/custom/1', content)++class TestEntityPropertiesEditView(SyncViewTestCase):"""Tests for EntityPropertiesEditView - handles entity properties (name, type) editing only.diff --git a/src/hi/apps/entity/views.py b/src/hi/apps/entity/views.pyindex 1b92481b..b1812945 100644--- a/src/hi/apps/entity/views.py+++ b/src/hi/apps/entity/views.py@@ -14,6 +14,7 @@ from hi.apps.entity.state_panel_dispatch import StatePanelDispatcherfrom hi.apps.monitor.display_data import EntityDisplayDatafrom hi.apps.monitor.status_display_manager import StatusDisplayManager+from hi.integrations.integration_manager import IntegrationManagerfrom hi.views import page_not_found_responsefrom hi.hi_async_view import HiModalViewfrom hi.apps.entity.edit.entity_type_transition_handler import EntityTypeTransitionHandler@@ -174,8 +175,22 @@ class EntityEditView( HiModalView, EntityViewMixin, AttributeEditViewMixin ):template_context = self.create_initial_template_context(attr_item_context= attr_item_context,)+ template_context['external_view_data'] = self._get_external_view_data( entity )return self.modal_response( request, template_context )-++ def _get_external_view_data( self, entity ):+ if not entity.integration_id:+ return None+ try:+ gateway = IntegrationManager().get_integration_gateway( entity.integration_id )+ except KeyError:+ logger.warning(+ 'No integration gateway registered for entity '+ f'{entity.id} (integration_id={entity.integration_id!r}).'+ )+ return None+ return gateway.get_external_view_data( entity )+def post( self, request,*args, **kwargs ):entity = self.get_entity(request, *args, **kwargs)original_entity_type = entity.entity_typediff --git a/src/hi/integrations/entity_operations.py b/src/hi/integrations/entity_operations.pyindex dae8502a..9b0a6030 100644--- a/src/hi/integrations/entity_operations.py+++ b/src/hi/integrations/entity_operations.py@@ -389,7 +389,7 @@ class EntityIntegrationOperations:# entity is no longer integration-managed, so user-management# rights are restored.entity.can_user_delete = True- entity.can_add_custom_attributes = True+ entity.allow_internal_attributes = True# Suppress integration-backed capabilities. The intrinsic# video-stream capability is genuinely lost (the backing sensordiff --git a/src/hi/integrations/external_view_data.py b/src/hi/integrations/external_view_data.pynew file mode 100644index 00000000..f9646ecf--- /dev/null+++ b/src/hi/integrations/external_view_data.py@@ -0,0 +1,82 @@+"""+External-data view models for the entity-detail modal.++An integration's gateway returns an ``ExternalViewData`` subclass+instance from ``get_external_view_data(entity)`` to render the+external-data view region of the modal; returning ``None`` suppresses+that region entirely. ``template_name`` is a class-level attribute on+each subclass pointing at the partial that renders it; integrations+can provide their own subclass with a custom ``template_name`` for+fully bespoke layouts.++Default partials live under+``hi/integrations/templates/integrations/external_data/entity/``.+"""+from dataclasses import dataclass, field+from typing import Dict, List, Optional+++@dataclass+class NameValuePair:+ """A single named value for display in a ``StructuredViewData``+ attribute list. Order is determined by list position."""+ name: str+ value: str+++@dataclass+class AttachmentRef:+ """A reference to an externally-hosted attachment for display in a+ ``StructuredViewData`` attachment grid. The integration is+ responsible for providing a working ``thumbnail_url`` and+ ``open_url`` (which may point at HI proxy endpoints for auth-gated+ upstreams)."""+ id: str+ title: str+ mime_type: str+ thumbnail_url: Optional[str] = None+ open_url: Optional[str] = None+++@dataclass+class ExternalViewData:+ """Base for external-data view payloads. Subclasses set+ ``template_name`` to the partial that renders them."""++ template_name: str = ''+ deep_link_url: Optional[str] = None+++@dataclass+class StructuredViewData(ExternalViewData):+ """Common case: name/value rows plus a grid of attachments."""++ template_name: str = 'integrations/external_data/entity/structured.html'+ attributes: List[NameValuePair] = field(default_factory=list)+ attachments: List[AttachmentRef] = field(default_factory=list)+++@dataclass+class CustomTemplateViewData(ExternalViewData):+ """Escape hatch for integrations needing a fully custom layout.+ The integration sets ``template_name`` to a path under its own+ ``services/<name>/templates/...`` and supplies whatever+ ``context`` it needs."""++ template_name: str = ''+ context: Dict = field(default_factory=dict)++ def __post_init__(self):+ if not self.template_name or not self.template_name.strip():+ raise ValueError(+ 'CustomTemplateViewData requires a non-empty template_name.'+ )+++@dataclass+class MinimalViewData(ExternalViewData):+ """Placeholder when a full view payload is unavailable. Renders the+ deep link and the optional ``error_message``."""++ template_name: str = 'integrations/external_data/entity/minimal.html'+ error_message: Optional[str] = Nonediff --git a/src/hi/integrations/integration_gateway.py b/src/hi/integrations/integration_gateway.pyindex d7e21853..63061790 100644--- a/src/hi/integrations/integration_gateway.py+++ b/src/hi/integrations/integration_gateway.py@@ -6,6 +6,7 @@ from hi.apps.monitor.periodic_monitor import PeriodicMonitorfrom hi.apps.sense.transient_models import SensorResponsefrom hi.apps.system.health_status_provider import HealthStatusProvider+from .external_view_data import ExternalViewDatafrom .integration_controller import IntegrationControllerfrom .integration_manage_view_pane import IntegrationManageViewPanefrom .integration_synchronizer import IntegrationSynchronizer@@ -109,3 +110,13 @@ class IntegrationGateway:``SensorResponse.has_event_video_snapshot`` — only call whenthe flag is True."""return None++ def get_external_view_data(self, entity: Entity) -> Optional[ExternalViewData]:+ """Return the external-data view payload for the entity-detail+ modal. Return ``None`` if this integration has no external view+ for ``entity`` — the external-data region is then suppressed.++ Defaults to ``None``; integrations whose data lives upstream+ override this hook to return a populated ``ExternalViewData``+ subclass (typically ``StructuredViewData``)."""+ return Nonediff --git a/src/hi/integrations/templates/integrations/external_data/entity/header.html b/src/hi/integrations/templates/integrations/external_data/entity/header.htmlnew file mode 100644index 00000000..72d98c56--- /dev/null+++ b/src/hi/integrations/templates/integrations/external_data/entity/header.html@@ -0,0 +1,18 @@+{% load static integration_tags %}+{% integration_logo_path entity as integration_logo %}+{% integration_display_name entity as integration_name %}++<div class="attr-ext-header d-flex align-items-center">+ <div class="attr-ext-header__brand d-flex align-items-center">+ {% if integration_logo %}+ <img class="attr-ext-header__logo" src="{% static integration_logo %}" alt="{{ integration_name }} logo">+ {% endif %}+ <span class="text-muted small">From {{ integration_name }}</span>+ </div>+ {% if view_data.deep_link_url %}+ <a class="btn btn-sm btn-outline-primary ml-auto"+ href="{{ view_data.deep_link_url }}"+ target="_blank"+ rel="noopener noreferrer">Open in {{ integration_name }} →</a>+ {% endif %}+</div>diff --git a/src/hi/integrations/templates/integrations/external_data/entity/minimal.html b/src/hi/integrations/templates/integrations/external_data/entity/minimal.htmlnew file mode 100644index 00000000..03508dbe--- /dev/null+++ b/src/hi/integrations/templates/integrations/external_data/entity/minimal.html@@ -0,0 +1,13 @@+<div class="attr-v2-external-minimal">++ {% include "integrations/external_data/entity/header.html" %}++ {% if view_data.error_message %}+ <div class="alert alert-warning attr-ext-minimal-error" role="alert">+ {{ view_data.error_message }}+ </div>+ {% elif not view_data.deep_link_url %}+ <p class="text-muted">External data unavailable.</p>+ {% endif %}++</div>diff --git a/src/hi/integrations/templates/integrations/external_data/entity/structured.html b/src/hi/integrations/templates/integrations/external_data/entity/structured.htmlnew file mode 100644index 00000000..68ffeac1--- /dev/null+++ b/src/hi/integrations/templates/integrations/external_data/entity/structured.html@@ -0,0 +1,71 @@+{% load icons %}++<div class="attr-v2-external-structured">++ {% include "integrations/external_data/entity/header.html" %}++ {% if view_data.attachments %}+ <div class="attr-v2-file-section attr-ext-attachments">+ <div class="attr-v2-file-grid">+ {% for attachment in view_data.attachments %}+ <div class="attr-v2-file-card attr-ext-attachment"+ data-mime-type="{{ attachment.mime_type }}">+ <a class="attr-ext-attachment__link"+ href="{{ attachment.open_url }}"+ target="_blank"+ rel="noopener noreferrer"+ title="{{ attachment.title }}">+ <div class="attr-v2-file-thumbnail{% if attachment.thumbnail_url %} has-thumbnail{% endif %}">+ {% if attachment.thumbnail_url %}+ <img src="{{ attachment.thumbnail_url }}"+ alt="{{ attachment.title }}"+ class="attr-v2-file-thumbnail-image"+ loading="lazy"+ decoding="async">+ {% else %}+ {% if attachment.mime_type|slice:":5" == "image" %}+ {% icon "camera" size="lg" %}+ <div class="attr-v2-file-type-label">IMAGE</div>+ {% elif attachment.mime_type == "application/pdf" %}+ {% icon "upload" size="lg" %}+ <div class="attr-v2-file-type-label">PDF</div>+ {% elif attachment.mime_type|slice:":5" == "video" %}+ {% icon "video" size="lg" %}+ <div class="attr-v2-file-type-label">VIDEO</div>+ {% else %}+ {% icon "upload" size="lg" %}+ <div class="attr-v2-file-type-label">FILE</div>+ {% endif %}+ {% endif %}+ </div>+ <div class="attr-v2-file-info">+ <div class="attr-v2-file-name">{{ attachment.title }}</div>+ </div>+ </a>+ </div>+ {% endfor %}+ </div>+ </div>+ {% endif %}++ {% if view_data.attributes %}+ <div class="attr-v2-attribute-list attr-ext-attribute-list">+ {% for pair in view_data.attributes %}+ <div class="attr-v2-attribute-card attr-ext-attribute-card">+ <div class="attr-v2-attribute-header">+ <div class="attr-v2-attribute-name">+ <input type="text"+ value="{{ pair.name }}"+ class="attr-v2-title-input"+ disabled>+ </div>+ </div>+ <div class="attr-v2-attribute-value">+ <div class="attr-ext-value attr-ext-value--clamped">{{ pair.value }}</div>+ </div>+ </div>+ {% endfor %}+ </div>+ {% endif %}++</div>diff --git a/src/hi/integrations/tests/test_entity_operations.py b/src/hi/integrations/tests/test_entity_operations.pyindex 7db63b14..b392cb9f 100644--- a/src/hi/integrations/tests/test_entity_operations.py+++ b/src/hi/integrations/tests/test_entity_operations.py@@ -242,7 +242,7 @@ class PreserveWithUserDataFlagTests(TestCase):integration_id='test_integration',integration_name='locked_device',can_user_delete=False,- can_add_custom_attributes=False,+ allow_internal_attributes=False,)# Has user data so it qualifies for preservation.EntityAttribute.objects.create(@@ -261,7 +261,7 @@ class PreserveWithUserDataFlagTests(TestCase):entity.refresh_from_db()self.assertIsNone(entity.integration_id)self.assertTrue(entity.can_user_delete)- self.assertTrue(entity.can_add_custom_attributes)+ self.assertTrue(entity.allow_internal_attributes)def test_disconnected_entity_capabilities_are_suppressed(self):"""diff --git a/src/hi/integrations/tests/test_external_view_data.py b/src/hi/integrations/tests/test_external_view_data.pynew file mode 100644index 00000000..cf398491--- /dev/null+++ b/src/hi/integrations/tests/test_external_view_data.py@@ -0,0 +1,82 @@+"""Tests for the IntegrationGateway base-class default behavior+around the external-view-data hook plus basic shape checks on the+ExternalViewData dataclass hierarchy.++The gateway hook defaults to None so integrations without an+external-view override automatically suppress the entity-detail+modal's external-data view region. Pinning this default catches+accidental override drift on the base class.+"""+import logging++from django.test import TestCase++from hi.integrations.external_view_data import (+ AttachmentRef,+ CustomTemplateViewData,+ MinimalViewData,+ NameValuePair,+ StructuredViewData,+)+from hi.integrations.integration_gateway import IntegrationGateway++logging.disable(logging.CRITICAL)+++class IntegrationGatewayExternalViewDataDefaultTests(TestCase):++ def test_get_external_view_data_defaults_to_none(self):+ gateway = IntegrationGateway()+ self.assertIsNone(gateway.get_external_view_data(entity=None))+++class ExternalViewDataDefaultTemplateNameTests(TestCase):+ """Each subclass has a load-bearing default template_name that+ drives the external-data view include. Direct assertions guard+ against silent renames of the framework partials."""++ def test_structured_view_data_default_template_name(self):+ instance = StructuredViewData(+ attributes=[NameValuePair(name='k', value='v')],+ )+ self.assertEqual(+ instance.template_name,+ 'integrations/external_data/entity/structured.html',+ )++ def test_minimal_view_data_default_template_name(self):+ instance = MinimalViewData(deep_link_url='https://example/')+ self.assertEqual(+ instance.template_name,+ 'integrations/external_data/entity/minimal.html',+ )++ def test_custom_template_view_data_takes_explicit_template_name(self):+ instance = CustomTemplateViewData(+ template_name='services/foo/templates/foo/custom.html',+ context={'k': 'v'},+ )+ self.assertEqual(+ instance.template_name,+ 'services/foo/templates/foo/custom.html',+ )++ def test_structured_view_data_carries_attachments_independently(self):+ instance = StructuredViewData(+ attachments=[+ AttachmentRef(id='a', title='A', mime_type='image/png'),+ ],+ )+ self.assertEqual(len(instance.attachments), 1)+ self.assertEqual(instance.attributes, [])++ def test_custom_template_view_data_requires_template_name(self):+ """CustomTemplateViewData has no usable default template_name —+ the empty default would silently misroute the include. Empty+ and whitespace-only values must fail loudly at construction."""+ with self.assertRaises(ValueError):+ CustomTemplateViewData()+ with self.assertRaises(ValueError):+ CustomTemplateViewData(template_name='')+ with self.assertRaises(ValueError):+ CustomTemplateViewData(template_name=' ')diff --git a/src/hi/integrations/transient_models.py b/src/hi/integrations/transient_models.pyindex c28d9cf1..232252ff 100644--- a/src/hi/integrations/transient_models.py+++ b/src/hi/integrations/transient_models.py@@ -13,7 +13,7 @@ class IntegrationMetaData:label : str # For human-friendly displayingattribute_type : IntegrationAttributeTypeallow_entity_deletion : bool- can_add_custom_attributes : bool = True+ allow_internal_attributes : bool = Truelogo_static_path : str = 'img/integrations/default.svg'diff --git a/src/hi/services/hass/hass_converter.py b/src/hi/services/hass/hass_converter.pyindex 8e094801..db1bb16d 100644--- a/src/hi/services/hass/hass_converter.py+++ b/src/hi/services/hass/hass_converter.py@@ -592,7 +592,7 @@ class HassConverter:"""Refresh integration-owned components on an existing entity.``entity.name`` and ``entity.entity_type`` are user-editable- in HI's UI on HASS entities (``can_add_custom_attributes``+ in HI's UI on HASS entities (``allow_internal_attributes``defaults to True), so they're treated as user-owned aftercreation: this method does not touch them on update. Theoperator's choice of name and type sticks across refreshes.diff --git a/src/hi/services/hass/tests/test_hass_converter_create.py b/src/hi/services/hass/tests/test_hass_converter_create.pyindex 51e3e04a..a646fb38 100644--- a/src/hi/services/hass/tests/test_hass_converter_create.py+++ b/src/hi/services/hass/tests/test_hass_converter_create.py@@ -234,7 +234,7 @@ class CreateModelsForHassDeviceReconnectContractTests(TestCase):class UpdateModelsForHassDeviceContractTests(TestCase):"""Pin that ``update_models_for_hass_device`` treats user-editablefields (``name``, ``entity_type``) as user-owned after creation.- HASS entities default ``can_add_custom_attributes=True`` so the+ HASS entities default ``allow_internal_attributes=True`` so theoperator can edit name/type via the entity-edit modal; onceedited, refreshes must not silently revert those changes."""diff --git a/src/hi/services/homebox/connector/__init__.py b/src/hi/services/homebox/connector/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/services/homebox/connector/hb_connector.py b/src/hi/services/homebox/connector/hb_connector.pynew file mode 100644index 00000000..9e934876--- /dev/null+++ b/src/hi/services/homebox/connector/hb_connector.py@@ -0,0 +1,141 @@+"""+HomeBox Connect-mode resolver. Fetches the live HomeBox item state+on each modal open; returns ``StructuredViewData`` on success or+``MinimalViewData`` on failure.+"""+import logging+from typing import List, Optional+from urllib.parse import urljoin++from django.urls import reverse++from hi.apps.entity.models import Entity+from hi.integrations.external_view_data import (+ AttachmentRef,+ ExternalViewData,+ MinimalViewData,+ NameValuePair,+ StructuredViewData,+)++from hi.services.homebox.shared.hb_converter import HB_ITEM_FIELD_PAIRS+from hi.services.homebox.shared.hb_manager import HomeBoxManager+from hi.services.homebox.shared.hb_models import HbItem++logger = logging.getLogger(__name__)+++class HomeBoxConnector:+ """Stateless resolver for the entity-detail external-data view hook."""++ def get_external_view_data(self, entity: Entity) -> Optional[ExternalViewData]:+ item_id = entity.integration_name+ if not item_id:+ return None++ deep_link_url = self._build_deep_link_url(item_id)++ try:+ hb_manager = HomeBoxManager()+ hb_manager.ensure_initialized()+ hb_item = hb_manager.fetch_hb_item_from_api(item_id=item_id, verbose=False)+ except Exception as e:+ logger.warning(+ f'HomeBox Connect resolver: failed to fetch item {item_id} '+ f'for entity {entity.id}: {e}'+ )+ return MinimalViewData(+ deep_link_url=deep_link_url,+ error_message=f'HomeBox upstream unavailable: {e}',+ )++ return StructuredViewData(+ deep_link_url=deep_link_url,+ attributes=self._build_attributes(hb_item),+ attachments=self._build_attachments(entity, hb_item),+ )++ def _build_attributes(self, hb_item: HbItem) -> List[NameValuePair]:+ rows: List[NameValuePair] = []++ for prop_name, label in HB_ITEM_FIELD_PAIRS:+ value = getattr(hb_item, prop_name, None)+ if value is None:+ continue+ value_str = str(value).strip()+ if not value_str:+ continue+ rows.append(NameValuePair(name=label, value=value_str))++ for hb_field in (hb_item.fields or []):+ if not isinstance(hb_field, dict):+ continue+ name = str(hb_field.get('name', '')).strip()+ value = str(hb_field.get('textValue', '')).strip()+ if not name or not value:+ continue+ rows.append(NameValuePair(name=name, value=value))++ tags = hb_item.tags or []+ tag_names = [+ str(tag.get('name', '')).strip()+ for tag in tags+ if isinstance(tag, dict) and str(tag.get('name', '')).strip()+ ]+ if tag_names:+ rows.append(NameValuePair(name='Tags', value=', '.join(tag_names)))++ return rows++ def _build_attachments(self, entity: Entity, hb_item: HbItem) -> List[AttachmentRef]:+ refs: List[AttachmentRef] = []+ for attachment in (hb_item.attachments or []):+ if not isinstance(attachment, dict):+ continue+ attachment_id = str(attachment.get('id', '') or '').strip()+ if not attachment_id:+ continue+ title = str(attachment.get('title', '') or '').strip() or f'Attachment {attachment_id}'+ mime_type = str(attachment.get('mimeType', '') or '').strip()++ attachment_url = self._build_proxy_url(entity.id, attachment_id)++ thumbnail_id = ''+ thumbnail_info = attachment.get('thumbnail')+ if isinstance(thumbnail_info, dict):+ thumbnail_id = str(thumbnail_info.get('id', '') or '').strip()+ thumbnail_url = (+ self._build_proxy_url(entity.id, thumbnail_id)+ if thumbnail_id else None+ )++ refs.append(AttachmentRef(+ id=attachment_id,+ title=title,+ mime_type=mime_type,+ thumbnail_url=thumbnail_url,+ open_url=attachment_url,+ ))+ return refs++ def _build_proxy_url(self, entity_id: int, attachment_id: str) -> str:+ return reverse(+ 'homebox_attachment_proxy',+ kwargs={'entity_id': entity_id, 'attachment_id': attachment_id},+ )++ def _build_deep_link_url(self, item_id: str) -> Optional[str]:+ """Best-effort: strip a trailing ``/api`` from the configured+ URL and append ``/item/<id>``. Returns None if no API URL is+ configured."""+ hb_manager = HomeBoxManager()+ if not hb_manager.hb_client:+ return None+ api_url = hb_manager.hb_client.api_url+ if not api_url:+ return None+ if api_url.endswith('/api'):+ web_base = api_url[:-len('/api')]+ else:+ web_base = api_url+ return urljoin(web_base + '/', f'item/{item_id}')diff --git a/src/hi/services/homebox/connector/proxy_views.py b/src/hi/services/homebox/connector/proxy_views.pynew file mode 100644index 00000000..550439eb--- /dev/null+++ b/src/hi/services/homebox/connector/proxy_views.py@@ -0,0 +1,62 @@+"""+HomeBox attachment proxy. HomeBox requires bearer-token auth so the+browser cannot fetch attachments directly; the proxy fetches+server-side and streams bytes back with the upstream content-type.+"""+import logging++from django.http import Http404, HttpResponse+from django.views import View++from hi.apps.entity.models import Entity+from hi.services.homebox.hb_metadata import HbMetaData+from hi.services.homebox.shared.hb_manager import HomeBoxManager++logger = logging.getLogger(__name__)+++class HomeBoxAttachmentProxyView(View):++ def get(self, request, entity_id: int, attachment_id: str):+ try:+ entity = Entity.objects.get(+ pk=entity_id,+ integration_id=HbMetaData.integration_id,+ )+ except Entity.DoesNotExist:+ raise Http404('Entity not found or not a HomeBox entity.')++ item_id = entity.integration_name+ if not item_id:+ raise Http404('Entity has no HomeBox item id.')++ hb_manager = HomeBoxManager()+ hb_manager.ensure_initialized()+ if not hb_manager.hb_client:+ return HttpResponse(status=503, content='HomeBox integration unavailable.')++ try:+ downloaded = hb_manager.hb_client.download_attachment(+ item_id=item_id,+ attachment_id=attachment_id,+ )+ except Exception as e:+ # Upstream connectivity / auth / HTTP failure during the+ # download itself. Surface as a 502 (bad gateway) rather+ # than 404 so the browser and ops can tell upstream+ # trouble apart from a genuinely-missing attachment.+ logger.warning(+ f'HomeBox attachment proxy: download failed for entity '+ f'{entity_id} attachment {attachment_id}: {e}'+ )+ return HttpResponse(status=502, content='HomeBox upstream error.')++ if not downloaded:+ raise Http404('Attachment not returned by HomeBox.')++ content = downloaded.get('content')+ mime_type = downloaded.get('mime_type') or 'application/octet-stream'+ if content is None:+ raise Http404('Attachment empty.')++ return HttpResponse(content=content, content_type=mime_type)diff --git a/src/hi/services/homebox/hb_metadata.py b/src/hi/services/homebox/hb_metadata.pyindex 69e2e26f..f877c27d 100644--- a/src/hi/services/homebox/hb_metadata.py+++ b/src/hi/services/homebox/hb_metadata.py@@ -8,6 +8,6 @@ HbMetaData = IntegrationMetaData(label = 'HomeBox',attribute_type = HbAttributeType,allow_entity_deletion = False,- can_add_custom_attributes = False,+ allow_internal_attributes = False,logo_static_path = 'img/integrations/homebox.svg',)diff --git a/src/hi/services/homebox/hb_mixins.py b/src/hi/services/homebox/hb_mixins.pyindex 576bd3f5..0e72d6ed 100644--- a/src/hi/services/homebox/hb_mixins.py+++ b/src/hi/services/homebox/hb_mixins.py@@ -2,7 +2,7 @@ from asgiref.sync import sync_to_asyncimport asyncioimport logging-from .hb_manager import HomeBoxManager+from .shared.hb_manager import HomeBoxManagerlogger = logging.getLogger(__name__)diff --git a/src/hi/services/homebox/importer/__init__.py b/src/hi/services/homebox/importer/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/services/homebox/importer/hb_importer.py b/src/hi/services/homebox/importer/hb_importer.pynew file mode 100644index 00000000..7aa7e5ec--- /dev/null+++ b/src/hi/services/homebox/importer/hb_importer.py@@ -0,0 +1,175 @@+from typing import Dict, List, Optional+import logging++from django.db import transaction++from hi.apps.entity.models import Entity, EntityAttribute++from hi.services.homebox.hb_metadata import HbMetaData+from hi.services.homebox.shared.hb_converter import HbConverter+from hi.services.homebox.shared.hb_models import HbItem++logger = logging.getLogger(__name__)+++class HbImporter:++ @classmethod+ def create_models_for_hb_item( cls,+ hb_item : HbItem,+ entity : Optional[Entity] = None ) -> Entity:+ """+ Create or repopulate the integration-owned components for an+ HbItem. When ``entity`` is None (the standard import path), a+ fresh Entity is created from the upstream payload. When+ ``entity`` is provided (the auto-reconnect path from Issue+ #281), the integration-owned fields on that entity are+ repopulated; the entity's ``name`` is deliberately preserved+ because the user may have edited it before/after the+ intervening disconnect.+ """+ with transaction.atomic():+ entity_integration_key = HbConverter.hb_item_to_integration_key( hb_item = hb_item )+ entity_payload = HbConverter.hb_item_to_entity_payload( hb_item = hb_item )++ if entity is None:+ entity = Entity(+ name = HbConverter.hb_item_to_entity_name( hb_item = hb_item ),+ entity_type_str = str( HbConverter.hb_item_to_entity_type( hb_item = hb_item ) ),+ )++ # The fields below apply equally to fresh-create and+ # reconnect: integration_key, integration_payload, and the+ # integration-managed access flags are all integration-owned+ # and must reflect the current upstream state. The entity+ # name and entity_type are intentionally left alone on the+ # reconnect path (set above only for fresh-create).+ entity.integration_key = entity_integration_key+ entity.integration_payload = entity_payload+ entity.can_user_delete = HbMetaData.allow_entity_deletion+ entity.allow_internal_attributes = HbMetaData.allow_internal_attributes+ entity.save()++ return entity++ @classmethod+ def update_models_for_hb_item( cls, entity : Entity, hb_item ) -> List[str]:+ messages = list()++ with transaction.atomic():+ entity_name = HbConverter.hb_item_to_entity_name( hb_item = hb_item )+ if entity.name != entity_name:+ messages.append( f'Name changed for {entity}. Setting to "{entity_name}"' )+ entity.name = entity_name++ desired_entity_type = HbConverter.hb_item_to_entity_type( hb_item = hb_item )+ if entity.entity_type != desired_entity_type:+ messages.append( f'Entity type changed for {entity}. Setting to "{desired_entity_type}"' )+ entity.entity_type = desired_entity_type++ if entity.allow_internal_attributes != HbMetaData.allow_internal_attributes:+ messages.append( f'allow_internal_attributes changed for {entity}.' )+ entity.allow_internal_attributes = HbMetaData.allow_internal_attributes++ new_payload = HbConverter.hb_item_to_entity_payload( hb_item = hb_item )+ if entity.integration_payload != new_payload:+ entity.integration_payload = new_payload+ messages.append( f'Integration payload updated for {entity}.' )++ if messages:+ entity.save()++ return messages++ @classmethod+ def create_attribute_from_hb_field( cls,+ entity: Entity,+ hb_field: Dict,+ order_id: int ) -> Optional[EntityAttribute]:+ payload = HbConverter.hb_field_to_attribute_payload(+ hb_field = hb_field,+ order_id = order_id,+ )+ if not payload:+ return None++ return EntityAttribute.objects.create(+ entity = entity,+ **payload,+ )++ @classmethod+ def update_attribute_from_hb_field( cls,+ attribute: EntityAttribute,+ hb_field: Dict,+ order_id: int ) -> bool:+ payload = HbConverter.hb_field_to_attribute_payload(+ hb_field = hb_field,+ order_id = order_id,+ )+ if not payload:+ return False++ incoming_file = payload.pop( 'file_value', None )++ was_changed = False+ for field_name, field_value in payload.items():+ if getattr( attribute, field_name ) != field_value:+ setattr( attribute, field_name, field_value )+ was_changed = True++ # Only update file content when needed; this avoids rewriting the same file on each sync.+ if incoming_file and not attribute.file_value:+ attribute.file_value = incoming_file+ was_changed = True++ if was_changed:+ attribute.save()++ return was_changed++ @classmethod+ def create_attribute_from_hb_attachment( cls,+ entity: Entity,+ hb_attachment: Dict,+ order_id: int ) -> Optional[EntityAttribute]:+ payload = HbConverter.hb_attachment_to_attribute_payload(+ hb_attachment = hb_attachment,+ order_id = order_id,+ )+ if not payload:+ return None++ return EntityAttribute.objects.create(+ entity = entity,+ **payload,+ )++ @classmethod+ def update_attribute_from_hb_attachment( cls,+ attribute: EntityAttribute,+ hb_attachment: Dict,+ order_id: int ) -> bool:+ payload = HbConverter.hb_attachment_to_attribute_payload(+ hb_attachment = hb_attachment,+ order_id = order_id,+ )+ if not payload:+ return False++ incoming_file = payload.pop( 'file_value', None )++ was_changed = False+ for field_name, field_value in payload.items():+ if getattr( attribute, field_name ) != field_value:+ setattr( attribute, field_name, field_value )+ was_changed = True++ if incoming_file and not attribute.file_value:+ attribute.file_value = incoming_file+ was_changed = True++ if was_changed:+ attribute.save()++ return was_changeddiff --git a/src/hi/services/homebox/hb_sync.py b/src/hi/services/homebox/importer/hb_sync.pysimilarity index 94%rename from src/hi/services/homebox/hb_sync.pyrename to src/hi/services/homebox/importer/hb_sync.pyindex 49cdca31..6302366a 100644--- a/src/hi/services/homebox/hb_sync.py+++ b/src/hi/services/homebox/importer/hb_sync.py@@ -11,10 +11,11 @@ from hi.integrations.sync_check import IntegrationSyncCheck, SyncDeltafrom hi.integrations.sync_result import IntegrationSyncResultfrom hi.integrations.transient_models import IntegrationKey-from .hb_converter import HbConverter-from .hb_metadata import HbMetaData-from .hb_mixins import HomeBoxMixin-from .hb_models import HbItem+from hi.services.homebox.shared.hb_converter import HbConverter+from hi.services.homebox.hb_metadata import HbMetaData+from hi.services.homebox.hb_mixins import HomeBoxMixin+from hi.services.homebox.shared.hb_models import HbItem+from .hb_importer import HbImporterlogger = logging.getLogger(__name__)@@ -181,11 +182,7 @@ class HomeBoxSynchronizer( IntegrationSynchronizer, HomeBoxMixin ):entity = self._create_entity( item = hb_item, result = result )created_entities.append( entity )- self._sync_helper_entity_attributes(- entity = entity,- hb_item = hb_item,- result = result,- )+ # Attributes are fetched live by the connector.continuefor integration_key, entity in integration_key_to_entity.items():@@ -198,11 +195,10 @@ class HomeBoxSynchronizer( IntegrationSynchronizer, HomeBoxMixin ):entity : Entity,upstream : HbItem,result : IntegrationSyncResult ):- """Issue #281: dispatch to the HomeBox converter with the- existing-entity parameter set, so the converter repopulates- integration-owned components on the previously-disconnected- entity rather than creating a fresh one."""- HbConverter.create_models_for_hb_item(+ """Reconnect hook: dispatch to ``HbImporter`` with the existing+ entity so integration-owned components are repopulated on the+ previously-disconnected entity rather than creating a new one."""+ HbImporter.create_models_for_hb_item(hb_item = upstream,entity = entity,)@@ -231,7 +227,7 @@ class HomeBoxSynchronizer( IntegrationSynchronizer, HomeBoxMixin ):def _create_entity( self,item : HbItem,result : IntegrationSyncResult ) -> Entity:- entity = HbConverter.create_models_for_hb_item( hb_item = item )+ entity = HbImporter.create_models_for_hb_item( hb_item = item )result.created_list.append( entity.name )return entity@@ -242,7 +238,7 @@ class HomeBoxSynchronizer( IntegrationSynchronizer, HomeBoxMixin ):# update_models_for_hb_item returns a list of change# description strings — non-empty means at least one# operator-visible change was made.- change_messages = HbConverter.update_models_for_hb_item(+ change_messages = HbImporter.update_models_for_hb_item(entity = entity, hb_item = item,)if change_messages and entity.name not in result.updated_list:@@ -389,7 +385,7 @@ class HomeBoxSynchronizer( IntegrationSynchronizer, HomeBoxMixin ):entity: Entity,hb_field: dict,order_id: int ) -> EntityAttribute:- return HbConverter.create_attribute_from_hb_field(+ return HbImporter.create_attribute_from_hb_field(entity = entity,hb_field = hb_field,order_id = order_id,@@ -401,7 +397,7 @@ class HomeBoxSynchronizer( IntegrationSynchronizer, HomeBoxMixin ):order_id: int,message_list: List[str],updated_prefix: str ):- was_changed = HbConverter.update_attribute_from_hb_field(+ was_changed = HbImporter.update_attribute_from_hb_field(attribute = attribute,hb_field = hb_field,order_id = order_id,@@ -433,7 +429,7 @@ class HomeBoxSynchronizer( IntegrationSynchronizer, HomeBoxMixin ):entity: Entity,hb_attachment: dict,order_id: int ) -> EntityAttribute:- return HbConverter.create_attribute_from_hb_attachment(+ return HbImporter.create_attribute_from_hb_attachment(entity = entity,hb_attachment = hb_attachment,order_id = order_id,@@ -445,7 +441,7 @@ class HomeBoxSynchronizer( IntegrationSynchronizer, HomeBoxMixin ):order_id: int,message_list: List[str],updated_prefix: str ):- was_changed = HbConverter.update_attribute_from_hb_attachment(+ was_changed = HbImporter.update_attribute_from_hb_attachment(attribute = attribute,hb_attachment = hb_attachment,order_id = order_id,diff --git a/src/hi/services/homebox/integration.py b/src/hi/services/homebox/integration.pyindex 9fd856bb..4236b108 100644--- a/src/hi/services/homebox/integration.py+++ b/src/hi/services/homebox/integration.py@@ -1,9 +1,11 @@import loggingfrom typing import List, Optional+from hi.apps.entity.models import Entityfrom hi.apps.system.enums import HealthStatusTypefrom hi.apps.system.health_status_provider import HealthStatusProvider+from hi.integrations.external_view_data import ExternalViewDatafrom hi.integrations.integration_controller import IntegrationControllerfrom hi.integrations.integration_gateway import IntegrationGatewayfrom hi.integrations.integration_manage_view_pane import IntegrationManageViewPane@@ -18,9 +20,9 @@ from hi.apps.monitor.periodic_monitor import PeriodicMonitorfrom .hb_controller import HomeBoxControllerfrom .hb_manage_view_pane import HbManageViewPane-from .hb_manager import HomeBoxManager+from .shared.hb_manager import HomeBoxManagerfrom .hb_metadata import HbMetaData-from .hb_sync import HomeBoxSynchronizer+from .importer.hb_sync import HomeBoxSynchronizerfrom .monitors import HomeBoxMonitorlogger = logging.getLogger(__name__)@@ -87,3 +89,7 @@ class HomeBoxGateway(IntegrationGateway):except Exception as e:logger.exception(f'Error in HomeBox connection test: {e}')return ConnectionTestResult.failure(f'Connection test error: {e}')++ def get_external_view_data(self, entity: Entity) -> Optional[ExternalViewData]:+ from .connector.hb_connector import HomeBoxConnector+ return HomeBoxConnector().get_external_view_data(entity)diff --git a/src/hi/services/homebox/shared/__init__.py b/src/hi/services/homebox/shared/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/services/homebox/hb_client.py b/src/hi/services/homebox/shared/hb_client.pysimilarity index 82%rename from src/hi/services/homebox/hb_client.pyrename to src/hi/services/homebox/shared/hb_client.pyindex 65ae9f6d..a64be839 100644--- a/src/hi/services/homebox/hb_client.py+++ b/src/hi/services/homebox/shared/hb_client.py@@ -16,10 +16,10 @@ class HbClient:API_VERSION = 'v1'def __init__(self, api_options: Dict[str, str], timeout_secs: Optional[float] = None):- self._api_url = api_options.get(self.API_URL)- assert self._api_url is not None- if self._api_url.endswith('/'):- self._api_url = self._api_url[:-1]+ self.api_url = api_options.get(self.API_URL)+ assert self.api_url is not None+ if self.api_url.endswith('/'):+ self.api_url = self.api_url[:-1]self._user = api_options.get(self.API_USER)assert self._user is not None@@ -43,7 +43,7 @@ class HbClient:self._authenticated = Falsedef _login(self):- url = f"{self._api_url}/{self.API_VERSION}/users/login"+ url = f"{self.api_url}/{self.API_VERSION}/users/login"data = {'username': self._user,'password': self._password,@@ -53,7 +53,7 @@ class HbClient:response = self._session.post(url, json=data, timeout=self._timeout_secs)except Exception as e:raise ConnectionError(- f'Cannot connect to HomeBox at {self._api_url}. '+ f'Cannot connect to HomeBox at {self.api_url}. 'f'Verify the API URL is correct and the server is running.') from e@@ -114,7 +114,7 @@ class HbClient:as a clear ValueError instead of letting downstream callersiterate the response as bytes."""- url_list = f"{self._api_url}/{self.API_VERSION}/items"+ url_list = f"{self.api_url}/{self.API_VERSION}/items"data = self._make_request('GET', url_list)if not isinstance(data, dict):raise ValueError(@@ -124,6 +124,22 @@ class HbClient:)return data.get('items', [])+ def get_item(self, item_id: str) -> HbItem:+ """Fetches a single item's full detail. Used by the Connect-mode+ on-demand resolver (each entity-detail modal open triggers one+ call). Returns the populated HbItem.++ Errors propagate to the caller (auth/network/HTTP errors). The+ Connect resolver wraps this call and degrades to a deep-link-only+ placeholder on failure rather than crashing the modal render."""+ url = f"{self.api_url}/{self.API_VERSION}/items/{item_id}"+ item_detail = self._make_request('GET', url)+ if not isinstance(item_detail, dict):+ raise ValueError(+ f'HomeBox returned non-JSON response for item {item_id}.'+ )+ return HbItem(api_dict=item_detail, client=self)+def get_items(self) -> List[HbItem]:"""Fetches the list of items and, for each one, fetches the full details.@@ -143,15 +159,13 @@ class HbClient:for summary in items_summary:item_id = summary.get('id')if item_id:- url_detail = f"{self._api_url}/{self.API_VERSION}/items/{item_id}"- item_detail = self._make_request('GET', url_detail)- full_items.append(HbItem(api_dict=item_detail, client=self))+ full_items.append(self.get_item(item_id))return full_itemsdef download_attachment(self, item_id: str, attachment_id: str) -> Optional[Dict[str, Any]]:"""Downloads an attachment """- url = f"{self._api_url}/{self.API_VERSION}/items/{item_id}/attachments/{attachment_id}"+ url = f"{self.api_url}/{self.API_VERSION}/items/{item_id}/attachments/{attachment_id}"response = self._make_request('GET', url)if not isinstance(response, Response):diff --git a/src/hi/services/homebox/hb_client_factory.py b/src/hi/services/homebox/shared/hb_client_factory.pysimilarity index 97%rename from src/hi/services/homebox/hb_client_factory.pyrename to src/hi/services/homebox/shared/hb_client_factory.pyindex ef7572a3..c6267268 100644--- a/src/hi/services/homebox/hb_client_factory.py+++ b/src/hi/services/homebox/shared/hb_client_factory.py@@ -8,9 +8,9 @@ from hi.integrations.exceptions import IntegrationAttributeErrorfrom hi.integrations.models import IntegrationAttributefrom hi.integrations.transient_models import IntegrationKey, IntegrationValidationResult-from .enums import HbAttributeType+from hi.services.homebox.enums import HbAttributeTypefrom .hb_client import HbClient-from .hb_metadata import HbMetaData+from hi.services.homebox.hb_metadata import HbMetaDatalogger = logging.getLogger(__name__)diff --git a/src/hi/services/homebox/hb_converter.py b/src/hi/services/homebox/shared/hb_converter.pysimilarity index 60%rename from src/hi/services/homebox/hb_converter.pyrename to src/hi/services/homebox/shared/hb_converter.pyindex 2900e1c6..2ac414c0 100644--- a/src/hi/services/homebox/hb_converter.py+++ b/src/hi/services/homebox/shared/hb_converter.py@@ -2,96 +2,39 @@ from typing import Dict, List, Optionalimport mimetypesimport os-from django.db import transactionfrom django.core.files.base import ContentFilefrom hi.apps.attribute.enums import AttributeType, AttributeValueTypefrom hi.apps.entity.enums import EntityType-from hi.apps.entity.models import Entity, EntityAttributefrom hi.integrations.transient_models import IntegrationKey-from .hb_metadata import HbMetaData+from hi.services.homebox.hb_metadata import HbMetaDatafrom .hb_models import HbItemimport logginglogger = logging.getLogger(__name__)-class HbConverter:-- HB_ITEM_ATTRIBUTE_FIELD_MAP = [- ( 'description', 'Description' ),- ( 'serial_number', 'Serial Number' ),- ( 'model_number', 'Model Number' ),- ( 'manufacturer', 'Manufacturer' ),- ]-- @classmethod- def create_models_for_hb_item( cls,- hb_item : HbItem,- entity : Optional[Entity] = None ) -> Entity:- """- Create or repopulate the integration-owned components for an- HbItem. When ``entity`` is None (the standard import path), a- fresh Entity is created from the upstream payload. When- ``entity`` is provided (the auto-reconnect path from Issue- #281), the integration-owned fields on that entity are- repopulated; the entity's ``name`` is deliberately preserved- because the user may have edited it before/after the- intervening disconnect.- """- with transaction.atomic():- entity_integration_key = cls.hb_item_to_integration_key( hb_item = hb_item )- entity_payload = cls.hb_item_to_entity_payload( hb_item = hb_item )-- if entity is None:- entity = Entity(- name = cls.hb_item_to_entity_name( hb_item = hb_item ),- entity_type_str = str( cls.hb_item_to_entity_type( hb_item = hb_item ) ),- )-- # The fields below apply equally to fresh-create and- # reconnect: integration_key, integration_payload, and the- # integration-managed access flags are all integration-owned- # and must reflect the current upstream state. The entity- # name and entity_type are intentionally left alone on the- # reconnect path (set above only for fresh-create).- entity.integration_key = entity_integration_key- entity.integration_payload = entity_payload- entity.can_user_delete = HbMetaData.allow_entity_deletion- entity.can_add_custom_attributes = HbMetaData.can_add_custom_attributes- entity.save()-- return entity-- @classmethod- def update_models_for_hb_item( cls, entity : Entity, hb_item ) -> List[str]:- messages = list()-- with transaction.atomic():- entity_name = cls.hb_item_to_entity_name( hb_item = hb_item )- if entity.name != entity_name:- messages.append( f'Name changed for {entity}. Setting to "{entity_name}"' )- entity.name = entity_name-- desired_entity_type = cls.hb_item_to_entity_type( hb_item = hb_item )- if entity.entity_type != desired_entity_type:- messages.append( f'Entity type changed for {entity}. Setting to "{desired_entity_type}"' )- entity.entity_type = desired_entity_type+# Canonical mapping of HbItem properties to user-visible labels. Shared+# by the Connect-mode resolver (live read-only display) and the+# importer's synthetic-field generation so both surfaces expose the+# same set of HomeBox item metadata.+# (HbItem property, display label)+HB_ITEM_FIELD_PAIRS = [+ ( 'description', 'Description' ),+ ( 'manufacturer', 'Manufacturer' ),+ ( 'model_number', 'Model Number' ),+ ( 'serial_number', 'Serial Number' ),+ ( 'asset_id', 'Asset ID' ),+ ( 'purchase_from', 'Purchased From' ),+ ( 'purchase_time', 'Purchase Date' ),+ ( 'warranty_details', 'Warranty Details' ),+ ( 'warranty_expires', 'Warranty Expires' ),+ ( 'notes', 'Notes' ),+]- if entity.can_add_custom_attributes != HbMetaData.can_add_custom_attributes:- messages.append( f'can_add_custom_attributes changed for {entity}.' )- entity.can_add_custom_attributes = HbMetaData.can_add_custom_attributes- new_payload = cls.hb_item_to_entity_payload( hb_item = hb_item )- if entity.integration_payload != new_payload:- entity.integration_payload = new_payload- messages.append( f'Integration payload updated for {entity}.' )-- if messages:- entity.save()-- return messages+class HbConverter:@classmethoddef hb_item_to_integration_key( cls, hb_item: HbItem ) -> IntegrationKey:@@ -109,7 +52,7 @@ class HbConverter:f'{hb_field.get("name", "")}. Cannot create integration key.')return None-+return IntegrationKey(integration_id = HbMetaData.integration_id,integration_name = f'field:{field_id}',@@ -122,7 +65,7 @@ class HbConverter:if not item_name:logger.error(f'Item name is missing for HomeBox item with id {hb_item.id}. Using default name.' )return f'HomeBox Item {hb_item.id}'-+return item_name@classmethod@@ -170,24 +113,24 @@ class HbConverter:'updatedAt': location.get( 'updatedAt' ),}- labels = hb_item.labels- if labels is None:- logger.warning( f'HomeBox item {hb_item.id} missing labels list' )- payload['labels'] = []+ tags = hb_item.tags+ if tags is None:+ logger.warning( f'HomeBox item {hb_item.id} missing tags list' )+ payload['tags'] = []else:- normalized_labels: List[Dict] = []- for label in labels:- if not isinstance( label, dict ):+ normalized_tags: List[Dict] = []+ for tag in tags:+ if not isinstance( tag, dict ):continue- normalized_labels.append({- 'id': label.get( 'id' ),- 'name': label.get( 'name' ),- 'description': label.get( 'description' ),- 'color': label.get( 'color' ),- 'created_at': label.get( 'createdAt' ),- 'updated_at': label.get( 'updatedAt' ),+ 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['labels'] = normalized_labels+ payload['tags'] = normalized_tagsreturn payload@@ -199,7 +142,7 @@ class HbConverter:def _hb_item_to_field_list( cls, hb_item: HbItem ) -> List[Dict]:hb_field_list = list( hb_item.fields )- for key, name in cls.HB_ITEM_ATTRIBUTE_FIELD_MAP:+ for key, name in HB_ITEM_FIELD_PAIRS:value = str( getattr( hb_item, key, '' ) or '' ).strip()if not value:continue@@ -387,96 +330,3 @@ class HbConverter:payload['file_value'] = ContentFile( raw_content, name = filename )return payload-- @classmethod- def create_attribute_from_hb_field( cls,- entity: Entity,- hb_field: Dict,- order_id: int ) -> Optional[EntityAttribute]:- payload = cls.hb_field_to_attribute_payload(- hb_field = hb_field,- order_id = order_id,- )- if not payload:- return None-- return EntityAttribute.objects.create(- entity = entity,- **payload,- )-- @classmethod- def update_attribute_from_hb_field( cls,- attribute: EntityAttribute,- hb_field: Dict,- order_id: int ) -> bool:- payload = cls.hb_field_to_attribute_payload(- hb_field = hb_field,- order_id = order_id,- )- if not payload:- return False-- incoming_file = payload.pop( 'file_value', None )-- was_changed = False- for field_name, field_value in payload.items():- if getattr( attribute, field_name ) != field_value:- setattr( attribute, field_name, field_value )- was_changed = True-- # Only update file content when needed; this avoids rewriting the same file on each sync.- if incoming_file and not attribute.file_value:- attribute.file_value = incoming_file- was_changed = True-- if was_changed:- attribute.save()-- return was_changed-- @classmethod- def create_attribute_from_hb_attachment( cls,- entity: Entity,- hb_attachment: Dict,- order_id: int ) -> Optional[EntityAttribute]:- payload = cls.hb_attachment_to_attribute_payload(- hb_attachment = hb_attachment,- order_id = order_id,- )- if not payload:- return None-- return EntityAttribute.objects.create(- entity = entity,- **payload,- )-- @classmethod- def update_attribute_from_hb_attachment( cls,- attribute: EntityAttribute,- hb_attachment: Dict,- order_id: int ) -> bool:- payload = cls.hb_attachment_to_attribute_payload(- hb_attachment = hb_attachment,- order_id = order_id,- )- if not payload:- return False-- incoming_file = payload.pop( 'file_value', None )-- was_changed = False- for field_name, field_value in payload.items():- if getattr( attribute, field_name ) != field_value:- setattr( attribute, field_name, field_value )- was_changed = True-- if incoming_file and not attribute.file_value:- attribute.file_value = incoming_file- was_changed = True-- if was_changed:- attribute.save()-- return was_changeddiff --git a/src/hi/services/homebox/hb_manager.py b/src/hi/services/homebox/shared/hb_manager.pysimilarity index 93%rename from src/hi/services/homebox/hb_manager.pyrename to src/hi/services/homebox/shared/hb_manager.pyindex 9315faf3..28edafb3 100644--- a/src/hi/services/homebox/hb_manager.py+++ b/src/hi/services/homebox/shared/hb_manager.py@@ -20,10 +20,11 @@ from hi.integrations.transient_models import ()from hi.integrations.models import Integration, IntegrationAttribute-from .enums import HbAttributeType+from hi.services.homebox.enums import HbAttributeTypefrom .hb_client import HbClientfrom .hb_client_factory import HbClientFactory-from .hb_metadata import HbMetaData+from .hb_models import HbItem+from hi.services.homebox.hb_metadata import HbMetaDatalogger = logging.getLogger(__name__)@@ -38,7 +39,7 @@ class HomeBoxManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusself._client_factory = HbClientFactory()self._hb_items_list = list()- self._hb_labels_list = list()+ self._hb_tags_list = list()self._hb_locations_list = list()self._hb_maintenances_list = list()@@ -117,7 +118,7 @@ class HomeBoxManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusdef clear_caches(self):self._hb_items_list = list()- self._hb_labels_list = list()+ self._hb_tags_list = list()self._hb_locations_list = list()self._hb_maintenances_list = list()return@@ -162,6 +163,20 @@ class HomeBoxManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusthread_sensitive = True,)(verbose=verbose)+ def fetch_hb_item_from_api( self, item_id : str, verbose : bool = True ) -> HbItem:+ if verbose:+ logger.debug( f'Getting HomeBox item {item_id}.' )++ if not self.hb_client:+ raise IntegrationError(+ 'HomeBox client is not available. The most recent reload '+ 'failed to construct a client (typically a connection or '+ 'configuration problem with the upstream HomeBox API).'+ )++ with self.api_call_context( 'hb_item' ):+ return self.hb_client.get_item( item_id )+def fetch_hb_items_summary_from_api( self ) -> list:"""Lightweight one-call probe used by the monitor's reachabilitydiff --git a/src/hi/services/homebox/hb_models.py b/src/hi/services/homebox/shared/hb_models.pysimilarity index 97%rename from src/hi/services/homebox/hb_models.pyrename to src/hi/services/homebox/shared/hb_models.pyindex a5e6ffad..05f8da8d 100644--- a/src/hi/services/homebox/hb_models.py+++ b/src/hi/services/homebox/shared/hb_models.py@@ -33,7 +33,7 @@ class HbApi:SOLD_NOTES_FIELD = 'soldNotes'NOTES_FIELD = 'notes'LOCATION_FIELD = 'location'- LABELS_FIELD = 'labels'+ TAGS_FIELD = 'tags'ATTACHMENTS_FIELD = 'attachments'FIELDS_FIELD = 'fields'@@ -160,8 +160,8 @@ class HbItem:return value if isinstance(value, dict) else None@property- def labels(self) -> Optional[List[Dict[str, Any]]]:- value = self.api_dict.get(HbApi.LABELS_FIELD)+ def tags(self) -> Optional[List[Dict[str, Any]]]:+ value = self.api_dict.get(HbApi.TAGS_FIELD)return value if isinstance(value, list) else None@propertydiff --git a/src/hi/services/homebox/tests/test_hb_client.py b/src/hi/services/homebox/tests/test_hb_client.pyindex 6d7558eb..1cb32e19 100644--- a/src/hi/services/homebox/tests/test_hb_client.py+++ b/src/hi/services/homebox/tests/test_hb_client.py@@ -5,7 +5,7 @@ from unittest.mock import Mock, patchfrom django.test import SimpleTestCasefrom requests import Response-from hi.services.homebox.hb_client import HbClient+from hi.services.homebox.shared.hb_client import HbClientlogging.disable(logging.CRITICAL)@@ -44,7 +44,7 @@ class TestHbClient(SimpleTestCase):HbClient.API_PASSWORD: 'pass',})- self.assertEqual(client._api_url, 'https://homebox.local')+ self.assertEqual(client.api_url, 'https://homebox.local')mock_login.assert_not_called()self.assertFalse(client._authenticated)@@ -170,6 +170,34 @@ class TestHbClient(SimpleTestCase):client.get_items()self.assertIn('detail request failed', str(context.exception))+ def test_get_item_returns_hb_item_from_detail_endpoint(self):+ with patch.object(HbClient, '_login'):+ client = HbClient(api_options=self._api_options())+ client._make_request = Mock(return_value={'id': 'item-5', 'name': 'Five'})++ item = client.get_item('item-5')++ self.assertEqual(item.id, 'item-5')+ self.assertEqual(item.name, 'Five')+ client._make_request.assert_called_once_with(+ 'GET',+ 'https://homebox.local/v1/items/item-5',+ )++ def test_get_item_raises_when_response_is_not_dict(self):+ with patch.object(HbClient, '_login'):+ client = HbClient(api_options=self._api_options())+ client._make_request = Mock(return_value=self._response(+ status_code=200,+ json_data=None,+ content_type='text/html',+ content=b'<html>not the api</html>',+ ))++ with self.assertRaises(ValueError) as context:+ client.get_item('item-5')+ self.assertIn('non-JSON', str(context.exception))+def test_download_attachment_returns_none_when_request_is_not_response(self):with patch.object(HbClient, '_login'):client = HbClient(api_options=self._api_options())diff --git a/src/hi/services/homebox/tests/test_hb_client_factory.py b/src/hi/services/homebox/tests/test_hb_client_factory.pyindex 212aba3f..1b792bdf 100644--- a/src/hi/services/homebox/tests/test_hb_client_factory.py+++ b/src/hi/services/homebox/tests/test_hb_client_factory.py@@ -13,7 +13,7 @@ from hi.integrations.models import IntegrationAttributefrom hi.integrations.transient_models import IntegrationKey, IntegrationValidationResultfrom hi.services.homebox.enums import HbAttributeType-from hi.services.homebox.hb_client_factory import HbClientFactory+from hi.services.homebox.shared.hb_client_factory import HbClientFactoryfrom hi.services.homebox.hb_metadata import HbMetaDatalogging.disable(logging.CRITICAL)@@ -50,10 +50,10 @@ class TestHbClientFactory(TestCase):return attributes- @patch('hi.services.homebox.hb_client_factory.HbClient')+ @patch('hi.services.homebox.shared.hb_client_factory.HbClient')def test_create_client_success(self, mock_client_class):"""Test successful client creation with valid attributes."""- from hi.services.homebox.hb_client import HbClient as RealHbClient+ from hi.services.homebox.shared.hb_client import HbClient as RealHbClientmock_client_class.API_URL = RealHbClient.API_URLmock_client_class.API_USER = RealHbClient.API_USERmock_client_class.API_PASSWORD = RealHbClient.API_PASSWORD@@ -148,10 +148,10 @@ class TestHbClientFactory(TestCase):mock_client.get_items_summary.assert_called_once()- @patch('hi.services.homebox.hb_client_factory.HbClient')+ @patch('hi.services.homebox.shared.hb_client_factory.HbClient')def test_create_client_threads_timeout_to_client(self, mock_client_class):"""create_client passes timeout_secs through to the HbClient."""- from hi.services.homebox.hb_client import HbClient as RealHbClient+ from hi.services.homebox.shared.hb_client import HbClient as RealHbClientmock_client_class.API_URL = RealHbClient.API_URLmock_client_class.API_USER = RealHbClient.API_USERmock_client_class.API_PASSWORD = RealHbClient.API_PASSWORDdiff --git a/src/hi/services/homebox/tests/test_hb_connector.py b/src/hi/services/homebox/tests/test_hb_connector.pynew file mode 100644index 00000000..b9c23fdf--- /dev/null+++ b/src/hi/services/homebox/tests/test_hb_connector.py@@ -0,0 +1,243 @@+"""+Tests for the HomeBox Connect-mode resolver.++Covers the entity-detail external-data view hook: native entities+(no integration_name) return None; upstream-unavailable returns a+MinimalViewData; successful fetch returns a StructuredViewData with+documented fields, custom fields, tags, and attachments (with proxy+URLs for thumbnails/downloads).+"""+import logging+from unittest.mock import Mock, patch++from django.test import TestCase++from hi.apps.entity.models import Entity+from hi.integrations.external_view_data import (+ MinimalViewData,+ NameValuePair,+ StructuredViewData,+)+from hi.services.homebox.connector.hb_connector import HomeBoxConnector+from hi.services.homebox.hb_metadata import HbMetaData+from hi.services.homebox.shared.hb_models import HbItem+++logging.disable(logging.CRITICAL)+++class HomeBoxConnectorTests(TestCase):++ def _make_hb_entity(self, item_id: str = '42') -> Entity:+ return Entity.objects.create(+ name=f'HomeBox Item {item_id}',+ entity_type_str='LIGHT',+ integration_id=HbMetaData.integration_id,+ integration_name=item_id,+ )++ def _make_native_entity(self) -> Entity:+ return Entity.objects.create(+ name='Native Entity',+ entity_type_str='LIGHT',+ )++ def test_returns_none_for_native_entity(self):+ entity = self._make_native_entity()+ connector = HomeBoxConnector()+ result = connector.get_external_view_data(entity)+ self.assertIsNone(result)++ def test_returns_minimal_when_upstream_fetch_raises(self):+ entity = self._make_hb_entity('42')++ manager = Mock()+ manager.hb_client = Mock()+ manager.hb_client.api_url = 'http://homebox.example.com/api'+ manager.fetch_hb_item_from_api.side_effect = RuntimeError('unreachable')+ manager.ensure_initialized = Mock()++ with patch(+ 'hi.services.homebox.connector.hb_connector.HomeBoxManager',+ return_value=manager,+ ):+ result = HomeBoxConnector().get_external_view_data(entity)++ self.assertIsInstance(result, MinimalViewData)+ self.assertEqual(result.deep_link_url, 'http://homebox.example.com/item/42')+ self.assertIsNotNone(result.error_message)+ self.assertIn('unreachable', result.error_message)++ def test_returns_minimal_when_client_unavailable(self):+ # Manager initialized but client is None (e.g., disabled+ # integration). The resolver still attempts a fetch, which+ # raises IntegrationError from the manager; the resolver+ # catches it and returns MinimalViewData. Since client is+ # None, the deep link URL cannot be derived and stays None.+ entity = self._make_hb_entity('99')++ manager = Mock()+ manager.hb_client = None+ manager.fetch_hb_item_from_api.side_effect = RuntimeError('no client')+ manager.ensure_initialized = Mock()++ with patch(+ 'hi.services.homebox.connector.hb_connector.HomeBoxManager',+ return_value=manager,+ ):+ result = HomeBoxConnector().get_external_view_data(entity)++ self.assertIsInstance(result, MinimalViewData)+ self.assertIsNone(result.deep_link_url)+ self.assertIsNotNone(result.error_message)+ self.assertIn('no client', result.error_message)++ def test_successful_fetch_returns_structured_data_with_field_ordering(self):+ entity = self._make_hb_entity('123')++ hb_item = HbItem(api_dict={+ 'id': '123',+ 'name': 'Drill',+ 'description': 'Cordless drill',+ 'manufacturer': 'Acme',+ 'modelNumber': 'X-99',+ 'serialNumber': '', # blank, must be skipped+ 'assetId': 'A-1',+ 'purchaseFrom': '', # blank, must be skipped+ 'purchaseTime': '2024-01-15',+ 'warrantyDetails': '',+ 'warrantyExpires': '2026-01-15',+ 'notes': 'Garage shelf',+ 'fields': [+ {'name': 'Bit Set', 'textValue': 'Phillips'},+ {'name': '', 'textValue': 'no-name-skip'},+ {'name': 'Empty', 'textValue': ''},+ 'not-a-dict',+ ],+ 'tags': [+ {'name': 'tools'},+ {'name': 'garage'},+ {'name': ''},+ 'not-a-dict',+ ],+ })++ manager = Mock()+ manager.hb_client = Mock()+ manager.hb_client.api_url = 'http://homebox.example.com/api'+ manager.fetch_hb_item_from_api.return_value = hb_item+ manager.ensure_initialized = Mock()++ with patch(+ 'hi.services.homebox.connector.hb_connector.HomeBoxManager',+ return_value=manager,+ ):+ result = HomeBoxConnector().get_external_view_data(entity)++ self.assertIsInstance(result, StructuredViewData)+ self.assertEqual(result.deep_link_url, 'http://homebox.example.com/item/123')++ # Documented fields, in ITEM_FIELD_PAIRS order, blanks skipped.+ # Custom fields appended next. Tags last.+ expected_pairs = [+ ('Description', 'Cordless drill'),+ ('Manufacturer', 'Acme'),+ ('Model Number', 'X-99'),+ ('Asset ID', 'A-1'),+ ('Purchase Date', '2024-01-15'),+ ('Warranty Expires', '2026-01-15'),+ ('Notes', 'Garage shelf'),+ ('Bit Set', 'Phillips'),+ ('Tags', 'tools, garage'),+ ]+ actual_pairs = [(row.name, row.value) for row in result.attributes]+ self.assertEqual(actual_pairs, expected_pairs)+ for row in result.attributes:+ self.assertIsInstance(row, NameValuePair)++ def test_attachments_built_with_proxy_urls(self):+ entity = self._make_hb_entity('77')++ hb_item = HbItem(api_dict={+ 'id': '77',+ 'attachments': [+ {+ 'id': 'att-1',+ 'title': 'Receipt',+ 'mimeType': 'image/png',+ 'thumbnail': {'id': 'thumb-1'},+ },+ {+ # No thumbnail block at all.+ 'id': 'att-2',+ 'title': '', # falls back to "Attachment att-2"+ 'mimeType': 'application/pdf',+ },+ {'id': ''}, # blank id, must be skipped+ 'not-a-dict',+ ],+ })++ manager = Mock()+ manager.hb_client = Mock()+ manager.hb_client.api_url = 'http://homebox.example.com/api'+ manager.fetch_hb_item_from_api.return_value = hb_item+ manager.ensure_initialized = Mock()++ with patch(+ 'hi.services.homebox.connector.hb_connector.HomeBoxManager',+ return_value=manager,+ ):+ result = HomeBoxConnector().get_external_view_data(entity)++ self.assertIsInstance(result, StructuredViewData)+ self.assertEqual(len(result.attachments), 2)++ att1 = result.attachments[0]+ self.assertEqual(att1.id, 'att-1')+ self.assertEqual(att1.title, 'Receipt')+ self.assertEqual(att1.mime_type, 'image/png')+ # Proxy URLs route via the framework's services/homebox/ mount.+ self.assertIn(f'/{entity.id}/att-1', att1.open_url)+ self.assertIn(f'/{entity.id}/thumb-1', att1.thumbnail_url)++ att2 = result.attachments[1]+ self.assertEqual(att2.id, 'att-2')+ self.assertEqual(att2.title, 'Attachment att-2')+ self.assertEqual(att2.mime_type, 'application/pdf')+ self.assertIsNone(att2.thumbnail_url)+ self.assertIn(f'/{entity.id}/att-2', att2.open_url)++ def test_deep_link_url_strips_api_suffix(self):+ entity = self._make_hb_entity('500')++ manager = Mock()+ manager.hb_client = Mock()+ manager.hb_client.api_url = 'http://homebox.example.com/api'+ manager.fetch_hb_item_from_api.side_effect = RuntimeError('upstream down')+ manager.ensure_initialized = Mock()++ with patch(+ 'hi.services.homebox.connector.hb_connector.HomeBoxManager',+ return_value=manager,+ ):+ result = HomeBoxConnector().get_external_view_data(entity)++ self.assertEqual(result.deep_link_url, 'http://homebox.example.com/item/500')++ def test_deep_link_url_when_api_url_has_no_api_suffix(self):+ entity = self._make_hb_entity('600')++ manager = Mock()+ manager.hb_client = Mock()+ manager.hb_client.api_url = 'http://homebox.example.com'+ manager.fetch_hb_item_from_api.side_effect = RuntimeError('upstream down')+ manager.ensure_initialized = Mock()++ with patch(+ 'hi.services.homebox.connector.hb_connector.HomeBoxManager',+ return_value=manager,+ ):+ result = HomeBoxConnector().get_external_view_data(entity)++ self.assertEqual(result.deep_link_url, 'http://homebox.example.com/item/600')diff --git a/src/hi/services/homebox/tests/test_hb_converter.py b/src/hi/services/homebox/tests/test_hb_converter.pyindex 2d1ab576..51767129 100644--- a/src/hi/services/homebox/tests/test_hb_converter.py+++ b/src/hi/services/homebox/tests/test_hb_converter.py@@ -4,11 +4,8 @@ from unittest.mock import Mockfrom django.test import TestCasefrom hi.apps.attribute.enums import AttributeValueType-from hi.apps.entity.enums import EntityType-from hi.apps.entity.models import Entity-from hi.services.homebox.hb_converter import HbConverter-from hi.services.homebox.hb_metadata import HbMetaData-from hi.services.homebox.hb_models import HbItem+from hi.services.homebox.shared.hb_converter import HbConverter+from hi.services.homebox.shared.hb_models import HbItemlogging.disable(logging.CRITICAL)@@ -23,7 +20,7 @@ class TestHbConverter(TestCase):'description': description,'quantity': quantity,'location': {'id': 'loc-1', 'name': 'Garage'},- 'labels': [{'id': 'lab-1', 'name': 'Tools'}],+ 'tags': [{'id': 'lab-1', 'name': 'Tools'}],'fields': [],'attachments': [],}@@ -33,80 +30,18 @@ class TestHbConverter(TestCase):return HbItem(api_dict=api_dict, client=client)- def test_create_models_for_hb_item_creates_entity(self):- item = self._mock_item(item_id='item-create', name='Drill')-- entity = HbConverter.create_models_for_hb_item(hb_item=item)-- self.assertIsInstance(entity, Entity)- self.assertEqual(entity.integration_id, HbMetaData.integration_id)- self.assertEqual(entity.integration_name, 'item-create')- self.assertEqual(entity.name, 'Drill')- self.assertEqual(entity.entity_type, EntityType.OTHER)- self.assertFalse(entity.can_add_custom_attributes)- self.assertNotIn('description', entity.integration_payload)- self.assertEqual(entity.integration_payload.get('location', {}).get('name'), 'Garage')- self.assertEqual(entity.integration_payload.get('labels')[0].get('name'), 'Tools')-- def test_create_models_with_existing_entity_does_not_create_new_and_preserves_name(self):- """Issue #281 reconnect contract: when an existing Entity is- passed in, repopulate its integration-owned fields without- creating a new row and without overwriting the (possibly- user-edited) name."""- existing = Entity.objects.create(- name='User Renamed Item',- entity_type_str=str(EntityType.SERVICE),- )- baseline_count = Entity.objects.count()- item = self._mock_item(item_id='item-reconnect', name='Upstream Drill Name')-- returned = HbConverter.create_models_for_hb_item(- hb_item=item,- entity=existing,- )-- self.assertEqual(Entity.objects.count(), baseline_count)- self.assertEqual(returned.id, existing.id)- existing.refresh_from_db()- # Name preserved (NOT 'Upstream Drill Name').- self.assertEqual(existing.name, 'User Renamed Item')- # Integration-owned fields repopulated from upstream.- self.assertEqual(existing.integration_id, HbMetaData.integration_id)- self.assertEqual(existing.integration_name, 'item-reconnect')- self.assertEqual(- existing.integration_payload.get('location', {}).get('name'),- 'Garage',- )-- def test_update_models_for_hb_item_updates_name_type_and_payload(self):- entity = Entity.objects.create(- name='Old Name',- entity_type_str=str(EntityType.SERVICE),- can_user_delete=False,- can_add_custom_attributes=True,- integration_id=HbMetaData.integration_id,- integration_name='item-update',- integration_payload={'quantity': 1},- )-- item = self._mock_item(item_id='item-update', name='New Name', description='new', quantity=3)-- messages = HbConverter.update_models_for_hb_item(entity=entity, hb_item=item)-- self.assertTrue(messages)- entity.refresh_from_db()- self.assertEqual(entity.name, 'New Name')- self.assertEqual(entity.entity_type, EntityType.OTHER)- self.assertFalse(entity.can_add_custom_attributes)- self.assertNotIn('description', entity.integration_payload)- self.assertEqual(entity.integration_payload.get('quantity'), 3)-def test_hb_item_to_attribute_field_list_contains_top_level_fields(self):item = self._mock_item(item_id='item-top-level')item.api_dict['description'] = 'Portable drill'item.api_dict['serialNumber'] = 'SN-123'item.api_dict['modelNumber'] = 'MD-456'item.api_dict['manufacturer'] = 'ACME'+ item.api_dict['assetId'] = 'AS-789'+ item.api_dict['purchaseFrom'] = 'Big Box Store'+ item.api_dict['purchaseTime'] = '2024-01-15'+ item.api_dict['warrantyDetails'] = '2 year limited'+ item.api_dict['warrantyExpires'] = '2026-01-15'+ item.api_dict['notes'] = 'Keep in workshop'hb_field_list = HbConverter.hb_item_to_attribute_field_list( hb_item = item )field_id_to_field = { field.get( 'id' ): field for field in hb_field_list }@@ -115,6 +50,12 @@ class TestHbConverter(TestCase):self.assertEqual( field_id_to_field['hb_item:serial_number']['textValue'], 'SN-123' )self.assertEqual( field_id_to_field['hb_item:model_number']['textValue'], 'MD-456' )self.assertEqual( field_id_to_field['hb_item:manufacturer']['textValue'], 'ACME' )+ self.assertEqual( field_id_to_field['hb_item:asset_id']['textValue'], 'AS-789' )+ self.assertEqual( field_id_to_field['hb_item:purchase_from']['textValue'], 'Big Box Store' )+ self.assertEqual( field_id_to_field['hb_item:purchase_time']['textValue'], '2024-01-15' )+ self.assertEqual( field_id_to_field['hb_item:warranty_details']['textValue'], '2 year limited' )+ self.assertEqual( field_id_to_field['hb_item:warranty_expires']['textValue'], '2026-01-15' )+ self.assertEqual( field_id_to_field['hb_item:notes']['textValue'], 'Keep in workshop' )def test_hb_item_attachment_maps_to_file_attribute_payload(self):item = self._mock_item(item_id='item-with-attachment')@@ -140,60 +81,6 @@ class TestHbConverter(TestCase):self.assertEqual(payload['file_mime_type'], 'text/plain')self.assertIn('file_value', payload)- def test_create_and_update_file_attribute_from_attachment(self):- item = self._mock_item(item_id='item-file-sync')- entity = HbConverter.create_models_for_hb_item(hb_item=item)-- attachment = {- 'id': 'att-2',- 'title': 'Teste.txt',- 'mimeType': 'text/plain; charset=utf-8',- 'path': 'x/y/z',- }- attachment_data = {- 'id': 'attachment:att-2',- 'type': 'attachment',- 'name': 'Teste.txt',- 'textValue': 'Teste.txt',- 'mimeType': 'text/plain; charset=utf-8',- 'attachment': attachment,- 'downloaded_attachment': {- 'content': b'v1',- 'mime_type': 'text/plain; charset=utf-8',- 'filename': 'Teste.txt',- 'source_url': 'https://example/v1',- }- }-- created_attribute = HbConverter.create_attribute_from_hb_attachment(- entity=entity,- hb_attachment=attachment_data,- order_id=0,- )-- self.assertEqual(created_attribute.value_type_str, str(AttributeValueType.FILE))- self.assertTrue(bool(created_attribute.file_value))-- # File should not be overwritten when already present.- original_name = created_attribute.file_value.name- attachment_data['downloaded_attachment'] = {- 'content': b'v2',- 'mime_type': 'text/plain; charset=utf-8',- 'filename': 'Teste-v2.txt',- 'source_url': 'https://example/v2',- }- was_changed = HbConverter.update_attribute_from_hb_attachment(- attribute=created_attribute,- hb_attachment=attachment_data,- order_id=1,- )-- self.assertTrue(was_changed)- created_attribute.refresh_from_db()- self.assertEqual(created_attribute.order_id, 1)- self.assertEqual(created_attribute.file_value.name, original_name)--class TestHbConverterPayloadTimestampOmission(TestCase):"""Regression coverage for the timestamp-omission contract on@@ -216,7 +103,7 @@ class TestHbConverterPayloadTimestampOmission(TestCase):'createdAt': '2026-01-01T00:00:00+00:00','updatedAt': '2026-01-01T00:00:00+00:00','location': {'id': 'loc-1', 'name': 'Garage'},- 'labels': [{'id': 'lab-1', 'name': 'Tools'}],+ 'tags': [{'id': 'lab-1', 'name': 'Tools'}],'fields': [],'attachments': [],}diff --git a/src/hi/services/homebox/tests/test_hb_importer.py b/src/hi/services/homebox/tests/test_hb_importer.pynew file mode 100644index 00000000..2b4f77d5--- /dev/null+++ b/src/hi/services/homebox/tests/test_hb_importer.py@@ -0,0 +1,155 @@+import logging+from unittest.mock import Mock++from django.test import TestCase++from hi.apps.attribute.enums import AttributeValueType+from hi.apps.entity.enums import EntityType+from hi.apps.entity.models import Entity+from hi.services.homebox.importer.hb_importer import HbImporter+from hi.services.homebox.hb_metadata import HbMetaData+from hi.services.homebox.shared.hb_models import HbItem+++logging.disable(logging.CRITICAL)+++class TestHbImporter(TestCase):++ def _mock_item(self, item_id='item-1', name='Item 1', description='desc', quantity=1):+ api_dict = {+ 'id': item_id,+ 'name': name,+ 'description': description,+ 'quantity': quantity,+ 'location': {'id': 'loc-1', 'name': 'Garage'},+ 'tags': [{'id': 'lab-1', 'name': 'Tools'}],+ 'fields': [],+ 'attachments': [],+ }++ client = Mock()+ client.download_attachment.return_value = None++ return HbItem(api_dict=api_dict, client=client)++ def test_create_models_for_hb_item_creates_entity(self):+ item = self._mock_item(item_id='item-create', name='Drill')++ entity = HbImporter.create_models_for_hb_item(hb_item=item)++ self.assertIsInstance(entity, Entity)+ self.assertEqual(entity.integration_id, HbMetaData.integration_id)+ self.assertEqual(entity.integration_name, 'item-create')+ self.assertEqual(entity.name, 'Drill')+ self.assertEqual(entity.entity_type, EntityType.OTHER)+ self.assertFalse(entity.allow_internal_attributes)+ 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')++ def test_create_models_with_existing_entity_does_not_create_new_and_preserves_name(self):+ """Issue #281 reconnect contract: when an existing Entity is+ passed in, repopulate its integration-owned fields without+ creating a new row and without overwriting the (possibly+ user-edited) name."""+ existing = Entity.objects.create(+ name='User Renamed Item',+ entity_type_str=str(EntityType.SERVICE),+ )+ baseline_count = Entity.objects.count()+ item = self._mock_item(item_id='item-reconnect', name='Upstream Drill Name')++ returned = HbImporter.create_models_for_hb_item(+ hb_item=item,+ entity=existing,+ )++ self.assertEqual(Entity.objects.count(), baseline_count)+ self.assertEqual(returned.id, existing.id)+ existing.refresh_from_db()+ # Name preserved (NOT 'Upstream Drill Name').+ self.assertEqual(existing.name, 'User Renamed Item')+ # Integration-owned fields repopulated from upstream.+ self.assertEqual(existing.integration_id, HbMetaData.integration_id)+ self.assertEqual(existing.integration_name, 'item-reconnect')+ self.assertEqual(+ existing.integration_payload.get('location', {}).get('name'),+ 'Garage',+ )++ def test_update_models_for_hb_item_updates_name_type_and_payload(self):+ entity = Entity.objects.create(+ name='Old Name',+ entity_type_str=str(EntityType.SERVICE),+ can_user_delete=False,+ allow_internal_attributes=True,+ integration_id=HbMetaData.integration_id,+ integration_name='item-update',+ integration_payload={'quantity': 1},+ )++ item = self._mock_item(item_id='item-update', name='New Name', description='new', quantity=3)++ messages = HbImporter.update_models_for_hb_item(entity=entity, hb_item=item)++ self.assertTrue(messages)+ entity.refresh_from_db()+ self.assertEqual(entity.name, 'New Name')+ self.assertEqual(entity.entity_type, EntityType.OTHER)+ self.assertFalse(entity.allow_internal_attributes)+ self.assertNotIn('description', entity.integration_payload)+ self.assertEqual(entity.integration_payload.get('quantity'), 3)++ def test_create_and_update_file_attribute_from_attachment(self):+ item = self._mock_item(item_id='item-file-sync')+ entity = HbImporter.create_models_for_hb_item(hb_item=item)++ attachment = {+ 'id': 'att-2',+ 'title': 'Teste.txt',+ 'mimeType': 'text/plain; charset=utf-8',+ 'path': 'x/y/z',+ }+ attachment_data = {+ 'id': 'attachment:att-2',+ 'type': 'attachment',+ 'name': 'Teste.txt',+ 'textValue': 'Teste.txt',+ 'mimeType': 'text/plain; charset=utf-8',+ 'attachment': attachment,+ 'downloaded_attachment': {+ 'content': b'v1',+ 'mime_type': 'text/plain; charset=utf-8',+ 'filename': 'Teste.txt',+ 'source_url': 'https://example/v1',+ }+ }++ created_attribute = HbImporter.create_attribute_from_hb_attachment(+ entity=entity,+ hb_attachment=attachment_data,+ order_id=0,+ )++ self.assertEqual(created_attribute.value_type_str, str(AttributeValueType.FILE))+ self.assertTrue(bool(created_attribute.file_value))++ # File should not be overwritten when already present.+ original_name = created_attribute.file_value.name+ attachment_data['downloaded_attachment'] = {+ 'content': b'v2',+ 'mime_type': 'text/plain; charset=utf-8',+ 'filename': 'Teste-v2.txt',+ 'source_url': 'https://example/v2',+ }+ was_changed = HbImporter.update_attribute_from_hb_attachment(+ attribute=created_attribute,+ hb_attachment=attachment_data,+ order_id=1,+ )++ self.assertTrue(was_changed)+ created_attribute.refresh_from_db()+ self.assertEqual(created_attribute.order_id, 1)+ self.assertEqual(created_attribute.file_value.name, original_name)diff --git a/src/hi/services/homebox/tests/test_hb_manager.py b/src/hi/services/homebox/tests/test_hb_manager.pyindex 218e41cf..fc664ad1 100644--- a/src/hi/services/homebox/tests/test_hb_manager.py+++ b/src/hi/services/homebox/tests/test_hb_manager.py@@ -7,7 +7,7 @@ from hi.integrations.exceptions import IntegrationAttributeErrorfrom hi.integrations.models import IntegrationAttributefrom hi.integrations.transient_models import IntegrationKeyfrom hi.services.homebox.enums import HbAttributeType-from hi.services.homebox.hb_manager import HomeBoxManager+from hi.services.homebox.shared.hb_manager import HomeBoxManagerfrom hi.services.homebox.hb_metadata import HbMetaDatadiff --git a/src/hi/services/homebox/tests/test_hb_models.py b/src/hi/services/homebox/tests/test_hb_models.pyindex 24a2ec58..39c88a45 100644--- a/src/hi/services/homebox/tests/test_hb_models.py+++ b/src/hi/services/homebox/tests/test_hb_models.py@@ -1,7 +1,7 @@import loggingfrom django.test import SimpleTestCase-from hi.services.homebox.hb_models import HbItem+from hi.services.homebox.shared.hb_models import HbItemlogging.disable(logging.CRITICAL)@@ -36,7 +36,7 @@ class TestHbItem(SimpleTestCase):'soldNotes': 'Used','notes': 'Shelf A','location': {'id': 'loc-1'},- 'labels': [{'id': 'lab-1'}],+ 'tags': [{'id': 'lab-1'}],'attachments': [{'id': 'att-1'}],'fields': [{'id': 'f-1'}],}@@ -71,7 +71,7 @@ class TestHbItem(SimpleTestCase):self.assertEqual(item.sold_notes, 'Used')self.assertEqual(item.notes, 'Shelf A')self.assertEqual(item.location, {'id': 'loc-1'})- self.assertEqual(item.labels, [{'id': 'lab-1'}])+ self.assertEqual(item.tags, [{'id': 'lab-1'}])self.assertEqual(item.attachments, [{'id': 'att-1'}])self.assertEqual(item.fields, [{'id': 'f-1'}])@@ -91,7 +91,7 @@ class TestHbItem(SimpleTestCase):soldTime='',soldPrice='80',location='garage',- labels='tools',+ tags='tools',)self.assertIsNone(item.quantity)@@ -108,7 +108,7 @@ class TestHbItem(SimpleTestCase):self.assertIsNone(item.sold_time)self.assertIsNone(item.sold_price)self.assertIsNone(item.location)- self.assertIsNone(item.labels)+ self.assertIsNone(item.tags)def test_returns_empty_collections_or_strings_when_missing(self):item = HbItem(api_dict={'id': 'item-2'})diff --git a/src/hi/services/homebox/tests/test_hb_sync.py b/src/hi/services/homebox/tests/test_hb_sync.pyindex 95b7b1cd..9e1dc15f 100644--- a/src/hi/services/homebox/tests/test_hb_sync.py+++ b/src/hi/services/homebox/tests/test_hb_sync.py@@ -8,7 +8,7 @@ from hi.apps.entity.models import Entityfrom hi.integrations.sync_result import IntegrationSyncResultfrom hi.integrations.transient_models import IntegrationKeyfrom hi.services.homebox.hb_metadata import HbMetaData-from hi.services.homebox.hb_sync import HomeBoxSynchronizer+from hi.services.homebox.importer.hb_sync import HomeBoxSynchronizerfrom hi.testing.async_task_utils import AsyncTaskTestCase@@ -66,13 +66,13 @@ class TestHomeBoxSynchronizer(SimpleTestCase):with ExitStack() as stack:stack.enter_context(patch(- 'hi.services.homebox.hb_sync.transaction.atomic',+ 'hi.services.homebox.importer.hb_sync.transaction.atomic',return_value=nullcontext(),))stack.enter_context(patch(- 'hi.services.homebox.hb_sync.HbConverter.hb_item_to_integration_key',+ 'hi.services.homebox.importer.hb_sync.HbConverter.hb_item_to_integration_key',side_effect=key_from_item,))@@ -99,6 +99,10 @@ class TestHomeBoxSynchronizer(SimpleTestCase):remove_entity_mock = stack.enter_context(patch.object(synchronizer, '_remove_entity'))+ # Connect-mode: _sync_helper_entity_attributes is no+ # longer called during sync (HomeBox attributes are+ # fetched live by the connector). Patch it anyway and+ # assert it is NOT called, to pin the new contract.sync_attrs_mock = stack.enter_context(patch.object(synchronizer, '_sync_helper_entity_attributes'))@@ -128,23 +132,10 @@ class TestHomeBoxSynchronizer(SimpleTestCase):result=result,)- self.assertEqual(sync_attrs_mock.call_count, 2)- self.assertEqual(- sync_attrs_mock.call_args_list[0].kwargs['entity'],- created_entity,- )- self.assertEqual(- sync_attrs_mock.call_args_list[0].kwargs['hb_item'],- item_new,- )- self.assertEqual(- sync_attrs_mock.call_args_list[1].kwargs['entity'],- existing_entity,- )- self.assertEqual(- sync_attrs_mock.call_args_list[1].kwargs['hb_item'],- item_existing,- )+ # Connect-mode contract: sync no longer creates/updates/+ # removes EntityAttribute rows. The attribute-sync helper is+ # not invoked by the Connect-mode sync flow.+ self.assertEqual(sync_attrs_mock.call_count, 0)self.assertIn('Found 2 existing HomeBox items.', result.info_list)self.assertTrue(any('Ignoring HomeBox item due to missing/invalid id' in message@@ -202,31 +193,31 @@ class TestHomeBoxSynchronizer(SimpleTestCase):with ExitStack() as stack:stack.enter_context(patch(- 'hi.services.homebox.hb_sync.transaction.atomic',+ 'hi.services.homebox.importer.hb_sync.transaction.atomic',return_value=nullcontext(),))stack.enter_context(patch(- 'hi.services.homebox.hb_sync.HbConverter.hb_item_to_attribute_field_list',+ 'hi.services.homebox.importer.hb_sync.HbConverter.hb_item_to_attribute_field_list',return_value=[field_existing, field_new],))stack.enter_context(patch(- 'hi.services.homebox.hb_sync.HbConverter.hb_field_to_integration_key',+ 'hi.services.homebox.importer.hb_sync.HbConverter.hb_field_to_integration_key',side_effect=field_key_from_field,))stack.enter_context(patch(- 'hi.services.homebox.hb_sync.HbConverter.hb_item_to_attachment_field_list',+ 'hi.services.homebox.importer.hb_sync.HbConverter.hb_item_to_attachment_field_list',return_value=[attachment_existing, attachment_new],))stack.enter_context(patch(- 'hi.services.homebox.hb_sync.HbConverter.hb_attachment_to_integration_key',+ 'hi.services.homebox.importer.hb_sync.HbConverter.hb_attachment_to_integration_key',side_effect=attachment_key_from_attachment,))@@ -386,7 +377,7 @@ class TestHomeBoxSynchronizerRebuildIntegrationComponents(SimpleTestCase):upstream = Mock(name='hb_item')with patch(- 'hi.services.homebox.hb_sync.HbConverter.create_models_for_hb_item'+ 'hi.services.homebox.importer.hb_sync.HbImporter.create_models_for_hb_item') as mock_converter:synchronizer._rebuild_integration_components(entity=existing_entity,diff --git a/src/hi/services/homebox/tests/test_integration_gateway.py b/src/hi/services/homebox/tests/test_integration_gateway.pynew file mode 100644index 00000000..da8ab2f4--- /dev/null+++ b/src/hi/services/homebox/tests/test_integration_gateway.py@@ -0,0 +1,36 @@+"""+Smoke tests for HomeBoxGateway hooks the framework calls.++The substantive behavior of each gateway method lives in the+collaborator it delegates to (HomeBoxConnector, HomeBoxManager,+HomeBoxSynchronizer); these tests pin the delegation contract.+"""+import logging+from unittest.mock import Mock, patch++from django.test import SimpleTestCase++from hi.services.homebox.integration import HomeBoxGateway+++logging.disable(logging.CRITICAL)+++class HomeBoxGatewayExternalViewDataTests(SimpleTestCase):++ def test_delegates_to_homebox_connector(self):+ gateway = HomeBoxGateway()+ entity = Mock(name='entity')+ expected_result = Mock(name='external_view_data')++ with patch(+ 'hi.services.homebox.connector.hb_connector.HomeBoxConnector'+ ) as connector_cls:+ connector_instance = connector_cls.return_value+ connector_instance.get_external_view_data.return_value = expected_result++ result = gateway.get_external_view_data(entity)++ self.assertIs(result, expected_result)+ connector_cls.assert_called_once_with()+ connector_instance.get_external_view_data.assert_called_once_with(entity)diff --git a/src/hi/services/homebox/tests/test_proxy_views.py b/src/hi/services/homebox/tests/test_proxy_views.pynew file mode 100644index 00000000..5859cffb--- /dev/null+++ b/src/hi/services/homebox/tests/test_proxy_views.py@@ -0,0 +1,179 @@+"""+Tests for the HomeBox attachment proxy view.++Covers the bearer-token proxy that streams HomeBox attachments and+thumbnails back to the browser: 404s for unknown / non-HomeBox+entities, 503 when the integration's client is unavailable, 502 on+upstream download failure, and a clean 200 with passthrough bytes+and content-type on success.+"""+import logging+from unittest.mock import Mock, patch++from django.test import TestCase+from django.urls import reverse++from hi.apps.entity.models import Entity+from hi.services.homebox.hb_metadata import HbMetaData+++logging.disable(logging.CRITICAL)+++class HomeBoxAttachmentProxyViewTests(TestCase):++ def _make_hb_entity(self, item_id: str = '42') -> Entity:+ return Entity.objects.create(+ name=f'HomeBox Item {item_id}',+ entity_type_str='LIGHT',+ integration_id=HbMetaData.integration_id,+ integration_name=item_id,+ )++ def _url(self, entity_id: int, attachment_id: str = 'att-1') -> str:+ return reverse(+ 'homebox_attachment_proxy',+ kwargs={'entity_id': entity_id, 'attachment_id': attachment_id},+ )++ def test_unknown_entity_returns_404(self):+ url = self._url(entity_id=99999, attachment_id='att-1')+ response = self.client.get(url)+ self.assertEqual(response.status_code, 404)++ def test_non_homebox_entity_returns_404(self):+ entity = Entity.objects.create(+ name='Native Entity',+ entity_type_str='LIGHT',+ )+ response = self.client.get(self._url(entity.id))+ self.assertEqual(response.status_code, 404)++ def test_returns_503_when_client_unavailable(self):+ entity = self._make_hb_entity('1')++ manager = Mock()+ manager.hb_client = None+ manager.ensure_initialized = Mock()++ with patch(+ 'hi.services.homebox.connector.proxy_views.HomeBoxManager',+ return_value=manager,+ ):+ response = self.client.get(self._url(entity.id))++ self.assertEqual(response.status_code, 503)++ def test_successful_download_returns_bytes_and_mime(self):+ entity = self._make_hb_entity('1')++ manager = Mock()+ client = Mock()+ client.download_attachment.return_value = {+ 'content': b'PNG-BYTES',+ 'mime_type': 'image/png',+ }+ manager.hb_client = client+ manager.ensure_initialized = Mock()++ with patch(+ 'hi.services.homebox.connector.proxy_views.HomeBoxManager',+ return_value=manager,+ ):+ response = self.client.get(self._url(entity.id, attachment_id='att-1'))++ self.assertEqual(response.status_code, 200)+ self.assertEqual(response.content, b'PNG-BYTES')+ self.assertEqual(response['Content-Type'], 'image/png')+ client.download_attachment.assert_called_once_with(+ item_id='1', attachment_id='att-1',+ )++ def test_download_returns_none_results_in_404(self):+ entity = self._make_hb_entity('1')++ manager = Mock()+ client = Mock()+ client.download_attachment.return_value = None+ manager.hb_client = client+ manager.ensure_initialized = Mock()++ with patch(+ 'hi.services.homebox.connector.proxy_views.HomeBoxManager',+ return_value=manager,+ ):+ response = self.client.get(self._url(entity.id))++ self.assertEqual(response.status_code, 404)++ def test_download_raises_results_in_502(self):+ """Upstream connectivity / auth failure surfaces as 502 (bad+ gateway) so the browser and ops can distinguish upstream+ trouble from a genuinely-missing attachment."""+ entity = self._make_hb_entity('1')++ manager = Mock()+ client = Mock()+ client.download_attachment.side_effect = RuntimeError('boom')+ manager.hb_client = client+ manager.ensure_initialized = Mock()++ with patch(+ 'hi.services.homebox.connector.proxy_views.HomeBoxManager',+ return_value=manager,+ ):+ response = self.client.get(self._url(entity.id))++ self.assertEqual(response.status_code, 502)++ def test_missing_content_returns_404(self):+ entity = self._make_hb_entity('1')++ manager = Mock()+ client = Mock()+ client.download_attachment.return_value = {+ 'content': None,+ 'mime_type': 'image/png',+ }+ manager.hb_client = client+ manager.ensure_initialized = Mock()++ with patch(+ 'hi.services.homebox.connector.proxy_views.HomeBoxManager',+ return_value=manager,+ ):+ response = self.client.get(self._url(entity.id))++ self.assertEqual(response.status_code, 404)++ def test_default_mime_when_upstream_omits(self):+ entity = self._make_hb_entity('1')++ manager = Mock()+ client = Mock()+ client.download_attachment.return_value = {+ 'content': b'raw',+ 'mime_type': None,+ }+ manager.hb_client = client+ manager.ensure_initialized = Mock()++ with patch(+ 'hi.services.homebox.connector.proxy_views.HomeBoxManager',+ return_value=manager,+ ):+ response = self.client.get(self._url(entity.id))++ self.assertEqual(response.status_code, 200)+ self.assertEqual(response['Content-Type'], 'application/octet-stream')++ def test_entity_with_no_integration_name_returns_404(self):+ # HomeBox-integrated entity but somehow missing item id.+ entity = Entity.objects.create(+ name='Broken HomeBox Entity',+ entity_type_str='LIGHT',+ integration_id=HbMetaData.integration_id,+ integration_name='',+ )+ response = self.client.get(self._url(entity.id))+ self.assertEqual(response.status_code, 404)diff --git a/src/hi/services/homebox/urls.py b/src/hi/services/homebox/urls.pyindex 4303b860..632a1374 100644--- a/src/hi/services/homebox/urls.py+++ b/src/hi/services/homebox/urls.py@@ -7,11 +7,21 @@ URLs here when an integration genuinely needs an endpoint theframework does not provide. URLs added here mount under``services/homebox/``.-Currently no integration-specific endpoints are required.+The attachment proxy endpoint serves HomeBox attachments and+thumbnails to the browser. HomeBox requires bearer-token auth so the+browser cannot fetch them directly; the proxy uses the server-side+stored token and streams the bytes through."""-from django.urls import re_path # noqa: F401+from django.urls import re_pathfrom . import views # noqa: F401+from .connector.proxy_views import HomeBoxAttachmentProxyView-urlpatterns = []+urlpatterns = [+ re_path(+ r'^proxy/attachment/(?P<entity_id>\d+)/(?P<attachment_id>[^/]+)/?$',+ HomeBoxAttachmentProxyView.as_view(),+ name='homebox_attachment_proxy',+ ),+]diff --git a/src/hi/services/zoneminder/zm_sync.py b/src/hi/services/zoneminder/zm_sync.pyindex 5844c6bb..7cb764cc 100644--- a/src/hi/services/zoneminder/zm_sync.py+++ b/src/hi/services/zoneminder/zm_sync.py@@ -373,7 +373,7 @@ class ZoneMinderSynchronizer( IntegrationSynchronizer, ZoneMinderMixin ):"""Refresh integration-owned components on an existing entity.``entity.name`` is user-editable in HI's UI on ZM entities- (``can_add_custom_attributes`` defaults to True), so it's+ (``allow_internal_attributes`` defaults to True), so it'streated as user-owned after creation: this method does nottouch it on update. ZM monitor renames upstream are notpropagated; the operator's chosen name stays.diff --git a/src/hi/simulator/management/commands/seed_sim_profiles.py b/src/hi/simulator/management/commands/seed_sim_profiles.pyindex af68a607..50af8032 100644--- a/src/hi/simulator/management/commands/seed_sim_profiles.py+++ b/src/hi/simulator/management/commands/seed_sim_profiles.py@@ -55,7 +55,7 @@ detached / removed transitions for that integration.later disappears upstream.2. Repeat for ZM: switch ZoneMinder to ``baseline``, sync, add acustom attribute to its ★-prefixed monitor. (HomeBox sets- ``can_add_custom_attributes = False`` by design, so HB+ ``allow_internal_attributes = False`` by design, so HBentities cannot participate in the detach/reconnect cycle andhave no anchor item.)3. Switch each module to its ``baseline-changed``. Refresh sync.@@ -365,7 +365,7 @@ class Command(BaseCommand):def _build_homebox_baseline(self, profile: SimProfile) -> int:# 4 items with mixed metadata richness. No ★-prefixed anchor- # here: HomeBox sets ``can_add_custom_attributes = False`` (the+ # here: HomeBox sets ``allow_internal_attributes = False`` (the# converter is the source of truth for HB item attributes), so# the operator cannot add a custom attribute on the HI side# and the detach/reconnect cycle does not apply to HB.@@ -451,19 +451,233 @@ class Command(BaseCommand):return profile.db_sim_entities.count()def _build_homebox_volume(self, profile: SimProfile) -> int:- # 25 items, varied metadata richness. Stresses HB list rendering- # and the inventory pagination/scroll behavior.- for index in range(25):+ # 25 items. Items 001-006 are explicitly configured to specific+ # 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.+ self._add_homebox_item(+ profile,+ 'Volume Item 001',+ item_id = 'volume-item-001',+ quantity = 1,+ )++ self._add_homebox_item(+ profile,+ 'Volume Item 002',+ item_id = 'volume-item-002',+ quantity = 1,+ description = 'Compact cordless screwdriver, kept in the kitchen drawer.',+ manufacturer = 'Acme',+ model_number = 'AC-002',+ serial_number = 'SN-00002',+ custom_fields = 'Color=Red',+ tags = 'tools,power',+ )++ self._add_homebox_item(+ profile,+ 'Volume Item 003',+ item_id = 'volume-item-003',+ quantity = 1,+ attachment_keys = ','.join([+ AttachmentTemplate.MANUAL.key,+ AttachmentTemplate.PHOTO.key,+ ]),+ )++ self._add_homebox_item(+ profile,+ 'Volume Item 004',+ item_id = 'volume-item-004',+ quantity = 1,+ manufacturer = 'Generic',+ model_number = 'GN-004',+ serial_number = 'GEN-00004',+ custom_fields = 'Storage Location=Garage Shelf B',+ tags = 'garage,workshop',+ attachment_keys = ','.join([+ AttachmentTemplate.RECEIPT.key,+ AttachmentTemplate.PHOTO.key,+ ]),+ )++ self._add_homebox_item(+ profile,+ 'Volume Item 005',+ item_id = 'volume-item-005',+ quantity = 2,+ description = 'Fully documented stress-test item exercising every field.',+ manufacturer = 'Acme',+ model_number = 'AC-005',+ serial_number = 'SN-00005',+ asset_id = 'AST-0005',+ purchase_from = 'Big Box Store',+ purchase_time = '2024-06-15',+ warranty_details = '2 year limited warranty covering parts and labor.',+ warranty_expires = '2026-06-15',+ notes = 'Demonstration item with all documented fields populated.',+ custom_fields = (+ 'Color=Black, Storage Location=Basement, '+ 'Material=Steel, Battery=Li-ion'+ ),+ tags = 'tools,power,electronics',+ attachment_keys = ','.join([+ AttachmentTemplate.MANUAL.key,+ AttachmentTemplate.RECEIPT.key,+ AttachmentTemplate.PHOTO.key,+ AttachmentTemplate.WARRANTY.key,+ ]),+ )++ # Item 006: varied-length values to exercise the JS Show+ # more / Show less truncation toggle on documented and+ # custom fields.+ long_warranty = (+ 'Covers manufacturing defects for 5 years from the date of purchase.\n'+ 'Excludes damage from misuse, accidents, unauthorized repairs, or normal wear.\n'+ 'Requires original proof of purchase for any claim submission.\n'+ 'Replacement parts are warranted for the remainder of the original term.\n'+ 'Shipping costs for warranty service are the responsibility of the owner.\n'+ 'Contact [email protected] to initiate a warranty claim.\n'+ 'See enclosed booklet for full terms and conditions.'+ )+ medium_notes = (+ 'Stored in the upstairs closet on the second shelf.\n'+ 'Original box and packing materials retained.\n'+ 'Last serviced in March; runs quietly.'+ )+ long_custom_value = (+ 'This unit was installed by the previous owner and has been in '+ 'continuous service for several years. It has had two minor '+ 'repairs documented in the maintenance log. The unit has been '+ 'observed to operate slightly above its rated current draw under '+ 'heavy load. A replacement filter cartridge is stored alongside '+ 'the unit. The manufacturer has issued a service bulletin for '+ 'this model number recommending an annual inspection. Operator '+ 'should consult the bulletin before performing any repairs.'+ )+ self._add_homebox_item(+ profile,+ 'Volume Item 006',+ item_id = 'volume-item-006',+ quantity = 1,+ description = 'Truncation toggle test item.',+ manufacturer = 'Acme',+ model_number = 'AC-006',+ serial_number = 'SN-00006',+ notes = medium_notes,+ warranty_details = long_warranty,+ custom_fields = (+ f'Color=Blue, History={long_custom_value}, '+ 'Storage Location=Attic Bin 4'+ ),+ attachment_keys = ','.join([+ AttachmentTemplate.PHOTO.key,+ AttachmentTemplate.PHOTO_SQUARE.key,+ AttachmentTemplate.PHOTO_WIDE.key,+ AttachmentTemplate.PHOTO_WIDE_X.key,+ AttachmentTemplate.PHOTO_TALL.key,+ AttachmentTemplate.PHOTO_TALL_X.key,+ ]),+ )++ custom_field_palette = [+ 'Color=Red, Storage Location=Garage Shelf B',+ 'Color=Blue, Storage Location=Basement, Condition=New',+ 'Material=Steel, Weight=2.5kg',+ 'Color=Black, Battery=Li-ion, Voltage=20V',+ 'Material=Plastic, Length=12in, Diameter=1in',+ 'Color=Green, Storage Location=Attic Bin 4',+ 'Material=Wood, Finish=Oak, Width=18in',+ ]+ tag_palette = [+ 'tools',+ 'tools,power',+ 'electronics',+ 'electronics,delicate',+ 'kitchen',+ 'garage,workshop',+ 'consumables',+ ]+ # Attachment template buckets indexed modulo 25 — first ~5+ # empty, next ~10 single, next ~5 paired, last ~5 with+ # three+ templates. Different choices keep the mime mix+ # visible to the operator.+ attachment_buckets = [+ # 0 attachments (indices 0..4)+ '', '', '', '', '',+ # 1 attachment (indices 5..14)+ AttachmentTemplate.MANUAL.key,+ AttachmentTemplate.RECEIPT.key,+ AttachmentTemplate.PHOTO.key,+ AttachmentTemplate.WARRANTY.key,+ AttachmentTemplate.MANUAL.key,+ AttachmentTemplate.RECEIPT.key,+ AttachmentTemplate.PHOTO.key,+ AttachmentTemplate.WARRANTY.key,+ AttachmentTemplate.MANUAL.key,+ AttachmentTemplate.RECEIPT.key,+ # 2 attachments (indices 15..19)+ ','.join([AttachmentTemplate.MANUAL.key, AttachmentTemplate.RECEIPT.key]),+ ','.join([AttachmentTemplate.PHOTO.key, AttachmentTemplate.WARRANTY.key]),+ ','.join([AttachmentTemplate.RECEIPT.key, AttachmentTemplate.PHOTO.key]),+ ','.join([AttachmentTemplate.MANUAL.key, AttachmentTemplate.WARRANTY.key]),+ ','.join([AttachmentTemplate.PHOTO.key, AttachmentTemplate.RECEIPT.key]),+ # 3+ attachments (indices 20..24)+ ','.join([AttachmentTemplate.MANUAL.key, AttachmentTemplate.RECEIPT.key,+ AttachmentTemplate.PHOTO.key]),+ ','.join([AttachmentTemplate.MANUAL.key, AttachmentTemplate.RECEIPT.key,+ AttachmentTemplate.PHOTO.key, AttachmentTemplate.WARRANTY.key]),+ ','.join([AttachmentTemplate.PHOTO.key, AttachmentTemplate.WARRANTY.key,+ AttachmentTemplate.MANUAL.key]),+ ','.join([AttachmentTemplate.RECEIPT.key, AttachmentTemplate.PHOTO.key,+ AttachmentTemplate.WARRANTY.key]),+ ','.join([AttachmentTemplate.MANUAL.key, AttachmentTemplate.PHOTO.key,+ AttachmentTemplate.RECEIPT.key, AttachmentTemplate.WARRANTY.key]),+ ]++ for index in range(6, 25):+ item_number = index + 1+ kwargs = {+ 'item_id': f'volume-item-{item_number:03}',+ 'quantity': (index % 4) + 1,+ 'attachment_keys': attachment_buckets[index],+ }++ if index % 5 == 0:+ # Fully documented item: every top-level field populated.+ kwargs.update({+ 'description': f'Stress-test inventory item #{item_number}',+ 'manufacturer': 'Acme',+ 'model_number': f'AC-{item_number:03}',+ 'serial_number': f'SN-{item_number:05}',+ 'asset_id': f'AST-{item_number:04}',+ 'purchase_from': 'Big Box Store',+ 'purchase_time': '2024-06-15',+ 'warranty_details': '2 year limited warranty',+ 'warranty_expires': '2026-06-15',+ 'notes': f'Documented stress-test item #{item_number}',+ })+ elif index % 3 == 0:+ # Partial documentation.+ kwargs.update({+ 'manufacturer': 'Generic',+ 'serial_number': f'GEN-{item_number:05}',+ })++ if index % 4 == 0:+ kwargs['custom_fields'] = custom_field_palette[+ index % len( custom_field_palette )+ ]++ if index % 3 == 0:+ kwargs['tags'] = tag_palette[ index % len( tag_palette ) ]+self._add_homebox_item(profile,- f'Volume Item {index + 1:03}',- item_id = f'volume-item-{index + 1:03}',- description = (- f'Stress-test inventory item #{index + 1}'- if index % 3 == 0 else ''- ),- manufacturer = 'Acme' if index % 5 == 0 else '',- quantity = (index % 4) + 1,+ f'Volume Item {item_number:03}',+ **kwargs,)return profile.db_sim_entities.count()diff --git a/src/hi/simulator/media.py b/src/hi/simulator/media.pyindex 0ee5404b..f4076c86 100644--- a/src/hi/simulator/media.py+++ b/src/hi/simulator/media.py@@ -1,11 +1,13 @@"""Shared synthetic-media primitives for the simulator.Renders a placeholder JPEG with operator-identifying text overlaid-so the image viewed inside HI is obviously synthetic.+so the image viewed inside HI is obviously synthetic. Also provides+generic placeholder image and PDF builders used by service-specific+attachment catalogs."""import iofrom datetime import datetime-from typing import List, Optional+from typing import List, Optional, Tuplefrom PIL import Image, ImageDraw@@ -17,12 +19,89 @@ FRAME_WIDTH = 320FRAME_HEIGHT = 240+def render_placeholder_image(+ text_lines : List[str],+ image_format : str = 'JPEG',+ size : Tuple[int, int] = ( FRAME_WIDTH, FRAME_HEIGHT ),+ bg_color : Tuple[int, int, int] = ( 230, 240, 250 ),+ fg_color : Tuple[int, int, int] = ( 30, 40, 80 ),+) -> bytes:+ """Pillow-rendered placeholder image. Default bitmap font so+ callers stay independent of system font availability."""+ image = Image.new( mode = 'RGB', size = size, color = bg_color )+ draw = ImageDraw.Draw( image )+ y = 30+ for line in text_lines:+ draw.text( ( 20, y ), line, fill = fg_color )+ y += 24+ buffer = io.BytesIO()+ image.save( buffer, format = image_format )+ return buffer.getvalue()+++def render_placeholder_pdf( text_lines : List[str] ) -> bytes:+ """Hand-rolled minimal single-page PDF. Avoids pulling in an+ external PDF library for what amounts to four objects of+ placeholder content. The first line is drawn near the top of the+ page; remaining lines stack below."""+ safe_lines = []+ for line in text_lines:+ text_safe = (+ str( line )+ .replace( '\\', '\\\\' )+ .replace( '(', '\\(' )+ .replace( ')', '\\)' )+ )+ safe_lines.append( text_safe )++ # Build the content stream as one text block with a leading+ # absolute placement followed by line-relative offsets for each+ # additional line. Skip the leading offset for the first line.+ content_parts = [ b'BT /F1 18 Tf 60 740 Td' ]+ for index, text_safe in enumerate( safe_lines ):+ if index > 0:+ content_parts.append( b'0 -24 Td' )+ content_parts.append( f'({text_safe}) Tj'.encode( 'latin-1' ) )+ content_parts.append( b'ET' )+ content_stream = b' '.join( content_parts )++ objects = [+ b'<< /Type /Catalog /Pages 2 0 R >>',+ b'<< /Type /Pages /Kids [3 0 R] /Count 1 >>',+ (+ b'<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] '+ b'/Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>'+ ),+ b'<< /Length ' + str( len( content_stream ) ).encode( 'latin-1' )+ + b' >>\nstream\n' + content_stream + b'\nendstream',+ b'<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>',+ ]++ output = bytearray( b'%PDF-1.4\n%\xe2\xe3\xcf\xd3\n' )+ offsets = []+ for index, body in enumerate( objects, start = 1 ):+ offsets.append( len( output ) )+ output += f'{index} 0 obj\n'.encode( 'latin-1' )+ output += body+ output += b'\nendobj\n'++ xref_offset = len( output )+ output += f'xref\n0 {len(objects) + 1}\n'.encode( 'latin-1' )+ output += b'0000000000 65535 f \n'+ for offset in offsets:+ output += f'{offset:010d} 00000 n \n'.encode( 'latin-1' )+ output += (+ f'trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\n'+ f'startxref\n{xref_offset}\n%%EOF\n'+ ).encode( 'latin-1' )+ return bytes( output )++def render_jpeg_frame(text_lines : List[str],timestamp_override : Optional[datetime] = None,) -> bytes:- """Pillow-rendered single JPEG frame. Default bitmap font so the- simulator stays independent of system font availability. The+ """Pillow-rendered single JPEG frame for camera-style media. Thetimestamp line is appended automatically so multiple framesrendered in quick succession still differ visibly. When``timestamp_override`` is provided (event playback), that valuediff --git a/src/hi/simulator/services/homebox/api/views.py b/src/hi/simulator/services/homebox/api/views.pyindex 7e750d5a..ec96ef33 100644--- a/src/hi/simulator/services/homebox/api/views.py+++ b/src/hi/simulator/services/homebox/api/views.py@@ -112,6 +112,17 @@ class AttachmentDownloadView( View ):item_id = kwargs.get('item_id')attachment_id = kwargs.get('attachment_id')+ # Thumbnail variants share the underlying catalog template+ # with the main attachment but render at a smaller size.+ # The wire convention is ``<template.key>-thumb`` (see+ # ``build_attachment_metadata``).+ thumbnail_suffix = '-thumb'+ is_thumbnail = attachment_id.endswith( thumbnail_suffix )+ lookup_key = (+ attachment_id[:-len(thumbnail_suffix)]+ if is_thumbnail else attachment_id+ )+simulator = HomeBoxSimulator()for ( sim_entity_id, fields, _archived_state,_created_at, _updated_at ) in simulator.get_sim_entity_pairs():@@ -121,14 +132,21 @@ class AttachmentDownloadView( View ):template.key: templatefor template in parse_attachment_keys( fields.attachment_keys )}- template = templates_by_key.get( attachment_id )+ template = templates_by_key.get( lookup_key )if template is None:return JsonResponse({ 'message': f'Attachment {attachment_id} not found' },status = 404,)+ if is_thumbnail and template.kind != 'image':+ return JsonResponse(+ { 'message': f'Attachment {attachment_id} not found' },+ status = 404,+ )rendered = render_attachment_content(- template = template, item_name = fields.name,+ template = template,+ item_name = fields.name,+ thumbnail = is_thumbnail,)if not rendered:return JsonResponse(diff --git a/src/hi/simulator/services/homebox/attachment_catalog.py b/src/hi/simulator/services/homebox/attachment_catalog.pyindex d540f3f7..cd2e8bdb 100644--- a/src/hi/simulator/services/homebox/attachment_catalog.py+++ b/src/hi/simulator/services/homebox/attachment_catalog.py@@ -19,40 +19,61 @@ Wire convention follows ``LabeledEnum``: a member's wire key is``attachment_keys`` CSV, and as the ``id`` field on the APIattachment dict."""-import ioimport loggingfrom typing import Dict, List, Optional, Tuple-from PIL import Image, ImageDraw-from hi.apps.common.enums import LabeledEnum+from hi.simulator.media import (+ render_placeholder_image,+ render_placeholder_pdf,+)+logger = logging.getLogger(__name__)+# Thumbnail rendering scale: real HomeBox thumbnails are scaled-down+# originals at the source aspect, not reformatted. The simulator+# follows the same shape.+_THUMBNAIL_SCALE = 0.75++class AttachmentTemplate( LabeledEnum ):"""Catalog of pre-canned attachment templates.- Each member carries the user-facing label, MIME type, and- rendering kind. The wire key (used in URLs, CSV fields, and the- API ``attachment.id`` value) is ``member.name.lower()`` per the- ``LabeledEnum`` convention. ``description`` is left empty —- operator-facing label is sufficient for the picker UI.+ Each member carries the user-facing label, MIME type, rendering+ kind, and source pixel dimensions. The wire key (used in URLs,+ CSV fields, and the API ``attachment.id`` value) is+ ``member.name.lower()`` per the ``LabeledEnum`` convention.+ ``description`` is left empty — operator-facing label is+ sufficient for the picker UI.++ Photo variants (``PHOTO_SQUARE`` / ``PHOTO_WIDE`` /+ ``PHOTO_WIDE_X`` / ``PHOTO_TALL`` / ``PHOTO_TALL_X``) exist so+ the operator can exercise the HI app's thumbnail grid across+ different image aspect ratios without uploading real files."""- RECEIPT = ( 'Receipt' , '' , 'image/png' , 'image' )- MANUAL = ( 'Manual' , '' , 'application/pdf' , 'pdf' )- PHOTO = ( 'Photo' , '' , 'image/jpeg' , 'image' )- WARRANTY = ( 'Warranty' , '' , 'application/pdf' , 'pdf' )+ RECEIPT = ('Receipt', '', 'image/png', 'image', (320, 240))+ MANUAL = ('Manual', '', 'application/pdf', 'pdf', (320, 240))+ PHOTO = ('Photo', '', 'image/jpeg', 'image', (320, 240))+ WARRANTY = ('Warranty', '', 'application/pdf', 'pdf', (320, 240))+ PHOTO_SQUARE = ('Photo (Square)', '', 'image/jpeg', 'image', (320, 320))+ PHOTO_WIDE = ('Photo (Wide)', '', 'image/jpeg', 'image', (320, 180))+ PHOTO_WIDE_X = ('Photo (Ultra Wide)', '', 'image/jpeg', 'image', (640, 180))+ PHOTO_TALL = ('Photo (Tall)', '', 'image/jpeg', 'image', (180, 320))+ PHOTO_TALL_X = ('Photo (Ultra Tall)', '', 'image/jpeg', 'image', (180, 640))def __init__( self,label : str,description : str,mime_type : str,- kind : str ):+ kind : str,+ source_size : Tuple[ int, int ] ):super().__init__( label, description )self.mime_type = mime_typeself.kind = kind+ self.source_size = source_sizereturn@property@@ -62,6 +83,11 @@ class AttachmentTemplate( LabeledEnum ):the enum member name is preserved."""return self.name.lower()+ @property+ def thumbnail_size( self ) -> Tuple[ int, int ]:+ width, height = self.source_size+ return ( int( width * _THUMBNAIL_SCALE ), int( height * _THUMBNAIL_SCALE ) )+def attachment_choices() -> List[ Tuple[ str, str ] ]:"""Choice tuples (value, label) for any UI that needs to render a@@ -96,98 +122,51 @@ def parse_attachment_keys( csv_value: str ) -> List[ AttachmentTemplate ]:return templates-def build_attachment_metadata( template: AttachmentTemplate ) -> Dict[ str, str ]:+def build_attachment_metadata( template: AttachmentTemplate ) -> Dict[ str, object ]:"""The dict shape the real HomeBox API emits inside an item's- ``attachments`` array. Returned shape is intentionally small —- the HI integration's HbItem parser reads ``id`` (used as the- download key here), ``title``, and ``mimeType``."""- return {+ ``attachments`` array. For image-kind templates also emits a+ ``thumbnail`` sub-dict so the integration's thumbnail proxy path+ can be exercised; PDF templates have no thumbnail entry."""+ metadata: Dict[ str, object ] = {'id' : template.key,'title' : template.label,'mimeType' : template.mime_type,}+ if template.kind == 'image':+ metadata['thumbnail'] = { 'id': f'{template.key}-thumb' }+ return metadatadef render_attachment_content( template : AttachmentTemplate,item_name : str,+ thumbnail : bool = False,) -> Optional[ Dict[ str, object ] ]:"""Generate the binary payload for the given catalog template,with ``item_name`` baked into the content so the operator can- distinguish artifacts in the HI UI. Returns a dict with+ distinguish artifacts in the HI UI. When ``thumbnail`` is True+ and the template is image-kind, the image is rendered at a+ smaller size at the same source aspect; ``thumbnail=True`` with+ a non-image template returns None. Returns a dict with``content`` (bytes) and ``mime_type`` (str), or None if the- template's ``kind`` is unrecognized (should not happen with- the current catalog)."""+ template's ``kind`` is unrecognized or unsupported for the+ requested variant."""if template.kind == 'image':- content = _render_image(- title = template.label,- item_name = item_name,- image_format = 'PNG' if template.mime_type == 'image/png' else 'JPEG',+ image_format = 'PNG' if template.mime_type == 'image/png' else 'JPEG'+ size = template.thumbnail_size if thumbnail else template.source_size+ content = render_placeholder_image(+ text_lines = [ template.label, item_name, '(simulator)' ],+ image_format = image_format,+ size = size,)elif template.kind == 'pdf':- content = _render_pdf( title = template.label, item_name = item_name )+ if thumbnail:+ return None+ content = render_placeholder_pdf(+ text_lines = [ f'{template.label}: {item_name} (simulator)' ],+ )else:return Nonereturn {'content' : content,'mime_type' : template.mime_type,}---def _render_image( title : str, item_name : str, image_format : str ) -> bytes:- """Pillow-rendered placeholder image: a colored canvas with the- attachment title and item name drawn on it. Default bitmap font- keeps the simulator independent of system font availability."""- image = Image.new( mode = 'RGB', size = ( 320, 160 ), color = ( 230, 240, 250 ) )- draw = ImageDraw.Draw( image )- draw.text( ( 20, 30 ), title, fill = ( 30, 40, 80 ) )- draw.text( ( 20, 70 ), item_name, fill = ( 30, 40, 80 ) )- draw.text( ( 20, 110 ), '(simulator)', fill = ( 90, 90, 90 ) )- buffer = io.BytesIO()- image.save( buffer, format = image_format )- return buffer.getvalue()---def _render_pdf( title : str, item_name : str ) -> bytes:- """Hand-rolled minimal single-page PDF. The PDF format is a mix- of structured text and a binary xref table; we build the body- first, then compute byte offsets for the xref. This avoids- pulling in an external PDF library for what amounts to four- objects of placeholder content. The output is a valid PDF that- most viewers will render with the title and item-name text."""- text = f'{title}: {item_name} (simulator)'- # Escape parens that would otherwise terminate a PDF string literal.- text_safe = text.replace( '\\', '\\\\' ).replace( '(', '\\(' ).replace( ')', '\\)' )- content_stream = (- f'BT /F1 18 Tf 60 740 Td ({text_safe}) Tj ET'- ).encode( 'latin-1' )-- objects = [- b'<< /Type /Catalog /Pages 2 0 R >>',- b'<< /Type /Pages /Kids [3 0 R] /Count 1 >>',- (- b'<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] '- b'/Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>'- ),- b'<< /Length ' + str( len( content_stream ) ).encode( 'latin-1' )- + b' >>\nstream\n' + content_stream + b'\nendstream',- b'<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>',- ]-- output = bytearray( b'%PDF-1.4\n%\xe2\xe3\xcf\xd3\n' )- offsets = []- for index, body in enumerate( objects, start = 1 ):- offsets.append( len( output ) )- output += f'{index} 0 obj\n'.encode( 'latin-1' )- output += body- output += b'\nendobj\n'-- xref_offset = len( output )- output += f'xref\n0 {len(objects) + 1}\n'.encode( 'latin-1' )- output += b'0000000000 65535 f \n'- for offset in offsets:- output += f'{offset:010d} 00000 n \n'.encode( 'latin-1' )- output += (- f'trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\n'- f'startxref\n{xref_offset}\n%%EOF\n'- ).encode( 'latin-1' )- return bytes( output )diff --git a/src/hi/simulator/services/homebox/sim_models.py b/src/hi/simulator/services/homebox/sim_models.pyindex 09bb9684..36d466d2 100644--- a/src/hi/simulator/services/homebox/sim_models.py+++ b/src/hi/simulator/services/homebox/sim_models.py@@ -7,9 +7,10 @@ HomeBoxInventoryItemFields (persisted via DbSimEntity); the only mutableruntime state is the ``archived`` flag.The to_api_dict helper builds the JSON shape the integration's HbItem parser-(src/hi/services/homebox/hb_models.py) consumes.+(src/hi/services/homebox/shared/hb_models.py) consumes."""+import loggingfrom dataclasses import dataclass, field as dc_fieldfrom typing import Any, Dict, List@@ -25,6 +26,9 @@ from .attachment_catalog import ()+logger = logging.getLogger(__name__)++@dataclass( frozen = True )class HomeBoxInventoryItemFields( SimEntityFields ):""" User-editable metadata for a simulated HomeBox inventory item.@@ -38,13 +42,32 @@ class HomeBoxInventoryItemFields( SimEntityFields ):item in two different profiles ends up with different ids."""- item_id : str = ''- description : str = ''- serial_number : str = ''- model_number : str = ''- manufacturer : str = ''- notes : str = ''- quantity : int = 1+ item_id : str = ''+ description : str = ''+ serial_number : str = ''+ model_number : str = ''+ manufacturer : str = ''+ asset_id : str = ''+ purchase_from : str = ''+ purchase_time : str = ''+ warranty_details : str = ''+ warranty_expires : str = ''+ notes : str = ''+ quantity : int = 1+ custom_fields : str = dc_field(+ default = '',+ metadata = {+ 'help_text': (+ 'Custom user-defined fields. CSV of name=value pairs.'+ ),+ },+ )+ tags : str = dc_field(+ default = '',+ metadata = {+ 'help_text': 'CSV of HomeBox tag names.',+ },+ )# Comma-separated wire keys of ``AttachmentTemplate`` members# (``hi.simulator.services.homebox.attachment_catalog``);# unknown keys are dropped silently. The simulator's API@@ -103,6 +126,58 @@ HOMEBOX_SIM_ENTITY_DEFINITION_LIST: List[SimEntityDefinition] = []+def _parse_custom_fields( csv_value : str ) -> List[ Dict[ str, Any ] ]:+ """Parse the operator's ``custom_fields`` CSV (``name=value``+ pairs) into the HomeBox-style field dict shape. Malformed pairs+ (missing ``=`` or blank name) are dropped with a debug log."""+ if not csv_value:+ return []+ parsed: List[ Dict[ str, Any ] ] = []+ index = 0+ for raw_pair in csv_value.split( ',' ):+ pair = raw_pair.strip()+ if not pair:+ continue+ if '=' not in pair:+ logger.debug( f'Ignoring malformed custom field "{pair}"' )+ continue+ name_part, value_part = pair.split( '=', 1 )+ name = name_part.strip()+ value = value_part.strip()+ if not name:+ logger.debug( f'Ignoring custom field with empty name "{pair}"' )+ continue+ parsed.append({+ 'id' : f'custom-{index + 1}',+ 'name' : name,+ 'textValue' : value,+ 'type' : 'text',+ 'numberValue' : None,+ 'booleanValue' : None,+ })+ index += 1+ return parsed+++def _parse_tags( csv_value : str ) -> List[ Dict[ str, str ] ]:+ """Parse the operator's ``tags`` CSV into the HomeBox-style tag+ dict shape. Blank entries are skipped."""+ if not csv_value:+ return []+ tags: List[ Dict[ str, str ] ] = []+ index = 0+ for raw_name in csv_value.split( ',' ):+ name = raw_name.strip()+ if not name:+ continue+ tags.append({+ 'id' : f'tag-{index + 1}',+ 'name' : name,+ })+ index += 1+ return tags++def build_item_api_dict( sim_entity_id : int,fields : HomeBoxInventoryItemFields,archived_state : HomeBoxItemArchivedState,@@ -112,11 +187,10 @@ 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.- Fields not in the simulator's scope (custom fields, location,- labels) are emitted as empty/null. Attachments are populated- from the per-item ``attachment_keys`` CSV via the catalog in- ``attachment_catalog``; the actual bytes are rendered on demand- by the download endpoint when the integration fetches each+ 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 eachattachment. Timestamps come from the persisted ``DbSimEntity``so they're stable across reads — change only when the operatoractually edits the row, matching real HomeBox behavior.@@ -130,19 +204,24 @@ def build_item_api_dict( sim_entity_id : int,for template in parse_attachment_keys( fields.attachment_keys )]return {- 'id' : item_id,- 'name' : fields.name,- 'description' : fields.description,- 'serialNumber' : fields.serial_number,- 'modelNumber' : fields.model_number,- 'manufacturer' : fields.manufacturer,- 'notes' : fields.notes,- 'quantity' : fields.quantity,- 'archived' : archived_state.is_archived,- 'fields' : [],- 'attachments' : attachments,- 'location' : None,- 'labels' : [],- 'createdAt' : created_at.isoformat(),- 'updatedAt' : updated_at.isoformat(),+ 'id' : item_id,+ 'name' : fields.name,+ 'description' : fields.description,+ 'serialNumber' : fields.serial_number,+ 'modelNumber' : fields.model_number,+ 'manufacturer' : fields.manufacturer,+ 'assetId' : fields.asset_id,+ 'purchaseFrom' : fields.purchase_from,+ 'purchaseTime' : fields.purchase_time,+ 'warrantyDetails' : fields.warranty_details,+ 'warrantyExpires' : fields.warranty_expires,+ 'notes' : fields.notes,+ 'quantity' : fields.quantity,+ 'archived' : archived_state.is_archived,+ 'fields' : _parse_custom_fields( fields.custom_fields ),+ 'attachments' : attachments,+ 'location' : None,+ 'tags' : _parse_tags( fields.tags ),+ 'createdAt' : created_at.isoformat(),+ 'updatedAt' : updated_at.isoformat(),}diff --git a/src/hi/simulator/services/homebox/templates/homebox/home.html b/src/hi/simulator/services/homebox/templates/homebox/home.htmlnew file mode 100644index 00000000..95871258--- /dev/null+++ b/src/hi/simulator/services/homebox/templates/homebox/home.html@@ -0,0 +1,21 @@+{% extends "simulator/pages/base.html" %}++{% block head_title %}HomeBox Simulator{% endblock %}++{% block content %}+ <div class="container mt-3">+ <h1>HomeBox Simulator Items</h1>+ {% if items %}+ <ul>+ {% for item in items %}+ <li>+ <a href="{% url 'homebox_item' item_id=item.id %}">{{ item.name }}</a>+ <small class="text-muted">({{ item.id }})</small>+ </li>+ {% endfor %}+ </ul>+ {% else %}+ <p>No items in the active profile.</p>+ {% endif %}+ </div>+{% endblock %}diff --git a/src/hi/simulator/services/homebox/templates/homebox/item.html b/src/hi/simulator/services/homebox/templates/homebox/item.htmlnew file mode 100644index 00000000..fd342a43--- /dev/null+++ b/src/hi/simulator/services/homebox/templates/homebox/item.html@@ -0,0 +1,99 @@+{% extends "simulator/pages/base.html" %}++{% block head_title %}{{ item.name }} - HomeBox Simulator{% endblock %}++{% block content %}+ <div class="container mt-3">+ <p><a href="{% url 'homebox_home' %}">← Back to HomeBox items</a></p>++ <h1>{{ item.name }}</h1>+ <p class="text-muted">ID: {{ item.id }}</p>++ <h2>Fields</h2>+ <dl class="row">+ {% if item.description %}+ <dt class="col-sm-3">Description</dt>+ <dd class="col-sm-9">{{ item.description|linebreaksbr }}</dd>+ {% endif %}+ {% if item.manufacturer %}+ <dt class="col-sm-3">Manufacturer</dt>+ <dd class="col-sm-9">{{ item.manufacturer }}</dd>+ {% endif %}+ {% if item.modelNumber %}+ <dt class="col-sm-3">Model Number</dt>+ <dd class="col-sm-9">{{ item.modelNumber }}</dd>+ {% endif %}+ {% if item.serialNumber %}+ <dt class="col-sm-3">Serial Number</dt>+ <dd class="col-sm-9">{{ item.serialNumber }}</dd>+ {% endif %}+ {% if item.assetId %}+ <dt class="col-sm-3">Asset ID</dt>+ <dd class="col-sm-9">{{ item.assetId }}</dd>+ {% endif %}+ {% if item.purchaseFrom %}+ <dt class="col-sm-3">Purchased From</dt>+ <dd class="col-sm-9">{{ item.purchaseFrom }}</dd>+ {% endif %}+ {% if item.purchaseTime %}+ <dt class="col-sm-3">Purchase Time</dt>+ <dd class="col-sm-9">{{ item.purchaseTime }}</dd>+ {% endif %}+ {% if item.warrantyDetails %}+ <dt class="col-sm-3">Warranty Details</dt>+ <dd class="col-sm-9">{{ item.warrantyDetails|linebreaksbr }}</dd>+ {% endif %}+ {% if item.warrantyExpires %}+ <dt class="col-sm-3">Warranty Expires</dt>+ <dd class="col-sm-9">{{ item.warrantyExpires }}</dd>+ {% endif %}+ {% if item.notes %}+ <dt class="col-sm-3">Notes</dt>+ <dd class="col-sm-9">{{ item.notes|linebreaksbr }}</dd>+ {% endif %}+ <dt class="col-sm-3">Quantity</dt>+ <dd class="col-sm-9">{{ item.quantity }}</dd>+ <dt class="col-sm-3">Archived</dt>+ <dd class="col-sm-9">{{ item.archived|yesno:"Yes,No" }}</dd>+ </dl>++ <h2>Tags</h2>+ {% if item.tags %}+ <ul>+ {% for tag in item.tags %}+ <li>{{ tag.name }}</li>+ {% endfor %}+ </ul>+ {% else %}+ <p class="text-muted">No tags.</p>+ {% endif %}++ <h2>Custom Fields</h2>+ {% if item.fields %}+ <dl class="row">+ {% for custom in item.fields %}+ <dt class="col-sm-3">{{ custom.name }}</dt>+ <dd class="col-sm-9">{{ custom.textValue|linebreaksbr }}</dd>+ {% endfor %}+ </dl>+ {% else %}+ <p class="text-muted">No custom fields.</p>+ {% endif %}++ <h2>Attachments</h2>+ {% if item.attachments %}+ <ul>+ {% for attachment in item.attachments %}+ <li>+ <a href="{% url 'homebox_api_attachment_download' item_id=item.id attachment_id=attachment.id %}">+ {{ attachment.title }}+ </a>+ <small class="text-muted">({{ attachment.mimeType }})</small>+ </li>+ {% endfor %}+ </ul>+ {% else %}+ <p class="text-muted">No attachments.</p>+ {% endif %}+ </div>+{% endblock %}diff --git a/src/hi/simulator/services/homebox/tests/__init__.py b/src/hi/simulator/services/homebox/tests/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/simulator/services/homebox/urls.py b/src/hi/simulator/services/homebox/urls.pyindex 52525969..f641d4ee 100644--- a/src/hi/simulator/services/homebox/urls.py+++ b/src/hi/simulator/services/homebox/urls.py@@ -9,5 +9,9 @@ urlpatterns = [views.HomeView.as_view(),name = 'homebox_home' ),+ path( 'item/<str:item_id>/',+ views.ItemView.as_view(),+ name = 'homebox_item' ),+path( 'api/', include('hi.simulator.services.homebox.api.urls' )),]diff --git a/src/hi/simulator/services/homebox/views.py b/src/hi/simulator/services/homebox/views.pyindex 0327d135..174a9ac0 100644--- a/src/hi/simulator/services/homebox/views.py+++ b/src/hi/simulator/services/homebox/views.py@@ -1,7 +1,53 @@+from django.http import Http404+from django.shortcuts import renderfrom django.views.generic import View+from hi.simulator.services.homebox.sim_models import build_item_api_dict+from hi.simulator.services.homebox.simulator import HomeBoxSimulator+++def _api_id_for(fields, sim_entity_id) -> str:+ return fields.item_id or str(sim_entity_id)+class HomeView( View ):def get(self, request, *args, **kwargs):- pass+ simulator = HomeBoxSimulator()+ items = []+ for ( sim_entity_id, fields, archived_state,+ created_at, updated_at ) in simulator.get_sim_entity_pairs():+ items.append({+ 'id' : _api_id_for( fields, sim_entity_id ),+ 'name' : fields.name,+ })+ items.sort( key = lambda row: row['name'] )+ return render(+ request,+ 'homebox/home.html',+ { 'items': items },+ )+++class ItemView( View ):++ def get(self, request, *args, **kwargs):+ item_id = kwargs.get('item_id')+ simulator = HomeBoxSimulator()+ for ( sim_entity_id, fields, archived_state,+ created_at, updated_at ) in simulator.get_sim_entity_pairs():+ if _api_id_for( fields, sim_entity_id ) != item_id:+ continue+ item = build_item_api_dict(+ sim_entity_id = sim_entity_id,+ fields = fields,+ archived_state = archived_state,+ created_at = created_at,+ updated_at = updated_at,+ )+ return render(+ request,+ 'homebox/item.html',+ { 'item': item },+ )+ raise Http404( f'Item {item_id} not found' )diff --git a/src/hi/static/css/attribute.css b/src/hi/static/css/attribute.cssindex 58680db8..08823763 100644--- a/src/hi/static/css/attribute.css+++ b/src/hi/static/css/attribute.css@@ -1670,10 +1670,75 @@/* Touch device optimizations */@media (max-width: 768px) {-+.attr-v2-add-form-actions {flex-direction: column;gap: 0.75rem;align-items: stretch;}}++/* External-data view (attr-ext-*) */++.attr-ext-header {+ padding: 0.5rem 0.75rem;+ margin-bottom: 1rem;+ background: var(--info-bg-light);+ border-left: 3px solid var(--secondary-color);+ border-radius: 0.375rem;+}++.attr-ext-header__brand {+ gap: 0.5rem;+}++.attr-ext-header__logo {+ height: 16px;+ width: auto;+}++.attr-ext-attachments {+ margin-bottom: 1.5rem;+}++.attr-ext-attachment__link {+ display: flex;+ flex-direction: column;+ color: inherit;+ text-decoration: none;+}++.attr-ext-attachment__link:hover,+.attr-ext-attachment__link:focus {+ color: inherit;+ text-decoration: none;+}++.attr-ext-attribute-list {+ margin-top: 0.5rem;+}++.attr-ext-attribute-card:hover,+.attr-ext-attribute-card:focus-within {+ border-color: var(--line-color);+ box-shadow: none;+}++.attr-ext-value {+ font-size: 0.9rem;+ color: var(--primary-text-color);+ white-space: pre-wrap;+ word-break: break-word;+}++.attr-ext-value--clamped {+ display: -webkit-box;+ -webkit-line-clamp: 4;+ -webkit-box-orient: vertical;+ overflow: hidden;+}++.attr-ext-more {+ padding-left: 0;+}+diff --git a/src/hi/static/js/attr.js b/src/hi/static/js/attr.jsindex 1d1db04c..a80ea488 100644--- a/src/hi/static/js/attr.js+++ b/src/hi/static/js/attr.js@@ -529,6 +529,18 @@_initializeAllContainers();e.stopPropagation(); // Prevent bubbling to other handlers});++ $(document).on('click', '.attr-ext-more', function() {+ const $btn = $(this);+ const $value = $btn.prev('.attr-ext-value');+ if ($value.hasClass('attr-ext-value--clamped')) {+ $value.removeClass('attr-ext-value--clamped');+ $btn.text('Show less');+ } else {+ $value.addClass('attr-ext-value--clamped');+ $btn.text('Show more...');+ }+ });// Container-aware utility function for updating form actions and browser history// This is a generic helper that can be called from template onclick handlers@@ -593,6 +605,7 @@_setupBasicEventListeners($container);_initializeExpandableTextareas($container); // Must come BEFORE autosize_initializeAutosizeTextareas($container); // Now only applies to non-truncated+ _initializeExpandableExternalValues();// Note: Form submission handler removed - textarea sync now handled in Ajax submission_setupCustomAjaxHandlers($container); // NEW: Custom Ajax form handling@@ -1034,8 +1047,10 @@if (editableTextareas.length > 0) {autosize.update(editableTextareas);}++ _initializeExpandableExternalValues();}-+// Update overflow state based on current contentfunction _updateOverflowState(textarea) {const content = textarea.val() || '';@@ -1121,6 +1136,19 @@expandControls.show();}+ function _initializeExpandableExternalValues() {+ $('.attr-ext-value.attr-ext-value--clamped').each(function() {+ const $value = $(this);+ if ($value.next('.attr-ext-more').length > 0) return;+ if (this.scrollHeight > this.clientHeight + 1) {+ const $btn = $('<button type="button" class="attr-ext-more btn btn-sm btn-link">Show more...</button>');+ $value.after($btn);+ } else {+ $value.removeClass('attr-ext-value--clamped');+ }+ });+ }+function _initializeExpandableTextareas() {// Initialize based on server-rendered overflow state using hidden field patternconst displayTextareas = $(Hi.ATTR_V2_DISPLAY_FIELD_SELECTOR);