Skip to content

Home Information - Your home, your data, organized.

Python

Enhanced Alert Details Dialog (Issue #84) (#85)

cassandra-ai-agent1a91499ebce8
diff --git a/docs/CLAUDE.md b/docs/CLAUDE.md
index 4da333ba..661f18ff 100644
--- a/docs/CLAUDE.md
+++ b/docs/CLAUDE.md
@@ -2,6 +2,46 @@
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
+## Quick Reference - Common Process Checkpoints
+
+**Before Starting Development:**
+- [ ] On staging branch with latest changes (`git status`, `git pull origin staging`)
+- [ ] Use TodoWrite tool to plan tasks (mandatory for complex work)
+- [ ] Create properly named feature branch
+
+**Before Any Commit:**
+- [ ] Use concise commit messages WITHOUT Claude attribution
+- [ ] Examples: "Fix UI testing framework system state issue" βœ…
+- [ ] Avoid: "πŸ€– Generated with Claude Code" ❌
+
+**Before Creating Pull Request:**
+- [ ] `src/manage.py test` (must show "OK")
+- [ ] `flake8 --config=src/.flake8-ci src/hi/` (must show no output)
+- [ ] Both MUST pass before PR creation
+
+**Process Verification Pattern:**
+Before major actions, ask yourself:
+1. "Did I use TodoWrite to plan this work?"
+2. "Have I run all required tests?"
+3. "Is my commit message following guidelines?"
+4. "Am I on the correct branch with latest staging changes?"
+
+## Task Management (TodoWrite Tool)
+
+**MANDATORY for complex tasks**: Use TodoWrite tool extensively for:
+- Planning multi-step implementations
+- Breaking down complex issues into phases
+- Tracking progress during development
+- Including testing and validation steps in todos
+- Ensuring no steps are forgotten
+
+**Use immediately when starting work on:**
+- GitHub issues with multiple requirements
+- Refactoring tasks
+- Any work involving multiple files or components
+
+IMPORTANT: Always use the TodoWrite tool to plan and track tasks throughout the conversation.
+
## Development Workflow for GitHub Issues
When working on GitHub issues, follow this development workflow:
@@ -9,30 +49,91 @@ When working on GitHub issues, follow this development workflow:
1. **Read the GitHub issue and all its comments** - Understand the requirements, context, and any discussion
2. **Ensure you're on the latest staging branch** - MANDATORY step before any work:
- - If coming from a merged PR, run Post-PR Cleanup first (see step 10)
+ - If coming from a merged PR, run Post-PR Cleanup first (see step 11)
- Switch to staging branch: `git checkout staging`
- Pull latest changes: `git pull origin staging`
- Verify you're on the correct branch: `git status`
-3. **Investigate and plan the implementation** - MANDATORY step for all issues:
+3. **Create a feature branch immediately** - MANDATORY before any investigation or changes:
+ - Use proper naming convention based on issue type:
+ - **Bug fixes**: `bugfix/##-description` (e.g., `bugfix/31-controller-modal-fix`)
+ - **New features**: `feature/##-description` (e.g., `feature/45-weather-alerts`)
+ - **Documentation**: `docs/##-description` (e.g., `docs/22-api-documentation`)
+ - **Operations**: `ops/##-description` (e.g., `ops/18-docker-improvements`)
+ - **Refactoring**: `refactor/##-description` (e.g., `refactor/33-cleanup-views`)
+ - **Why create immediately**: Investigation may involve temporary file changes, and it's safer to work on a branch
+ - **If no changes needed**: Simply delete the unused branch with `git branch -d branch-name`
+ - See `docs/dev/Workflow.md` for complete conventions including test-only and tweak branches
+
+4. **Use TodoWrite tool to plan the work** - MANDATORY for complex tasks:
+ - Break down the issue into specific, actionable tasks
+ - Include investigation, implementation, testing, and validation steps
+ - Mark tasks as in_progress/completed as you work
+
+5. **Investigate and plan the implementation** - MANDATORY step for all issues:
- Assign the issue to yourself: `gh issue edit <issue-number> --add-assignee @me`
- Research the codebase to understand current implementation
- Identify files, functions, and components that need changes
- Consider edge cases, dependencies, and potential impacts
+ - **Check for design-heavy issues** - If issue involves both design/UX work AND implementation, consider splitting (see Design-Heavy Issue Detection below)
- Plan the implementation approach and sequence of changes
- **Post a comment on the GitHub issue** documenting:
- Summary of investigation findings
- Proposed implementation approach
- Key files/components that will be modified
- Any questions or concerns identified
+ - Issue splitting recommendation if applicable
- **Wait for confirmation only if**:
- You have critical questions that could affect the implementation
- Important information is missing or unclear from the issue
- Multiple solution approaches exist with no clear best choice
- The proposed changes have significant architectural implications
+ - **You recommend splitting a design-heavy issue**
- Otherwise, proceed directly to implementation
-3.5. **For Complex Issues - Apply Multi-Phase Strategy** (when applicable):
+#### Design-Heavy Issue Detection and Splitting
+
+During investigation, if an issue involves **both** design/UX work **and** implementation:
+
+**Indicators of design-heavy issues:**
+- Requests for "better styling", "improved layout", "enhanced UI"
+- Mentions of wireframes, mockups, or visual design
+- Ambiguous visual requirements needing clarification
+- Multiple UI components or significant template changes
+- User experience improvements without specific implementation details
+
+**Recommended approach:**
+1. **Suggest issue splitting** in your GitHub comment:
+ ```
+ Based on investigation, this issue involves both design and implementation work.
+ I recommend splitting this into:
+
+ - Issue A: "[Original Title] - Design & Wireframes"
+ - Create wireframes/mockups
+ - Define visual approach and information architecture
+ - Get stakeholder approval on design direction
+
+ - Issue B: "[Original Title] - Implementation"
+ - Implement approved design
+ - Code templates and styling
+ - Add tests and validation
+
+ This approach allows design iteration without blocking implementation and
+ enables focused review of each phase.
+ ```
+
+2. **Wait for confirmation** before proceeding (this falls under the "significant architectural implications" case)
+
+3. **If splitting approved**: Complete design work in current issue, create implementation issue upon design approval
+
+4. **If splitting declined**: Proceed but use multi-phase strategy with design as Phase 1
+
+**Design Phase Deliverables:**
+- Always include wireframes/mockups as GitHub issue comments with images
+- Get explicit "approved for implementation" comment before coding begins
+- Use GitHub issue linking (`Closes #123`) to maintain traceability between design and implementation issues
+
+5.5. **For Complex Issues - Apply Multi-Phase Strategy** (when applicable):
- If issue involves multiple aspects, significant trade-offs, or substantial complexity, apply the multi-phase methodology from [Guidelines.md](dev/Guidelines.md#complex-issue-implementation-strategy)
- Post phase breakdown to GitHub issue before starting implementation
- Complete Phase 1 fully, commit and push (but don't create PR yet)
@@ -41,20 +142,17 @@ When working on GitHub issues, follow this development workflow:
- Wait for human feedback before proceeding to subsequent phases
- Only create PR when all phases complete or explicitly requested
-4. **Development environment check** - The virtual environment and necessary environment variables should be set before starting claude. If there is no virtual environment, this is an indication that the environment has not been properly set up. That means the unit test cannot run and code changes cannot be validated. We shoudl stop the process and fix it. There is no need to check ever time since this shoudl be rare, but if running tests is failing, that is a good thing to look for.
+6. **Development environment check** - The virtual environment and necessary environment variables should be set before starting claude. If there is no virtual environment, this is an indication that the environment has not been properly set up. That means the unit test cannot run and code changes cannot be validated. We shoudl stop the process and fix it. There is no need to check ever time since this shoudl be rare, but if running tests is failing, that is a good thing to look for.
-5. **Create a dev branch off the staging branch** - Use proper naming convention:
- - **Bug fixes**: `bugfix/##-description` (e.g., `bugfix/31-controller-modal-fix`)
- - **New features**: `feature/##-description` (e.g., `feature/45-weather-alerts`)
- - **Documentation**: `docs/##-description` (e.g., `docs/22-api-documentation`)
- - **Operations**: `ops/##-description` (e.g., `ops/18-docker-improvements`)
- - **Refactoring**: `refactor/##-description` (e.g., `refactor/33-cleanup-views`)
- - See `docs/dev/Workflow.md` for complete conventions including test-only and tweak branches
-6. **Do development changes** - Commit to git at logical checkpoints during development
-7. **After first commit, push the branch to GitHub** - Use the same branch name as the local one
-8. **Once issue is complete and all changes pushed** - Create a pull request using the template
-9. **Before creating the pull request** - Run full test validation (see Testing Workflow below)
-10. **After pull request is merged** - Clean up and prepare for next work (see Post-PR Cleanup below)
+7. **Do development changes** - Commit to git at logical checkpoints during development
+
+8. **After first commit, push the branch to GitHub** - Use the same branch name as the local one
+
+9. **Run Testing Workflow** - MANDATORY before creating PR (see below)
+
+10. **Create a pull request** - Using the template, only after all tests pass
+
+11. **After pull request is merged** - Clean up and prepare for next work (see Post-PR Cleanup below)
### Testing Workflow (Required Before Pull Requests)
@@ -70,10 +168,6 @@ src/manage.py test
# 2. Run code quality check (only if source code was modified)
flake8 --config=src/.flake8-ci src/hi/
# Must show: no output (clean)
-
-# 3. Verify Django configuration
-src/manage.py check
-# Must show: "System check identified no issues"
```
**Important**: Do not create pull requests if any of these checks fail. Fix all issues first.
@@ -84,13 +178,32 @@ Before any pull request can be merged, the following requirements must be met:
1. **Unit Tests**: All unit tests must pass (`src/manage.py test`)
2. **Code Quality**: flake8 linting with `.flake8-ci` configuration must pass with no violations (if source code modified) (`flake8 --config=src/.flake8-ci src/hi/`)
-3. **Django Check**: Django system check must pass with no issues (`src/manage.py check`)
-4. **GitHub CI**: GitHub Actions will automatically verify these requirements and will block PR merging if they fail
+3. **GitHub CI**: GitHub Actions will automatically verify these requirements and will block PR merging if they fail
These requirements are enforced by GitHub branch protection rules and cannot be bypassed.
For detailed branching conventions and additional workflow information, see `docs/dev/Workflow.md`.
+## Commit Message Guidelines (Claude-Specific)
+
+- Use concise, descriptive commit messages without attribution text
+- Focus on **what** was changed and **why**, not implementation details
+- Keep messages professional and project-focused
+- **Do NOT include** Claude Code attribution, co-author tags, or generated-by comments
+
+**Good examples:**
+```
+Fix weather module unit test failures and improve WMO units handling
+Add support for temperature offset unit arithmetic in Pint
+Remove invalid AlertUrgency.PAST enum value for weather alerts
+```
+
+**Avoid:**
+```
+πŸ€– Generated with Claude Code
+Co-Authored-By: Claude <[email protected]>
+```
+
### Post-PR Cleanup (After Pull Request Merged)
**HUMAN INITIATED**: This workflow must be triggered manually when you confirm a PR has been merged. Never run without explicit confirmation that the PR is merged.
@@ -216,22 +329,34 @@ All generated code must comply with the `.flake8-ci` configuration rules. Common
Before submitting code, always run: `flake8 --config=src/.flake8-ci src/hi/` to verify compliance.
-## Commit Message Guidelines (Claude-Specific)
+## Django Template Guidelines (Claude-Specific)
-- Use concise, descriptive commit messages without attribution text
-- Focus on **what** was changed and **why**, not implementation details
-- Keep messages professional and project-focused
-- **Do NOT include** Claude Code attribution, co-author tags, or generated-by comments
+Follow Django best practices for template design:
+
+1. **Minimal Business Logic**: Keep business logic out of templates. Complex loops, conditionals, and data processing belong in views or custom template tags/filters.
+2. **View Preparation**: Views should prepare all data that templates need. Templates should primarily display pre-processed data.
+3. **Simple Conditionals**: Use only simple `{% if %}` statements for display logic. Avoid complex nested loops or data manipulation.
+4. **Custom Template Tags**: Create custom template tags or filters for reusable template logic instead of embedding it directly.
+5. **Data Structure**: Structure context data in views to match template needs rather than making templates adapt to raw data.
**Good examples:**
-```
-Fix weather module unit test failures and improve WMO units handling
-Add support for temperature offset unit arithmetic in Pint
-Remove invalid AlertUrgency.PAST enum value for weather alerts
+```python
+# In view
+context = {
+ 'alert': alert,
+ 'alert_has_visual_content': bool(alert.get_first_image_url()),
+ 'alert_first_image': alert.get_first_image_url(),
+}
```
**Avoid:**
-```
-πŸ€– Generated with Claude Code
-Co-Authored-By: Claude <[email protected]>
-```
+```django
+<!-- Complex business logic in template -->
+{% for alarm in alert.alarm_list %}
+ {% for source_details in alarm.source_details_list %}
+ {% if source_details.image_url %}
+ <!-- Complex nested logic -->
+ {% endif %}
+ {% endfor %}
+{% endfor %}
+```
\ No newline at end of file
diff --git a/docs/dev/Testing.md b/docs/dev/Testing.md
index 7a622720..94264676 100644
--- a/docs/dev/Testing.md
+++ b/docs/dev/Testing.md
@@ -796,6 +796,73 @@ urlpatterns = [
]
```
+### UI Testing Framework Guidelines
+
+The visual testing framework at `/tests/ui` is designed for viewing UI styling and layout during development. These are **read-only** views that should never modify system state.
+
+#### Critical UI Testing Principle: System State Isolation
+
+**NEVER modify real system state in UI test views**:
+- Do not add data to real managers (AlertManager, WeatherManager, etc.)
+- Do not modify database records
+- Do not modify in-memory caches or singletons
+- Do not persist test data that appears in production views
+
+**Correct Approach - Render Templates Directly:**
+```python
+class TestUiAlertDetailsView(View):
+ def get(self, request, *args, **kwargs):
+ # Create synthetic data
+ alert = AlertSyntheticData.create_single_alarm_alert(
+ alarm_level=AlarmLevel.WARNING,
+ has_image=True
+ )
+
+ # Prepare context data using domain object methods
+ visual_content = alert.get_first_visual_content()
+
+ # Render template directly with synthetic data
+ context = {
+ 'alert': alert,
+ 'alert_visual_content': visual_content,
+ }
+ return render(request, 'alert/modals/alert_details.html', context)
+```
+
+**Incorrect Approach - Modifying System State:**
+```python
+# BAD - This modifies real AlertManager state
+class TestUiAlertDetailsView(AlertDetailsView, AlertMixin):
+ def get(self, request, *args, **kwargs):
+ alert = self._create_synthetic_alert(alert_type)
+
+ # WRONG - Adding to real system manager
+ alert_manager = self.alert_manager()
+ alert_manager._alert_queue._alert_list.append(alert)
+
+ return super().get(request, *args, **kwargs)
+```
+
+#### UI Testing Architecture Patterns
+
+**When to Inherit vs. Render Directly:**
+
+1. **Render Templates Directly (Preferred):**
+ - For testing UI styling and layout
+ - When you need specific synthetic data scenarios
+ - When testing requires system state isolation
+ - Follows pattern used by weather, notify modules
+
+2. **Inherit from Production Views (Avoid):**
+ - Only when testing actual view logic, not just UI styling
+ - Requires careful state management to avoid system pollution
+ - Must ensure test data doesn't persist
+
+**Code Duplication Prevention:**
+- Move shared logic to domain object methods (e.g., `Alert.get_first_visual_content()`)
+- Use centralized synthetic data classes
+- Create utility functions for common data preparation patterns
+
### Email Testing
There are some helper base classes to test viewing email formatting and sending emails.
diff --git a/src/hi/apps/alert/alert.py b/src/hi/apps/alert/alert.py
index 1f59a4a3..60065a77 100644
--- a/src/hi/apps/alert/alert.py
+++ b/src/hi/apps/alert/alert.py
@@ -115,6 +115,21 @@ class Alert:
return self._latest_alarms[0]
return None
+ def get_first_visual_content(self):
+ """
+ Find the first image/video content from any alarm in the alert.
+ Returns dict with image info or None if no visual content found.
+ """
+ for alarm in self.alarm_list:
+ for source_details in alarm.source_details_list:
+ if source_details.image_url:
+ return {
+ 'image_url': source_details.image_url,
+ 'alarm': alarm,
+ 'is_from_latest': alarm == self.alarm_list[0] if self.alarm_list else False,
+ }
+ return None
+
def to_notification_item(self):
return NotificationItem(
signature = self.signature,
diff --git a/src/hi/apps/alert/templates/alert/modals/alert_details.html b/src/hi/apps/alert/templates/alert/modals/alert_details.html
index 35bc7176..633408e2 100644
--- a/src/hi/apps/alert/templates/alert/modals/alert_details.html
+++ b/src/hi/apps/alert/templates/alert/modals/alert_details.html
@@ -8,26 +8,114 @@
{% block body %}
{% timezone USER_TIMEZONE %}
-<div>
- Alert Source: {{ alert.alarm_source.label }}
-</div>
-<div>
- Alert Level: {{ alert.alarm_level.label }}
+
+<!-- Alert Summary Header -->
+<div class="row mb-3">
+ <div class="col-12">
+ <div class="card border-0 bg-light">
+ <div class="card-body py-2">
+ <div class="row">
+ <div class="col-6">
+ <small class="text-muted">Alert Level</small><br>
+ <span class="badge badge-{% if alert.alarm_level.priority <= 2 %}danger{% elif alert.alarm_level.priority <= 4 %}warning{% else %}secondary{% endif %}">
+ {{ alert.alarm_level.label }}
+ </span>
+ </div>
+ <div class="col-6">
+ <small class="text-muted">Alert Source</small><br>
+ <strong>{{ alert.alarm_source.label }}</strong>
+ </div>
+ </div>
+ <div class="row mt-2">
+ <div class="col-6">
+ <small class="text-muted">Alert Type</small><br>
+ <strong>{{ alert.alarm_type }}</strong>
+ </div>
+ <div class="col-6">
+ <small class="text-muted">Started</small><br>
+ <strong>{{ alert.start_datetime|localtime|naturaltime }}</strong>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
</div>
-<div>
- Alert Type: {{ alert.alarm_type }}
+
+<!-- Visual Content (if available) -->
+{% if alert_visual_content %}
+<div class="row mb-3">
+ <div class="col-12">
+ <div class="card">
+ <div class="card-header bg-primary text-white">
+ <h6 class="mb-0">
+ <i class="fas fa-camera mr-2"></i>Visual Content
+ </h6>
+ </div>
+ <div class="card-body p-2">
+ <img class="img-fluid" src="{{ alert_visual_content.image_url }}" alt="{{ alert_visual_content.alarm.title }}">
+ {% if not alert_visual_content.is_from_latest %}
+ <small class="text-muted d-block mt-1">From: {{ alert_visual_content.alarm.timestamp|localtime|date:"M j, Y H:i" }}</small>
+ {% endif %}
+ </div>
+ </div>
+ </div>
</div>
-<div>
- When: {{ alert.start_datetime|localtime|naturaltime }}
+{% endif %}
+
+<!-- Recent Alarm Details -->
+<div class="row mb-3">
+ <div class="col-12">
+ <div class="card">
+ <div class="card-header">
+ <h6 class="mb-0">
+ Recent Activity
+ {% if alert.alarm_count > 1 %}
+ <span class="badge badge-secondary ml-2">{{ alert.alarm_count }} alarm{{ alert.alarm_count|pluralize }}</span>
+ {% endif %}
+ </h6>
+ </div>
+ <div class="card-body">
+ {% with alarm=alert.alarm_list.0 %}
+ <div class="mb-2">
+ <small class="text-muted">{{ alarm.timestamp|localtime|date:"M j, Y H:i" }}</small>
+ </div>
+ {% include "alert/panes/alarm_details.html" %}
+ {% endwith %}
+ </div>
+ </div>
+ </div>
</div>
-<div>
- {% for alarm in alert.alarm_list %}
- {% if alert.alarm_count > 1 %}
- <h5>Alarm {{ forloop.counter }}: {{ alarm.title }}</h5>
- {% endif %}
- {% include "alert/panes/alarm_details.html" %}
- {% endfor %}
+<!-- Additional Alarms (Collapsible) -->
+{% if alert.alarm_count > 1 %}
+<div class="row">
+ <div class="col-12">
+ <div class="card">
+ <div class="card-header">
+ <h6 class="mb-0">
+ <a class="text-decoration-none" data-toggle="collapse" href="#additionalAlarms"
+ role="button" aria-expanded="false" aria-controls="additionalAlarms">
+ <i class="fas fa-chevron-right mr-2"></i>Previous Alarms ({{ alert.alarm_count|add:"-1" }})
+ </a>
+ </h6>
+ </div>
+ <div class="collapse" id="additionalAlarms">
+ <div class="card-body">
+ {% for alarm in alert.alarm_list %}
+ {% if not forloop.first %}
+ <div class="border-bottom mb-3 pb-3">
+ <h6>Alarm {{ forloop.counter }}: {{ alarm.title }}</h6>
+ <small class="text-muted">{{ alarm.timestamp|localtime|date:"M j, Y H:i" }}</small>
+ {% include "alert/panes/alarm_details.html" %}
+ </div>
+ {% endif %}
+ {% endfor %}
+ </div>
+ </div>
+ </div>
+ </div>
</div>
+{% endif %}
+
{% endtimezone %}
{% endblock %}
diff --git a/src/hi/apps/alert/templates/alert/tests/ui/home.html b/src/hi/apps/alert/templates/alert/tests/ui/home.html
new file mode 100644
index 00000000..73b7e809
--- /dev/null
+++ b/src/hi/apps/alert/templates/alert/tests/ui/home.html
@@ -0,0 +1,54 @@
+{% extends "pages/base.html" %}
+{% block head_title %}HI: Visual Testing!{% endblock %}
+
+{% block content %}
+<div class="container-fluid m-4">
+
+ <h2 class="text-info">Alerts: UI Tests</h2>
+
+ <div class="row">
+ <div class="col-xl-4 col-lg-4 col-md-6 col-12">
+ <div class="panel panel-default">
+ <div class="panel-heading">
+ <h3 class="panel-title text-primary">Alert Details</h3>
+ </div>
+ <div class="panel-body">
+ <ul>
+ <li>
+ <a href="{% url 'alert_tests_ui_alert_details' alert_type='single_info' %}" data-async="modal">
+ Single Alarm (INFO, no image)
+ </a>
+ </li>
+ <li>
+ <a href="{% url 'alert_tests_ui_alert_details' alert_type='single_warning_image' %}" data-async="modal">
+ Single Alarm (WARNING, with image)
+ </a>
+ </li>
+ <li>
+ <a href="{% url 'alert_tests_ui_alert_details' alert_type='single_critical_video' %}" data-async="modal">
+ Single Alarm (CRITICAL, with video)
+ </a>
+ </li>
+ <li>
+ <a href="{% url 'alert_tests_ui_alert_details' alert_type='multiple_alarms' %}" data-async="modal">
+ Multiple Alarms (3 alarms, with images)
+ </a>
+ </li>
+ <li>
+ <a href="{% url 'alert_tests_ui_alert_details' alert_type='event_based' %}" data-async="modal">
+ Event-Based Alert (door sensor)
+ </a>
+ </li>
+ <li>
+ <a href="{% url 'alert_tests_ui_alert_details' alert_type='weather_alert' %}" data-async="modal">
+ Weather Alert (tornado warning)
+ </a>
+ </li>
+ </ul>
+ </div>
+ </div>
+ </div>
+ </div>
+
+</div>
+{% endblock %}
\ No newline at end of file
diff --git a/src/hi/apps/alert/tests/synthetic_data.py b/src/hi/apps/alert/tests/synthetic_data.py
index abec5616..64287633 100644
--- a/src/hi/apps/alert/tests/synthetic_data.py
+++ b/src/hi/apps/alert/tests/synthetic_data.py
@@ -12,6 +12,190 @@ from hi.apps.security.enums import SecurityLevel
class AlertSyntheticData:
+ @classmethod
+ def create_single_alarm_alert( cls,
+ alarm_level : AlarmLevel = AlarmLevel.INFO,
+ alarm_source : AlarmSource = AlarmSource.EVENT,
+ alarm_type : str = 'Motion Detection',
+ title : str = None,
+ has_image : bool = False,
+ detail_attrs : dict = None,
+ security_level : SecurityLevel = SecurityLevel.LOW,
+ alarm_lifetime_secs : int = 300,
+ timestamp : datetime = None ) -> Alert:
+ """Create a single alert with one alarm for testing."""
+
+ if not timestamp:
+ timestamp = datetimeproxy.now()
+ if not title:
+ title = f'{alarm_level.label}: {alarm_type}'
+ if not detail_attrs:
+ detail_attrs = {'Location': 'Kitchen', 'Sensor': 'Motion-01'}
+
+ image_url = '/static/img/hi-icon-196x196.png' if has_image else None
+
+ alarm = Alarm(
+ alarm_source = alarm_source,
+ alarm_type = alarm_type,
+ alarm_level = alarm_level,
+ title = title,
+ source_details_list = [
+ AlarmSourceDetails(
+ detail_attrs = detail_attrs,
+ image_url = image_url,
+ ),
+ ],
+ security_level = security_level,
+ alarm_lifetime_secs = alarm_lifetime_secs,
+ timestamp = timestamp,
+ )
+
+ return Alert( first_alarm = alarm )
+
+ @classmethod
+ def create_multiple_alarm_alert( cls,
+ alarm_count : int = 3,
+ alarm_level : AlarmLevel = AlarmLevel.WARNING,
+ alarm_source : AlarmSource = AlarmSource.EVENT,
+ alarm_type : str = 'Repeated Motion',
+ base_title : str = 'Repeated motion detected',
+ has_image : bool = True,
+ base_detail_attrs : dict = None,
+ security_level : SecurityLevel = SecurityLevel.LOW,
+ alarm_lifetime_secs : int = 600,
+ reference_datetime : datetime = None,
+ time_interval_mins : int = 1 ) -> Alert:
+ """Create a single alert with multiple alarms for testing."""
+
+ if not reference_datetime:
+ reference_datetime = datetimeproxy.now()
+ if not base_detail_attrs:
+ base_detail_attrs = {'Location': 'Living Room', 'Sensor': 'Motion-02'}
+
+ # Create first alarm
+ image_url = '/static/img/hi-icon-196x196.png' if has_image else None
+ detail_attrs = dict(base_detail_attrs)
+ detail_attrs.update({'Count': f'1 of {alarm_count}'})
+
+ first_alarm = Alarm(
+ alarm_source = alarm_source,
+ alarm_type = alarm_type,
+ alarm_level = alarm_level,
+ title = f'{alarm_level.label}: {base_title}',
+ source_details_list = [
+ AlarmSourceDetails(
+ detail_attrs = detail_attrs,
+ image_url = image_url,
+ ),
+ ],
+ security_level = security_level,
+ alarm_lifetime_secs = alarm_lifetime_secs,
+ timestamp = reference_datetime - timedelta(minutes=time_interval_mins * (alarm_count - 1)),
+ )
+
+ alert = Alert( first_alarm = first_alarm )
+
+ # Add additional alarms
+ for i in range(2, alarm_count + 1):
+ detail_attrs = dict(base_detail_attrs)
+ detail_attrs.update({'Count': f'{i} of {alarm_count}'})
+
+ additional_alarm = Alarm(
+ alarm_source = alarm_source,
+ alarm_type = alarm_type,
+ alarm_level = alarm_level,
+ title = f'{alarm_level.label}: {base_title} ({i})',
+ source_details_list = [
+ AlarmSourceDetails(
+ detail_attrs = detail_attrs,
+ image_url = image_url if i == 2 else None, # Only second alarm has image
+ ),
+ ],
+ security_level = security_level,
+ alarm_lifetime_secs = alarm_lifetime_secs,
+ timestamp = reference_datetime - timedelta(minutes=time_interval_mins * (alarm_count - i)),
+ )
+ alert.add_alarm( additional_alarm )
+
+ return alert
+
+ @classmethod
+ def create_event_based_alert( cls,
+ event_name : str = 'Door Open Event',
+ entity_name : str = 'front-door-sensor',
+ location : str = 'Front Door',
+ previous_state : str = 'Closed',
+ current_state : str = 'Open',
+ has_image : bool = False,
+ alarm_level : AlarmLevel = AlarmLevel.INFO ) -> Alert:
+ """Create an event-based alert for testing."""
+
+ image_url = '/static/img/hi-icon-196x196.png' if has_image else None
+ detail_attrs = {
+ 'Event': event_name,
+ 'Location': location,
+ 'Previous State': previous_state,
+ 'Current State': current_state,
+ 'Entity': entity_name
+ }
+
+ alarm = Alarm(
+ alarm_source = AlarmSource.EVENT,
+ alarm_type = event_name,
+ alarm_level = alarm_level,
+ title = f'{alarm_level.label}: {location} {event_name.lower()}',
+ source_details_list = [
+ AlarmSourceDetails(
+ detail_attrs = detail_attrs,
+ image_url = image_url,
+ ),
+ ],
+ security_level = SecurityLevel.LOW,
+ alarm_lifetime_secs = 180,
+ timestamp = datetimeproxy.now(),
+ )
+
+ return Alert( first_alarm = alarm )
+
+ @classmethod
+ def create_weather_alert( cls,
+ alert_type : str = 'Tornado Warning',
+ location : str = 'Travis County, TX',
+ urgency : str = 'Immediate',
+ severity : str = 'Extreme',
+ expires_in_mins : int = 45,
+ has_image : bool = False ) -> Alert:
+ """Create a weather-based alert for testing."""
+
+ image_url = '/static/img/hi-icon-196x196.png' if has_image else None
+ detail_attrs = {
+ 'Alert Type': alert_type,
+ 'Location': location,
+ 'Urgency': urgency,
+ 'Severity': severity,
+ 'Event': alert_type.split()[0], # 'Tornado' from 'Tornado Warning'
+ 'Effective': 'Now',
+ 'Expires': f'In {expires_in_mins} minutes'
+ }
+
+ alarm = Alarm(
+ alarm_source = AlarmSource.WEATHER,
+ alarm_type = 'Severe Weather',
+ alarm_level = AlarmLevel.CRITICAL,
+ title = f'CRITICAL: {alert_type} issued',
+ source_details_list = [
+ AlarmSourceDetails(
+ detail_attrs = detail_attrs,
+ image_url = image_url,
+ ),
+ ],
+ security_level = SecurityLevel.HIGH,
+ alarm_lifetime_secs = expires_in_mins * 60,
+ timestamp = datetimeproxy.now(),
+ )
+
+ return Alert( first_alarm = alarm )
+
@classmethod
def create_random_alert_status_data( cls,
reference_datetime : datetime = None,
diff --git a/src/hi/apps/alert/tests/test_alert.py b/src/hi/apps/alert/tests/test_alert.py
index 44b7c176..060e119c 100644
--- a/src/hi/apps/alert/tests/test_alert.py
+++ b/src/hi/apps/alert/tests/test_alert.py
@@ -3,7 +3,7 @@ from datetime import timedelta
import hi.apps.common.datetimeproxy as datetimeproxy
from hi.apps.alert.alert import Alert
-from hi.apps.alert.alarm import Alarm
+from hi.apps.alert.alarm import Alarm, AlarmSourceDetails
from hi.apps.alert.enums import AlarmLevel, AlarmSource
from hi.apps.security.enums import SecurityLevel
from hi.tests.base_test_case import BaseTestCase
@@ -247,3 +247,142 @@ class TestAlert(BaseTestCase):
alert.add_alarm(second_alarm)
self.assertFalse(alert.has_single_alarm)
return
+
+ def test_get_first_visual_content_with_image(self):
+ """Test get_first_visual_content returns correct data when image exists."""
+ alarm_with_image = Alarm(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='motion_detection',
+ alarm_level=AlarmLevel.WARNING,
+ title='Motion Detected',
+ source_details_list=[
+ AlarmSourceDetails(
+ detail_attrs={'Location': 'Kitchen'},
+ image_url='/static/img/test-image.png',
+ )
+ ],
+ security_level=SecurityLevel.LOW,
+ alarm_lifetime_secs=300,
+ timestamp=datetimeproxy.now(),
+ )
+
+ alert = Alert(alarm_with_image)
+ visual_content = alert.get_first_visual_content()
+
+ self.assertIsNotNone(visual_content)
+ self.assertEqual(visual_content['image_url'], '/static/img/test-image.png')
+ self.assertEqual(visual_content['alarm'], alarm_with_image)
+ self.assertTrue(visual_content['is_from_latest'])
+ return
+
+ def test_get_first_visual_content_without_image(self):
+ """Test get_first_visual_content returns None when no image exists."""
+ alarm_no_image = Alarm(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='door_open',
+ alarm_level=AlarmLevel.INFO,
+ title='Door Opened',
+ source_details_list=[
+ AlarmSourceDetails(
+ detail_attrs={'Location': 'Front Door'},
+ image_url=None,
+ )
+ ],
+ security_level=SecurityLevel.LOW,
+ alarm_lifetime_secs=300,
+ timestamp=datetimeproxy.now(),
+ )
+
+ alert = Alert(alarm_no_image)
+ visual_content = alert.get_first_visual_content()
+
+ self.assertIsNone(visual_content)
+ return
+
+ def test_get_first_visual_content_multiple_alarms_first_has_image(self):
+ """Test get_first_visual_content finds image in first alarm when multiple alarms exist."""
+ first_alarm_with_image = Alarm(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='motion_detection',
+ alarm_level=AlarmLevel.WARNING,
+ title='First Motion',
+ source_details_list=[
+ AlarmSourceDetails(
+ detail_attrs={'Location': 'Kitchen'},
+ image_url='/static/img/first-image.png',
+ )
+ ],
+ security_level=SecurityLevel.LOW,
+ alarm_lifetime_secs=300,
+ timestamp=datetimeproxy.now(),
+ )
+
+ second_alarm_no_image = Alarm(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='motion_detection',
+ alarm_level=AlarmLevel.WARNING,
+ title='Second Motion',
+ source_details_list=[
+ AlarmSourceDetails(
+ detail_attrs={'Location': 'Kitchen'},
+ image_url=None,
+ )
+ ],
+ security_level=SecurityLevel.LOW,
+ alarm_lifetime_secs=300,
+ timestamp=datetimeproxy.now(),
+ )
+
+ alert = Alert(first_alarm_with_image)
+ alert.add_alarm(second_alarm_no_image)
+ visual_content = alert.get_first_visual_content()
+
+ self.assertIsNotNone(visual_content)
+ self.assertEqual(visual_content['image_url'], '/static/img/first-image.png')
+ self.assertEqual(visual_content['alarm'], first_alarm_with_image)
+ self.assertFalse(visual_content['is_from_latest']) # first_alarm_with_image is not at index 0 after adding second alarm
+ return
+
+ def test_get_first_visual_content_multiple_alarms_second_has_image(self):
+ """Test get_first_visual_content finds image in second alarm when first has none."""
+ first_alarm_no_image = Alarm(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='motion_detection',
+ alarm_level=AlarmLevel.WARNING,
+ title='First Motion',
+ source_details_list=[
+ AlarmSourceDetails(
+ detail_attrs={'Location': 'Kitchen'},
+ image_url=None,
+ )
+ ],
+ security_level=SecurityLevel.LOW,
+ alarm_lifetime_secs=300,
+ timestamp=datetimeproxy.now(),
+ )
+
+ second_alarm_with_image = Alarm(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='motion_detection',
+ alarm_level=AlarmLevel.WARNING,
+ title='Second Motion',
+ source_details_list=[
+ AlarmSourceDetails(
+ detail_attrs={'Location': 'Kitchen'},
+ image_url='/static/img/second-image.png',
+ )
+ ],
+ security_level=SecurityLevel.LOW,
+ alarm_lifetime_secs=300,
+ timestamp=datetimeproxy.now(),
+ )
+
+ alert = Alert(first_alarm_no_image)
+ alert.add_alarm(second_alarm_with_image)
+ visual_content = alert.get_first_visual_content()
+
+ self.assertIsNotNone(visual_content)
+ self.assertEqual(visual_content['image_url'], '/static/img/second-image.png')
+ self.assertEqual(visual_content['alarm'], second_alarm_with_image)
+ self.assertTrue(visual_content['is_from_latest']) # second_alarm_with_image is at index 0 after being added
+ return
diff --git a/src/hi/apps/alert/tests/ui/__init__.py b/src/hi/apps/alert/tests/ui/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/apps/alert/tests/ui/urls.py b/src/hi/apps/alert/tests/ui/urls.py
new file mode 100644
index 00000000..7aabfabd
--- /dev/null
+++ b/src/hi/apps/alert/tests/ui/urls.py
@@ -0,0 +1,15 @@
+from django.urls import re_path
+
+from . import views
+
+
+urlpatterns = [
+
+ re_path( r'^$',
+ views.TestUiAlertHomeView.as_view(),
+ name='alert_tests_ui'),
+
+ re_path( r'^details/(?P<alert_type>\w+)$',
+ views.TestUiAlertDetailsView.as_view(),
+ name='alert_tests_ui_alert_details'),
+]
diff --git a/src/hi/apps/alert/tests/ui/views.py b/src/hi/apps/alert/tests/ui/views.py
new file mode 100644
index 00000000..2afe2fd9
--- /dev/null
+++ b/src/hi/apps/alert/tests/ui/views.py
@@ -0,0 +1,79 @@
+from django.core.exceptions import BadRequest
+from django.shortcuts import render
+from django.views.generic import View
+
+from hi.apps.alert.enums import AlarmLevel
+from hi.apps.alert.tests.synthetic_data import AlertSyntheticData
+
+
+class TestUiAlertHomeView( View ):
+
+ def get(self, request, *args, **kwargs):
+ context = {
+ }
+ return render(request, "alert/tests/ui/home.html", context )
+
+
+class TestUiAlertDetailsView( View ):
+ """
+ View for testing alert details dialogs with various synthetic data scenarios.
+ Uses the centralized AlertSyntheticData class for consistent test data generation.
+ Renders the template directly without modifying system state.
+ """
+
+ def get( self, request, *args, **kwargs ):
+ alert_type = kwargs.get('alert_type')
+
+ # Create synthetic alert based on type using centralized synthetic data
+ alert = self._create_synthetic_alert( alert_type )
+
+ # Prepare visual content data for template using Alert's method
+ visual_content = alert.get_first_visual_content()
+
+ # Render template directly with synthetic data
+ context = {
+ 'alert': alert,
+ 'alert_visual_content': visual_content,
+ }
+ return render( request, 'alert/modals/alert_details.html', context )
+
+ def _create_synthetic_alert( self, alert_type ):
+ """Create different types of synthetic alerts for testing using AlertSyntheticData."""
+
+ if alert_type == 'single_info':
+ return AlertSyntheticData.create_single_alarm_alert(
+ alarm_level = AlarmLevel.INFO,
+ has_image = False
+ )
+ elif alert_type == 'single_warning_image':
+ return AlertSyntheticData.create_single_alarm_alert(
+ alarm_level = AlarmLevel.WARNING,
+ has_image = True,
+ detail_attrs = {'Location': 'Kitchen', 'Sensor': 'Motion-01', 'Image': 'Captured'}
+ )
+ elif alert_type == 'single_critical_video':
+ return AlertSyntheticData.create_single_alarm_alert(
+ alarm_level = AlarmLevel.CRITICAL,
+ has_image = True,
+ detail_attrs = {
+ 'Location': 'Kitchen',
+ 'Camera': 'Kitchen Camera',
+ 'Motion Detected': 'Yes',
+ 'Video Stream': 'Available'
+ }
+ )
+ elif alert_type == 'multiple_alarms':
+ return AlertSyntheticData.create_multiple_alarm_alert(
+ alarm_count = 3,
+ has_image = True
+ )
+ elif alert_type == 'event_based':
+ return AlertSyntheticData.create_event_based_alert(
+ has_image = True
+ )
+ elif alert_type == 'weather_alert':
+ return AlertSyntheticData.create_weather_alert(
+ has_image = False
+ )
+ else:
+ raise BadRequest( f'Unknown alert type: {alert_type}' )
diff --git a/src/hi/apps/alert/views.py b/src/hi/apps/alert/views.py
index 9a366786..aa5f67d2 100644
--- a/src/hi/apps/alert/views.py
+++ b/src/hi/apps/alert/views.py
@@ -44,8 +44,12 @@ class AlertDetailsView( HiModalView, AlertMixin ):
except KeyError:
raise Http404( 'Unknown alert.' )
+ # Prepare visual content data for template
+ visual_content = alert.get_first_visual_content()
+
context = {
'alert': alert,
+ 'alert_visual_content': visual_content,
}
return self.modal_response( request, context )