Home Information - Your home, your data, organized.
Python
Enhance Trigger History Modal with Video Browsing Integration (#118)
Tony C6e6205ad8fbe
diff --git a/src/hi/apps/event/templates/event/modals/event_history.html b/src/hi/apps/event/templates/event/modals/event_history.htmlindex fd4849ee..20dc3688 100644--- a/src/hi/apps/event/templates/event/modals/event_history.html+++ b/src/hi/apps/event/templates/event/modals/event_history.html@@ -1,11 +1,33 @@{% extends "modals/action_done.html" %}+{% block modal_dialog_class %}hi-modal-dialog-800{% endblock %}+{% block title_text %}Trigger History{% endblock %}{% block body %}-<h5>Trigger History</h5>-{% include "event/panes/event_history_list.html" with event_history_list=event_history_list %}-{% include "common/panes/pagination.html" with pagination=pagination %}+<div class="container-fluid px-0">+ <div class="row mb-3">+ <div class="col-12">+ <h5 class="mb-0">+ <i class="fas fa-history text-primary mr-2"></i>+ Trigger History+ </h5>+ <small class="text-muted">Recent trigger events and their details</small>+ </div>+ </div>++ <div class="row">+ <div class="col-12">+ {% include "event/panes/event_history_list.html" with event_history_list=event_history_list today=today yesterday=yesterday %}+ </div>+ </div>++ <div class="row">+ <div class="col-12">+ {% include "common/panes/pagination.html" with pagination=pagination %}+ </div>+ </div>+</div>{% endblock %}diff --git a/src/hi/apps/event/templates/event/panes/event_history_list.html b/src/hi/apps/event/templates/event/panes/event_history_list.htmlindex a3613047..fd1332fc 100644--- a/src/hi/apps/event/templates/event/panes/event_history_list.html+++ b/src/hi/apps/event/templates/event/panes/event_history_list.html@@ -1,29 +1,71 @@{% load tz %}+{% load humanize %}{% timezone USER_TIMEZONE %}-<div>- <div class="table-responsive">- <table class="table table-striped">- <thead>- <tr>- <th>Timestamp</th>- <th>Trigger Name</th>- </tr>- </thead>- <tbody>- {% for event_history in event_history_list %}- <tr>- <td>- {{ event_history.event_datetime|localtime }}- </td>- <td>- {{ event_history.event_definition.name }}- </td>- </tr>- {% empty %}- <tr><td colspan="6"><div><em>No event history</em></div></td></tr>- {% endfor %}- </tbody>- </table>+{% if event_history_list %}+ <div class="timeline-items">+ {% for event_history in event_history_list %}+ <div class="timeline-item mb-2">+ <div class="card border-left-primary">+ <div class="card-body py-2 px-3">+ <div class="row align-items-center">+ <div class="col-md-3 col-sm-4">+ <div class="text-center">+ {% if event_history.event_datetime|localtime|date:"Y-m-d" == today %}+ <strong class="text-primary d-block">Today {{ event_history.event_datetime|localtime|date:"g:i A" }}</strong>+ {% elif event_history.event_datetime|localtime|date:"Y-m-d" == yesterday %}+ <strong class="text-primary d-block">Yesterday {{ event_history.event_datetime|localtime|date:"g:i A" }}</strong>+ {% else %}+ <strong class="text-primary d-block">{{ event_history.event_datetime|localtime|date:"l, M j" }}</strong>+ <span class="text-primary">{{ event_history.event_datetime|localtime|date:"g:i A" }}</span>+ {% endif %}+ <small class="text-muted d-block">{{ event_history.event_datetime|localtime|naturaltime }}</small>+ </div>+ </div>+ <div class="col-md-5 col-sm-8">+ <div>+ <strong class="d-block mb-1">{{ event_history.event_definition.name }}</strong>+ <span class="badge badge-info mr-2">{{ event_history.event_definition.event_type.label }}</span>+ {% if event_history.entity_count == 1 %}+ <span class="badge badge-secondary">{{ event_history.entity_count }} item</span>+ {% else %}+ <span class="badge badge-secondary">{{ event_history.entity_count }} items</span>+ {% endif %}+ </div>+ </div>+ <div class="col-md-4 col-12">+ {% if event_history.entity_display_list %}+ <div class="mt-1 mt-md-0">+ <small class="text-muted d-block">Involved Items:</small>+ <div class="mt-1">+ {% for entity_display in event_history.entity_display_list %}+ {% if entity_display.has_video %}+ <a href="{% url 'console_entity_video_sensor_history_earlier' entity_display.entity.id entity_display.video_sensor.id event_history.video_url_timestamp %}"+ class="btn btn-sm btn-outline-primary mr-1 mb-1"+ data-async="#main-content"+ title="View video from {{ entity_display.entity.name }} around this event">+ <i class="fas fa-video"></i> {{ entity_display.entity.name }}+ </a>+ {% else %}+ <span class="text-info mr-2">{{ entity_display.entity.name }}</span>{% if not forloop.last %}, {% endif %}+ {% endif %}+ {% endfor %}+ </div>+ </div>+ {% endif %}+ </div>+ </div>+ </div>+ </div>+ </div>+ {% endfor %}</div>-</div>+{% else %}+ <div class="card border-0 bg-light">+ <div class="card-body text-center py-4">+ <i class="fas fa-clock text-muted fa-2x mb-3"></i>+ <h6 class="text-muted">No Event History</h6>+ <p class="text-muted mb-0">No trigger events have been recorded yet.</p>+ </div>+ </div>+{% endif %}{% endtimezone %}diff --git a/src/hi/apps/event/view_helpers.py b/src/hi/apps/event/view_helpers.pynew file mode 100644index 00000000..fb045b9f--- /dev/null+++ b/src/hi/apps/event/view_helpers.py@@ -0,0 +1,119 @@+from typing import List, Dict, Any+from django.utils import timezone++from .models import EventHistory+++class EventHistoryViewHelper:+ """+ Helper class to encapsulate business logic for EventHistoryView.+ Handles complex data transformations for event history display and video integration.+ """++ @classmethod+ def enhance_event_history_list(cls, event_history_list: List[EventHistory]) -> List[EventHistory]:+ """+ Enhance a list of EventHistory objects with computed fields for display and video integration.++ Args:+ event_history_list: List of EventHistory objects with prefetched relationships++ Returns:+ The same list with additional computed attributes added to each EventHistory object:+ - entity_count: Number of entities involved in the event+ - entity_names: List of entity names+ - video_entities: List of entities with video capabilities+ - entity_display_list: Unified list for template rendering+ - video_url_timestamp: Adjusted timestamp for video browser integration+ """+ for event_history in event_history_list:+ cls._add_entity_information(event_history)+ cls._add_video_integration_data(event_history)+ cls._add_timestamp_adjustment(event_history)++ return event_history_list++ @classmethod+ def _add_entity_information(cls, event_history: EventHistory) -> None:+ """Add basic entity count and names to EventHistory object."""+ event_history.entity_count = event_history.event_definition.event_clauses.count()+ event_history.entity_names = [+ clause.entity_state.entity.name+ for clause in event_history.event_definition.event_clauses.all()+ ]++ @classmethod+ def _add_video_integration_data(cls, event_history: EventHistory) -> None:+ """Add video-related data structures for browser integration."""+ # Group video-capable sensors by entity for video browser integration+ video_entities = cls._group_video_entities_by_entity(event_history)+ event_history.video_entities = list(video_entities.values())++ # Create unified entity display list that combines regular entities and video entities+ event_history.entity_display_list = cls._create_entity_display_list(+ event_history, video_entities+ )++ @classmethod+ def _group_video_entities_by_entity(cls, event_history: EventHistory) -> Dict[int, Dict[str, Any]]:+ """+ Group video-capable sensors by their parent entity.++ Returns:+ Dict mapping entity.id to {'entity': Entity, 'sensors': [Sensor, ...]}+ """+ video_entities = {}++ for clause in event_history.event_definition.event_clauses.all():+ entity = clause.entity_state.entity+ for sensor in clause.entity_state.sensors.all():+ if sensor.provides_video_stream:+ if entity.id not in video_entities:+ video_entities[entity.id] = {+ 'entity': entity,+ 'sensors': []+ }+ video_entities[entity.id]['sensors'].append(sensor)++ return video_entities++ @classmethod+ def _create_entity_display_list(cls, event_history: EventHistory,+ video_entities: Dict[int, Dict[str, Any]]) -> List[Dict[str, Any]]:+ """+ Create unified entity display list for template rendering.++ Returns:+ List of dicts with keys: 'entity', 'has_video', 'video_sensor'+ """+ entity_display_list = []++ for clause in event_history.event_definition.event_clauses.all():+ entity = clause.entity_state.entity++ # Check if this entity has video capability+ video_info = video_entities.get(entity.id)+ if video_info:+ # Entity has video - create display object with video info+ entity_display_list.append({+ 'entity': entity,+ 'has_video': True,+ 'video_sensor': video_info['sensors'][0] # Use first available video sensor+ })+ else:+ # Entity has no video - create display object for text display+ entity_display_list.append({+ 'entity': entity,+ 'has_video': False,+ 'video_sensor': None+ })++ return entity_display_list++ @classmethod+ def _add_timestamp_adjustment(cls, event_history: EventHistory) -> None:+ """Add adjusted timestamp for inclusive video browser results."""+ # Add 2 minutes to event timestamp for inclusive video browser results+ # This ensures we capture the triggering response + surrounding context+ adjusted_timestamp = event_history.event_datetime + timezone.timedelta(minutes=2)+ event_history.video_url_timestamp = int(adjusted_timestamp.timestamp())diff --git a/src/hi/apps/event/views.py b/src/hi/apps/event/views.pyindex fbabfa43..ca849026 100644--- a/src/hi/apps/event/views.py+++ b/src/hi/apps/event/views.py@@ -1,4 +1,5 @@from django.urls import reverse+from django.utils import timezonefrom hi.apps.common.pagination import compute_pagination_from_querysetfrom hi.apps.config.enums import ConfigPageType@@ -7,6 +8,7 @@ from hi.apps.config.views import ConfigPageViewfrom hi.hi_async_view import HiModalViewfrom .models import EventDefinition, EventHistory+from .view_helpers import EventHistoryViewHelperclass EventDefinitionsView( ConfigPageView ):@@ -43,16 +45,30 @@ class EventHistoryView( HiModalView ):base_url = reverse( 'event_history' )- queryset = EventHistory.objects.all()+ queryset = EventHistory.objects.select_related(+ 'event_definition'+ ).prefetch_related(+ 'event_definition__event_clauses__entity_state__entity'+ ).all()pagination = compute_pagination_from_queryset( request = request,queryset = queryset,base_url = base_url,page_size = self.EVENT_HISTORY_PAGE_SIZE,async_urls = True )- event_history_list = queryset[pagination.start_offset:pagination.end_offset + 1]+ event_history_list = list(queryset[pagination.start_offset:pagination.end_offset + 1])++ # Enhance event history objects with computed fields for display and video integration+ EventHistoryViewHelper.enhance_event_history_list(event_history_list)++ # Add timezone-aware date context for template+ now = timezone.now()+ today = now.date()+ yesterday = today - timezone.timedelta(days=1)context = {'event_history_list': event_history_list,'pagination': pagination,+ 'today': today,+ 'yesterday': yesterday,}return self.modal_response( request, context )diff --git a/src/hi/static/css/main.css b/src/hi/static/css/main.cssindex b73515c1..726bf820 100644--- a/src/hi/static/css/main.css+++ b/src/hi/static/css/main.css@@ -181,6 +181,41 @@ a.clickable-card:active {background-color: var(--muted-color) !important;}+/* Outline Button Overrides */+.btn-outline-primary {+ color: var(--primary-color) !important;+ border-color: var(--primary-color) !important;+ background-color: transparent !important;+}+.btn-outline-primary:hover,+.btn-outline-primary:focus,+.btn-outline-primary:active,+.btn-outline-primary.active {+ color: var(--on-primary-color) !important;+ background-color: var(--primary-color) !important;+ border-color: var(--primary-highlight-color) !important;+}+.btn-outline-primary:focus {+ box-shadow: 0 0 0 0.2rem rgba(23, 112, 114, 0.25) !important;+}++.btn-outline-secondary {+ color: var(--secondary-color) !important;+ border-color: var(--secondary-color) !important;+ background-color: transparent !important;+}+.btn-outline-secondary:hover,+.btn-outline-secondary:focus,+.btn-outline-secondary:active,+.btn-outline-secondary.active {+ color: var(--on-secondary-color) !important;+ background-color: var(--secondary-color) !important;+ border-color: var(--secondary-highlight-color) !important;+}+.btn-outline-secondary:focus {+ box-shadow: 0 0 0 0.2rem rgba(244, 95, 54, 0.25) !important;+}+.interstitial-page {display: flex;flex-wrap: wrap;