Home Information - Your home, your data, organized.
Python
[Feature] External Reference framework — Linked Content tab (#392)
Tony Cc30c0a99acbb
diff --git a/docs/dev/integrations/immich.md b/docs/dev/integrations/immich.mdindex 7adabff2..09d59588 100644--- a/docs/dev/integrations/immich.md+++ b/docs/dev/integrations/immich.md@@ -2,10 +2,10 @@## Overview-Immich declares only the `ATTRIBUTE_REFERENCE` capability — no+Immich declares only the `EXTERNAL_REFERENCE` capability — noconnector, no importer, no manager singleton, no monitors. Thegateway returns a referencer, and the referencer translates Immich's-smart-search response into `AttributeReferenceResult` rows. Per-search+smart-search response into `ExternalReferenceResult` rows. Per-searchHTTP happens inline; there is no cached client. The integrationmirrors the paperless-ngx shape almost exactly — same file layout,same lifecycle, same thumbnail-proxy pattern — with the differences@@ -16,7 +16,7 @@ documented under [Implementation notes](#implementation-notes).- `src/hi/services/immich/integration.py` — `ImmichGateway`. Gatewayentry point; `validate_access` lives here.- `src/hi/services/immich/im_referencer.py` —- `ImmichAttributeReferencer`. Smart-search dispatch + asset+ `ImmichExternalReferencer`. Smart-search dispatch + assettranslation + secondary-text builder.- `src/hi/services/immich/im_client.py` — `ImmichClient` and`build_client`. Thin `requests.Session` wrapper.@@ -71,7 +71,7 @@ makes one search call per picker query, no background loop.composes a short blurb from `fileCreatedAt` + `exifInfo.city` /`country` instead; returns `None` when neither is present so thepicker template omits the snippet row entirely.-- **Error channel via `AttributeReferenceSearchResult.error_message`.**+- **Error channel via `ExternalReferenceSearchResult.error_message`.**Each failure path (no config, HTTP 401, HTTP 403, generic HTTPfailure, connectivity, unexpected) returns the dataclass with anamed user-facing message instead of raising or returning an emptydiff --git a/docs/dev/integrations/integration-guidelines.md b/docs/dev/integrations/integration-guidelines.mdindex a6c5f599..09b2554c 100644--- a/docs/dev/integrations/integration-guidelines.md+++ b/docs/dev/integrations/integration-guidelines.md@@ -14,9 +14,9 @@ Each integration declares its `IntegrationCapability` set on `IntegrationMetaDat- **`CONNECT`** — live mirror of an upstream system. Realized by an `IntegrationConnector` subclass returned from `IntegrationGateway.get_connector()`. All four "Connectors"-tab integrations (HA, ZM, Frigate, HomeBox) declare CONNECT.- **`IMPORT`** — one-shot copy of upstream items into HI as locally-owned entities. Realized by an `IntegrationImporter` subclass returned from `IntegrationGateway.get_importer()`. HomeBox is the only integration to declare IMPORT alongside CONNECT today (see [`docs/dev/integrations/data-import.md`](data-import.md) for the developer surface).-- **`ATTRIBUTE_REFERENCE`** — search-and-attach surface that contributes URL attributes to existing Entity / Location records (no entity import, no live mirror). Realized by an `IntegrationAttributeReferencer` subclass returned from `IntegrationGateway.get_attribute_referencer()`. Paperless-ngx and Immich declare ATTRIBUTE_REFERENCE today. ATTRIBUTE_REFERENCE-only integrations are configured on a sibling tab labeled "Content Sources" instead of "Connectors" — the page chrome differs because there's no monitor / sync lifecycle.+- **`EXTERNAL_REFERENCE`** — search-and-attach surface that contributes URL attributes to existing Entity / Location records (no entity import, no live mirror). Realized by an `IntegrationExternalReferencer` subclass returned from `IntegrationGateway.get_external_referencer()`. Paperless-ngx and Immich declare EXTERNAL_REFERENCE today. EXTERNAL_REFERENCE-only integrations are configured on a sibling tab labeled "Content Sources" instead of "Connectors" — the page chrome differs because there's no monitor / sync lifecycle.-The three per-capability classes (`IntegrationConnector`, `IntegrationImporter`, `IntegrationAttributeReferencer`) share a common base `CapabilityGateway` (`hi/integrations/capability_gateway.py`). Each declares a `capability` class attribute identifying the `IntegrationCapability` it realizes, and overrides cross-capability concerns: `get_metadata()` (abstract), `get_description()` (operator-facing one-line description), and `get_attribute_actions_template_name()` (optional template fragment for the attribute form's action bar). Capability-specific concerns (sync, import, search) stay on the subclass. Adding a new capability means subclassing `CapabilityGateway`, declaring the `capability` class attribute, and overriding only the methods that apply to the new shape.+The three per-capability classes (`IntegrationConnector`, `IntegrationImporter`, `IntegrationExternalReferencer`) share a common base `CapabilityGateway` (`hi/integrations/capability_gateway.py`). Each declares a `capability` class attribute identifying the `IntegrationCapability` it realizes, and overrides cross-capability concerns: `get_metadata()` (abstract), `get_description()` (operator-facing one-line description), and `get_attribute_actions_template_name()` (optional template fragment for the attribute form's action bar). Capability-specific concerns (sync, import, search) stay on the subclass. Adding a new capability means subclassing `CapabilityGateway`, declaring the `capability` class attribute, and overriding only the methods that apply to the new shape.The `connector/`, `importer/`, and `referencer/` sub-packages live as peers under `hi/integrations/`.@@ -84,7 +84,7 @@ Each integration is a self-contained Django app under `hi/services/<integration_`<prefix>` is a short integration mnemonic (`hass_`, `zm_`, `hb_`, `pl_`, `im_`). Keep it consistent across all files within the integration.-ATTRIBUTE_REFERENCE-only integrations (paperless-ngx and Immich today) don't need all the role-files above — they have no monitors, no sync, no converter, and no manager singleton (the capability has no live state to own). They still ship `integration.py`, `<prefix>_metadata.py`, `<prefix>_client.py`, plus a `<prefix>_referencer.py` for the `IntegrationAttributeReferencer` subclass and `<prefix>_models.py` (or `_constants.py`) for the wire-format strings.+EXTERNAL_REFERENCE-only integrations (paperless-ngx and Immich today) don't need all the role-files above — they have no monitors, no sync, no converter, and no manager singleton (the capability has no live state to own). They still ship `integration.py`, `<prefix>_metadata.py`, `<prefix>_client.py`, plus a `<prefix>_referencer.py` for the `IntegrationExternalReferencer` subclass and `<prefix>_models.py` (or `_constants.py`) for the wire-format strings.### Centralize wire-format stringsEvery integration centralizes its wire-format strings — domain/endpoint names, attribute keys, device-class names, service names, special-state sentinels — in a single class per integration. The exemplar is `HassApi` in `hi/services/hass/hass_models.py`; ZoneMinder's equivalent is `hi/services/zoneminder/constants.py`. The converter, sync, controller, and service composer all import their wire strings from this single source.@@ -119,7 +119,7 @@ cd src/hi/services- Add to `INSTALLED_APPS` in `hi/settings/base.py`### 3. Declare Metadata and Capabilities-Create a module-level `IntegrationMetaData` instance (in `<prefix>_metadata.py`) declaring the integration's `integration_id`, label, logo path, attribute-type enum, and `capabilities` set. The `capabilities` set is what binds the integration to its UI surfaces — CONNECT puts it on the Connectors tab; IMPORT adds it to the Data Import tab; ATTRIBUTE_REFERENCE puts it on the Content Sources tab.+Create a module-level `IntegrationMetaData` instance (in `<prefix>_metadata.py`) declaring the integration's `integration_id`, label, logo path, attribute-type enum, and `capabilities` set. The `capabilities` set is what binds the integration to its UI surfaces — CONNECT puts it on the Connectors tab; IMPORT adds it to the Data Import tab; EXTERNAL_REFERENCE puts it on the Content Sources tab.### 4. Create Gateway ClassImplement `IntegrationGateway` (in `integration.py`) with the methods that apply to the declared capabilities:@@ -127,7 +127,7 @@ Implement `IntegrationGateway` (in `integration.py`) with the methods that apply- `get_metadata()` — return the `IntegrationMetaData` instance. Required.- `get_connector()` — return an `IntegrationConnector` subclass instance when CONNECT is advertised; default `None`.- `get_importer()` — return an `IntegrationImporter` subclass instance when IMPORT is advertised; default `None`.-- `get_attribute_referencer()` — return an `IntegrationAttributeReferencer` subclass instance when ATTRIBUTE_REFERENCE is advertised; default `None`.+- `get_external_referencer()` — return an `IntegrationExternalReferencer` subclass instance when EXTERNAL_REFERENCE is advertised; default `None`.- `validate_configuration(integration_attributes)` — schema-only validation of the attribute set. Required (no network operations).- `validate_access(integration_attributes, timeout_secs)` — bounded live probe against the configured credentials. Required (used by the configure flow and by health-check helpers).- `notify_settings_changed()` — invoked by the framework after the operator saves attributes. Reload your manager / re-init clients here. Default no-op.@@ -198,7 +198,7 @@ Custom exception hierarchy (`hi/integrations/exceptions.py`):- `hi.integrations.capability_gateway.CapabilityGateway` — shared base of the three per-capability classes; carries `capability`, `get_metadata`, `get_description`, `get_attribute_actions_template_name`.- `hi.integrations.connector.integration_connector.IntegrationConnector` — CONNECT capability surface (sync, monitor, controller, health).- `hi.integrations.importer.integration_importer.IntegrationImporter` — IMPORT capability surface (candidate list, run, discard).-- `hi.integrations.referencer.integration_referencer.IntegrationAttributeReferencer` — ATTRIBUTE_REFERENCE capability surface (search).+- `hi.integrations.referencer.integration_referencer.IntegrationExternalReferencer` — EXTERNAL_REFERENCE capability surface (search).- `hi.integrations.integration_manager.IntegrationManager` — discovery and lifecycle singleton.- `hi.apps.common.singleton.Singleton` — singleton base used by `IntegrationManager` and many per-integration managers.@@ -207,8 +207,8 @@ Custom exception hierarchy (`hi/integrations/exceptions.py`):- `hi.services.zoneminder/` — ZoneMinder (CONNECT).- `hi.services.frigate/` — Frigate (CONNECT).- `hi.services.homebox/` — HomeBox (CONNECT + IMPORT).-- `hi.services.paperless/` — paperless-ngx (ATTRIBUTE_REFERENCE-only). Slimmer file layout — no manager singleton, no monitors, no converter — because the capability has no live state to own.-- `hi.services.immich/` — Immich (ATTRIBUTE_REFERENCE-only). Same slimmer layout as paperless-ngx.+- `hi.services.paperless/` — paperless-ngx (EXTERNAL_REFERENCE-only). Slimmer file layout — no manager singleton, no monitors, no converter — because the capability has no live state to own.+- `hi.services.immich/` — Immich (EXTERNAL_REFERENCE-only). Same slimmer layout as paperless-ngx.## Related Documentation- [Service Patterns](service-patterns.md)diff --git a/docs/dev/integrations/paperless-ngx.md b/docs/dev/integrations/paperless-ngx.mdindex 6c917873..499ee4bf 100644--- a/docs/dev/integrations/paperless-ngx.md+++ b/docs/dev/integrations/paperless-ngx.md@@ -2,10 +2,10 @@## Capability shape-Paperless declares only the `ATTRIBUTE_REFERENCE` capability — no+Paperless declares only the `EXTERNAL_REFERENCE` capability — noconnector, no importer, no manager singleton, no monitors. Thegateway returns a referencer, and the referencer translates-paperless's documents-search response into `AttributeReferenceResult`+paperless's documents-search response into `ExternalReferenceResult`rows. Per-search HTTP happens inline; there is no cached client.## Key design decisions@@ -20,7 +20,7 @@ rows. Per-search HTTP happens inline; there is no cached client.paperless's own per-document web URL. Operators authenticate withpaperless's own session when they click — same UX as cut-and-paste.Proxying would couple the link's lifetime to HI's session.-- **No manager singleton**. ATTRIBUTE_REFERENCE has no monitors and+- **No manager singleton**. EXTERNAL_REFERENCE has no monitors andno cached state, so there is no `pl_manager.py`. The client isbuilt per-call from the stored attributes; `build_client` is theentry point to refactor through if a reason to cache emerges.diff --git a/src/hi/apps/attribute/edit_context.py b/src/hi/apps/attribute/edit_context.pyindex d14798b0..9951fa92 100644--- a/src/hi/apps/attribute/edit_context.py+++ b/src/hi/apps/attribute/edit_context.py@@ -36,10 +36,19 @@ from .models import AttributeModel, SoftDeleteAttributeModelclass AttributePageEditContext:-- def __init__(self, owner_type: str, owner: Model = None ) -> None:++ def __init__(self,+ owner_type : str,+ owner : Model = None,+ extra_template_context : Optional[Dict] = None ) -> None:self.owner_type = owner_type.lower()self.owner = owner+ # View-supplied extras that the framework's template-context+ # builders merge in via ``to_template_context()``. Stored as+ # data only; the view owns the business logic that built it.+ # Both the initial-GET and async-POST response paths pick+ # the extras up because both call ``to_template_context()``.+ self._extra_template_context = dict( extra_template_context or {} )return@property@@ -179,9 +188,11 @@ class AttributePageEditContext:return ''def to_template_context(self) -> Dict[str, Any]:- return {+ ctx: Dict[str, Any] = {"attr_page_context": self,}+ ctx.update( self._extra_template_context )+ return ctxclass AttributeItemEditContext( AttributePageEditContext ):@@ -193,8 +204,15 @@ class AttributeItemEditContext( AttributePageEditContext ):type-safe access to owner information, URLs, and DOM identifiers."""- def __init__(self, owner: Model, owner_type: str) -> None:- super().__init__( owner_type = owner_type, owner = owner )+ def __init__(self,+ owner : Model,+ owner_type : str,+ extra_template_context : Optional[Dict] = None ) -> None:+ super().__init__(+ owner_type = owner_type,+ owner = owner,+ extra_template_context = extra_template_context,+ )return@propertydiff --git a/src/hi/apps/attribute/edit_form_handler.py b/src/hi/apps/attribute/edit_form_handler.pyindex c2628221..971cf0a5 100644--- a/src/hi/apps/attribute/edit_form_handler.py+++ b/src/hi/apps/attribute/edit_form_handler.py@@ -32,9 +32,13 @@ class AttributeEditFormHandler:owner_form = attr_item_context.create_owner_form( form_data )# Get file attributes for display (not a formset, just for template rendering)+ # Display order: manual reorder (order_id ASC) wins; ties+ # break recency-first so newly-uploaded files (default+ # order_id=0) appear at the top of the unsorted block until+ # the operator manually positions them.file_attributes: QuerySet[AttributeModel] = attr_item_context.attributes_queryset().filter(value_type_str = str( AttributeValueType.FILE )- ).order_by('id')+ ).order_by( 'order_id', '-created_datetime' )deleted_attributes = attr_item_context.soft_deleted_attributes_queryset().order_by('-updated_datetime',@@ -75,7 +79,11 @@ class AttributeEditFormHandler:edit_form_data.owner_form.save()edit_form_data.regular_attributes_formset.save()- self.process_file_title_updates(+ self.process_file_title_updates(+ attr_item_context = attr_item_context,+ request = request,+ )+ self.process_file_order_updates(attr_item_context = attr_item_context,request = request,)@@ -155,6 +163,58 @@ class AttributeEditFormHandler:except (AttributeModelClass.DoesNotExist) as e:logger.warning(f'File attribute not found {field_name}: {e}')+ def process_file_order_updates( self,+ attr_item_context : AttributeItemEditContext,+ request : HttpRequest ) -> None:+ """Process file_order_id_* fields from POST data to update+ each file attribute's ``order_id``. File attributes don't+ ride the regular formset, so they need ad-hoc named inputs+ the client populates on reorder.++ The per-row saves run inside one transaction so a mid-batch+ failure can't leave a partially-renumbered ordering. The+ per-row ``ValueError`` / ``DoesNotExist`` paths are+ per-field validation and don't propagate; only unhandled+ exceptions (DB errors) roll back."""+ file_order_pattern = re.compile(r'^file_order_id_(\d+)_(\d+)$')++ AttributeModelClass = attr_item_context.attribute_model_subclass++ with transaction.atomic():+ for field_name, new_order_str in request.POST.items():+ match = file_order_pattern.match(field_name)+ if not match:+ continue++ owner_id_str: str+ attribute_id_str: str+ owner_id_str, attribute_id_str = match.groups()++ if int(owner_id_str) != attr_item_context.owner.id:+ logger.warning(+ f'File order field {field_name} has mismatched owner ID'+ )+ continue++ try:+ attribute_id: int = int(attribute_id_str)+ new_order: int = int(new_order_str)+ attribute = AttributeModelClass.objects.get(+ id = attribute_id,+ value_type_str = str( AttributeValueType.FILE ),+ )+ if attribute.order_id != new_order:+ attribute.order_id = new_order+ attribute.save( update_fields = [ 'order_id' ] )+ except (ValueError) as e:+ logger.warning(+ f'Invalid file order field {field_name}: {e}'+ )+ except (AttributeModelClass.DoesNotExist) as e:+ logger.warning(+ f'File attribute not found {field_name}: {e}'+ )+def collect_form_errors(self, edit_form_data: AttributeEditFormData) -> List[str]:"""Collect errors for central display and count all form errors (as side efffect).diff --git a/src/hi/apps/attribute/templates/attribute/components/edit_content_body.html b/src/hi/apps/attribute/templates/attribute/components/edit_content_body.htmlindex d82c909c..8c1c37a4 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@@ -1,4 +1,4 @@-{% load icons %}+{% load icons static %}{% comment %}Generic V2 Content Body FragmentContains the main content area - used by both initial load and updates@@ -94,7 +94,7 @@ by using the AttributeItemEditContext pattern.{% block file_upload_button %}<button type="button"class="btn btn-sm btn-outline-primary mb-0"- onclick="document.getElementById('{{ attr_item_context.file_input_html_id }}').click();">+ onclick="window.Hi.attr.showAddFile(this, '{{ attr_item_context.file_input_html_id }}');">{% icon "upload" size="sm" css_class="hi-icon-left" %}Add File</button>{% endblock %}@@ -115,32 +115,90 @@ by using the AttributeItemEditContext pattern.<div id="{{ attr_page_context.scrollable_content_html_id }}"class="{{ DIVID.ATTR_V2_SCROLLABLE_CONTENT_CLASS }}">- {% if attr_page_context.allow_internal_attributes %}-- <!-- Files Section -->- {% block files_section %}- {% include "attribute/components/file_grid.html" with file_attributes=file_attributes %}- {% endblock %}-- <!-- Properties Section -->- {% block properties_section %}- {% include "attribute/components/regular_attribute_list.html" with regular_attributes_formset=regular_attributes_formset %}- {% endblock %}-- <!-- Additional Sections -->- {% block additional_sections %}- {% include "attribute/components/deleted_attribute_list.html" with deleted_attributes=deleted_attributes %}- {% endblock %}-+ {% comment %}+ Regular-attributes formset management form is hoisted above the+ tabs so it survives ``tab1_pane`` overrides (e.g., the+ integration-bound entity that swaps Tab 1 content for a "From+ [integration]" panel). Without it the surrounding form would+ POST without TOTAL_FORMS / INITIAL_FORMS / MIN / MAX, and+ Django would reject the submission even for non-attribute+ fields like the entity's name and type.+ {% endcomment %}+ {% if regular_attributes_formset %}+ {{ regular_attributes_formset.management_form }}{% endif %}- {% block external_view_data %}- {% if external_view_data %}- <div class="attr-v2-external-view-data">- {% include external_view_data.template_name with view_data=external_view_data %}+ {% comment %}+ Tabbed content region. The attribute framework owns Tab 1 (Home+ Information -- files + regulars + deleted) and provides empty+ slots for two additional tabs. Subclass templates (entity,+ location, etc.) fill those slots based on their own context;+ this template does not reference any integration-specific+ variables or concepts.++ Sticky-panel chrome (UPDATE button, dirty messaging, action+ buttons) sits above this region and is intentionally not inside+ any tab -- UPDATE applies to Tab 1 content only but stays+ visible regardless of active tab.+ {% endcomment %}+ <ul class="nav nav-tabs" role="tablist">+ <li class="nav-item">+ <a class="nav-link {% block tab1_nav_active %}active{% endblock %}"+ data-toggle="tab"+ href="#hi-attr-tab1-{{ attr_item_context.owner_id }}"+ role="tab">+ <img class="mr-1" style="width: 16px; height: 16px; vertical-align: middle;"+ src="{% static 'img/hi-icon-16x16.png' %}" alt="">Home Information+ </a>+ </li>+ {% block tab2_nav %}{% endblock %}+ {% block tab3_nav %}{% endblock %}+ </ul>++ <div class="tab-content">+ <div class="tab-pane {% block tab1_pane_active %}show active{% endblock %}"+ id="hi-attr-tab1-{{ attr_item_context.owner_id }}"+ role="tabpanel">+ {% block tab1_pane %}+ {% if attr_page_context.allow_internal_attributes %}+ {% block files_section %}+ {% include "attribute/components/file_grid.html" with file_attributes=file_attributes %}+ {% endblock %}++ {% block properties_section %}+ {% include "attribute/components/regular_attribute_list.html" with regular_attributes_formset=regular_attributes_formset %}+ {% endblock %}++ {% block additional_sections %}+ {% include "attribute/components/deleted_attribute_list.html" with deleted_attributes=deleted_attributes %}+ {% endblock %}++ {% block tab1_empty_state %}+ {% with has_files=file_attributes|length has_regulars=regular_attributes_formset.queryset|length has_deleted=deleted_attributes|length %}+ {% if not has_files and not has_regulars and not has_deleted %}+ <div class="text-muted small p-3">+ No data yet. Use the action buttons above to+ <em>Add File</em>, <em>Add Info</em>, or <em>Link Content</em>+ (if enabled).+ </div>+ {% endif %}+ {% endwith %}+ {% endblock %}+ {% else %}+ {% comment %}+ Internal-attribute editing is suppressed for this owner+ (typically integration-bound entities). Subclass templates+ override ``tab1_pane`` to render a richer "From [integration]"+ panel instead; this default fires only if no override is+ provided.+ {% endcomment %}+ <div class="text-muted small p-3">No data.</div>+ {% endif %}+ {% endblock %}+ </div>+ {% block tab2_pane %}{% endblock %}+ {% block tab3_pane %}{% endblock %}</div>- {% endif %}- {% endblock %}</div>diff --git a/src/hi/apps/attribute/templates/attribute/components/file_card.html b/src/hi/apps/attribute/templates/attribute/components/file_card.htmlindex c880b682..98362f79 100644--- a/src/hi/apps/attribute/templates/attribute/components/file_card.html+++ b/src/hi/apps/attribute/templates/attribute/components/file_card.html@@ -22,10 +22,21 @@ tag in attribute_extras.py.data-file-size="{{ attribute.file_value.size|default:0 }}"><!-- Hidden field for deletion marking -->- <input type="hidden"- name="{{ DIVID.ATTR_V2_DELETE_FILE_ATTR }}"- value=""+ <input type="hidden"+ name="{{ DIVID.ATTR_V2_DELETE_FILE_ATTR }}"+ value=""data-attribute-id="{{ attribute.id }}">++ {% comment %}+ Per-file order_id. File attributes aren't in the regular formset,+ so they need ad-hoc named inputs (same pattern as file_title_*).+ The JS reorder handler swaps two cards' values in place; the+ server processes file_order_id_* keys in process_file_order_updates.+ {% endcomment %}+ <input type="hidden"+ id="file_order_id_{{ attr_item_context.owner.id }}_{{ attribute.id }}"+ name="file_order_id_{{ attr_item_context.owner.id }}_{{ attribute.id }}"+ value="{{ attribute.order_id }}"><!-- File Preview/Thumbnail Area --><div class="attr-v2-file-thumbnail{% if attribute.has_thumbnail %} has-thumbnail{% endif %}{% if attribute.file_mime_type == 'application/pdf' %} is-document{% endif %}"@@ -57,26 +68,6 @@ tag in attribute_extras.py.{% endif %}{% endif %}- <!-- Reorder Controls (overlay in upper right) -->- <div class="attr-v2-reorder-controls"- onclick="event.stopPropagation();"- onmouseenter="this.parentElement.classList.add('reorder-hover');"- onmouseleave="this.parentElement.classList.remove('reorder-hover');">- <button type="button"- class="btn btn-sm btn-outline-secondary"- disabled- title="Reordering available in future update"- data-reorder-action="left">- {% icon "chevron-left" size="sm" %}- </button>- <button type="button"- class="btn btn-sm btn-outline-secondary"- disabled- title="Reordering available in future update"- data-reorder-action="right">- {% icon "chevron-right" size="sm" %}- </button>- </div></div><!-- File Info -->@@ -93,21 +84,37 @@ tag in attribute_extras.py.<!-- File Actions --><div class="attr-v2-file-actions">- <button type="button"+ {% comment %}+ Reorder buttons live in the action row (not as a thumbnail+ overlay) so they're touch-visible without hover, off the image+ so no contrast concerns, and use the action row's+ touch-friendly 44px minimum. ``mr-auto`` / ``ml-auto`` pushes+ them to the edges of the row, leaving view/delete clustered in+ the middle. Smaller icon (size="md") differentiates them+ visually from the primary view/delete actions.+ {% endcomment %}+ <button type="button"+ class="btn btn-sm btn-outline-secondary mr-auto"+ onclick="Hi.attr.reorderAttributeCard(this, 'up')"+ title="Move left"+ data-reorder-action="left">+ {% icon "chevron-left" size="md" %}+ </button>+ <button type="button"class="btn btn-sm btn-outline-primary"onclick="window.open('{{ attribute.file_value.url }}', '_blank');"title="View file">- {% icon "eye" size="sm" %}+ {% icon "eye" size="xl" %}</button>-+{% if attribute.attribute_type.can_delete %}- <button type="button"+ <button type="button"class="btn btn-sm btn-outline-danger {{ DIVID.ATTR_V2_DELETE_BTN_CLASS }}"onclick="markFileForDeletion('{{ attribute.id }}', '#{{ attr_page_context.container_html_id }}')"title="Delete file">- {% icon "delete" size="sm" %}+ {% icon "delete" size="xl" %}</button>- <button type="button"+ <button type="button"class="btn btn-sm btn-outline-secondary {{ DIVID.ATTR_V2_UNDO_BTN_CLASS }}"onclick="undoFileDeletion('{{ attribute.id }}', '#{{ attr_page_context.container_html_id }}')"title="Undo deletion"@@ -115,6 +122,13 @@ tag in attribute_extras.py.Undo</button>{% endif %}+ <button type="button"+ class="btn btn-sm btn-outline-secondary ml-auto"+ onclick="Hi.attr.reorderAttributeCard(this, 'down')"+ title="Move right"+ data-reorder-action="right">+ {% icon "chevron-right" size="md" %}+ </button></div></div></div>diff --git a/src/hi/apps/attribute/templates/attribute/components/regular_attribute_list.html b/src/hi/apps/attribute/templates/attribute/components/regular_attribute_list.htmlindex b47c2a06..2a2a4dbf 100644--- a/src/hi/apps/attribute/templates/attribute/components/regular_attribute_list.html+++ b/src/hi/apps/attribute/templates/attribute/components/regular_attribute_list.html@@ -1,6 +1,10 @@{% load static %}{% if regular_attributes_formset %}-{{ regular_attributes_formset.management_form }}+{% comment %}+``regular_attributes_formset.management_form`` is rendered by the+parent (``edit_content_body.html``) above the tab structure so it+survives ``tab1_pane`` overrides. Do not duplicate it here.+{% endcomment %}<div class="attr-v2-attribute-section">{% if title %}<h6 class="attr-v2-section-title">{{ title }}</h6>diff --git a/src/hi/apps/attribute/tests/test_thumbnail.py b/src/hi/apps/attribute/tests/test_thumbnail.pynew file mode 100644index 00000000..df89536d--- /dev/null+++ b/src/hi/apps/attribute/tests/test_thumbnail.py@@ -0,0 +1,116 @@+"""Tests for ThumbnailHelpers.bytes_to_thumbnail_png.++Generates source bytes inline with Pillow (the same library the+helper consumes) so test fixtures stay self-contained and the+asserts cover real PNG/JPEG round-trips, not stub data.+"""+import logging+from io import BytesIO+from unittest.mock import patch++from django.test import SimpleTestCase+from PIL import Image++from hi.apps.attribute.thumbnail import ThumbnailHelpers+++logging.disable(logging.CRITICAL)+++def _make_image_bytes(format='PNG', size=(640, 480), color='red'):+ img = Image.new('RGB', size, color)+ buf = BytesIO()+ img.save(buf, format=format)+ return buf.getvalue()+++class TestBytesToThumbnailPng(SimpleTestCase):++ def test_jpeg_in_returns_png_under_thumbnail_size(self):+ src = _make_image_bytes(format='JPEG', size=(800, 600))+ out = ThumbnailHelpers.bytes_to_thumbnail_png(src, 'image/jpeg')+ self.assertIsNotNone(out)+ with Image.open(BytesIO(out)) as img:+ self.assertEqual(img.format, 'PNG')+ self.assertLessEqual(img.width, ThumbnailHelpers.THUMBNAIL_SIZE[0])+ self.assertLessEqual(img.height, ThumbnailHelpers.THUMBNAIL_SIZE[1])++ def test_png_in_returns_png(self):+ src = _make_image_bytes(format='PNG', size=(400, 300))+ out = ThumbnailHelpers.bytes_to_thumbnail_png(src, 'image/png')+ self.assertIsNotNone(out)+ with Image.open(BytesIO(out)) as img:+ self.assertEqual(img.format, 'PNG')++ def test_mime_type_with_charset_suffix_is_accepted(self):+ # Some upstreams return "image/jpeg; charset=binary" or similar+ # -- the leading mime type is what matters.+ src = _make_image_bytes(format='JPEG')+ out = ThumbnailHelpers.bytes_to_thumbnail_png(+ src, 'image/jpeg; charset=binary',+ )+ self.assertIsNotNone(out)++ def test_empty_bytes_returns_none(self):+ self.assertIsNone(+ ThumbnailHelpers.bytes_to_thumbnail_png(b'', 'image/png')+ )++ def test_unsupported_mime_type_returns_none(self):+ src = _make_image_bytes(format='PNG')+ self.assertIsNone(+ ThumbnailHelpers.bytes_to_thumbnail_png(src, 'text/plain')+ )++ def test_empty_mime_type_returns_none(self):+ src = _make_image_bytes(format='PNG')+ self.assertIsNone(ThumbnailHelpers.bytes_to_thumbnail_png(src, ''))++ def test_oversize_image_returns_none(self):+ # Synthesize a byte string that exceeds the image cap without+ # actually allocating that much pixel data -- the size check+ # runs against len(source_bytes), not decoded image dimensions.+ oversize = b'x' * (ThumbnailHelpers.MAX_SOURCE_BYTES + 1)+ self.assertIsNone(+ ThumbnailHelpers.bytes_to_thumbnail_png(oversize, 'image/jpeg')+ )++ def test_oversize_pdf_returns_none(self):+ oversize = b'x' * (ThumbnailHelpers.MAX_PDF_SOURCE_BYTES + 1)+ self.assertIsNone(+ ThumbnailHelpers.bytes_to_thumbnail_png(+ oversize, 'application/pdf',+ )+ )++ def test_malformed_image_bytes_returns_none(self):+ self.assertIsNone(+ ThumbnailHelpers.bytes_to_thumbnail_png(b'not an image', 'image/png')+ )++ @patch('pdf2image.convert_from_bytes')+ def test_pdf_dispatch_calls_pdf2image(self, mock_convert):+ # Verify the PDF branch routes through pdf2image. Return a+ # real PIL image so the downstream PIL save path still works.+ mock_convert.return_value = [Image.new('RGB', (640, 480), 'blue')]+ out = ThumbnailHelpers.bytes_to_thumbnail_png(+ b'%PDF-1.4 stub', 'application/pdf',+ )+ self.assertIsNotNone(out)+ mock_convert.assert_called_once()++ @patch('pdf2image.convert_from_bytes', return_value=[])+ def test_pdf_with_no_pages_returns_none(self, _mock_convert):+ self.assertIsNone(+ ThumbnailHelpers.bytes_to_thumbnail_png(+ b'%PDF-1.4 stub', 'application/pdf',+ )+ )++ @patch('pdf2image.convert_from_bytes', side_effect=RuntimeError('boom'))+ def test_pdf_render_exception_returns_none(self, _mock_convert):+ self.assertIsNone(+ ThumbnailHelpers.bytes_to_thumbnail_png(+ b'%PDF-1.4 stub', 'application/pdf',+ )+ )diff --git a/src/hi/apps/attribute/thumbnail.py b/src/hi/apps/attribute/thumbnail.pyindex 6a67677e..87e6046b 100644--- a/src/hi/apps/attribute/thumbnail.py+++ b/src/hi/apps/attribute/thumbnail.py@@ -1,8 +1,29 @@+"""Thumbnail generation for attribute file values + the shared+bytes-to-PNG pipeline.++Three classes:++ - ``ThumbnailHelpers``: the pure bytes-in / bytes-out conversion+ pipeline plus its supporting constants (supported mime types,+ size caps, PDF render config). Reusable by any caller that+ already has bytes in memory (e.g. integration referencers+ fetching upstream original-bytes).++ - ``AttributeThumbnailRules``: attribute-specific rules for+ mime-type resolution (filename fallback) and thumbnail-path+ computation under ``default_storage``.++ - ``AttributeThumbnail``: storage-aware wrapper. Reads the+ attribute's file_value from ``default_storage``, applies an+ existence-skip + pre-read size cap, delegates the conversion+ to ``ThumbnailHelpers``, and writes the PNG back to storage+ at the rule-computed path.+"""import loggingimport mimetypesfrom io import BytesIOfrom pathlib import PurePosixPath-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Optionalfrom django.core.files.base import ContentFilefrom django.core.files.storage import default_storage@@ -13,20 +34,147 @@ if TYPE_CHECKING:logger = logging.getLogger(__name__)-class AttributeThumbnailRules:+class ThumbnailHelpers:+ """Pure bytes-to-PNG thumbnail pipeline + the constants that+ parameterize it. All members are class-level; nothing here+ needs per-instance state."""- THUMBNAIL_SUBDIRECTORY = 'thumbnails'- THUMBNAIL_SUFFIX = '.thumb.png'- THUMBNAIL_IMAGE_MIME_TYPES = {+ THUMBNAIL_SIZE = (320, 320)++ THUMBNAIL_IMAGE_MIME_TYPES = frozenset({'image/jpeg','image/png','image/webp','image/gif',- }- THUMBNAIL_PDF_MIME_TYPES = {+ })+ THUMBNAIL_PDF_MIME_TYPES = frozenset({'application/pdf',- }- THUMBNAIL_SUPPORTED_MIME_TYPES = THUMBNAIL_IMAGE_MIME_TYPES | THUMBNAIL_PDF_MIME_TYPES+ })+ THUMBNAIL_SUPPORTED_MIME_TYPES = (+ THUMBNAIL_IMAGE_MIME_TYPES | THUMBNAIL_PDF_MIME_TYPES+ )++ # Per-mime-type input size caps. PDFs get a tighter ceiling+ # because rendering cost scales with page dimensions and+ # complexity, not raw byte count -- a small but pathological PDF+ # can still be much more expensive than a moderately sized image.+ MAX_SOURCE_BYTES = 20 * 1024 * 1024+ MAX_PDF_SOURCE_BYTES = 10 * 1024 * 1024++ # Bounds on PDF rendering. PDF_RENDER_SIZE caps the rasterized+ # output dimensions before the thumbnail resize, preventing a+ # large-page PDF from producing a multi-GB pixel buffer at+ # pdf2image's 200-DPI default. PDF_RENDER_TIMEOUT_SECS is+ # threaded through to the underlying pdftoppm subprocess so a+ # crafted PDF can't hang generation indefinitely.+ PDF_RENDER_SIZE = (640, 640)+ PDF_RENDER_TIMEOUT_SECS = 30++ @classmethod+ def max_bytes_for_mime(cls, mime_type : str) -> int:+ if mime_type in cls.THUMBNAIL_PDF_MIME_TYPES:+ return cls.MAX_PDF_SOURCE_BYTES+ return cls.MAX_SOURCE_BYTES++ @classmethod+ def bytes_to_thumbnail_png(+ cls, source_bytes : bytes, mime_type : str,+ ) -> Optional[bytes]:+ """Convert source bytes + mime_type into a PNG thumbnail.+ Returns None on any failure (unsupported mime, oversize+ input, malformed bytes, missing optional dependency).+ Best-effort: callers should treat None as "no thumbnail"+ rather than as an error to surface."""+ if not source_bytes:+ return None++ mime_lower = ( mime_type or '' ).split( ';', 1 )[0].strip().lower()+ if mime_lower not in cls.THUMBNAIL_SUPPORTED_MIME_TYPES:+ return None++ max_bytes = cls.max_bytes_for_mime( mime_lower )+ if len( source_bytes ) > max_bytes:+ logger.info(+ f'Thumbnail skipped: source too large '+ f'({len(source_bytes)} bytes, limit {max_bytes} '+ f'for {mime_lower}).'+ )+ return None++ try:+ from PIL import Image, ImageOps, UnidentifiedImageError+ except Exception as e:+ logger.warning(+ f'Pillow unavailable for thumbnail generation: {e}'+ )+ return None++ try:+ if mime_lower in cls.THUMBNAIL_PDF_MIME_TYPES:+ source_img = cls._render_pdf_first_page( source_bytes )+ if source_img is None:+ return None+ else:+ with Image.open( BytesIO( source_bytes ) ) as opened:+ source_img = ImageOps.exif_transpose( opened ).copy()++ resampling = (+ Image.Resampling.LANCZOS+ if hasattr( Image, 'Resampling' )+ else Image.LANCZOS+ )+ source_img.thumbnail( cls.THUMBNAIL_SIZE, resampling )++ if source_img.mode not in ( 'RGB', 'RGBA' ):+ if 'A' in source_img.getbands():+ source_img = source_img.convert( 'RGBA' )+ else:+ source_img = source_img.convert( 'RGB' )++ out_buffer = BytesIO()+ source_img.save( out_buffer, format = 'PNG', optimize = True )+ return out_buffer.getvalue()+ except UnidentifiedImageError:+ logger.warning(+ 'Thumbnail skipped: unrecognized image content.'+ )+ except Exception as e:+ logger.warning( f'Thumbnail generation failed: {e}' )+ return None++ @classmethod+ def _render_pdf_first_page(cls, pdf_bytes : bytes):+ """Rasterize the first page of a PDF to a PIL Image.+ Returns None when pdf2image is unavailable or rendering+ fails."""+ try:+ from pdf2image import convert_from_bytes+ except Exception as e:+ logger.warning(+ f'pdf2image unavailable for PDF thumbnail generation: {e}'+ )+ return None++ try:+ pages = convert_from_bytes(+ pdf_bytes,+ first_page = 1,+ last_page = 1,+ size = cls.PDF_RENDER_SIZE,+ timeout = cls.PDF_RENDER_TIMEOUT_SECS,+ )+ if not pages:+ return None+ return pages[0]+ except Exception as e:+ logger.warning( f'Error rendering PDF thumbnail: {e}' )+ return None+++class AttributeThumbnailRules:++ THUMBNAIL_SUBDIRECTORY = 'thumbnails'+ THUMBNAIL_SUFFIX = '.thumb.png'@classmethoddef effective_file_mime_type(cls, file_value, file_mime_type):@@ -50,146 +198,80 @@ class AttributeThumbnailRules:file_value=file_value,file_mime_type=file_mime_type,)- return bool(mime_type and mime_type in cls.THUMBNAIL_SUPPORTED_MIME_TYPES)+ return bool(+ mime_type+ and mime_type in ThumbnailHelpers.THUMBNAIL_SUPPORTED_MIME_TYPES+ )@classmethoddef thumbnail_relative_path(cls, file_value, file_mime_type):- if not cls.supports_thumbnail_generation( file_value = file_value, file_mime_type = file_mime_type ):+ if not cls.supports_thumbnail_generation(+ file_value = file_value, file_mime_type = file_mime_type,+ ):return Nonesource_path = PurePosixPath(file_value.name)thumbnail_name = f'{source_path.stem}{cls.THUMBNAIL_SUFFIX}'if str(source_path.parent) == '.':- return str(PurePosixPath(cls.THUMBNAIL_SUBDIRECTORY) / thumbnail_name)- return str(source_path.parent / cls.THUMBNAIL_SUBDIRECTORY / thumbnail_name)+ return str(+ PurePosixPath(cls.THUMBNAIL_SUBDIRECTORY) / thumbnail_name+ )+ return str(+ source_path.parent / cls.THUMBNAIL_SUBDIRECTORY / thumbnail_name+ )class AttributeThumbnail:- THUMBNAIL_SIZE = (320, 320)-- # Per-mime-type input size caps. PDFs get a tighter ceiling because- # rendering cost scales with page dimensions and complexity, not- # raw byte count — a small but pathological PDF can still be much- # more expensive than a moderately sized image.- THUMBNAIL_MAX_SOURCE_BYTES = 20 * 1024 * 1024- THUMBNAIL_MAX_PDF_SOURCE_BYTES = 10 * 1024 * 1024-- # Bounds on PDF rendering. ``PDF_RENDER_SIZE`` caps the rasterized- # output dimensions before the thumbnail resize, preventing a- # large-page PDF from producing a multi-GB pixel buffer at- # pdf2image's 200-DPI default. ``PDF_RENDER_TIMEOUT_SECS`` is- # threaded through to the underlying pdftoppm subprocess so a- # crafted PDF can't hang generation indefinitely.- PDF_RENDER_SIZE = (640, 640)- PDF_RENDER_TIMEOUT_SECS = 30-def __init__(self, attribute: 'AttributeModel'):self.attribute = attribute- def _max_source_bytes_for_mime_type(self, mime_type):- if mime_type in AttributeThumbnailRules.THUMBNAIL_PDF_MIME_TYPES:- return self.THUMBNAIL_MAX_PDF_SOURCE_BYTES- return self.THUMBNAIL_MAX_SOURCE_BYTES-- def _render_pdf_first_page_image(self, file_handle):- try:- from pdf2image import convert_from_bytes- except Exception as e:- logger.warning( f'pdf2image unavailable for PDF thumbnail generation: {e}' )- return None-- try:- pdf_bytes = file_handle.read()- rendered_pages = convert_from_bytes(- pdf_bytes,- first_page = 1,- last_page = 1,- size = self.PDF_RENDER_SIZE,- timeout = self.PDF_RENDER_TIMEOUT_SECS,- )- if not rendered_pages:- logger.warning( f'Cannot generate thumbnail for empty PDF: {self.attribute.file_value.name}' )- return None- return rendered_pages[0]-- except Exception as e:- logger.warning( f'Error rendering PDF thumbnail for {self.attribute.file_value.name}: {e}' )- return None-- def _load_source_image_for_thumbnail(self, file_handle, mime_type, image_module, image_ops_module):- if mime_type in AttributeThumbnailRules.THUMBNAIL_PDF_MIME_TYPES:- return self._render_pdf_first_page_image(file_handle=file_handle)-- with image_module.open(file_handle) as img:- processed_img = image_ops_module.exif_transpose(img)- return processed_img.copy()-def generate_thumbnail_best_effort(self, force=False):thumbnail_path = self.attribute.thumbnail_relative_pathif not thumbnail_path:return False+ if not force and default_storage.exists(thumbnail_path):+ return True+mime_type = AttributeThumbnailRules.effective_file_mime_type(file_value=self.attribute.file_value,file_mime_type=self.attribute.file_mime_type,)- if not force and default_storage.exists(thumbnail_path):- return True-- if self.attribute.file_value and getattr(self.attribute.file_value, 'size', None):- max_source_bytes = self._max_source_bytes_for_mime_type( mime_type )- if self.attribute.file_value.size > max_source_bytes:+ # Pre-read size check: skip without reading the file from+ # storage when we already know we'd reject the bytes. The+ # shared converter re-checks against the same limit on the+ # bytes it actually sees; this guard is just an I/O save.+ file_value = self.attribute.file_value+ file_size = getattr( file_value, 'size', None ) if file_value else None+ if file_size is not None:+ max_bytes = ThumbnailHelpers.max_bytes_for_mime( mime_type )+ if file_size > max_bytes:logger.info(- f'Skipping thumbnail generation for {self.attribute.file_value.name}: '- f'file too large ({self.attribute.file_value.size} bytes, '- f'limit {max_source_bytes} bytes for {mime_type})'+ f'Skipping thumbnail generation for {file_value.name}: '+ f'file too large ({file_size} bytes, '+ f'limit {max_bytes} bytes for {mime_type})')return Falsetry:- from PIL import Image, ImageOps, UnidentifiedImageError+ with default_storage.open(file_value.name, 'rb') as file_handle:+ source_bytes = file_handle.read()except Exception as e:- logger.warning( f'Pillow unavailable for thumbnail generation: {e}' )- return False-- try:- with default_storage.open(self.attribute.file_value.name, 'rb') as file_handle:- processed_img = self._load_source_image_for_thumbnail(- file_handle=file_handle,- mime_type=mime_type,- image_module=Image,- image_ops_module=ImageOps,- )-- if not processed_img:- return False-- resampling = (- Image.Resampling.LANCZOS- if hasattr(Image, 'Resampling')- else Image.LANCZOS+ logger.warning(+ f'Error reading source for thumbnail '+ f'{file_value.name}: {e}')- processed_img.thumbnail(self.THUMBNAIL_SIZE, resampling)-- if processed_img.mode not in ('RGB', 'RGBA'):- if 'A' in processed_img.getbands():- processed_img = processed_img.convert('RGBA')- else:- processed_img = processed_img.convert('RGB')-- bytes_buffer = BytesIO()- processed_img.save(bytes_buffer, format='PNG', optimize=True)- thumbnail_content = ContentFile(bytes_buffer.getvalue())+ return False- if default_storage.exists(thumbnail_path):- default_storage.delete(thumbnail_path)+ png_bytes = ThumbnailHelpers.bytes_to_thumbnail_png(+ source_bytes = source_bytes, mime_type = mime_type,+ )+ if png_bytes is None:+ return False- default_storage.save(thumbnail_path, thumbnail_content)- return True- except UnidentifiedImageError:- logger.warning( f'Cannot generate thumbnail due to unrecognized image content: {self.attribute.file_value.name}' )- except Exception as e:- logger.warning( f'Error generating thumbnail for {self.attribute.file_value.name}: {e}' )- return False+ if default_storage.exists(thumbnail_path):+ default_storage.delete(thumbnail_path)+ default_storage.save(thumbnail_path, ContentFile(png_bytes))+ return Truediff --git a/src/hi/apps/common/templatetags/icons.py b/src/hi/apps/common/templatetags/icons.pyindex f4f27e04..b39b8387 100644--- a/src/hi/apps/common/templatetags/icons.py+++ b/src/hi/apps/common/templatetags/icons.py@@ -69,6 +69,7 @@ AVAILABLE_ICONS = {'tasks','times-circle','undo',+ 'unlink','unlock','upload','video',diff --git a/src/hi/apps/config/templates/config/panes/subsystem_edit_content_body.html b/src/hi/apps/config/templates/config/panes/subsystem_edit_content_body.htmlindex 3d1b9560..79999a15 100644--- a/src/hi/apps/config/templates/config/panes/subsystem_edit_content_body.html+++ b/src/hi/apps/config/templates/config/panes/subsystem_edit_content_body.html@@ -30,6 +30,8 @@ This is what gets replaced on form submission{% block files_section %}{% endblock %}+{% block tab1_empty_state %}{% endblock %}+{% block left_column %}<nav class="nav flex-column hi-vertical-nav mr-3" id="subsystemTabs" role="tablist">{% for multi_edit_form_data in multi_edit_form_data_list %}diff --git a/src/hi/apps/entity/entity_attribute_edit_context.py b/src/hi/apps/entity/entity_attribute_edit_context.pyindex e361b00c..736bc47f 100644--- a/src/hi/apps/entity/entity_attribute_edit_context.py+++ b/src/hi/apps/entity/entity_attribute_edit_context.py@@ -26,14 +26,25 @@ class EntityAttributeItemEditContext(AttributeItemEditContext):the generic interface expected by attribute editing templates."""- def __init__(self, entity: Entity) -> None:+ def __init__(self,+ entity : Entity,+ extra_template_context : Optional[Dict[str, Any]] = None ) -> None:"""Initialize context for Entity attribute editing.-+Args:entity: The Entity instance that owns the attributes+ extra_template_context: View-supplied template variables+ (external_view_data, external_references, data_priority,+ etc.). The view computes them once and threads them+ through the context so the framework's GET and async-+ POST renderers both see them."""- super().__init__( owner_type = 'entity', owner = entity )+ super().__init__(+ owner_type = 'entity',+ owner = entity,+ extra_template_context = extra_template_context,+ )return@propertydiff --git a/src/hi/apps/entity/templates/entity/panes/entity_edit_content_body.html b/src/hi/apps/entity/templates/entity/panes/entity_edit_content_body.htmlindex b50c6aa6..6e1177eb 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@@ -7,14 +7,99 @@ Extends the generic attribute edit content body with entity-specific field layou{% endcomment %}{% block additional_actions %}-{% has_attribute_referencers as has_referencers %}-{% if has_referencers and attr_page_context.allow_internal_attributes %}-<a href="{% url 'integrations_attribute_reference_picker' %}?item_type=ENTITY&item_id={{ attr_item_context.owner.id }}"+{% has_external_referencers as has_referencers %}+{% if has_referencers %}+<a href="{% url 'integrations_external_reference_picker' %}?item_type=ENTITY&item_id={{ attr_item_context.owner.id }}"data-async="modal"class="btn btn-sm btn-outline-primary mb-0">{% icon "link" size="sm" css_class="hi-icon-left" %}Link Content</a>{% endif %}+{% if external_view_data and external_view_data.deep_link_url %}+{% integration_display_name attr_item_context.owner as deep_link_label %}+<a href="{{ external_view_data.deep_link_url }}"+ target="_blank"+ rel="noopener noreferrer"+ class="btn btn-sm btn-outline-primary mb-0">+ Open in {{ deep_link_label|default:"source" }} →+</a>+{% endif %}+{% endblock %}++{% load static %}++{% block tab1_nav_active %}{% if data_priority.is_internal %}active{% endif %}{% endblock %}+{% block tab1_pane_active %}{% if data_priority.is_internal %}show active{% endif %}{% endblock %}++{% block tab1_pane %}+{% if attr_item_context.owner.integration_id and not attr_page_context.allow_internal_attributes %}+<div class="p-3">+ {% comment %}+ Integration-bound entity with internal editing suppressed:+ show the same "From [integration]" header used in the+ external_view_data partials (gives the operator an immediate+ "this isn't HI-owned, here's where to go edit it" affordance).+ Both conditions must be true -- a hybrid integration-bound+ entity that still allows internal attribute editing falls+ through to the framework default to keep its attribute UI.+ {% endcomment %}+ {% include "integrations/external_data/entity/header.html" with view_data=external_view_data %}+</div>+{% else %}+ {{ block.super }}+{% endif %}+{% endblock %}++{% block tab2_nav %}+{% if external_view_data and external_view_data.has_content %}+{% integration_logo_path attr_item_context.owner as tab2_logo %}+{% integration_display_name attr_item_context.owner as tab2_label %}+<li class="nav-item">+ <a class="nav-link {% if data_priority.is_external %}active{% endif %}"+ data-toggle="tab"+ href="#hi-attr-tab2-{{ attr_item_context.owner_id }}"+ role="tab">+ {% if tab2_logo %}+ <img class="mr-1" style="width: 16px; height: 16px; vertical-align: middle;"+ src="{% static tab2_logo %}" alt="">+ {% endif %}+ {{ tab2_label|default:"External" }}+ </a>+</li>+{% endif %}+{% endblock %}++{% block tab2_pane %}+{% if external_view_data and external_view_data.has_content %}+<div class="tab-pane {% if data_priority.is_external %}show active{% endif %}"+ id="hi-attr-tab2-{{ attr_item_context.owner_id }}"+ role="tabpanel">+ {% include external_view_data.template_name with view_data=external_view_data %}+</div>+{% endif %}+{% endblock %}++{% block tab3_nav %}+{% if external_references %}+<li class="nav-item">+ <a class="nav-link {% if data_priority.is_reference %}active{% endif %}"+ data-toggle="tab"+ href="#hi-attr-tab3-{{ attr_item_context.owner_id }}"+ role="tab">+ {% icon "link" size="sm" css_class="hi-icon-left" %}Linked Content+ </a>+</li>+{% endif %}+{% endblock %}++{% block tab3_pane %}+{% if external_references %}+<div class="tab-pane {% if data_priority.is_reference %}show active{% endif %}"+ id="hi-attr-tab3-{{ attr_item_context.owner_id }}"+ role="tabpanel">+ {% include "integrations/panes/external_reference_grid.html" with external_references=external_references owner_type='entity' owner_id=attr_item_context.owner.id %}+</div>+{% endif %}{% endblock %}{% block owner_fields %}diff --git a/src/hi/apps/entity/tests/test_views.py b/src/hi/apps/entity/tests/test_views.pyindex 09f46039..e6476108 100644--- a/src/hi/apps/entity/tests/test_views.py+++ b/src/hi/apps/entity/tests/test_views.py@@ -471,7 +471,7 @@ class TestEntityEditViewExternalViewData(DualModeViewTestCase):self.assertSuccessResponse(response)self.assertIsNone(response.context['external_view_data'])mock_lookup.assert_not_called()- self.assertNotIn('attr-v2-external-view-data', response.content.decode('utf-8'))+ self.assertNotIn('hi-attr-tab2-', response.content.decode('utf-8'))def test_integration_entity_hook_returns_none_omits_section(self):"""Integration entity whose gateway hook returns None: the@@ -496,7 +496,7 @@ class TestEntityEditViewExternalViewData(DualModeViewTestCase):# view for an entity with no state data), so we don't pin the# exact call count.mock_gateway.get_connector.return_value.get_external_view_data.assert_called_with(self.integration_entity)- self.assertNotIn('attr-v2-external-view-data', response.content.decode('utf-8'))+ self.assertNotIn('hi-attr-tab2-', response.content.decode('utf-8'))def test_integration_entity_structured_view_data_renders_section(self):"""``StructuredViewData`` renders the structured partial with@@ -515,7 +515,7 @@ class TestEntityEditViewExternalViewData(DualModeViewTestCase):self.assertSuccessResponse(response)content = response.content.decode('utf-8')- self.assertIn('attr-v2-external-view-data', content)+ self.assertIn('hi-attr-tab2-', content)self.assertIn('attr-v2-external-structured', content)self.assertIn('Manufacturer', content)self.assertIn('Acme', content)@@ -524,8 +524,10 @@ class TestEntityEditViewExternalViewData(DualModeViewTestCase):self.assertIn('https://upstream.example/items/42', content)def test_integration_entity_minimal_view_data_renders_deep_link_only(self):- """``MinimalViewData`` renders only the deep link placeholder- — no structured-partial markers."""+ """``MinimalViewData`` with only a deep link has no in-tab+ content (its ``has_content`` returns False), so no External+ tab is rendered. The deep link still reaches the operator+ via the sticky-panel "Open in [integration]" action button."""url = reverse('entity_edit', kwargs={'entity_id': self.integration_entity.id})minimal = self._make_minimal_view_data()@@ -540,10 +542,10 @@ class TestEntityEditViewExternalViewData(DualModeViewTestCase):self.assertSuccessResponse(response)content = response.content.decode('utf-8')- self.assertIn('attr-v2-external-view-data', content)- self.assertIn('attr-v2-external-minimal', content)+ self.assertNotIn('hi-attr-tab2-', content)+ self.assertNotIn('attr-v2-external-minimal', content)+ # Deep link surfaces via the additional-actions button.self.assertIn('https://upstream.example/items/99', content)- self.assertNotIn('attr-v2-external-structured', content)def test_integration_entity_minimal_view_data_surfaces_error_message(self):"""``MinimalViewData.error_message`` renders in the modal so@@ -629,7 +631,7 @@ class TestEntityEditViewExternalViewData(DualModeViewTestCase):self.assertSuccessResponse(response)content = response.content.decode('utf-8')- self.assertIn('attr-v2-external-view-data', content)+ self.assertIn('hi-attr-tab2-', content)self.assertIn('attr-v2-external-structured', content)self.assertNotIn('orphan_internal_prop', content)self.assertNotIn('>Add File<', content)@@ -651,7 +653,7 @@ class TestEntityEditViewExternalViewData(DualModeViewTestCase):self.assertSuccessResponse(response)self.assertIsNone(response.context['external_view_data'])- self.assertNotIn('attr-v2-external-view-data', response.content.decode('utf-8'))+ self.assertNotIn('hi-attr-tab2-', response.content.decode('utf-8'))def test_custom_template_view_data_uses_instance_template_name(self):"""``CustomTemplateViewData`` is the escape hatch: thediff --git a/src/hi/apps/entity/views.py b/src/hi/apps/entity/views.pyindex 441ad430..bad6c701 100644--- a/src/hi/apps/entity/views.py+++ b/src/hi/apps/entity/views.py@@ -14,6 +14,7 @@ from hi.apps.entity.state_panel_dispatch import StatePanelDispatcherfrom hi.apps.monitor.display_data import EntityDisplayDatafrom hi.apps.monitor.status_display_manager import StatusDisplayManager+from hi.enums import ViewDataPriorityfrom hi.integrations.integration_manager import IntegrationManagerfrom hi.views import page_not_found_responsefrom hi.hi_async_view import HiModalView@@ -170,14 +171,82 @@ class EntityEditView( HiModalView, EntityViewMixin, AttributeEditViewMixin ):return 'entity/modals/entity_edit.html'def get( self, request,*args, **kwargs ):+ priority_override = kwargs.pop( 'data_priority', None ) \+ or request.GET.get( 'data_priority' )entity = self.get_entity(request, *args, **kwargs)- attr_item_context = EntityAttributeItemEditContext( entity = entity )+ attr_item_context = EntityAttributeItemEditContext(+ entity = entity,+ extra_template_context = self._build_extra_template_context(+ entity,+ priority_override = priority_override,+ ),+ )template_context = self.create_initial_template_context(attr_item_context= attr_item_context,)- template_context['external_view_data'] = self._get_external_view_data( entity )return self.modal_response( request, template_context )+ def _build_extra_template_context(+ self, entity, priority_override : Optional[str] = None ) -> Dict[str, Any]:+ """Compute the entity-specific template variables (external+ view data, linked references, data priority) once. The+ result is stored on the AttributeItemEditContext and+ re-emitted by both the initial GET render and the async+ POST success render -- so the post-save modal refresh+ carries the same context as the initial open. (Active-tab+ persistence across the round-trip is handled client-side+ in attr.js, not via this initial data-priority value.)"""+ external_view_data = self._get_external_view_data( entity )+ external_references = entity.external_references.all()+ data_priority = self._resolve_data_priority(+ entity = entity,+ external_view_data = external_view_data,+ external_references = external_references,+ priority_override = priority_override,+ )+ return {+ 'external_view_data': external_view_data,+ 'external_references': external_references,+ 'data_priority': data_priority,+ }++ @staticmethod+ def _resolve_data_priority( entity, external_view_data,+ external_references,+ priority_override : Optional[str] = None+ ) -> ViewDataPriority:+ """Precedence: caller override (e.g., post-picker landing on+ Linked Content), then INTERNAL > EXTERNAL > REFERENCE. Falls+ back to INTERNAL when no category has content. An invalid+ override name silently falls through to the data-derived+ computation rather than erroring -- the override is an+ optional UX hint, not a contract."""+ if priority_override:+ override_value = ViewDataPriority.from_name_safe( priority_override )+ if override_value is not None:+ return override_value+ from hi.apps.attribute.enums import AttributeValueType+ file_type = str( AttributeValueType.FILE )+ has_files = entity.attributes.filter(+ value_type_str = file_type,+ ).exists()+ has_regulars = entity.attributes.exclude(+ value_type_str = file_type,+ ).exists()+ has_deleted = (+ EntityAttribute.deleted_objects.filter( entity = entity ).exists()+ if getattr( EntityAttribute, 'supports_soft_delete', False )+ else False+ )+ has_internal = has_files or has_regulars or has_deleted+ if has_internal:+ return ViewDataPriority.INTERNAL+ if external_view_data and external_view_data.has_content:+ return ViewDataPriority.EXTERNAL+ if external_references:+ return ViewDataPriority.REFERENCE+ return ViewDataPriority.default()+def _get_external_view_data( self, entity ):if not entity.integration_id:return None@@ -197,7 +266,10 @@ class EntityEditView( HiModalView, EntityViewMixin, AttributeEditViewMixin ):def post( self, request,*args, **kwargs ):entity = self.get_entity(request, *args, **kwargs)original_entity_type = entity.entity_type- attr_item_context = EntityAttributeItemEditContext( entity = entity )+ attr_item_context = EntityAttributeItemEditContext(+ entity = entity,+ extra_template_context = self._build_extra_template_context( entity ),+ )response = self.post_attribute_form(request = request,attr_item_context = attr_item_context,diff --git a/src/hi/apps/location/location_attribute_edit_context.py b/src/hi/apps/location/location_attribute_edit_context.pyindex e924cc7a..3541f514 100644--- a/src/hi/apps/location/location_attribute_edit_context.py+++ b/src/hi/apps/location/location_attribute_edit_context.py@@ -26,14 +26,25 @@ class LocationAttributeItemEditContext( AttributeItemEditContext ):the generic interface expected by attribute editing templates."""- def __init__(self, location: Location ) -> None:+ def __init__(self,+ location : Location,+ extra_template_context : Optional[Dict[str, Any]] = None ) -> None:"""Initialize context for Location attribute editing.-+Args:location: The Location instance that owns the attributes+ extra_template_context: View-supplied template variables+ (external_references, data_priority, etc.). The view+ computes them once and threads them through the+ context so the framework's GET and async-POST+ renderers both see them."""- super().__init__( owner_type = 'location', owner = location)+ super().__init__(+ owner_type = 'location',+ owner = location,+ extra_template_context = extra_template_context,+ )return@propertydiff --git a/src/hi/apps/location/templates/location/panes/location_edit_content_body.html b/src/hi/apps/location/templates/location/panes/location_edit_content_body.htmlindex 0773788d..e399b549 100644--- a/src/hi/apps/location/templates/location/panes/location_edit_content_body.html+++ b/src/hi/apps/location/templates/location/panes/location_edit_content_body.html@@ -7,9 +7,9 @@ Extends the generic attribute edit content body with location-specific field lay{% endcomment %}{% block additional_actions %}-{% has_attribute_referencers as has_referencers %}-{% if has_referencers and attr_page_context.allow_internal_attributes %}-<a href="{% url 'integrations_attribute_reference_picker' %}?item_type=LOCATION&item_id={{ attr_item_context.owner.id }}"+{% has_external_referencers as has_referencers %}+{% if has_referencers %}+<a href="{% url 'integrations_external_reference_picker' %}?item_type=LOCATION&item_id={{ attr_item_context.owner.id }}"data-async="modal"class="btn btn-sm btn-outline-primary mb-0">{% icon "link" size="sm" css_class="hi-icon-left" %}Link Content@@ -17,6 +17,32 @@ Extends the generic attribute edit content body with location-specific field lay{% endif %}{% endblock %}+{% block tab1_nav_active %}{% if data_priority.is_internal %}active{% endif %}{% endblock %}+{% block tab1_pane_active %}{% if data_priority.is_internal %}show active{% endif %}{% endblock %}++{% block tab3_nav %}+{% if external_references %}+<li class="nav-item">+ <a class="nav-link {% if data_priority.is_reference %}active{% endif %}"+ data-toggle="tab"+ href="#hi-attr-tab3-{{ attr_item_context.owner_id }}"+ role="tab">+ {% icon "link" size="sm" css_class="hi-icon-left" %}Linked Content+ </a>+</li>+{% endif %}+{% endblock %}++{% block tab3_pane %}+{% if external_references %}+<div class="tab-pane {% if data_priority.is_reference %}show active{% endif %}"+ id="hi-attr-tab3-{{ attr_item_context.owner_id }}"+ role="tabpanel">+ {% include "integrations/panes/external_reference_grid.html" with external_references=external_references owner_type='location' owner_id=attr_item_context.owner.id %}+</div>+{% endif %}+{% endblock %}+{% block owner_fields %}<!-- Location-specific fields: Only name field for modal editing --><div class="row">diff --git a/src/hi/apps/location/views.py b/src/hi/apps/location/views.pyindex cd1eae32..43df2f9c 100644--- a/src/hi/apps/location/views.py+++ b/src/hi/apps/location/views.py@@ -19,7 +19,7 @@ from hi.apps.control.one_click_control_service import (from hi.apps.entity.models import Entityfrom hi.apps.entity.view_mixins import EntityViewMixinfrom hi.apps.monitor.status_display_manager import StatusDisplayManager-from hi.enums import ItemType, ViewType+from hi.enums import ItemType, ViewDataPriority, ViewTypefrom hi.exceptions import ForceSynchronousExceptionfrom hi.hi_async_view import HiModalViewfrom hi.hi_grid_view import HiGridView@@ -199,22 +199,77 @@ class LocationEditView( HiModalView, LocationViewMixin, AttributeEditViewMixin )return 'location/modals/location_edit.html'def get( self, request,*args, **kwargs ):+ priority_override = kwargs.pop( 'data_priority', None ) \+ or request.GET.get( 'data_priority' )location = self.get_location(request, *args, **kwargs)- attr_item_context = LocationAttributeItemEditContext( location = location )+ attr_item_context = LocationAttributeItemEditContext(+ location = location,+ extra_template_context = self._build_extra_template_context(+ location,+ priority_override = priority_override,+ ),+ )template_context = self.create_initial_template_context(attr_item_context= attr_item_context,)return self.modal_response( request, template_context )++ def _build_extra_template_context( self, location, priority_override = None ):+ external_references = location.external_references.all()+ data_priority = self._resolve_data_priority(+ location = location,+ external_references = external_references,+ priority_override = priority_override,+ )+ return {+ 'external_references': external_references,+ 'data_priority': data_priority,+ }++ @staticmethod+ def _resolve_data_priority( location, external_references,+ priority_override = None ) -> ViewDataPriority:+ """Precedence: caller override (e.g., post-picker landing on+ Linked Content), then INTERNAL > REFERENCE. Locations have no+ EXTERNAL view-data category. An invalid override name+ silently falls through to the data-derived computation."""+ if priority_override:+ override_value = ViewDataPriority.from_name_safe( priority_override )+ if override_value is not None:+ return override_value+ from hi.apps.attribute.enums import AttributeValueType+ from hi.apps.location.models import LocationAttribute+ file_type = str( AttributeValueType.FILE )+ has_files = location.attributes.filter(+ value_type_str = file_type,+ ).exists()+ has_regulars = location.attributes.exclude(+ value_type_str = file_type,+ ).exists()+ has_deleted = (+ LocationAttribute.deleted_objects.filter( location = location ).exists()+ if getattr( LocationAttribute, 'supports_soft_delete', False )+ else False+ )+ has_internal = has_files or has_regulars or has_deleted+ if has_internal:+ return ViewDataPriority.INTERNAL+ if external_references:+ return ViewDataPriority.REFERENCE+ return ViewDataPriority.default()def post( self, request,*args, **kwargs ):location = self.get_location(request, *args, **kwargs)- attr_item_context = LocationAttributeItemEditContext( location = location )+ attr_item_context = LocationAttributeItemEditContext(+ location = location,+ extra_template_context = self._build_extra_template_context( location ),+ )return self.post_attribute_form(request = request,attr_item_context = attr_item_context,)-+class LocationAttributeUploadView( View, LocationViewMixin, AttributeEditViewMixin ):def post( self, request,*args, **kwargs ):diff --git a/src/hi/constants.py b/src/hi/constants.pyindex faa6b7b6..16b4b3d2 100644--- a/src/hi/constants.py+++ b/src/hi/constants.py@@ -161,38 +161,60 @@ DIVID = {# Entity Picker - Filter values'ENTITY_PICKER_FILTER_ALL': 'all',- # ATTRIBUTE_REFERENCE picker — DOM classes / data attributes+ # EXTERNAL_REFERENCE picker — DOM classes / data attributes# / wire-format field names shared between the picker templates,- # the picker views, and attr-picker.js. Mirror these in- # ``src/hi/static/js/main.js`` (``Hi.ATTR_PICKER_*``).- 'ATTR_PICKER_ROOT_CLASS': 'hi-attr-picker',- 'ATTR_PICKER_CHIPS_CLASS': 'hi-attr-picker-chips',- 'ATTR_PICKER_CHIPS_EMPTY_CLASS': 'hi-attr-picker-chips-empty',- 'ATTR_PICKER_CHIP_REMOVE_CLASS': 'hi-attr-picker-chip-remove',- 'ATTR_PICKER_RESULTS_CLASS': 'hi-attr-picker-results',- 'ATTR_PICKER_SEARCH_FORM_CLASS': 'hi-attr-picker-search-form',- 'ATTR_PICKER_ATTACH_FORM_CLASS': 'hi-attr-picker-attach-form',- 'ATTR_PICKER_ATTACH_BTN_CLASS': 'hi-attr-picker-attach-btn',- 'ATTR_PICKER_ATTACH_LABEL_CLASS': 'hi-attr-picker-attach-label',- 'ATTR_PICKER_RESULT_CHECKBOX_CLASS': 'hi-attr-picker-result-checkbox',- 'ATTR_PICKER_SEARCH_URL_ATTR': 'data-attr-picker-search-url',- 'ATTR_PICKER_TITLE_ATTR': 'data-attr-picker-title',- 'ATTR_PICKER_SOURCE_URL_ATTR': 'data-attr-picker-source-url',- 'ATTR_PICKER_QUERY_FIELD': 'query',- 'ATTR_PICKER_LIMIT_FIELD': 'limit',- 'ATTR_PICKER_ITEM_TYPE_FIELD': 'item_type',- 'ATTR_PICKER_ITEM_ID_FIELD': 'item_id',- 'ATTR_PICKER_INTEGRATION_ID_FIELD': 'integration_id',- 'ATTR_PICKER_SELECTIONS_JSON_FIELD': 'selections_json',- 'ATTR_PICKER_SELECTION_TITLE_KEY': 'title',- 'ATTR_PICKER_SELECTION_URL_KEY': 'source_url',- 'ATTR_PICKER_SOURCE_BANNER_CLASS': 'hi-attr-picker-source-banner',- 'ATTR_PICKER_SOURCE_BANNER_LOGO_CLASS': 'hi-attr-picker-source-banner-logo',- 'ATTR_PICKER_SOURCE_BANNER_LABEL_CLASS': 'hi-attr-picker-source-banner-label',- 'ATTR_PICKER_SOURCE_OPTION_CLASS': 'hi-attr-picker-source-option',- 'ATTR_PICKER_SOURCE_ID_ATTR': 'data-attr-picker-source-id',- 'ATTR_PICKER_SOURCE_LOGO_ATTR': 'data-attr-picker-source-logo',- 'ATTR_PICKER_SOURCE_LABEL_ATTR': 'data-attr-picker-source-label',+ # the picker views, and external-reference-picker.js. Mirror these in+ # ``src/hi/static/js/main.js`` (``Hi.REF_PICKER_*``).+ 'REF_PICKER_ROOT_CLASS': 'hi-ref-picker',+ 'REF_PICKER_CHIPS_CLASS': 'hi-ref-picker-chips',+ 'REF_PICKER_CHIPS_EMPTY_CLASS': 'hi-ref-picker-chips-empty',+ 'REF_PICKER_CHIP_REMOVE_CLASS': 'hi-ref-picker-chip-remove',+ 'REF_PICKER_RESULTS_CLASS': 'hi-ref-picker-results',+ 'REF_PICKER_SEARCH_FORM_CLASS': 'hi-ref-picker-search-form',+ 'REF_PICKER_ATTACH_FORM_CLASS': 'hi-ref-picker-attach-form',+ 'REF_PICKER_ATTACH_BTN_CLASS': 'hi-ref-picker-attach-btn',+ 'REF_PICKER_ATTACH_LABEL_CLASS': 'hi-ref-picker-attach-label',+ 'REF_PICKER_RESULT_CHECKBOX_CLASS': 'hi-ref-picker-result-checkbox',+ 'REF_PICKER_SEARCH_URL_ATTR': 'data-ref-picker-search-url',+ 'REF_PICKER_TITLE_ATTR': 'data-ref-picker-title',+ 'REF_PICKER_SOURCE_URL_ATTR': 'data-ref-picker-source-url',+ 'REF_PICKER_INTEGRATION_NAME_ATTR': 'data-ref-picker-integration-name',+ 'REF_PICKER_MIME_TYPE_ATTR': 'data-ref-picker-mime-type',+ 'REF_PICKER_QUERY_FIELD': 'query',+ 'REF_PICKER_LIMIT_FIELD': 'limit',+ 'REF_PICKER_ITEM_TYPE_FIELD': 'item_type',+ 'REF_PICKER_ITEM_ID_FIELD': 'item_id',+ 'REF_PICKER_INTEGRATION_ID_FIELD': 'integration_id',+ 'REF_PICKER_SELECTIONS_JSON_FIELD': 'selections_json',+ 'REF_PICKER_SELECTION_TITLE_KEY': 'title',+ 'REF_PICKER_SELECTION_URL_KEY': 'source_url',+ 'REF_PICKER_SELECTION_INTEGRATION_NAME_KEY': 'integration_name',+ 'REF_PICKER_SELECTION_MIME_TYPE_KEY': 'mime_type',+ 'REF_PICKER_SOURCE_BANNER_CLASS': 'hi-ref-picker-source-banner',+ 'REF_PICKER_SOURCE_BANNER_LOGO_CLASS': 'hi-ref-picker-source-banner-logo',+ 'REF_PICKER_SOURCE_BANNER_LABEL_CLASS': 'hi-ref-picker-source-banner-label',+ 'REF_PICKER_SOURCE_OPTION_CLASS': 'hi-ref-picker-source-option',+ 'REF_PICKER_SOURCE_ID_ATTR': 'data-ref-picker-source-id',+ 'REF_PICKER_SOURCE_LOGO_ATTR': 'data-ref-picker-source-logo',+ 'REF_PICKER_SOURCE_LABEL_ATTR': 'data-ref-picker-source-label',++ # External-reference grid -- DOM classes, data attributes, and+ # action endpoint URL names for the framework-rendered card grid+ # on the entity/location edit pages. Mirror in+ # ``src/hi/static/js/main.js`` (``Hi.EXT_REF_*``).+ 'EXT_REF_GRID_CLASS': 'hi-ext-ref-grid',+ 'EXT_REF_CARD_CLASS': 'hi-ext-ref-card',+ 'EXT_REF_TITLE_INPUT_CLASS': 'hi-ext-ref-title-input',+ 'EXT_REF_DELETE_BTN_CLASS': 'hi-ext-ref-delete-btn',+ 'EXT_REF_REORDER_LEFT_CLASS': 'hi-ext-ref-reorder-left',+ 'EXT_REF_REORDER_RIGHT_CLASS': 'hi-ext-ref-reorder-right',+ 'EXT_REF_REFERENCE_ID_ATTR': 'data-ext-ref-id',+ 'EXT_REF_OWNER_TYPE_ATTR': 'data-ext-ref-owner-type',+ 'EXT_REF_SOURCE_URL_ATTR': 'data-ext-ref-source-url',+ 'EXT_REF_TITLE_FIELD': 'title',+ 'EXT_REF_DIRECTION_FIELD': 'direction',+ 'EXT_REF_DIRECTION_LEFT': 'left',+ 'EXT_REF_DIRECTION_RIGHT': 'right',# Location SVG Editor Grid Structure'LOCATION_SVG_EDIT_TOP': 'hi-location-svg-editor-top',diff --git a/src/hi/enums.py b/src/hi/enums.pyindex 569d035e..58df52dc 100644--- a/src/hi/enums.py+++ b/src/hi/enums.py@@ -48,7 +48,35 @@ class ViewMode(LabeledEnum):def is_editing(self):return bool( self == ViewMode.EDIT )-++class ViewDataPriority(LabeledEnum):+ """Which category of owner-detail data the edit modal should+ foreground when multiple categories are present. Views compute+ this from the available data; templates map each value onto+ whichever tab holds that category. Decouples view-layer+ precedence decisions from template-layer tab ordering."""++ INTERNAL = ('Internal', '') # HI-owned files / regular attributes+ EXTERNAL = ('External', '') # integration-supplied view data+ REFERENCE = ('Reference', '') # cross-source linked content++ @classmethod+ def default(cls):+ return cls.INTERNAL++ @property+ def is_internal(self) -> bool:+ return self == ViewDataPriority.INTERNAL++ @property+ def is_external(self) -> bool:+ return self == ViewDataPriority.EXTERNAL++ @property+ def is_reference(self) -> bool:+ return self == ViewDataPriority.REFERENCE++class ItemType(LabeledEnum):# Many class have polymorpic behavior along different dimensions with# the dimensions being overlapping between subsets. This is mostly@@ -63,6 +91,22 @@ class ItemType(LabeledEnum):LOCATION = ( 'Location', '' )LOCATION_VIEW = ( 'Location View', '' )+ @property+ def is_entity(self) -> bool:+ return self == ItemType.ENTITY++ @property+ def is_collection(self) -> bool:+ return self == ItemType.COLLECTION++ @property+ def is_location(self) -> bool:+ return self == ItemType.LOCATION++ @property+ def is_location_view(self) -> bool:+ return self == ItemType.LOCATION_VIEW+@classmethoddef HTML_ID_ARG(cls):return 'html_id'diff --git a/src/hi/integrations/admin.py b/src/hi/integrations/admin.pyindex c223a95f..00368d74 100644--- a/src/hi/integrations/admin.py+++ b/src/hi/integrations/admin.py@@ -36,7 +36,7 @@ class IntegrationAdmin(admin.ModelAdmin):class IntegrationAttributeAdmin(admin.ModelAdmin):show_full_result_count = False-+list_display = ('integration','name',@@ -49,3 +49,51 @@ class IntegrationAttributeAdmin(admin.ModelAdmin):search_fields = ['name', 'integration__integration_id']readonly_fields = ('integration', 'created_datetime')inlines = [IntegrationAttributeHistoryInLine]++[email protected](models.EntityExternalReference)+class EntityExternalReferenceAdmin(admin.ModelAdmin):++ show_full_result_count = False++ list_display = (+ 'entity',+ 'integration_id',+ 'integration_name',+ 'title',+ 'mime_type',+ 'order_id',+ 'updated_datetime',+ )++ list_filter = ( 'integration_id', )+ search_fields = [+ 'title',+ 'integration_name',+ 'entity__name',+ ]+ readonly_fields = ( 'entity', 'created_datetime', 'updated_datetime' )++[email protected](models.LocationExternalReference)+class LocationExternalReferenceAdmin(admin.ModelAdmin):++ show_full_result_count = False++ list_display = (+ 'location',+ 'integration_id',+ 'integration_name',+ 'title',+ 'mime_type',+ 'order_id',+ 'updated_datetime',+ )++ list_filter = ( 'integration_id', )+ search_fields = [+ 'title',+ 'integration_name',+ 'location__name',+ ]+ readonly_fields = ( 'location', 'created_datetime', 'updated_datetime' )diff --git a/src/hi/integrations/capability_gateway.py b/src/hi/integrations/capability_gateway.pyindex 23296541..413981fb 100644--- a/src/hi/integrations/capability_gateway.py+++ b/src/hi/integrations/capability_gateway.py@@ -1,7 +1,7 @@"""Common base for the per-capability gateway peers.``IntegrationConnector``, ``IntegrationImporter``, and-``IntegrationAttributeReferencer`` are the three per-capability+``IntegrationExternalReferencer`` are the three per-capabilitygateway classes today: each is the framework-facing surface for aspecific ``IntegrationCapability``.diff --git a/src/hi/integrations/connector/external_view_data.py b/src/hi/integrations/connector/external_view_data.pyindex f9646ecf..03125882 100644--- a/src/hi/integrations/connector/external_view_data.py+++ b/src/hi/integrations/connector/external_view_data.py@@ -46,6 +46,13 @@ class ExternalViewData:template_name: str = ''deep_link_url: Optional[str] = None+ @property+ def has_content(self) -> bool:+ """True when the rendered partial would produce visible+ content. The tabbed UI consults this to decide whether to+ show the integration's data tab at all."""+ return False+@dataclassclass StructuredViewData(ExternalViewData):@@ -55,6 +62,10 @@ class StructuredViewData(ExternalViewData):attributes: List[NameValuePair] = field(default_factory=list)attachments: List[AttachmentRef] = field(default_factory=list)+ @property+ def has_content(self) -> bool:+ return bool(self.attachments or self.attributes)+@dataclassclass CustomTemplateViewData(ExternalViewData):@@ -72,6 +83,12 @@ class CustomTemplateViewData(ExternalViewData):'CustomTemplateViewData requires a non-empty template_name.')+ @property+ def has_content(self) -> bool:+ # Custom template implies the integration knows what it+ # wants; assume the partial produces something.+ return True+@dataclassclass MinimalViewData(ExternalViewData):@@ -80,3 +97,11 @@ class MinimalViewData(ExternalViewData):template_name: str = 'integrations/external_data/entity/minimal.html'error_message: Optional[str] = None++ @property+ def has_content(self) -> bool:+ # Renders the alert when error_message is set, and the+ # "External data unavailable" hint when deep_link_url is+ # absent. With only a deep_link, the partial body is empty+ # (the link is surfaced elsewhere).+ return bool(self.error_message) or not self.deep_link_urldiff --git a/src/hi/integrations/enums.py b/src/hi/integrations/enums.pyindex edcfa080..7301c039 100644--- a/src/hi/integrations/enums.py+++ b/src/hi/integrations/enums.py@@ -8,9 +8,9 @@ class IntegrationCapability( LabeledEnum ):CONNECT = ( 'Connect', 'Live mirror of an upstream system.' )IMPORT = ( 'Import', 'One-shot pull of upstream items into HI.' )- ATTRIBUTE_REFERENCE = (- 'Attribute Reference',- 'Search-and-attach external documents as Entity/Location attributes.',+ EXTERNAL_REFERENCE = (+ 'External Reference',+ 'Search-and-attach external documents/photos as Entity/Location external references.',)diff --git a/src/hi/integrations/integration_gateway.py b/src/hi/integrations/integration_gateway.pyindex 5a01c4e8..35c59eb9 100644--- a/src/hi/integrations/integration_gateway.py+++ b/src/hi/integrations/integration_gateway.py@@ -7,7 +7,7 @@ from hi.apps.entity.entity_placement import (from hi.apps.entity.models import Entityfrom hi.integrations.referencer.integration_referencer import (- IntegrationAttributeReferencer,+ IntegrationExternalReferencer,)from hi.integrations.connector.integration_connector import IntegrationConnectorfrom hi.integrations.importer.integration_importer import IntegrationImporter@@ -49,9 +49,9 @@ class IntegrationGateway:ingest, and discard operations."""return None- def get_attribute_referencer(self) -> Optional[IntegrationAttributeReferencer]:- """Return the integration's attribute-referencer when it supports the- ATTRIBUTE_REFERENCE capability; None otherwise. The framework owns+ def get_external_referencer(self) -> Optional[IntegrationExternalReferencer]:+ """Return the integration's external-referencer when it supports the+ EXTERNAL_REFERENCE capability; None otherwise. The framework ownsthe picker and the TEXT-attribute attach lifecycle; the referencersupplies the integration-specific search-against-upstream operation."""return Nonediff --git a/src/hi/integrations/managers.py b/src/hi/integrations/managers.pyindex 7077fb3a..5e6ae7b3 100644--- a/src/hi/integrations/managers.py+++ b/src/hi/integrations/managers.py@@ -1,11 +1,16 @@-from typing import Sequence+import logging+from typing import Optional, Sequence-from django.db import models+from django.core.files.base import ContentFile+from django.db import models, transactionfrom django.db.models import Qfrom .transient_models import IntegrationKey+logger = logging.getLogger(__name__)++class IntegrationDetailsModelManager(models.Manager):def filter_by_integration_key( self, integration_key : IntegrationKey ):@@ -15,11 +20,112 @@ class IntegrationDetailsModelManager(models.Manager):def filter_by_integration_keys( self, integration_keys : Sequence[ IntegrationKey ] ):if not integration_keys:return self.none()-+query = Q()for integration_key in integration_keys:query |= Q( integration_id = integration_key.integration_id,integration_name = integration_key.integration_name )continuereturn self.filter(query)+++class ExternalReferenceManagerBase( models.Manager ):+ """Shared upsert logic for the two ExternalReference concrete+ models. Concrete managers set ``_owner_field_name`` to wire the+ owner FK into the lookup."""++ _owner_field_name: str = ''++ def create_or_update(+ self, *,+ owner,+ integration_key : IntegrationKey,+ title : str,+ source_url : str,+ mime_type : str = '',+ thumbnail_bytes : Optional[bytes] = None,+ ):+ """Upsert by ``(owner, integration_key)``.++ On insert all fields are set; the thumbnail file is written+ when ``thumbnail_bytes`` is provided. On update,+ ``source_url`` and ``mime_type`` are overwritten with the+ upstream's current values; ``title``, ``order_id``, and+ ``created_datetime`` are preserved (operator may have edited+ the title locally and the position is the operator's, not+ the upstream's); ``updated_datetime`` bumps; the thumbnail+ is re-written when ``thumbnail_bytes`` is provided (None+ leaves the existing thumbnail intact so a transient upstream+ thumbnail outage doesn't blank out an otherwise-good card).+ """+ lookup = {+ self._owner_field_name : owner,+ 'integration_id' : integration_key.integration_id,+ 'integration_name' : integration_key.integration_name,+ }+ existing = self.filter( **lookup ).first()++ if existing is None:+ # Insert path is two saves separated by a file write+ # (FileField.save() doesn't bind the new path until we+ # save the model row again). Wrap in atomic so the row+ # state is consistent even if the second save fails;+ # the file itself isn't rolled back by atomic, but+ # orphan media files are the existing best-effort+ # tradeoff (see AttributeModel.delete()).+ with transaction.atomic():+ instance = self.model(+ **lookup,+ title = title,+ source_url = source_url,+ mime_type = mime_type or '',+ )+ instance.save()+ if thumbnail_bytes:+ self._write_thumbnail(+ instance, integration_key.integration_name, thumbnail_bytes,+ )+ instance.save( update_fields = [ 'thumbnail', 'updated_datetime' ] )+ return instance++ existing.source_url = source_url+ existing.mime_type = mime_type or ''+ update_fields = [ 'source_url', 'mime_type', 'updated_datetime' ]+ if thumbnail_bytes:+ self._write_thumbnail(+ existing, integration_key.integration_name, thumbnail_bytes,+ )+ update_fields.append( 'thumbnail' )+ existing.save( update_fields = update_fields )+ return existing++ @staticmethod+ def _write_thumbnail(+ instance, integration_name : str, thumbnail_bytes : bytes,+ ):+ # Stable, filesystem-safe filename per integration_name so+ # repeated upsert calls land on the same path. Deleting any+ # pre-existing file first sidesteps Django FileField's+ # uniqueness-suffix collision handling.+ safe_name = integration_name.replace( '/', '_' ).replace( '\\', '_' )+ filename = f'{safe_name}.png'+ if instance.thumbnail:+ try:+ instance.thumbnail.delete( save = False )+ except Exception as e:+ logger.warning(+ f'Error deleting old external-reference thumbnail '+ f'{instance.thumbnail.name}: {e}'+ )+ instance.thumbnail.save(+ filename, ContentFile( thumbnail_bytes ), save = False,+ )+++class EntityExternalReferenceManager( ExternalReferenceManagerBase ):+ _owner_field_name = 'entity'+++class LocationExternalReferenceManager( ExternalReferenceManagerBase ):+ _owner_field_name = 'location'diff --git a/src/hi/integrations/migrations/0007_entityexternalreference_locationexternalreference.py b/src/hi/integrations/migrations/0007_entityexternalreference_locationexternalreference.pynew file mode 100644index 00000000..c3408834--- /dev/null+++ b/src/hi/integrations/migrations/0007_entityexternalreference_locationexternalreference.py@@ -0,0 +1,161 @@+# Generated by Django 5.2.14 on 2026-05-31 15:22++import django.db.models.deletion+import hi.integrations.models+from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("entity", "0020_entity_allow_internal_attributes"),+ ("integrations", "0006_add_integration_is_paused"),+ ("location", "0006_add_locationattribute_is_deleted"),+ ]++ operations = [+ migrations.CreateModel(+ name="EntityExternalReference",+ fields=[+ (+ "id",+ models.BigAutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ (+ "integration_id",+ models.CharField(+ db_index=True, max_length=32, verbose_name="Integration Id"+ ),+ ),+ (+ "integration_name",+ models.CharField(max_length=255, verbose_name="Integration Name"),+ ),+ ("title", models.CharField(max_length=255, verbose_name="Title")),+ (+ "source_url",+ models.URLField(max_length=2048, verbose_name="Source URL"),+ ),+ (+ "mime_type",+ models.CharField(+ blank=True, default="", max_length=128, verbose_name="MIME Type"+ ),+ ),+ (+ "thumbnail",+ models.FileField(+ blank=True,+ null=True,+ upload_to=hi.integrations.models._external_reference_upload_to,+ verbose_name="Thumbnail",+ ),+ ),+ (+ "order_id",+ models.PositiveIntegerField(default=0, verbose_name="Order"),+ ),+ (+ "created_datetime",+ models.DateTimeField(auto_now_add=True, verbose_name="Created"),+ ),+ (+ "updated_datetime",+ models.DateTimeField(auto_now=True, verbose_name="Updated"),+ ),+ (+ "entity",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="external_references",+ to="entity.entity",+ verbose_name="Entity",+ ),+ ),+ ],+ options={+ "verbose_name": "Entity External Reference",+ "verbose_name_plural": "Entity External References",+ "ordering": ["order_id", "-created_datetime"],+ "abstract": False,+ "unique_together": {("entity", "integration_id", "integration_name")},+ },+ ),+ migrations.CreateModel(+ name="LocationExternalReference",+ fields=[+ (+ "id",+ models.BigAutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ (+ "integration_id",+ models.CharField(+ db_index=True, max_length=32, verbose_name="Integration Id"+ ),+ ),+ (+ "integration_name",+ models.CharField(max_length=255, verbose_name="Integration Name"),+ ),+ ("title", models.CharField(max_length=255, verbose_name="Title")),+ (+ "source_url",+ models.URLField(max_length=2048, verbose_name="Source URL"),+ ),+ (+ "mime_type",+ models.CharField(+ blank=True, default="", max_length=128, verbose_name="MIME Type"+ ),+ ),+ (+ "thumbnail",+ models.FileField(+ blank=True,+ null=True,+ upload_to=hi.integrations.models._external_reference_upload_to,+ verbose_name="Thumbnail",+ ),+ ),+ (+ "order_id",+ models.PositiveIntegerField(default=0, verbose_name="Order"),+ ),+ (+ "created_datetime",+ models.DateTimeField(auto_now_add=True, verbose_name="Created"),+ ),+ (+ "updated_datetime",+ models.DateTimeField(auto_now=True, verbose_name="Updated"),+ ),+ (+ "location",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="external_references",+ to="location.location",+ verbose_name="Location",+ ),+ ),+ ],+ options={+ "verbose_name": "Location External Reference",+ "verbose_name_plural": "Location External References",+ "ordering": ["order_id", "-created_datetime"],+ "abstract": False,+ "unique_together": {("location", "integration_id", "integration_name")},+ },+ ),+ ]diff --git a/src/hi/integrations/models.py b/src/hi/integrations/models.pyindex fdfbc09a..a2a440d2 100644--- a/src/hi/integrations/models.py+++ b/src/hi/integrations/models.py@@ -1,11 +1,20 @@-from typing import Dict+import logging+from typing import Dict, Optional+from django.core.files.storage import default_storagefrom django.db import modelsfrom hi.apps.attribute.models import AttributeModel, AttributeValueHistoryModelfrom .transient_models import IntegrationKey, IntegrationDetails-from .managers import IntegrationDetailsModelManager+from .managers import (+ EntityExternalReferenceManager,+ IntegrationDetailsModelManager,+ LocationExternalReferenceManager,+)+++logger = logging.getLogger(__name__)class Integration( models.Model ):@@ -213,3 +222,156 @@ class IntegrationAttributeHistory(AttributeValueHistoryModel):indexes = [models.Index(fields=['attribute', '-changed_datetime']),]+++def _external_reference_upload_to( instance, filename ):+ """Per-owner-type, per-integration thumbnail path. Concrete+ subclasses set ``_owner_type_path_segment`` so this resolves+ without per-subclass duplication."""+ return (+ f'{instance._owner_type_path_segment}/external/'+ f'{instance.integration_id}/thumbnails/{filename}'+ )+++class ExternalReferenceBase( models.Model ):+ """Abstract base for the per-owner external-reference tables.++ Each row represents an upstream item (Paperless document, Immich+ asset, etc.) attached to an HI Entity or Location. Field naming+ follows IntegrationKey -- ``(integration_id, integration_name)``+ -- so the existing IntegrationKey machinery rounds-trips through+ the property/setter below. ``integration_name`` holds the+ upstream's opaque identifier (Immich UUID, Paperless document+ id, etc.).++ Thumbnail bytes are persisted under MEDIA_ROOT; ``delete()``+ cleans up the file on a best-effort basis.+ """++ integration_id = models.CharField(+ 'Integration Id',+ max_length = 32,+ db_index = True,+ )+ integration_name = models.CharField(+ 'Integration Name',+ max_length = 255,+ )+ title = models.CharField(+ 'Title',+ max_length = 255,+ )+ source_url = models.URLField(+ 'Source URL',+ max_length = 2048,+ )+ mime_type = models.CharField(+ 'MIME Type',+ max_length = 128,+ blank = True,+ default = '',+ )+ thumbnail = models.FileField(+ 'Thumbnail',+ upload_to = _external_reference_upload_to,+ blank = True,+ null = True,+ )+ order_id = models.PositiveIntegerField(+ 'Order',+ default = 0,+ )+ created_datetime = models.DateTimeField(+ 'Created',+ auto_now_add = True,+ blank = True,+ )+ updated_datetime = models.DateTimeField(+ 'Updated',+ auto_now = True,+ blank = True,+ )++ # Concrete subclasses set this to the path segment used in+ # ``_external_reference_upload_to``: ``'entity'`` or ``'location'``.+ _owner_type_path_segment: str = ''++ class Meta:+ abstract = True+ ordering = [ 'order_id', '-created_datetime' ]++ @property+ def integration_key(self) -> Optional[IntegrationKey]:+ # Returns None when fields are unset (shouldn't happen on a+ # saved row; defensive).+ if self.integration_id is None or self.integration_name is None:+ return None+ return IntegrationKey(+ integration_id = self.integration_id,+ integration_name = self.integration_name,+ )++ @integration_key.setter+ def integration_key(self, integration_key: Optional[IntegrationKey]):+ if not integration_key:+ self.integration_id = None+ self.integration_name = None+ return+ self.integration_id = integration_key.integration_id+ self.integration_name = integration_key.integration_name++ def delete(self, *args, **kwargs):+ """Best-effort thumbnail file cleanup."""+ thumbnail_name = self.thumbnail.name if self.thumbnail else None+ if thumbnail_name:+ try:+ if default_storage.exists( thumbnail_name ):+ default_storage.delete( thumbnail_name )+ logger.debug(+ f'Deleted external-reference thumbnail: {thumbnail_name}'+ )+ except Exception as e:+ logger.warning(+ f'Error deleting external-reference thumbnail '+ f'{thumbnail_name}: {e}'+ )+ return super().delete( *args, **kwargs )+++class EntityExternalReference( ExternalReferenceBase ):++ entity = models.ForeignKey(+ 'entity.Entity',+ related_name = 'external_references',+ verbose_name = 'Entity',+ on_delete = models.CASCADE,+ )++ _owner_type_path_segment = 'entity'++ objects = EntityExternalReferenceManager()++ class Meta( ExternalReferenceBase.Meta ):+ verbose_name = 'Entity External Reference'+ verbose_name_plural = 'Entity External References'+ unique_together = [ ( 'entity', 'integration_id', 'integration_name' ) ]+++class LocationExternalReference( ExternalReferenceBase ):++ location = models.ForeignKey(+ 'location.Location',+ related_name = 'external_references',+ verbose_name = 'Location',+ on_delete = models.CASCADE,+ )++ _owner_type_path_segment = 'location'++ objects = LocationExternalReferenceManager()++ class Meta( ExternalReferenceBase.Meta ):+ verbose_name = 'Location External Reference'+ verbose_name_plural = 'Location External References'+ unique_together = [ ( 'location', 'integration_id', 'integration_name' ) ]diff --git a/src/hi/integrations/referencer/integration_referencer.py b/src/hi/integrations/referencer/integration_referencer.pyindex 2da29e8d..1d2fbb30 100644--- a/src/hi/integrations/referencer/integration_referencer.py+++ b/src/hi/integrations/referencer/integration_referencer.py@@ -1,26 +1,36 @@"""-Per-integration ATTRIBUTE_REFERENCE base class.+Per-integration EXTERNAL_REFERENCE base class.Each integration that advertises-``IntegrationCapability.ATTRIBUTE_REFERENCE`` provides a concrete+``IntegrationCapability.EXTERNAL_REFERENCE`` provides a concretesubclass and returns an instance from-``IntegrationGateway.get_attribute_referencer()``. The framework-owns the picker UI, attach lifecycle, and TEXT-attribute creation;-the integration participates by translating a search query into a-list of ``AttributeReferenceResult`` candidates.+``IntegrationGateway.get_external_referencer()``. The framework+owns the picker UI, attach dispatcher, and the+EntityExternalReference / LocationExternalReference tables; the+integration participates by (a) translating a search query into+``ExternalReferenceResult`` candidates and (b) attaching selected+candidates as rows on those tables, fetching thumbnail bytes from+upstream as part of attach."""+import loggingfrom typing import List, Optionalfrom hi.integrations.capability_gateway import CapabilityGatewayfrom hi.integrations.enums import IntegrationCapability+from hi.integrations.exceptions import IntegrationAttributeErrorfrom hi.integrations.models import IntegrationAttributefrom hi.integrations.transient_models import IntegrationValidationResult-from .transient_models import AttributeReferenceSearchResult+from .transient_models import (+ ExternalReferenceAttachBatchOutcome,+ ExternalReferenceAttachOutcome,+ ExternalReferenceResult,+ ExternalReferenceSearchResult,+)-class IntegrationAttributeReferencer( CapabilityGateway ):+class IntegrationExternalReferencer( CapabilityGateway ):"""Search-and-attach surface contributed by integrations thatexpose a queryable corpus of linkable resources (documents,@@ -28,7 +38,7 @@ class IntegrationAttributeReferencer( CapabilityGateway ):``search_references`` from the picker view and presents thereturned candidates to the operator for multi-select attach."""- capability = IntegrationCapability.ATTRIBUTE_REFERENCE+ capability = IntegrationCapability.EXTERNAL_REFERENCEdef validate_configuration(self,@@ -42,17 +52,17 @@ class IntegrationAttributeReferencer( CapabilityGateway ):self,query: str,limit: int = 20,- ) -> AttributeReferenceSearchResult:+ ) -> ExternalReferenceSearchResult:"""Query the upstream corpus and return up to ``limit``candidates wrapped in an- ``AttributeReferenceSearchResult``. Operators see the+ ``ExternalReferenceSearchResult``. Operators see thereturned list rendered as cards (thumbnail/mime-icon +title + snippet + clickable source URL); multi-selecting- any subset attaches them as TEXT attributes on the host- Entity or Location.+ any subset attaches them via ``attach_references`` on the+ host Entity or Location.Implementations should:- - Return ``AttributeReferenceSearchResult(results=[])``+ - Return ``ExternalReferenceSearchResult(results=[])``when the query yields no matches (no ``error_message``).- Populate ``error_message`` when the upstream call fails(auth rejected, unreachable, etc.) so the picker@@ -63,13 +73,174 @@ class IntegrationAttributeReferencer( CapabilityGateway ):- Order results by upstream relevance (most-relevantfirst); the picker preserves this order.- Not raise on empty/whitespace queries; return- ``AttributeReferenceSearchResult(results=[])``.+ ``ExternalReferenceSearchResult(results=[])``."""raise NotImplementedError('Subclasses must override this method')+ def attach_references(+ self,+ owner,+ selections: List[ExternalReferenceResult],+ ) -> ExternalReferenceAttachBatchOutcome:+ """Attach the operator-selected upstream items as+ ExternalReference rows on the given owner (Entity or+ Location). Concrete here: subclasses contribute the upstream+ client and per-selection attach logic via ``_build_client``,+ ``_try_upstream_thumbnail``, and ``_try_generate_from_original``.++ Returns one ``ExternalReferenceAttachOutcome`` per selection+ wrapped in an ``ExternalReferenceAttachBatchOutcome``. The+ framework dispatcher hands the composite to the view; the+ view chooses the next modal (owner edit on full success,+ error modal otherwise) from the aggregate counts.++ Failure semantics:+ - A failure to build the upstream client synthesizes an+ all-failure batch (one outcome per selection), so the+ error modal carries an outcome count consistent with+ what the operator selected.+ - Per-selection exceptions become ``success=False``+ outcomes with an operator-readable ``error_message``;+ they do NOT abort the rest of the batch. Batch-level+ atomicity is deliberately NOT used -- it would defeat+ the per-selection isolation. Per-row consistency is+ owned by ``create_or_update``.+ - A missing thumbnail is NOT a failure outcome -- the+ placeholder render covers it.+ """+ label = self.get_metadata().label+ try:+ client = self.build_client()+ except IntegrationAttributeError as e:+ self.logger.warning( f'{label} attach aborted: {e}' )+ return self._all_failure_batch(+ selections,+ f'{label} integration is not configured.',+ )+ except Exception as e:+ self.logger.exception( f'{label} client build failed: {e}' )+ return self._all_failure_batch(+ selections,+ f'{label} integration error -- see server logs.',+ )++ outcomes : List[ExternalReferenceAttachOutcome] = []+ manager = self._manager_for_owner( owner )+ for selection in selections:+ try:+ self._attach_one( client, manager, owner, selection )+ outcomes.append( ExternalReferenceAttachOutcome(+ success = True,+ ) )+ except Exception as e:+ self.logger.warning(+ f'{label} attach failed for '+ f'{selection.integration_key.integration_name}: {e}'+ )+ outcomes.append( ExternalReferenceAttachOutcome(+ success = False,+ error_message = (+ f'{label} could not attach '+ f'{selection.title!r} -- see server logs.'+ ),+ ) )+ return ExternalReferenceAttachBatchOutcome( outcomes = outcomes )++ def _attach_one(+ self, client, manager, owner,+ selection : ExternalReferenceResult,+ ) -> None:+ """Per-selection attach: fetch a thumbnail via the defensive+ chain (upstream -> HI-generated from original -> none) then+ upsert via the framework manager. Subclasses supply the+ two thumbnail-fetch hooks; both may return None and the row+ is created either way."""+ integration_name = selection.integration_key.integration_name+ mime_type = selection.mime_type or ''+ thumbnail_bytes = self._try_upstream_thumbnail(+ client, integration_name,+ )+ if thumbnail_bytes is None:+ thumbnail_bytes = self._try_generate_from_original(+ client, integration_name, mime_type,+ )+ manager.create_or_update(+ owner = owner,+ integration_key = selection.integration_key,+ title = selection.title,+ source_url = selection.source_url,+ mime_type = mime_type,+ thumbnail_bytes = thumbnail_bytes,+ )++ def build_client(self):+ """Build and return the integration's upstream client. The+ usual subclass binding is ``build_client =+ staticmethod(module_build_client)`` -- the module-level+ client factory IS the interface implementation, no wrapper+ method needed.++ May raise ``IntegrationAttributeError`` for configuration+ problems (becomes an "integration is not configured"+ all-failure batch); any other exception becomes a generic+ "integration error -- see server logs" all-failure batch."""+ raise NotImplementedError('Subclasses must override this method')++ def _try_upstream_thumbnail(+ self, client, integration_name : str,+ ) -> Optional[bytes]:+ """Return upstream thumbnail bytes for ``integration_name``,+ or None when none can be fetched. Must not raise."""+ raise NotImplementedError('Subclasses must override this method')++ def _try_generate_from_original(+ self, client, integration_name : str, mime_type : str,+ ) -> Optional[bytes]:+ """Return HI-generator thumbnail bytes from upstream+ original-bytes, or None when the integration can't / won't+ produce one for this mime type. Must not raise."""+ raise NotImplementedError('Subclasses must override this method')++ @staticmethod+ def _all_failure_batch(+ selections : List[ExternalReferenceResult],+ error_message : str,+ ) -> ExternalReferenceAttachBatchOutcome:+ return ExternalReferenceAttachBatchOutcome(+ outcomes = [+ ExternalReferenceAttachOutcome(+ success = False, error_message = error_message,+ )+ for _ in selections+ ],+ )++ @property+ def logger(self) -> logging.Logger:+ # Resolve at call time so log lines surface under the+ # subclass's module (e.g. ``hi.services.paperless...``), not+ # this base module. Operators grepping by integration get+ # the per-module hits they expect.+ return logging.getLogger( self.__class__.__module__ )++ @staticmethod+ def _manager_for_owner(owner):+ """Resolve the framework external-reference manager for the+ given owner type. Imported lazily to avoid pulling the+ Entity / Location models into framework module-load order+ prematurely."""+ from hi.apps.entity.models import Entity+ from hi.integrations.models import (+ EntityExternalReference,+ LocationExternalReference,+ )+ if isinstance(owner, Entity):+ return EntityExternalReference.objects+ return LocationExternalReference.objects+def get_attribute_actions_template_name(self) -> Optional[str]:"""Per-capability template fragment to render in the- integration attribute form's action bar. ATTRIBUTE_REFERENCE+ integration attribute form's action bar. EXTERNAL_REFERENCEcontributes the enabled/disabled status badge plus theDisable button. Individual integrations can override tosubstitute their own fragment."""diff --git a/src/hi/integrations/referencer/transient_models.py b/src/hi/integrations/referencer/transient_models.pyindex 1a9522bd..dbe430c2 100644--- a/src/hi/integrations/referencer/transient_models.py+++ b/src/hi/integrations/referencer/transient_models.py@@ -1,39 +1,46 @@"""-Transient (non-persisted) models for the ATTRIBUTE_REFERENCE+Transient (non-persisted) models for the EXTERNAL_REFERENCEcapability.-``AttributeReferenceResult`` is the picker-only view of an upstream+``ExternalReferenceResult`` is the picker-only view of an upstreamdocument or other linkable resource: shown in the search modal,selected by the operator, and discarded once the resulting``EntityAttribute`` / ``LocationAttribute`` row is created. Only``title`` and ``source_url`` survive into persistent storage; theremaining fields exist solely for picker UX.-``AttributeReferenceSearchResult`` is the wrapper returned by-``IntegrationAttributeReferencer.search_references``. It carries the+``ExternalReferenceSearchResult`` is the wrapper returned by+``IntegrationExternalReferencer.search_references``. It carries theresult list plus an optional ``error_message`` so the picker candistinguish a legitimately-empty search from an upstream failure(auth rejected, unreachable, etc.) and surface a banner instead ofthe "No results." string.Wire-format strings (form field names, JSON record keys) shared-between the picker views, templates, and ``attr-picker.js`` live in+between the picker views, templates, and ``external-reference-picker.js`` live in``hi.constants.DIVID`` (mirrored in ``static/js/main.js``). See the-``ATTR_PICKER_*`` entries there.+``REF_PICKER_*`` entries there."""from dataclasses import dataclass, fieldfrom typing import List, Optional+from hi.integrations.transient_models import IntegrationKey+@dataclass(frozen=True)-class AttributeReferenceResult:- """One row in the picker's result list.+class ExternalReferenceResult:+ """One upstream item, carried from search through attach.- ``title`` and ``source_url`` are the only fields that survive- the attach step -- they become the attribute's ``name`` and- ``value`` respectively. Everything else is picker chrome.+ Surfaces in the picker's result list (rendered as a card with+ ``thumbnail_url`` + ``title`` + ``snippet`` + clickable+ ``source_url``); operator selection turns it into the input to+ the integration's ``attach_references``, which persists a row+ using ``integration_key``, ``title``, ``source_url``, and+ ``mime_type``. ``thumbnail_url`` and ``snippet`` are picker+ chrome and unused at attach time."""+ integration_key: IntegrationKeytitle: strsource_url: strthumbnail_url: Optional[str] = None@@ -42,9 +49,54 @@ class AttributeReferenceResult:@dataclass(frozen=True)-class AttributeReferenceSearchResult:+class ExternalReferenceSearchResult:"""``error_message`` is None on success, including the legitimateempty-results case. A non-None value signals upstream failureeven when ``results`` is empty."""- results: List[AttributeReferenceResult] = field(default_factory=list)+ results: List[ExternalReferenceResult] = field(default_factory=list)+ error_message: Optional[str] = None+++@dataclass(frozen=True)+class ExternalReferenceAttachOutcome:+ """One operator-selection's attach outcome.++ ``success=False`` means the row did not persist; the operator's+ intent for this selection was not fulfilled. ``error_message``+ explains why. Identity fields (integration_key, title) aren't+ carried -- the error modal shows aggregate counts and per-failure+ messages only, not per-item identification.+ """+ success: boolerror_message: Optional[str] = None+++@dataclass(frozen=True)+class ExternalReferenceAttachBatchOutcome:+ """Composite result of one attach submission: every selection+ contributes exactly one outcome, regardless of which integration+ processed it. Returned from ``attach_references`` for a single+ integration, and from the dispatcher's merged result across all+ integrations in one operator submission."""+ outcomes: List[ExternalReferenceAttachOutcome] = field(default_factory=list)++ @property+ def total(self) -> int:+ return len(self.outcomes)++ @property+ def success_count(self) -> int:+ return sum(1 for o in self.outcomes if o.success)++ @property+ def failure_count(self) -> int:+ return self.total - self.success_count++ @property+ def has_failures(self) -> bool:+ return self.failure_count > 0++ @property+ def error_messages(self) -> List[str]:+ return [o.error_message for o in self.outcomes+ if not o.success and o.error_message]diff --git a/src/hi/integrations/referencer/urls.py b/src/hi/integrations/referencer/urls.pyindex c02313ed..a732e32a 100644--- a/src/hi/integrations/referencer/urls.py+++ b/src/hi/integrations/referencer/urls.py@@ -5,16 +5,16 @@ from . import viewsurlpatterns = [path( 'picker/',- views.AttributeReferencePickerView.as_view(),- name='integrations_attribute_reference_picker' ),+ views.ExternalReferencePickerView.as_view(),+ name='integrations_external_reference_picker' ),path( 'picker/search/',- views.AttributeReferenceSearchView.as_view(),- name='integrations_attribute_reference_search' ),+ views.ExternalReferenceSearchView.as_view(),+ name='integrations_external_reference_search' ),path( 'picker/attach/',- views.AttributeReferenceAttachView.as_view(),- name='integrations_attribute_reference_attach' ),+ views.ExternalReferenceAttachView.as_view(),+ name='integrations_external_reference_attach' ),path( 'home/',views.ReferenceHomeView.as_view(),diff --git a/src/hi/integrations/referencer/view_mixins.py b/src/hi/integrations/referencer/view_mixins.pynew file mode 100644index 00000000..b711e085--- /dev/null+++ b/src/hi/integrations/referencer/view_mixins.py@@ -0,0 +1,132 @@+"""View mixins for the EXTERNAL_REFERENCE capability.++Helpers specific to the capability live here so view files are all+view classes and no orphan module-level utilities. Shared across+the picker / search / attach views and available to any future+external-reference view.+"""++import logging+from typing import List, Tuple++from django.core.exceptions import BadRequest+from django.http import Http404++from hi.apps.entity.models import Entity+from hi.apps.location.models import Location+from hi.constants import DIVID+from hi.enums import ItemType++from hi.integrations.integration_data import IntegrationData++from .integration_referencer import IntegrationExternalReferencer+from .transient_models import ExternalReferenceSearchResult+++logger = logging.getLogger(__name__)+++class ExternalReferenceViewMixin:+ """Shared helpers for EXTERNAL_REFERENCE views: integration+ resolution from form-posted ids, raw-form owner resolution, and+ upstream search with a labeled fallback banner. The supported+ owner ItemTypes are the two external-references can attach to+ (entities and locations)."""++ PAGE_SIZE_CHOICES = (20, 50, 100)+ DEFAULT_LIMIT = 20++ OWNER_MODELS = {+ ItemType.ENTITY: Entity,+ ItemType.LOCATION: Location,+ }++ def resolve_integration_data(+ self,+ integration_data_list : List[IntegrationData],+ integration_id : str,+ ) -> IntegrationData:+ """Map the form's posted integration_id to one of the+ currently-enabled referencer integrations. Rejects unknown+ or now-disabled ids so a stale modal can't drive an action+ against an integration the operator has turned off."""+ if not integration_id:+ raise BadRequest(+ f'Missing {DIVID["REF_PICKER_INTEGRATION_ID_FIELD"]}.',+ )+ for candidate in integration_data_list:+ if candidate.integration_id == integration_id:+ return candidate+ raise BadRequest(+ f'Unknown {DIVID["REF_PICKER_INTEGRATION_ID_FIELD"]}: '+ f'{integration_id!r}',+ )++ def resolve_owner_from_form(+ self,+ raw_item_type : str,+ raw_item_id : str,+ ) -> Tuple[ItemType, object]:+ """Parse the picker form's item_type + item_id and fetch+ the owner row. Returns ``(item_type, owner)``; raises+ BadRequest for unparseable / out-of-domain inputs and+ Http404 when the row doesn't exist."""+ try:+ item_type = ItemType.from_name( raw_item_type )+ except ValueError:+ raise BadRequest(+ f'Unsupported {DIVID["REF_PICKER_ITEM_TYPE_FIELD"]}: '+ f'{raw_item_type!r}',+ )+ if item_type not in self.OWNER_MODELS:+ raise BadRequest(+ f'Unsupported {DIVID["REF_PICKER_ITEM_TYPE_FIELD"]}: '+ f'{raw_item_type!r}',+ )+ try:+ item_id = int( raw_item_id )+ except (TypeError, ValueError):+ raise BadRequest(+ f'Invalid {DIVID["REF_PICKER_ITEM_ID_FIELD"]}.',+ )+ owner_model = self.OWNER_MODELS[ item_type ]+ try:+ owner = owner_model.objects.get( id = item_id )+ except owner_model.DoesNotExist:+ raise Http404( f'{item_type.label} not found.' )+ return item_type, owner++ def search_upstream(+ self,+ referencer : IntegrationExternalReferencer,+ query : str,+ limit : int,+ ) -> ExternalReferenceSearchResult:+ if not query:+ return ExternalReferenceSearchResult( results = [] )+ try:+ return referencer.search_references( query = query, limit = limit )+ except Exception:+ # The contract asks referencers to populate+ # ``error_message`` instead of raising, so reaching this+ # branch means the referencer itself is broken. Surface+ # a labeled message so operators with multiple+ # referencers know which one to look at; the stack lands+ # in the server log.+ logger.exception( 'Attribute-reference search failed.' )+ label = self._safe_label( referencer )+ return ExternalReferenceSearchResult(+ results = [],+ error_message = f'{label} search failed — see server logs.',+ )++ def _safe_label(+ self, referencer : IntegrationExternalReferencer,+ ) -> str:+ # Defensive: a referencer broken enough to raise from search+ # may also raise from get_metadata. Fall back to a generic+ # label so the banner never compounds the failure.+ try:+ return referencer.get_metadata().label+ except Exception:+ return 'Integration'diff --git a/src/hi/integrations/referencer/views.py b/src/hi/integrations/referencer/views.pyindex 0aefd8e6..144b23ca 100644--- a/src/hi/integrations/referencer/views.py+++ b/src/hi/integrations/referencer/views.py@@ -1,41 +1,32 @@"""-ATTRIBUTE_REFERENCE picker -- one HiModal view backed by antinode+EXTERNAL_REFERENCE picker -- one HiModal view backed by antinodepartial swaps.Workflow:- GET ``/integrations/referencer/picker/`` with ``item_type`` +``item_id`` query params renders the full picker modal. The- view discovers all currently-enabled ATTRIBUTE_REFERENCE+ view discovers all currently-enabled EXTERNAL_REFERENCEintegrations and lets the operator choose between them via anin-modal selector when more than one is configured.- - POST to the same URL re-renders the picker body. The form- carries ``integration_id`` as a hidden field so the view knows- which referencer to drive the search against. The form's- ``data-async="#picker-body-<uuid>"`` + ``data-stay-in-modal``- keeps the modal open while the body partial swaps in.-- - When the operator submits with ``action=attach``, the view- creates one TEXT attribute per current selection on the host- Entity / Location and returns ``antinode.refresh_response()`` to- reload the parent page (modal closes via page reload).--Multi-select state is server-driven via three form fields:-``selections_json`` (canonical existing list, hidden), ``visible_url``-(hidden per result; identifies what was rendered), and ``result_url``-(checkbox value per result; only submitted when checked). The view-computes the new selection list each POST: existing + newly checked-- unchecked visibles +/- an explicit ``remove_url`` if the operator-clicked a chip's remove button.+ - POST to ``/integrations/referencer/picker/search/`` re-renders+ the result-cards partial. The form carries ``integration_id``+ as a hidden field so the view knows which referencer to drive+ the search against. The picker JS swaps the partial into the+ modal's results container.++ - POST to ``/integrations/referencer/picker/attach/`` commits the+ operator's selection set. The picker resets selections on+ source-switch, so one submission carries items from one+ integration only; the form-level ``integration_id`` is the+ single source of truth for routing."""import jsonimport logging-from typing import Dict, List+from typing import List-from django.core.exceptions import BadRequest-from django.db import transactionfrom django.http import Http404, HttpResponsefrom django.template.loader import render_to_stringfrom django.urls import reverse@@ -43,15 +34,12 @@ from django.views.generic import Viewfrom hi.apps.attribute.edit_form_handler import AttributeEditFormHandlerfrom hi.apps.attribute.edit_response_renderer import AttributeEditResponseRenderer-from hi.apps.attribute.enums import AttributeType, AttributeValueTypefrom hi.apps.attribute.view_mixins import AttributeEditViewMixinfrom hi.apps.common import antinodefrom hi.apps.config.enums import ConfigPageTypefrom hi.apps.config.views import ConfigPageView-from hi.apps.entity.models import Entity, EntityAttribute-from hi.apps.location.models import Location, LocationAttributefrom hi.constants import DIVID-from hi.enums import ItemType+from hi.enums import ItemType, ViewDataPriorityfrom hi.exceptions import ForceRedirectExceptionfrom hi.hi_async_view import HiModalView@@ -60,280 +48,139 @@ from hi.integrations.integration_attribute_edit_context import (IntegrationAttributeItemEditContext,)from hi.integrations.integration_data import IntegrationData-from hi.integrations.integration_manager import IntegrationManager+from hi.integrations.transient_models import IntegrationKeyfrom hi.integrations.view_mixins import IntegrationViewMixin-from .integration_referencer import IntegrationAttributeReferencer-from .transient_models import AttributeReferenceSearchResult+from .transient_models import (+ ExternalReferenceAttachBatchOutcome,+ ExternalReferenceAttachOutcome,+ ExternalReferenceResult,+ ExternalReferenceSearchResult,+)+from .view_mixins import ExternalReferenceViewMixinlogger = logging.getLogger(__name__)-_PAGE_SIZE_CHOICES = (20, 50, 100)-_DEFAULT_LIMIT = 20-_MAX_LIMIT = 100--# ItemType -> (owner model, attribute model, owner FK field name).-_ATTRIBUTE_OWNER_MODELS = {- ItemType.ENTITY: (Entity, EntityAttribute, 'entity'),- ItemType.LOCATION: (Location, LocationAttribute, 'location'),-}---def _get_referencer_integration_data_list() -> List[ IntegrationData ]:- """All currently-enabled integrations that advertise the- ATTRIBUTE_REFERENCE capability. Returned in label order- (the manager already sorts by label)."""- return IntegrationManager().get_integration_data_list(- enabled_only=True,- capabilities=frozenset({ IntegrationCapability.ATTRIBUTE_REFERENCE }),- )---def _resolve_integration_data(- integration_data_list: List[ IntegrationData ],- integration_id: str,-) -> IntegrationData:- """Map the form's posted integration_id to one of the- currently-enabled referencer integrations. Rejects unknown- or now-disabled ids so a stale modal can't drive a search- against an integration the operator has turned off."""- if not integration_id:- raise BadRequest(- f'Missing {DIVID["ATTR_PICKER_INTEGRATION_ID_FIELD"]}.',- )- for candidate in integration_data_list:- if candidate.integration_id == integration_id:- return candidate- raise BadRequest(- f'Unknown {DIVID["ATTR_PICKER_INTEGRATION_ID_FIELD"]}: '- f'{integration_id!r}',- )---def _require_referencer(- integration_data: IntegrationData,- request,-) -> IntegrationAttributeReferencer:- referencer = integration_data.integration_gateway.get_attribute_referencer()- if referencer is None:- raise Http404( request )- return referencer---def _parse_item_type(raw_value: str) -> ItemType:- try:- item_type = ItemType.from_name( raw_value )- except ValueError:- raise BadRequest(- f'Unsupported {DIVID["ATTR_PICKER_ITEM_TYPE_FIELD"]}: {raw_value!r}',- )- if item_type not in _ATTRIBUTE_OWNER_MODELS:- raise BadRequest(- f'Unsupported {DIVID["ATTR_PICKER_ITEM_TYPE_FIELD"]}: {raw_value!r}',- )- return item_type---def _parse_item_id(raw_value) -> int:- try:- return int( raw_value )- except (TypeError, ValueError):- raise BadRequest(- f'Invalid {DIVID["ATTR_PICKER_ITEM_ID_FIELD"]}.',- )---def _parse_limit(raw_limit) -> int:- try:- limit = int( raw_limit )- except (TypeError, ValueError):- return _DEFAULT_LIMIT- if limit not in _PAGE_SIZE_CHOICES:- return _DEFAULT_LIMIT- return min( limit, _MAX_LIMIT )---def _resolve_owner(item_type: ItemType, item_id: int):- owner_model, _attribute_model, _owner_field = _ATTRIBUTE_OWNER_MODELS[ item_type ]- try:- return owner_model.objects.get( id=item_id )- except owner_model.DoesNotExist:- raise Http404( f'{item_type.label} not found.' )---def _search_upstream(- referencer: IntegrationAttributeReferencer,- query: str,- limit: int,-) -> AttributeReferenceSearchResult:- if not query:- return AttributeReferenceSearchResult( results = [] )- try:- return referencer.search_references( query = query, limit = limit )- except Exception:- # The contract asks referencers to populate ``error_message``- # instead of raising, so reaching this branch means the- # referencer itself is broken. Surface a labeled message so- # operators with multiple referencers know which one to look- # at; the stack lands in the server log.- logger.exception( 'Attribute-reference search failed.' )- label = _safe_label( referencer )- return AttributeReferenceSearchResult(- results = [],- error_message = f'{label} search failed — see server logs.',- )+_REFERENCER_CAPABILITIES = frozenset({ IntegrationCapability.EXTERNAL_REFERENCE })-def _safe_label( referencer: IntegrationAttributeReferencer ) -> str:- # Defensive: a referencer broken enough to raise from search may- # also raise from get_metadata. Fall back to a generic label so- # the banner never compounds the failure.- try:- return referencer.get_metadata().label- except Exception:- return 'Integration'---def _parse_selections_json(raw: str) -> List[ Dict[str, str] ]:- """Parse the JS-built ``selections_json`` payload submitted on- attach. Skips records with missing title or source_url and- falls back to an empty list on any decode error."""- if not raw:- return []- try:- decoded = json.loads( raw )- except json.JSONDecodeError:- return []- if not isinstance( decoded, list ):- return []- parsed: List[ Dict[str, str] ] = []- for item in decoded:- if not isinstance( item, dict ):- continue- title = ( item.get( DIVID['ATTR_PICKER_SELECTION_TITLE_KEY'] ) or '' ).strip()- url = ( item.get( DIVID['ATTR_PICKER_SELECTION_URL_KEY'] ) or '' ).strip()- if not title or not url:- continue- parsed.append( {- DIVID['ATTR_PICKER_SELECTION_TITLE_KEY']: title,- DIVID['ATTR_PICKER_SELECTION_URL_KEY']: url,- } )- return parsed---def _create_attributes(- item_type: ItemType,- owner,- selections: List[ Dict[str, str] ],-) -> List[ int ]:- if not selections:- return []- _owner_model, attribute_model, owner_field = _ATTRIBUTE_OWNER_MODELS[ item_type ]- created_ids: List[ int ] = []- with transaction.atomic():- for selection in selections:- attr = attribute_model.objects.create( **{- owner_field: owner,- 'name': selection[ DIVID['ATTR_PICKER_SELECTION_TITLE_KEY'] ][:64],- 'value': selection[ DIVID['ATTR_PICKER_SELECTION_URL_KEY'] ],- 'value_type_str': str( AttributeValueType.TEXT ),- 'attribute_type_str': str( AttributeType.CUSTOM ),- 'is_editable': True,- 'is_required': False,- } )- created_ids.append( attr.id )- return created_ids---class AttributeReferencePickerView( HiModalView ):+class ExternalReferencePickerView(+ HiModalView, IntegrationViewMixin, ExternalReferenceViewMixin ):"""GET the picker modal. Initial render seeds the result listby searching on the owner's name; selection state then lives inJS. Subsequent search results arrive via async POST to- ``integrations_attribute_reference_search``, and the final- commit posts to ``integrations_attribute_reference_attach``."""+ ``integrations_external_reference_search``, and the final+ commit posts to ``integrations_external_reference_attach``."""- MODAL_TEMPLATE_NAME = 'integrations/referencer/modals/attr_picker.html'+ MODAL_TEMPLATE_NAME = 'integrations/referencer/modals/external_reference_picker.html'def get_template_name(self) -> str:return self.MODAL_TEMPLATE_NAMEdef get(self, request, *args, **kwargs):- integration_data_list = _get_referencer_integration_data_list()+ integration_data_list = self.get_integration_data_list(+ enabled_only = True,+ capabilities = _REFERENCER_CAPABILITIES,+ )if not integration_data_list:raise Http404( request )- item_type = _parse_item_type(- request.GET.get( DIVID['ATTR_PICKER_ITEM_TYPE_FIELD'] ),- )- item_id = _parse_item_id(- request.GET.get( DIVID['ATTR_PICKER_ITEM_ID_FIELD'] ),+ item_type, owner = self.resolve_owner_from_form(+ raw_item_type = request.GET.get( DIVID['REF_PICKER_ITEM_TYPE_FIELD'] ),+ raw_item_id = request.GET.get( DIVID['REF_PICKER_ITEM_ID_FIELD'] ),)- owner = _resolve_owner( item_type=item_type, item_id=item_id )- # Default to the first configured referencer. The operator- # can switch via the picker's integration <select> when more- # than one referencer is configured.- integration_data = integration_data_list[0]+ # Default to the operator's last successfully-used referencer+ # if it's still enabled; otherwise fall back to the first+ # configured one. The session-stored id is set by the attach+ # view on successful link, so the picker re-opens to the+ # source most likely to match what they're working on. The+ # operator can still switch via the picker's integration+ # <select> when more than one referencer is configured.+ integration_data = self._default_integration_data(+ integration_data_list = integration_data_list,+ request = request,+ )# Seed the picker with a query based on the owner's name so# the operator opens to relevant results without retyping# what they're already configuring.query = owner.name- referencer = integration_data.integration_gateway.get_attribute_referencer()+ referencer = integration_data.integration_gateway.get_external_referencer()if referencer is not None:- search_result = _search_upstream(+ search_result = self.search_upstream(referencer = referencer,query = query,- limit = _DEFAULT_LIMIT,+ limit = self.DEFAULT_LIMIT,)else:- search_result = AttributeReferenceSearchResult( results = [] )+ search_result = ExternalReferenceSearchResult( results = [] )context = {'integration_data_list': integration_data_list,'integration_data': integration_data,- 'item_type_value': str( item_type ),+ 'item_type': item_type,'item_id': owner.id,- 'limit': _DEFAULT_LIMIT,- 'page_size_choices': _PAGE_SIZE_CHOICES,+ 'limit': self.DEFAULT_LIMIT,+ 'page_size_choices': self.PAGE_SIZE_CHOICES,'query': query,'results': search_result.results,'error_message': search_result.error_message,}- return self.modal_response( request, context=context )-+ return self.modal_response( request, context = context )-class AttributeReferenceSearchView( View ):+ @staticmethod+ def _default_integration_data( integration_data_list, request ):+ """Pick the initial source for the picker dropdown. Honors+ the session-stored last-successful integration when it's+ still in the enabled list; otherwise falls back to the first+ entry."""+ saved_id = request.view_parameters.ref_picker_integration_id+ if saved_id:+ for candidate in integration_data_list:+ if candidate.integration_id == saved_id:+ return candidate+ return integration_data_list[0]+++class ExternalReferenceSearchView(+ View, IntegrationViewMixin, ExternalReferenceViewMixin ):"""POST endpoint that runs an upstream search and returns only- the result-cards HTML partial. The attr-picker JS swaps the+ the result-cards HTML partial. The external-reference-picker JS swaps thereturned markup into the picker's results container, thenre-applies checkbox state from its in-memory selection set.Empty / whitespace queries short-circuit to an empty resultpartial (no upstream call)."""- RESULTS_TEMPLATE_NAME = 'integrations/referencer/panes/attr_picker_results.html'+ RESULTS_TEMPLATE_NAME = 'integrations/referencer/panes/external_reference_picker_results.html'+ MAX_LIMIT = 100def post(self, request, *args, **kwargs):- integration_data_list = _get_referencer_integration_data_list()+ integration_data_list = self.get_integration_data_list(+ enabled_only = True,+ capabilities = _REFERENCER_CAPABILITIES,+ )if not integration_data_list:raise Http404( request )- integration_data = _resolve_integration_data(- integration_data_list=integration_data_list,- integration_id=request.POST.get(- DIVID['ATTR_PICKER_INTEGRATION_ID_FIELD'],+ integration_data = self.resolve_integration_data(+ integration_data_list = integration_data_list,+ integration_id = request.POST.get(+ DIVID['REF_PICKER_INTEGRATION_ID_FIELD'],),)- referencer = _require_referencer( integration_data, request )+ referencer = integration_data.integration_gateway.get_external_referencer()+ if referencer is None:+ raise Http404( request )query = (- request.POST.get( DIVID['ATTR_PICKER_QUERY_FIELD'] ) or ''+ request.POST.get( DIVID['REF_PICKER_QUERY_FIELD'] ) or '').strip()- limit = _parse_limit(- request.POST.get( DIVID['ATTR_PICKER_LIMIT_FIELD'] ),+ limit = self._parse_limit(+ request.POST.get( DIVID['REF_PICKER_LIMIT_FIELD'] ),)- search_result = _search_upstream(+ search_result = self.search_upstream(referencer = referencer, query = query, limit = limit,)html = render_to_string(@@ -347,31 +194,225 @@ class AttributeReferenceSearchView( View ):)return HttpResponse( html )+ def _parse_limit(self, raw_limit) -> int:+ try:+ limit = int( raw_limit )+ except (TypeError, ValueError):+ return self.DEFAULT_LIMIT+ if limit not in self.PAGE_SIZE_CHOICES:+ return self.DEFAULT_LIMIT+ return min( limit, self.MAX_LIMIT )+++class ExternalReferenceAttachView(+ View, IntegrationViewMixin, ExternalReferenceViewMixin ):+ """POST endpoint that dispatches the operator's selected+ references to the source integration for attach. The picker+ resets selection state on source-switch, so one submission+ always carries items from one integration; the form-level+ ``integration_id`` hidden field is the single source of truth+ for routing.++ Response branches on whether any selection failed:+ * all-success -- delegate to the owner's edit view's GET so+ the operator sees the edit modal with the+ new cards already in the grid.+ * any-failure -- render the error modal with the per-failure+ messages plus LINK MORE / DISMISS actions.+ Modals swap one-at-a-time via the antinode+ ``modal`` response key.+ """-class AttributeReferenceAttachView( View ):- """POST endpoint that creates TEXT attributes for the operator's- selected references. The JS module serializes its in-memory- selection set into ``selections_json`` just before the form- submits.-- Returns ``antinode.refresh_response()`` so the parent page- reloads and the modal closes naturally."""+ ERRORS_MODAL_TEMPLATE_NAME = (+ 'integrations/modals/external_reference_attach_errors.html'+ )def post(self, request, *args, **kwargs):- item_type = _parse_item_type(- request.POST.get( DIVID['ATTR_PICKER_ITEM_TYPE_FIELD'] ),+ integration_data_list = self.get_integration_data_list(+ enabled_only = True,+ capabilities = _REFERENCER_CAPABILITIES,)- item_id = _parse_item_id(- request.POST.get( DIVID['ATTR_PICKER_ITEM_ID_FIELD'] ),+ if not integration_data_list:+ raise Http404( request )+ integration_data = self.resolve_integration_data(+ integration_data_list = integration_data_list,+ integration_id = request.POST.get(+ DIVID['REF_PICKER_INTEGRATION_ID_FIELD'],+ ),)- owner = _resolve_owner( item_type=item_type, item_id=item_id )- selections = _parse_selections_json(- request.POST.get( DIVID['ATTR_PICKER_SELECTIONS_JSON_FIELD'] ) or '',+ item_type, owner = self.resolve_owner_from_form(+ raw_item_type = request.POST.get( DIVID['REF_PICKER_ITEM_TYPE_FIELD'] ),+ raw_item_id = request.POST.get( DIVID['REF_PICKER_ITEM_ID_FIELD'] ),)- _create_attributes(- item_type=item_type, owner=owner, selections=selections,+ selections = self._parse_selections_json(+ raw = request.POST.get(+ DIVID['REF_PICKER_SELECTIONS_JSON_FIELD'],+ ) or '',+ integration_id = integration_data.integration_id,)- return antinode.refresh_response()+ batch = self._dispatch_attach(+ owner = owner,+ integration_data = integration_data,+ selections = selections,+ )+ # Remember the chosen referencer on any successful link so+ # the next picker open defaults to the same source. Partial-+ # failure batches still count -- the operator picked this+ # integration and at least some items attached.+ if batch.success_count > 0:+ request.view_parameters.ref_picker_integration_id = (+ integration_data.integration_id+ )+ request.view_parameters.to_session( request )+ if batch.has_failures:+ return self._render_errors_modal(+ request, item_type, owner, batch,+ )+ return self._render_owner_edit_modal( request, item_type, owner )++ def _parse_selections_json(+ self,+ raw : str,+ integration_id : str,+ ) -> List[ExternalReferenceResult]:+ """Parse the JS-built ``selections_json`` payload into+ ``ExternalReferenceResult`` instances. All selections in+ one submission share the same ``integration_id`` (taken+ from the form-level hidden field) because the picker+ resets its selection state on source-switch; the per-record+ JSON carries only the upstream identifier. Skips records+ with missing title / source_url / integration_name and+ falls back to an empty list on any decode error."""+ if not raw:+ return []+ try:+ decoded = json.loads( raw )+ except json.JSONDecodeError:+ return []+ if not isinstance( decoded, list ):+ return []+ parsed: List[ExternalReferenceResult] = []+ for item in decoded:+ if not isinstance( item, dict ):+ continue+ title = ( item.get(+ DIVID['REF_PICKER_SELECTION_TITLE_KEY']+ ) or '' ).strip()+ url = ( item.get(+ DIVID['REF_PICKER_SELECTION_URL_KEY']+ ) or '' ).strip()+ integration_name = ( item.get(+ DIVID['REF_PICKER_SELECTION_INTEGRATION_NAME_KEY']+ ) or '' ).strip()+ mime_type = ( item.get(+ DIVID['REF_PICKER_SELECTION_MIME_TYPE_KEY']+ ) or '' ).strip()+ if not title or not url or not integration_name:+ continue+ parsed.append( ExternalReferenceResult(+ integration_key = IntegrationKey(+ integration_id = integration_id,+ integration_name = integration_name,+ ),+ title = title,+ source_url = url,+ mime_type = mime_type or None,+ ) )+ return parsed++ def _dispatch_attach(+ self,+ owner,+ integration_data : IntegrationData,+ selections : List[ExternalReferenceResult],+ ) -> ExternalReferenceAttachBatchOutcome:+ """Call the integration's ``attach_references`` for all+ selections in one submission. The picker resets selection+ state on source-switch (see ``external-reference-picker.js``), so one+ submission always carries items from a single integration+ -- no grouping needed.++ Returns the integration's+ ``ExternalReferenceAttachBatchOutcome`` directly, or a+ synthesized all-failure batch when the integration has no+ enabled referencer (every input selection still contributes+ exactly one outcome)."""+ if not selections:+ return ExternalReferenceAttachBatchOutcome()+ referencer = integration_data.integration_gateway.get_external_referencer()+ if referencer is None:+ logger.warning(+ f'External reference attach skipped {len(selections)} '+ f'selections: integration '+ f'{integration_data.integration_id!r} has no enabled '+ f'referencer.'+ )+ return ExternalReferenceAttachBatchOutcome(+ outcomes = [+ ExternalReferenceAttachOutcome(+ success = False,+ error_message = (+ f'Integration '+ f'{integration_data.integration_id!r} '+ f'is not available.'+ ),+ )+ for _ in selections+ ],+ )+ return referencer.attach_references( owner, selections )++ @staticmethod+ def _render_owner_edit_modal(request, item_type : ItemType, owner):+ """Delegate to the owner's existing edit view so we don't+ duplicate its context-building logic. CBVs are designed to+ be called this way once you have the request in hand. The+ ``data_priority`` override lands the operator on Tab 3+ (Linked Content) so the just-attached references are+ immediately visible regardless of what the data-derived+ default would have picked."""+ from hi.apps.entity.views import EntityEditView+ from hi.apps.location.views import LocationEditView+ priority_kwarg = ViewDataPriority.REFERENCE.name+ if item_type.is_entity:+ return EntityEditView().get(+ request, entity_id = owner.id,+ data_priority = priority_kwarg,+ )+ return LocationEditView().get(+ request, location_id = owner.id,+ data_priority = priority_kwarg,+ )++ def _render_errors_modal(+ self, request, item_type : ItemType, owner, batch,+ ):+ picker_url = (+ reverse( 'integrations_external_reference_picker' )+ + f'?{DIVID["REF_PICKER_ITEM_TYPE_FIELD"]}={item_type}'+ + f'&{DIVID["REF_PICKER_ITEM_ID_FIELD"]}={owner.id}'+ )+ if item_type.is_entity:+ owner_edit_url = reverse(+ 'entity_edit', kwargs = { 'entity_id': owner.id },+ )+ else:+ owner_edit_url = reverse(+ 'location_edit_location_edit',+ kwargs = { 'location_id': owner.id },+ )+ modal_html = render_to_string(+ self.ERRORS_MODAL_TEMPLATE_NAME,+ {+ 'batch' : batch,+ 'item_type' : item_type,+ 'item_id' : owner.id,+ 'picker_url' : picker_url,+ 'owner_edit_url' : owner_edit_url,+ },+ request = request,+ )+ return antinode.response( modal_content = modal_html )# The operator-facing tab label is "Content Sources"; code-side@@ -381,7 +422,7 @@ class AttributeReferenceAttachView( View ):class ReferenceHomeView( ConfigPageView, IntegrationViewMixin ):"""Landing route for the reference-management page. Picks the- first ATTRIBUTE_REFERENCE integration (enabled or not) and+ first EXTERNAL_REFERENCE integration (enabled or not) andredirects to its manage URL. Returns the empty-state templatewhen none are discovered."""@@ -392,8 +433,8 @@ class ReferenceHomeView( ConfigPageView, IntegrationViewMixin ):return 'integrations/referencer/pages/no_integrations.html'def get_main_template_context( self, request, *args, **kwargs ):- integration_data_list = IntegrationManager().get_integration_data_list(- capabilities = frozenset({ IntegrationCapability.ATTRIBUTE_REFERENCE }),+ integration_data_list = self.get_integration_data_list(+ capabilities = _REFERENCER_CAPABILITIES,)if not integration_data_list:return dict()@@ -405,13 +446,13 @@ class ReferenceHomeView( ConfigPageView, IntegrationViewMixin ):class ReferenceManageView( ConfigPageView, IntegrationViewMixin, AttributeEditViewMixin ):- """Per-integration attribute-form page for ATTRIBUTE_REFERENCE+ """Per-integration attribute-form page for EXTERNAL_REFERENCEintegrations.- ATTRIBUTE_REFERENCE has no monitors and no sync cycle, so the+ EXTERNAL_REFERENCE has no monitors and no sync cycle, so thepage does not surface health status, sync-check state, orhas_entities. The attribute queryset is filtered to attributes- the ATTRIBUTE_REFERENCE capability declares. ``is_enabled =+ the EXTERNAL_REFERENCE capability declares. ``is_enabled =False`` integrations are tolerated so the operator can configurecredentials here before the integration is enabled."""@@ -535,8 +576,8 @@ class ReferenceManageView( ConfigPageView, IntegrationViewMixin, AttributeEditVireturndef _resolve( self, integration_id ):- integration_data_list = IntegrationManager().get_integration_data_list(- capabilities = frozenset({ IntegrationCapability.ATTRIBUTE_REFERENCE }),+ integration_data_list = self.get_integration_data_list(+ capabilities = _REFERENCER_CAPABILITIES,)if not integration_data_list:raise Http404( 'No reference integrations are installed.' )@@ -562,19 +603,17 @@ class ReferenceManageView( ConfigPageView, IntegrationViewMixin, AttributeEditVi)return IntegrationAttributeItemEditContext(integration_data = integration_data,- capability_gateway = integration_data.integration_gateway.get_attribute_referencer(),+ capability_gateway = integration_data.integration_gateway.get_external_referencer(),health_status = None,update_button_label = update_label,)@staticmethoddef _find_integration_data(- integration_data_list: List[ IntegrationData ],+ integration_data_list: List[IntegrationData],integration_id: str,) -> IntegrationData:for candidate in integration_data_list:if candidate.integration_id == integration_id:return candidatereturn None--diff --git a/src/hi/integrations/templates/integrations/external_data/entity/minimal.html b/src/hi/integrations/templates/integrations/external_data/entity/minimal.htmlindex 03508dbe..565fdd16 100644--- a/src/hi/integrations/templates/integrations/external_data/entity/minimal.html+++ b/src/hi/integrations/templates/integrations/external_data/entity/minimal.html@@ -1,7 +1,5 @@<div class="attr-v2-external-minimal">- {% include "integrations/external_data/entity/header.html" %}-{% if view_data.error_message %}<div class="alert alert-warning attr-ext-minimal-error" role="alert">{{ view_data.error_message }}diff --git a/src/hi/integrations/templates/integrations/external_data/entity/structured.html b/src/hi/integrations/templates/integrations/external_data/entity/structured.htmlindex 68ffeac1..99260979 100644--- a/src/hi/integrations/templates/integrations/external_data/entity/structured.html+++ b/src/hi/integrations/templates/integrations/external_data/entity/structured.html@@ -2,8 +2,6 @@<div class="attr-v2-external-structured">- {% include "integrations/external_data/entity/header.html" %}-{% if view_data.attachments %}<div class="attr-v2-file-section attr-ext-attachments"><div class="attr-v2-file-grid">diff --git a/src/hi/integrations/templates/integrations/modals/external_reference_attach_errors.html b/src/hi/integrations/templates/integrations/modals/external_reference_attach_errors.htmlnew file mode 100644index 00000000..373bac7c--- /dev/null+++ b/src/hi/integrations/templates/integrations/modals/external_reference_attach_errors.html@@ -0,0 +1,64 @@+{% extends "modals/action_2.html" %}+{% load icons %}+{% comment %}+Shown after the Link Content picker submits with one or more+attach failures. Modal swaps in place of the picker (one modal at+a time -- the edit modal that the picker opened from was already+removed when the picker opened).++Two action buttons, both data-async links:+ LINK MORE -- re-open the picker on the same owner. Empty search;+ no carryover of previously-selected items.+ DISMISS -- open the owner's edit modal. Successful attachments+ from the same submission are visible in the grid.+ The header 'X' close is the only path that leaves+ the screen with no modal open.++Context:+ batch : ExternalReferenceAttachBatchOutcome+ item_type : ItemType (ENTITY or LOCATION)+ item_id : owner pk+ picker_url : URL for the picker re-open (LINK MORE)+ owner_edit_url : URL for the owner's edit modal (DISMISS)+{% endcomment %}++{% block modal_dialog_class %}modal-md{% endblock %}+{% block header_class %}bg-secondary{% endblock %}++{% block title_text %}+ Some links could not be attached+{% endblock %}++{% block body %}+<p class="mb-3">+ Linked+ <strong>{{ batch.success_count }}</strong>+ of+ <strong>{{ batch.total }}</strong>+ selected item{{ batch.total|pluralize }}.+ {{ batch.failure_count }} could not be attached:+</p>+<ul class="mb-0">+ {% for message in batch.error_messages %}+ <li>{{ message }}</li>+ {% endfor %}+</ul>+{% endblock %}++{% block action_left %}+<a role="button"+ class="btn btn-outline-primary"+ href="{{ picker_url }}"+ data-async="modal">+ {% icon "link" size="sm" css_class="hi-icon-left" %}LINK MORE+</a>+{% endblock %}++{% block action_right %}+<a role="button"+ class="btn btn-outline-tertiary"+ href="{{ owner_edit_url }}"+ data-async="modal">+ {% icon "close" size="sm" css_class="hi-icon-left" %}DISMISS+</a>+{% endblock %}diff --git a/src/hi/integrations/templates/integrations/panes/external_reference_card.html b/src/hi/integrations/templates/integrations/panes/external_reference_card.htmlnew file mode 100644index 00000000..af3c4bb5--- /dev/null+++ b/src/hi/integrations/templates/integrations/panes/external_reference_card.html@@ -0,0 +1,110 @@+{% load icons integration_tags static %}+{% comment %}+External-reference card. Visually mirrors the internal file card+(same overlay reorder controls, title input, action-button row)+with two intentional differences:++ - View affordance is the integration's logo (not the eye icon),+ so source attribution doubles as the click-to-open control.+ - Delete affordance is an unlink icon (times-circle), signaling+ the row is a pointer being severed -- not HI-owned content+ being removed.++Per-card actions (rename / unlink / reorder) post to integration+framework endpoints; the cards are not part of the surrounding+attribute formset.++Context:+ reference : EntityExternalReference or LocationExternalReference+ owner_type : 'entity' or 'location'+{% endcomment %}+{% integration_logo_path reference as integration_logo %}+{% integration_display_name reference as integration_label %}++<div class="{{ DIVID.EXT_REF_CARD_CLASS }} attr-v2-file-card"+ {{ DIVID.EXT_REF_REFERENCE_ID_ATTR }}="{{ reference.id }}"+ {{ DIVID.EXT_REF_OWNER_TYPE_ATTR }}="{{ owner_type }}"+ data-order-index="{{ forloop.counter }}">++ {# ``source_url`` is upstream-supplied; passing it through a #}+ {# ``data-`` attribute and opening via a delegated JS handler #}+ {# avoids the inline-onclick escape-context pitfall where #}+ {# Django's attribute escaping decodes back into a JS string #}+ {# literal and a crafted URL can break out of the quotes. #}+ <div class="attr-v2-file-thumbnail{% if reference.thumbnail %} has-thumbnail{% endif %}"+ {{ DIVID.EXT_REF_SOURCE_URL_ATTR }}="{{ reference.source_url }}"+ title="Open on {{ integration_label|default:'external source' }}">+ {% if reference.thumbnail %}+ <img src="{{ reference.thumbnail.url }}"+ alt="Preview for {{ reference.title }}"+ class="attr-v2-file-thumbnail-image"+ loading="lazy"+ decoding="async">+ {% else %}+ {% if reference.mime_type|slice:':5' == 'image' %}+ {% icon "camera" size="lg" %}+ <div class="attr-v2-file-type-label">IMAGE</div>+ {% elif reference.mime_type == 'application/pdf' %}+ {% icon "upload" size="lg" %}+ <div class="attr-v2-file-type-label">PDF</div>+ {% elif reference.mime_type|slice:':5' == 'video' %}+ {% icon "video" size="lg" %}+ <div class="attr-v2-file-type-label">VIDEO</div>+ {% else %}+ {% icon "link" size="lg" %}+ <div class="attr-v2-file-type-label">LINK</div>+ {% endif %}+ {% endif %}+ </div>++ <div class="attr-v2-file-info">+ <input type="text"+ value="{{ reference.title }}"+ class="{{ DIVID.EXT_REF_TITLE_INPUT_CLASS }} attr-v2-file-title-input"+ placeholder="Reference title"+ maxlength="255">+ <div class="attr-v2-file-name">+ {{ integration_label|default:reference.integration_id }}+ </div>++ <div class="attr-v2-file-actions">+ {% comment %}+ Reorder buttons live in the action row -- not a thumbnail+ overlay -- so they're touch-visible without hover, off the+ image so contrast is never an issue, and use the action+ row's touch-friendly 44px minimum. ``mr-auto`` / ``ml-auto``+ pushes them to the edges; view + unlink cluster in the+ middle. Smaller icon (size="md") distinguishes them from+ the primary actions.+ {% endcomment %}+ <button type="button"+ class="btn btn-sm btn-outline-secondary mr-auto {{ DIVID.EXT_REF_REORDER_LEFT_CLASS }}"+ title="Move left">+ {% icon "chevron-left" size="md" %}+ </button>+ <a href="{{ reference.source_url }}"+ target="_blank"+ rel="noopener"+ class="btn btn-sm btn-outline-primary"+ title="Open on {{ integration_label|default:'external source' }}">+ {% if integration_logo %}+ <img src="{% static integration_logo %}"+ alt=""+ class="hi-ext-ref-integration-logo">+ {% else %}+ {% icon "eye" size="xl" %}+ {% endif %}+ </a>+ <button type="button"+ class="btn btn-sm btn-outline-danger {{ DIVID.EXT_REF_DELETE_BTN_CLASS }}"+ title="Unlink this reference">+ {% icon "unlink" size="xl" %}+ </button>+ <button type="button"+ class="btn btn-sm btn-outline-secondary ml-auto {{ DIVID.EXT_REF_REORDER_RIGHT_CLASS }}"+ title="Move right">+ {% icon "chevron-right" size="md" %}+ </button>+ </div>+ </div>+</div>diff --git a/src/hi/integrations/templates/integrations/panes/external_reference_grid.html b/src/hi/integrations/templates/integrations/panes/external_reference_grid.htmlnew file mode 100644index 00000000..071ba2e0--- /dev/null+++ b/src/hi/integrations/templates/integrations/panes/external_reference_grid.html@@ -0,0 +1,26 @@+{% comment %}+Framework-rendered grid of external-reference cards. Capability-+agnostic -- any integration's references render the same way once+they're attached. Mirrors the internal-file grid's container+structure so the two grids feel identical to operators.++Per-card action endpoints return this same template freshly+rendered; external-references.js finds the surrounding grid via+``closest()`` from the clicked card and replaces it in place, so+the surrounding modal stays open without any JS/template magic-+string id agreement.++Context:+ external_references : queryset of EntityExternalReference or+ LocationExternalReference instances.+ owner_type : 'entity' or 'location' -- drives the per-card+ action URL routing and the grid id.+ owner_id : pk of the owning Entity / Location -- pairs+ with owner_type to compose the grid id.+{% endcomment %}+<div id="hi-ext-ref-grid-{{ owner_type }}-{{ owner_id }}"+ class="{{ DIVID.EXT_REF_GRID_CLASS }} attr-v2-file-grid">+ {% for reference in external_references %}+ {% include "integrations/panes/external_reference_card.html" with reference=reference owner_type=owner_type owner_id=owner_id %}+ {% endfor %}+</div>diff --git a/src/hi/integrations/templates/integrations/referencer/modals/attr_picker.html b/src/hi/integrations/templates/integrations/referencer/modals/external_reference_picker.htmlsimilarity index 54%rename from src/hi/integrations/templates/integrations/referencer/modals/attr_picker.htmlrename to src/hi/integrations/templates/integrations/referencer/modals/external_reference_picker.htmlindex 42097f49..f9044c1b 100644--- a/src/hi/integrations/templates/integrations/referencer/modals/attr_picker.html+++ b/src/hi/integrations/templates/integrations/referencer/modals/external_reference_picker.html@@ -2,11 +2,11 @@{% load icons %}{% comment %}-ATTRIBUTE_REFERENCE picker modal.+EXTERNAL_REFERENCE picker modal.-Selection state lives in attr-picker.js (one selection set per open+Selection state lives in external-reference-picker.js (one selection set per openmodal instance, keyed by the picker-root DOM node -- i.e., this-modal-dialog). attr-picker.js attaches its handlers as delegated+modal-dialog). external-reference-picker.js attaches its handlers as delegatedlisteners at document level, so antinode-injected modal contentwires up automatically -- no init step in this template.@@ -25,24 +25,24 @@ Layout:Context:integration_data_list : list[IntegrationData]integration_data : IntegrationData (initially-selected source)- item_type_value : str(ItemType.ENTITY) or str(ItemType.LOCATION)+ item_type : ItemType (ENTITY or LOCATION)item_id : int (host record id)limit : int (initial page size)page_size_choices : tuple[int]Wire-format strings (DOM class names, data-attribute names, formfield names) come from ``hi.constants.DIVID`` (mirrored in-``static/js/main.js`` under ``Hi.ATTR_PICKER_*``).+``static/js/main.js`` under ``Hi.REF_PICKER_*``).{% endcomment %}-{% block modal_dialog_class %}modal-dialog-scrollable hi-modal-dialog-700 {{ DIVID.ATTR_PICKER_ROOT_CLASS }}{% endblock %}+{% block modal_dialog_class %}modal-dialog-scrollable hi-modal-dialog-700 {{ DIVID.REF_PICKER_ROOT_CLASS }}{% endblock %}{% block title_text %}Link Content{% endblock %}{% block body %}-{% include "integrations/referencer/panes/attr_picker_body.html" %}+{% include "integrations/referencer/panes/external_reference_picker_body.html" %}{% endblock %}{% block footer %}@@ -50,37 +50,48 @@ Link Content{# ----- Chip row + empty-state hint ----- #}<div class="d-flex flex-wrap align-items-center mb-2 mt-1">- <div class="{{ DIVID.ATTR_PICKER_CHIPS_EMPTY_CLASS }} small text-muted">+ <div class="{{ DIVID.REF_PICKER_CHIPS_EMPTY_CLASS }} small text-muted">No content selected yet.</div>- <div class="{{ DIVID.ATTR_PICKER_CHIPS_CLASS }} d-flex flex-wrap"></div>+ <div class="{{ DIVID.REF_PICKER_CHIPS_CLASS }} d-flex flex-wrap"></div></div>{# ----- Cancel + Add row ----- #}<div class="d-flex justify-content-between align-items-center">+ {% if item_type.is_entity %}+ {% url 'entity_edit' entity_id=item_id as owner_edit_url %}+ {% else %}+ {% url 'location_edit_location_edit' location_id=item_id as owner_edit_url %}+ {% endif %}<a id="hi-modal-cancel" role="button"- class="btn btn-outline-tertiary" href="#" data-dismiss="modal">+ class="btn btn-outline-tertiary"+ href="{{ owner_edit_url }}"+ data-async="modal">{% icon "cancel" size="sm" css_class="hi-icon-left" %}CANCEL</a>{% comment %}- No ``data-async`` here: attr-picker.js owns the submit so it can+ No ``data-async`` here: external-reference-picker.js owns the submit so it canpopulate ``selections_json`` and POST through antinode's publicAPI (``AN.hideModalIfNeeded`` + ``AN.post``). Letting antinodealso bind via ``data-async`` would race the field-population --- antinode reads the form at the <body> level before attr-picker's+ antinode reads the form at the <body> level before external-reference-picker'sdocument-level submit handler fires.{% endcomment %}- <form class="{{ DIVID.ATTR_PICKER_ATTACH_FORM_CLASS }} m-0"+ <form class="{{ DIVID.REF_PICKER_ATTACH_FORM_CLASS }} m-0"method="post"- action="{% url 'integrations_attribute_reference_attach' %}">+ action="{% url 'integrations_external_reference_attach' %}">{% csrf_token %}- <input type="hidden" name="{{ DIVID.ATTR_PICKER_ITEM_TYPE_FIELD }}" value="{{ item_type_value }}">- <input type="hidden" name="{{ DIVID.ATTR_PICKER_ITEM_ID_FIELD }}" value="{{ item_id }}">- <input type="hidden" name="{{ DIVID.ATTR_PICKER_SELECTIONS_JSON_FIELD }}" value="">+ <input type="hidden" name="{{ DIVID.REF_PICKER_ITEM_TYPE_FIELD }}" value="{{ item_type }}">+ <input type="hidden" name="{{ DIVID.REF_PICKER_ITEM_ID_FIELD }}" value="{{ item_id }}">+ {# Kept in sync with the search-form copy by external-reference-picker.js on source switch. #}+ <input type="hidden"+ name="{{ DIVID.REF_PICKER_INTEGRATION_ID_FIELD }}"+ value="{{ integration_data.integration_id }}">+ <input type="hidden" name="{{ DIVID.REF_PICKER_SELECTIONS_JSON_FIELD }}" value=""><button type="submit"- class="btn btn-primary {{ DIVID.ATTR_PICKER_ATTACH_BTN_CLASS }}"+ class="btn btn-primary {{ DIVID.REF_PICKER_ATTACH_BTN_CLASS }}"disabled>- {% icon "check-circle" size="sm" css_class="hi-icon-left" %}<span class="{{ DIVID.ATTR_PICKER_ATTACH_LABEL_CLASS }}">Add 0 Links</span>+ {% icon "check-circle" size="sm" css_class="hi-icon-left" %}<span class="{{ DIVID.REF_PICKER_ATTACH_LABEL_CLASS }}">Add 0 Links</span></button></form></div>diff --git a/src/hi/integrations/templates/integrations/referencer/panes/attribute_actions.html b/src/hi/integrations/templates/integrations/referencer/panes/attribute_actions.htmlindex bfc6407b..24e915c4 100644--- a/src/hi/integrations/templates/integrations/referencer/panes/attribute_actions.html+++ b/src/hi/integrations/templates/integrations/referencer/panes/attribute_actions.html@@ -1,6 +1,6 @@{% load icons %}{% comment %}-Attribute-form action-bar fragment for the ATTRIBUTE_REFERENCE+Attribute-form action-bar fragment for the EXTERNAL_REFERENCEcapability: ENABLED / DISABLED status badge plus the DISABLEbutton (only when enabled). The framework re-renders thisfragment as part of the attribute form's post-save response, sodiff --git a/src/hi/integrations/templates/integrations/referencer/panes/attr_picker_body.html b/src/hi/integrations/templates/integrations/referencer/panes/external_reference_picker_body.htmlsimilarity index 65%rename from src/hi/integrations/templates/integrations/referencer/panes/attr_picker_body.htmlrename to src/hi/integrations/templates/integrations/referencer/panes/external_reference_picker_body.htmlindex bead3e1c..238409f8 100644--- a/src/hi/integrations/templates/integrations/referencer/panes/attr_picker_body.html+++ b/src/hi/integrations/templates/integrations/referencer/panes/external_reference_picker_body.html@@ -2,10 +2,10 @@{% comment %}Picker modal body. Holds the search controls and a placeholdercontainer for result cards (server-rendered partial swapped in on-each search by attr-picker.js).+each search by external-reference-picker.js).The chip row, Cancel button, and Add button live in the modal-footer (see attr_picker.html). The footer stays anchored when the+footer (see external_reference_picker.html). The footer stays anchored when thebody scrolls because the modal opts into Bootstrap's``modal-dialog-scrollable`` behavior.@@ -15,20 +15,20 @@ same picker instance.DOM classes, data-attribute names, and wire-format field namescome from ``hi.constants.DIVID`` (mirrored in ``static/js/main.js``-under ``Hi.ATTR_PICKER_*``).+under ``Hi.REF_PICKER_*``).Context:integration_data_list : list[IntegrationData]integration_data : IntegrationData (the default-selected source)- item_type_value : str (ItemType serialized)+ item_type : ItemType (ENTITY or LOCATION)item_id : intlimit : int (initial page size)page_size_choices : tuple[int]{% endcomment %}{# ----- Search form ----- #}-<form class="{{ DIVID.ATTR_PICKER_SEARCH_FORM_CLASS }}"- {{ DIVID.ATTR_PICKER_SEARCH_URL_ATTR }}="{% url 'integrations_attribute_reference_search' %}">+<form class="{{ DIVID.REF_PICKER_SEARCH_FORM_CLASS }}"+ {{ DIVID.REF_PICKER_SEARCH_URL_ATTR }}="{% url 'integrations_external_reference_search' %}">{% csrf_token %}{% comment %}@@ -36,31 +36,31 @@ Context:whether one source or many. Bootstrap dropdown shows``[logo] [name] [caret]``; the caret + dropdown are disabledvia CSS when only one source is configured. The current source- is carried in a sibling hidden input that attr-picker.js+ is carried in a sibling hidden input that external-reference-picker.jsupdates on dropdown selection.{% endcomment %}<div class="dropdown mb-3- {% if integration_data_list|length == 1 %}hi-attr-picker-source-banner-single{% endif %}">+ {% if integration_data_list|length == 1 %}hi-ref-picker-source-banner-single{% endif %}"><button type="button"- class="btn btn-light btn-block dropdown-toggle text-left d-flex align-items-center {{ DIVID.ATTR_PICKER_SOURCE_BANNER_CLASS }}"+ class="btn btn-light btn-block dropdown-toggle text-left d-flex align-items-center {{ DIVID.REF_PICKER_SOURCE_BANNER_CLASS }}"data-toggle="dropdown"aria-haspopup="true"aria-expanded="false"{% if integration_data_list|length == 1 %}disabled{% endif %}>- <img class="mr-2 {{ DIVID.ATTR_PICKER_SOURCE_BANNER_LOGO_CLASS }}"+ <img class="mr-2 {{ DIVID.REF_PICKER_SOURCE_BANNER_LOGO_CLASS }}"src="{% static integration_data.integration_metadata.logo_static_path %}"alt="">- <span class="flex-grow-1 {{ DIVID.ATTR_PICKER_SOURCE_BANNER_LABEL_CLASS }}">+ <span class="flex-grow-1 {{ DIVID.REF_PICKER_SOURCE_BANNER_LABEL_CLASS }}">{{ integration_data.label }}</span></button><div class="dropdown-menu w-100">{% for option in integration_data_list %}<a href="#"- class="dropdown-item d-flex align-items-center {{ DIVID.ATTR_PICKER_SOURCE_OPTION_CLASS }}"- {{ DIVID.ATTR_PICKER_SOURCE_ID_ATTR }}="{{ option.integration_id }}"- {{ DIVID.ATTR_PICKER_SOURCE_LOGO_ATTR }}="{% static option.integration_metadata.logo_static_path %}"- {{ DIVID.ATTR_PICKER_SOURCE_LABEL_ATTR }}="{{ option.label }}">+ class="dropdown-item d-flex align-items-center {{ DIVID.REF_PICKER_SOURCE_OPTION_CLASS }}"+ {{ DIVID.REF_PICKER_SOURCE_ID_ATTR }}="{{ option.integration_id }}"+ {{ DIVID.REF_PICKER_SOURCE_LOGO_ATTR }}="{% static option.integration_metadata.logo_static_path %}"+ {{ DIVID.REF_PICKER_SOURCE_LABEL_ATTR }}="{{ option.label }}"><img class="mr-2" src="{% static option.integration_metadata.logo_static_path %}" alt=""><span>{{ option.label }}</span></a>@@ -68,28 +68,28 @@ Context:</div></div><input type="hidden"- name="{{ DIVID.ATTR_PICKER_INTEGRATION_ID_FIELD }}"+ name="{{ DIVID.REF_PICKER_INTEGRATION_ID_FIELD }}"value="{{ integration_data.integration_id }}"><div class="form-row align-items-end mb-3"><div class="col">- <label for="hi-attr-picker-query" class="small text-muted mb-1">+ <label for="hi-ref-picker-query" class="small text-muted mb-1">Search</label><input type="text"- id="hi-attr-picker-query"- name="{{ DIVID.ATTR_PICKER_QUERY_FIELD }}"+ id="hi-ref-picker-query"+ name="{{ DIVID.REF_PICKER_QUERY_FIELD }}"value="{{ query }}"placeholder="Type to search and press Enter"class="form-control form-control-sm"autofocus></div><div class="col-auto">- <label for="hi-attr-picker-limit" class="small text-muted mb-1">+ <label for="hi-ref-picker-limit" class="small text-muted mb-1">Page size</label>- <select id="hi-attr-picker-limit"- name="{{ DIVID.ATTR_PICKER_LIMIT_FIELD }}"+ <select id="hi-ref-picker-limit"+ name="{{ DIVID.REF_PICKER_LIMIT_FIELD }}"class="form-control form-control-sm">{% for choice in page_size_choices %}<option value="{{ choice }}" {% if choice == limit %}selected{% endif %}>{{ choice }}</option>@@ -107,9 +107,9 @@ Context:{# ----- Results container ----- #}{% comment %}The initial render uses the same partial the search endpoint-returns; attr-picker.js swaps the container's contents on each+returns; external-reference-picker.js swaps the container's contents on eachsubsequent search.{% endcomment %}-<div class="{{ DIVID.ATTR_PICKER_RESULTS_CLASS }}">- {% include "integrations/referencer/panes/attr_picker_results.html" %}+<div class="{{ DIVID.REF_PICKER_RESULTS_CLASS }}">+ {% include "integrations/referencer/panes/external_reference_picker_results.html" %}</div>diff --git a/src/hi/integrations/templates/integrations/referencer/panes/attr_picker_results.html b/src/hi/integrations/templates/integrations/referencer/panes/external_reference_picker_results.htmlsimilarity index 55%rename from src/hi/integrations/templates/integrations/referencer/panes/attr_picker_results.htmlrename to src/hi/integrations/templates/integrations/referencer/panes/external_reference_picker_results.htmlindex 832a8c60..9f89eeb0 100644--- a/src/hi/integrations/templates/integrations/referencer/panes/attr_picker_results.html+++ b/src/hi/integrations/templates/integrations/referencer/panes/external_reference_picker_results.html@@ -1,17 +1,17 @@{% load icons %}{% comment %}Result-cards partial returned by the search endpoint and swapped-into the picker's results container by attr-picker.js. Each card+into the picker's results container by external-reference-picker.js. Each cardcarries the source title and URL as data attributes so the JS canread them on checkbox change without parsing the DOM.DOM classes / data-attribute names come from ``hi.constants.DIVID``-(mirrored in ``static/js/main.js`` under ``Hi.ATTR_PICKER_*``).+(mirrored in ``static/js/main.js`` under ``Hi.REF_PICKER_*``).Context:query : str (the search query that produced these results;used only for the no-results message)- results : list[AttributeReferenceResult]+ results : list[ExternalReferenceResult]error_message : Optional[str] (upstream failure banner; when set,suppresses the no-results messagefor an empty result list)@@ -24,16 +24,29 @@ Context:{% if results %}<div class="list-group">{% for r in results %}- <label class="list-group-item d-flex align-items-start mb-0">+ <label class="list-group-item d-flex align-items-start mb-0 hi-ref-picker-row"><input type="checkbox"- class="{{ DIVID.ATTR_PICKER_RESULT_CHECKBOX_CLASS }} mt-1 mr-3"- {{ DIVID.ATTR_PICKER_TITLE_ATTR }}="{{ r.title }}"- {{ DIVID.ATTR_PICKER_SOURCE_URL_ATTR }}="{{ r.source_url }}">+ class="{{ DIVID.REF_PICKER_RESULT_CHECKBOX_CLASS }} mt-1 mr-3"+ {{ DIVID.REF_PICKER_TITLE_ATTR }}="{{ r.title }}"+ {{ DIVID.REF_PICKER_SOURCE_URL_ATTR }}="{{ r.source_url }}"+ {{ DIVID.REF_PICKER_INTEGRATION_NAME_ATTR }}="{{ r.integration_key.integration_name }}"+ {{ DIVID.REF_PICKER_MIME_TYPE_ATTR }}="{{ r.mime_type|default:'' }}">{% if r.thumbnail_url %}- <img src="{{ r.thumbnail_url }}"- alt=""- class="mr-3 rounded"- style="width: 56px; height: 56px; object-fit: cover;">+ {% comment %}+ Hover-zoom: pure CSS. The small img is the 56-square shown in+ the row; the zoom img is a sibling positioned absolutely and+ revealed on hover of the wrapper. Both <img> elements use the+ same upstream URL so the zoom is the native-size source (no+ extra request).+ {% endcomment %}+ <span class="hi-ref-picker-thumb mr-3">+ <img src="{{ r.thumbnail_url }}"+ alt=""+ class="hi-ref-picker-thumb-small rounded">+ <img src="{{ r.thumbnail_url }}"+ alt=""+ class="hi-ref-picker-thumb-zoom rounded">+ </span>{% else %}<div class="mr-3 d-flex align-items-center justify-content-center bg-light rounded text-muted"style="width: 56px; height: 56px;">@@ -46,7 +59,7 @@ Context:<div class="small text-muted text-truncate">{{ r.snippet }}</div>{% endif %}<a href="{{ r.source_url }}" target="_blank" rel="noopener"- class="small text-truncate d-block"+ class="small text-truncate d-block hi-ref-picker-source-link"onclick="event.stopPropagation();">{{ r.source_url }}</a>diff --git a/src/hi/integrations/templatetags/integration_tags.py b/src/hi/integrations/templatetags/integration_tags.pyindex 6b68c3ad..7605dcae 100644--- a/src/hi/integrations/templatetags/integration_tags.py+++ b/src/hi/integrations/templatetags/integration_tags.py@@ -67,13 +67,12 @@ def previous_integration_logo_path( model : IntegrationDetailsModel ) -> str:@register.simple_tag-def has_attribute_referencers() -> bool:+def has_external_referencers() -> bool:"""True iff at least one currently-enabled integration advertises- the ATTRIBUTE_REFERENCE capability. Used by Entity/Location edit- surfaces to decide whether to show the "LINK" action-bar button."""+ the EXTERNAL_REFERENCE capability."""return bool( IntegrationManager().get_integration_data_list(enabled_only = True,- capabilities = frozenset({ IntegrationCapability.ATTRIBUTE_REFERENCE }),+ capabilities = frozenset({ IntegrationCapability.EXTERNAL_REFERENCE }),) )diff --git a/src/hi/integrations/tests/test_card_action_views.py b/src/hi/integrations/tests/test_card_action_views.pynew file mode 100644index 00000000..91b2fe07--- /dev/null+++ b/src/hi/integrations/tests/test_card_action_views.py@@ -0,0 +1,274 @@+"""View tests for the per-card external-reference action endpoints+(rename, delete, reorder). Each view POSTs and responds with the+freshly-rendered grid HTML; the JS layer swaps the response in+place via ``$grid.replaceWith(html)``.++Focus is the branching logic: title validation, direction+validation, sibling re-order arithmetic, and the 404 path through+``get_external_reference_or_404``. The grid-render response shape+is asserted at the integration boundary (presence of the grid div+id) rather than re-asserting full HTML.+"""+import logging++from django.urls import reverse++from hi.apps.entity.enums import EntityType+from hi.apps.entity.models import Entity+from hi.apps.location.models import Location+from hi.enums import ViewMode+from hi.integrations.models import (+ EntityExternalReference,+ LocationExternalReference,+)+from hi.testing.view_test_base import ViewTestBase+++logging.disable(logging.CRITICAL)+++def _make_entity(name='Dishwasher'):+ return Entity.objects.create(+ name=name,+ entity_type_str=str(EntityType.DISHWASHER),+ )+++def _make_location(name='Kitchen'):+ return Location.objects.create(+ name=name,+ svg_fragment_filename='kitchen.svg',+ svg_view_box_str='0 0 100 100',+ )+++def _make_entity_ref(entity, *, integration_name='doc-1', title='Doc',+ order_id=0):+ return EntityExternalReference.objects.create(+ entity=entity,+ integration_id='ref',+ integration_name=integration_name,+ title=title,+ source_url=f'https://example.com/{integration_name}',+ order_id=order_id,+ )+++# ---- rename ------------------------------------------------------+++class TestExternalReferenceRenameView(ViewTestBase):++ def setUp(self):+ super().setUp()+ self.client.force_login(self.user)+ self.setSessionViewMode(ViewMode.EDIT)+ self.entity = _make_entity()++ def _url(self, reference, owner_type='entity'):+ return reverse('external_reference_rename', kwargs={+ 'owner_type': owner_type,+ 'reference_id': reference.id,+ })++ def test_rename_updates_title_and_returns_grid_html(self):+ ref = _make_entity_ref(self.entity, title='Old')+ response = self.client.post(+ self._url(ref), data={'title': 'New Title'},+ **self.async_http_headers,+ )+ self.assertEqual(response.status_code, 200)+ ref.refresh_from_db()+ self.assertEqual(ref.title, 'New Title')+ # Response carries the rendered grid for the owner.+ self.assertIn(+ f'hi-ext-ref-grid-entity-{self.entity.id}',+ response.content.decode(),+ )++ def test_rename_empty_title_returns_400(self):+ ref = _make_entity_ref(self.entity, title='Old')+ response = self.client.post(+ self._url(ref), data={'title': ' '},+ **self.async_http_headers,+ )+ self.assertEqual(response.status_code, 400)+ ref.refresh_from_db()+ self.assertEqual(ref.title, 'Old')++ def test_rename_truncates_long_title_to_255_chars(self):+ ref = _make_entity_ref(self.entity)+ long_title = 'x' * 500+ self.client.post(+ self._url(ref), data={'title': long_title},+ **self.async_http_headers,+ )+ ref.refresh_from_db()+ self.assertEqual(len(ref.title), 255)++ def test_rename_unknown_owner_type_returns_404(self):+ ref = _make_entity_ref(self.entity)+ response = self.client.post(+ self._url(ref, owner_type='nonsense'),+ data={'title': 'X'},+ **self.async_http_headers,+ )+ self.assertEqual(response.status_code, 404)++ def test_rename_missing_reference_returns_404(self):+ url = reverse('external_reference_rename', kwargs={+ 'owner_type': 'entity', 'reference_id': 99999,+ })+ response = self.client.post(+ url, data={'title': 'X'}, **self.async_http_headers,+ )+ self.assertEqual(response.status_code, 404)+++# ---- delete ------------------------------------------------------+++class TestExternalReferenceDeleteView(ViewTestBase):++ def setUp(self):+ super().setUp()+ self.client.force_login(self.user)+ self.setSessionViewMode(ViewMode.EDIT)++ def _url(self, reference, owner_type='entity'):+ return reverse('external_reference_delete', kwargs={+ 'owner_type': owner_type,+ 'reference_id': reference.id,+ })++ def test_delete_removes_row_and_returns_grid_html(self):+ entity = _make_entity()+ ref = _make_entity_ref(entity)+ _make_entity_ref(+ entity, integration_name='doc-2', title='Survivor',+ )+ response = self.client.post(+ self._url(ref), **self.async_http_headers,+ )+ self.assertEqual(response.status_code, 200)+ self.assertFalse(+ EntityExternalReference.objects.filter(pk=ref.pk).exists()+ )+ # Sibling and the freshly-rendered grid for the owner survive.+ body = response.content.decode()+ self.assertIn(f'hi-ext-ref-grid-entity-{entity.id}', body)+ self.assertIn('Survivor', body)++ def test_delete_for_location_owner(self):+ location = _make_location()+ ref = LocationExternalReference.objects.create(+ location=location,+ integration_id='ref',+ integration_name='asset-1',+ title='Photo',+ source_url='https://example.com/asset-1',+ )+ response = self.client.post(+ self._url(ref, owner_type='location'),+ **self.async_http_headers,+ )+ self.assertEqual(response.status_code, 200)+ self.assertFalse(+ LocationExternalReference.objects.filter(pk=ref.pk).exists()+ )+ self.assertIn(+ f'hi-ext-ref-grid-location-{location.id}',+ response.content.decode(),+ )+++# ---- reorder -----------------------------------------------------+++class TestExternalReferenceReorderView(ViewTestBase):++ def setUp(self):+ super().setUp()+ self.client.force_login(self.user)+ self.setSessionViewMode(ViewMode.EDIT)+ self.entity = _make_entity()+ # Three siblings with explicit order_ids so the test reads as+ # "the second one moves" rather than relying on insert order.+ self.r0 = _make_entity_ref(+ self.entity, integration_name='a', title='A', order_id=0,+ )+ self.r1 = _make_entity_ref(+ self.entity, integration_name='b', title='B', order_id=1,+ )+ self.r2 = _make_entity_ref(+ self.entity, integration_name='c', title='C', order_id=2,+ )++ def _url(self, reference):+ return reverse('external_reference_reorder', kwargs={+ 'owner_type': 'entity',+ 'reference_id': reference.id,+ })++ def _current_order(self):+ return list(+ EntityExternalReference.objects+ .filter(entity=self.entity)+ .order_by('order_id', '-created_datetime')+ .values_list('title', flat=True)+ )++ def test_reorder_left_swaps_with_previous_sibling(self):+ response = self.client.post(+ self._url(self.r1), data={'direction': 'left'},+ **self.async_http_headers,+ )+ self.assertEqual(response.status_code, 200)+ self.assertEqual(self._current_order(), ['B', 'A', 'C'])++ def test_reorder_right_swaps_with_next_sibling(self):+ response = self.client.post(+ self._url(self.r1), data={'direction': 'right'},+ **self.async_http_headers,+ )+ self.assertEqual(response.status_code, 200)+ self.assertEqual(self._current_order(), ['A', 'C', 'B'])++ def test_reorder_left_at_first_position_is_noop(self):+ response = self.client.post(+ self._url(self.r0), data={'direction': 'left'},+ **self.async_http_headers,+ )+ self.assertEqual(response.status_code, 200)+ self.assertEqual(self._current_order(), ['A', 'B', 'C'])++ def test_reorder_renormalizes_order_ids_to_dense_sequence(self):+ # Start with sparse / non-zero-based order_ids; a swap should+ # leave the affected rows densely numbered 0..N-1.+ for ref, sparse in ((self.r0, 10), (self.r1, 20), (self.r2, 30)):+ ref.order_id = sparse+ ref.save(update_fields=['order_id'])+ self.client.post(+ self._url(self.r1), data={'direction': 'left'},+ **self.async_http_headers,+ )+ order_ids = sorted(+ EntityExternalReference.objects+ .filter(entity=self.entity)+ .values_list('order_id', flat=True)+ )+ self.assertEqual(order_ids, [0, 1, 2])++ def test_reorder_invalid_direction_returns_400(self):+ response = self.client.post(+ self._url(self.r1), data={'direction': 'sideways'},+ **self.async_http_headers,+ )+ self.assertEqual(response.status_code, 400)+ self.assertEqual(self._current_order(), ['A', 'B', 'C'])++ def test_reorder_missing_direction_returns_400(self):+ response = self.client.post(+ self._url(self.r1), **self.async_http_headers,+ )+ self.assertEqual(response.status_code, 400)diff --git a/src/hi/integrations/tests/test_external_reference_models.py b/src/hi/integrations/tests/test_external_reference_models.pynew file mode 100644index 00000000..1f3ed983--- /dev/null+++ b/src/hi/integrations/tests/test_external_reference_models.py@@ -0,0 +1,224 @@+"""Tests for the external-reference models: create_or_update+upsert semantics and delete-time thumbnail cleanup. Thumbnail+bytes are synthesized inline with Pillow so fixtures stay+self-contained.+"""+import logging+from io import BytesIO+from unittest.mock import patch++from django.core.files.storage import default_storage+from django.test import TestCase+from PIL import Image++from hi.apps.entity.enums import EntityType+from hi.apps.entity.models import Entity+from hi.apps.location.models import Location+from hi.integrations.models import (+ EntityExternalReference,+ LocationExternalReference,+)+from hi.integrations.transient_models import IntegrationKey+++def _key(integration_id, integration_name):+ return IntegrationKey(+ integration_id=integration_id,+ integration_name=integration_name,+ )+++logging.disable(logging.CRITICAL)+++def _png_bytes(color='red'):+ img = Image.new('RGB', (16, 16), color)+ buf = BytesIO()+ img.save(buf, format='PNG')+ return buf.getvalue()+++class TestCreateOrUpdateInsert(TestCase):++ def setUp(self):+ self.entity = Entity.objects.create(+ name='Fridge', entity_type_str=str(EntityType.APPLIANCE),+ )++ def test_insert_with_all_fields_writes_thumbnail_under_per_integration_path(self):+ instance = EntityExternalReference.objects.create_or_update(+ owner=self.entity,+ integration_key=_key('immich', 'asset-uuid-1'),+ title='Fridge serial plate',+ source_url='https://im.example.com/photos/asset-uuid-1',+ mime_type='image/jpeg',+ thumbnail_bytes=_png_bytes(),+ )+ self.assertEqual(instance.integration_id, 'immich')+ self.assertEqual(instance.integration_name, 'asset-uuid-1')+ self.assertIn('entity/external/immich/thumbnails/',+ instance.thumbnail.name)+ # Cleanup so the test leaves no media residue.+ instance.delete()++ def test_insert_without_thumbnail_bytes_leaves_thumbnail_empty(self):+ instance = EntityExternalReference.objects.create_or_update(+ owner=self.entity,+ integration_key=_key('paperless', '42'),+ title='Warranty',+ source_url='https://p.example.com/documents/42/details/',+ )+ self.assertFalse(instance.thumbnail)+++class TestCreateOrUpdateUpsert(TestCase):++ def setUp(self):+ self.entity = Entity.objects.create(+ name='Fridge', entity_type_str=str(EntityType.APPLIANCE),+ )+ self.original = EntityExternalReference.objects.create_or_update(+ owner=self.entity,+ integration_key=_key('immich', 'uuid-1'),+ title='Original title',+ source_url='https://im.example.com/photos/uuid-1',+ mime_type='image/jpeg',+ thumbnail_bytes=_png_bytes('red'),+ )+ # Operator edits the local title + repositions the card.+ self.original.order_id = 7+ self.original.title = 'Operator-edited title'+ self.original.save(update_fields=['order_id', 'title'])++ def tearDown(self):+ # Reload to get the post-upsert thumbnail name for cleanup.+ for row in EntityExternalReference.objects.filter(entity=self.entity):+ row.delete()++ def test_upsert_overwrites_source_url_and_mime_type(self):+ updated = EntityExternalReference.objects.create_or_update(+ owner=self.entity,+ integration_key=_key('immich', 'uuid-1'),+ title='Upstream title (ignored)',+ source_url='https://im.example.com/photos/uuid-1?v=2',+ mime_type='image/png',+ )+ self.assertEqual(updated.pk, self.original.pk)+ self.assertEqual(updated.source_url,+ 'https://im.example.com/photos/uuid-1?v=2')+ self.assertEqual(updated.mime_type, 'image/png')++ def test_upsert_preserves_operator_title_order_id_created_datetime(self):+ updated = EntityExternalReference.objects.create_or_update(+ owner=self.entity,+ integration_key=_key('immich', 'uuid-1'),+ title='Upstream title (should be ignored)',+ source_url='https://im.example.com/photos/uuid-1',+ mime_type='image/jpeg',+ )+ self.assertEqual(updated.title, 'Operator-edited title')+ self.assertEqual(updated.order_id, 7)+ self.assertEqual(updated.created_datetime,+ self.original.created_datetime)++ def test_upsert_without_thumbnail_bytes_leaves_existing_thumbnail(self):+ original_thumbnail_name = self.original.thumbnail.name+ self.assertTrue(default_storage.exists(original_thumbnail_name))+ updated = EntityExternalReference.objects.create_or_update(+ owner=self.entity,+ integration_key=_key('immich', 'uuid-1'),+ title='x',+ source_url='https://im.example.com/photos/uuid-1',+ mime_type='image/jpeg',+ thumbnail_bytes=None,+ )+ self.assertEqual(updated.thumbnail.name, original_thumbnail_name)+ self.assertTrue(default_storage.exists(updated.thumbnail.name))++ def test_upsert_with_thumbnail_bytes_replaces_file(self):+ original_thumbnail_name = self.original.thumbnail.name+ self.assertTrue(default_storage.exists(original_thumbnail_name))+ updated = EntityExternalReference.objects.create_or_update(+ owner=self.entity,+ integration_key=_key('immich', 'uuid-1'),+ title='x',+ source_url='https://im.example.com/photos/uuid-1',+ mime_type='image/jpeg',+ thumbnail_bytes=_png_bytes('blue'),+ )+ # Stable filename per (owner, integration_name) so the rewrite+ # lands on the same path; the old file is deleted and the new+ # one occupies the same slot.+ self.assertTrue(default_storage.exists(updated.thumbnail.name))+++class TestExternalReferenceDelete(TestCase):++ def setUp(self):+ self.entity = Entity.objects.create(+ name='Fridge', entity_type_str=str(EntityType.APPLIANCE),+ )++ def test_delete_removes_thumbnail_file(self):+ instance = EntityExternalReference.objects.create_or_update(+ owner=self.entity,+ integration_key=_key('immich', 'uuid-1'),+ title='X',+ source_url='https://im.example.com/photos/uuid-1',+ mime_type='image/jpeg',+ thumbnail_bytes=_png_bytes(),+ )+ thumbnail_name = instance.thumbnail.name+ self.assertTrue(default_storage.exists(thumbnail_name))+ instance.delete()+ self.assertFalse(default_storage.exists(thumbnail_name))++ def test_delete_without_thumbnail_does_not_raise(self):+ instance = EntityExternalReference.objects.create_or_update(+ owner=self.entity,+ integration_key=_key('paperless', '42'),+ title='X',+ source_url='https://p.example.com/documents/42/details/',+ )+ instance.delete()++ @patch('hi.integrations.models.default_storage.delete',+ side_effect=OSError('disk gone'))+ def test_delete_swallows_storage_errors_best_effort(self, _mock_delete):+ instance = EntityExternalReference.objects.create_or_update(+ owner=self.entity,+ integration_key=_key('immich', 'uuid-1'),+ title='X',+ source_url='https://im.example.com/photos/uuid-1',+ mime_type='image/jpeg',+ thumbnail_bytes=_png_bytes(),+ )+ # Delete must succeed even though file deletion errored.+ instance.delete()+ self.assertFalse(+ EntityExternalReference.objects.filter(pk=instance.pk).exists(),+ )+++class TestLocationExternalReference(TestCase):+ """Spot-check that the Location flavor uses the same path+ convention as Entity. Deep coverage stays on Entity since the+ abstract base owns the shared behavior."""++ def test_create_or_update_inserts_under_location_thumbnail_path(self):+ location = Location.objects.create(+ name='Kitchen', svg_view_box_str='0 0 100 100',+ )+ instance = LocationExternalReference.objects.create_or_update(+ owner=location,+ integration_key=_key('immich', 'uuid-1'),+ title='X',+ source_url='https://im.example.com/photos/uuid-1',+ mime_type='image/jpeg',+ thumbnail_bytes=_png_bytes(),+ )+ self.assertEqual(instance.location, location)+ self.assertIn('location/external/immich/thumbnails/',+ instance.thumbnail.name)+ # Cleanup so the test leaves no media residue.+ instance.delete()diff --git a/src/hi/integrations/tests/test_referencer_views.py b/src/hi/integrations/tests/test_referencer_views.pyindex 56050f16..d2cfd9d1 100644--- a/src/hi/integrations/tests/test_referencer_views.py+++ b/src/hi/integrations/tests/test_referencer_views.py@@ -1,13 +1,13 @@-"""View tests for the ATTRIBUTE_REFERENCE picker.+"""View tests for the EXTERNAL_REFERENCE picker.The picker is split into three endpoints:- - ``integrations_attribute_reference_picker`` — GET, renders the+ - ``integrations_external_reference_picker`` — GET, renders theinitial empty modal.- - ``integrations_attribute_reference_search`` — POST, returns the- result-cards partial. The attr-picker.js module swaps the+ - ``integrations_external_reference_search`` — POST, returns the+ result-cards partial. The external-reference-picker.js module swaps thereturned HTML into the picker's results container.- - ``integrations_attribute_reference_attach`` — POST, reads the+ - ``integrations_external_reference_attach`` — POST, reads theJS-built ``selections_json`` payload, creates one TEXTattribute per record, returns ``antinode.refresh_response()``.@@ -20,10 +20,10 @@ import loggingfrom django.urls import reverse-from hi.apps.attribute.enums import AttributeType, AttributeValueType+from hi.apps.attribute.enums import AttributeValueTypefrom hi.apps.entity.enums import EntityType-from hi.apps.entity.models import Entity, EntityAttribute-from hi.apps.location.models import Location, LocationAttribute+from hi.apps.entity.models import Entity+from hi.apps.location.models import Locationfrom hi.enums import ItemType, ViewModefrom hi.integrations.enums import IntegrationAttributeType, IntegrationCapabilityfrom hi.integrations.integration_data import IntegrationData@@ -31,15 +31,18 @@ from hi.integrations.integration_gateway import IntegrationGatewayfrom hi.integrations.integration_manager import IntegrationManagerfrom hi.integrations.models import Integrationfrom hi.integrations.referencer.integration_referencer import (- IntegrationAttributeReferencer,+ IntegrationExternalReferencer,)from hi.constants import DIVIDfrom hi.integrations.referencer.transient_models import (- AttributeReferenceResult,- AttributeReferenceSearchResult,+ ExternalReferenceAttachBatchOutcome,+ ExternalReferenceAttachOutcome,+ ExternalReferenceResult,+ ExternalReferenceSearchResult,)from hi.integrations.transient_models import (ConnectionTestResult,+ IntegrationKey,IntegrationMetaData,IntegrationValidationResult,)@@ -59,19 +62,22 @@ class _RefAttributeType(IntegrationAttributeType):)-class _StubReferencer(IntegrationAttributeReferencer):+class _StubReferencer(IntegrationExternalReferencer):"""In-memory referencer the tests inject via the gateway.Captures search args so tests can assert dispatch shape."""def __init__(self, integration_id='ref', label='Ref Test',- results=None, raises=None, error_message=None):+ results=None, raises=None, error_message=None,+ attach_outcomes=None):self._integration_id = integration_idself._label = labelself._results = results or []self._raises = raisesself._error_message = error_message+ self._attach_outcomes = attach_outcomesself.last_query = Noneself.last_limit = None+ self.attach_calls = []def get_metadata(self):return IntegrationMetaData(@@ -79,7 +85,7 @@ class _StubReferencer(IntegrationAttributeReferencer):label=self._label,attribute_type=_RefAttributeType,allow_entity_deletion=True,- capabilities=frozenset({IntegrationCapability.ATTRIBUTE_REFERENCE}),+ capabilities=frozenset({IntegrationCapability.EXTERNAL_REFERENCE}),)def validate_configuration(self, integration_attributes):@@ -90,15 +96,31 @@ class _StubReferencer(IntegrationAttributeReferencer):self.last_limit = limitif self._raises is not None:raise self._raises- return AttributeReferenceSearchResult(+ return ExternalReferenceSearchResult(results=list(self._results),error_message=self._error_message,)+ def attach_references(self, owner, selections):+ # Capture (owner, selections-list) for dispatch-shape asserts;+ # return either the injected outcomes or default-success-for-all.+ selections = list(selections)+ self.attach_calls.append((owner, selections))+ if self._attach_outcomes is not None:+ return ExternalReferenceAttachBatchOutcome(+ outcomes=list(self._attach_outcomes),+ )+ return ExternalReferenceAttachBatchOutcome(+ outcomes=[+ ExternalReferenceAttachOutcome(success=True)+ for _ in selections+ ],+ )+class _ReferencerCapableGateway(IntegrationGateway):- """Gateway that advertises ATTRIBUTE_REFERENCE and returns the- test's stub referencer from ``get_attribute_referencer``."""+ """Gateway that advertises EXTERNAL_REFERENCE and returns the+ test's stub referencer from ``get_external_referencer``."""def __init__(self, integration_id='ref', label='Ref Test', referencer=None):self.integration_id = integration_id@@ -111,7 +133,7 @@ class _ReferencerCapableGateway(IntegrationGateway):label=self.label,attribute_type=_RefAttributeType,allow_entity_deletion=True,- capabilities=frozenset({IntegrationCapability.ATTRIBUTE_REFERENCE}),+ capabilities=frozenset({IntegrationCapability.EXTERNAL_REFERENCE}),)def validate_configuration(self, integration_attributes):@@ -120,7 +142,7 @@ class _ReferencerCapableGateway(IntegrationGateway):def validate_access(self, integration_attributes, timeout_secs):return ConnectionTestResult.success()- def get_attribute_referencer(self):+ def get_external_referencer(self):return self._referencer@@ -145,8 +167,13 @@ def _populate_manager(pairs, enabled=True):def _result(title='Doc', source_url='https://example.com/doc/1',+ integration_id='ref', integration_name='doc-1',thumbnail_url=None, mime_type=None, snippet=None):- return AttributeReferenceResult(+ return ExternalReferenceResult(+ integration_key=IntegrationKey(+ integration_id=integration_id,+ integration_name=integration_name,+ ),title=title,source_url=source_url,thumbnail_url=thumbnail_url,@@ -158,18 +185,18 @@ def _result(title='Doc', source_url='https://example.com/doc/1',# ---- gateway default ---------------------------------------------class TestIntegrationGatewayAttributeReferencerDefault(ViewTestBase):- """Default ``IntegrationGateway`` advertises no ATTRIBUTE_REFERENCE+class TestIntegrationGatewayExternalReferencerDefault(ViewTestBase):+ """Default ``IntegrationGateway`` advertises no EXTERNAL_REFERENCEreferencer — only integrations that explicitly opt in do."""def test_default_returns_none(self):- self.assertIsNone(IntegrationGateway().get_attribute_referencer())+ self.assertIsNone(IntegrationGateway().get_external_referencer())# ---- picker GET -----------------------------------------------------class TestAttributeReferencePickerView(ViewTestBase):+class TestExternalReferencePickerView(ViewTestBase):"""GET renders the initial empty modal. Search and attach aresibling endpoints (tested separately below)."""@@ -194,15 +221,15 @@ class TestAttributeReferencePickerView(ViewTestBase):)def _url(self):- return reverse('integrations_attribute_reference_picker')+ return reverse('integrations_external_reference_picker')def test_get_renders_modal_with_integration_label(self):entity = self._entity()response = self.client.get(self._url(),data={- DIVID['ATTR_PICKER_ITEM_TYPE_FIELD']: str(ItemType.ENTITY),- DIVID['ATTR_PICKER_ITEM_ID_FIELD']: entity.id,+ DIVID['REF_PICKER_ITEM_TYPE_FIELD']: str(ItemType.ENTITY),+ DIVID['REF_PICKER_ITEM_ID_FIELD']: entity.id,},**self.async_http_headers,)@@ -215,8 +242,8 @@ class TestAttributeReferencePickerView(ViewTestBase):response = self.client.get(self._url(),data={- DIVID['ATTR_PICKER_ITEM_TYPE_FIELD']: str(ItemType.ENTITY),- DIVID['ATTR_PICKER_ITEM_ID_FIELD']: entity.id,+ DIVID['REF_PICKER_ITEM_TYPE_FIELD']: str(ItemType.ENTITY),+ DIVID['REF_PICKER_ITEM_ID_FIELD']: entity.id,},**self.async_http_headers,)@@ -226,8 +253,8 @@ class TestAttributeReferencePickerView(ViewTestBase):response = self.client.get(self._url(),data={- DIVID['ATTR_PICKER_ITEM_TYPE_FIELD']: 'banana',- DIVID['ATTR_PICKER_ITEM_ID_FIELD']: 1,+ DIVID['REF_PICKER_ITEM_TYPE_FIELD']: 'banana',+ DIVID['REF_PICKER_ITEM_ID_FIELD']: 1,},**self.async_http_headers,)@@ -237,8 +264,8 @@ class TestAttributeReferencePickerView(ViewTestBase):response = self.client.get(self._url(),data={- DIVID['ATTR_PICKER_ITEM_TYPE_FIELD']: str(ItemType.ENTITY),- DIVID['ATTR_PICKER_ITEM_ID_FIELD']: 99999,+ DIVID['REF_PICKER_ITEM_TYPE_FIELD']: str(ItemType.ENTITY),+ DIVID['REF_PICKER_ITEM_ID_FIELD']: 99999,},**self.async_http_headers,)@@ -257,8 +284,8 @@ class TestAttributeReferencePickerView(ViewTestBase):response = self.client.get(self._url(),data={- DIVID['ATTR_PICKER_ITEM_TYPE_FIELD']: str(ItemType.ENTITY),- DIVID['ATTR_PICKER_ITEM_ID_FIELD']: entity.id,+ DIVID['REF_PICKER_ITEM_TYPE_FIELD']: str(ItemType.ENTITY),+ DIVID['REF_PICKER_ITEM_ID_FIELD']: entity.id,},**self.async_http_headers,)@@ -271,7 +298,7 @@ class TestAttributeReferencePickerView(ViewTestBase):# ---- search endpoint -----------------------------------------------class TestAttributeReferenceSearchView(ViewTestBase):+class TestExternalReferenceSearchView(ViewTestBase):"""POST returns the result-cards partial. The picker JS swapsthe returned HTML into the results container."""@@ -290,13 +317,13 @@ class TestAttributeReferenceSearchView(ViewTestBase):_populate_manager([(self.INTEGRATION_ID, self.gateway)])def _url(self):- return reverse('integrations_attribute_reference_search')+ return reverse('integrations_external_reference_search')def _payload(self, query='', limit=20, integration_id=None):return {- DIVID['ATTR_PICKER_QUERY_FIELD']: query,- DIVID['ATTR_PICKER_LIMIT_FIELD']: str(limit),- DIVID['ATTR_PICKER_INTEGRATION_ID_FIELD']: integration_id or self.INTEGRATION_ID,+ DIVID['REF_PICKER_QUERY_FIELD']: query,+ DIVID['REF_PICKER_LIMIT_FIELD']: str(limit),+ DIVID['REF_PICKER_INTEGRATION_ID_FIELD']: integration_id or self.INTEGRATION_ID,}def test_empty_query_does_not_call_referencer(self):@@ -335,8 +362,8 @@ class TestAttributeReferenceSearchView(ViewTestBase):self.assertIn('https://p/doc/1', body)# Cards carry data attributes so JS can read title + URL on# checkbox change without parsing the DOM.- self.assertIn('data-attr-picker-source-url', body)- self.assertIn('data-attr-picker-title', body)+ self.assertIn('data-ref-picker-source-url', body)+ self.assertIn('data-ref-picker-title', body)def test_search_with_no_results_returns_empty_message(self):self.referencer._results = []@@ -351,7 +378,7 @@ class TestAttributeReferenceSearchView(ViewTestBase):def test_search_invalid_limit_falls_back_to_default(self):self.referencer._results = [_result()]payload = self._payload(query='q')- payload[DIVID['ATTR_PICKER_LIMIT_FIELD']] = 'not-a-number'+ payload[DIVID['REF_PICKER_LIMIT_FIELD']] = 'not-a-number'self.client.post(self._url(), data=payload, **self.async_http_headers,)@@ -398,9 +425,18 @@ class TestAttributeReferenceSearchView(ViewTestBase):# ---- attach endpoint -----------------------------------------------class TestAttributeReferenceAttachView(ViewTestBase):- """POST reads the JS-built ``selections_json`` payload and- creates one TEXT attribute per record on the named owner."""+class TestExternalReferenceAttachView(ViewTestBase):+ """POST parses ``selections_json``, routes the batch to the+ single source integration's ``attach_references``, and branches+ on the resulting outcome batch:+ - all-success -> owner edit modal (delegated GET response)+ - any-failure -> error modal with LINK MORE / EDIT / DISMISS++ The picker resets selection state on source-switch, so each+ submission carries one integration's items only; the form-level+ integration_id field is the single source of truth for routing.+ Tests verify dispatch shape, modal response shape, and the+ failure-path branch."""def setUp(self):super().setUp()@@ -410,7 +446,7 @@ class TestAttributeReferenceAttachView(ViewTestBase):self.setSessionViewMode(ViewMode.EDIT)def _url(self):- return reverse('integrations_attribute_reference_attach')+ return reverse('integrations_external_reference_attach')@staticmethoddef _entity(name='Dishwasher'):@@ -428,128 +464,242 @@ class TestAttributeReferenceAttachView(ViewTestBase):)@staticmethod- def _selections_json(*pairs):- return json.dumps([- {DIVID['ATTR_PICKER_SELECTION_TITLE_KEY']: title, DIVID['ATTR_PICKER_SELECTION_URL_KEY']: url}- for title, url in pairs- ])+ def _selection_dict(*, integration_name='item-1',+ title='Title', source_url='https://example.com/1',+ mime_type='application/pdf'):+ return {+ DIVID['REF_PICKER_SELECTION_TITLE_KEY']: title,+ DIVID['REF_PICKER_SELECTION_URL_KEY']: source_url,+ DIVID['REF_PICKER_SELECTION_INTEGRATION_NAME_KEY']: integration_name,+ DIVID['REF_PICKER_SELECTION_MIME_TYPE_KEY']: mime_type,+ }- def _payload(self, owner, selections_json):+ def _payload(self, owner, integration_id, selections):item_type = ItemType.ENTITY if isinstance(owner, Entity) else ItemType.LOCATIONreturn {- DIVID['ATTR_PICKER_ITEM_TYPE_FIELD']: str(item_type),- DIVID['ATTR_PICKER_ITEM_ID_FIELD']: owner.id,- DIVID['ATTR_PICKER_SELECTIONS_JSON_FIELD']: selections_json,+ DIVID['REF_PICKER_ITEM_TYPE_FIELD']: str(item_type),+ DIVID['REF_PICKER_ITEM_ID_FIELD']: owner.id,+ DIVID['REF_PICKER_INTEGRATION_ID_FIELD']: integration_id,+ DIVID['REF_PICKER_SELECTIONS_JSON_FIELD']: json.dumps(selections),}- def test_attach_creates_text_attributes_on_entity(self):+ def test_attach_dispatches_to_referencer_for_form_integration_id(self):entity = self._entity()+ ref = _StubReferencer(integration_id='paperless')+ _populate_manager([('paperless', _ReferencerCapableGateway(+ integration_id='paperless', referencer=ref,+ ))])++ self.client.post(+ self._url(),+ data=self._payload(entity, 'paperless', [+ self._selection_dict(+ integration_name='42',+ title='Warranty',+ source_url='https://p/doc/42',+ ),+ self._selection_dict(+ integration_name='99',+ title='Manual',+ source_url='https://p/doc/99',+ ),+ ]),+ **self.async_http_headers,+ )+ self.assertEqual(len(ref.attach_calls), 1)+ owner_arg, selections = ref.attach_calls[0]+ self.assertEqual(owner_arg, entity)+ self.assertEqual(+ [s.integration_key.integration_name for s in selections],+ ['42', '99'],+ )+ # Form-level integration_id stamped onto every selection.+ self.assertTrue(all(+ s.integration_key.integration_id == 'paperless'+ for s in selections+ ))++ def test_all_success_returns_owner_edit_modal(self):+ # Default _StubReferencer returns success-for-all. Response+ # should carry the owner's edit modal as antinode modal+ # content (not a refresh, not the error modal).+ entity = self._entity()+ ref = _StubReferencer(integration_id='paperless')+ _populate_manager([('paperless', _ReferencerCapableGateway(+ integration_id='paperless', referencer=ref,+ ))])+response = self.client.post(self._url(),- data=self._payload(entity, self._selections_json(- ('Warranty', 'https://p/doc/1'),- ('Manual', 'https://p/doc/2'),- )),+ data=self._payload(entity, 'paperless', [+ self._selection_dict(integration_name='42'),+ ]),**self.async_http_headers,)self.assertEqual(response.status_code, 200)body = json.loads(response.content)- self.assertTrue(body.get('refresh'))+ self.assertIn('modal', body)+ self.assertNotIn('Some links could not be attached', body['modal'])- attrs = list(EntityAttribute.objects.filter(entity=entity).order_by('id'))- self.assertEqual(len(attrs), 2)- self.assertEqual(attrs[0].name, 'Warranty')- self.assertEqual(attrs[0].value, 'https://p/doc/1')- self.assertEqual(attrs[0].value_type, AttributeValueType.TEXT)- self.assertEqual(attrs[0].attribute_type, AttributeType.CUSTOM)- self.assertEqual(attrs[1].name, 'Manual')+ def test_any_failure_returns_error_modal(self):+ entity = self._entity()+ ref = _StubReferencer(+ integration_id='paperless',+ attach_outcomes=[+ ExternalReferenceAttachOutcome(success=True),+ ExternalReferenceAttachOutcome(+ success=False,+ error_message='Paperless rejected doc 99.',+ ),+ ],+ )+ _populate_manager([('paperless', _ReferencerCapableGateway(+ integration_id='paperless', referencer=ref,+ ))])- def test_attach_creates_text_attribute_on_location(self):- location = self._location()response = self.client.post(self._url(),- data=self._payload(location, self._selections_json(- ('Floor Plan', 'https://p/doc/floor-plan'),- )),+ data=self._payload(entity, 'paperless', [+ self._selection_dict(integration_name='42'),+ self._selection_dict(integration_name='99'),+ ]),**self.async_http_headers,)- self.assertEqual(response.status_code, 200)- attrs = list(LocationAttribute.objects.filter(location=location))- self.assertEqual(len(attrs), 1)- self.assertEqual(attrs[0].name, 'Floor Plan')+ body = json.loads(response.content)+ self.assertIn('modal', body)+ self.assertIn('Some links could not be attached', body['modal'])+ self.assertIn('Paperless rejected doc 99.', body['modal'])++ def test_attach_dispatches_to_location_owner(self):+ location = self._location()+ ref = _StubReferencer(integration_id='paperless')+ _populate_manager([('paperless', _ReferencerCapableGateway(+ integration_id='paperless', referencer=ref,+ ))])++ self.client.post(+ self._url(),+ data=self._payload(location, 'paperless', [+ self._selection_dict(integration_name='42'),+ ]),+ **self.async_http_headers,+ )+ self.assertEqual(len(ref.attach_calls), 1)+ self.assertEqual(ref.attach_calls[0][0], location)- def test_attach_with_empty_selections_creates_nothing(self):+ def test_empty_selections_yields_owner_edit_modal_no_dispatch(self):entity = self._entity()+ ref = _StubReferencer(integration_id='paperless')+ _populate_manager([('paperless', _ReferencerCapableGateway(+ integration_id='paperless', referencer=ref,+ ))])response = self.client.post(self._url(),- data=self._payload(entity, json.dumps([])),+ data=self._payload(entity, 'paperless', []),**self.async_http_headers,)self.assertEqual(response.status_code, 200)- self.assertEqual(- EntityAttribute.objects.filter(entity=entity).count(), 0,- )+ self.assertEqual(ref.attach_calls, [])+ self.assertIn('modal', json.loads(response.content))- def test_attach_with_malformed_json_creates_nothing(self):- # Defensive: malformed JSON yields no attributes rather than- # a 500. The JS contract submits valid JSON; this guards+ def test_malformed_json_yields_owner_edit_modal_no_dispatch(self):+ # Defensive: malformed JSON yields no dispatch + edit modal,+ # not 500. The JS contract submits valid JSON; this guards# against a manual replay.entity = self._entity()+ ref = _StubReferencer(integration_id='paperless')+ _populate_manager([('paperless', _ReferencerCapableGateway(+ integration_id='paperless', referencer=ref,+ ))])+ payload = self._payload(entity, 'paperless', [])+ payload[DIVID['REF_PICKER_SELECTIONS_JSON_FIELD']] = 'not-json'response = self.client.post(- self._url(),- data=self._payload(entity, 'not-json'),- **self.async_http_headers,+ self._url(), data=payload, **self.async_http_headers,)self.assertEqual(response.status_code, 200)- self.assertEqual(- EntityAttribute.objects.filter(entity=entity).count(), 0,+ self.assertEqual(ref.attach_calls, [])++ def test_records_with_missing_fields_skipped(self):+ entity = self._entity()+ ref = _StubReferencer(integration_id='paperless')+ _populate_manager([('paperless', _ReferencerCapableGateway(+ integration_id='paperless', referencer=ref,+ ))])+ # Three records: missing title, missing url, missing integration_name.+ # All are filtered out; the referencer sees no selections.+ self.client.post(+ self._url(),+ data=self._payload(entity, 'paperless', [+ self._selection_dict(integration_name='1', title=''),+ self._selection_dict(integration_name='2', source_url=''),+ self._selection_dict(integration_name=''),+ ]),+ **self.async_http_headers,)+ self.assertEqual(ref.attach_calls, [])- def test_attach_skips_records_with_missing_fields(self):+ def test_unknown_integration_id_returns_400(self):entity = self._entity()- payload = self._payload(entity, json.dumps([- {DIVID['ATTR_PICKER_SELECTION_TITLE_KEY']: '', DIVID['ATTR_PICKER_SELECTION_URL_KEY']: 'https://p/1'},- {DIVID['ATTR_PICKER_SELECTION_TITLE_KEY']: 'Good', DIVID['ATTR_PICKER_SELECTION_URL_KEY']: 'https://p/2'},- {DIVID['ATTR_PICKER_SELECTION_TITLE_KEY']: 'No URL', DIVID['ATTR_PICKER_SELECTION_URL_KEY']: ''},- ]))- self.client.post(self._url(), data=payload, **self.async_http_headers)- attrs = list(EntityAttribute.objects.filter(entity=entity).order_by('id'))- self.assertEqual(len(attrs), 1)- self.assertEqual(attrs[0].name, 'Good')-- def test_attach_long_title_truncated_to_max_length(self):+ ref = _StubReferencer(integration_id='paperless')+ _populate_manager([('paperless', _ReferencerCapableGateway(+ integration_id='paperless', referencer=ref,+ ))])+ response = self.client.post(+ self._url(),+ data=self._payload(entity, 'unknown-integration', [+ self._selection_dict(integration_name='1'),+ ]),+ **self.async_http_headers,+ )+ # _resolve_integration_data raises BadRequest for unknown id.+ self.assertEqual(response.status_code, 400)++ def test_missing_integration_id_returns_400(self):entity = self._entity()- long_title = 'X' * 100- payload = self._payload(entity, json.dumps([{- DIVID['ATTR_PICKER_SELECTION_TITLE_KEY']: long_title,- DIVID['ATTR_PICKER_SELECTION_URL_KEY']: 'https://p/1',- }]))+ ref = _StubReferencer(integration_id='paperless')+ _populate_manager([('paperless', _ReferencerCapableGateway(+ integration_id='paperless', referencer=ref,+ ))])+ payload = self._payload(entity, 'paperless', [+ self._selection_dict(integration_name='1'),+ ])+ del payload[DIVID['REF_PICKER_INTEGRATION_ID_FIELD']]response = self.client.post(self._url(), data=payload, **self.async_http_headers,)- self.assertEqual(response.status_code, 200)- attr = EntityAttribute.objects.get(entity=entity)- self.assertEqual(len(attr.name), 64)+ self.assertEqual(response.status_code, 400)- def test_attach_unsupported_item_type_returns_400(self):+ def test_unsupported_item_type_returns_400(self):+ ref = _StubReferencer(integration_id='paperless')+ _populate_manager([('paperless', _ReferencerCapableGateway(+ integration_id='paperless', referencer=ref,+ ))])response = self.client.post(self._url(),data={- DIVID['ATTR_PICKER_ITEM_TYPE_FIELD']: str(ItemType.COLLECTION),- DIVID['ATTR_PICKER_ITEM_ID_FIELD']: 1,- DIVID['ATTR_PICKER_SELECTIONS_JSON_FIELD']: self._selections_json(('A', 'https://p/1')),+ DIVID['REF_PICKER_ITEM_TYPE_FIELD']: str(ItemType.COLLECTION),+ DIVID['REF_PICKER_ITEM_ID_FIELD']: 1,+ DIVID['REF_PICKER_INTEGRATION_ID_FIELD']: 'paperless',+ DIVID['REF_PICKER_SELECTIONS_JSON_FIELD']: json.dumps(+ [self._selection_dict()]),},**self.async_http_headers,)self.assertEqual(response.status_code, 400)- def test_attach_unknown_owner_returns_404(self):+ def test_unknown_owner_returns_404(self):+ ref = _StubReferencer(integration_id='paperless')+ _populate_manager([('paperless', _ReferencerCapableGateway(+ integration_id='paperless', referencer=ref,+ ))])response = self.client.post(self._url(),data={- DIVID['ATTR_PICKER_ITEM_TYPE_FIELD']: str(ItemType.ENTITY),- DIVID['ATTR_PICKER_ITEM_ID_FIELD']: 99999,- DIVID['ATTR_PICKER_SELECTIONS_JSON_FIELD']: self._selections_json(('A', 'https://p/1')),+ DIVID['REF_PICKER_ITEM_TYPE_FIELD']: str(ItemType.ENTITY),+ DIVID['REF_PICKER_ITEM_ID_FIELD']: 99999,+ DIVID['REF_PICKER_INTEGRATION_ID_FIELD']: 'paperless',+ DIVID['REF_PICKER_SELECTIONS_JSON_FIELD']: json.dumps(+ [self._selection_dict()]),},**self.async_http_headers,)diff --git a/src/hi/integrations/urls.py b/src/hi/integrations/urls.pyindex e5c1c1bf..d5d3527e 100644--- a/src/hi/integrations/urls.py+++ b/src/hi/integrations/urls.py@@ -24,6 +24,16 @@ urlpatterns = [path( 'attribute/restore/<int:integration_id>/<int:attribute_id>/<int:history_id>/',views.IntegrationAttributeRestoreInlineView.as_view(),name='integration_attribute_restore_inline' ),++ path( 'external-references/<str:owner_type>/<int:reference_id>/rename/',+ views.ExternalReferenceRenameView.as_view(),+ name='external_reference_rename' ),+ path( 'external-references/<str:owner_type>/<int:reference_id>/delete/',+ views.ExternalReferenceDeleteView.as_view(),+ name='external_reference_delete' ),+ path( 'external-references/<str:owner_type>/<int:reference_id>/reorder/',+ views.ExternalReferenceReorderView.as_view(),+ name='external_reference_reorder' ),]diff --git a/src/hi/integrations/view_mixins.py b/src/hi/integrations/view_mixins.pyindex 49eb3dd6..0965a33a 100644--- a/src/hi/integrations/view_mixins.py+++ b/src/hi/integrations/view_mixins.py@@ -3,6 +3,7 @@ from typing import FrozenSet, Optionalfrom django.core.exceptions import BadRequestfrom django.db.models import Countfrom django.http import Http404+from django.shortcuts import renderfrom django.urls import reversefrom hi.apps.collection.collection_manager import CollectionManager@@ -14,63 +15,14 @@ from hi.apps.location.models import Location, LocationViewfrom hi.integrations.enums import IntegrationCapabilityfrom hi.integrations.integration_manager import IntegrationManager+from hi.integrations.models import (+ EntityExternalReference,+ LocationExternalReference,+)from hi.integrations.placement_request import PlacementUrlParams-class CapabilityBlockViewMixin:- """Block IMPORT initiation when the integration has active Connect- entities, directing the user to disable the integration first.-- The asymmetry is principled. CONNECT does not need a symmetric block:- sync's reconnect-then-create order will adopt any pre-existing- detached/imported rows for the same integration into the live Connect- session, so no collision is possible. IMPORT creates new HI-owned rows,- which would collide with active-Connect rows unless we block this entry- point.- """-- def render_capability_block_if_conflict(- self,- request,- integration_data,- capability_being_initiated : IntegrationCapability,- ):- if capability_being_initiated != IntegrationCapability.IMPORT:- return None- capabilities = integration_data.integration_metadata.capabilities- if IntegrationCapability.CONNECT not in capabilities:- return None-- existing_count = Entity.objects.external_for(- integration_id = integration_data.integration_id,- ).count()- if existing_count == 0:- return None-- return self.modal_response(- request,- context = {- 'integration_data': integration_data,- 'my_label': 'Import',- 'existing_count': existing_count,- 'existing_mode_clause': (- 'already configured as a Connector with'- ),- 'desired_action_clause': (- f'use {integration_data.label} as a Data Importer'- ),- 'remediation_clause': (- f'disable the {integration_data.label} '- f'Connector'- ),- 'link_url': reverse( 'integrations_connect_home' ),- 'link_label': 'GO TO CONNECTORS',- },- template_name = 'integrations/modals/capability_blocked.html',- )--class IntegrationViewMixin:def get_integration_data( self, request, *args, **kwargs ):@@ -425,3 +377,107 @@ class IntegrationPlacementViewMixin:{ 'label': group.label, 'count': len( group.items ) }for group in placement_input.groups]+++class ExternalReferenceCardViewMixin:+ """Helpers for the per-card external-reference action views+ (rename, delete, reorder). Centralizes the owner_type-to-model+ binding and the post-mutation grid-replace render. The+ owner_type URL segment doubles as the foreign-key attribute+ name on the row, so the binding is a flat string -> model+ dict."""++ EXTERNAL_REFERENCE_MODELS = {+ 'entity' : EntityExternalReference,+ 'location': LocationExternalReference,+ }+ GRID_TEMPLATE = 'integrations/panes/external_reference_grid.html'++ def get_external_reference_or_404( self, owner_type : str, reference_id : int ):+ """Resolve a row by (owner_type, id). Raises Http404 on an+ unknown owner type or a missing row -- the same response+ either way so probing the wrong path never reveals whether a+ row exists under the other type."""+ model = self.EXTERNAL_REFERENCE_MODELS.get( owner_type )+ if model is None:+ raise Http404+ try:+ return model.objects.get( pk = reference_id )+ except model.DoesNotExist:+ raise Http404++ def render_grid_replace( self, request, owner_type : str, owner ):+ """Re-render the grid as plain HTML. The action source+ elements (per-card inputs / buttons) carry+ ``data-async="#<grid_id>"`` and ``data-mode="replace"``, so+ antinode's ``replaceWith`` swaps the targeted grid element+ with this response. View and template never duplicate the+ target id -- the template owns it. Owner is passed+ explicitly so the delete view (whose row is gone+ post-mutation) can use the same path."""+ model = self.EXTERNAL_REFERENCE_MODELS[ owner_type ]+ external_references = model.objects.filter(+ **{ owner_type: owner },+ ).order_by( 'order_id', '-created_datetime' )+ return render(+ request,+ self.GRID_TEMPLATE,+ {+ 'external_references': external_references,+ 'owner_type' : owner_type,+ 'owner_id' : owner.id,+ },+ )+++class CapabilityBlockViewMixin:+ """Block IMPORT initiation when the integration has active Connect+ entities, directing the user to disable the integration first.++ The asymmetry is principled. CONNECT does not need a symmetric block:+ sync's reconnect-then-create order will adopt any pre-existing+ detached/imported rows for the same integration into the live Connect+ session, so no collision is possible. IMPORT creates new HI-owned rows,+ which would collide with active-Connect rows unless we block this entry+ point.+ """++ def render_capability_block_if_conflict(+ self,+ request,+ integration_data,+ capability_being_initiated : IntegrationCapability,+ ):+ if capability_being_initiated != IntegrationCapability.IMPORT:+ return None+ capabilities = integration_data.integration_metadata.capabilities+ if IntegrationCapability.CONNECT not in capabilities:+ return None++ existing_count = Entity.objects.external_for(+ integration_id = integration_data.integration_id,+ ).count()+ if existing_count == 0:+ return None++ return self.modal_response(+ request,+ context = {+ 'integration_data': integration_data,+ 'my_label': 'Import',+ 'existing_count': existing_count,+ 'existing_mode_clause': (+ 'already configured as a Connector with'+ ),+ 'desired_action_clause': (+ f'use {integration_data.label} as a Data Importer'+ ),+ 'remediation_clause': (+ f'disable the {integration_data.label} '+ f'Connector'+ ),+ 'link_url': reverse( 'integrations_connect_home' ),+ 'link_label': 'GO TO CONNECTORS',+ },+ template_name = 'integrations/modals/capability_blocked.html',+ )diff --git a/src/hi/integrations/views.py b/src/hi/integrations/views.pyindex 0c66354b..03bb4135 100644--- a/src/hi/integrations/views.py+++ b/src/hi/integrations/views.py@@ -1,7 +1,11 @@"""Framework-level integration views shared across capabilities."""+import logging+from django.core.exceptions import BadRequest+from django.db import transaction+from django.http import Http404from django.shortcuts import redirectfrom django.urls import reversefrom django.views.generic import View@@ -9,6 +13,7 @@ from django.views.generic import Viewfrom hi.apps.attribute.view_mixins import AttributeEditViewMixinfrom hi.apps.entity.entity_placement import EntityPlacementServicefrom hi.apps.location.models import LocationView+from hi.constants import DIVIDfrom hi.enums import ViewMode, ViewTypefrom hi.hi_async_view import HiModalViewfrom hi.views import page_not_found_response@@ -23,11 +28,113 @@ from hi.integrations.models import IntegrationAttributefrom hi.integrations.placement_request import PlacementFormParser, PlacementUrlParamsfrom hi.integrations.view_mixins import (CapabilityBlockViewMixin,+ ExternalReferenceCardViewMixin,IntegrationPlacementViewMixin,IntegrationViewMixin,)+logger = logging.getLogger(__name__)+++class ExternalReferenceRenameView( View, ExternalReferenceCardViewMixin ):+ """POST endpoint: rename a single external-reference card. The+ title is operator-controlled and persists across upserts on+ re-attach."""++ def post( self, request, owner_type, reference_id, *args, **kwargs ):+ reference = self.get_external_reference_or_404(+ owner_type = owner_type, reference_id = reference_id,+ )+ new_title = ( request.POST.get(+ DIVID['EXT_REF_TITLE_FIELD']+ ) or '' ).strip()+ if not new_title:+ raise BadRequest( 'Title must be non-empty.' )+ reference.title = new_title[:255]+ reference.save( update_fields = [ 'title', 'updated_datetime' ] )+ return self.render_grid_replace(+ request, owner_type, getattr( reference, owner_type ),+ )+++class ExternalReferenceDeleteView( View, ExternalReferenceCardViewMixin ):+ """POST endpoint: unlink (delete) a single external-reference+ card. Best-effort thumbnail-file cleanup is the model's+ responsibility."""++ def post( self, request, owner_type, reference_id, *args, **kwargs ):+ reference = self.get_external_reference_or_404(+ owner_type = owner_type, reference_id = reference_id,+ )+ # Capture the owner before delete; the row's FK accessor is+ # unreliable after delete().+ owner = getattr( reference, owner_type )+ reference.delete()+ return self.render_grid_replace( request, owner_type, owner )+++class ExternalReferenceReorderView( View, ExternalReferenceCardViewMixin ):+ """POST endpoint: move a single external-reference card one slot+ left or right. Re-normalizes order_ids of the affected siblings+ so the new ordering survives subsequent reorders without+ accumulating gaps."""++ def post( self, request, owner_type, reference_id, *args, **kwargs ):+ direction = request.POST.get( DIVID['EXT_REF_DIRECTION_FIELD'] )+ if direction not in (+ DIVID['EXT_REF_DIRECTION_LEFT'],+ DIVID['EXT_REF_DIRECTION_RIGHT'],+ ):+ raise BadRequest( 'Invalid direction.' )++ reference = self.get_external_reference_or_404(+ owner_type = owner_type, reference_id = reference_id,+ )+ model = self.EXTERNAL_REFERENCE_MODELS[ owner_type ]+ owner = getattr( reference, owner_type )++ # The read + renumber + writes run inside one transaction+ # with row locks on the sibling set so concurrent reorders+ # serialize. Without this, two simultaneous POSTs each see+ # a stale ordering and the second writer clobbers the+ # first, occasionally leaving duplicate ``order_id`` values+ # the ordering meta can't disambiguate.+ with transaction.atomic():+ siblings = list(+ model.objects.select_for_update().filter(+ **{ owner_type: owner },+ ).order_by( 'order_id', '-created_datetime' )+ )+ try:+ current_idx = next(+ i for i, r in enumerate(siblings) if r.pk == reference.pk+ )+ except StopIteration:+ raise Http404++ if direction == DIVID['EXT_REF_DIRECTION_LEFT'] and current_idx > 0:+ siblings[current_idx], siblings[current_idx - 1] = (+ siblings[current_idx - 1], siblings[current_idx],+ )+ elif (+ direction == DIVID['EXT_REF_DIRECTION_RIGHT']+ and current_idx < len(siblings) - 1+ ):+ siblings[current_idx], siblings[current_idx + 1] = (+ siblings[current_idx + 1], siblings[current_idx],+ )+ # Re-normalize order_ids based on the new ordering. Rows+ # whose position didn't change get no DB write (cheap ++ # avoids unnecessary updated_datetime bumps).+ for new_index, sibling in enumerate(siblings):+ if sibling.order_id != new_index:+ sibling.order_id = new_index+ sibling.save( update_fields = [ 'order_id', 'updated_datetime' ] )++ return self.render_grid_replace( request, owner_type, owner )++class CapabilityConfigureView( HiModalView,IntegrationViewMixin,CapabilityBlockViewMixin,diff --git a/src/hi/services/immich/im_client.py b/src/hi/services/immich/im_client.pyindex df6d242e..46b40d04 100644--- a/src/hi/services/immich/im_client.py+++ b/src/hi/services/immich/im_client.py@@ -79,6 +79,22 @@ class ImmichClient:),}+ def download_original( self, asset_id : str ) -> Dict[str, Any]:+ """Fetch the per-asset original bytes. Returns+ ``{'content': bytes, 'mime_type': str}``. Callers should+ gate this on the mime type (image only) to avoid pulling+ whole videos."""+ path = ImmichApi.ASSET_ORIGINAL_PATH.format( id = asset_id )+ url = urljoin( self.api_url, path )+ response = self._session.get( url, timeout = self._timeout_secs )+ response.raise_for_status()+ return {+ 'content': response.content,+ 'mime_type': response.headers.get(+ 'Content-Type', 'application/octet-stream',+ ),+ }+def build_asset_web_url( self, asset_id : str ) -> str:"""Per-asset web UI URL on the configured Immich server.Persisted as the saved attribute's value so an operatordiff --git a/src/hi/services/immich/im_metadata.py b/src/hi/services/immich/im_metadata.pyindex 875e443d..d06e4e4f 100644--- a/src/hi/services/immich/im_metadata.py+++ b/src/hi/services/immich/im_metadata.py@@ -12,6 +12,6 @@ ImmichMetaData = IntegrationMetaData(allow_internal_attributes = False,logo_static_path = 'img/integrations/immich.png',capabilities = frozenset({- IntegrationCapability.ATTRIBUTE_REFERENCE,+ IntegrationCapability.EXTERNAL_REFERENCE,}),)diff --git a/src/hi/services/immich/im_models.py b/src/hi/services/immich/im_models.pyindex a0b391de..84ddb46e 100644--- a/src/hi/services/immich/im_models.py+++ b/src/hi/services/immich/im_models.py@@ -13,6 +13,11 @@ class ImmichApi:# has no free-text query field.SEARCH_METADATA_PROBE_PATH = 'api/search/metadata'ASSET_THUMBNAIL_PATH = 'api/assets/{id}/thumbnail'+ # Original-bytes endpoint -- used by the referencer's defensive+ # thumbnail fallback (HI-side generator from original) when the+ # upstream thumbnail endpoint is unavailable. Gated upstream on+ # image mime types so we don't pull whole videos.+ ASSET_ORIGINAL_PATH = 'api/assets/{id}/original'# Per-asset web UI route. Used unchanged as the persisted attribute# value; operators clicking the saved link land on Immich's own# page (authenticated by their Immich session, not by HI).diff --git a/src/hi/services/immich/im_referencer.py b/src/hi/services/immich/im_referencer.pyindex f3a52fc9..edd50106 100644--- a/src/hi/services/immich/im_referencer.py+++ b/src/hi/services/immich/im_referencer.py@@ -6,13 +6,15 @@ from requests import HTTPErrorfrom hi.integrations.exceptions import IntegrationAttributeErrorfrom hi.integrations.referencer.integration_referencer import (- IntegrationAttributeReferencer,+ IntegrationExternalReferencer,)from hi.integrations.referencer.transient_models import (- AttributeReferenceResult,- AttributeReferenceSearchResult,+ ExternalReferenceResult,+ ExternalReferenceSearchResult,)+from hi.apps.attribute.thumbnail import ThumbnailHelpersfrom hi.integrations.transient_models import (+ IntegrationKey,IntegrationMetaData,IntegrationValidationResult,)@@ -26,7 +28,7 @@ from .im_validation import validate_attributeslogger = logging.getLogger(__name__)-class ImmichAttributeReferencer( IntegrationAttributeReferencer ):+class ImmichExternalReferencer( IntegrationExternalReferencer ):def get_metadata( self ) -> IntegrationMetaData:return ImmichMetaData@@ -41,20 +43,20 @@ class ImmichAttributeReferencer( IntegrationAttributeReferencer ):self,query : str,limit : int = 20,- ) -> AttributeReferenceSearchResult:+ ) -> ExternalReferenceSearchResult:if not query or not query.strip():- return AttributeReferenceSearchResult( results = [] )+ return ExternalReferenceSearchResult( results = [] )try:client = build_client()except IntegrationAttributeError as e:logger.warning( f'Immich search aborted: {e}' )- return AttributeReferenceSearchResult(+ return ExternalReferenceSearchResult(results = [],error_message = 'Immich integration is not configured.',)except Exception as e:logger.exception( f'Immich client build failed: {e}' )- return AttributeReferenceSearchResult(+ return ExternalReferenceSearchResult(results = [],error_message = 'Immich integration error — see server logs.',)@@ -69,7 +71,7 @@ class ImmichAttributeReferencer( IntegrationAttributeReferencer ):f'Immich search HTTP {status} for query 'f'{query!r}: {e}')- return AttributeReferenceSearchResult(+ return ExternalReferenceSearchResult(results = [],error_message = self._http_error_message( status ),)@@ -77,7 +79,7 @@ class ImmichAttributeReferencer( IntegrationAttributeReferencer ):logger.warning(f'Immich search failed for query {query!r}: {e}')- return AttributeReferenceSearchResult(+ return ExternalReferenceSearchResult(results = [],error_message = 'Immich search failed — see server logs.',)@@ -101,11 +103,63 @@ class ImmichAttributeReferencer( IntegrationAttributeReferencer ):f'Immich asset translation failed for query 'f'{query!r}: {e}')- return AttributeReferenceSearchResult(+ return ExternalReferenceSearchResult(results = [],error_message = self._http_error_message( None ),)- return AttributeReferenceSearchResult( results = results )+ return ExternalReferenceSearchResult( results = results )++ # The module-level client factory satisfies the base's+ # ``build_client`` interface directly -- no wrapper method.+ build_client = staticmethod( build_client )++ @staticmethod+ def _try_upstream_thumbnail(+ client : ImmichClient, integration_name : str,+ ) -> Optional[bytes]:+ try:+ downloaded = client.download_thumbnail( asset_id = integration_name )+ except Exception as e:+ # Broad catch: this is a best-effort thumbnail fetch.+ # Any failure here (HTTP, network, code bug) should mean+ # "no thumbnail", never "the whole attach failed".+ logger.warning(+ f'Immich thumbnail unavailable for asset '+ f'{integration_name}: {e}'+ )+ return None+ return downloaded.get( 'content' )++ @staticmethod+ def _try_generate_from_original(+ client : ImmichClient,+ integration_name : str,+ mime_type : str,+ ) -> Optional[bytes]:+ """Pull the original bytes and ask the framework generator+ for a thumbnail. Gated on mime type to avoid downloading+ videos just to discover the generator can't make a poster+ for them."""+ if mime_type not in ThumbnailHelpers.THUMBNAIL_IMAGE_MIME_TYPES:+ return None+ try:+ downloaded = client.download_original( asset_id = integration_name )+ except Exception as e:+ # Broad catch: same rationale as ``_try_upstream_thumbnail``+ # -- the original-bytes fallback is best-effort; any+ # failure here means "no thumbnail", never per-selection+ # attach failure.+ logger.warning(+ f'Immich original-bytes fetch failed for asset '+ f'{integration_name}: {e}'+ )+ return None+ original_bytes = downloaded.get( 'content' )+ if not original_bytes:+ return None+ return ThumbnailHelpers.bytes_to_thumbnail_png(+ original_bytes, mime_type,+ )@staticmethoddef _http_error_message( status : Optional[int] ) -> str:@@ -122,14 +176,18 @@ class ImmichAttributeReferencer( IntegrationAttributeReferencer ):self,client : ImmichClient,asset : dict,- ) -> AttributeReferenceResult:+ ) -> ExternalReferenceResult:asset_id = asset.get( ImmichApi.ASSET_ID )title = (asset.get( ImmichApi.ASSET_ORIGINAL_FILE_NAME )or asset_idor '')- return AttributeReferenceResult(+ return ExternalReferenceResult(+ integration_key = IntegrationKey(+ integration_id = ImmichMetaData.integration_id,+ integration_name = asset_id or '',+ ),title = title,source_url = client.build_asset_web_url( asset_id ),thumbnail_url = self._proxy_thumbnail_url( asset_id ),diff --git a/src/hi/services/immich/integration.py b/src/hi/services/immich/integration.pyindex ec9b2980..2e250f5a 100644--- a/src/hi/services/immich/integration.py+++ b/src/hi/services/immich/integration.py@@ -7,7 +7,7 @@ import requestsfrom hi.integrations.integration_gateway import IntegrationGatewayfrom hi.integrations.models import IntegrationAttributefrom hi.integrations.referencer.integration_referencer import (- IntegrationAttributeReferencer,+ IntegrationExternalReferencer,)from hi.integrations.transient_models import (ConnectionTestResult,@@ -19,7 +19,7 @@ from hi.integrations.transient_models import (from .enums import ImAttributeTypefrom .im_metadata import ImmichMetaDatafrom .im_models import ImmichApi-from .im_referencer import ImmichAttributeReferencer+from .im_referencer import ImmichExternalReferencerfrom .im_validation import validate_attributes@@ -31,8 +31,8 @@ class ImmichGateway( IntegrationGateway ):def get_metadata( self ) -> IntegrationMetaData:return ImmichMetaData- def get_attribute_referencer( self ) -> IntegrationAttributeReferencer:- return ImmichAttributeReferencer()+ def get_external_referencer( self ) -> IntegrationExternalReferencer:+ return ImmichExternalReferencer()def validate_configuration(self,diff --git a/src/hi/services/immich/tests/test_im_referencer.py b/src/hi/services/immich/tests/test_im_referencer.pyindex 1a4746f8..95eb26fc 100644--- a/src/hi/services/immich/tests/test_im_referencer.py+++ b/src/hi/services/immich/tests/test_im_referencer.py@@ -6,7 +6,8 @@ from requests import HTTPErrorfrom hi.integrations.exceptions import IntegrationAttributeError-from hi.services.immich.im_referencer import ImmichAttributeReferencer+from hi.apps.attribute.thumbnail import ThumbnailHelpers+from hi.services.immich.im_referencer import ImmichExternalReferencerlogging.disable(logging.CRITICAL)@@ -51,7 +52,7 @@ class TestSearchReferencesShortCircuits(TestCase):@patch('hi.services.immich.im_referencer.build_client')def test_empty_query_returns_empty(self, mock_build):- result = ImmichAttributeReferencer().search_references(+ result = ImmichExternalReferencer().search_references(query = '', limit = 20,)self.assertEqual(result.results, [])@@ -60,7 +61,7 @@ class TestSearchReferencesShortCircuits(TestCase):@patch('hi.services.immich.im_referencer.build_client')def test_whitespace_query_returns_empty(self, mock_build):- result = ImmichAttributeReferencer().search_references(+ result = ImmichExternalReferencer().search_references(query = ' ', limit = 20,)self.assertEqual(result.results, [])@@ -75,7 +76,7 @@ class TestSearchReferences(TestCase):client = _make_client(_envelope(_asset('a1')))mock_build.return_value = client- ImmichAttributeReferencer().search_references(+ ImmichExternalReferencer().search_references(query = ' dishwasher ', limit = 10,)@@ -92,7 +93,7 @@ class TestSearchReferences(TestCase):))mock_build.return_value = client- result = ImmichAttributeReferencer().search_references(+ result = ImmichExternalReferencer().search_references(query = 'q', limit = 20,)@@ -118,7 +119,7 @@ class TestSearchReferences(TestCase):))mock_build.return_value = client- result = ImmichAttributeReferencer().search_references(+ result = ImmichExternalReferencer().search_references(query = 'q', limit = 20,)self.assertEqual(result.results[0].title, 'a1')@@ -128,7 +129,7 @@ class TestSearchReferences(TestCase):client = _make_client(_envelope())mock_build.return_value = client- ImmichAttributeReferencer().search_references(query = 'q', limit = 50)+ ImmichExternalReferencer().search_references(query = 'q', limit = 50)client.search_smart.assert_called_once_with(query = 'q', size = 50)@patch('hi.services.immich.im_referencer.build_client')@@ -137,7 +138,7 @@ class TestSearchReferences(TestCase):# assets wrapper.client = _make_client({'albums': {}})mock_build.return_value = client- result = ImmichAttributeReferencer().search_references(+ result = ImmichExternalReferencer().search_references(query = 'q', limit = 20,)self.assertEqual(result.results, [])@@ -147,7 +148,7 @@ class TestSearchReferences(TestCase):def test_missing_items_inside_assets_yields_empty(self, mock_build):client = _make_client({'assets': {}, 'albums': {}})mock_build.return_value = client- result = ImmichAttributeReferencer().search_references(+ result = ImmichExternalReferencer().search_references(query = 'q', limit = 20,)self.assertEqual(result.results, [])@@ -162,7 +163,7 @@ class TestSearchReferencesErrorMessages(TestCase):@patch('hi.services.immich.im_referencer.build_client',side_effect = IntegrationAttributeError('not configured'))def test_unconfigured_integration(self, _mock_build):- result = ImmichAttributeReferencer().search_references(+ result = ImmichExternalReferencer().search_references(query = 'q', limit = 20,)self.assertEqual(result.results, [])@@ -171,7 +172,7 @@ class TestSearchReferencesErrorMessages(TestCase):@patch('hi.services.immich.im_referencer.build_client',side_effect = RuntimeError('boom in build'))def test_unexpected_client_build_error(self, _mock_build):- result = ImmichAttributeReferencer().search_references(+ result = ImmichExternalReferencer().search_references(query = 'q', limit = 20,)self.assertEqual(result.results, [])@@ -184,7 +185,7 @@ class TestSearchReferencesErrorMessages(TestCase):response.status_code = 401client.search_smart.side_effect = HTTPError('401', response = response)mock_build.return_value = client- result = ImmichAttributeReferencer().search_references(+ result = ImmichExternalReferencer().search_references(query = 'q', limit = 20,)self.assertEqual(result.results, [])@@ -197,7 +198,7 @@ class TestSearchReferencesErrorMessages(TestCase):response.status_code = 403client.search_smart.side_effect = HTTPError('403', response = response)mock_build.return_value = client- result = ImmichAttributeReferencer().search_references(+ result = ImmichExternalReferencer().search_references(query = 'q', limit = 20,)self.assertIn('asset.read', result.error_message)@@ -209,7 +210,7 @@ class TestSearchReferencesErrorMessages(TestCase):response.status_code = 500client.search_smart.side_effect = HTTPError('500', response = response)mock_build.return_value = client- result = ImmichAttributeReferencer().search_references(+ result = ImmichExternalReferencer().search_references(query = 'q', limit = 20,)self.assertIn('500', result.error_message)@@ -219,7 +220,7 @@ class TestSearchReferencesErrorMessages(TestCase):client = _make_client(_envelope())client.search_smart.side_effect = RuntimeError('boom')mock_build.return_value = client- result = ImmichAttributeReferencer().search_references(+ result = ImmichExternalReferencer().search_references(query = 'q', limit = 20,)self.assertEqual(result.results, [])@@ -233,7 +234,7 @@ class TestSearchReferencesErrorMessages(TestCase):# the exception escape to the framework's generic fallback.client = _make_client(_envelope('not-a-dict'))mock_build.return_value = client- result = ImmichAttributeReferencer().search_references(+ result = ImmichExternalReferencer().search_references(query = 'q', limit = 20,)self.assertEqual(result.results, [])@@ -247,43 +248,193 @@ class TestBuildSecondaryText(TestCase):def test_returns_none_when_no_date_no_exif(self):self.assertIsNone(- ImmichAttributeReferencer._build_secondary_text({})+ ImmichExternalReferencer._build_secondary_text({}))def test_date_only(self):- result = ImmichAttributeReferencer._build_secondary_text({+ result = ImmichExternalReferencer._build_secondary_text({'fileCreatedAt': '2025-08-14T10:32:00.000Z',})self.assertEqual(result, '2025-08-14')def test_city_and_country(self):- result = ImmichAttributeReferencer._build_secondary_text({+ result = ImmichExternalReferencer._build_secondary_text({'exifInfo': {'city': 'Portland', 'country': 'USA'},})self.assertEqual(result, 'Portland, USA')def test_city_only(self):- result = ImmichAttributeReferencer._build_secondary_text({+ result = ImmichExternalReferencer._build_secondary_text({'exifInfo': {'city': 'Portland'},})self.assertEqual(result, 'Portland')def test_country_only(self):- result = ImmichAttributeReferencer._build_secondary_text({+ result = ImmichExternalReferencer._build_secondary_text({'exifInfo': {'country': 'USA'},})self.assertEqual(result, 'USA')def test_date_and_place(self):- result = ImmichAttributeReferencer._build_secondary_text({+ result = ImmichExternalReferencer._build_secondary_text({'fileCreatedAt': '2025-08-14T10:32:00.000Z','exifInfo': {'city': 'Portland', 'country': 'USA'},})self.assertEqual(result, '2025-08-14 · Portland, USA')def test_null_exif_treated_as_empty(self):- result = ImmichAttributeReferencer._build_secondary_text({+ result = ImmichExternalReferencer._build_secondary_text({'fileCreatedAt': '2025-08-14T10:32:00.000Z','exifInfo': None,})self.assertEqual(result, '2025-08-14')+++class TestAttachReferences(TestCase):+ """Cover each branch of the defensive thumbnail chain:+ 1. upstream thumbnail succeeds+ 2. upstream thumbnail fails → original succeeds → generate succeeds+ 3. upstream thumbnail fails → original succeeds → generate fails+ 4. upstream thumbnail fails → original fails+ 5. video mime type → skip original fetch entirely+ Plus client-build failure aborts the batch silently.+ """++ def setUp(self):+ from hi.apps.entity.enums import EntityType+ from hi.apps.entity.models import Entity+ self.entity = Entity.objects.create(+ name='Fridge', entity_type_str=str(EntityType.APPLIANCE),+ )+ self.referencer = ImmichExternalReferencer()++ def tearDown(self):+ from hi.integrations.models import EntityExternalReference+ for row in EntityExternalReference.objects.filter(entity=self.entity):+ row.delete()++ def _selection(self, asset_id='uuid-1', title='Fridge plate',+ source_url='https://im.example.com/photos/uuid-1',+ mime_type='image/jpeg'):+ from hi.integrations.referencer.transient_models import (+ ExternalReferenceResult,+ )+ from hi.integrations.transient_models import IntegrationKey+ from hi.services.immich.im_metadata import ImmichMetaData+ return ExternalReferenceResult(+ integration_key=IntegrationKey(+ integration_id=ImmichMetaData.integration_id,+ integration_name=asset_id,+ ),+ title=title,+ source_url=source_url,+ mime_type=mime_type,+ )++ @patch.object(ImmichExternalReferencer, 'build_client')+ def test_upstream_thumbnail_success_attaches_with_upstream_bytes(+ self, mock_build):+ from hi.integrations.models import EntityExternalReference+ client = Mock()+ client.download_thumbnail.return_value = {+ 'content': b'UPSTREAM-PNG', 'mime_type': 'image/png',+ }+ mock_build.return_value = client++ self.referencer.attach_references(self.entity, [self._selection()])++ row = EntityExternalReference.objects.get(+ entity=self.entity, integration_name='uuid-1',+ )+ self.assertTrue(row.thumbnail.name)+ # Original fetch shouldn't have been attempted — upstream+ # thumbnail succeeded.+ client.download_original.assert_not_called()++ @patch.object(ThumbnailHelpers, 'bytes_to_thumbnail_png',+ return_value=b'GENERATED-PNG')+ @patch.object(ImmichExternalReferencer, 'build_client')+ def test_thumbnail_fail_original_succeed_generate_succeed(+ self, mock_build, mock_generate):+ from hi.integrations.models import EntityExternalReference+ client = Mock()+ client.download_thumbnail.side_effect = HTTPError('500')+ client.download_original.return_value = {+ 'content': b'JPEG-RAW', 'mime_type': 'image/jpeg',+ }+ mock_build.return_value = client++ self.referencer.attach_references(self.entity, [self._selection()])++ row = EntityExternalReference.objects.get(+ entity=self.entity, integration_name='uuid-1',+ )+ self.assertTrue(row.thumbnail.name)+ mock_generate.assert_called_once_with(b'JPEG-RAW', 'image/jpeg')++ @patch.object(ThumbnailHelpers, 'bytes_to_thumbnail_png',+ return_value=None)+ @patch.object(ImmichExternalReferencer, 'build_client')+ def test_thumbnail_fail_original_succeed_generate_fail(+ self, mock_build, _mock_generate):+ from hi.integrations.models import EntityExternalReference+ client = Mock()+ client.download_thumbnail.side_effect = HTTPError('500')+ client.download_original.return_value = {+ 'content': b'JPEG-RAW', 'mime_type': 'image/jpeg',+ }+ mock_build.return_value = client++ self.referencer.attach_references(self.entity, [self._selection()])++ row = EntityExternalReference.objects.get(+ entity=self.entity, integration_name='uuid-1',+ )+ self.assertFalse(row.thumbnail)++ @patch.object(ImmichExternalReferencer, 'build_client')+ def test_thumbnail_fail_original_fail_attaches_without_thumbnail(+ self, mock_build):+ from hi.integrations.models import EntityExternalReference+ client = Mock()+ client.download_thumbnail.side_effect = HTTPError('500')+ client.download_original.side_effect = HTTPError('502')+ mock_build.return_value = client++ self.referencer.attach_references(self.entity, [self._selection()])++ row = EntityExternalReference.objects.get(+ entity=self.entity, integration_name='uuid-1',+ )+ self.assertFalse(row.thumbnail)++ @patch.object(ImmichExternalReferencer, 'build_client')+ def test_video_mime_type_skips_original_fetch(self, mock_build):+ # Downloading an entire video just to discover the generator+ # can't make a poster is wasteful. The chain should skip+ # original-fetch for non-image mime types.+ from hi.integrations.models import EntityExternalReference+ client = Mock()+ client.download_thumbnail.side_effect = HTTPError('500')+ mock_build.return_value = client++ self.referencer.attach_references(+ self.entity,+ [self._selection(mime_type='video/mp4')],+ )++ row = EntityExternalReference.objects.get(+ entity=self.entity, integration_name='uuid-1',+ )+ self.assertFalse(row.thumbnail)+ client.download_original.assert_not_called()++ @patch.object(ImmichExternalReferencer, 'build_client',+ side_effect=IntegrationAttributeError('not configured'))+ def test_client_build_failure_aborts_silently(self, _mock_build):+ from hi.integrations.models import EntityExternalReference+ self.referencer.attach_references(self.entity, [self._selection()])+ self.assertEqual(+ EntityExternalReference.objects.filter(entity=self.entity).count(),+ 0,+ )diff --git a/src/hi/services/paperless/enums.py b/src/hi/services/paperless/enums.pyindex 66c94f99..d6a092bf 100644--- a/src/hi/services/paperless/enums.py+++ b/src/hi/services/paperless/enums.py@@ -6,7 +6,7 @@ from hi.integrations.enums import IntegrationAttributeTypeclass PlAttributeType( IntegrationAttributeType ):"""Operator-configurable settings for the paperless integration.- Two required fields drive the entire ATTRIBUTE_REFERENCE surface:+ Two required fields drive the entire EXTERNAL_REFERENCE surface:the base URL of the paperless server (used by the referencer'sHTTP client and by the thumbnail proxy) and the API token sentas ``Authorization: Token <value>`` on every upstream call.diff --git a/src/hi/services/paperless/integration.py b/src/hi/services/paperless/integration.pyindex 2c8a96bf..6c14237e 100644--- a/src/hi/services/paperless/integration.py+++ b/src/hi/services/paperless/integration.py@@ -1,6 +1,6 @@"""Gateway registration entry point for the paperless integration.-ATTRIBUTE_REFERENCE-only: no Connector, no Importer, no monitors.+EXTERNAL_REFERENCE-only: no Connector, no Importer, no monitors.The gateway returns the referencer and answers configuration /access validation; the referencer carries the actual search logic."""@@ -22,7 +22,7 @@ from hi.integrations.transient_models import (from .enums import PlAttributeTypefrom .pl_metadata import PaperlessMetaDatafrom .pl_models import PaperlessApi-from .pl_referencer import PaperlessAttributeReferencer+from .pl_referencer import PaperlessExternalReferencerfrom .pl_validation import validate_attributes@@ -34,8 +34,8 @@ class PaperlessGateway( IntegrationGateway ):def get_metadata( self ) -> IntegrationMetaData:return PaperlessMetaData- def get_attribute_referencer( self ) -> PaperlessAttributeReferencer:- return PaperlessAttributeReferencer()+ def get_external_referencer( self ) -> PaperlessExternalReferencer:+ return PaperlessExternalReferencer()def validate_configuration(self,diff --git a/src/hi/services/paperless/pl_client.py b/src/hi/services/paperless/pl_client.pyindex 37c87b63..a8facbbc 100644--- a/src/hi/services/paperless/pl_client.py+++ b/src/hi/services/paperless/pl_client.py@@ -1,9 +1,9 @@-"""HTTP client for the paperless-ngx ATTRIBUTE_REFERENCE integration.+"""HTTP client for the paperless-ngx EXTERNAL_REFERENCE integration.The client is intentionally small: a single thin wrapper over``requests.Session`` plus a factory that constructs one from thestored ``Integration`` attributes. There is no manager singleton —-ATTRIBUTE_REFERENCE has no monitors and no cached state to own, so+EXTERNAL_REFERENCE has no monitors and no cached state to own, soeach call builds a fresh client from current DB state.The browser-facing thumbnail URL is built by the *referencer*, not@@ -91,6 +91,23 @@ class PaperlessClient:),}+ def download_original( self, document_id : int ) -> Dict[str, Any]:+ """Fetch the per-document original bytes from+ ``/api/documents/<id>/download/``. Returns+ ``{'content': bytes, 'mime_type': str}``. Callers should+ gate this on the mime type to skip formats the framework's+ thumbnail generator can't handle."""+ path = PaperlessApi.DOCUMENT_DOWNLOAD_PATH.format( id = document_id )+ url = urljoin( self.api_url, path )+ response = self._session.get( url, timeout = self._timeout_secs )+ response.raise_for_status()+ return {+ 'content': response.content,+ 'mime_type': response.headers.get(+ 'Content-Type', 'application/octet-stream',+ ),+ }+def build_document_details_url( self, document_id : int ) -> str:"""Per-document web UI URL on the configured paperless server.Persisted as the saved attribute's value so an operatordiff --git a/src/hi/services/paperless/pl_metadata.py b/src/hi/services/paperless/pl_metadata.pyindex fd8f188f..ed631ecd 100644--- a/src/hi/services/paperless/pl_metadata.py+++ b/src/hi/services/paperless/pl_metadata.py@@ -12,7 +12,7 @@ PaperlessMetaData = IntegrationMetaData(label = 'Paperless-ngx',attribute_type = PlAttributeType,# Paperless documents become TEXT attributes on existing- # Entity / Location records via ATTRIBUTE_REFERENCE; the+ # Entity / Location records via EXTERNAL_REFERENCE; the# integration never creates HI Entities of its own, so deletion# behavior is moot. Internal attributes (those created by HI# outside the integration's settings) are not supported here.@@ -20,6 +20,6 @@ PaperlessMetaData = IntegrationMetaData(allow_internal_attributes = False,logo_static_path = 'img/integrations/paperless.png',capabilities = frozenset({- IntegrationCapability.ATTRIBUTE_REFERENCE,+ IntegrationCapability.EXTERNAL_REFERENCE,}),)diff --git a/src/hi/services/paperless/pl_models.py b/src/hi/services/paperless/pl_models.pyindex 3c5264f9..681c673a 100644--- a/src/hi/services/paperless/pl_models.py+++ b/src/hi/services/paperless/pl_models.py@@ -16,6 +16,12 @@ class PaperlessApi:DOCUMENTS_PATH = 'api/documents/'DOCUMENT_THUMB_PATH = 'api/documents/{id}/thumb/'+ # Original-bytes endpoint. Used by attach_references as the+ # fallback when the upstream thumbnail endpoint fails -- the+ # framework's thumbnail generator then makes a small PNG from+ # the original. Only fetched for mime types the generator+ # supports (image + PDF); other document types skip the fetch.+ DOCUMENT_DOWNLOAD_PATH = 'api/documents/{id}/download/'# Per-document web UI route. Used unchanged as the persisted# attribute value; operators clicking the saved link land on# paperless's own page (authenticated by their paperless session,diff --git a/src/hi/services/paperless/pl_referencer.py b/src/hi/services/paperless/pl_referencer.pyindex 94f619e9..a6dd3829 100644--- a/src/hi/services/paperless/pl_referencer.py+++ b/src/hi/services/paperless/pl_referencer.py@@ -1,7 +1,7 @@-"""ATTRIBUTE_REFERENCE implementation for paperless-ngx.+"""EXTERNAL_REFERENCE implementation for paperless-ngx.Translates each paperless documents-search hit into a single-``AttributeReferenceResult``:+``ExternalReferenceResult``:- ``title`` → document title (verbatim)- ``source_url`` → upstream per-document URL on the configured@@ -30,13 +30,15 @@ from requests import HTTPErrorfrom hi.integrations.exceptions import IntegrationAttributeErrorfrom hi.integrations.referencer.integration_referencer import (- IntegrationAttributeReferencer,+ IntegrationExternalReferencer,)from hi.integrations.referencer.transient_models import (- AttributeReferenceResult,- AttributeReferenceSearchResult,+ ExternalReferenceResult,+ ExternalReferenceSearchResult,)+from hi.apps.attribute.thumbnail import ThumbnailHelpersfrom hi.integrations.transient_models import (+ IntegrationKey,IntegrationMetaData,IntegrationValidationResult,)@@ -50,7 +52,7 @@ from .pl_validation import validate_attributeslogger = logging.getLogger(__name__)-class PaperlessAttributeReferencer( IntegrationAttributeReferencer ):+class PaperlessExternalReferencer( IntegrationExternalReferencer ):# Window cap matches the picker's snippet rendering — long# enough to carry useful context, short enough to keep cards@@ -74,20 +76,20 @@ class PaperlessAttributeReferencer( IntegrationAttributeReferencer ):self,query : str,limit : int = 20,- ) -> AttributeReferenceSearchResult:+ ) -> ExternalReferenceSearchResult:if not query or not query.strip():- return AttributeReferenceSearchResult( results = [] )+ return ExternalReferenceSearchResult( results = [] )try:client = build_client()except IntegrationAttributeError as e:logger.warning( f'Paperless search aborted: {e}' )- return AttributeReferenceSearchResult(+ return ExternalReferenceSearchResult(results = [],error_message = 'Paperless integration is not configured.',)except Exception as e:logger.exception( f'Paperless client build failed: {e}' )- return AttributeReferenceSearchResult(+ return ExternalReferenceSearchResult(results = [],error_message = 'Paperless integration error — see server logs.',)@@ -102,7 +104,7 @@ class PaperlessAttributeReferencer( IntegrationAttributeReferencer ):f'Paperless search HTTP {status} for query 'f'{query!r}: {e}')- return AttributeReferenceSearchResult(+ return ExternalReferenceSearchResult(results = [],error_message = self._http_error_message( status ),)@@ -110,19 +112,84 @@ class PaperlessAttributeReferencer( IntegrationAttributeReferencer ):logger.warning(f'Paperless search failed for query {query!r}: {e}')- return AttributeReferenceSearchResult(+ return ExternalReferenceSearchResult(results = [],error_message = 'Paperless search failed — see server logs.',)documents = envelope.get( PaperlessApi.RESPONSE_RESULTS, [] ) or []- return AttributeReferenceSearchResult(+ return ExternalReferenceSearchResult(results = [self._translate( client = client, document = doc, query = query )for doc in documents],)+ # The module-level client factory satisfies the base's+ # ``build_client`` interface directly -- no wrapper method.+ build_client = staticmethod( build_client )++ @staticmethod+ def _try_upstream_thumbnail(+ client : PaperlessClient,+ integration_name : str,+ ) -> Optional[bytes]:+ """Fetch upstream thumbnail bytes; return None on any+ failure. Paperless document ids are integers on the wire but+ are carried as strings through the IntegrationKey."""+ try:+ document_id = int( integration_name )+ except (TypeError, ValueError):+ return None+ try:+ downloaded = client.download_thumbnail( document_id = document_id )+ except Exception as e:+ # Broad catch: this is a best-effort thumbnail fetch.+ # Any failure here (HTTP, network, code bug) should mean+ # "no thumbnail", never "the whole attach failed".+ logger.warning(+ f'Paperless thumbnail unavailable for document '+ f'{integration_name}: {e}'+ )+ return None+ return downloaded.get( 'content' )++ @staticmethod+ def _try_generate_from_original(+ client : PaperlessClient,+ integration_name : str,+ mime_type : str,+ ) -> Optional[bytes]:+ """Pull the original document bytes and ask the framework+ generator for a thumbnail. Gated on mime type to skip+ formats the generator can't handle (office docs, text)+ rather than waste bandwidth on bytes the generator will+ reject."""+ if mime_type not in ThumbnailHelpers.THUMBNAIL_SUPPORTED_MIME_TYPES:+ return None+ try:+ document_id = int( integration_name )+ except (TypeError, ValueError):+ return None+ try:+ downloaded = client.download_original( document_id = document_id )+ except Exception as e:+ # Broad catch: same rationale as ``_try_upstream_thumbnail``+ # -- the original-bytes fallback is best-effort; any+ # failure here means "no thumbnail", never per-selection+ # attach failure.+ logger.warning(+ f'Paperless original-bytes fetch failed for document '+ f'{integration_name}: {e}'+ )+ return None+ original_bytes = downloaded.get( 'content' )+ if not original_bytes:+ return None+ return ThumbnailHelpers.bytes_to_thumbnail_png(+ original_bytes, mime_type,+ )+@staticmethoddef _http_error_message( status : Optional[int] ) -> str:if status in (401, 403):@@ -137,12 +204,16 @@ class PaperlessAttributeReferencer( IntegrationAttributeReferencer ):client : PaperlessClient,document : dict,query : str,- ) -> AttributeReferenceResult:+ ) -> ExternalReferenceResult:document_id = document.get( PaperlessApi.DOC_ID )title = document.get( PaperlessApi.DOC_TITLE ) or ''content = document.get( PaperlessApi.DOC_CONTENT ) or ''mime_type = document.get( PaperlessApi.DOC_MIME_TYPE )- return AttributeReferenceResult(+ return ExternalReferenceResult(+ integration_key = IntegrationKey(+ integration_id = PaperlessMetaData.integration_id,+ integration_name = str( document_id ),+ ),title = title,source_url = client.build_document_details_url( document_id ),thumbnail_url = self._proxy_thumbnail_url( document_id ),diff --git a/src/hi/services/paperless/tests/test_pl_gateway.py b/src/hi/services/paperless/tests/test_pl_gateway.pyindex 8c9a7e11..4620ca35 100644--- a/src/hi/services/paperless/tests/test_pl_gateway.py+++ b/src/hi/services/paperless/tests/test_pl_gateway.py@@ -18,7 +18,7 @@ from hi.integrations.transient_models import IntegrationKeyfrom hi.services.paperless.enums import PlAttributeTypefrom hi.services.paperless.integration import PaperlessGatewayfrom hi.services.paperless.pl_metadata import PaperlessMetaData-from hi.services.paperless.pl_referencer import PaperlessAttributeReferencer+from hi.services.paperless.pl_referencer import PaperlessExternalReferencerlogging.disable(logging.CRITICAL)@@ -41,16 +41,16 @@ def _make_attr(integration, attr_type, value):class TestPaperlessGatewayWiring(TestCase):- def test_metadata_declares_attribute_reference(self):+ def test_metadata_declares_external_reference(self):meta = PaperlessGateway().get_metadata()self.assertEqual(meta.integration_id, 'paperless')self.assertEqual(meta.label, 'Paperless-ngx')- self.assertIn(IntegrationCapability.ATTRIBUTE_REFERENCE,+ self.assertIn(IntegrationCapability.EXTERNAL_REFERENCE,meta.capabilities)def test_returns_referencer(self):- referencer = PaperlessGateway().get_attribute_referencer()- self.assertIsInstance(referencer, PaperlessAttributeReferencer)+ referencer = PaperlessGateway().get_external_referencer()+ self.assertIsInstance(referencer, PaperlessExternalReferencer)class TestValidateAccess(TestCase):diff --git a/src/hi/services/paperless/tests/test_pl_referencer.py b/src/hi/services/paperless/tests/test_pl_referencer.pyindex 6ef6df33..a37d1517 100644--- a/src/hi/services/paperless/tests/test_pl_referencer.py+++ b/src/hi/services/paperless/tests/test_pl_referencer.py@@ -1,9 +1,9 @@-"""Tests for the ATTRIBUTE_REFERENCE referencer.+"""Tests for the EXTERNAL_REFERENCE referencer.Covers the two surfaces that matter for picker UX: snippetextraction (window around the matched query, with paperless-stylefallbacks when no match) and the end-to-end translation of a-paperless documents-search response into AttributeReferenceResult+paperless documents-search response into ExternalReferenceResultrows the framework can hand to the picker."""import logging@@ -19,7 +19,8 @@ from hi.integrations.transient_models import IntegrationKeyfrom hi.services.paperless.enums import PlAttributeTypefrom hi.services.paperless.pl_metadata import PaperlessMetaData-from hi.services.paperless.pl_referencer import PaperlessAttributeReferencer+from hi.apps.attribute.thumbnail import ThumbnailHelpers+from hi.services.paperless.pl_referencer import PaperlessExternalReferencerlogging.disable(logging.CRITICAL)@@ -47,21 +48,21 @@ class TestSnippetExtraction(TestCase):# Empty content => omit the snippet row entirely in the# picker rather than render an empty placeholder.self.assertIsNone(- PaperlessAttributeReferencer._extract_snippet(+ PaperlessExternalReferencer._extract_snippet(content = '', query = 'q',))def test_short_content_returned_verbatim(self):self.assertEqual(- PaperlessAttributeReferencer._extract_snippet(+ PaperlessExternalReferencer._extract_snippet(content = 'Short doc text.', query = 'missing',),'Short doc text.',)def test_long_content_without_match_truncates(self):- result = PaperlessAttributeReferencer._extract_snippet(+ result = PaperlessExternalReferencer._extract_snippet(content = 'A' * 500, query = 'missing',)self.assertLessEqual(len(result), 161) # 160 + the ellipsis@@ -69,7 +70,7 @@ class TestSnippetExtraction(TestCase):def test_match_in_middle_emits_leading_and_trailing_ellipses(self):content = 'x' * 200 + ' DISHWASHER ' + 'y' * 200- result = PaperlessAttributeReferencer._extract_snippet(+ result = PaperlessExternalReferencer._extract_snippet(content = content, query = 'dishwasher',)self.assertIn('DISHWASHER', result)@@ -77,13 +78,13 @@ class TestSnippetExtraction(TestCase):self.assertTrue(result.endswith('…'))def test_match_at_start_no_leading_ellipsis(self):- result = PaperlessAttributeReferencer._extract_snippet(+ result = PaperlessExternalReferencer._extract_snippet(content = 'Warranty info follows.', query = 'warranty',)self.assertFalse(result.startswith('…'))def test_case_insensitive_match(self):- result = PaperlessAttributeReferencer._extract_snippet(+ result = PaperlessExternalReferencer._extract_snippet(content = 'The DISHWASHER manual.', query = 'dishwasher',)self.assertIn('DISHWASHER', result)@@ -93,7 +94,7 @@ class TestSearchReferences(TestCase):"""End-to-end search via a mocked PaperlessClient."""def setUp(self):- self.referencer = PaperlessAttributeReferencer()+ self.referencer = PaperlessExternalReferencer()def _envelope(self, *docs):return {'count': len(docs), 'results': list(docs)}@@ -192,7 +193,7 @@ class TestSearchReferencesErrorMessages(TestCase):to "no results."""def setUp(self):- self.referencer = PaperlessAttributeReferencer()+ self.referencer = PaperlessExternalReferencer()@patch('hi.services.paperless.pl_referencer.build_client',side_effect = IntegrationAttributeError('not configured'))@@ -257,7 +258,7 @@ class TestValidateConfiguration(TestCase):'https://paperless.example.com/'),_make_attr(self.integration, PlAttributeType.API_TOKEN, 'token'),]- result = PaperlessAttributeReferencer().validate_configuration(attrs)+ result = PaperlessExternalReferencer().validate_configuration(attrs)self.assertTrue(result.is_valid)def test_error_when_token_missing(self):@@ -265,5 +266,183 @@ class TestValidateConfiguration(TestCase):_make_attr(self.integration, PlAttributeType.API_URL,'https://paperless.example.com/'),]- result = PaperlessAttributeReferencer().validate_configuration(attrs)+ result = PaperlessExternalReferencer().validate_configuration(attrs)self.assertFalse(result.is_valid)+++class TestAttachReferences(TestCase):+ """End-to-end attach via a mocked PaperlessClient and a real+ Entity. Verifies the framework row is created and that the+ defensive thumbnail-fetch chain handles each failure mode+ gracefully (linking is the primary user goal)."""++ def setUp(self):+ from hi.apps.entity.enums import EntityType+ from hi.apps.entity.models import Entity+ self.entity = Entity.objects.create(+ name='Fridge', entity_type_str=str(EntityType.APPLIANCE),+ )+ self.referencer = PaperlessExternalReferencer()++ def tearDown(self):+ from hi.integrations.models import EntityExternalReference+ for row in EntityExternalReference.objects.filter(entity=self.entity):+ row.delete()++ def _selection(self, doc_id='42', title='Warranty',+ source_url='https://p.example.com/documents/42/details/',+ mime_type='application/pdf'):+ from hi.integrations.referencer.transient_models import (+ ExternalReferenceResult,+ )+ return ExternalReferenceResult(+ integration_key=IntegrationKey(+ integration_id=PaperlessMetaData.integration_id,+ integration_name=doc_id,+ ),+ title=title,+ source_url=source_url,+ mime_type=mime_type,+ )++ @patch.object(PaperlessExternalReferencer, 'build_client')+ def test_happy_path_creates_row_with_thumbnail(self, mock_build):+ from hi.integrations.models import EntityExternalReference+ client = Mock()+ client.download_thumbnail.return_value = {+ 'content': b'PNG-BYTES', 'mime_type': 'image/png',+ }+ mock_build.return_value = client++ self.referencer.attach_references(+ self.entity, [self._selection(doc_id='42')],+ )++ row = EntityExternalReference.objects.get(+ entity=self.entity,+ integration_id='paperless',+ integration_name='42',+ )+ self.assertEqual(row.title, 'Warranty')+ self.assertTrue(row.thumbnail.name)++ @patch.object(PaperlessExternalReferencer, 'build_client')+ def test_thumbnail_fail_original_fail_attaches_without_thumbnail(+ self, mock_build):+ from hi.integrations.models import EntityExternalReference+ client = Mock()+ client.download_thumbnail.side_effect = HTTPError('500')+ client.download_original.side_effect = HTTPError('502')+ mock_build.return_value = client++ self.referencer.attach_references(+ self.entity, [self._selection(doc_id='99')],+ )++ row = EntityExternalReference.objects.get(+ entity=self.entity, integration_name='99',+ )+ self.assertFalse(row.thumbnail)++ @patch.object(ThumbnailHelpers, 'bytes_to_thumbnail_png',+ return_value=b'GENERATED-PNG')+ @patch.object(PaperlessExternalReferencer, 'build_client')+ def test_thumbnail_fail_original_succeed_generate_succeed(+ self, mock_build, mock_generate):+ from hi.integrations.models import EntityExternalReference+ client = Mock()+ client.download_thumbnail.side_effect = HTTPError('500')+ client.download_original.return_value = {+ 'content': b'PDF-RAW', 'mime_type': 'application/pdf',+ }+ mock_build.return_value = client++ self.referencer.attach_references(+ self.entity, [self._selection(doc_id='99')],+ )++ row = EntityExternalReference.objects.get(+ entity=self.entity, integration_name='99',+ )+ self.assertTrue(row.thumbnail.name)+ mock_generate.assert_called_once_with(b'PDF-RAW', 'application/pdf')++ @patch.object(ThumbnailHelpers, 'bytes_to_thumbnail_png',+ return_value=None)+ @patch.object(PaperlessExternalReferencer, 'build_client')+ def test_thumbnail_fail_original_succeed_generate_fail(+ self, mock_build, _mock_generate):+ from hi.integrations.models import EntityExternalReference+ client = Mock()+ client.download_thumbnail.side_effect = HTTPError('500')+ client.download_original.return_value = {+ 'content': b'PDF-RAW', 'mime_type': 'application/pdf',+ }+ mock_build.return_value = client++ self.referencer.attach_references(+ self.entity, [self._selection(doc_id='99')],+ )++ row = EntityExternalReference.objects.get(+ entity=self.entity, integration_name='99',+ )+ self.assertFalse(row.thumbnail)++ @patch.object(PaperlessExternalReferencer, 'build_client')+ def test_unsupported_mime_skips_original_fetch(self, mock_build):+ # Office docs / text / etc. the generator can't handle should+ # not trigger an original-bytes download just to discover the+ # generator will reject the bytes.+ from hi.integrations.models import EntityExternalReference+ client = Mock()+ client.download_thumbnail.side_effect = HTTPError('500')+ mock_build.return_value = client++ self.referencer.attach_references(+ self.entity,+ [self._selection(doc_id='99',+ mime_type='application/vnd.oasis.opendocument.text')],+ )++ row = EntityExternalReference.objects.get(+ entity=self.entity, integration_name='99',+ )+ self.assertFalse(row.thumbnail)+ client.download_original.assert_not_called()++ @patch.object(PaperlessExternalReferencer, 'build_client',+ side_effect=IntegrationAttributeError('not configured'))+ def test_client_build_failure_aborts_silently(self, _mock_build):+ from hi.integrations.models import EntityExternalReference+ self.referencer.attach_references(+ self.entity, [self._selection()],+ )+ self.assertEqual(+ EntityExternalReference.objects.filter(entity=self.entity).count(),+ 0,+ )++ @patch.object(PaperlessExternalReferencer, 'build_client')+ def test_per_selection_exception_does_not_abort_batch(self, mock_build):+ from hi.integrations.models import EntityExternalReference+ # First selection has a non-numeric doc id; _try_upstream_thumbnail+ # returns None on the int cast, so the row still attaches. The+ # second selection succeeds normally. Verifies both end up+ # persisted.+ client = Mock()+ client.download_thumbnail.return_value = {+ 'content': b'PNG', 'mime_type': 'image/png',+ }+ mock_build.return_value = client++ self.referencer.attach_references(+ self.entity, [+ self._selection(doc_id='not-numeric'),+ self._selection(doc_id='7'),+ ],+ )+ self.assertEqual(+ EntityExternalReference.objects.filter(entity=self.entity).count(),+ 2,+ )diff --git a/src/hi/services/paperless/urls.py b/src/hi/services/paperless/urls.pyindex 2a02cfda..18e1cde0 100644--- a/src/hi/services/paperless/urls.py+++ b/src/hi/services/paperless/urls.py@@ -2,7 +2,7 @@Mounts under ``services/paperless/`` via the framework'sauto-discovery (see hi/integrations/urls.py). One route: a thumbnail-proxy used by the ATTRIBUTE_REFERENCE picker so browser-rendered+proxy used by the EXTERNAL_REFERENCE picker so browser-rendered<img> tags can fetch paperless thumbnails through HI's sessioninstead of requiring the upstream paperless API token."""diff --git a/src/hi/settings/base.py b/src/hi/settings/base.pyindex 7782e6f5..26802a72 100644--- a/src/hi/settings/base.py+++ b/src/hi/settings/base.py@@ -295,7 +295,8 @@ PIPELINE = {'js/video-timeline.js','js/attr.js','js/attr-dirty-tracking.js',- 'js/attr-picker.js',+ 'js/external-reference-picker.js',+ 'js/external-references.js',),'output_filename': 'js/js_hi_grid_header_content.js',},diff --git a/src/hi/simulator/services/immich/simulator.py b/src/hi/simulator/services/immich/simulator.pyindex 397267a7..489b872a 100644--- a/src/hi/simulator/services/immich/simulator.py+++ b/src/hi/simulator/services/immich/simulator.py@@ -1,6 +1,6 @@"""Immich simulator: parametric smart-search responses.-Contributes only the ATTRIBUTE_REFERENCE capability -- TEXT+Contributes only the EXTERNAL_REFERENCE capability -- TEXTattributes on existing Entity / Location records, no SimEntities ofits own. Search results are generated on the fly, shaped byoperator-tuned knobs on the singleton.@@ -13,20 +13,55 @@ Knobs:- result_count : how many assets each smart search returns(0/1/3/10/50 -- exercises empty / single / multipicker rendering paths).+ - mime_mix : which mime-type mix populates result rows+ (images only, videos only, mixed). Drives the+ ``_try_generate_from_original`` branch in the+ referencer -- only image mimes pull original+ bytes; video mimes skip that fetch.- include_exif : whether generated assets carry EXIF city /country (drives the snippet on / off path in thereferencer's ``_build_secondary_text``).- - latency_ms : artificial latency on the smart-search endpoint,- for surfacing debounce or loading issues in the- picker.+ - thumbnails : whether ``/api/assets/<id>/thumbnail`` serves a+ PNG placeholder (when off the endpoint 404s and+ HI falls back to the ``/api/assets/<id>/original``+ bytes-to-thumbnail-png pipeline -- which produces+ a HI-generated thumbnail with a different visual+ so the operator can tell which path produced the+ saved card's image). To exercise the full+ no-thumbnail path (mime fallback icon on the+ card), force a ``ServiceFaultMode.SERVER_ERROR``+ so all endpoints fail.++Artificial latency is intentionally NOT a knob here -- the+framework ``ServiceFaultMode`` already exposes a ``SLOW`` mode that+covers the same operator need without per-simulator duplication."""from dataclasses import dataclass+from enum import Enumfrom typing import Dict, Listfrom hi.simulator.services.base_models import SimEntityDefinitionfrom hi.simulator.services.service_simulator import ServiceSimulator+class MimeMix( Enum ):+ """Which mime types populate generated search results. Drives+ the referencer's image-vs-video gating through different code+ branches."""++ IMAGE_ONLY = 'Images only'+ VIDEO_ONLY = 'Videos only'+ MIXED = 'Mixed'++ @classmethod+ def default(cls) -> 'MimeMix':+ return cls.MIXED++ @property+ def label(self) -> str:+ return self.value++# Discrete result counts the operator can pick; exercises distinct# picker rendering paths.RESULT_COUNT_CHOICES = ( 0, 1, 3, 10, 50 )@@ -37,9 +72,10 @@ class ImmichSimSettings:"""Knobs that parametrize every response. Held on theImmichSimulator singleton; ephemeral."""- result_count : int = 3- include_exif : bool = True- latency_ms : int = 0+ result_count : int = 3+ mime_mix : MimeMix = MimeMix.MIXED+ include_exif : bool = True+ thumbnails : bool = Trueclass ImmichSimulator( ServiceSimulator ):@@ -84,4 +120,5 @@ class ImmichSimulator( ServiceSimulator ):return {'settings' : self._settings,'result_count_choices' : RESULT_COUNT_CHOICES,+ 'mime_mix_choices' : list( MimeMix ),}diff --git a/src/hi/simulator/services/immich/templates/immich/pages/photo_preview.html b/src/hi/simulator/services/immich/templates/immich/pages/photo_preview.htmlindex e954a2dd..b71a9b7d 100644--- a/src/hi/simulator/services/immich/templates/immich/pages/photo_preview.html+++ b/src/hi/simulator/services/immich/templates/immich/pages/photo_preview.html@@ -12,6 +12,6 @@<body><div class="asset-id">Photo {{ asset_id }}</div><p>This is the Immich simulator's stand-in for the per-asset view. The real Immich web UI would show the photo, EXIF, albums, and tags here.</p>- <p class="hint">Source URLs from the ATTRIBUTE_REFERENCE picker link to pages like this one; close the tab to return to the picker modal.</p>+ <p class="hint">Source URLs from the EXTERNAL_REFERENCE picker link to pages like this one; close the tab to return to the picker modal.</p></body></html>diff --git a/src/hi/simulator/services/immich/templates/immich/panes/settings_form.html b/src/hi/simulator/services/immich/templates/immich/panes/settings_form.htmlindex 2bd2db4a..43794e97 100644--- a/src/hi/simulator/services/immich/templates/immich/panes/settings_form.html+++ b/src/hi/simulator/services/immich/templates/immich/panes/settings_form.html@@ -6,6 +6,7 @@Context:settings : ImmichSimSettingsresult_count_choices : tuple[int]+ mime_mix_choices : list[MimeMix]{% endcomment %}<form id="hi-immich-settings-form"method="post"@@ -34,20 +35,35 @@</div><div class="form-group col-auto">- <label for="hi-immich-latency" class="small text-muted mb-1">- Latency (ms)+ <label for="hi-immich-mime-mix" class="small text-muted mb-1">+ Mime mix</label>- <input type="number"- id="hi-immich-latency"- name="latency_ms"- value="{{ settings.latency_ms }}"- min="0" max="10000" step="50"- class="form-control form-control-sm"- style="width: 8em;"- onchange="this.form.requestSubmit ? this.form.requestSubmit() : this.form.submit()">+ <select id="hi-immich-mime-mix"+ name="mime_mix"+ class="form-control form-control-sm"+ onchange="this.form.requestSubmit ? this.form.requestSubmit() : this.form.submit()">+ {% for choice in mime_mix_choices %}+ <option value="{{ choice.name }}"+ {% if choice == settings.mime_mix %}selected{% endif %}>+ {{ choice.label }}+ </option>+ {% endfor %}+ </select></div><div class="form-group col-auto mb-0">+ <div class="form-check">+ <input type="checkbox"+ id="hi-immich-thumbnails"+ name="thumbnails"+ value="on"+ class="form-check-input"+ {% if settings.thumbnails %}checked{% endif %}+ onchange="this.form.requestSubmit ? this.form.requestSubmit() : this.form.submit()">+ <label class="form-check-label small" for="hi-immich-thumbnails">+ Thumbnails+ </label>+ </div><div class="form-check"><input type="checkbox"id="hi-immich-include-exif"diff --git a/src/hi/simulator/services/immich/urls.py b/src/hi/simulator/services/immich/urls.pyindex e69ba670..510f1d57 100644--- a/src/hi/simulator/services/immich/urls.py+++ b/src/hi/simulator/services/immich/urls.py@@ -17,6 +17,10 @@ urlpatterns = [views.ThumbnailView.as_view(),name = 'immich_asset_thumbnail' ),+ path( 'api/assets/<str:asset_id>/original',+ views.OriginalView.as_view(),+ name = 'immich_asset_original' ),+path( 'photos/<str:asset_id>',views.PhotoPreviewView.as_view(),name = 'immich_photo_preview' ),diff --git a/src/hi/simulator/services/immich/views.py b/src/hi/simulator/services/immich/views.pyindex 7a850ed4..9a44fd12 100644--- a/src/hi/simulator/services/immich/views.py+++ b/src/hi/simulator/services/immich/views.py@@ -22,9 +22,9 @@ these views do not inspect the ``x-api-key`` header themselves."""import hashlibimport json-import timefrom dataclasses import replacefrom datetime import datetime, timezone+from io import BytesIOfrom typing import List, Optionalfrom django.core.exceptions import BadRequest@@ -33,10 +33,12 @@ from django.shortcuts import renderfrom django.utils.decorators import method_decoratorfrom django.views import Viewfrom django.views.decorators.csrf import csrf_exempt+from PIL import Image, ImageDrawfrom .simulator import (ImmichSimSettings,ImmichSimulator,+ MimeMix,RESULT_COUNT_CHOICES,)@@ -51,6 +53,25 @@ _CITY_COUNTRY_CYCLE = (( None, None ), # exercise the no-EXIF row)+# Per-mime-mix palette of (mime_type, asset_type, file_extension).+# IMAGE assets cycle through real-world Immich image formats; VIDEO+# assets are mp4 (the most common). MIXED alternates per index so a+# single result page surfaces both card types.+_MIME_PALETTE = {+ MimeMix.IMAGE_ONLY: (+ ( 'image/jpeg', 'IMAGE', 'jpg' ),+ ( 'image/png', 'IMAGE', 'png' ),+ ),+ MimeMix.VIDEO_ONLY: (+ ( 'video/mp4', 'VIDEO', 'mp4' ),+ ),+ MimeMix.MIXED: (+ ( 'image/jpeg', 'IMAGE', 'jpg' ),+ ( 'video/mp4', 'VIDEO', 'mp4' ),+ ( 'image/png', 'IMAGE', 'png' ),+ ),+}+def _stable_asset_id( query : str, index : int ) -> str:"""Map (query, index) to a stable UUID-shaped string. Different@@ -63,6 +84,14 @@ def _stable_asset_id( query : str, index : int ) -> str:)+def _pick_mime( mix : MimeMix, index : int ):+ """Deterministic per-index palette pick. Cycles through the+ palette so a multi-result page rendered with MIXED visits each+ type. Returns ``(mime_type, asset_type, file_extension)``."""+ palette = _MIME_PALETTE[ mix ]+ return palette[ index % len(palette) ]++def _generate_assets(settings : ImmichSimSettings, query : str,) -> List[dict]:@@ -73,14 +102,18 @@ def _generate_assets(assets = []for index in range( settings.result_count ):asset_id = _stable_asset_id( query or '', index )+ mime_type, asset_type, extension = _pick_mime(+ settings.mime_mix, index,+ )# Filename bakes in the query so operators can visually trace# what was searched.- filename = f'{(query or "asset").strip().replace(" ", "-")}-{index + 1}.jpg'+ stem = (query or "asset").strip().replace(" ", "-")+ filename = f'{stem}-{index + 1}.{extension}'asset = {'id' : asset_id,'originalFileName' : filename,- 'originalMimeType' : 'image/jpeg',- 'type' : 'IMAGE',+ 'originalMimeType' : mime_type,+ 'type' : asset_type,'fileCreatedAt' : now_iso,}if settings.include_exif:@@ -121,8 +154,6 @@ class SmartSearchView( View ):def post( self, request, *args, **kwargs ):simulator = ImmichSimulator()settings = simulator.settings- if settings.latency_ms > 0:- time.sleep( settings.latency_ms / 1000.0 )# Body is JSON: {"query": "...", "size": N}. Query is read for# stable id generation and filename baking only; size isn't# honored because the operator-chosen result_count is the@@ -147,25 +178,78 @@ class MetadataSearchView( View ):return JsonResponse( _search_envelope( assets = [] ))-def _thumbnail_svg( asset_id : str ) -> bytes:- short = asset_id.split('-')[0]- return (- f'<svg xmlns="http://www.w3.org/2000/svg" width="160" height="160" '- f'viewBox="0 0 160 160">'- f'<rect width="160" height="160" fill="#cfe2ff" stroke="#0d6efd"/>'- f'<text x="80" y="86" text-anchor="middle" font-family="sans-serif" '- f'font-size="18" fill="#084298">{short}</text>'- f'</svg>'- ).encode('utf-8')+def _thumbnail_png( asset_id : str ) -> bytes:+ """Tiny PNG placeholder generated with Pillow. Real Immich+ returns a raster image from this endpoint; matching that lets+ the framework's attach-time bytes-to-file write produce a file+ the browser can later decode (the manager hard-codes the saved+ filename's extension to ``.png``)."""+ short = asset_id.split('-')[0] if asset_id else 'asset'+ img = Image.new( 'RGB', ( 160, 160 ), ( 207, 226, 255 ))+ draw = ImageDraw.Draw( img )+ text_box = draw.textbbox( ( 0, 0 ), short )+ text_w = text_box[2] - text_box[0]+ text_h = text_box[3] - text_box[1]+ draw.text(+ ( (160 - text_w) // 2, (160 - text_h) // 2 ),+ short, fill = ( 8, 66, 152 ),+ )+ buf = BytesIO()+ img.save( buf, format = 'PNG' )+ return buf.getvalue()class ThumbnailView( View ):+ """``GET /api/assets/<id>/thumbnail`` -- serves a PNG placeholder+ when thumbnails are enabled; 404s otherwise so HI's no-thumbnail+ fallback can be exercised."""++ def get( self, request, *args, **kwargs ):+ simulator = ImmichSimulator()+ if not simulator.settings.thumbnails:+ return HttpResponse( status = 404 )+ asset_id = kwargs.get( 'asset_id' ) or ''+ return HttpResponse(+ _thumbnail_png( asset_id ),+ content_type = 'image/png',+ )+++def _original_png( asset_id : str ) -> bytes:+ """Real PNG bytes for the original-asset endpoint. Larger than+ the thumbnail placeholder and orange-tinted so a HI-generated+ thumbnail produced from these bytes is visually distinguishable+ from the blue upstream thumbnail when the operator toggles+ ``thumbnails`` off to exercise the fallback path."""+ short = asset_id.split('-')[0] if asset_id else 'asset'+ img = Image.new( 'RGB', ( 640, 480 ), ( 255, 224, 178 ))+ draw = ImageDraw.Draw( img )+ label = f'original\n{short}'+ text_box = draw.multiline_textbbox( ( 0, 0 ), label )+ text_w = text_box[2] - text_box[0]+ text_h = text_box[3] - text_box[1]+ draw.multiline_text(+ ( (640 - text_w) // 2, (480 - text_h) // 2 ),+ label, fill = ( 230, 81, 0 ), align = 'center',+ )+ buf = BytesIO()+ img.save( buf, format = 'PNG' )+ return buf.getvalue()+++class OriginalView( View ):+ """``GET /api/assets/<id>/original`` -- always-on PNG. HI's+ referencer hits this as the defensive fallback when the+ thumbnail endpoint is unavailable; serving real bytes here lets+ operators exercise the HI-generated thumbnail path (turn+ ``thumbnails`` off, attach an image asset, see a HI-generated+ thumbnail on the saved card)."""def get( self, request, *args, **kwargs ):asset_id = kwargs.get( 'asset_id' ) or ''return HttpResponse(- _thumbnail_svg( asset_id ),- content_type = 'image/svg+xml',+ _original_png( asset_id ),+ content_type = 'image/png',)@@ -199,11 +283,14 @@ class SetSettingsView( View ):result_count = self._parse_result_count(request.POST.get( 'result_count' ), current.result_count,),+ mime_mix = self._parse_mime_mix(+ request.POST.get( 'mime_mix' ),+ ),include_exif = self._parse_bool(request.POST.get( 'include_exif' ),),- latency_ms = self._parse_latency_ms(- request.POST.get( 'latency_ms' ), current.latency_ms,+ thumbnails = self._parse_bool(+ request.POST.get( 'thumbnails' ),),)simulator.set_settings( new_settings )@@ -213,6 +300,7 @@ class SetSettingsView( View ):{'settings' : new_settings,'result_count_choices' : RESULT_COUNT_CHOICES,+ 'mime_mix_choices' : list( MimeMix ),},)@@ -226,6 +314,13 @@ class SetSettingsView( View ):raise BadRequest( f'Invalid result_count: {raw!r}' )return value+ @staticmethod+ def _parse_mime_mix( raw : Optional[str] ) -> MimeMix:+ try:+ return MimeMix[ raw ]+ except (KeyError, TypeError):+ raise BadRequest( f'Invalid mime_mix: {raw!r}' )+@staticmethoddef _parse_bool( raw : Optional[str] ) -> bool:# An unchecked checkbox is absent from the POST body, so the@@ -233,16 +328,6 @@ class SetSettingsView( View ):# the signal.return bool( raw )- @staticmethod- def _parse_latency_ms( raw : Optional[str], fallback : int ) -> int:- try:- value = int( raw )- except (TypeError, ValueError):- return fallback- if value < 0 or value > 10000:- raise BadRequest( f'latency_ms out of range: {raw!r}' )- return value-# ---- helpers ----------------------------------------------------diff --git a/src/hi/simulator/services/paperless/simulator.py b/src/hi/simulator/services/paperless/simulator.pyindex b910f48b..b00ca84d 100644--- a/src/hi/simulator/services/paperless/simulator.py+++ b/src/hi/simulator/services/paperless/simulator.py@@ -2,7 +2,7 @@Unlike the entity-shaped simulators (HASS, HomeBox, ZoneMinder),paperless-ngx has no 1-to-1 mapping onto HI Entities — its-contribution is the ATTRIBUTE_REFERENCE capability, which produces+contribution is the EXTERNAL_REFERENCE capability, which producesTEXT attributes on existing Entity / Location records, not newentities. So this simulator has no SimEntities and no persistentcorpus. Instead it generates synthetic search results on the fly,@@ -14,15 +14,22 @@ singleton:rendering paths)- mime_mix : which mime-type mix populates result rows (PDFonly, images only, plain text only, or mixed)- - thumbnails : whether the simulator's- ``/api/documents/<id>/thumb/`` endpoint serves- a thumbnail (when off, the endpoint 404s and- the picker falls back to its icon)+ - thumbnails : whether ``/api/documents/<id>/thumb/`` serves+ a thumbnail (when off the endpoint 404s and HI+ falls back to the ``/api/documents/<id>/download/``+ original-bytes -> pdf2image -> thumbnail+ pipeline -- which produces a HI-generated+ thumbnail visually distinguishable from the+ upstream placeholder). To exercise the full+ no-thumbnail path (mime fallback icon on the+ card), force a ``ServiceFaultMode.SERVER_ERROR``+ so all endpoints fail.- snippets : whether each result carries a content snippet(exercises picker layout with / without it)- - latency_ms : artificial latency on the documents-list- endpoint, for surfacing any debounce or- loading-state issues in the picker++Artificial latency is intentionally NOT a knob here -- the+framework ``ServiceFaultMode`` already exposes a ``SLOW`` mode that+covers the same operator need without per-simulator duplication.Settings live in memory on the singleton (same lifecycle asHomeBox's ``_api_version``) — lost on server restart, survives@@ -70,7 +77,6 @@ class PaperlessSimSettings:mime_mix : MimeMix = MimeMix.MIXEDthumbnails : bool = Truesnippets : bool = True- latency_ms : int = 0class PaperlessSimulator( ServiceSimulator ):@@ -108,7 +114,7 @@ class PaperlessSimulator( ServiceSimulator ):@propertydef sim_entity_definition_list(self) -> List[ SimEntityDefinition ]:- # Paperless contributes only via ATTRIBUTE_REFERENCE — no+ # Paperless contributes only via EXTERNAL_REFERENCE — no# SimEntity rows ever, so the service page's entity-list# area renders empty. The extras pane carries the operator# UI.diff --git a/src/hi/simulator/services/paperless/templates/paperless/pages/document_preview.html b/src/hi/simulator/services/paperless/templates/paperless/pages/document_preview.htmlindex 41055134..fabe495b 100644--- a/src/hi/simulator/services/paperless/templates/paperless/pages/document_preview.html+++ b/src/hi/simulator/services/paperless/templates/paperless/pages/document_preview.html@@ -12,6 +12,6 @@<body><div class="doc-id">Document #{{ document_id }}</div><p>This is the paperless-ngx simulator's stand-in for the per-document view. The real paperless web UI would show the document's metadata and content here.</p>- <p class="hint">Source URLs from the ATTRIBUTE_REFERENCE picker link to pages like this one; close the tab to return to the picker modal.</p>+ <p class="hint">Source URLs from the EXTERNAL_REFERENCE picker link to pages like this one; close the tab to return to the picker modal.</p></body></html>diff --git a/src/hi/simulator/services/paperless/templates/paperless/panes/settings_form.html b/src/hi/simulator/services/paperless/templates/paperless/panes/settings_form.htmlindex 069e16d4..e6ff8d44 100644--- a/src/hi/simulator/services/paperless/templates/paperless/panes/settings_form.html+++ b/src/hi/simulator/services/paperless/templates/paperless/panes/settings_form.html@@ -56,20 +56,6 @@</select></div>- <div class="form-group col-auto">- <label for="hi-paperless-latency" class="small text-muted mb-1">- Latency (ms)- </label>- <input type="number"- id="hi-paperless-latency"- name="latency_ms"- value="{{ settings.latency_ms }}"- min="0" max="10000" step="50"- class="form-control form-control-sm"- style="width: 8em;"- onchange="this.form.requestSubmit ? this.form.requestSubmit() : this.form.submit()">- </div>-<div class="form-group col-auto mb-0"><div class="form-check"><input type="checkbox"diff --git a/src/hi/simulator/services/paperless/urls.py b/src/hi/simulator/services/paperless/urls.pyindex c406c738..9b7df2c5 100644--- a/src/hi/simulator/services/paperless/urls.py+++ b/src/hi/simulator/services/paperless/urls.py@@ -13,6 +13,10 @@ urlpatterns = [views.ThumbnailView.as_view(),name = 'paperless_document_thumbnail' ),+ path( 'api/documents/<int:document_id>/download/',+ views.DownloadView.as_view(),+ name = 'paperless_document_download' ),+path( 'documents/<int:document_id>/details/',views.PreviewView.as_view(),name = 'paperless_document_preview' ),diff --git a/src/hi/simulator/services/paperless/views.py b/src/hi/simulator/services/paperless/views.pyindex 464f913c..29c6cbeb 100644--- a/src/hi/simulator/services/paperless/views.py+++ b/src/hi/simulator/services/paperless/views.py@@ -20,15 +20,16 @@ Three endpoint families:"""import hashlibimport random-import timefrom dataclasses import replacefrom datetime import datetime, timezone+from io import BytesIOfrom typing import List, Optionalfrom django.core.exceptions import BadRequestfrom django.http import HttpResponse, JsonResponsefrom django.shortcuts import renderfrom django.views import View+from PIL import Image, ImageDrawfrom .simulator import (MimeMix,@@ -144,8 +145,6 @@ class DocumentsListView( View ):def get( self, request, *args, **kwargs ):simulator = PaperlessSimulator()settings = simulator.settings- if settings.latency_ms > 0:- time.sleep( settings.latency_ms / 1000.0 )query = request.GET.get( 'query', '' ).strip()results = _generate_results( settings, query )# Mirrors the DRF pagination envelope the real paperless@@ -159,21 +158,31 @@ class DocumentsListView( View ):})-def _thumbnail_svg( document_id : int ) -> bytes:- """Tiny SVG placeholder. Avoids shipping a binary thumbnail just- so the picker can render *something* in the thumbnail slot."""- return (- f'<svg xmlns="http://www.w3.org/2000/svg" width="120" height="160" '- f'viewBox="0 0 120 160">'- f'<rect width="120" height="160" fill="#e9ecef" stroke="#adb5bd"/>'- f'<text x="60" y="86" text-anchor="middle" font-family="sans-serif" '- f'font-size="20" fill="#495057">#{document_id}</text>'- f'</svg>'- ).encode('utf-8')+def _thumbnail_png( document_id : int ) -> bytes:+ """Tiny PNG placeholder generated with Pillow. Real paperless+ returns image/png from this endpoint; matching that lets the+ framework's attach-time bytes-to-file write produce a file the+ browser can later decode (the manager hard-codes the saved+ filename's extension to ``.png``)."""+ img = Image.new( 'RGB', ( 120, 160 ), ( 233, 236, 239 ))+ draw = ImageDraw.Draw( img )+ label = f'#{document_id}'+ # Default font is PIL's 8x13 bitmap -- ugly but readable and+ # avoids a fontconfig / TrueType dependency in the simulator.+ text_box = draw.textbbox( ( 0, 0 ), label )+ text_w = text_box[2] - text_box[0]+ text_h = text_box[3] - text_box[1]+ draw.text(+ ( (120 - text_w) // 2, (160 - text_h) // 2 ),+ label, fill = ( 73, 80, 87 ),+ )+ buf = BytesIO()+ img.save( buf, format = 'PNG' )+ return buf.getvalue()class ThumbnailView( View ):- """``GET /api/documents/<id>/thumb/`` — serves an SVG placeholder+ """``GET /api/documents/<id>/thumb/`` -- serves a PNG placeholderwhen thumbnails are enabled; 404s otherwise so the picker'sfallback-icon path can be exercised."""@@ -186,8 +195,56 @@ class ThumbnailView( View ):except (TypeError, ValueError):return HttpResponse( status = 404 )return HttpResponse(- _thumbnail_svg( document_id ),- content_type = 'image/svg+xml',+ _thumbnail_png( document_id ),+ content_type = 'image/png',+ )+++def _download_pdf( document_id : int ) -> bytes:+ """One-page PDF placeholder generated by Pillow's PDF writer.+ Used by ``DownloadView`` so HI can exercise the defensive+ original-bytes -> pdf2image -> thumbnail pipeline when the+ upstream thumbnail endpoint is unavailable. Pillow's PDF output+ avoids a reportlab dependency."""+ img = Image.new( 'RGB', ( 612, 792 ), ( 252, 252, 252 ))+ draw = ImageDraw.Draw( img )+ label = f'paperless\nsim doc\n#{document_id}'+ text_box = draw.multiline_textbbox( ( 0, 0 ), label )+ text_w = text_box[2] - text_box[0]+ text_h = text_box[3] - text_box[1]+ draw.multiline_text(+ ( (612 - text_w) // 2, (792 - text_h) // 2 ),+ label, fill = ( 33, 37, 41 ), align = 'center',+ )+ buf = BytesIO()+ img.save( buf, format = 'PDF' )+ return buf.getvalue()+++class DownloadView( View ):+ """``GET /api/documents/<id>/download/`` -- always-on PDF+ placeholder. HI's referencer hits this as the defensive+ fallback when the thumbnail endpoint is unavailable; serving+ real PDF bytes lets the operator exercise the HI-generated+ thumbnail path (turn ``thumbnails`` off, attach a PDF+ selection, see a pdf2image-rendered thumbnail on the saved+ card).++ Always serves PDF regardless of the selection's mime: paperless+ simulator selections include image and text mimes too, but+ those mimes never reach the original-bytes fallback (the image+ pipeline would reject PDF bytes and the text mime is gated out+ of the supported set). Set ``MimeMix.PDF_ONLY`` to exercise+ the generation path."""++ def get( self, request, *args, **kwargs ):+ try:+ document_id = int( kwargs.get( 'document_id' ) )+ except (TypeError, ValueError):+ return HttpResponse( status = 404 )+ return HttpResponse(+ _download_pdf( document_id ),+ content_type = 'application/pdf',)@@ -233,9 +290,6 @@ class SetSettingsView( View ):snippets = self._parse_bool(request.POST.get( 'snippets' ),),- latency_ms = self._parse_latency_ms(- request.POST.get( 'latency_ms' ), current.latency_ms,- ),)simulator.set_settings( new_settings )return render(@@ -271,13 +325,3 @@ class SetSettingsView( View ):# mere presence of the field name (with any truthy value) is# the signal.return bool( raw )-- @staticmethod- def _parse_latency_ms( raw : Optional[str], fallback : int ) -> int:- try:- value = int( raw )- except (TypeError, ValueError):- return fallback- if value < 0 or value > 10000:- raise BadRequest( f'latency_ms out of range: {raw!r}' )- return valuediff --git a/src/hi/static/css/attribute.css b/src/hi/static/css/attribute.cssindex 8a774c5f..618099fb 100644--- a/src/hi/static/css/attribute.css+++ b/src/hi/static/css/attribute.css@@ -150,6 +150,37 @@margin-bottom: 2rem;}+/* Collapse the file section when it has no cards. The wrapper+ stays in the DOM (file_grid_html_id is the target for "Add+ File" insertions) but takes zero vertical space. */+.attr-v2-file-section:not(:has(.attr-v2-file-card)) {+ margin-bottom: 0;+}+.attr-v2-file-section:not(:has(.attr-v2-file-card)) .attr-v2-file-grid {+ margin-top: 0;+}++/* External-reference card: integration logo inside the open-link+ action button. Sized 24px so it reads as an icon at typical+ button height. */+.hi-ext-ref-integration-logo {+ width: 24px;+ height: 24px;+ vertical-align: middle;+}++/* Action buttons in any file-card actions row (native attribute+ file cards and the external-reference card both use+ ``attr-v2-file-actions``). inline-flex centers tall children+ (24px icons / integration logos) inside btn-sm's padded box;+ without this an img > line-height defaults to baseline-ish+ vertical alignment and visually sits high in the button. */+.attr-v2-file-actions .btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+}+.attr-v2-file-grid {display: grid;grid-template-columns: repeat(3, 1fr);@@ -393,6 +424,22 @@border-radius: 0.25rem;}+/* Hide the "previous" reorder chevron on the first card and the+ "next" chevron on the last card. ``visibility: hidden`` (not+ ``display: none``) preserves the grid slot so the action row's+ ``mr-auto`` / ``ml-auto`` spacing for the middle cluster stays+ consistent across first / middle / last cards. The DOM-swap+ reorder path (``insertBefore``) retriggers ``:first-child`` /+ ``:last-child`` automatically -- no JS state to maintain. */+.attr-v2-file-grid > .attr-v2-file-card:first-child [data-reorder-action="left"],+.attr-v2-file-grid > .hi-ext-ref-card:first-child .hi-ext-ref-reorder-left {+ visibility: hidden;+}+.attr-v2-file-grid > .attr-v2-file-card:last-child [data-reorder-action="right"],+.attr-v2-file-grid > .hi-ext-ref-card:last-child .hi-ext-ref-reorder-right {+ visibility: hidden;+}+/* Reorder Controls - Overlay in upper right of thumbnail */.attr-v2-reorder-controls {position: absolute;@@ -471,6 +518,16 @@margin-bottom: 2rem;}+/* Collapse the attribute section when no saved-instance cards are+ present (only Django formset extras would render an+ ``attr-v2-new-attribute`` card; that card stays hidden until+ "Add Info" reveals it). The wrapper stays in the DOM so the+ formset's management form remains intact and "Add Info"'s+ reveal still finds its target. */+.attr-v2-attribute-section:not(:has(.attr-v2-attribute-card:not(.attr-v2-new-attribute))) {+ margin-bottom: 0;+}+.attr-v2-attribute-list {display: flex;flex-direction: column;@@ -1777,7 +1834,7 @@anchored. Pin the search controls to the top edge of the body so theoperator can refine their query at any scroll position withoutscrolling back up to find the search row. */-.hi-attr-picker-search-form {+.hi-ref-picker-search-form {position: sticky;top: 0;z-index: 1;@@ -1790,7 +1847,7 @@against the title -- otherwise modal-body's default padding-top showsscrolling content through the gap above the sticky element. Thesearch form supplies its own padding-top for breathing room. */-.hi-attr-picker .modal-body {+.hi-ref-picker .modal-body {padding-top: 0;}@@ -1800,27 +1857,70 @@that does nothing useful. The button face shows the source'slogo on a light background; native logos meant for white rendercorrectly here. */-.hi-attr-picker-source-banner {+.hi-ref-picker-source-banner {background-color: #fff;border: 1px solid var(--line-color, #dee2e6);padding: 0.5rem 0.75rem;}-.hi-attr-picker-source-banner-logo {+.hi-ref-picker-source-banner-logo {max-height: 24px;width: auto;}-.hi-attr-picker-source-banner-label {+.hi-ref-picker-source-banner-label {font-weight: 500;}-.hi-attr-picker-source-banner-single .dropdown-toggle::after {+.hi-ref-picker-source-banner-single .dropdown-toggle::after {display: none;}-.hi-attr-picker-source-banner-single .dropdown-toggle:disabled {+.hi-ref-picker-source-banner-single .dropdown-toggle:disabled {opacity: 1;cursor: default;}-.hi-attr-picker-source-option img {+.hi-ref-picker-source-option img {max-height: 20px;width: auto;}+/* Hover-zoom for picker result thumbnails. Pure CSS: the wrapper+ carries a hidden native-size sibling image; ``:hover`` reveals+ it. ``pointer-events: none`` keeps the zoom from intercepting+ clicks on the row text it overlaps. ``z-index`` puts it above+ sibling rows but stays inside the modal body's scroll area;+ tall rows near the bottom can clip. */+.hi-ref-picker-thumb {+ position: relative;+ display: inline-block;+ flex-shrink: 0;+}+.hi-ref-picker-thumb-small {+ display: block;+ width: 56px;+ height: 56px;+ object-fit: cover;+}+.hi-ref-picker-thumb-zoom {+ display: none;+ position: absolute;+ left: 64px;+ top: 0;+ max-width: 320px;+ max-height: 320px;+ background: #fff;+ border: 1px solid #6c757d;+ box-shadow: 0 0.25rem 0.5rem rgba(0, 0, 0, 0.2);+ z-index: 10;+ pointer-events: none;+}+.hi-ref-picker-thumb:hover .hi-ref-picker-thumb-zoom {+ display: block;+}++/* Second hover trigger: the source-URL link in the row's text area+ also reveals the same zoom. ``:has()`` lets a sibling-of-thumb+ trigger (the link is in a deeper subtree) bubble back up and+ match the row, so a single zoom element serves both triggers. */+.hi-ref-picker-row:has(.hi-ref-picker-source-link:hover)+ .hi-ref-picker-thumb-zoom {+ display: block;+}+diff --git a/src/hi/static/js/attr-dirty-tracking.js b/src/hi/static/js/attr-dirty-tracking.jsindex 8368d2a9..d14c060e 100644--- a/src/hi/static/js/attr-dirty-tracking.js+++ b/src/hi/static/js/attr-dirty-tracking.js@@ -84,6 +84,15 @@this.captureFieldValue(field);});+ // File cards aren't in the formset and use the+ // ``file_order_id_*`` naming. Pick them up alongside+ // the formset order fields so file reorder is dirty-+ // tracked the same way.+ const fileOrderFields = form.querySelectorAll('input[type="hidden"][name^="file_order_id_"]');+ fileOrderFields.forEach(field => {+ this.captureFieldValue(field);+ });+const fileTitleFields = form.querySelectorAll(Hi.ATTR_V2_FILE_TITLE_INPUT_SELECTOR);fileTitleFields.forEach(field => {this.captureFieldValue(field);@@ -226,6 +235,17 @@}}+ // File order_id is a hidden input, so the field itself+ // isn't a visible target. Point the dirty indicator at+ // the file info area (title + filename) -- visible and+ // mirrors where file title's dirty cue appears.+ if (field.name && field.name.indexOf('file_order_id_') === 0) {+ const fileCard = field.closest(Hi.ATTR_V2_FILE_CARD_SELECTOR);+ if (fileCard) {+ return fileCard.querySelector(Hi.ATTR_V2_FILE_INFO_SELECTOR) || fileCard;+ }+ }+const attributeCard = field.closest(Hi.ATTR_V2_ATTRIBUTE_CARD_SELECTOR);if (attributeCard) {return attributeCard.querySelector(Hi.ATTR_V2_ATTRIBUTE_NAME_SELECTOR);@@ -337,6 +357,14 @@orderFields.forEach(field => {this.handleFieldChange(field);});++ // File cards have ad-hoc ``file_order_id_*`` hidden+ // inputs (not formset-prefixed); re-evaluate them so the+ // file-grid reorder path lights up dirty-tracking too.+ const fileOrderFields = form.querySelectorAll('input[type="hidden"][name^="file_order_id_"]');+ fileOrderFields.forEach(field => {+ this.handleFieldChange(field);+ });},handleFormSuccess: function(e) {diff --git a/src/hi/static/js/attr.js b/src/hi/static/js/attr.jsindex d8b2d367..c130a96f 100644--- a/src/hi/static/js/attr.js+++ b/src/hi/static/js/attr.js@@ -103,6 +103,10 @@showAddAttribute: function(containerSelector = null) {return _showAddAttribute(containerSelector);},++ showAddFile: function(button, fileInputId) {+ return _showAddFile(button, fileInputId);+ },toggleSecretField: function(button) {return _toggleSecretField(button);@@ -359,6 +363,13 @@// Process DOM updates first (works for both success and error)const lastAppendTarget = this.processDOMUpdates(data, options);++ // After the swap, restore the operator's active tab so+ // that an UPDATE round-trip doesn't drop them back to+ // the server's data-derived default.+ if (window.Hi.attr.restoreActiveTabs) {+ window.Hi.attr.restoreActiveTabs();+ }// Handle scroll-to-new-content if requested by callerif (options.scrollToNewContent && lastAppendTarget) {@@ -779,16 +790,41 @@});}+ // The Add Info / Add File buttons live in the sticky panel above+ // the tabs and target content that lives inside Tab 1. When the+ // operator triggers them from an inactive tab, reveal Tab 1+ // first so the newly exposed form/picker is actually visible.+ // Tab 1 is located by the framework's id convention+ // ("hi-attr-tab1-<owner_id>"), which the attribute framework+ // owns end-to-end.+ function _ensureAttributeTabActive(elementInForm) {+ const $form = elementInForm+ ? $(elementInForm).closest('form')+ : $();+ const $scope = $form.length > 0 ? $form : $(document);+ const $pane = $scope.find('[id^="hi-attr-tab1-"]').first();+ if ($pane.length === 0) return;+ const paneId = $pane.attr('id');+ const $nav = $scope.find(+ 'a[data-toggle="tab"][href="#' + paneId + '"]'+ );+ if ($nav.length > 0 && !$nav.hasClass('active')) {+ $nav.tab('show');+ }+ }+// Simple add attribute - just show the last (empty) formset formfunction _showAddAttribute(containerSelector = null) {// Find the last attribute card (should be the empty extra form)const scope = containerSelector ? $(containerSelector) : $(document);const attributeCards = scope.find(Hi.ATTR_V2_ATTRIBUTE_CARD_SELECTOR);-+if (attributeCards.length > 0) {const lastCard = attributeCards[attributeCards.length - 1];const $lastCard = $(lastCard);-++ _ensureAttributeTabActive(lastCard);+// Show the card if hidden$lastCard.show();@@ -809,7 +845,13 @@lastCard.scrollIntoView({ behavior: 'smooth', block: 'nearest' });}};-++ function _showAddFile(button, fileInputId) {+ _ensureAttributeTabActive(button);+ const input = document.getElementById(fileInputId);+ if (input) input.click();+ }+// Removed dedicated add attribute form functions - using Django formset approach only@@ -1440,26 +1482,47 @@if (!parent) return;+ let other = null;switch (direction) {case "up":- const prev = card.previousElementSibling;- if (prev) parent.insertBefore(card, prev);+ other = card.previousElementSibling;+ if (other) parent.insertBefore(card, other);break;case "down":- const next = card.nextElementSibling;- if (next) parent.insertBefore(next, card);+ other = card.nextElementSibling;+ if (other) parent.insertBefore(other, card);break;default:console.error(`Invalid direction: ${direction}`);return;}+ if (!other) return; // already at boundary; nothing to persist.++ // File cards don't ride the regular formset, so the global+ // renumber path doesn't reach them. Renumber just the file+ // section in DOM order via the ad-hoc hidden inputs. A pure+ // swap is wrong here -- files default to order_id=0 on+ // upload, so two equal values would no-op the swap and the+ // ordering never differentiates. Renumbering 0..N-1 inside+ // the file grid bootstraps from the all-zero state and+ // stays correct through subsequent reorders without+ // touching any non-file attribute's order_id.+ // Regular attribute cards: keep the existing renumber path+ // -- their formset save handles per-row order_id and the+ // UI partitions display by type, so the renumber's numeric+ // overlap with file order_ids is benign.+ const isFileCard = $(card).is(Hi.ATTR_V2_FILE_CARD_SELECTOR);+ if (isFileCard) {+ _renumberFileCardOrderIds(parent);+ }const $container = $(card).closest(Hi.ATTR_V2_CONTAINER_SELECTOR);if ($container.length > 0) {- _updateOrderIndexes($container);-+ if (!isFileCard) {+ _updateOrderIndexes($container);+ }if (window.Hi.attr.dirtyTracking) {const containerId = $container.attr('id');if (containerId) {@@ -1472,6 +1535,23 @@}}+ function _renumberFileCardOrderIds(fileGridParent) {+ // Walk file-card siblings in DOM order and write 0..N-1 to+ // each card's ``file_order_id_*`` hidden input. Server+ // processes the changes via ``process_file_order_updates``.+ const $cards = $(fileGridParent).find(+ Hi.ATTR_V2_FILE_CARD_SELECTOR+ );+ $cards.each(function(index) {+ const $input = $(this).find(+ 'input[type="hidden"][name^="file_order_id_"]'+ ).first();+ if ($input.length) {+ $input.val(String(index));+ }+ });+ }+function _restoreDefaultValue(attributeId, containerSelector = null) {const scope = containerSelector ? $(containerSelector) : $(document);const $card = scope.find(`[${Hi.DATA_ATTRIBUTE_ID_ATTR}="${attributeId}"]`);@@ -1589,7 +1669,12 @@function _updateOrderIndexes($container) {let order = 1;-++ // Regular attribute cards only. File cards are intentionally+ // excluded -- file ordering uses a scoped renumber over the+ // file grid alone (``_renumberFileCardOrderIds``) so it+ // can't clobber non-file order_ids when files share the+ // order_id namespace with hundreds of regular attributes.const $cards = $container.find(Hi.ATTR_V2_ATTRIBUTE_CARD_SELECTOR);$cards.each(function() {@@ -1612,5 +1697,41 @@order += 1;});}-++ // Persist the operator's active-tab choice across async form+ // submissions. The form element survives the response swap+ // (it wraps the replaced content body), so its data attribute+ // is a stable carrier for the active tab's href. Generic: no+ // knowledge of how many tabs exist or what they mean.+ //+ // Stash on tab change.+ $(document).on(+ 'shown.bs.tab',+ 'a[data-toggle="tab"]',+ function() {+ const $form = $(this).closest('form');+ if ($form.length === 0) return;+ $form.attr('data-active-tab', $(this).attr('href'));+ }+ );++ // Exposed on Hi.attr so the response handler can invoke it+ // after swapping fresh content into the form, without reaching+ // into module internals.+ function _restoreActiveTabs() {+ $('form[data-active-tab]').each(function() {+ const $form = $(this);+ const targetHref = $form.attr('data-active-tab');+ if (!targetHref) return;+ const $tab = $form.find(+ 'a[data-toggle="tab"][href="' + targetHref + '"]'+ );+ if ($tab.length === 0) return;+ if (!$tab.hasClass('active')) {+ $tab.tab('show');+ }+ });+ }+ window.Hi.attr.restoreActiveTabs = _restoreActiveTabs;+})();diff --git a/src/hi/static/js/attr-picker.js b/src/hi/static/js/external-reference-picker.jssimilarity index 69%rename from src/hi/static/js/attr-picker.jsrename to src/hi/static/js/external-reference-picker.jsindex d1eb8fcc..59c2f7d6 100644--- a/src/hi/static/js/attr-picker.js+++ b/src/hi/static/js/external-reference-picker.js@@ -1,7 +1,7 @@/*- * Home Information - Attribute-reference picker UI state+ * Home Information - External-reference picker UI state*- * Multi-select picker for ATTRIBUTE_REFERENCE integrations (e.g.,+ * Multi-select picker for EXTERNAL_REFERENCE integrations (e.g.,* paperless-ngx). The picker lets the operator search an upstream* source and accumulate a set of references (title + URL) across* multiple searches, then commit the whole set as TEXT attributes@@ -32,13 +32,13 @@* modal is removed.** DOM classes, data-attribute names, and wire-format field names- * all come from ``Hi.ATTR_PICKER_*`` in ``main.js``, mirrored+ * all come from ``Hi.REF_PICKER_*`` in ``main.js``, mirrored* server-side in ``hi.constants.DIVID``.*/(function() {'use strict';- const EventNs = '.attr-picker';+ const EventNs = '.external-reference-picker';// Per-picker selection state, keyed by the picker-root DOM node// so multiple open modals would not collide. State is lazily@@ -60,20 +60,22 @@}function _hasSelection(state, sourceUrl) {- const key = Hi.ATTR_PICKER_SELECTION_URL_KEY;+ const key = Hi.REF_PICKER_SELECTION_URL_KEY;return state.attrSelections.some(s => s[key] === sourceUrl);}- function _addSelection(state, title, sourceUrl) {- if (_hasSelection(state, sourceUrl)) return;+ function _addSelection(state, fields) {+ if (_hasSelection(state, fields.sourceUrl)) return;const record = {};- record[Hi.ATTR_PICKER_SELECTION_TITLE_KEY] = title;- record[Hi.ATTR_PICKER_SELECTION_URL_KEY] = sourceUrl;+ record[Hi.REF_PICKER_SELECTION_TITLE_KEY] = fields.title;+ record[Hi.REF_PICKER_SELECTION_URL_KEY] = fields.sourceUrl;+ record[Hi.REF_PICKER_SELECTION_INTEGRATION_NAME_KEY] = fields.integrationName;+ record[Hi.REF_PICKER_SELECTION_MIME_TYPE_KEY] = fields.mimeType || '';state.attrSelections.push(record);}function _removeSelection(state, sourceUrl) {- const key = Hi.ATTR_PICKER_SELECTION_URL_KEY;+ const key = Hi.REF_PICKER_SELECTION_URL_KEY;state.attrSelections = state.attrSelections.filter(s => s[key] !== sourceUrl);@@ -81,10 +83,10 @@function _renderChips($pickerRoot, state) {const $chipsContainer = $pickerRoot.find(- _classSelector(Hi.ATTR_PICKER_CHIPS_CLASS)+ _classSelector(Hi.REF_PICKER_CHIPS_CLASS));const $emptyHint = $pickerRoot.find(- _classSelector(Hi.ATTR_PICKER_CHIPS_EMPTY_CLASS)+ _classSelector(Hi.REF_PICKER_CHIPS_EMPTY_CLASS));$chipsContainer.empty();if (state.attrSelections.length === 0) {@@ -92,8 +94,8 @@return;}$emptyHint.addClass('d-none');- const titleKey = Hi.ATTR_PICKER_SELECTION_TITLE_KEY;- const urlKey = Hi.ATTR_PICKER_SELECTION_URL_KEY;+ const titleKey = Hi.REF_PICKER_SELECTION_TITLE_KEY;+ const urlKey = Hi.REF_PICKER_SELECTION_URL_KEY;state.attrSelections.forEach(function(sel) {const $chip = $('<span>').addClass('badge badge-secondary mr-2 mb-2 d-inline-flex align-items-center');@@ -105,9 +107,9 @@.appendTo($chip);$('<button type="button">').addClass('btn btn-link btn-sm p-0 text-white ml-1')- .addClass(Hi.ATTR_PICKER_CHIP_REMOVE_CLASS)+ .addClass(Hi.REF_PICKER_CHIP_REMOVE_CLASS).attr('title', 'Remove from selection')- .attr(Hi.ATTR_PICKER_SOURCE_URL_ATTR, sel[urlKey])+ .attr(Hi.REF_PICKER_SOURCE_URL_ATTR, sel[urlKey]).text('×') // ×.appendTo($chip);$chipsContainer.append($chip);@@ -117,11 +119,11 @@function _renderAttachButton($pickerRoot, state) {const count = state.attrSelections.length;const $btn = $pickerRoot.find(- _classSelector(Hi.ATTR_PICKER_ATTACH_BTN_CLASS)+ _classSelector(Hi.REF_PICKER_ATTACH_BTN_CLASS));const noun = count === 1 ? 'Link' : 'Links';const $label = $btn.find(- _classSelector(Hi.ATTR_PICKER_ATTACH_LABEL_CLASS)+ _classSelector(Hi.REF_PICKER_ATTACH_LABEL_CLASS));const text = 'Add ' + count + ' ' + noun;if ($label.length) {@@ -139,10 +141,10 @@function _syncCheckboxesToState($pickerRoot, state) {$pickerRoot.find(- _classSelector(Hi.ATTR_PICKER_RESULT_CHECKBOX_CLASS)+ _classSelector(Hi.REF_PICKER_RESULT_CHECKBOX_CLASS)).each(function() {const $cb = $(this);- const sourceUrl = $cb.attr(Hi.ATTR_PICKER_SOURCE_URL_ATTR);+ const sourceUrl = $cb.attr(Hi.REF_PICKER_SOURCE_URL_ATTR);if (sourceUrl == null) return;$cb.prop('checked', _hasSelection(state, sourceUrl));});@@ -152,19 +154,23 @@$(document).on('change' + EventNs,- _classSelector(Hi.ATTR_PICKER_RESULT_CHECKBOX_CLASS),+ _classSelector(Hi.REF_PICKER_RESULT_CHECKBOX_CLASS),function() {const $cb = $(this);const $pickerRoot = $cb.closest(- _classSelector(Hi.ATTR_PICKER_ROOT_CLASS)+ _classSelector(Hi.REF_PICKER_ROOT_CLASS));if ($pickerRoot.length === 0) return;const state = _state($pickerRoot[0]);- const title = $cb.attr(Hi.ATTR_PICKER_TITLE_ATTR);- const sourceUrl = $cb.attr(Hi.ATTR_PICKER_SOURCE_URL_ATTR);+ const sourceUrl = $cb.attr(Hi.REF_PICKER_SOURCE_URL_ATTR);if (sourceUrl == null) return;if ($cb.is(':checked')) {- _addSelection(state, title, sourceUrl);+ _addSelection(state, {+ title: $cb.attr(Hi.REF_PICKER_TITLE_ATTR),+ sourceUrl: sourceUrl,+ integrationName: $cb.attr(Hi.REF_PICKER_INTEGRATION_NAME_ATTR),+ mimeType: $cb.attr(Hi.REF_PICKER_MIME_TYPE_ATTR),+ });} else {_removeSelection(state, sourceUrl);}@@ -174,22 +180,22 @@$(document).on('click' + EventNs,- _classSelector(Hi.ATTR_PICKER_CHIP_REMOVE_CLASS),+ _classSelector(Hi.REF_PICKER_CHIP_REMOVE_CLASS),function() {const $btn = $(this);const $pickerRoot = $btn.closest(- _classSelector(Hi.ATTR_PICKER_ROOT_CLASS)+ _classSelector(Hi.REF_PICKER_ROOT_CLASS));if ($pickerRoot.length === 0) return;- const sourceUrl = $btn.attr(Hi.ATTR_PICKER_SOURCE_URL_ATTR);+ const sourceUrl = $btn.attr(Hi.REF_PICKER_SOURCE_URL_ATTR);if (sourceUrl == null) return;const state = _state($pickerRoot[0]);_removeSelection(state, sourceUrl);// Uncheck any visible result card whose URL matches.$pickerRoot- .find(_classSelector(Hi.ATTR_PICKER_RESULT_CHECKBOX_CLASS))+ .find(_classSelector(Hi.REF_PICKER_RESULT_CHECKBOX_CLASS)).filter(function() {- return $(this).attr(Hi.ATTR_PICKER_SOURCE_URL_ATTR) === sourceUrl;+ return $(this).attr(Hi.REF_PICKER_SOURCE_URL_ATTR) === sourceUrl;}).prop('checked', false);_renderAll($pickerRoot, state);@@ -198,15 +204,15 @@$(document).on('submit' + EventNs,- _classSelector(Hi.ATTR_PICKER_SEARCH_FORM_CLASS),+ _classSelector(Hi.REF_PICKER_SEARCH_FORM_CLASS),function(e) {e.preventDefault();const $form = $(this);const $pickerRoot = $form.closest(- _classSelector(Hi.ATTR_PICKER_ROOT_CLASS)+ _classSelector(Hi.REF_PICKER_ROOT_CLASS));if ($pickerRoot.length === 0) return;- const searchUrl = $form.attr(Hi.ATTR_PICKER_SEARCH_URL_ATTR);+ const searchUrl = $form.attr(Hi.REF_PICKER_SEARCH_URL_ATTR);$.ajax({url: searchUrl,method: 'POST',@@ -214,7 +220,7 @@headers: { 'X-Requested-With': 'XMLHttpRequest' }}).done(function(html) {$pickerRoot.find(- _classSelector(Hi.ATTR_PICKER_RESULTS_CLASS)+ _classSelector(Hi.REF_PICKER_RESULTS_CLASS)).html(html);_syncCheckboxesToState($pickerRoot, _state($pickerRoot[0]));});@@ -223,7 +229,7 @@$(document).on('submit' + EventNs,- _classSelector(Hi.ATTR_PICKER_ATTACH_FORM_CLASS),+ _classSelector(Hi.REF_PICKER_ATTACH_FORM_CLASS),function(e) {// Own the submit lifecycle so the in-memory selection set// is populated into the hidden input BEFORE the form is@@ -235,11 +241,11 @@e.preventDefault();const $form = $(this);const $pickerRoot = $form.closest(- _classSelector(Hi.ATTR_PICKER_ROOT_CLASS)+ _classSelector(Hi.REF_PICKER_ROOT_CLASS));if ($pickerRoot.length === 0) return;const state = _state($pickerRoot[0]);- const fieldName = Hi.ATTR_PICKER_SELECTIONS_JSON_FIELD;+ const fieldName = Hi.REF_PICKER_SELECTIONS_JSON_FIELD;$form.find('input[name="' + fieldName + '"]').val(JSON.stringify(state.attrSelections));if (!window.AN) {@@ -256,35 +262,38 @@$(document).on('click' + EventNs,- _classSelector(Hi.ATTR_PICKER_SOURCE_OPTION_CLASS),+ _classSelector(Hi.REF_PICKER_SOURCE_OPTION_CLASS),function(e) {- // Switch the active source: update the banner face, set- // the hidden integration_id input, and re-issue the- // current search against the new source. Selections- // already in state stay put — they're keyed by URL, not- // by source.+ // Switch the active source. Selections are CLEARED --+ // each submission carries items from one integration+ // only, matching the typical "pick from this source"+ // workflow. Operators who want a mix submit one batch+ // per source.e.preventDefault();const $option = $(this);const $pickerRoot = $option.closest(- _classSelector(Hi.ATTR_PICKER_ROOT_CLASS)+ _classSelector(Hi.REF_PICKER_ROOT_CLASS));if ($pickerRoot.length === 0) return;- const sourceId = $option.attr(Hi.ATTR_PICKER_SOURCE_ID_ATTR);- const sourceLogo = $option.attr(Hi.ATTR_PICKER_SOURCE_LOGO_ATTR);- const sourceLabel = $option.attr(Hi.ATTR_PICKER_SOURCE_LABEL_ATTR);+ const sourceId = $option.attr(Hi.REF_PICKER_SOURCE_ID_ATTR);+ const sourceLogo = $option.attr(Hi.REF_PICKER_SOURCE_LOGO_ATTR);+ const sourceLabel = $option.attr(Hi.REF_PICKER_SOURCE_LABEL_ATTR);if (sourceId == null) return;+ const state = _state($pickerRoot[0]);+ state.attrSelections = [];+ _renderAll($pickerRoot, state);$pickerRoot- .find(_classSelector(Hi.ATTR_PICKER_SOURCE_BANNER_LOGO_CLASS))+ .find(_classSelector(Hi.REF_PICKER_SOURCE_BANNER_LOGO_CLASS)).attr('src', sourceLogo);$pickerRoot- .find(_classSelector(Hi.ATTR_PICKER_SOURCE_BANNER_LABEL_CLASS))+ .find(_classSelector(Hi.REF_PICKER_SOURCE_BANNER_LABEL_CLASS)).text(sourceLabel);- const fieldName = Hi.ATTR_PICKER_INTEGRATION_ID_FIELD;+ const fieldName = Hi.REF_PICKER_INTEGRATION_ID_FIELD;$pickerRoot.find('input[name="' + fieldName + '"]').val(sourceId);$pickerRoot- .find(_classSelector(Hi.ATTR_PICKER_SEARCH_FORM_CLASS))+ .find(_classSelector(Hi.REF_PICKER_SEARCH_FORM_CLASS)).trigger('submit');});diff --git a/src/hi/static/js/external-references.js b/src/hi/static/js/external-references.jsnew file mode 100644index 00000000..fef44ffe--- /dev/null+++ b/src/hi/static/js/external-references.js@@ -0,0 +1,189 @@+/*+ * Home Information - External-reference card actions+ *+ * Per-card rename / unlink / reorder for the framework-rendered+ * external-reference grid on Entity / Location edit modals. Each+ * action POSTs to its own endpoint; the response is the freshly-+ * rendered grid HTML, which replaces the existing grid in place so+ * the surrounding modal stays open.+ *+ * The action endpoints already require custom JS (we extract the+ * reference id from the card, fire on input blur for rename, etc.),+ * so antinode's declarative wiring doesn't pull weight here -- we+ * just $.ajax + replaceWith directly. The grid is located by+ * closest() traversal from the clicked card, so no template ->+ * JS magic-string id agreement is required.+ *+ * Handlers are delegated at the document level so dynamically-+ * inserted modal content wires up automatically -- no per-modal+ * init step. CSS reuse is via the existing ``attr-v2-file-*``+ * classes on the card template itself.+ *+ * DOM classes, data attributes, and JSON field names come from+ * ``Hi.EXT_REF_*`` in main.js, mirrored server-side in+ * ``hi.constants.DIVID``.+ */+(function() {+ 'use strict';++ const EventNs = '.ext-ref';++ function _classSelector(className) {+ return '.' + className;+ }++ function _csrfToken() {+ const name = 'csrftoken';+ const cookies = document.cookie ? document.cookie.split(';') : [];+ for (let i = 0; i < cookies.length; i++) {+ const c = cookies[i].trim();+ if (c.substring(0, name.length + 1) === (name + '=')) {+ return decodeURIComponent(c.substring(name.length + 1));+ }+ }+ return '';+ }++ function _cardContext($card) {+ return {+ referenceId: $card.attr(Hi.EXT_REF_REFERENCE_ID_ATTR),+ ownerType: $card.attr(Hi.EXT_REF_OWNER_TYPE_ATTR),+ };+ }++ function _postAction(url, fields, $card) {+ // The grid is the card's nearest ancestor with the grid+ // class -- no id agreement between JS and template needed.+ const $grid = $card.closest(_classSelector(Hi.EXT_REF_GRID_CLASS));+ const payload = Object.assign({ csrfmiddlewaretoken: _csrfToken() }, fields);+ // No .fail() handler: server-side BadRequest / 404 responses+ // are dropped client-side and the grid simply doesn't+ // refresh. The server logs the error; the operator can+ // retry or refresh the modal.+ $.ajax({+ url: url,+ method: 'POST',+ data: payload,+ headers: { 'X-Requested-With': 'XMLHttpRequest' },+ }).done(function(html) {+ $grid.replaceWith(html);+ });+ }++ function _actionUrl(viewName, ownerType, referenceId) {+ // Template-rendered Django URLs aren't available client-side+ // for arbitrary view names, so the path is composed by+ // convention. Keep this in sync with ``hi.integrations.urls``.+ return '/integration/external-references/'+ + encodeURIComponent(ownerType)+ + '/' + encodeURIComponent(referenceId)+ + '/' + viewName + '/';+ }++ // ---- Title rename: commit on blur or Enter --------------------++ $(document).on(+ 'change' + EventNs + ' blur' + EventNs,+ _classSelector(Hi.EXT_REF_TITLE_INPUT_CLASS),+ function() {+ const $input = $(this);+ const $card = $input.closest(_classSelector(Hi.EXT_REF_CARD_CLASS));+ if ($card.length === 0) return;+ const newTitle = ($input.val() || '').trim();+ if (!newTitle) {+ // Restore the previous value rather than POST an+ // empty title (the server would 400). Use the input's+ // last-good defaultValue if present.+ $input.val($input.prop('defaultValue'));+ return;+ }+ if (newTitle === $input.prop('defaultValue')) {+ // No-op when the value hasn't actually changed+ // (blur fires even on a no-edit visit).+ return;+ }+ const ctx = _cardContext($card);+ const fields = {};+ fields[Hi.EXT_REF_TITLE_FIELD] = newTitle;+ _postAction(+ _actionUrl('rename', ctx.ownerType, ctx.referenceId),+ fields,+ $card,+ );+ }+ );++ $(document).on(+ 'keydown' + EventNs,+ _classSelector(Hi.EXT_REF_TITLE_INPUT_CLASS),+ function(e) {+ if (e.key === 'Enter') {+ e.preventDefault();+ $(this).blur();+ }+ }+ );++ // ---- Unlink (delete) ---------------------------------------++ $(document).on(+ 'click' + EventNs,+ _classSelector(Hi.EXT_REF_DELETE_BTN_CLASS),+ function(e) {+ e.preventDefault();+ const $card = $(this).closest(_classSelector(Hi.EXT_REF_CARD_CLASS));+ if ($card.length === 0) return;+ const ctx = _cardContext($card);+ _postAction(+ _actionUrl('delete', ctx.ownerType, ctx.referenceId),+ {},+ $card,+ );+ }+ );++ // ---- Reorder (move left / right) ---------------------------++ function _reorder(e, direction) {+ e.preventDefault();+ const $card = $(this).closest(_classSelector(Hi.EXT_REF_CARD_CLASS));+ if ($card.length === 0) return;+ const ctx = _cardContext($card);+ const fields = {};+ fields[Hi.EXT_REF_DIRECTION_FIELD] = direction;+ _postAction(+ _actionUrl('reorder', ctx.ownerType, ctx.referenceId),+ fields,+ $card,+ );+ }++ $(document).on(+ 'click' + EventNs,+ _classSelector(Hi.EXT_REF_REORDER_LEFT_CLASS),+ function(e) { _reorder.call(this, e, Hi.EXT_REF_DIRECTION_LEFT); }+ );+ $(document).on(+ 'click' + EventNs,+ _classSelector(Hi.EXT_REF_REORDER_RIGHT_CLASS),+ function(e) { _reorder.call(this, e, Hi.EXT_REF_DIRECTION_RIGHT); }+ );++ // ---- Open upstream (thumbnail click) -----------------------++ // The thumbnail click is wired here (rather than inline on the+ // template) because ``source_url`` is upstream-supplied; an+ // inline ``onclick="window.open('{{ url }}', ...)"`` lets a+ // crafted URL break out of the JS string literal even after+ // Django's attribute escaping. Reading the URL via .attr()+ // round-trips safely.+ $(document).on(+ 'click' + EventNs,+ '[' + Hi.EXT_REF_SOURCE_URL_ATTR + ']',+ function() {+ const url = $(this).attr(Hi.EXT_REF_SOURCE_URL_ATTR);+ if (url) window.open(url, '_blank', 'noopener');+ }+ );++})();diff --git a/src/hi/static/js/main.js b/src/hi/static/js/main.jsindex 80ac7981..6c34e88f 100644--- a/src/hi/static/js/main.js+++ b/src/hi/static/js/main.js@@ -165,38 +165,58 @@// Entity Picker - Filter valuesENTITY_PICKER_FILTER_ALL: 'all',- // ATTRIBUTE_REFERENCE picker — DOM classes / data attributes+ // EXTERNAL_REFERENCE picker — DOM classes / data attributes// / wire-format field names shared with the server. Mirror- // of the ``ATTR_PICKER_*`` entries in+ // of the ``REF_PICKER_*`` entries in// ``src/hi/constants.py:DIVID``.- ATTR_PICKER_ROOT_CLASS: 'hi-attr-picker',- ATTR_PICKER_CHIPS_CLASS: 'hi-attr-picker-chips',- ATTR_PICKER_CHIPS_EMPTY_CLASS: 'hi-attr-picker-chips-empty',- ATTR_PICKER_CHIP_REMOVE_CLASS: 'hi-attr-picker-chip-remove',- ATTR_PICKER_RESULTS_CLASS: 'hi-attr-picker-results',- ATTR_PICKER_SEARCH_FORM_CLASS: 'hi-attr-picker-search-form',- ATTR_PICKER_ATTACH_FORM_CLASS: 'hi-attr-picker-attach-form',- ATTR_PICKER_ATTACH_BTN_CLASS: 'hi-attr-picker-attach-btn',- ATTR_PICKER_ATTACH_LABEL_CLASS: 'hi-attr-picker-attach-label',- ATTR_PICKER_RESULT_CHECKBOX_CLASS: 'hi-attr-picker-result-checkbox',- ATTR_PICKER_SEARCH_URL_ATTR: 'data-attr-picker-search-url',- ATTR_PICKER_TITLE_ATTR: 'data-attr-picker-title',- ATTR_PICKER_SOURCE_URL_ATTR: 'data-attr-picker-source-url',- ATTR_PICKER_QUERY_FIELD: 'query',- ATTR_PICKER_LIMIT_FIELD: 'limit',- ATTR_PICKER_ITEM_TYPE_FIELD: 'item_type',- ATTR_PICKER_ITEM_ID_FIELD: 'item_id',- ATTR_PICKER_INTEGRATION_ID_FIELD: 'integration_id',- ATTR_PICKER_SELECTIONS_JSON_FIELD: 'selections_json',- ATTR_PICKER_SELECTION_TITLE_KEY: 'title',- ATTR_PICKER_SELECTION_URL_KEY: 'source_url',- ATTR_PICKER_SOURCE_BANNER_CLASS: 'hi-attr-picker-source-banner',- ATTR_PICKER_SOURCE_BANNER_LOGO_CLASS: 'hi-attr-picker-source-banner-logo',- ATTR_PICKER_SOURCE_BANNER_LABEL_CLASS: 'hi-attr-picker-source-banner-label',- ATTR_PICKER_SOURCE_OPTION_CLASS: 'hi-attr-picker-source-option',- ATTR_PICKER_SOURCE_ID_ATTR: 'data-attr-picker-source-id',- ATTR_PICKER_SOURCE_LOGO_ATTR: 'data-attr-picker-source-logo',- ATTR_PICKER_SOURCE_LABEL_ATTR: 'data-attr-picker-source-label'+ REF_PICKER_ROOT_CLASS: 'hi-ref-picker',+ REF_PICKER_CHIPS_CLASS: 'hi-ref-picker-chips',+ REF_PICKER_CHIPS_EMPTY_CLASS: 'hi-ref-picker-chips-empty',+ REF_PICKER_CHIP_REMOVE_CLASS: 'hi-ref-picker-chip-remove',+ REF_PICKER_RESULTS_CLASS: 'hi-ref-picker-results',+ REF_PICKER_SEARCH_FORM_CLASS: 'hi-ref-picker-search-form',+ REF_PICKER_ATTACH_FORM_CLASS: 'hi-ref-picker-attach-form',+ REF_PICKER_ATTACH_BTN_CLASS: 'hi-ref-picker-attach-btn',+ REF_PICKER_ATTACH_LABEL_CLASS: 'hi-ref-picker-attach-label',+ REF_PICKER_RESULT_CHECKBOX_CLASS: 'hi-ref-picker-result-checkbox',+ REF_PICKER_SEARCH_URL_ATTR: 'data-ref-picker-search-url',+ REF_PICKER_TITLE_ATTR: 'data-ref-picker-title',+ REF_PICKER_SOURCE_URL_ATTR: 'data-ref-picker-source-url',+ REF_PICKER_INTEGRATION_NAME_ATTR: 'data-ref-picker-integration-name',+ REF_PICKER_MIME_TYPE_ATTR: 'data-ref-picker-mime-type',+ REF_PICKER_QUERY_FIELD: 'query',+ REF_PICKER_LIMIT_FIELD: 'limit',+ REF_PICKER_ITEM_TYPE_FIELD: 'item_type',+ REF_PICKER_ITEM_ID_FIELD: 'item_id',+ REF_PICKER_INTEGRATION_ID_FIELD: 'integration_id',+ REF_PICKER_SELECTIONS_JSON_FIELD: 'selections_json',+ REF_PICKER_SELECTION_TITLE_KEY: 'title',+ REF_PICKER_SELECTION_URL_KEY: 'source_url',+ REF_PICKER_SELECTION_INTEGRATION_NAME_KEY: 'integration_name',+ REF_PICKER_SELECTION_MIME_TYPE_KEY: 'mime_type',+ REF_PICKER_SOURCE_BANNER_CLASS: 'hi-ref-picker-source-banner',+ REF_PICKER_SOURCE_BANNER_LOGO_CLASS: 'hi-ref-picker-source-banner-logo',+ REF_PICKER_SOURCE_BANNER_LABEL_CLASS: 'hi-ref-picker-source-banner-label',+ REF_PICKER_SOURCE_OPTION_CLASS: 'hi-ref-picker-source-option',+ REF_PICKER_SOURCE_ID_ATTR: 'data-ref-picker-source-id',+ REF_PICKER_SOURCE_LOGO_ATTR: 'data-ref-picker-source-logo',+ REF_PICKER_SOURCE_LABEL_ATTR: 'data-ref-picker-source-label',++ // External-reference card grid -- mirrors EXT_REF_* keys in+ // hi.constants.DIVID.+ EXT_REF_GRID_CLASS: 'hi-ext-ref-grid',+ EXT_REF_CARD_CLASS: 'hi-ext-ref-card',+ EXT_REF_TITLE_INPUT_CLASS: 'hi-ext-ref-title-input',+ EXT_REF_DELETE_BTN_CLASS: 'hi-ext-ref-delete-btn',+ EXT_REF_REORDER_LEFT_CLASS: 'hi-ext-ref-reorder-left',+ EXT_REF_REORDER_RIGHT_CLASS: 'hi-ext-ref-reorder-right',+ EXT_REF_REFERENCE_ID_ATTR: 'data-ext-ref-id',+ EXT_REF_OWNER_TYPE_ATTR: 'data-ext-ref-owner-type',+ EXT_REF_SOURCE_URL_ATTR: 'data-ext-ref-source-url',+ EXT_REF_TITLE_FIELD: 'title',+ EXT_REF_DIRECTION_FIELD: 'direction',+ EXT_REF_DIRECTION_LEFT: 'left',+ EXT_REF_DIRECTION_RIGHT: 'right'};window.Hi = Hi;@@ -488,4 +508,4 @@}-})();\ No newline at end of file+})();diff --git a/src/hi/templates/icons/unlink.html b/src/hi/templates/icons/unlink.htmlnew file mode 100644index 00000000..86d56e30--- /dev/null+++ b/src/hi/templates/icons/unlink.html@@ -0,0 +1,3 @@+<svg class="{{ class_attr }}" viewBox="0 0 24 24" fill="currentColor" {{ accessibility_attrs }}>+ <path d="M17 7h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1 0 1.31-.82 2.42-1.96 2.87l1.4 1.4A4.99 4.99 0 0 0 22 12c0-2.76-2.24-5-5-5zM2.27 2.27 1 3.54l3.18 3.18A4.992 4.992 0 0 0 2 12c0 2.76 2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1 0-1.43.97-2.62 2.28-2.97L7.81 10.5H8v.19l1.81 1.81H8v2h3.81l2.39 2.39V17h.19l5.07 5.07 1.27-1.27L2.27 2.27z"/>+</svg>diff --git a/src/hi/view_parameters.py b/src/hi/view_parameters.pyindex 00074325..ac79cd47 100644--- a/src/hi/view_parameters.py+++ b/src/hi/view_parameters.py@@ -17,10 +17,11 @@ class ViewParameters:# requires additional event registrations to handle mouse and gesture# events..- view_type : ViewType = None- view_mode : ViewMode = None- location_view_id : int = None # Last LocationView viewed- collection_id : int = None # Last Collection viewed+ view_type : ViewType = None+ view_mode : ViewMode = None+ location_view_id : int = None # Last LocationView viewed+ collection_id : int = None # Last Collection viewed+ ref_picker_integration_id : str = None # Last referencer the operator successfully linked fromdef __post_init__(self):if self.view_type is None:@@ -125,6 +126,7 @@ class ViewParameters:request.session['view_mode'] = str(self.view_mode)request.session['location_view_id'] = self.location_view_idrequest.session['collection_id'] = self.collection_id+ request.session['ref_picker_integration_id'] = self.ref_picker_integration_idreturn@staticmethod@@ -146,10 +148,15 @@ class ViewParameters:except ( TypeError, ValueError ):collection_id = None+ ref_picker_integration_id = request.session.get(+ 'ref_picker_integration_id',+ )+return ViewParameters(view_type = view_type,view_mode = view_mode,location_view_id = location_view_id,collection_id = collection_id,+ ref_picker_integration_id = ref_picker_integration_id,)