Skip to content

Home Information - Your home, your data, organized.

Python

Feature/234 homebox integration (#249)

Thiago Trautwein Santos10444fc165df
diff --git a/docs/FAQ.md b/docs/FAQ.md
index 4feae48a..9eaca0e8 100644
--- a/docs/FAQ.md
+++ b/docs/FAQ.md
@@ -58,11 +58,11 @@ We also provide some helper scripts [Helper Scripts README](../scripts/README.md
## Integrations & Compatibility
-### Q: Do I need Home Assistant or ZoneMinder to use this?
-**A:** No, integrations are completely optional. Home Information provides value as a standalone information management system. Integrations add device control and monitoring capabilities when you want them.
+### Q: Do I need Home Assistant, ZoneMinder, or HomeBox to use this?
+**A:** No, integrations are completely optional. Home Information provides value as a standalone information management system. Integrations add device control, monitoring, and inventory management capabilities when you want them.
### Q: Will it work with my existing smart home setup?
-**A:** If your devices work with Home Assistant, they'll integrate well. Home Assistant supports hundreds of device types and protocols. For security cameras, ZoneMinder integration works with most IP cameras and many older CCTV systems.
+**A:** If your devices work with Home Assistant, they'll integrate well. Home Assistant supports hundreds of device types and protocols. For security cameras, ZoneMinder integration works with most IP cameras and many older CCTV systems. For home inventory tracking, HomeBox items can be imported and displayed on your home layout.
### Q: What if my devices aren't supported?
**A:** You can still use Home Information for documentation and information management about those devices. As the project grows, we'll add more integrations based on user demand.
diff --git a/docs/Features.md b/docs/Features.md
index 1878605c..8cef5160 100644
--- a/docs/Features.md
+++ b/docs/Features.md
@@ -33,6 +33,14 @@ Home Information provides comprehensive tools for organizing, monitoring, and co
**Perfect for:** Managing complex properties where a single view becomes cluttered, or focusing on specific systems (like showing only HVAC-related items).
+### HomeBox Inventory Integration
+- **Item synchronization** - automatically import items from HomeBox into your home layout
+- **Attribute display** - view item details, warranties, purchase info, and custom fields
+- **Attachment support** - access documents and photos attached to HomeBox items
+- **Managed attributes** - HomeBox-sourced attributes are read-only to avoid conflicting edits
+
+**Use case example:** You track all your appliances and tools in HomeBox. Home Information pulls them in so you can position them on your floor plan alongside your smart home devices, giving you a complete view of everything in your home.
+
## Home Automation & Device Control
**What it does:** Integrate with existing home automation systems to provide device control within the spatial context of your home.
@@ -124,6 +132,7 @@ Home Information provides comprehensive tools for organizing, monitoring, and co
### Current Integrations
- **Home Assistant** - Complete integration with the popular open-source home automation platform
- **ZoneMinder** - Full-featured security camera management
+- **HomeBox** - Home inventory management and item tracking
- **Weather APIs** - National Weather Service and OpenMeteo for local conditions
### Integration Architecture
diff --git a/docs/Installation.md b/docs/Installation.md
index 4ffd1413..b5dd026a 100644
--- a/docs/Installation.md
+++ b/docs/Installation.md
@@ -204,6 +204,7 @@ If you enabled user authentication, you'll need to create user accounts manually
Connect Home Information with your existing home automation and security systems. See the [Integrations Guide](Integrations.md) for setup instructions:
- **Home Assistant** - Device control and monitoring
- **ZoneMinder** - Security camera management
+- **HomeBox** - Home inventory management
## Next Steps
diff --git a/docs/Integrations.md b/docs/Integrations.md
index 261a4cb0..bc1ab75f 100644
--- a/docs/Integrations.md
+++ b/docs/Integrations.md
@@ -5,6 +5,7 @@
We will add more integrations as there is demand, but presently the current supported integrations are:
- **Home Assistant** - General home automation platform for many types of devices and protocols. Requires installation and setup.
- **ZoneMinder** - For managing security cameras with motion detection. Requires installation and setup.
+- **HomeBox** - Home inventory management system for tracking household items, warranties, and documentation. Requires installation and setup.
To enable an integration, go to "Settings > Integrations > Add Integrations".
@@ -18,6 +19,10 @@ You will need install and set this up by following all their documentation. Star
You will need install and set this up by following all their documentation. Start at the [ZoneMinder Home Page](https://zoneminder.com//).
+## HomeBox
+
+You will need to install and set this up by following all their documentation. Start at the [HomeBox Home Page](https://homebox.software/). The API credentials are the same username and password you use to log into the HomeBox web interface.
+
### CORS Issues
If you are going to use the ZoneMinder integration, then viewing the camera video streams requires the server to authorize the browser to allow the ZoneMinder server to be an allowed off-site "origin". You will need to add the ZoneMinder URL to an envirornment variable to have Django server up the right headers to the browser:
diff --git a/docs/dev/integrations/integration-guidelines.md b/docs/dev/integrations/integration-guidelines.md
index 0f69a340..2ca8254d 100644
--- a/docs/dev/integrations/integration-guidelines.md
+++ b/docs/dev/integrations/integration-guidelines.md
@@ -82,7 +82,7 @@ Custom exception hierarchy:
### Example Integrations
- `hi.services.hass/` - Home Assistant integration
- `hi.services.zoneminder/` - ZoneMinder integration
-- `hi.services.weather/` - Weather service integration
+- `hi.services.homebox/` - HomeBox integration
## Related Documentation
- [Service Patterns](service-patterns.md)
diff --git a/docs/dev/integrations/service-patterns.md b/docs/dev/integrations/service-patterns.md
index 08bf09df..ad6181e3 100644
--- a/docs/dev/integrations/service-patterns.md
+++ b/docs/dev/integrations/service-patterns.md
@@ -23,6 +23,13 @@ Camera and video surveillance system integration:
- Video stream management
- Motion detection events
+## HomeBox Integration
+
+Home inventory and asset management system integration:
+- Item synchronization with read-only entity attributes
+- Custom field and attachment downloads
+- Username/password authentication with token-based session management
+
## Integration Patterns
- **HTTP API Clients**: REST API integration patterns
diff --git a/docs/dev/shared/architecture-overview.md b/docs/dev/shared/architecture-overview.md
index c1b82b6e..6075b0e2 100644
--- a/docs/dev/shared/architecture-overview.md
+++ b/docs/dev/shared/architecture-overview.md
@@ -34,6 +34,8 @@
**ZoneMinder Integration** (`src/hi/services/zoneminder/`): Camera and video surveillance system integration for security monitoring.
+**HomeBox Integration** (`src/hi/services/homebox/`): Home inventory system integration for item tracking and attribute synchronization.
+
**Integration Pattern**: All external systems use integration keys for mapping entities between systems.
## Key Architectural Patterns
diff --git a/src/hi/apps/attribute/edit_context.py b/src/hi/apps/attribute/edit_context.py
index dbb5f957..0339835b 100644
--- a/src/hi/apps/attribute/edit_context.py
+++ b/src/hi/apps/attribute/edit_context.py
@@ -240,6 +240,14 @@ class AttributeItemEditContext( AttributePageEditContext ):
@property
def add_attribute_button_html_id(self) -> str:
return f"{DIVID['ATTR_V2_ADD_ATTRIBUTE_BTN_ID']}{self.id_suffix}"
+
+ @property
+ def can_add_custom_attributes(self) -> bool:
+ return True
+
+ @property
+ def add_attribute_disabled_message(self) -> str:
+ return ''
def to_template_context(self) -> Dict[str, Any]:
template_context = super().to_template_context()
diff --git a/src/hi/apps/attribute/forms.py b/src/hi/apps/attribute/forms.py
index eaff8d15..49e9f98e 100644
--- a/src/hi/apps/attribute/forms.py
+++ b/src/hi/apps/attribute/forms.py
@@ -75,12 +75,23 @@ class AttributeForm( forms.ModelForm ):
@property
def show_secrets(self):
return self._show_secrets
-
+
+ @property
+ def suppress_add_new(self):
+ """Whether the add-new-attribute form should be suppressed in the UI.
+ Suppressed when: form is unbound (initial render) or custom attributes not allowed."""
+ if self.instance and self.instance.pk:
+ return False
+ if not self.is_bound:
+ return True
+ return not self._can_add_custom_attributes
+
def __init__(self, *args, **kwargs):
self._show_as_editable = kwargs.pop( 'show_as_editable', True )
self._allow_reordering = kwargs.pop( 'allow_reordering', True )
self._suppress_history = kwargs.pop( 'suppress_history', False )
self._show_secrets = kwargs.pop( 'show_secrets', False )
+ self._can_add_custom_attributes = kwargs.pop( 'can_add_custom_attributes', True )
instance = kwargs.get('instance')
super().__init__(*args, **kwargs)
@@ -104,10 +115,8 @@ class AttributeForm( forms.ModelForm ):
form_is_bound = bool( self.instance.pk )
if form_is_bound:
- if ( not self.instance.is_editable
- and ( value is not None )
- and ( value != self.instance.value )):
- raise ValidationError( f'The attribute "{self.instance.name}" is not editable.' )
+ if not self.instance.is_editable:
+ return cleaned_data
if ( self.instance.attribute_type == AttributeType.PREDEFINED
and ( name is not None )
and ( name != self.instance.name )):
diff --git a/src/hi/apps/attribute/templates/attribute/components/attribute_history_inline.html b/src/hi/apps/attribute/templates/attribute/components/attribute_history_inline.html
index 2d7bb2c8..eb8a9d7b 100644
--- a/src/hi/apps/attribute/templates/attribute/components/attribute_history_inline.html
+++ b/src/hi/apps/attribute/templates/attribute/components/attribute_history_inline.html
@@ -39,11 +39,21 @@ Compact history display that loads into attribute cards
</div>
<div>
{% if record.value != attribute.value %}
- <a href="{% attr_restore_url attr_item_context attribute.id record.pk %}"
- class="btn btn-xs btn-outline-primary {{ DIVID.ATTR_V2_RESTORE_LINK_CLASS }}"
- title="Restore this value">
- Restore
- </a>
+ {% if attr_item_context.can_add_custom_attributes %}
+ <a href="{% attr_restore_url attr_item_context attribute.id record.pk %}"
+ class="btn btn-xs btn-outline-primary {{ DIVID.ATTR_V2_RESTORE_LINK_CLASS }}"
+ title="Restore this value">
+ Restore
+ </a>
+ {% else %}
+ <button type="button"
+ class="btn btn-xs btn-outline-primary {{ DIVID.ATTR_V2_RESTORE_LINK_CLASS }}"
+ disabled
+ aria-disabled="true"
+ title="{{ attr_item_context.add_attribute_disabled_message }}">
+ Restore
+ </button>
+ {% endif %}
{% else %}
<small class="text-muted">Current</small>
{% endif %}
diff --git a/src/hi/apps/attribute/templates/attribute/components/edit_content_body.html b/src/hi/apps/attribute/templates/attribute/components/edit_content_body.html
index b97e5f38..97023eac 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
@@ -75,15 +75,18 @@ by using the AttributeItemEditContext pattern.
{% block additional_actions %}
{% endblock %}
{% block file_upload_button %}
- <label for="{{ attr_item_context.file_input_html_id }}"
- class="btn btn-sm btn-outline-primary mb-0">
+ <button type="button"
+ class="btn btn-sm btn-outline-primary mb-0"
+ {% if not attr_item_context.can_add_custom_attributes %}disabled aria-disabled="true" title="{{ attr_item_context.add_attribute_disabled_message }}"{% endif %}
+ onclick="document.getElementById('{{ attr_item_context.file_input_html_id }}').click();">
{% icon "upload" size="sm" css_class="hi-icon-left" %}Add File
- </label>
+ </button>
{% endblock %}
{% block add_attribute_button %}
<button id="{{ attr_item_context.add_attribute_button_html_id }}"
type="button"
class="btn btn-sm btn-outline-primary"
+ {% if not attr_item_context.can_add_custom_attributes %}disabled aria-disabled="true" title="{{ attr_item_context.add_attribute_disabled_message }}"{% endif %}
onclick="window.Hi.attr.showAddAttribute('#{{ attr_page_context.container_html_id }}');">
{% icon "plus" size="sm" css_class="hi-icon-left" %}Add Info
</button>
diff --git a/src/hi/apps/attribute/templates/attribute/components/regular_attribute_card.html b/src/hi/apps/attribute/templates/attribute/components/regular_attribute_card.html
index a4b929b5..e9705dd1 100644
--- a/src/hi/apps/attribute/templates/attribute/components/regular_attribute_card.html
+++ b/src/hi/apps/attribute/templates/attribute/components/regular_attribute_card.html
@@ -17,7 +17,7 @@ Individual attribute attribute card with value editing and actions
{% if attr_item_context.can_restore_default %}
data-default-value="{{ attribute_form.instance.get_attribute_default_value }}"
{% endif %}
- {% if not attribute_form.instance.pk and not attribute_form.is_bound %}style="display: none;"{% endif %}
+ {% if attribute_form.suppress_add_new %}style="display: none;"{% endif %}
{% if attribute_form.instance and not attribute_form.instance.is_editable %}is_editable="false"{% endif %} >
<!-- Hidden form fields -->
diff --git a/src/hi/apps/config/migrations/0006_alter_subsystemattribute_options.py b/src/hi/apps/config/migrations/0006_alter_subsystemattribute_options.py
new file mode 100644
index 00000000..57451451
--- /dev/null
+++ b/src/hi/apps/config/migrations/0006_alter_subsystemattribute_options.py
@@ -0,0 +1,21 @@
+# Generated by Django 4.2.25 on 2026-02-25 09:48
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("config", "0005_subsystemattribute_order_id"),
+ ]
+
+ operations = [
+ migrations.AlterModelOptions(
+ name="subsystemattribute",
+ options={
+ "ordering": ["order_id", "id"],
+ "verbose_name": "Subsystem Attribute",
+ "verbose_name_plural": "Subsystem Attributes",
+ },
+ ),
+ ]
diff --git a/src/hi/apps/entity/entity_attribute_edit_context.py b/src/hi/apps/entity/entity_attribute_edit_context.py
index 017e19db..3a14f5b2 100644
--- a/src/hi/apps/entity/entity_attribute_edit_context.py
+++ b/src/hi/apps/entity/entity_attribute_edit_context.py
@@ -61,6 +61,9 @@ class EntityAttributeItemEditContext(AttributeItemEditContext):
form_data,
instance = self.entity,
prefix = self.formset_prefix,
+ form_kwargs = {
+ 'can_add_custom_attributes': self.can_add_custom_attributes,
+ },
)
@property
@@ -75,3 +78,13 @@ class EntityAttributeItemEditContext(AttributeItemEditContext):
def file_upload_url(self) -> str:
return reverse( 'entity_attribute_upload',
kwargs = { 'entity_id': self.entity.id })
+
+ @property
+ def can_add_custom_attributes(self) -> bool:
+ 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.'
diff --git a/src/hi/apps/entity/forms.py b/src/hi/apps/entity/forms.py
index ba428873..c2dd60b0 100644
--- a/src/hi/apps/entity/forms.py
+++ b/src/hi/apps/entity/forms.py
@@ -28,11 +28,44 @@ class EntityAttributeForm( AttributeForm ):
model = EntityAttribute
+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 entity because attributes are managed externally.'
+ )
+
+
EntityAttributeRegularFormSet = forms.inlineformset_factory(
Entity,
EntityAttribute,
form = EntityAttributeForm,
- formset = RegularAttributeBaseFormSet,
+ formset = EntityAttributeRegularFormSet,
extra = 1,
max_num = 100,
absolute_max = 100,
diff --git a/src/hi/apps/entity/migrations/0010_alter_entityattribute_options.py b/src/hi/apps/entity/migrations/0010_alter_entityattribute_options.py
new file mode 100644
index 00000000..47415ea5
--- /dev/null
+++ b/src/hi/apps/entity/migrations/0010_alter_entityattribute_options.py
@@ -0,0 +1,21 @@
+# Generated by Django 4.2.25 on 2026-02-25 10:10
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("entity", "0009_entityattribute_order_id"),
+ ]
+
+ operations = [
+ migrations.AlterModelOptions(
+ name="entityattribute",
+ options={
+ "ordering": ["order_id", "id"],
+ "verbose_name": "Attribute",
+ "verbose_name_plural": "Attributes",
+ },
+ ),
+ ]
diff --git a/src/hi/apps/entity/migrations/0011_entity_can_add_custom_attributes.py b/src/hi/apps/entity/migrations/0011_entity_can_add_custom_attributes.py
new file mode 100644
index 00000000..7cc7a4ca
--- /dev/null
+++ b/src/hi/apps/entity/migrations/0011_entity_can_add_custom_attributes.py
@@ -0,0 +1,18 @@
+# Generated by Django 4.2.25 on 2026-02-25 10:10
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("entity", "0010_alter_entityattribute_options"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="entity",
+ name="can_add_custom_attributes",
+ field=models.BooleanField(default=True, verbose_name="Can Add Attributes?"),
+ ),
+ ]
diff --git a/src/hi/apps/entity/models.py b/src/hi/apps/entity/models.py
index 0d4e284f..86bfce5b 100644
--- a/src/hi/apps/entity/models.py
+++ b/src/hi/apps/entity/models.py
@@ -50,6 +50,10 @@ class Entity( IntegrationDetailsModel, LocationItemModelMixin ):
'User Delete?',
default = True,
)
+ can_add_custom_attributes = models.BooleanField(
+ 'Can Add Attributes?',
+ default = True,
+ )
has_video_stream = models.BooleanField(
'Has Video Stream',
default = False,
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.html
index 0d575876..7ab6fc57 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
@@ -15,7 +15,8 @@ Extends the generic attribute edit content body with entity-specific field layou
name="{{ owner_form.name.html_name }}"
value="{{ owner_form.name.value|default:'' }}"
class="form-control form-control-sm"
- {% if owner_form.name.field.required %}required{% endif %}>
+ {% if owner_form.name.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.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.py
index a30c6527..2d9ca8a0 100644
--- a/src/hi/apps/entity/tests/test_models.py
+++ b/src/hi/apps/entity/tests/test_models.py
@@ -12,6 +12,17 @@ logging.disable(logging.CRITICAL)
class TestEntity(BaseTestCase):
+ def test_can_add_attributes_defaults_to_true(self):
+ entity = Entity.objects.create(
+ name='Default Flags Entity',
+ entity_type_str=str(EntityType.OTHER),
+ integration_id='default_flags_001',
+ integration_name='test_integration',
+ )
+
+ self.assertTrue(entity.can_add_custom_attributes)
+ return
+
def test_integration_key_enforces_unique_entity_identification(self):
"""Test integration key uniqueness - critical for data integrity."""
# Create first entity with unique integration key
diff --git a/src/hi/apps/entity/tests/test_views.py b/src/hi/apps/entity/tests/test_views.py
index 3da5274a..0624c9eb 100644
--- a/src/hi/apps/entity/tests/test_views.py
+++ b/src/hi/apps/entity/tests/test_views.py
@@ -288,6 +288,47 @@ class TestEntityEditView(DualModeViewTestCase):
self.assertIsNotNone(new_attr)
self.assertEqual(new_attr.value, 'new value')
+ def test_get_disables_add_info_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})
+ response = self.client.get(url)
+
+ self.assertSuccessResponse(response)
+
+ content = response.content.decode('utf-8')
+ self.assertIn(f'attr-v2-add-attribute-btn-entity-{self.entity.id}', content)
+ self.assertIn('disabled aria-disabled="true"', content)
+ self.assertIn('New attributes are disabled for externally managed entities.', 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 entity 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
diff --git a/src/hi/apps/location/migrations/0005_alter_locationattribute_options.py b/src/hi/apps/location/migrations/0005_alter_locationattribute_options.py
new file mode 100644
index 00000000..3db8e4d6
--- /dev/null
+++ b/src/hi/apps/location/migrations/0005_alter_locationattribute_options.py
@@ -0,0 +1,21 @@
+# Generated by Django 4.2.25 on 2026-02-25 09:48
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("location", "0004_locationattribute_order_id"),
+ ]
+
+ operations = [
+ migrations.AlterModelOptions(
+ name="locationattribute",
+ options={
+ "ordering": ["order_id", "id"],
+ "verbose_name": "Attribute",
+ "verbose_name_plural": "Attributes",
+ },
+ ),
+ ]
diff --git a/src/hi/integrations/migrations/0004_alter_integrationattribute_options.py b/src/hi/integrations/migrations/0004_alter_integrationattribute_options.py
new file mode 100644
index 00000000..97eafada
--- /dev/null
+++ b/src/hi/integrations/migrations/0004_alter_integrationattribute_options.py
@@ -0,0 +1,21 @@
+# Generated by Django 4.2.25 on 2026-02-25 09:48
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("integrations", "0003_integrationattribute_order_id"),
+ ]
+
+ operations = [
+ migrations.AlterModelOptions(
+ name="integrationattribute",
+ options={
+ "ordering": ["order_id", "id"],
+ "verbose_name": "Attribute",
+ "verbose_name_plural": "Attributes",
+ },
+ ),
+ ]
diff --git a/src/hi/integrations/transient_models.py b/src/hi/integrations/transient_models.py
index aeb116e9..db068f1f 100644
--- a/src/hi/integrations/transient_models.py
+++ b/src/hi/integrations/transient_models.py
@@ -9,10 +9,11 @@ from .enums import IntegrationAttributeType
@dataclass
class IntegrationMetaData:
- integration_id : str # An identifier that must be unique across all integrations
- label : str # For human-friendly displaying
- attribute_type : IntegrationAttributeType
- allow_entity_deletion : bool
+ integration_id : str # An identifier that must be unique across all integrations
+ label : str # For human-friendly displaying
+ attribute_type : IntegrationAttributeType
+ allow_entity_deletion : bool
+ can_add_custom_attributes : bool = True
@dataclass
diff --git a/src/hi/services/homebox/__init__.py b/src/hi/services/homebox/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/services/homebox/apps.py b/src/hi/services/homebox/apps.py
new file mode 100644
index 00000000..2a1b7a95
--- /dev/null
+++ b/src/hi/services/homebox/apps.py
@@ -0,0 +1,6 @@
+from django.apps import AppConfig
+
+
+class HomeboxConfig(AppConfig):
+ default_auto_field = 'django.db.models.BigAutoField'
+ name = 'hi.services.homebox'
diff --git a/src/hi/services/homebox/enums.py b/src/hi/services/homebox/enums.py
new file mode 100644
index 00000000..5f8bdf8c
--- /dev/null
+++ b/src/hi/services/homebox/enums.py
@@ -0,0 +1,31 @@
+from hi.apps.attribute.enums import AttributeValueType
+
+from hi.integrations.enums import IntegrationAttributeType
+
+
+class HbAttributeType( IntegrationAttributeType ):
+
+ API_URL = (
+ 'API URL',
+ 'e.g., https://myserver:8443/hb/api',
+ AttributeValueType.TEXT,
+ None,
+ True,
+ True,
+ )
+ API_USER = (
+ 'Username',
+ '',
+ AttributeValueType.TEXT,
+ None,
+ True,
+ True,
+ )
+ API_PASSWORD = (
+ 'Password',
+ '',
+ AttributeValueType.SECRET,
+ None,
+ True,
+ True,
+ )
diff --git a/src/hi/services/homebox/hb_client.py b/src/hi/services/homebox/hb_client.py
new file mode 100644
index 00000000..2ebdbdcd
--- /dev/null
+++ b/src/hi/services/homebox/hb_client.py
@@ -0,0 +1,100 @@
+import logging
+from typing import Dict, List, Union, Any, Optional
+from requests import Session, Response
+
+from .hb_models import HbItem
+
+logger = logging.getLogger(__name__)
+
+
+class HbClient:
+ API_URL = 'apiurl'
+ API_USER = 'user'
+ API_PASSWORD = 'password'
+
+ DEFAULT_TIMEOUT = 25.0
+ API_VERSION = 'v1'
+
+ def __init__(self, api_options: Dict[str, str]):
+ 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
+ self._password = api_options.get(self.API_PASSWORD)
+ assert self._password is not None
+
+ self._session = Session()
+ self._login()
+
+ def _login(self):
+ url = f"{self._api_url}/{self.API_VERSION}/users/login"
+ data = {
+ 'username': self._user,
+ 'password': self._password,
+ 'stayLoggedIn': True
+ }
+ response = self._session.post(url, json=data, timeout=self.DEFAULT_TIMEOUT)
+ response.raise_for_status()
+
+ token = response.json().get('token')
+ if token:
+ self._session.headers.update({'Authorization': token})
+ else:
+ logger.warning("HomeBox login succeeded but response did not contain a token.")
+
+ def _make_request(self, method: str, url: str, **kwargs) -> Union[dict, Response]:
+ """Helper to make requests with simple re-authentication."""
+
+ kwargs.setdefault('timeout', self.DEFAULT_TIMEOUT)
+
+ response = self._session.request(method, url, **kwargs)
+
+ if response.status_code == 401 and self._user:
+ self._login()
+ response = self._session.request(method, url, **kwargs)
+
+ response.raise_for_status()
+
+ content_type = response.headers.get('content-type', '')
+ if content_type.startswith('application/json'):
+ return response.json()
+ return response
+
+ def get_items(self) -> List[HbItem]:
+ """
+ Fetches the list of items and, for each one, fetches the full details.
+ Returns a list of fully populated HbItem objects.
+ """
+ url_list = f"{self._api_url}/{self.API_VERSION}/items"
+ data = self._make_request('GET', url_list)
+ items_summary = data.get('items', []) if isinstance(data, dict) else data
+
+ full_items = []
+ for summary in items_summary:
+ item_id = summary.get('id')
+ if item_id:
+ try:
+ 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))
+ except Exception as e:
+ logger.error(f"Error fetching details for item {item_id}: {e}")
+
+ return full_items
+
+ def 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}"
+ response = self._make_request('GET', url)
+
+ if not isinstance(response, Response):
+ logger.warning(f"Expected a Response object for attachment download, got {type(response)}")
+ return None
+
+ return {
+ 'content': response.content,
+ 'mime_type': response.headers.get('content-type'),
+ }
diff --git a/src/hi/services/homebox/hb_client_factory.py b/src/hi/services/homebox/hb_client_factory.py
new file mode 100644
index 00000000..a947af02
--- /dev/null
+++ b/src/hi/services/homebox/hb_client_factory.py
@@ -0,0 +1,120 @@
+"""Factory for creating and testing HomeBox API clients."""
+
+import logging
+from typing import Dict
+
+from hi.apps.system.enums import HealthStatusType
+from hi.integrations.exceptions import IntegrationAttributeError
+from hi.integrations.models import IntegrationAttribute
+from hi.integrations.transient_models import IntegrationKey, IntegrationValidationResult
+
+from .enums import HbAttributeType
+from .hb_client import HbClient
+from .hb_metadata import HbMetaData
+
+logger = logging.getLogger(__name__)
+
+
+class HbClientFactory:
+ """Factory for creating and testing HomeBox API clients."""
+
+ def create_client(
+ self,
+ hb_attr_type_to_attribute: Dict[HbAttributeType, IntegrationAttribute]) -> HbClient:
+ """
+ Create a HbClient client from integration attributes.
+
+ Args:
+ hb_attr_type_to_attribute: Dictionary mapping attribute types to attribute objects
+
+ Returns:
+ Configured HbClient instance
+
+ Raises:
+ IntegrationAttributeError: If required attributes are missing or invalid
+ """
+ # Build API data payload
+ api_options = {
+ # 'disable_ssl_cert_check': True
+ }
+
+ attr_to_api_option_key = {
+ HbAttributeType.API_URL: HbClient.API_URL,
+ HbAttributeType.API_USER: HbClient.API_USER,
+ HbAttributeType.API_PASSWORD: HbClient.API_PASSWORD,
+ }
+
+ integration_key_to_attribute = { x.integration_key: x
+ for x in hb_attr_type_to_attribute.values() }
+
+ for hb_attr_type in attr_to_api_option_key.keys():
+ integration_key = IntegrationKey(
+ integration_id=HbMetaData.integration_id,
+ integration_name=str(hb_attr_type),
+ )
+ hb_attr = integration_key_to_attribute.get(integration_key)
+
+ if not hb_attr:
+ raise IntegrationAttributeError(
+ f'Missing HB API attribute {hb_attr_type}')
+ if not hb_attr.value.strip():
+ raise IntegrationAttributeError(
+ f'Missing HB API attribute value for {hb_attr_type}')
+
+ options_key = attr_to_api_option_key[hb_attr_type]
+ api_options[options_key] = hb_attr.value
+
+ return HbClient(api_options=api_options)
+
+ def test_client(self, client: HbClient) -> IntegrationValidationResult:
+ """
+ Test API connectivity for a given client.
+
+ Args:
+ client: HbClient instance to test
+
+ Returns:
+ IntegrationValidationResult indicating success or failure with details
+ """
+ try:
+ # Test basic API connectivity by fetching items
+ items = client.get_items()
+ if items is not None:
+ # Successful API call
+ return IntegrationValidationResult.success()
+ else:
+ return IntegrationValidationResult.error(
+ status=HealthStatusType.ERROR,
+ error_message='Failed to fetch items from HomeBox API'
+ )
+
+ except Exception as e:
+ error_msg = str(e).lower()
+
+ # Categorize common error types for better user feedback
+ if any(keyword in error_msg for keyword in ['auth',
+ 'unauthorized',
+ 'forbidden',
+ 'login',
+ 'credential',
+ 'password']):
+ status = HealthStatusType.ERROR
+ user_message = f'Authentication failed: {e}'
+ elif any(keyword in error_msg for keyword in ['connect',
+ 'network',
+ 'timeout',
+ 'unreachable',
+ 'resolve',
+ 'schema',
+ 'url']):
+ status = HealthStatusType.ERROR
+ user_message = f'Cannot connect to HomeBox: {e}'
+ else:
+ status = HealthStatusType.WARNING
+ user_message = f'API test failed: {e}'
+
+ return IntegrationValidationResult.error(
+ status=status,
+ error_message=user_message
+ )
+
diff --git a/src/hi/services/homebox/hb_controller.py b/src/hi/services/homebox/hb_controller.py
new file mode 100644
index 00000000..80c60b5a
--- /dev/null
+++ b/src/hi/services/homebox/hb_controller.py
@@ -0,0 +1,26 @@
+import logging
+
+from hi.integrations.integration_controller import IntegrationController
+from hi.integrations.transient_models import IntegrationDetails
+from hi.integrations.transient_models import IntegrationControlResult
+
+from .hb_mixins import HomeBoxMixin
+
+logger = logging.getLogger(__name__)
+
+
+class HomeBoxController( IntegrationController, HomeBoxMixin ):
+
+ def do_control(
+ self,
+ integration_details: IntegrationDetails,
+ control_value: str,
+ ) -> IntegrationControlResult:
+ logger.debug(
+ f'HomeBox do_control unsupported. details={integration_details},'
+ f' value={control_value}'
+ )
+ return IntegrationControlResult(
+ new_value = None,
+ error_list = [ 'HomeBox control actions are not implemented yet.' ],
+ )
diff --git a/src/hi/services/homebox/hb_converter.py b/src/hi/services/homebox/hb_converter.py
new file mode 100644
index 00000000..6f821dfd
--- /dev/null
+++ b/src/hi/services/homebox/hb_converter.py
@@ -0,0 +1,460 @@
+from typing import Dict, List, Optional
+import mimetypes
+import os
+
+from django.db import transaction
+from django.core.files.base import ContentFile
+
+from hi.apps.attribute.enums import AttributeType, AttributeValueType
+from hi.apps.entity.enums import EntityType
+from hi.apps.entity.models import Entity, EntityAttribute
+from hi.integrations.transient_models import IntegrationKey
+
+from .hb_metadata import HbMetaData
+from .hb_models import HbItem
+import logging
+
+logger = 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:
+
+ with transaction.atomic():
+ entity_integration_key = cls.hb_item_to_integration_key( hb_item = hb_item )
+ entity_name = cls.hb_item_to_entity_name( hb_item = hb_item )
+ entity_type = cls.hb_item_to_entity_type( hb_item = hb_item )
+
+ entity = Entity(
+ name = entity_name,
+ entity_type_str = str(entity_type),
+ can_user_delete = HbMetaData.allow_entity_deletion,
+ can_add_custom_attributes = HbMetaData.can_add_custom_attributes,
+ integration_payload = cls.hb_item_to_entity_payload( hb_item = hb_item ),
+ )
+
+ entity.integration_key = entity_integration_key
+ 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
+
+ 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
+
+ @classmethod
+ def hb_item_to_integration_key( cls, hb_item: HbItem ) -> IntegrationKey:
+ return IntegrationKey(
+ integration_id = HbMetaData.integration_id,
+ integration_name = str( hb_item.id ),
+ )
+
+ @classmethod
+ def hb_field_to_integration_key( cls, hb_field: Dict ) -> IntegrationKey:
+ field_id = str(hb_field.get('id', '')).strip()
+ if not field_id:
+ logger.error(
+ 'Field id is missing for HomeBox field with name '
+ f'{hb_field.get("name", "")}. Cannot create integration key.'
+ )
+ return None
+
+ return IntegrationKey(
+ integration_id = HbMetaData.integration_id,
+ integration_name = f'field:{field_id}',
+ )
+
+ @classmethod
+ def hb_item_to_entity_name( cls, hb_item: HbItem ) -> str:
+ item_name = hb_item.name
+
+ 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
+ def hb_item_to_entity_type( cls, hb_item: HbItem ) -> EntityType:
+ return EntityType.OTHER
+
+ @classmethod
+ def hb_item_to_entity_payload( cls, hb_item: HbItem ) -> Dict:
+ payload: Dict = {
+ 'quantity': hb_item.quantity,
+ 'insured': hb_item.insured,
+ 'archived': hb_item.archived,
+ 'created_at': hb_item.created_at,
+ 'updated_at': hb_item.updated_at,
+ 'purchase_price': hb_item.purchase_price,
+ 'asset_id': hb_item.asset_id,
+ 'sync_child_items_locations': hb_item.sync_child_items_locations,
+ 'lifetime_warranty': hb_item.lifetime_warranty,
+ 'warranty_expires': hb_item.warranty_expires,
+ 'warranty_details': hb_item.warranty_details,
+ 'purchase_time': hb_item.purchase_time,
+ 'purchase_from': hb_item.purchase_from,
+ 'sold_time': hb_item.sold_time,
+ 'sold_to': hb_item.sold_to,
+ 'sold_price': hb_item.sold_price,
+ 'sold_notes': hb_item.sold_notes,
+ 'notes': hb_item.notes,
+ }
+
+ location = hb_item.location
+ if location is None:
+ logger.warning( f'HomeBox item {hb_item.id} missing location dict' )
+ payload['location'] = None
+ else:
+ payload['location'] = {
+ 'id': location.get( 'id' ),
+ 'name': location.get( 'name' ),
+ 'description': location.get( 'description' ),
+ 'createdAt': location.get( 'createdAt' ),
+ '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'] = []
+ else:
+ normalized_labels: List[Dict] = []
+ for label in labels:
+ if not isinstance( label, 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' ),
+ })
+ payload['labels'] = normalized_labels
+
+ return payload
+
+ @classmethod
+ def hb_field_to_attribute_name( cls, hb_field: Dict ) -> str:
+ return str(hb_field.get('name', '')).strip()
+
+ @classmethod
+ 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:
+ value = str( getattr( hb_item, key, '' ) or '' ).strip()
+ if not value:
+ continue
+
+ hb_field_list.append({
+ 'id': f'hb_item:{key}',
+ 'type': 'text', # all HomeBox-created fields are text, even for numbers/booleans
+ 'name': name,
+ 'textValue': value,
+ 'numberValue': None,
+ 'booleanValue': None,
+ })
+
+ return hb_field_list
+
+ @classmethod
+ def hb_item_to_attribute_field_list( cls, hb_item: HbItem ) -> List[Dict]:
+ """Returns only normal (non-attachment) attribute fields from HomeBox item."""
+ return cls._hb_item_to_field_list( hb_item = hb_item )
+
+ @classmethod
+ def hb_attachment_to_filename( cls, hb_attachment: Dict, mime_type: str = '' ) -> str:
+ title = str( hb_attachment.get( 'title', '' ) or '' ).strip()
+ if title:
+ filename = os.path.basename( title )
+ else:
+ attachment_id = str( hb_attachment.get( 'id', '' ) or '' ).strip() or 'attachment'
+ filename = attachment_id
+
+ if '.' in filename:
+ return filename
+
+ guessed_extension = ''
+ normalized_mime_type = str( mime_type or '' ).split(';')[0].strip()
+ if normalized_mime_type:
+ guessed_extension = mimetypes.guess_extension( normalized_mime_type ) or ''
+
+ if guessed_extension:
+ return f'{filename}{guessed_extension}'
+ return filename
+
+ @classmethod
+ def hb_item_to_attachment_field_list( cls, hb_item: HbItem ) -> List[Dict]:
+ attachment_list = []
+
+ if not getattr( hb_item, 'client', None ):
+ logger.warning( f'HomeBox item {hb_item.id} has no client; cannot download attachments' )
+ return attachment_list
+
+ for attachment in list( hb_item.attachments or [] ):
+ if not isinstance( attachment, dict ):
+ continue
+
+ attachment_id = str( attachment.get( 'id', '' ) or '' ).strip()
+ if not attachment_id:
+ continue
+
+ attachment_title = (
+ str( attachment.get( 'title', '' ) or '' ).strip()
+ or f'Attachment {attachment_id}'
+ )
+ attachment_mime_type = str( attachment.get( 'mimeType', '' ) or '' ).strip()
+
+ downloaded_attachment = None
+ try:
+ downloaded_attachment = hb_item.client.download_attachment(
+ item_id = hb_item.id,
+ attachment_id = attachment_id,
+ )
+ except Exception as e:
+ logger.warning(
+ 'Unable to download HomeBox attachment '
+ f'{attachment_id} for item {hb_item.id}: {e}'
+ )
+ continue
+
+ if not downloaded_attachment:
+ logger.warning(
+ 'Missing downloaded content for HomeBox attachment '
+ f'{attachment_id} (item {hb_item.id}); skipping attachment'
+ )
+ continue
+
+ attachment_list.append({
+ 'id': f'attachment:{attachment_id}',
+ 'type': 'attachment',
+ 'name': attachment_title,
+ 'textValue': attachment_title,
+ 'numberValue': None,
+ 'booleanValue': None,
+ 'mimeType': attachment_mime_type,
+ 'attachment': attachment,
+ 'downloaded_attachment': downloaded_attachment,
+ })
+
+ return attachment_list
+
+ @classmethod
+ def hb_attachment_to_attribute_name( cls, hb_attachment: Dict ) -> str:
+ return str(hb_attachment.get('name', '')).strip()
+
+ @classmethod
+ def hb_attachment_to_integration_key( cls, hb_attachment: Dict ) -> IntegrationKey:
+ return cls.hb_field_to_integration_key( hb_field = hb_attachment )
+
+ @classmethod
+ def hb_field_to_attribute_payload( cls, hb_field: Dict, order_id: int ) -> Optional[Dict]:
+ if not isinstance( hb_field, dict ):
+ return None
+
+ hb_field_type = str( hb_field.get( 'type', '' ) or '' ).strip().lower()
+
+ if hb_field_type == 'attachment':
+ return cls.hb_attachment_to_attribute_payload(
+ hb_attachment = hb_field,
+ order_id = order_id,
+ )
+
+ integration_key = cls.hb_field_to_integration_key( hb_field = hb_field )
+ if not integration_key:
+ logger.warning( 'HomeBox field missing integration key; skipping attribute payload' )
+ return None
+
+ return {
+ 'name': cls.hb_field_to_attribute_name( hb_field = hb_field ),
+ 'value': hb_field.get('textValue', ''),
+ 'value_type_str': str(AttributeValueType.TEXT),
+ 'attribute_type_str': str(AttributeType.PREDEFINED),
+ 'is_editable': False,
+ 'is_required': False,
+ 'order_id': order_id,
+ 'integration_key_str': str( integration_key ),
+ }
+
+ @classmethod
+ def hb_attachment_to_attribute_payload( cls, hb_attachment: Dict, order_id: int ) -> Optional[Dict]:
+ if not isinstance( hb_attachment, dict ):
+ return None
+
+ downloaded_attachment = hb_attachment.get( 'downloaded_attachment' )
+ if not downloaded_attachment or not isinstance( downloaded_attachment, dict ):
+ logger.warning(
+ 'HomeBox attachment payload missing downloaded_attachment; '
+ 'skipping attribute creation'
+ )
+ return None
+
+ raw_content = downloaded_attachment.get( 'content' )
+ if not raw_content:
+ logger.warning('HomeBox attachment payload missing content; skipping attribute creation')
+ return None
+
+ mime_type = str( downloaded_attachment.get( 'mime_type', '' ) ).strip()
+ if not mime_type:
+ logger.warning('HomeBox attachment payload missing mime_type; skipping attribute creation')
+ return None
+
+ attachment_info = hb_attachment.get( 'attachment' )
+ if not attachment_info or not isinstance( attachment_info, dict ):
+ logger.warning('HomeBox attachment payload missing attachment info; skipping attribute creation')
+ return None
+
+ integration_key = cls.hb_attachment_to_integration_key( hb_attachment = hb_attachment )
+ if not integration_key:
+ logger.warning( 'HomeBox attachment missing integration key; skipping attribute creation' )
+ return None
+
+ filename = cls.hb_attachment_to_filename(
+ hb_attachment = attachment_info,
+ mime_type = mime_type,
+ )
+
+ payload = {
+ 'name': cls.hb_attachment_to_attribute_name( hb_attachment = hb_attachment ),
+ 'value': hb_attachment.get('textValue', ''),
+ 'value_type_str': str(AttributeValueType.FILE),
+ 'attribute_type_str': str(AttributeType.PREDEFINED),
+ 'is_editable': False,
+ 'is_required': False,
+ 'order_id': order_id,
+ 'integration_key_str': str( integration_key ),
+ 'file_mime_type': mime_type if mime_type else None,
+ }
+
+ 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_changed
diff --git a/src/hi/services/homebox/hb_manage_view_pane.py b/src/hi/services/homebox/hb_manage_view_pane.py
new file mode 100644
index 00000000..94226b33
--- /dev/null
+++ b/src/hi/services/homebox/hb_manage_view_pane.py
@@ -0,0 +1,19 @@
+from typing import Dict
+
+from hi.apps.entity.models import Entity
+from hi.integrations.integration_data import IntegrationData
+from hi.integrations.integration_manage_view_pane import IntegrationManageViewPane
+
+
+class HbManageViewPane( IntegrationManageViewPane ):
+
+ def get_template_name( self ) -> str:
+ return 'homebox/panes/hb_manage.html'
+
+ def get_template_context( self, integration_data : IntegrationData ) -> Dict[ str, object ]:
+
+ has_entities = Entity.objects.filter( integration_id = integration_data.integration_id ).exists()
+
+ return {
+ 'has_entities': has_entities,
+ }
diff --git a/src/hi/services/homebox/hb_manager.py b/src/hi/services/homebox/hb_manager.py
new file mode 100644
index 00000000..a066791a
--- /dev/null
+++ b/src/hi/services/homebox/hb_manager.py
@@ -0,0 +1,242 @@
+import logging
+from asgiref.sync import sync_to_async
+from typing import Dict, List
+
+from hi.apps.common.singleton_manager import SingletonManager
+from hi.apps.system.aggregate_health_provider import AggregateHealthProvider
+from hi.apps.system.api_health_status_provider import ApiHealthStatusProvider
+from hi.apps.system.provider_info import ProviderInfo
+from hi.apps.system.enums import HealthStatusType
+
+from hi.integrations.exceptions import (
+ IntegrationAttributeError,
+ IntegrationError,
+ IntegrationDisabledError,
+)
+from hi.integrations.transient_models import (
+ IntegrationKey,
+ IntegrationValidationResult,
+)
+from hi.integrations.models import Integration, IntegrationAttribute
+
+from .enums import HbAttributeType
+from .hb_client import HbClient
+from .hb_client_factory import HbClientFactory
+from .hb_metadata import HbMetaData
+
+logger = logging.getLogger(__name__)
+
+
+class HomeBoxManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusProvider ):
+
+ def __init_singleton__( self ):
+ super().__init_singleton__()
+
+ self._hb_attr_type_to_attribute = dict()
+ self._hb_client = None
+ self._client_factory = HbClientFactory()
+
+ self._hb_items_list = list()
+ self._hb_labels_list = list()
+ self._hb_locations_list = list()
+ self._hb_maintenances_list = list()
+
+ self._change_listeners = set()
+
+ self.add_api_health_status_provider(self)
+
+ return
+
+ @classmethod
+ def get_provider_info(cls) -> ProviderInfo:
+ return ProviderInfo(
+ provider_id = 'hi.services.homebox.manager',
+ provider_name = 'HomeBox Integration',
+ description = '',
+ )
+
+ @classmethod
+ def get_api_provider_info(cls) -> ProviderInfo:
+ return ProviderInfo(
+ provider_id = 'hi.services.homebox.api',
+ provider_name = 'HomeBox API',
+ description = 'HomeBox REST API',
+ )
+
+ def register_change_listener( self, callback ):
+ if callback not in self._change_listeners:
+ logger.debug( f'Adding HomeBox setting change listener from {callback.__module__}' )
+ self._change_listeners.add( callback )
+ else:
+ logger.debug( f'HomeBox setting change listener from'
+ f' {callback.__module__} already registered, skipping duplicate' )
+ return
+
+ def notify_settings_changed(self):
+ self.reload()
+ for callback in self._change_listeners:
+ try:
+ callback()
+ except Exception:
+ logger.exception( 'Problem calling setting change callback.' )
+ continue
+ return
+
+ @property
+ def hb_client(self) -> HbClient:
+ return self._hb_client
+
+ def _reload_implementation( self ):
+ try:
+ self._hb_attr_type_to_attribute = self._load_attributes()
+ self._hb_client = self.create_hb_client( self._hb_attr_type_to_attribute )
+ self.clear_caches()
+ self.record_healthy('Reloaded')
+
+ except IntegrationDisabledError:
+ msg = 'HomeBox integration disabled'
+ logger.info(msg)
+ self.record_disabled( msg )
+
+ except IntegrationError as e:
+ error_msg = f'HomeBox integration configuration error: {e}'
+ logger.error(error_msg)
+ self.record_error( f'Configuration error: {error_msg}' )
+
+ except IntegrationAttributeError as e:
+ error_msg = f'HomeBox integration attribute error: {e}'
+ logger.error(error_msg)
+ self.record_error( f'Configuration error: {error_msg}' )
+
+ except Exception as e:
+ error_msg = f'Unexpected error loading HomeBox configuration: {e}'
+ logger.exception(error_msg)
+ self.record_warning( f'Temporary issue: {error_msg}' )
+ return
+
+ def clear_caches(self):
+ self._hb_items_list = list()
+ self._hb_labels_list = list()
+ self._hb_locations_list = list()
+ self._hb_maintenances_list = list()
+ return
+
+ def _load_attributes(self) -> Dict[ HbAttributeType, IntegrationAttribute ]:
+ try:
+ hb_integration = Integration.objects.get( integration_id = HbMetaData.integration_id )
+ except Integration.DoesNotExist:
+ raise IntegrationError( 'HomeBox integration is not implemented.' )
+
+ if not hb_integration.is_enabled:
+ raise IntegrationDisabledError( 'HomeBox integration is not enabled.' )
+
+ integration_attributes = list(hb_integration.attributes.all())
+ return self._build_hb_attr_type_to_attribute_map(
+ integration_attributes = integration_attributes,
+ enforce_requirements = True,
+ )
+
+ def create_hb_client(
+ self,
+ hb_attr_type_to_attribute : Dict[ HbAttributeType, IntegrationAttribute ] ) -> HbClient:
+ return self._client_factory.create_client(hb_attr_type_to_attribute)
+
+ def fetch_hb_items_from_api( self, verbose : bool = True ) -> list:
+ if verbose:
+ logger.debug( 'Getting current HomeBox items.' )
+
+ if not self.hb_client:
+ logger.warning('HomeBox client not available - cannot fetch items')
+ return []
+
+ with self.api_call_context( 'hb_items' ):
+ return self.hb_client.get_items()
+
+ async def fetch_hb_items_from_api_async( self, verbose : bool = True ) -> list:
+ return await sync_to_async(
+ self.fetch_hb_items_from_api,
+ thread_sensitive = True,
+ )(verbose=verbose)
+
+ def test_connection(self) -> bool:
+ try:
+ if not self.hb_client:
+ self.record_error('HomeBox client not configured')
+ return False
+
+ items = self.fetch_hb_items_from_api(verbose=False)
+ if items is not None:
+ self.record_healthy('OK')
+ return True
+
+ self.record_error('Failed to fetch items from HomeBox API')
+ return False
+
+ except Exception as e:
+ error_msg = f'Connection test failed: {e}'
+ logger.debug(error_msg)
+ self.record_error( f'Connection error: {error_msg}' )
+ return False
+
+ def test_client_with_attributes(
+ self,
+ hb_attr_type_to_attribute: Dict[HbAttributeType, IntegrationAttribute]
+ ) -> IntegrationValidationResult:
+ try:
+ temp_client = self._client_factory.create_client(hb_attr_type_to_attribute)
+ return self._client_factory.test_client(temp_client)
+
+ except IntegrationError as e:
+ return IntegrationValidationResult.error(
+ status=HealthStatusType.ERROR,
+ error_message=str(e),
+ )
+ except IntegrationAttributeError as e:
+ return IntegrationValidationResult.error(
+ status=HealthStatusType.ERROR,
+ error_message=str(e),
+ )
+
+ def validate_configuration(
+ self,
+ integration_attributes: List[IntegrationAttribute]) -> IntegrationValidationResult:
+ try:
+ hb_attr_type_to_attribute = self._build_hb_attr_type_to_attribute_map(
+ integration_attributes = integration_attributes,
+ enforce_requirements = False,
+ )
+ return self.test_client_with_attributes(hb_attr_type_to_attribute)
+
+ except Exception as e:
+ logger.exception(f'Error in HomeBox configuration validation: {e}')
+ return IntegrationValidationResult.error(
+ status=HealthStatusType.WARNING,
+ error_message=f'Configuration validation failed: {e}'
+ )
+
+ def _build_hb_attr_type_to_attribute_map(
+ self,
+ integration_attributes: List[IntegrationAttribute],
+ enforce_requirements: bool = True) -> Dict[HbAttributeType, IntegrationAttribute]:
+ hb_attr_type_to_attribute = {}
+ integration_key_to_attribute = {attr.integration_key: attr for attr in integration_attributes}
+
+ for hb_attr_type in HbAttributeType:
+ integration_key = IntegrationKey(
+ integration_id = HbMetaData.integration_id,
+ integration_name = str(hb_attr_type),
+ )
+ hb_attr = integration_key_to_attribute.get(integration_key)
+
+ if not hb_attr:
+ if enforce_requirements and hb_attr_type.is_required:
+ raise IntegrationAttributeError(f'Missing HomeBox attribute {hb_attr_type}')
+ continue
+
+ if enforce_requirements and hb_attr.is_required and not hb_attr.value.strip():
+ raise IntegrationAttributeError(
+ f'Missing HomeBox attribute value for {hb_attr_type}')
+
+ hb_attr_type_to_attribute[hb_attr_type] = hb_attr
+
+ return hb_attr_type_to_attribute
diff --git a/src/hi/services/homebox/hb_metadata.py b/src/hi/services/homebox/hb_metadata.py
new file mode 100644
index 00000000..d7c41969
--- /dev/null
+++ b/src/hi/services/homebox/hb_metadata.py
@@ -0,0 +1,12 @@
+from hi.integrations.transient_models import IntegrationMetaData
+
+from .enums import HbAttributeType
+
+
+HbMetaData = IntegrationMetaData(
+ integration_id = 'hb',
+ label = 'HomeBox',
+ attribute_type = HbAttributeType,
+ allow_entity_deletion = False,
+ can_add_custom_attributes = False,
+)
diff --git a/src/hi/services/homebox/hb_mixins.py b/src/hi/services/homebox/hb_mixins.py
new file mode 100644
index 00000000..576bd3f5
--- /dev/null
+++ b/src/hi/services/homebox/hb_mixins.py
@@ -0,0 +1,34 @@
+from asgiref.sync import sync_to_async
+import asyncio
+import logging
+
+from .hb_manager import HomeBoxManager
+
+logger = logging.getLogger(__name__)
+
+
+class HomeBoxMixin:
+
+ def hb_manager(self) -> HomeBoxManager:
+ if not hasattr( self, '_hb_manager' ):
+ self._hb_manager = HomeBoxManager()
+ self._hb_manager.ensure_initialized()
+ return self._hb_manager
+
+ async def hb_manager_async(self) -> HomeBoxManager:
+ if not hasattr( self, '_hb_manager' ):
+ self._hb_manager = HomeBoxManager()
+ try:
+ await asyncio.shield(
+ sync_to_async( self._hb_manager.ensure_initialized, thread_sensitive=True )())
+
+ except asyncio.CancelledError:
+ logger.warning( 'HomeBox init sync_to_async() was cancelled! Handling gracefully.' )
+ return None
+
+ except Exception as e:
+ logger.warning(
+ f'HomeBox init sync_to_async() exception! Handling gracefully. ({e})' )
+ return None
+
+ return self._hb_manager
diff --git a/src/hi/services/homebox/hb_models.py b/src/hi/services/homebox/hb_models.py
new file mode 100644
index 00000000..a5e6ffad
--- /dev/null
+++ b/src/hi/services/homebox/hb_models.py
@@ -0,0 +1,173 @@
+from typing import Dict, List, Optional, TYPE_CHECKING, Any
+from dataclasses import dataclass
+
+if TYPE_CHECKING:
+ from .hb_client import HbClient
+
+
+class HbApi:
+ """ Central place for translating HomeBox API response strings and internal variables. """
+
+ ID_FIELD = 'id'
+ NAME_FIELD = 'name'
+ DESCRIPTION_FIELD = 'description'
+ QUANTITY_FIELD = 'quantity'
+ INSURED_FIELD = 'insured'
+ ARCHIVED_FIELD = 'archived'
+ CREATED_AT_FIELD = 'createdAt'
+ UPDATED_AT_FIELD = 'updatedAt'
+ PURCHASE_PRICE_FIELD = 'purchasePrice'
+ ASSET_ID_FIELD = 'assetId'
+ SYNC_CHILD_ITEMS_LOCATIONS_FIELD = 'syncChildItemsLocations'
+ SERIAL_NUMBER_FIELD = 'serialNumber'
+ MODEL_NUMBER_FIELD = 'modelNumber'
+ MANUFACTURER_FIELD = 'manufacturer'
+ LIFETIME_WARRANTY_FIELD = 'lifetimeWarranty'
+ WARRANTY_EXPIRES_FIELD = 'warrantyExpires'
+ WARRANTY_DETAILS_FIELD = 'warrantyDetails'
+ PURCHASE_TIME_FIELD = 'purchaseTime'
+ PURCHASE_FROM_FIELD = 'purchaseFrom'
+ SOLD_TIME_FIELD = 'soldTime'
+ SOLD_TO_FIELD = 'soldTo'
+ SOLD_PRICE_FIELD = 'soldPrice'
+ SOLD_NOTES_FIELD = 'soldNotes'
+ NOTES_FIELD = 'notes'
+ LOCATION_FIELD = 'location'
+ LABELS_FIELD = 'labels'
+ ATTACHMENTS_FIELD = 'attachments'
+ FIELDS_FIELD = 'fields'
+
+
+@dataclass
+class HbItem:
+ """ Wraps the JSON object from the API """
+
+ api_dict: Dict[str, Any]
+ client: Optional['HbClient'] = None
+
+ @property
+ def id(self) -> str:
+ return self.api_dict.get(HbApi.ID_FIELD)
+
+ @property
+ def name(self) -> str:
+ return self.api_dict.get(HbApi.NAME_FIELD, '')
+
+ @property
+ def description(self) -> str:
+ return self.api_dict.get(HbApi.DESCRIPTION_FIELD, '')
+
+ @property
+ def quantity(self) -> Optional[int]:
+ value = self.api_dict.get(HbApi.QUANTITY_FIELD)
+ return value if isinstance(value, int) else None
+
+ @property
+ def insured(self) -> Optional[bool]:
+ value = self.api_dict.get(HbApi.INSURED_FIELD)
+ return value if isinstance(value, bool) else None
+
+ @property
+ def archived(self) -> Optional[bool]:
+ value = self.api_dict.get(HbApi.ARCHIVED_FIELD)
+ return value if isinstance(value, bool) else None
+
+ @property
+ def created_at(self) -> Optional[str]:
+ value = self.api_dict.get(HbApi.CREATED_AT_FIELD)
+ return value if isinstance(value, str) and value.strip() else None
+
+ @property
+ def updated_at(self) -> Optional[str]:
+ value = self.api_dict.get(HbApi.UPDATED_AT_FIELD)
+ return value if isinstance(value, str) and value.strip() else None
+
+ @property
+ def purchase_price(self) -> Optional[float]:
+ value = self.api_dict.get(HbApi.PURCHASE_PRICE_FIELD)
+ return value if isinstance(value, (int, float)) else None
+
+ @property
+ def asset_id(self) -> Optional[str]:
+ value = self.api_dict.get(HbApi.ASSET_ID_FIELD)
+ return value if isinstance(value, str) and value.strip() else None
+
+ @property
+ def sync_child_items_locations(self) -> Optional[bool]:
+ value = self.api_dict.get(HbApi.SYNC_CHILD_ITEMS_LOCATIONS_FIELD)
+ return value if isinstance(value, bool) else None
+
+ @property
+ def serial_number(self) -> str:
+ return self.api_dict.get(HbApi.SERIAL_NUMBER_FIELD, '')
+
+ @property
+ def model_number(self) -> str:
+ return self.api_dict.get(HbApi.MODEL_NUMBER_FIELD, '')
+
+ @property
+ def manufacturer(self) -> str:
+ return self.api_dict.get(HbApi.MANUFACTURER_FIELD, '')
+
+ @property
+ def lifetime_warranty(self) -> Optional[bool]:
+ value = self.api_dict.get(HbApi.LIFETIME_WARRANTY_FIELD)
+ return value if isinstance(value, bool) else None
+
+ @property
+ def warranty_expires(self) -> Optional[str]:
+ value = self.api_dict.get(HbApi.WARRANTY_EXPIRES_FIELD)
+ return value if isinstance(value, str) and value.strip() else None
+
+ @property
+ def warranty_details(self) -> str:
+ return self.api_dict.get(HbApi.WARRANTY_DETAILS_FIELD, '')
+
+ @property
+ def purchase_time(self) -> Optional[str]:
+ value = self.api_dict.get(HbApi.PURCHASE_TIME_FIELD)
+ return value if isinstance(value, str) and value.strip() else None
+
+ @property
+ def purchase_from(self) -> str:
+ return self.api_dict.get(HbApi.PURCHASE_FROM_FIELD, '')
+
+ @property
+ def sold_time(self) -> Optional[str]:
+ value = self.api_dict.get(HbApi.SOLD_TIME_FIELD)
+ return value if isinstance(value, str) and value.strip() else None
+
+ @property
+ def sold_to(self) -> str:
+ return self.api_dict.get(HbApi.SOLD_TO_FIELD, '')
+
+ @property
+ def sold_price(self) -> Optional[float]:
+ value = self.api_dict.get(HbApi.SOLD_PRICE_FIELD)
+ return value if isinstance(value, (int, float)) else None
+
+ @property
+ def sold_notes(self) -> str:
+ return self.api_dict.get(HbApi.SOLD_NOTES_FIELD, '')
+
+ @property
+ def notes(self) -> str:
+ return self.api_dict.get(HbApi.NOTES_FIELD, '')
+
+ @property
+ def location(self) -> Optional[Dict[str, Any]]:
+ value = self.api_dict.get(HbApi.LOCATION_FIELD)
+ 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)
+ return value if isinstance(value, list) else None
+
+ @property
+ def attachments(self) -> List[Dict]:
+ return self.api_dict.get(HbApi.ATTACHMENTS_FIELD, [])
+
+ @property
+ def fields(self) -> List[Dict]:
+ return self.api_dict.get(HbApi.FIELDS_FIELD, [])
diff --git a/src/hi/services/homebox/hb_sync.py b/src/hi/services/homebox/hb_sync.py
new file mode 100644
index 00000000..da94176d
--- /dev/null
+++ b/src/hi/services/homebox/hb_sync.py
@@ -0,0 +1,330 @@
+import logging
+from typing import Dict, List
+
+from django.db import transaction
+
+from hi.apps.common.database_lock import ExclusionLockContext
+from hi.apps.common.processing_result import ProcessingResult
+from hi.apps.entity.models import Entity, EntityAttribute
+
+from hi.integrations.transient_models import IntegrationKey
+from hi.integrations.sync_mixins import IntegrationSyncMixin
+
+from .hb_converter import HbConverter
+from .hb_metadata import HbMetaData
+from .hb_mixins import HomeBoxMixin
+from .hb_models import HbItem
+
+logger = logging.getLogger(__name__)
+
+
+class HomeBoxSynchronizer( HomeBoxMixin, IntegrationSyncMixin ):
+
+ SYNCHRONIZATION_LOCK_NAME = 'hb_integration_sync'
+
+ def __init__(self):
+ return
+
+ def sync( self ) -> ProcessingResult:
+ try:
+ with ExclusionLockContext( name = self.SYNCHRONIZATION_LOCK_NAME ):
+ logger.debug( 'HomeBox integration sync started.' )
+ return self._sync_helper()
+ except RuntimeError as e:
+ logger.exception( e )
+ return ProcessingResult(
+ title = 'HomeBox Import Result',
+ error_list = [ str(e) ],
+ )
+ finally:
+ logger.debug( 'HomeBox integration sync ended.' )
+
+ def _sync_helper( self ) -> ProcessingResult:
+ hb_manager = self.hb_manager()
+ result = ProcessingResult( title = 'HomeBox Import Result' )
+
+ if not hb_manager.hb_client:
+ logger.debug( 'HomeBox client not created. HomeBox integration disabled?' )
+ result.error_list.append( 'Sync problem. HomeBox integration disabled?' )
+ return result
+
+ item_list = hb_manager.fetch_hb_items_from_api()
+ result.message_list.append( f'Found {len(item_list)} current HomeBox items.' )
+
+ self._sync_helper_entities( item_list = item_list, result = result )
+
+ return result
+
+ def _sync_helper_entities( self,
+ item_list: List[HbItem],
+ result: ProcessingResult ):
+
+ integration_key_to_item = dict()
+ for item in item_list:
+ try:
+ integration_key = HbConverter.hb_item_to_integration_key( hb_item = item )
+ integration_key_to_item[integration_key] = item
+ except Exception as e:
+ result.error_list.append( f'Ignoring HomeBox item due to missing/invalid id: {e}' )
+ continue
+
+ integration_key_to_entity = self._get_existing_hb_entities( result = result )
+ result.message_list.append( f'Found {len(integration_key_to_entity)} existing HomeBox entities.' )
+
+ with transaction.atomic():
+ for integration_key, hb_item in integration_key_to_item.items():
+ entity = integration_key_to_entity.get( integration_key )
+ if entity:
+ self._update_entity(
+ entity = entity,
+ item = hb_item,
+ result = result,
+ )
+ else:
+ entity = self._create_entity( item = hb_item, result = result )
+
+ self._sync_helper_entity_attributes(
+ entity = entity,
+ hb_item = hb_item,
+ result = result,
+ )
+ continue
+
+ for integration_key, entity in integration_key_to_entity.items():
+ if integration_key not in integration_key_to_item:
+ self._remove_entity( entity = entity, result = result )
+ continue
+
+ def _get_existing_hb_entities( self, result : ProcessingResult ) -> Dict[ IntegrationKey, Entity ]:
+ logger.debug( 'Getting existing HomeBox entities.' )
+ integration_key_to_entity = dict()
+
+ entity_queryset = Entity.objects.filter( integration_id = HbMetaData.integration_id )
+ for entity in entity_queryset:
+ integration_key = entity.integration_key
+ if not integration_key:
+ result.error_list.append( f'Entity found without valid HomeBox Id: {entity}' )
+ mock_hb_device_id = 1000000 + entity.id # We need a (unique) placeholder for removals
+ integration_key = IntegrationKey(
+ integration_id = HbMetaData.integration_id,
+ integration_name = str( mock_hb_device_id ),
+ )
+
+ integration_key_to_entity[integration_key] = entity
+ continue
+
+ return integration_key_to_entity
+
+ def _create_entity( self,
+ item : HbItem,
+ result : ProcessingResult ) -> Entity:
+ entity = HbConverter.create_models_for_hb_item( hb_item = item )
+
+ result.message_list.append( f'Created HomeBox entity: {entity}' )
+ return entity
+
+ def _update_entity( self,
+ entity : Entity,
+ item : HbItem,
+ result : ProcessingResult ):
+ message_list = HbConverter.update_models_for_hb_item( entity = entity, hb_item = item )
+
+ if message_list:
+ result.message_list.append( f'Updated HomeBox entity: {entity} ({", ".join(message_list)})' )
+ else:
+ result.message_list.append( f'No changes found for HomeBox entity: {entity}' )
+ return
+
+ def _remove_entity( self,
+ entity : Entity,
+ result : ProcessingResult ):
+ self._remove_entity_intelligently( entity, result, 'HomeBox' )
+ return
+
+ def _sync_helper_entity_attributes( self,
+ entity: Entity,
+ hb_item: HbItem,
+ result: ProcessingResult ):
+ attribute_message_list = list()
+
+ integration_key_to_regular_field = dict()
+ hb_field_list = HbConverter.hb_item_to_attribute_field_list( hb_item = hb_item )
+ for order_id, hb_field in enumerate( hb_field_list ):
+ if not isinstance( hb_field, dict ):
+ continue
+
+ integration_key = HbConverter.hb_field_to_integration_key( hb_field = hb_field )
+ if integration_key:
+ integration_key_to_regular_field[integration_key] = (hb_field, order_id)
+
+ integration_key_to_attachment = dict()
+ attachment_list = HbConverter.hb_item_to_attachment_field_list( hb_item = hb_item )
+ field_count = len( hb_field_list )
+ for order_id, hb_attachment in enumerate( attachment_list, start = field_count ):
+ if not isinstance( hb_attachment, dict ):
+ continue
+
+ integration_key = HbConverter.hb_attachment_to_integration_key( hb_attachment = hb_attachment )
+ if integration_key:
+ integration_key_to_attachment[integration_key] = ( hb_attachment, order_id )
+
+ active_integration_keys = set(integration_key_to_regular_field.keys())
+ active_integration_keys.update(integration_key_to_attachment.keys())
+
+ integration_key_to_attr = self._get_existing_hb_attributes(entity = entity)
+
+ with transaction.atomic():
+
+ for integration_key, field_data in integration_key_to_regular_field.items():
+ hb_field, order_id = field_data
+ attribute = integration_key_to_attr.get( integration_key )
+
+ if attribute:
+ self._update_attribute(
+ attribute = attribute,
+ hb_field = hb_field,
+ order_id = order_id,
+ message_list = attribute_message_list,
+ updated_prefix = 'Field attribute updated',
+ )
+ else:
+ created_attribute = self._create_attribute(
+ entity = entity,
+ hb_field = hb_field,
+ order_id = order_id,
+ )
+ if created_attribute:
+ integration_key_to_attr[integration_key] = created_attribute
+ attribute_message_list.append(
+ f'Field attribute added: {created_attribute.name}'
+ )
+ continue
+
+ for integration_key, hb_attachment_tuple in integration_key_to_attachment.items():
+ hb_attachment, order_id = hb_attachment_tuple
+ attribute = integration_key_to_attr.get( integration_key )
+
+ if attribute:
+ self._update_attachment_attribute(
+ attribute = attribute,
+ hb_attachment = hb_attachment,
+ order_id = order_id,
+ message_list = attribute_message_list,
+ updated_prefix = 'Attachment attribute updated',
+ )
+ else:
+ created_attribute = self._create_attachment_attribute(
+ entity = entity,
+ hb_attachment = hb_attachment,
+ order_id = order_id,
+ )
+ if created_attribute:
+ integration_key_to_attr[integration_key] = created_attribute
+ attribute_message_list.append(
+ f'Attachment attribute added: {created_attribute.name}'
+ )
+ continue
+
+ for field_key, attribute in list( integration_key_to_attr.items() ):
+ if attribute.entity_id != entity.id:
+ continue
+
+ if field_key not in active_integration_keys:
+ self._remove_attribute( attribute = attribute, message_list = attribute_message_list )
+ del integration_key_to_attr[field_key]
+ continue
+
+ if attribute_message_list:
+ message = (
+ f'Updated HomeBox entity attributes: {entity} '
+ f'({", ".join(attribute_message_list)})'
+ )
+ result.message_list.append( message )
+ return
+
+ def _get_existing_hb_attributes( self, entity: Entity ) -> Dict[ IntegrationKey, EntityAttribute ]:
+ integration_key_to_attribute = dict()
+
+ queryset = entity.attributes.filter(
+ integration_key_str__isnull = False
+ ).exclude( integration_key_str = '' )
+
+ for attribute in queryset:
+ try:
+ integration_key = IntegrationKey.from_string( attribute.integration_key_str )
+ except Exception:
+ logger.debug(
+ 'Ignoring entity attribute with invalid integration key: '
+ f'{attribute.integration_key_str}'
+ )
+ continue
+
+ integration_key_to_attribute[integration_key] = attribute
+
+ return integration_key_to_attribute
+
+ def _create_attribute( self,
+ entity: Entity,
+ hb_field: dict,
+ order_id: int ) -> EntityAttribute:
+ return HbConverter.create_attribute_from_hb_field(
+ entity = entity,
+ hb_field = hb_field,
+ order_id = order_id,
+ )
+
+ def _update_attribute( self,
+ attribute: EntityAttribute,
+ hb_field: dict,
+ order_id: int,
+ message_list: List[str],
+ updated_prefix: str ):
+ was_changed = HbConverter.update_attribute_from_hb_field(
+ attribute = attribute,
+ hb_field = hb_field,
+ order_id = order_id,
+ )
+ if was_changed:
+ message = (
+ f'{updated_prefix}: '
+ f'{HbConverter.hb_field_to_attribute_name( hb_field = hb_field )}'
+ )
+ message_list.append( message )
+ return
+
+ def _remove_attribute( self,
+ attribute: EntityAttribute,
+ message_list: List[str] ):
+ old_name = attribute.name
+ attribute.delete()
+ message_list.append( f'Field attribute removed: {old_name}' )
+ return
+
+ def _create_attachment_attribute( self,
+ entity: Entity,
+ hb_attachment: dict,
+ order_id: int ) -> EntityAttribute:
+ return HbConverter.create_attribute_from_hb_attachment(
+ entity = entity,
+ hb_attachment = hb_attachment,
+ order_id = order_id,
+ )
+
+ def _update_attachment_attribute( self,
+ attribute: EntityAttribute,
+ hb_attachment: dict,
+ order_id: int,
+ message_list: List[str],
+ updated_prefix: str ):
+ was_changed = HbConverter.update_attribute_from_hb_attachment(
+ attribute = attribute,
+ hb_attachment = hb_attachment,
+ order_id = order_id,
+ )
+ if was_changed:
+ message = (
+ f'{updated_prefix}: '
+ f'{HbConverter.hb_attachment_to_attribute_name( hb_attachment = hb_attachment )}'
+ )
+ message_list.append( message )
+ return
diff --git a/src/hi/services/homebox/integration.py b/src/hi/services/homebox/integration.py
new file mode 100644
index 00000000..27d32d84
--- /dev/null
+++ b/src/hi/services/homebox/integration.py
@@ -0,0 +1,67 @@
+import logging
+from typing import List
+
+from hi.apps.system.enums import HealthStatusType
+from hi.apps.system.health_status_provider import HealthStatusProvider
+
+from hi.integrations.integration_controller import IntegrationController
+from hi.integrations.integration_gateway import IntegrationGateway
+from hi.integrations.integration_manage_view_pane import IntegrationManageViewPane
+from hi.integrations.models import IntegrationAttribute
+from hi.integrations.transient_models import IntegrationMetaData, IntegrationValidationResult
+from hi.apps.monitor.periodic_monitor import PeriodicMonitor
+
+from .hb_controller import HomeBoxController
+from .hb_manage_view_pane import HbManageViewPane
+from .hb_manager import HomeBoxManager
+from .hb_metadata import HbMetaData
+from .monitors import HomeBoxMonitor
+
+logger = logging.getLogger(__name__)
+
+
+class HomeBoxGateway(IntegrationGateway):
+ def get_metadata(self) -> IntegrationMetaData:
+ return HbMetaData
+
+ def get_manage_view_pane(self) -> IntegrationManageViewPane:
+ return HbManageViewPane()
+
+ def get_monitor(self) -> PeriodicMonitor:
+ return HomeBoxMonitor()
+
+ def get_controller(self) -> IntegrationController:
+ return HomeBoxController()
+
+ def notify_settings_changed(self):
+ """Notify HomeBox integration that settings have changed.
+
+ Delegates to HomeBoxManager to reload configuration and notify monitors.
+ """
+ try:
+ hb_manager = HomeBoxManager()
+ hb_manager.notify_settings_changed()
+ logger.debug('HomeBox integration notified of settings change')
+ except Exception as e:
+ logger.exception(f'Error notifying HomeBox integration of settings change: {e}')
+
+ def get_health_status_provider(self) -> HealthStatusProvider:
+ return HomeBoxManager()
+
+ def validate_configuration(
+ self,
+ integration_attributes: List[IntegrationAttribute]
+ ) -> IntegrationValidationResult:
+ """Validate HomeBox integration configuration by testing API connectivity.
+
+ Delegates to HomeBoxManager for configuration validation.
+ """
+ try:
+ hb_manager = HomeBoxManager()
+ return hb_manager.validate_configuration(integration_attributes)
+ except Exception as e:
+ logger.exception(f'Error validating HomeBox integration configuration: {e}')
+ return IntegrationValidationResult.error(
+ status=HealthStatusType.WARNING,
+ error_message=f'Configuration validation failed: {e}'
+ )
diff --git a/src/hi/services/homebox/monitors.py b/src/hi/services/homebox/monitors.py
new file mode 100644
index 00000000..76455fd9
--- /dev/null
+++ b/src/hi/services/homebox/monitors.py
@@ -0,0 +1,75 @@
+import logging
+
+from hi.apps.monitor.periodic_monitor import PeriodicMonitor
+from hi.apps.system.provider_info import ProviderInfo
+
+from .hb_mixins import HomeBoxMixin
+
+logger = logging.getLogger(__name__)
+
+
+class HomeBoxMonitor( PeriodicMonitor, HomeBoxMixin ):
+
+ MONITOR_ID = 'hi.services.homebox.monitor'
+ HOMEBOX_POLLING_INTERVAL_SECS = 30
+ HOMEBOX_API_TIMEOUT_SECS = 20.0
+
+ def __init__( self ):
+ super().__init__(
+ id = self.MONITOR_ID,
+ interval_secs = self.HOMEBOX_POLLING_INTERVAL_SECS,
+ )
+ self._was_initialized = False
+ return
+
+ def get_api_timeout(self) -> float:
+ return self.HOMEBOX_API_TIMEOUT_SECS
+
+ async def _initialize(self):
+ hb_manager = await self.hb_manager_async()
+ if not hb_manager:
+ return
+ hb_manager.register_change_listener( self.refresh )
+ self._was_initialized = True
+ return
+
+ def refresh( self ):
+ self._was_initialized = False
+ logger.info( 'HomeBoxMonitor refreshed - will reinitialize with new settings on next cycle' )
+ return
+
+ @classmethod
+ def get_provider_info(cls) -> ProviderInfo:
+ return ProviderInfo(
+ provider_id = cls.MONITOR_ID,
+ provider_name = 'HomeBox Monitor',
+ description = 'HomeBox integration health monitor',
+ expected_heartbeat_interval_secs = cls.HOMEBOX_POLLING_INTERVAL_SECS,
+ )
+
+ async def do_work(self):
+ if not self._was_initialized:
+ await self._initialize()
+
+ if not self._was_initialized:
+ logger.warning( 'HomeBox monitor failed to initialize. Skipping work cycle.' )
+ self.record_warning( 'Was not initialized.' )
+ return
+
+ hb_manager = await self.hb_manager_async()
+ if not hb_manager:
+ self.record_error( 'No manager found.' )
+ return
+
+ item_list = await self._process_items( hb_manager )
+
+ message = (
+ f'Processed HomeBox resources. '
+ f'items={len(item_list)}'
+ )
+ self.record_healthy( message )
+ hb_manager.record_healthy( message )
+ return
+
+ async def _process_items(self, hb_manager):
+ return await hb_manager.fetch_hb_items_from_api_async( verbose = False )
diff --git a/src/hi/services/homebox/templates/homebox/panes/hb_manage.html b/src/hi/services/homebox/templates/homebox/panes/hb_manage.html
new file mode 100644
index 00000000..2e1817e3
--- /dev/null
+++ b/src/hi/services/homebox/templates/homebox/panes/hb_manage.html
@@ -0,0 +1,30 @@
+{% load static %}
+{% load icons %}
+
+<div class="d-flex justify-content-between">
+ <div class="h3 integration-title">
+ <img class="img-fluid"
+ src="{% static 'img/integrations/homebox.svg' %}"
+ alt="HomeBox Logo">
+ HomeBox
+ </div>
+ <div class="">
+ <form action="{% url 'hb_sync' %}"
+ method="POST" role="form" data-async="true">
+ {% csrf_token %}
+ <button type="submit" class="btn btn-outline-secondary" role="button"
+ name="action" value="sync" >
+ {% if has_entities %}
+ {% icon "sync" size="sm" css_class="hi-icon-left" %}RE-SYNC
+ {% else %}
+ {% icon "upload" size="sm" css_class="hi-icon-left" %}IMPORT
+ {% endif %}
+ </button>
+ </form>
+ </div>
+</div>
+{% if not has_entities %}
+<div class="alert alert-warning text-center">
+ Use the "IMPORT" button to add items from HomeBox.
+</div>
+{% endif %}
diff --git a/src/hi/services/homebox/tests/__init__.py b/src/hi/services/homebox/tests/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/services/homebox/tests/test_hb_client.py b/src/hi/services/homebox/tests/test_hb_client.py
new file mode 100644
index 00000000..24d44189
--- /dev/null
+++ b/src/hi/services/homebox/tests/test_hb_client.py
@@ -0,0 +1,131 @@
+import logging
+import json
+from unittest.mock import Mock, patch
+
+from django.test import SimpleTestCase
+from requests import Response
+
+from hi.services.homebox.hb_client import HbClient
+from hi.services.homebox.hb_models import HbItem
+
+
+logging.disable(logging.CRITICAL)
+
+
+class TestHbClient(SimpleTestCase):
+
+ def _api_options(self):
+ return {
+ HbClient.API_URL: 'https://homebox.local',
+ HbClient.API_USER: 'user',
+ HbClient.API_PASSWORD: 'pass',
+ }
+
+ def _response(self, status_code=200, json_data=None, content_type='application/json', content=b''):
+ response = Response()
+ response.status_code = status_code
+ response.headers['content-type'] = content_type
+
+ if json_data is not None:
+ response._content = json.dumps(json_data).encode('utf-8')
+ else:
+ response._content = content
+
+ return response
+
+ def test_init_strips_trailing_slash_and_logs_in_when_credentials_exist(self):
+ with patch.object(HbClient, '_login') as mock_login:
+ client = HbClient(api_options={
+ HbClient.API_URL: 'https://homebox.local/',
+ HbClient.API_USER: 'user',
+ HbClient.API_PASSWORD: 'pass',
+ })
+
+ self.assertEqual(client._api_url, 'https://homebox.local')
+ mock_login.assert_called_once()
+
+ def test_make_request_retries_after_unauthorized(self):
+ with patch.object(HbClient, '_login') as mock_login:
+ client = HbClient(api_options={
+ HbClient.API_URL: 'https://homebox.local',
+ HbClient.API_USER: 'user',
+ HbClient.API_PASSWORD: 'pass',
+ })
+ mock_login.reset_mock()
+
+ unauthorized = self._response(status_code=401, json_data={'detail': 'Unauthorized'})
+ success = self._response(status_code=200, json_data={'items': []})
+
+ client._session.request = Mock(side_effect=[unauthorized, success])
+
+ result = client._make_request('GET', 'https://homebox.local/v1/items')
+
+ self.assertEqual(result, {'items': []})
+ self.assertEqual(client._session.request.call_count, 2)
+ mock_login.assert_called_once()
+
+ def test_make_request_returns_response_for_non_json_content(self):
+ with patch.object(HbClient, '_login'):
+ client = HbClient(api_options=self._api_options())
+
+ binary_response = self._response(
+ status_code=200,
+ json_data=None,
+ content_type='application/octet-stream',
+ content=b'file-bytes',
+ )
+ client._session.request = Mock(return_value=binary_response)
+
+ result = client._make_request('GET', 'https://homebox.local/v1/items/1/attachments/1')
+
+ self.assertIs(result, binary_response)
+
+ def test_get_items_fetches_detail_and_skips_invalid_or_failed_items(self):
+ with patch.object(HbClient, '_login'):
+ client = HbClient(api_options=self._api_options())
+
+ client._make_request = Mock(side_effect=[
+ {'items': [{'id': 'item-1'}, {'id': 'item-2'}, {}, {'id': 'item-3'}]},
+ {'id': 'item-1', 'name': 'One'},
+ Exception('detail request failed'),
+ {'id': 'item-3', 'name': 'Three'},
+ ])
+
+ items = client.get_items()
+
+ self.assertEqual(len(items), 2)
+ self.assertIsInstance(items[0], HbItem)
+ self.assertIsInstance(items[1], HbItem)
+ self.assertEqual(items[0].id, 'item-1')
+ self.assertEqual(items[1].id, 'item-3')
+
+ def test_download_attachment_returns_none_when_request_is_not_response(self):
+ with patch.object(HbClient, '_login'):
+ client = HbClient(api_options=self._api_options())
+ client._make_request = Mock(return_value={'content': 'wrong-type'})
+
+ payload = client.download_attachment(item_id='item-1', attachment_id='att-1')
+
+ self.assertIsNone(payload)
+ client._make_request.assert_called_once_with(
+ 'GET',
+ 'https://homebox.local/v1/items/item-1/attachments/att-1',
+ )
+
+ def test_download_attachment_returns_content_and_mime_type(self):
+ with patch.object(HbClient, '_login'):
+ client = HbClient(api_options=self._api_options())
+ response = self._response(
+ status_code=200,
+ json_data=None,
+ content_type='image/png',
+ content=b'PNGDATA',
+ )
+ client._make_request = Mock(return_value=response)
+
+ payload = client.download_attachment(item_id='item-1', attachment_id='att-1')
+
+ self.assertEqual(payload, {
+ 'content': b'PNGDATA',
+ 'mime_type': 'image/png',
+ })
diff --git a/src/hi/services/homebox/tests/test_hb_client_factory.py b/src/hi/services/homebox/tests/test_hb_client_factory.py
new file mode 100644
index 00000000..6572090e
--- /dev/null
+++ b/src/hi/services/homebox/tests/test_hb_client_factory.py
@@ -0,0 +1,148 @@
+"""
+Tests for HomeBox client factory functionality.
+Focuses on high-value testing: client creation, validation, and error handling.
+"""
+
+import logging
+from unittest.mock import Mock, patch
+from django.test import TestCase
+
+from hi.apps.system.enums import HealthStatusType
+from hi.integrations.exceptions import IntegrationAttributeError
+from hi.integrations.models import IntegrationAttribute
+from hi.integrations.transient_models import IntegrationKey, IntegrationValidationResult
+
+from hi.services.homebox.enums import HbAttributeType
+from hi.services.homebox.hb_client_factory import HbClientFactory
+from hi.services.homebox.hb_metadata import HbMetaData
+
+logging.disable(logging.CRITICAL)
+
+
+class TestHbClientFactory(TestCase):
+ """Test HbClientFactory creation and validation behavior."""
+
+ def setUp(self):
+ self.factory = HbClientFactory()
+
+ def _create_test_attributes(self):
+ """Create realistic test attributes for client creation."""
+ attributes = {}
+
+ attr_values = {
+ HbAttributeType.API_URL: 'https://homebox.example.com/api',
+ HbAttributeType.API_USER: 'test_user',
+ HbAttributeType.API_PASSWORD: 'test_password',
+ }
+
+ for attr_type, value in attr_values.items():
+ integration_key = IntegrationKey(
+ integration_id=HbMetaData.integration_id,
+ integration_name=str(attr_type),
+ )
+
+ attr = Mock(spec=IntegrationAttribute)
+ attr.integration_key = integration_key
+ attr.value = value
+ attr.is_required = attr_type.is_required
+
+ attributes[attr_type] = attr
+
+ return attributes
+
+ @patch('hi.services.homebox.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
+ mock_client_class.API_URL = RealHbClient.API_URL
+ mock_client_class.API_USER = RealHbClient.API_USER
+ mock_client_class.API_PASSWORD = RealHbClient.API_PASSWORD
+
+ mock_client = Mock()
+ mock_client_class.return_value = mock_client
+ attributes = self._create_test_attributes()
+
+ result = self.factory.create_client(attributes)
+
+ self.assertIs(result, mock_client)
+
+ expected_options = {
+ RealHbClient.API_URL: 'https://homebox.example.com/api',
+ RealHbClient.API_USER: 'test_user',
+ RealHbClient.API_PASSWORD: 'test_password',
+ }
+ mock_client_class.assert_called_once_with(api_options=expected_options)
+
+ def test_create_client_missing_required_attribute(self):
+ """Test client creation fails with missing required attribute."""
+ attributes = self._create_test_attributes()
+ del attributes[HbAttributeType.API_URL]
+
+ with self.assertRaises(IntegrationAttributeError) as context:
+ self.factory.create_client(attributes)
+
+ self.assertIn('Missing HB API attribute', str(context.exception))
+ self.assertIn('api_url', str(context.exception))
+
+ def test_create_client_empty_attribute_value(self):
+ """Test client creation fails with empty attribute value."""
+ attributes = self._create_test_attributes()
+ attributes[HbAttributeType.API_USER].value = ' '
+
+ with self.assertRaises(IntegrationAttributeError) as context:
+ self.factory.create_client(attributes)
+
+ self.assertIn('Missing HB API attribute value', str(context.exception))
+ self.assertIn('api_user', str(context.exception))
+
+ def test_test_client_success(self):
+ """Test successful client connectivity testing."""
+ mock_client = Mock()
+ mock_client.get_items.return_value = []
+
+ result = self.factory.test_client(mock_client)
+
+ self.assertIsInstance(result, IntegrationValidationResult)
+ self.assertTrue(result.is_valid)
+ self.assertEqual(result.status, HealthStatusType.HEALTHY)
+ self.assertIsNone(result.error_message)
+
+ mock_client.get_items.assert_called_once()
+
+ def test_test_client_connection_failure(self):
+ """Test client testing with connection failure."""
+ mock_client = Mock()
+ mock_client.get_items.side_effect = ConnectionError('Cannot connect to HomeBox')
+
+ result = self.factory.test_client(mock_client)
+
+ self.assertIsInstance(result, IntegrationValidationResult)
+ self.assertFalse(result.is_valid)
+ self.assertEqual(result.status, HealthStatusType.ERROR)
+ self.assertIn('Cannot connect to HomeBox', result.error_message)
+
+ def test_test_client_authentication_failure(self):
+ """Test client testing with authentication failure."""
+ mock_client = Mock()
+ mock_client.get_items.side_effect = Exception('401 Unauthorized')
+
+ result = self.factory.test_client(mock_client)
+
+ self.assertIsInstance(result, IntegrationValidationResult)
+ self.assertFalse(result.is_valid)
+ self.assertEqual(result.status, HealthStatusType.ERROR)
+ self.assertIn('Authentication failed', result.error_message)
+
+ def test_test_client_returns_none_items(self):
+ """Test client testing when items call returns None."""
+ mock_client = Mock()
+ mock_client.get_items.return_value = None
+
+ result = self.factory.test_client(mock_client)
+
+ self.assertIsInstance(result, IntegrationValidationResult)
+ self.assertFalse(result.is_valid)
+ self.assertEqual(result.status, HealthStatusType.ERROR)
+ self.assertIn('Failed to fetch items from HomeBox API', result.error_message)
+
+ mock_client.get_items.assert_called_once()
diff --git a/src/hi/services/homebox/tests/test_hb_converter.py b/src/hi/services/homebox/tests/test_hb_converter.py
new file mode 100644
index 00000000..7da1d984
--- /dev/null
+++ b/src/hi/services/homebox/tests/test_hb_converter.py
@@ -0,0 +1,164 @@
+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.hb_converter import HbConverter
+from hi.services.homebox.hb_metadata import HbMetaData
+from hi.services.homebox.hb_models import HbItem
+
+
+logging.disable(logging.CRITICAL)
+
+
+class TestHbConverter(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'},
+ 'labels': [{'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 = 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_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'
+
+ 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 }
+
+ self.assertEqual( field_id_to_field['hb_item:description']['textValue'], 'Portable drill' )
+ 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' )
+
+ def test_hb_item_attachment_maps_to_file_attribute_payload(self):
+ item = self._mock_item(item_id='item-with-attachment')
+ item.api_dict['attachments'] = [{
+ 'id': 'att-1',
+ 'title': 'Manual',
+ 'mimeType': 'text/plain',
+ 'path': 'some/path',
+ }]
+ item.client.download_attachment.return_value = {
+ 'content': b'attachment-content',
+ 'mime_type': 'text/plain',
+ 'filename': 'Manual.txt',
+ 'source_url': 'https://example/download',
+ }
+
+ attachment_field_list = HbConverter.hb_item_to_attachment_field_list(hb_item=item)
+ attachment_data = attachment_field_list[0]
+ payload = HbConverter.hb_attachment_to_attribute_payload(hb_attachment=attachment_data, order_id=0)
+
+ self.assertEqual(payload['value_type_str'], str(AttributeValueType.FILE))
+ self.assertEqual(payload['name'], 'Manual')
+ 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)
diff --git a/src/hi/services/homebox/tests/test_hb_manager.py b/src/hi/services/homebox/tests/test_hb_manager.py
new file mode 100644
index 00000000..218e41cf
--- /dev/null
+++ b/src/hi/services/homebox/tests/test_hb_manager.py
@@ -0,0 +1,87 @@
+import logging
+from unittest.mock import Mock
+
+from django.test import SimpleTestCase
+
+from hi.integrations.exceptions import IntegrationAttributeError
+from hi.integrations.models import IntegrationAttribute
+from hi.integrations.transient_models import IntegrationKey
+from hi.services.homebox.enums import HbAttributeType
+from hi.services.homebox.hb_manager import HomeBoxManager
+from hi.services.homebox.hb_metadata import HbMetaData
+
+
+logging.disable(logging.CRITICAL)
+
+
+class TestHomeBoxManagerAttributeMap(SimpleTestCase):
+
+ def setUp(self):
+ self.manager = HomeBoxManager.__new__(HomeBoxManager)
+
+ def _mock_attribute(self, hb_attr_type: HbAttributeType, value: str):
+ attr = Mock(spec=IntegrationAttribute)
+ attr.integration_key = IntegrationKey(
+ integration_id=HbMetaData.integration_id,
+ integration_name=str(hb_attr_type),
+ )
+ attr.value = value
+ attr.is_required = hb_attr_type.is_required
+ return attr
+
+ def test_build_map_returns_all_required_attributes_when_valid(self):
+ attrs = [
+ self._mock_attribute(HbAttributeType.API_URL, 'https://homebox.local/api'),
+ self._mock_attribute(HbAttributeType.API_USER, 'user'),
+ self._mock_attribute(HbAttributeType.API_PASSWORD, 'secret'),
+ ]
+
+ result = self.manager._build_hb_attr_type_to_attribute_map(
+ integration_attributes=attrs,
+ enforce_requirements=True,
+ )
+
+ self.assertEqual(set(result.keys()), set(HbAttributeType))
+
+ def test_build_map_raises_when_required_attribute_missing_and_enforced(self):
+ attrs = [
+ self._mock_attribute(HbAttributeType.API_URL, 'https://homebox.local/api'),
+ self._mock_attribute(HbAttributeType.API_USER, 'user'),
+ ]
+
+ with self.assertRaises(IntegrationAttributeError) as context:
+ self.manager._build_hb_attr_type_to_attribute_map(
+ integration_attributes=attrs,
+ enforce_requirements=True,
+ )
+
+ self.assertIn('Missing HomeBox attribute', str(context.exception))
+ self.assertIn('api_password', str(context.exception))
+
+ def test_build_map_allows_missing_when_requirements_not_enforced(self):
+ attrs = [
+ self._mock_attribute(HbAttributeType.API_URL, 'https://homebox.local/api'),
+ ]
+
+ result = self.manager._build_hb_attr_type_to_attribute_map(
+ integration_attributes=attrs,
+ enforce_requirements=False,
+ )
+
+ self.assertEqual(set(result.keys()), {HbAttributeType.API_URL})
+
+ def test_build_map_raises_when_required_value_is_blank_and_enforced(self):
+ attrs = [
+ self._mock_attribute(HbAttributeType.API_URL, 'https://homebox.local/api'),
+ self._mock_attribute(HbAttributeType.API_USER, ' '),
+ self._mock_attribute(HbAttributeType.API_PASSWORD, 'secret'),
+ ]
+
+ with self.assertRaises(IntegrationAttributeError) as context:
+ self.manager._build_hb_attr_type_to_attribute_map(
+ integration_attributes=attrs,
+ enforce_requirements=True,
+ )
+
+ self.assertIn('Missing HomeBox attribute value', str(context.exception))
+ self.assertIn('api_user', str(context.exception))
diff --git a/src/hi/services/homebox/tests/test_hb_models.py b/src/hi/services/homebox/tests/test_hb_models.py
new file mode 100644
index 00000000..24a2ec58
--- /dev/null
+++ b/src/hi/services/homebox/tests/test_hb_models.py
@@ -0,0 +1,127 @@
+import logging
+from django.test import SimpleTestCase
+
+from hi.services.homebox.hb_models import HbItem
+
+
+logging.disable(logging.CRITICAL)
+
+
+class TestHbItem(SimpleTestCase):
+
+ def _create_item(self, **kwargs):
+ base_data = {
+ 'id': 'item-1',
+ 'name': 'Drill',
+ 'description': 'Cordless drill',
+ 'quantity': 2,
+ 'insured': True,
+ 'archived': False,
+ 'createdAt': '2025-01-01T00:00:00Z',
+ 'updatedAt': '2025-01-02T00:00:00Z',
+ 'purchasePrice': 99.5,
+ 'assetId': 'A-1',
+ 'syncChildItemsLocations': True,
+ 'serialNumber': 'S-1',
+ 'modelNumber': 'M-1',
+ 'manufacturer': 'ACME',
+ 'lifetimeWarranty': False,
+ 'warrantyExpires': '2026-01-01',
+ 'warrantyDetails': '2 years',
+ 'purchaseTime': '2025-01-01',
+ 'purchaseFrom': 'Store',
+ 'soldTime': '2025-02-01',
+ 'soldTo': 'Buyer',
+ 'soldPrice': 80,
+ 'soldNotes': 'Used',
+ 'notes': 'Shelf A',
+ 'location': {'id': 'loc-1'},
+ 'labels': [{'id': 'lab-1'}],
+ 'attachments': [{'id': 'att-1'}],
+ 'fields': [{'id': 'f-1'}],
+ }
+ base_data.update(kwargs)
+ return HbItem(api_dict=base_data)
+
+ def test_returns_expected_values_for_valid_types(self):
+ item = self._create_item()
+
+ self.assertEqual(item.id, 'item-1')
+ self.assertEqual(item.name, 'Drill')
+ self.assertEqual(item.description, 'Cordless drill')
+ self.assertEqual(item.quantity, 2)
+ self.assertTrue(item.insured)
+ self.assertFalse(item.archived)
+ self.assertEqual(item.created_at, '2025-01-01T00:00:00Z')
+ self.assertEqual(item.updated_at, '2025-01-02T00:00:00Z')
+ self.assertEqual(item.purchase_price, 99.5)
+ self.assertEqual(item.asset_id, 'A-1')
+ self.assertTrue(item.sync_child_items_locations)
+ self.assertEqual(item.serial_number, 'S-1')
+ self.assertEqual(item.model_number, 'M-1')
+ self.assertEqual(item.manufacturer, 'ACME')
+ self.assertFalse(item.lifetime_warranty)
+ self.assertEqual(item.warranty_expires, '2026-01-01')
+ self.assertEqual(item.warranty_details, '2 years')
+ self.assertEqual(item.purchase_time, '2025-01-01')
+ self.assertEqual(item.purchase_from, 'Store')
+ self.assertEqual(item.sold_time, '2025-02-01')
+ self.assertEqual(item.sold_to, 'Buyer')
+ self.assertEqual(item.sold_price, 80)
+ 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.attachments, [{'id': 'att-1'}])
+ self.assertEqual(item.fields, [{'id': 'f-1'}])
+
+ def test_returns_none_for_invalid_typed_optional_fields(self):
+ item = self._create_item(
+ quantity='2',
+ insured='true',
+ archived='false',
+ createdAt=' ',
+ updatedAt=123,
+ purchasePrice='99.5',
+ assetId=' ',
+ syncChildItemsLocations='yes',
+ lifetimeWarranty='false',
+ warrantyExpires=' ',
+ purchaseTime=0,
+ soldTime='',
+ soldPrice='80',
+ location='garage',
+ labels='tools',
+ )
+
+ self.assertIsNone(item.quantity)
+ self.assertIsNone(item.insured)
+ self.assertIsNone(item.archived)
+ self.assertIsNone(item.created_at)
+ self.assertIsNone(item.updated_at)
+ self.assertIsNone(item.purchase_price)
+ self.assertIsNone(item.asset_id)
+ self.assertIsNone(item.sync_child_items_locations)
+ self.assertIsNone(item.lifetime_warranty)
+ self.assertIsNone(item.warranty_expires)
+ self.assertIsNone(item.purchase_time)
+ self.assertIsNone(item.sold_time)
+ self.assertIsNone(item.sold_price)
+ self.assertIsNone(item.location)
+ self.assertIsNone(item.labels)
+
+ def test_returns_empty_collections_or_strings_when_missing(self):
+ item = HbItem(api_dict={'id': 'item-2'})
+
+ self.assertEqual(item.name, '')
+ self.assertEqual(item.description, '')
+ self.assertEqual(item.serial_number, '')
+ self.assertEqual(item.model_number, '')
+ self.assertEqual(item.manufacturer, '')
+ self.assertEqual(item.warranty_details, '')
+ self.assertEqual(item.purchase_from, '')
+ self.assertEqual(item.sold_to, '')
+ self.assertEqual(item.sold_notes, '')
+ self.assertEqual(item.notes, '')
+ self.assertEqual(item.attachments, [])
+ self.assertEqual(item.fields, [])
diff --git a/src/hi/services/homebox/tests/test_hb_sync.py b/src/hi/services/homebox/tests/test_hb_sync.py
new file mode 100644
index 00000000..f7c35a49
--- /dev/null
+++ b/src/hi/services/homebox/tests/test_hb_sync.py
@@ -0,0 +1,294 @@
+import logging
+from contextlib import ExitStack, nullcontext
+from unittest.mock import ANY, Mock, patch
+
+from django.test import SimpleTestCase
+
+from hi.apps.common.processing_result import ProcessingResult
+from hi.integrations.transient_models import IntegrationKey
+from hi.services.homebox.hb_metadata import HbMetaData
+from hi.services.homebox.hb_sync import HomeBoxSynchronizer
+
+
+logging.disable(logging.CRITICAL)
+
+
+class TestHomeBoxSynchronizer(SimpleTestCase):
+
+ def _key(self, name: str) -> IntegrationKey:
+ return IntegrationKey(
+ integration_id=HbMetaData.integration_id,
+ integration_name=name,
+ )
+
+ def test_sync_helper_uses_mocked_api_response_and_delegates_entity_sync(self):
+ synchronizer = HomeBoxSynchronizer()
+ manager = Mock()
+ manager.hb_client = object()
+ manager.fetch_hb_items_from_api.return_value = [Mock(), Mock(), Mock()]
+
+ with patch.object(synchronizer, 'hb_manager', return_value=manager), \
+ patch.object(synchronizer, '_sync_helper_entities') as sync_entities_mock:
+ result = synchronizer._sync_helper()
+
+ self.assertIsInstance(result, ProcessingResult)
+ self.assertIn('Found 3 current HomeBox items.', result.message_list)
+ sync_entities_mock.assert_called_once_with(
+ item_list=manager.fetch_hb_items_from_api.return_value,
+ result=result,
+ )
+
+ def test_sync_helper_entities_create_update_remove_entities(self):
+ synchronizer = HomeBoxSynchronizer()
+ result = ProcessingResult(title='HomeBox Import Result')
+
+ item_new = Mock(name='item_new')
+ item_existing = Mock(name='item_existing')
+ item_invalid = Mock(name='item_invalid')
+
+ new_key = self._key('item-new')
+ existing_key = self._key('item-existing')
+ stale_key = self._key('item-stale')
+
+ existing_entity = Mock(name='existing_entity')
+ stale_entity = Mock(name='stale_entity')
+ created_entity = Mock(name='created_entity')
+
+ def key_from_item(hb_item):
+ if hb_item is item_new:
+ return new_key
+ if hb_item is item_existing:
+ return existing_key
+ raise ValueError('missing id')
+
+ with ExitStack() as stack:
+ stack.enter_context(
+ patch(
+ 'hi.services.homebox.hb_sync.transaction.atomic',
+ return_value=nullcontext(),
+ )
+ )
+ stack.enter_context(
+ patch(
+ 'hi.services.homebox.hb_sync.HbConverter.hb_item_to_integration_key',
+ side_effect=key_from_item,
+ )
+ )
+ stack.enter_context(
+ patch.object(
+ synchronizer,
+ '_get_existing_hb_entities',
+ return_value={
+ existing_key: existing_entity,
+ stale_key: stale_entity,
+ },
+ )
+ )
+ create_entity_mock = stack.enter_context(
+ patch.object(
+ synchronizer,
+ '_create_entity',
+ return_value=created_entity,
+ )
+ )
+ update_entity_mock = stack.enter_context(
+ patch.object(synchronizer, '_update_entity')
+ )
+ remove_entity_mock = stack.enter_context(
+ patch.object(synchronizer, '_remove_entity')
+ )
+ sync_attrs_mock = stack.enter_context(
+ patch.object(synchronizer, '_sync_helper_entity_attributes')
+ )
+
+ synchronizer._sync_helper_entities(
+ item_list=[item_new, item_existing, item_invalid],
+ result=result,
+ )
+
+ create_entity_mock.assert_called_once_with(item=item_new, result=result)
+ update_entity_mock.assert_called_once_with(
+ entity=existing_entity,
+ item=item_existing,
+ result=result,
+ )
+ remove_entity_mock.assert_called_once_with(
+ entity=stale_entity,
+ 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,
+ )
+
+ self.assertIn('Found 2 existing HomeBox entities.', result.message_list)
+ self.assertTrue(any('Ignoring HomeBox item due to missing/invalid id' in message
+ for message in result.error_list))
+
+ def test_sync_helper_entity_attributes_create_update_remove_fields_and_attachments(self):
+ synchronizer = HomeBoxSynchronizer()
+ result = ProcessingResult(title='HomeBox Import Result')
+
+ entity = Mock(name='entity')
+ entity.id = 10
+
+ field_existing = {'id': 'field-existing', 'name': 'Field Existing'}
+ field_new = {'id': 'field-new', 'name': 'Field New'}
+ attachment_existing = {'id': 'attachment-existing', 'name': 'Attachment Existing'}
+ attachment_new = {'id': 'attachment-new', 'name': 'Attachment New'}
+
+ field_existing_key = self._key('field:field-existing')
+ field_new_key = self._key('field:field-new')
+ attachment_existing_key = self._key('field:attachment-existing')
+ attachment_new_key = self._key('field:attachment-new')
+ stale_key = self._key('field:stale-field')
+ foreign_key = self._key('field:foreign-field')
+
+ existing_field_attr = Mock(name='existing_field_attr')
+ existing_field_attr.entity_id = entity.id
+ existing_attachment_attr = Mock(name='existing_attachment_attr')
+ existing_attachment_attr.entity_id = entity.id
+ stale_attr = Mock(name='stale_attr')
+ stale_attr.entity_id = entity.id
+ stale_attr.name = 'Stale Field'
+ foreign_attr = Mock(name='foreign_attr')
+ foreign_attr.entity_id = entity.id + 1
+
+ created_field_attr = Mock(name='created_field_attr')
+ created_field_attr.name = 'Field New'
+ created_attachment_attr = Mock(name='created_attachment_attr')
+ created_attachment_attr.name = 'Attachment New'
+
+ field_key_by_id = {
+ 'field-existing': field_existing_key,
+ 'field-new': field_new_key,
+ }
+ attachment_key_by_id = {
+ 'attachment-existing': attachment_existing_key,
+ 'attachment-new': attachment_new_key,
+ }
+
+ def field_key_from_field(hb_field):
+ return field_key_by_id.get(hb_field.get('id'))
+
+ def attachment_key_from_attachment(hb_attachment):
+ return attachment_key_by_id.get(hb_attachment.get('id'))
+
+ with ExitStack() as stack:
+ stack.enter_context(
+ patch(
+ 'hi.services.homebox.hb_sync.transaction.atomic',
+ return_value=nullcontext(),
+ )
+ )
+ stack.enter_context(
+ patch(
+ 'hi.services.homebox.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',
+ side_effect=field_key_from_field,
+ )
+ )
+ stack.enter_context(
+ patch(
+ 'hi.services.homebox.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',
+ side_effect=attachment_key_from_attachment,
+ )
+ )
+ stack.enter_context(
+ patch.object(
+ synchronizer,
+ '_get_existing_hb_attributes',
+ return_value={
+ field_existing_key: existing_field_attr,
+ attachment_existing_key: existing_attachment_attr,
+ stale_key: stale_attr,
+ foreign_key: foreign_attr,
+ },
+ )
+ )
+ update_attr_mock = stack.enter_context(
+ patch.object(synchronizer, '_update_attribute')
+ )
+ create_attr_mock = stack.enter_context(
+ patch.object(
+ synchronizer,
+ '_create_attribute',
+ return_value=created_field_attr,
+ )
+ )
+ update_attachment_mock = stack.enter_context(
+ patch.object(synchronizer, '_update_attachment_attribute')
+ )
+ create_attachment_mock = stack.enter_context(
+ patch.object(
+ synchronizer,
+ '_create_attachment_attribute',
+ return_value=created_attachment_attr,
+ )
+ )
+
+ synchronizer._sync_helper_entity_attributes(
+ entity=entity,
+ hb_item=Mock(),
+ result=result,
+ )
+
+ update_attr_mock.assert_called_once_with(
+ attribute=existing_field_attr,
+ hb_field=field_existing,
+ order_id=0,
+ message_list=ANY,
+ updated_prefix='Field attribute updated',
+ )
+ create_attr_mock.assert_called_once_with(
+ entity=entity,
+ hb_field=field_new,
+ order_id=1,
+ )
+
+ update_attachment_mock.assert_called_once_with(
+ attribute=existing_attachment_attr,
+ hb_attachment=attachment_existing,
+ order_id=2,
+ message_list=ANY,
+ updated_prefix='Attachment attribute updated',
+ )
+ create_attachment_mock.assert_called_once_with(
+ entity=entity,
+ hb_attachment=attachment_new,
+ order_id=3,
+ )
+
+ stale_attr.delete.assert_called_once()
+ foreign_attr.delete.assert_not_called()
+
+ self.assertEqual(len(result.message_list), 1)
+ self.assertIn('Updated HomeBox entity attributes', result.message_list[0])
+ self.assertIn('Field attribute added: Field New', result.message_list[0])
+ self.assertIn('Attachment attribute added: Attachment New', result.message_list[0])
+ self.assertIn('Field attribute removed: Stale Field', result.message_list[0])
diff --git a/src/hi/services/homebox/urls.py b/src/hi/services/homebox/urls.py
new file mode 100644
index 00000000..71f86b4a
--- /dev/null
+++ b/src/hi/services/homebox/urls.py
@@ -0,0 +1,14 @@
+from django.urls import re_path
+
+from . import views
+
+
+urlpatterns = [
+
+ re_path(
+ r'^sync$',
+ views.HbSyncView.as_view(),
+ name='hb_sync',
+ ),
+
+]
diff --git a/src/hi/services/homebox/views.py b/src/hi/services/homebox/views.py
new file mode 100644
index 00000000..3f1a6e50
--- /dev/null
+++ b/src/hi/services/homebox/views.py
@@ -0,0 +1,17 @@
+from hi.hi_async_view import HiModalView
+
+from .hb_sync import HomeBoxSynchronizer
+
+
+class HbSyncView( HiModalView ):
+
+ def get_template_name( self ) -> str:
+ return 'common/modals/processing_result.html'
+
+ def post(self, request, *args, **kwargs):
+
+ processing_result = HomeBoxSynchronizer().sync()
+ context = {
+ 'processing_result': processing_result,
+ }
+ return self.modal_response( request, context )
diff --git a/src/hi/settings/base.py b/src/hi/settings/base.py
index b0f71be8..a15d74d3 100644
--- a/src/hi/settings/base.py
+++ b/src/hi/settings/base.py
@@ -127,6 +127,7 @@ INSTALLED_APPS = [
'hi.integrations',
'hi.services.zoneminder',
'hi.services.hass',
+ 'hi.services.homebox',
'hi.apps.profiles',
]
diff --git a/src/hi/static/img/integrations/homebox.svg b/src/hi/static/img/integrations/homebox.svg
new file mode 100644
index 00000000..08670bbb
--- /dev/null
+++ b/src/hi/static/img/integrations/homebox.svg
@@ -0,0 +1,11 @@
+<svg viewBox="0 0 10817 9730" xmlns="http://www.w3.org/2000/svg" xml:space="preserve" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:5.42683">
+ <path d="M9310.16 2560.9c245.302 249.894 419.711 539.916 565.373 845.231 47.039 98.872 36.229 215.514-28.2 304.05-64.391 88.536-172.099 134.676-280.631 120.28 0 .053-.039.053-.039.053" style="fill:gray;stroke:#000;stroke-width:206.41px"/>
+ <path d="M5401.56 487.044c-127.958 6.227-254.855 40.77-370.992 103.628-765.271 414.225-2397.45 1297.68-3193.03 1728.32-137.966 74.669-250.327 183.605-328.791 313.046l3963.09 2122.43s-249.048 416.428-470.593 786.926c-189.24 316.445-592.833 429.831-919.198 258.219l-2699.36-1419.32v2215.59c0 226.273 128.751 435.33 337.755 548.466 764.649 413.885 2620.97 1418.66 3385.59 1832.51 209.018 113.137 466.496 113.137 675.514 0 764.623-413.857 2620.94-1418.63 3385.59-1832.51 208.989-113.136 337.743-322.193 337.743-548.466v-3513.48c0-318.684-174.59-611.722-454.853-763.409-795.543-430.632-2427.75-1314.09-3193.02-1728.32-141.693-76.684-299.364-111.227-455.442-103.628" style="fill:#dadada;stroke:#000;stroke-width:206.42px"/>
+ <path d="M5471.83 4754.46V504.71c-127.958 6.226-325.127 23.1-441.264 85.958-765.271 414.225-2397.45 1297.68-3193.03 1728.32-137.966 74.669-250.327 183.605-328.791 313.046l3963.09 2122.43Z" style="fill:gray;stroke:#000;stroke-width:206.42px"/>
+ <path d="m1459.34 2725.96-373.791 715.667c-177.166 339.292-46.417 758 292.375 936.167l4.75 2.5m0 0 2699.37 1419.29c326.374 171.625 729.916 58.25 919.165-258.208 221.542-370.5 470.583-786.917 470.583-786.917l-3963.04-2122.42-2.167 3.458-47.25 90.458" style="fill:#dadada;stroke:#000;stroke-width:206.42px"/>
+ <path d="M5443.74 520.879v4149.79" style="fill:none;stroke:#000;stroke-width:153.5px"/>
+ <path d="M8951.41 4102.72c0-41.65-22.221-80.136-58.291-100.961-36.069-20.825-80.51-20.825-116.58 0l-2439.92 1408.69c-36.07 20.825-58.29 59.311-58.29 100.961V7058c0 41.65 22.22 80.136 58.29 100.961 36.07 20.825 80.51 20.825 116.58 0l2439.92-1408.69c36.07-20.825 58.291-59.312 58.291-100.962v-1546.59Z" style="fill:#567f67"/>
+ <path d="M8951.41 4102.72c0-41.65-22.221-80.136-58.291-100.961-36.069-20.825-80.51-20.825-116.58 0l-2439.92 1408.69c-36.07 20.825-58.29 59.311-58.29 100.961V7058c0 41.65 22.22 80.136 58.29 100.961 36.07 20.825 80.51 20.825 116.58 0l2439.92-1408.69c36.07-20.825 58.291-59.312 58.291-100.962v-1546.59ZM6463.98 5551.29v1387.06l2301.77-1328.92V4222.37L6463.98 5551.29Z"/>
+ <path d="M5443.76 9041.74v-4278.4" style="fill:none;stroke:#000;stroke-width:206.44px;stroke-linejoin:miter"/>
+ <path d="m5471.79 4773.86 3829.35-2188.22" style="fill:none;stroke:#000;stroke-width:206.43px;stroke-linejoin:miter"/>
+</svg>