Skip to content

Home Information - Your home, your data, organized.

Python

Refactor developer documentation for role-based use (#126)

Tony C39c7266e778e
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index b88ad96f..d8bbebdd 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -32,12 +32,9 @@ Any and all feedback and ideas are welcome, such as:
### Software Development Contributions
-The following pages are for those wanting to contribute to the code base:
+The following page is for those wanting to contribute to the code base:
- [Development Page](docs/Development.md)
-- [Development Setup Page](docs/dev/Setup.md)
-- [Development Workflow Page](docs/dev/Workflow.md)
-- [Developer Documentation](docs/dev/README.md)
### Graphic and UX Design Contributions
diff --git a/docs/CLAUDE.md b/docs/CLAUDE.md
index c63cf453..0ece8f23 100644
--- a/docs/CLAUDE.md
+++ b/docs/CLAUDE.md
@@ -27,7 +27,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
- [ ] Follow `.github/PULL_REQUEST_TEMPLATE.md` structure
**Before Creating Unit Tests:**
-- [ ] Consult Testing guidelines and `docs/dev/Testing.md`
+- [ ] Consult Testing guidelines and `docs/dev/testing/testing-guidelines.md`
**Process Verification Pattern:**
Before major actions, ask yourself:
@@ -73,7 +73,7 @@ When working on GitHub issues, follow this development workflow:
- **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
+ - See `docs/dev/workflow/workflow-guidelines.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
@@ -144,7 +144,7 @@ During investigation, if an issue involves **both** design/UX work **and** imple
- 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)
+ - If issue involves multiple aspects, significant trade-offs, or substantial complexity, apply the multi-phase methodology from [Domain Guidelines](dev/domain/domain-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)
- Update TodoWrite tool with phase completion status
@@ -192,7 +192,7 @@ Before any pull request can be merged, the following requirements must be met:
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`.
+For detailed branching conventions and additional workflow information, see `docs/dev/workflow/workflow-guidelines.md`.
## Commit Message Guidelines (Claude-Specific)
@@ -315,15 +315,15 @@ src/manage.py runserver # http://127.0.0.1:8411
For comprehensive project information, see:
-- **Architecture**: [dev/Architecture.md](dev/Architecture.md) - System design, patterns, and component overview
-- **Development Guidelines**: [dev/Guidelines.md](dev/Guidelines.md) - Coding standards, style guide, and conventions
-- **Testing**: [dev/Testing.md](dev/Testing.md) - Testing patterns, best practices, and anti-patterns
+- **Architecture**: [dev/shared/architecture-overview.md](dev/shared/architecture-overview.md) - System design, patterns, and component overview
+- **Development Guidelines**: [dev/shared/coding-standards.md](dev/shared/coding-standards.md) - Coding standards, style guide, and conventions
+- **Testing**: [dev/testing/testing-guidelines.md](dev/testing/testing-guidelines.md) - Testing patterns, best practices, and anti-patterns
- **Setup**: [dev/Setup.md](dev/Setup.md) - Environment setup and daily development commands
-- **Workflow**: [dev/Workflow.md](dev/Workflow.md) - Branching, commits, and pull request process
+- **Workflow**: [dev/workflow/workflow-guidelines.md](dev/workflow/workflow-guidelines.md) - Branching, commits, and pull request process
## Release Process (Claude-Specific)
-When executing the release process documented in `docs/dev/ReleaseProcesses.md`, use these AI-specific commands and considerations:
+When executing the release process documented in `docs/dev/workflow/release-process.md`, use these AI-specific commands and considerations:
### Release Execution Commands
```bash
@@ -348,7 +348,7 @@ gh release create vX.X.X --title "vX.X.X" --generate-notes --latest
- **Documentation Changes**: Commit any documentation updates to staging before switching branches
- **GitHub CLI**: Prefer `gh` command for release creation over manual UI steps
-See `docs/dev/ReleaseProcesses.md` for the complete process documentation.
+See `docs/dev/workflow/release-process.md` for the complete process documentation.
## Generated Code Standards (Claude-Specific)
diff --git a/docs/Development.md b/docs/Development.md
index 3d6c3374..d8f6bc60 100644
--- a/docs/Development.md
+++ b/docs/Development.md
@@ -1,6 +1,6 @@
<img src="../src/hi/static/img/hi-logo-w-tagline-197x96.png" alt="Home Information Logo" width="128">
-# Development
+# Development Guide for Contributors
## Requirements and Dependencies
@@ -8,8 +8,6 @@
- Redis - installed and running.
- A GitHub account.
-See the [Dependencies Page](dev/Dependencies.md) if you want help installing those.
-
## Tech Stack
- Django 4.2 (back-end)
@@ -18,18 +16,29 @@ See the [Dependencies Page](dev/Dependencies.md) if you want help installing tho
- SQLite (database)
- Redis (caching)
-## Development Setup
+## Getting Started
+
+Follow these steps in order to begin contributing:
-See the [Development Setup Page](dev/Setup.md).
+- **[Environment Setup](dev/Setup.md)** - Install and configure your development environment
+- **[Contributor Workflow](dev/ContributorWorkflow.md)** - Git workflow and pull request process
-## Development Workflow
+## Core Guidelines (Essential Reading)
-See the [Development Workflow Page](dev/Workflow.md).
+These documents contain fundamental concepts that apply across all development areas:
-## Development Guidelines
+- **[Architecture Overview](dev/shared/architecture-overview.md)** - High-level system design and key patterns
+- **[Coding Standards](dev/shared/coding-standards.md)** - Code organization, style, and conventions
+- **[Data Model Concepts](dev/shared/data-model-concepts.md)** - Core domain models and relationships
+- **[Testing Guidelines](dev/testing/testing-guidelines.md)** - Testing philosophy, best practices, and anti-patterns
-See the [Development Guidelines Page](dev/Guidelines.md).
+## Development Areas
-## Developer Documentation
+Choose the area that matches your contribution focus and browse the relevant documentation:
-See the [Developer Documentation Page](dev/README.md).
+- **[Backend Development](dev/backend/)** - Django models, views, and business logic
+- **[Frontend Development](dev/frontend/)** - Templates, styling, and user interface
+- **[Testing](dev/testing/)** - Testing standards and patterns
+- **[Integration Development](dev/integrations/)** - External service integration and API patterns
+- **[Domain & Data Modeling](dev/domain/)** - Domain modeling and business logic
+- **[Shared Reference](dev/shared/)** - Common concepts used across all areas
diff --git a/docs/dev/AiAgentSetup.md b/docs/dev/AiAgentSetup.md
deleted file mode 100644
index fbbf2500..00000000
--- a/docs/dev/AiAgentSetup.md
+++ /dev/null
@@ -1,567 +0,0 @@
-# Setup for AI Agent Assistant
-
-**Goal**: Create a dedicated local user account and GitHub account for Claude Code operations, ensuring clear attribution and separation from personal development work.
-
-**Key Components**:
-- Dedicated local user account (`ai-agent`) on both macOS and Ubuntu
-- Separate GitHub user account for AI operations
-- Claude Code authentication on both platforms
-- GitHub CLI (`gh`) for GitHub operations
-
-## Create Dedicated User Accounts
-
-### MacOS
-
-Create dev-shared group
-```
-sudo dseditgroup -o create -n . dev-shared
-```
-
-Find which user ids exists on system and choose a non-existent one
-```
-dscl . -list /Users UniqueID | sort -k2 -n
-```
-
-Create ai-agent user
-```
-sudo dscl . -create /Users/ai-agent
-sudo dscl . -create /Users/ai-agent UserShell /bin/bash
-sudo dscl . -create /Users/ai-agent RealName "AI Agent for Claude Code"
-sudo dscl . -create /Users/ai-agent UniqueID 505
-sudo dscl . -create /Users/ai-agent PrimaryGroupID 20
-sudo dscl . -create /Users/ai-agent NFSHomeDirectory /Users/ai-agent
-```
-
-Add users to dev-shared group
-```
-sudo dseditgroup -o edit -a arc -t user dev-shared
-sudo dseditgroup -o edit -a ai-agent -t user dev-shared
-```
-
-Create home directory with proper permissions
-```
-sudo createhomedir -c -u ai-agent
-sudo chown ai-agent:dev-shared /Users/ai-agent
-sudo chmod 770 /Users/ai-agent # ai-agent: rwx, dev-shared: r-x, others: none
-sudo chmod g+s /Users/ai-agent
-```
-
-Set password for ai-agent
-```
-sudo passwd ai-agent
-```
-
-Verify setup
-```
-su - ai-agent
-whoami # Should show: ai-agent
-pwd # Should show: /Users/ai-agent (macOS) or /home/ai-agent (Linux)
-groups # Should show: dev-shared (and other groups)
-ls -la # Check home directory permissions
-```
-
-**Gotcha**: The keychain password warning for macOS can be ignored - it's only relevant for GUI logins.
-
-Ensure unified environment on login
-```
-cat >> ~/.bash_profile << 'EOF'
-if [ -r ~/.bashrc ] ; then
- . ~/.bashrc
-fi
-EOF
-```
-
-Ensure groups math parent directory
-```
-echo "umask 002" >> ~/.bashrc
-```
-
-### Ubuntu (GNU/Linux)
-
-Create dev-shared group
-```
-sudo groupadd dev-shared
-```
-
-Create ai-agent user
-```
-sudo useradd -m -s /bin/bash -c "AI Agent" ai-agent
-```
-
-Add users to dev-shared group
-```
-sudo usermod -a -G dev-shared $(whoami)
-sudo usermod -a -G dev-shared ai-agent
-```
-
-Set proper home directory permissions
-```
-sudo chown ai-agent:dev-shared /home/ai-agent
-sudo chmod 770 /home/ai-agent
-```
-
-Set password for ai-agent
-```
-sudo passwd ai-agent
-```
-
-Verify setup
-```
-su - ai-agent
-whoami # Should show: ai-agent
-pwd # Should show: /Users/ai-agent (macOS) or /home/ai-agent (Linux)
-groups # Should show: dev-shared (and other groups)
-ls -la # Check home directory permissions
-```
-
-## Workspace Setup
-
-Create workspace structure
-```
-mkdir ~/proj
-cd ~/proj
-```
-
-Clone the repository
-```
-git clone https://github.com/cassandra/home-information.git
-mv home-information hi
-ln -s hi home-information
-cd hi
-```
-
-Configure git identity for ai-agent
-```
-git config user.name "AI Agent"
-git config user.email "[email protected]"
-```
-
-Also set global git config for consistency:
-```
-git config --global user.name "AI Agent"
-git config --global user.email "[email protected]"
-```
-
-Verify the setup
-```
-git remote -v
-git status
-pwd
-```
-
-## Setup SSH Keys
-
- Generate SSH key pair (use same email on both machines for consistency)
-```
-# MacOS
-ssh-keygen -t ed25519 -C "ai-agent@strudel" -f ~/.ssh/id_ed25519
-
-# Ubuntu
-ssh-keygen -t ed25519 -C "ai-agent@groovy" -f ~/.ssh/id_ed25519
-```
-
-Set proper permissions
-```
-chmod 700 ~/.ssh
-chmod 600 ~/.ssh/id_ed25519
-chmod 644 ~/.ssh/id_ed25519.pub
-```
-
-## App Development Setup
-
-You can eiher use the `./deploy/dev-setup.sh script`, or manually set up by continueing to follow sections below. If using `./deploy/dev-setup.sh script`, then skip to section "Redis Tweaks".
-
-
-### Environment Variables
-
-**Note**: This is mostly duplicative to [Setup.md](Setup.md) though slightly customized for the AI agent setup. Check there if you run into issues in case this file gets outdated.
-
-Create environment variables for secrets (never commit these!)
-
-#### Option 1: Copy existing
-
-```
-# Copy an existing development.sh file
-
-cd ~/proj/hi
-mkdir -p .private/env
-cat > .private/env/development.sh << 'EOF'
-[[paste your development.sh contents here]]
-EOF
-```
-
-#### Option 2: Env Variable Generaton Script
-
-Use interactive script to genrate needed development.sh.
-```
-make env-build-dev
-```
-
-### Virtual Environment
-
-Create and initialize virtual environment
-```
-python3.11 -m venv venv
-
-# Activate and source
-. ./init-env-dev.sh
-```
-
-Install python dependencies
-```
-pip install -r src/hi/requirements/development.txt
-```
-
-### App and Database Initializations
-```
-cd ~/proj/hi
-mkdir -p data/database
-./src/manage.py check
-./src/manage.py migrate
-./src/manage.py hi_createsuperuser
-./src/manage.py hi_creategroups
-```
-
-Verify app code
-```
-cd ~/proj/hi
-make check
-```
-
-### Redis Tweaks
-
-If you also are presonally also doing development on the same machine, then you should be running Redis and that can also be used by the agent with no extra Redis server needed, but with an environment variable tweak needed (see below).
-
-If Redis is not running on the machine, you'll need to install and/or start redis as shown in [Dependencies.md](Dependencies.md).
-
-When sharing the same Redis server, we will need to avoid collisions on the key space between development environments. There is a Redis key prefix environment variable that can be used to do that. For the ai-agent user, chnage this:
-
-export HI_REDIS_KEY_PREFIX="dev-ai"
-```
-grep -q "HI_REDIS_KEY_PREFIX" .private/env/development.sh && sed -i '' '/HI_REDIS_KEY_PREFIX/c\
-export HI_REDIS_KEY_PREFIX="dev-ai"
-' .private/env/development.sh
-
-# Then verify value change
-grep HI_REDIS_KEY_PREFIX .private/env/development.sh
-```
-
-## Claude Code
-
-Install Claude Code using the official installer
-```
-curl -fsSL https://claude.ai/install.sh | bash
-```
-
-Add to PATH env (now and future)
-```
-export PATH="~/.local/bin:$PATH"
-echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc
-```
-
-
-After installation, verify:
-```
-claude --version
-```
-
-
-### MacOS-only Create Keychain for Claude OAuth token
-
-**Critical**: Terminal-created users don't have a login keychain, which Claude needs.
-
-Create a keychain for ai-agent:
-```
-security create-keychain -p "b92ZnuzkXfAYcAth7gXk" ~/Library/Keychains/login.keychain-db
-```
-
-Set it as the default keychain
-```
-security default-keychain -s ~/Library/Keychains/login.keychain-db
-```
-
-Verify it exists
-```
-security list-keychains
-security default-keychain
-```
-
-Unlock it for use and keep it unlocked for session
-```
-security unlock-keychain ~/Library/Keychains/login.keychain-db
-security set-keychain-settings -t 3600 ~/Library/Keychains/login.keychain-db
-```
-
-Create convenience script
-
-```
-cd ~
-cat > ~/start-claude.sh << 'EOF'
-#!/bin/bash
-cd ~/proj/hi
-. init-env-dev.sh
-claude
-EOF
-
-chmod +x ~/start-claude.sh
-
-# Then just run:
-~/start-claude.sh
-```
-
-### Run OAuth flow to Autheticate to Anthropic
-
-- Start up with `claude`.
-- Select the color scheme when prompted
-- On authetication screen, choose subsciption login
-- This gives a browser URL (or visits url if browser access available)
-- Visit URL, login into Anthropic account (if needed)
-- Click button to authorize
-- Copy and paste resulting token from browser into terninal.
-
-**Gotcha**: After OAuth completes, you may have to exit and restart Claude for the authentication to take effect.
-
-## GitHub Setup
-
-### Option 1: Separate GitHub User
-
-#### Create new GitHub account:
-
-- Go to github.com in incognito/private browser
-- Sign up with a new email ([email protected])
-- Username suggestion: cassandra-ai-agent
-
-#### Add SSH keys to New Account
-
-Display the public key to add to GitHub
-```
-cat ~/.ssh/id_ed25519.pub
-```
-
-For GitHub setup:
-
-1. Copy the public key output from both machines
-2. Go to GitHub → User Icon → Settings → SSH and GPG keys → New SSH key
-3. Add both public keys with descriptive titles:
- - "ai-agent@strudel (MacOS laptop)"
- - "ai-agent@groovy (Ubuntu Desktop)"
-
-Test SSH connection (run on both machines as ai-agent):
-```
-```
-
-Update git origin for SSH access
-```
-git remote set-url origin [email protected]:cassandra/home-information.git
-```
-
-Verify the change
-```
-git remote -v
-```
-
-#### Add as collaborator:
-
-- In your main account, go to repository Settings
-- Collaborators → Add people
-- Invite the new account with "Write" access
-
-#### Install gh CLI
-
-Install from main account (system-wide install)
-```
-# MacOS
-brew install gh
-
-# Ubuntu
-sudo apt install gh
-
-# Verify installation (as ai-agent on both):
-gh --version
-```
-
-#### Configure gh CLI:
-
-Generate a Personal Acess Toke (PAT in GitHub Console
-1. Login to the new GitHub account (in any browser)
-2. Go to Settings → Developer settings → Personal access tokens → Tokens (classic)
-3. Click Generate new token → Generate new token (classic)
-4. Set name
-5. Set expiry (Custom -> One year)
-6. Set permission scopes
- - repo (all)
- - workflow
- - admin.org -> read.org
- - write:discussion
- - project (all)
-7. Generate and save in 1Password
-
-Autheticate CLI with token
-```
-gh auth login
-```
-
-1. Choose: GitHub.com
-2. HTTPS
-3. Auth w/GitHub Credentials
-4. Paste token from 1Password
-
-#### Prepare for Use
-
-Create helper script. Environment must be initialized before starting claude!
-```
-cat > ~/start.sh << 'EOF'
-#!/bin/bash
-cd proj/hi
-. init-env-dev.sh
-claude
-EOF
-
-chmod 755 ~/start.sh
-```
-
-Usage
-```
-su - aipagent
-./start.sh
-```
-
-## Option to Avoid: GitHub App Setup (Aborted)
-
-* THIS DID NOT WORK. LIKELY BUG IN CLAUDE CODE. SAVING STEPS FOR REFERFENCE ONLY. *
-
-#### Create GitHub App
-
-In GitHub console:
-
-- Creat GitHub app in GitHub profile
- - Read and write access to actions, checks, code, commit statuses, discussions, issues, and pull requests
-- Generate and downloaded private key
-- Connect GitHub app to home-information repo.
-
-#### App Details
-
-- cassandra-ai-agent
-- App ID: 1798555
-- Client ID: Iv23lik8L3LA5QzJVd9K
-- Installation Id for home-information repo: 81448612
-- Private key: ~/.ssh//cassandra-ai-agent.2025-08-17.private-key.pem
-
-### Setting GitHub App Credentials
-
-Create Claude Code configuration directory
-```
-mkdir -p ~/.claude-code
-```
-
-Create project-specific Claude settings
-```
-cd ~/proj/hi
-mkdir -p .claude
-```
-
-Copy the GitHub app private key to both ai-agent accounts:
-```
-# As 'arc' user:
-scp ~/.ssh/cassandra-ai-agent.2025-08-17.private-key.pem strudel:/tmp
-scp ~/.ssh/cassandra-ai-agent.2025-08-17.private-key.pem groovy:/tmp
-```
-
-As ai-agent, create secure directory for GitHub App credentials
-```
-mkdir -p ~/.config/github-app
-chmod 700 ~/.config/github-app
-```
-
-Copy your .pem file to this location (you'll need to do this manually).
-```
-cp /tmp/cassandra-ai-agent.2025-08-17.private-key.pem ~/.config/github-app/github-app-private-key.pem
-```
-
-Then set proper permissions:
-```
-chmod 600 ~/.config/github-app/github-app-private-key.pem
-```
-
-Create Claude settings to use GitHub App instead of PAT
-```
-cd ~/proj/hi
-
-cat > .claude/settings.local.json << 'EOF'
-{
- "mcp": {
- "servers": {
- "github": {
- "command": "npx",
- "args": ["-y", "@modelcontextprotocol/server-github"],
- "env": {
- "GITHUB_APP_ID": "1798555",
- "GITHUB_APP_INSTALLATION_ID": "81448612",
- "GITHUB_APP_PRIVATE_KEY_PATH": "~/.config/github-app/github-app-private-key.pem"
- }
- }
- }
- },
- "permissions": {
- "allow": [
- "mcp__github__*",
- "Bash(python manage.py:*)",
- "Bash(./manage.py test:*)",
- "Bash(flake8:*)",
- "Bash(gh issue:*)",
- "Bash(python -m pytest:*)",
- "Bash(find:*)",
- "Bash(grep:*)",
- "Bash(python -m flake8:*)",
- "Bash(python:*)",
- "Bash(git:*)"
- ],
- "deny": []
- }
-}
-EOF
-```
-
-### Node Install
-
-Also install Node.js if not available (needed for GitHub MCP server)
-```
-# On macOS (as 'arc' user who has Homebrew access available):
-brew install node
-
-# On Ubuntu (as 'arc' user who has apt access available):
-sudo apt update && sudo apt install nodejs npm
-
-```
-
-Verify ai-agent user can access required executables:
-```
-which claude
-which node
-which npm
-```
-
-### Verify Authentication to GitHub
-
-
-Test GitHub App authentication by starting Claude and asking it to list issues
-```
-claude
-```
-
-In Claude, test these commands:
-1. List the open issues in this repository
-2. Show me the recent commits
-3. What files are in the src directory?
-
-Expected results:
-- Claude Code starts without errors
-- MCP GitHub server connects successfully
-- You can see repository issues
-- GitHub App authentication works
-
-If you get errors:
-- Check file paths in settings.local.json
-- Verify .pem file permissions (should be 600)
-- Ensure the repository directory contains .claude/settings.local.json
diff --git a/docs/dev/Workflow.md b/docs/dev/ContributorWorkflow.md
similarity index 96%
rename from docs/dev/Workflow.md
rename to docs/dev/ContributorWorkflow.md
index 2cd8ff4b..ebfb6118 100644
--- a/docs/dev/Workflow.md
+++ b/docs/dev/ContributorWorkflow.md
@@ -3,8 +3,7 @@
# Development Workflow
- See the [Contributing Page](../../CONTRIBUTING.md) for general information about contributing.
-- See the [Development Page](Setup.md) for how to set up your development environment.
-- See the [Development Guidelines Page](Guidelines.md) for the projects best practices for development.
+- See the [Development Setup Page](Setup.md) for how to set up your development environment.
## Branching Strategy
diff --git a/docs/dev/DataModel.md b/docs/dev/DataModel.md
deleted file mode 100644
index 341f999c..00000000
--- a/docs/dev/DataModel.md
+++ /dev/null
@@ -1,77 +0,0 @@
-<img src="../../src/hi/static/img/hi-logo-w-tagline-197x96.png" alt="Home Information Logo" width="128">
-
-# Data Model and Concepts
-
-## Entity
-
-- A physical or logical object with associated information.
-- Has zero or more attributes.
-- May or may not have sensors and controllers (from device integrations).
-- May or may not have (hidden) EntityState variables.
-- May or may not define other entities as delegates of its state.
-
-## EntityState
-
-- The hidden state of the entity/device that is sensed and/or controlled
-- A single entity may have zero or more states.
-
-## EntityStateDelegation
-
-- An EntityState of an entity may just be a proxy for another entity's state. e.g., A thermometer entity with a temperature state is a proxy for an area that is a room.
-- We use the terms 'delegate' and 'principal' for the entities involved in the relation.
-- Main use is to have the delegate's visual representation reflect the status of the principal's state.
-- May be one-to-one, one-to-many or many-to-one relationship.
-
-## Location
-
-- Has an SVG image that defines the visual and coordinate space.
-- Has zero or more entities.
-- Entities optionally associated with a position.
-- Has zero or more collections.
-- Collections optionally associated with a position.
-- Can dfined one or more locations.
-
-## LocationView
-
-- Associated with a Location.
-- Can define one or more Location Views for a Location.
-- Defines the view a bounding box area and rotation of the location SVG.
-- Defines what entities are and are not visible in this views.
-- Defines the view context for sensors and controllers (info, control)
-- ViewContext = { information, control }
-
-## LocationItem
-
-- Used as an abstraction/interface for items that can be associated with a Location.
-- Helps define a consistent visual represenation for LocationView.
-- Initially, Entity and Collection are the two concrete examples fof an LocationItem
-
-## EntityPosition / CollectionPosition
-
-- For entities/collections positioned in a Location an visually appearing as an icon.
-- Defines the position, scale and rotation of the icon.
-
-
-## EntityPath / CollectionPath
-
-- For entities/collections positioned in a Location an visually appearing as an open or closed path.
-
-## Device (runtime concept, not a DB model)
-
-- An entity with at least one sensor or controller
-
-## Sensor
-
-- Provides an observation value of a single entity's state variable.
-- Sensors and their states can only be created through integrations (not user editable).
-
-## Controller
-
-- Provides an action to affect a single entity state variable.
-- Controllers and their states can only be created through integrations (not user editable).
-
-## Collection
-
-- Defines a logical connection for a group of one or more entities.
-- Some entities in a collection may be unpositioned e.g., tools, appliances and devices are potential examples of unpositioned collections
-- Collections may or may not be shown in a Location View (as a path).
diff --git a/docs/dev/Debugging.md b/docs/dev/Debugging.md
deleted file mode 100644
index 8515e751..00000000
--- a/docs/dev/Debugging.md
+++ /dev/null
@@ -1,11 +0,0 @@
-<img src="../../src/hi/static/img/hi-logo-w-tagline-197x96.png" alt="Home Information Logo" width="128">
-
-# Debugging
-
-## Custom Debug Settings
-
-You can modify these variables in `src/hi/settings/development.py` to enable/disable some custom development features:
-
-- `SUPPRESS_SELECT_REQUEST_ENPOINTS_LOGGING` - Suppress showing the request line log message. The polling front-end will generate a long stream of these and it make it hard to see other requests.
-- `SUPPRESS_MONITORS` - Turns off running any of the background monitor tasks. Useful when working on something not related ot them to prevent unnecessary logging and resource usage.
-- `BASE_URL_FOR_EMAIL_LINKS` - If needing to test the links in delivered emails. We usually need this to point back to the local development server that send the email.
diff --git a/docs/dev/EntityStatus.md b/docs/dev/EntityStatus.md
deleted file mode 100644
index 37b43178..00000000
--- a/docs/dev/EntityStatus.md
+++ /dev/null
@@ -1,44 +0,0 @@
-<img src="../../src/hi/static/img/hi-logo-w-tagline-197x96.png" alt="Home Information Logo" width="128">
-
-# Entity Status Display
-
-All entity state variables are indirectly observed through a sensor, and all sensor values come from an integration, usually by polling an external service, device, file, etc. Integrations are responsible for normalizing sensor values and encapsulating them in a SensorResponse instance. The SensorResponseManager is the module that will receive these responses from integrations and will provide the latest status values and value histories to the various views. The SensorResponseManager also detects changes of status values and feed those into the alerting subsystem.
-
-## Status (Visual) Display [Location View]
-
-A given Entity (SVG icon or SVG path) can alter its screen appearance based on the value of sensor readings for its underlying state variables. Mapping sensor responses to SVG appearance is the responsibility of the Status Display Helpers using `StatusDisplayData`. There are a few ways this can be done, depending on the underlying entity state type that the sensor is observing.
-
-1. It can take the (normalized) sensor value directly and add it as a CSS class name to the displayed SVG file. This allows CSS rules to adjust the visual display for any well-known sensor values (hardcoded in CSS rules).
-2. For well known sensor values, there can also be predefined/hard-coded alternative SVG icons.
-3. It can map a sensor value into a color scheme that is used for the SVG fill, stroke and opacity attributes. This is predominantly used for area entitiess (closed SVG paths) to visually show activity in an area. This can be from a continuous variable sensor value (e.g., temperature) or a function of the sensor value history (see Value Decaying section below).
-
-## Value Decaying
-
-For some entity state types (and sensors), we not only want to display the current sensor value, but also visually represent the recent past values. For example, when motion is detected in an area, we want to highlight that, but after the motion event is over, we will want to visually show that it was "active" in the recent past. e.g., Active motion is shown as red, but over time decays to oranges then yellows when the motion is over.
-
-### Implementation Approach
-
-The decaying logic creates synthetic visual states ("recent" and "past") that are not actual EntityState values, but are derived from the history and timing of sensor readings. The system examines both current and previous sensor values along with their timestamps to determine the appropriate visual representation.
-
-**Key Concept**: The system uses configurable time thresholds to transition between visual states. For example, an entity that was recently active but is now idle will show as "recent" (orange) for a period, then transition to "past" (yellow), and finally to "idle" (green).
-
-**Supported State Types**: Currently implemented for movement sensors, presence sensors, and open/close sensors - entity types where showing recent activity history provides valuable context to users.
-
-**Color Progression**: The typical color flow is: Active (red) → Recent (orange) → Past (yellow) → Idle (green/gray). This creates an intuitive visual "cooling off" effect.
-
-**Architecture**: The logic is centralized in the status display system (`StatusDisplayData` and `StatusDisplayManager` classes) and integrates with the existing client-server polling mechanism for real-time updates.
-
-## Multiple Sensors
-
-The visual representation provided is always for an Entity, but an entity can have multiple states and multiple sensors. Trying to reason about and support visual distinctions across the cross-product of values for multiple sensors would be more complicated than anyone could understand as well and complicated to implement. Thus, the design decision is that at most one entity state will determine the visual view of the SVG.
-
-To achieve this, we define a default priority of the entity states and the highest priority state will be used. However, a single static priority order is too limiting for many use cases. Thus, we need to be able to support different priorties for different purposes. For example, we may want a climate control view and a security view of a defined area. In the former, we want the temperature sensor value to dictate the visual display, while in the latter, the motion sensor should have its value impacting the area's visual display.
-
-To allow some user control over the visuals from sensor values, each LocationView instance can have its `location_view_type` set to one of the enum values whicih will determine which EntityStateType value will take precedence for status displays. See `hi.apps.location.enums.LocationViewType`.
-
-## Client-Server Interactions to Refresh State Display
-
-The Javascript `polling.js` module polls the server for the latest sensor values for all entity states. The server fetches the latest sensor values via `StatusDataHelper`, computes their visual display using `StatusDisplayData` and then returns a generalized JSON dictionary that maps css class names to a set of attribute name-value pairs to update. The original rendered HTML from the Django templates will make sure the proper entities have the proper class names and attribute values for this to work.
-
-The `polling.js` module tries to be general and only deal with finding class names and updating attribute name-value pairs. This works for the SVG `g` and `path` tags. However, there a few special case patterns needs for `select` tags for controllers and `div` elements for the non-SVG display cases (e.g., viewing entity status in a Collection View or in a sttaus modal).
-
diff --git a/docs/dev/EntityTypes.md b/docs/dev/EntityTypes.md
deleted file mode 100644
index 568e3e03..00000000
--- a/docs/dev/EntityTypes.md
+++ /dev/null
@@ -1,86 +0,0 @@
-<img src="../../src/hi/static/img/hi-logo-w-tagline-197x96.png" alt="Home Information Logo" width="128">
-
-# Entity Types
-
-## Adding New Entity Types
-
-Add an new entry in this Enum:
-
-``` shell
-hi.apps.entity.enums.EntityType
-```
-
-Add the new type to the appropriate group in this Enum:
-
-``` shell
-hi.apps.entity.enums.EntityGroupType
-```
-
-Next, follow the section below depending on whether this is to be displayed as a icon, or as a path.
-
-### Adding as an Icon
-
-Create an SVG icon for the new entity type. However, this will only be the drawing commands for the SVG and should **not** include any wrapping `<svg>` element or other decorations. See current examples for a clearer view.
-
-By default, the SVG viewbox for the icon will be `0 0 64 64`, but you can use a custom viewbox if needed (see below). Put the SVG drawing commands in a file in the following directory and with the shown naming convention:
-
-``` shell
-hi/apps/entity/templates/entity/svg/type.${TYPE}.svg
-```
-
-The `${TYPE}` must match the enum's name, but with all lower case characters.
-
-You should also add as the first drawing element a rectangle that covers the entire SVG viewbox. This should not have any stroke or fill, but it ensures that the entire icon area is "clickable". Without this, clicks on transparent areas of the icon will have no effect. e.g.,
-
-``` shell
-<rect class="hi-entity-bg" x="0" y="0" width="64" height="64" fill="none"/>
-```
-
-If the SVG viewbox needed is not the default `0 0 64 64`, then also add an entry to the following dictionary to define the viewbox:
-
-``` shell
-hi.hi_styles.EntityStyle.EntityTypeToIconViewbox
-```
-
-Finally, add an entry to this set:
-``` shell
-hi.hi_styles.EntityStyle.EntityTypesWithIcons
-```
-
-### Adding as a Path
-
-If the new entity type will be a closed path, then add to this set:
-
-``` shell
-hi.hi_styles.EntityStyle.EntityTypeClosedPaths
-```
-
-Else, if a closed path, add to the set:
-
-``` shell
-hi.hi_styles.EntityStyle.EntityTypeOpenPaths
-```
-
-Define which style to use for drawing the path. Usually, a new entity type requires defining a new style, but an existing style can be reused. You reference the style to use for the new type in this dictionary:
-
-``` shell
-hi.hi_styles.EntityStyle.PathEntityTypeToSvgStatusStyle
-```
-
-When you need a new style for it, also add a new class variable to `hi.hi_styles.EntityStyle` with the type `SvgStatusStyle`. See the existing definitions for more details.
-
-A closed path will default to appearing as a square, but you can adjust the default sizing by added an entry to this dictionary:
-
-``` shell
-hi.hi_styles.EntityStyle.EntityTypePathInitialRadius
-```
-
-
-
-### Simulator
-
-If the new type is something you want the simulator to support (rare), then you will also need to add it there:
-
-``` shell
-hi.simulator.enums.SimEntityType
-```
diff --git a/docs/dev/Guidelines.md b/docs/dev/Guidelines.md
deleted file mode 100644
index 76ed3d69..00000000
--- a/docs/dev/Guidelines.md
+++ /dev/null
@@ -1,207 +0,0 @@
-<img src="../../src/hi/static/img/hi-logo-w-tagline-197x96.png" alt="Home Information Logo" width="128">
-
-# Development Guidelines
-
-## Code Organization and Conventions
-
-### Directories
-
-#### Top-level Directory
-
-- `src`: application source code (see below).
-- `deploy`: helper scripts and files for deploying and setting up the application.
-- `package`: extra items that need to be packaged up to support running the application in Docker.
-- `Makefile`: provides convenience wrappers around command for building, packaging and running.
-- `docs`: all documentation that suitable to be in markdown files.
-
-#### The `src` Directory
-
-- `hi`: entry point urls/views and some app-wide helper classes.
-- `hi/templates`: For top-level views and app-wide common base templates.
-- `hi/apps/${APPNAME}`: For normal application modules.
-- `hi/apps/${APPNAME}/edit`: For normal application modules.
-- `hi/apps/`: For normal application modules.
-- `hi/integrations`: Code for dealing with integration not related to a specific integration.
-- `hi/services/${SERVICENAME}`: Code for a particular integration. See the [Integrations Page](Integrations.md).
-- `hi/simulator`: The code for the separate simulator helper app. See the [Simulator Page](Simulator.md).
-- `hi/settings`: Django settings, including runtime population from environment variables.
-- `hi/requirements`: Python package dependencies.
-- `custom`: Custom user model and other general customizations.
-- `bin`: Helper scripts needed with the code to run inside a Docker container.
-
-### App Module Structure
-
-- `enums.py`: For enums related to the module.
-- `models.py`: For Django ORM models (by Django conventions).
-- `transient_models.py`: For (small-ish) non-ORM models that are not persisted.
-- `urls.py` - When module provides views.
-- `views.py` - Main views for module.
-- `views_mixin.py` - If there is common view functions needs.
-- `forms.py` - If any Django forms are using in views.
-- `${NAME}_manager.py` - If there is internal, persistent data the module provides, a singleton manager class is used.
-- `settings.py`: If app wants to provide user-controllable settings.
-- `monitors.py`: If app module needs a periodic background process.
-- `templates/${APPNAME}`: The apps templates. Also see the [Templates Page](Templates.md).
-- `apps.py`: Django-required module definition.
-- `tests/test_${NAME}`: Unit tests for the module (by Django conventions).
-- `admin.py`: For adding to Django admin console (by Django conventions).
-
-If a module provides views or functionality that is only applicable to edit mode, then an `edit` subdirectory is used with the same structure, e.g.,
-
-- `edit/urls.py` - URLs if module provides edit-only views.
-- `edit/views.py` - Edit-only views for module.
-- etc.
-
-## Coding Style
-
-### Flake8 Configurations
-
-The project uses two different flake8 configurations for different purposes:
-
-#### Development Configuration (`.flake8`)
-Our preferred style for daily development work. The project tries to adhere to PEP8 but we strongly disagree with the broadly accepted coding guidelines around spaces. Spaces are great visual delimiters and greatly enhance readability. The whitespace deviations we make to PEP8 are shown in this Flake8 config file (`ignore`).
-
-``` shell
-[flake8]
-max-line-length = 110
-
-# Things I disable:
-#
-# E129 - visually indented line with same indent as next logical line
-# D203 -
-# E201 - whitespace after brackets
-# E202 - whitespace before brackets
-# E203 -
-# E221 - multiple spaces before operator
-# E231 -
-# E251 - unexpeced whitespace around keyword parameters
-# W293 - blank line contains whitespace
-# W291 - white space at end of line
-# W391 - blank line at end of file
-# W503 - line break before binary operator
-
-ignore = E129,D203,E201,E202,E203,E221,E231,E251,W293,W291,W391,W503
-```
-
-#### CI Configuration (`.flake8-ci`)
-**Hard requirement** for pull request approval. GitHub uses this configuration to enforce code quality standards and will block PR merging if linting fails.
-
-**Before submitting any PR**, you must run: `flake8 --config=src/.flake8-ci src/` and ensure it passes with no violations.
-
-### Generated Code Standards
-
-All generated code (including AI-generated code) must comply with the `.flake8-ci` configuration rules. Common issues to avoid:
-
-1. **Final Newlines**: All files must end with a single newline character
-2. **Unused Imports**: Remove all unused import statements
-3. **Unused Variables**: Remove or prefix unused variables with underscore (`_variable`)
-4. **Line Continuation**: Proper indentation for multi-line statements following PEP 8
-5. **Line Length**: Respect maximum line length limits defined in `.flake8-ci`
-
-### Control Flow Statements
-- Always include explicit `continue` statements in loops, even when not syntactically required
-- Always include explicit `return` statements in functions, even when not syntactically required
-- This improves code readability and makes control flow intentions explicit
-
-### Operator Spacing
-- Use spaces around assignment operators and most other operators in expressions
-- Examples: `x = y + z`, `result += value`, `if count == 0`, `total -= amount`
-- Exception: Don't add spaces in function keyword arguments (`func(x=y)`) or type annotations (`x: int = 5`)
-
-Example:
-```python
-def process_items(items):
- results = []
- for item in items:
- if not item.valid:
- continue # Explicit continue for invalid items
-
- if item.needs_processing:
- result = process(item)
- results.append(result)
- continue # Explicit continue after processing
-
- # Handle non-processing case
- results.append(item.default_value)
- continue # Explicit continue at end of loop
-
- return results # Explicit return at end of function
-
-def simple_function():
- print("Hello world")
- return # Explicit return even for void functions
-```
-
-### General Guidelines
-- Follow existing code patterns and conventions in the codebase
-- Use descriptive variable and function names
-- Maintain consistency with Django and Python best practices
-- **Boolean expressions**: When assigning or returning boolean values, wrap expressions in `bool()` to make intent explicit and improve readability:
- ```python
- # Good - explicit boolean conversion
- is_active = bool(user.last_login)
- in_modal_context = bool(request.POST.get('context') == 'modal')
-
- # Avoid - implicit boolean conversion
- is_active = user.last_login
- in_modal_context = request.POST.get('context') == 'modal'
- ```
-
-## Testing Conventions
-
-See [Testing Guidelines](Testing.md) for comprehensive testing patterns, conventions, and best practices.
-
-## Complex Issue Implementation Strategy
-
-When tackling issues that involve multiple aspects, trade-offs, or significant complexity, use this proven multi-phase approach:
-
-### Core Methodology
-
-1. **Analyze and Break Down**: Identify distinct phases or approaches
- - Phase 1: Simple, reliable solution that fully addresses the core issue
- - Phase 2+: Advanced optimizations, UX improvements, or edge cases
-
-2. **Implement Incrementally**: Complete phases sequentially
- - Complete Phase 1 first - ensure the bug/issue is FULLY RESOLVED
- - Commit and push Phase 1 (but do not create PR yet)
- - Validate approach before proceeding to optimizations
- - Wait for feedback before proceeding to Phase 2
-
-3. **Communication and Review**: Natural checkpoints for feedback
- - Post investigation findings and phase breakdown to GitHub issue
- - After each phase, update issue with implementation details
- - Only create PR when all phases are complete or explicitly requested
- - Enable course correction if needed
-
-4. **Benefits of This Approach**:
- - Allows for early validation of approach
- - Enables course correction if needed
- - Provides natural checkpoints for review
- - Ensures core functionality before optimizations
- - Independent value delivery per phase
-
-### Key Principles
-
-1. **Always solve the core issue first** - Phase 1 must fully resolve the bug
-2. **Incremental value delivery** - Each phase should be independently valuable
-3. **Natural stopping points** - Complete phases are good moments for review
-4. **No PR until complete** - Unless explicitly asked, wait until all phases done
-
-### Case Study: Issue #30 - EntityType Icon Updates
-
-- **Phase 1**: Simple page refresh on EntityType change (reliable, addresses core issue)
-- **Phase 2**: Smart transitions with database management (UX optimization)
-
-This strategy proved highly effective by providing early validation of the approach, allowing for feedback before complex optimizations, ensuring the core bug was fixed before adding enhancements, and creating natural checkpoints for code review.
-
-## Commit Messages
-
-See [Workflow Guidelines](Workflow.md) for commit message standards and branching conventions.
-
-## PR Descriptions
-
-See [Workflow Guidelines](Workflow.md) for pull request templates and review process.
-
-## Documentation
-
-_TBD_
diff --git a/docs/dev/Integrations.md b/docs/dev/Integrations.md
deleted file mode 100644
index 5c0b82d2..00000000
--- a/docs/dev/Integrations.md
+++ /dev/null
@@ -1,91 +0,0 @@
-<img src="../../src/hi/static/img/hi-logo-w-tagline-197x96.png" alt="Home Information Logo" width="128">
-
-# Integrations
-
-- Each integration is a Django app in the `hi/services` directory.
-- The `hi.integration` app handles integration management and required interfaces.
-
-## Nomenclature
-
-- **integration_id** - Unique identifier for each integration type
-- **integration_key** - Used to associate with external integration for entities, sensors, controllers. etc
-- **integration_attr_key** - Unique identifier for the user-defined attributes needed by the implementation
-
-## How to Add an Integration
-
-_Looking at an existing integration is the best way to see the pattern of what is needed._
-
-Create a new Django app. e.g.,
-``` shell
-cd src/hi/services
-../../manage.py startapp myintegration
-cd ..
-```
-
-Ensure `name` is fully qualified in (e.g., `hi.services.myintegration`):
-``` shell
-hi/services/myintegration/app.py
-```
-
-Add 'myintegration' to `INSTALLED_APPS` in:
-``` shell
-hi/settings/base.py
-```
-
-Need this to be able to reference templates, e.g., `myintegration/panes/somepage.html`
-
-Add to the IntegrationType enum
-
-``` shell
- MYINTEGRATION = ( 'My Integration', 'For my stuff.' )
-```
-
-Create subclass of enum `IntegrationAttributeType`. This defines the necessary attributes the integration needs (URLs, credentials, etc.)
-
-Create an "Integration Gateway" using `IntegrationGateway`.
-``` shell
-hi/services/myintegration/myintegration_gateway.py
-```
-
-With content starting like this:
-
-``` shell
-from hi.integration.integration_gateway import IntegrationGateway
-
-class MyIntegrationGateway( Singleton, IntegrationGateway ):
-```
-
-Add gateway to the `IntegrationFactory` class
-``` shell
-hi/integrations/integration_factory.py:get_integration_gateway()
-
-from hi.services.myintegration.myintegration_gateway import MyIM
-
-elif integration_type == IntegrationType.MYINTEGRATION:
- return MyIntegrationGateway
-
-```
-
-### Implement the IntegrationGateway Methods
-
-#### Activate
-
-In this simplest case, this can just update the status of the Integration DB object and display an 'info_message'.
-
-In other caess, this allows an entry point into any activation flow. As a typical example, this would first render apage with a form for the user to fill out any prerequirsite integration properties. e.g., URLs, usernames, passwords, etc.
-
-#### Deactivate
-
-In this simplest case, this can just update the status of the Integration DB object and display an 'info_message'.
-
-In other cases, this allows an entry point into a deact9ivation flow. For example, if the database entries associated with thei integration need to be removed, this could first gather and show all that need deletion and asking user for confirmation.
-
-#### Manage
-
-The manage method is the gateway to adding as much additional configuration views and administratuve features as needed.
-
-Any additional views needed beside for enable, disable and manage should go through the 'manage' url with adding appropriate GET and POST parameters as needed for the particular admin feature.
-``` shell
-{% url 'integration_manage name=integration.integration_type.name %}
-```
-This url support both GET and POST, thoujgh bth go through the manage() method.
diff --git a/docs/dev/ReleaseProcesses.md b/docs/dev/ReleaseProcesses.md
deleted file mode 100644
index e5f75217..00000000
--- a/docs/dev/ReleaseProcesses.md
+++ /dev/null
@@ -1,91 +0,0 @@
-<img src="../../src/hi/static/img/hi-logo-w-tagline-197x96.png" alt="Home Information Logo" width="128">
-
-# Release Process
-
-## Overview
-
-Releases are managed through a structured branch workflow where:
-- All development work occurs in feature branches
-- Feature branches are merged into the `staging` branch via pull requests
-- The `master` branch serves as the release branch
-- Releases involve merging accumulated changes from `staging` into `master`
-
-## Prerequisites
-
-- Direct repository access (core maintainers only)
-- Local development environment properly configured
-- All target changes already merged into `staging` branch
-
-## Pre-Release Verification
-
-Before starting the release process, verify the staging branch is ready:
-
-1. **Confirm CI Status**: Ensure all GitHub Actions checks are passing on `staging`
-2. **Run Local Validation**: Execute tests and linting as a sanity check
- ```bash
- make check
- ```
-3. **Review Recent Changes**: Check recent commits and merged PRs for any concerns
-
-## Release Steps
-
-### 1. Prepare Staging Branch
-- Switch to `staging` branch locally
-- Sync your local `staging` branch with remote/upstream:
- ```bash
- git checkout staging
- git pull github staging
- ```
-
-### 2. Update Version Number
-- Bump the version number in `HI_VERSION` file following semantic versioning
-- Commit the version change directly to upstream `staging`:
- ```bash
- git add HI_VERSION
- git commit -m "Bump version number to vX.X.X"
- git push github staging
- ```
-
-### 3. Merge to Master
-- Switch to local `master` branch and sync with remote:
- ```bash
- git checkout master
- git pull github master
- ```
-- Merge from `staging` into `master`:
- ```bash
- git merge staging
- git push github master
- ```
-
-### 4. Create GitHub Release
-1. Navigate to the GitHub repository releases page
-2. Click "Create a new release"
-3. **Tag**: Create new tag in format `vX.X.X`
-4. **Target**: Set to `master` branch
-5. **Title**: Use the tag name (e.g., `v1.2.3`)
-6. **Description**: Use "Generate release notes" button and edit as needed
-7. **Settings**:
- - Check "Set as the latest release" (typically)
- - Leave "Set as a pre-release" unchecked (for stable releases)
-8. Click "Publish Release"
-
-## Future Considerations
-
-### Version Bumping Criteria
-**TBD** - Establish clear guidelines for when to increment:
-- Major version (breaking changes)
-- Minor version (new features, backward compatible)
-- Patch version (bug fixes, backward compatible)
-
-### Rollback Procedures
-**TBD** - Document rollback procedures for failed releases:
-- How to revert problematic releases
-- Communication protocols for rollback situations
-- Testing procedures post-rollback
-
-## Notes
-
-- **Changelog Management**: Release notes are generated from GitHub's automatic changelog feature rather than maintaining a separate changelog file
-- **Deployment**: Current releases are distributed as downloadable packages for self-installation
-- **Quality Assurance**: GitHub branch protection rules enforce passing tests and code quality checks before PRs can merge to `staging`
diff --git a/docs/dev/Settings.md b/docs/dev/Settings.md
deleted file mode 100644
index a4029830..00000000
--- a/docs/dev/Settings.md
+++ /dev/null
@@ -1,32 +0,0 @@
-<img src="../../src/hi/static/img/hi-logo-w-tagline-197x96.png" alt="Home Information Logo" width="128">
-
-# Settings
-
-## App Settings
-
-Each internal Django app module can provide user-controllable settings that appear on the main config page. These settings are auto-discovered by the `config` app module. The presence of a file named `settings.py` in an app module will automatically get picked up an create a new config area on the user-facing config page.
-
-In this `settings.py` file, defined a subclass of the enum `SettingEnum` to define the label and data types. See existing examples for details.
-
-## Internal Settings
-
-For help in debugging, there is a URL to inspect the Django internal `settings.py` content.
-``` shell
-http://localhost/config/internal
-```
-
-## Adding to an Existing setting.py
-
-After adding a new value to and app's `SettingEnum`, you wil-l need to run `./manage.py migrate` in order to populate the database with the new setting and its default value. (New settings are written to the DB using a post-migrate signal.)
-
-## Adding a New Tab Section to the Config UI
-
-- Add entry to `ConfigPageType`
-- Add a View - view class should extend `ConfigPageView`
-- Override:
- - `config_page_type()`
- - `get_main_template_name()`
- - `get_template_context()`
-- Create template (matching name)
-- Should extend `config/pages/config_base.html`
-- Add to `urls.py` (ensure this is included in top-level `urls.py`)
diff --git a/docs/dev/Setup.md b/docs/dev/Setup.md
index c7a166c0..2cea299f 100644
--- a/docs/dev/Setup.md
+++ b/docs/dev/Setup.md
@@ -195,6 +195,6 @@ make docker-stop
If you want to familiarize yourself with how to use the app before diving into the code, see the [Getting Started Page](../GettingStarted.md).
A look through these docs might also be a good starting point:
-- [Data Model](DataModel.md)
-- [Architecture](Architecture.md)
+- [Data Model](shared/data-model-concepts.md)
+- [Architecture](shared/architecture-overview.md)
diff --git a/docs/dev/Simulator.md b/docs/dev/Simulator.md
deleted file mode 100644
index 85656a5f..00000000
--- a/docs/dev/Simulator.md
+++ /dev/null
@@ -1,18 +0,0 @@
-<img src="../../src/hi/static/img/hi-logo-w-tagline-197x96.png" alt="Home Information Logo" width="128">
-
-# Simulator
-
-The simulator is used to simulate integrations to help test the Home Application app. It is a separate Django application with a separate database, though the code can be found in the `hi/simulator` directory. There is a special `simulator.py` command along side then main Django `manage.py` script. The `simulator.py` script acts just like the main `manage.py` script, with all the same commands (runserver, migrate, etc.), but does this to manage the simulator application.
-
-## Initialize the Simulator Database
-
-``` shell
-cd $PROJ_DIR
-cd src
-./simulator.py migrate
-./simulator.py hi_createsuperuser
-./simulator.py hi_creategroups
-./simulator.py runserver
-```
-
-Then, visit: [http://127.0.0.1:7411](http://127.0.0.1:7411) to access the simulator.
diff --git a/docs/dev/Templates.md b/docs/dev/Templates.md
deleted file mode 100644
index d653aa8a..00000000
--- a/docs/dev/Templates.md
+++ /dev/null
@@ -1,97 +0,0 @@
-<img src="../../src/hi/static/img/hi-logo-w-tagline-197x96.png" alt="Home Information Logo" width="128">
-
-# Django Templates
-
-## Template naming conventions
-
-- `pages` - For full HTML pages
-- `modals` - For HTML modals
-- `panes` - For all other HTML page fragments
-- `email` - For email templates
-- `svg` - for SVG files.
-
-For app modules that also define some separate "edit" views, they will be in the same structure, one level down in an `edit` subdirectory.
-
-## The "Hi Grid" Template Structure
-
-_TBD_
-
-### Important DIV Ids
-
-This are gathered in `src/hi/constants.py:DIV_IDS`:
-
-- `#hi-main-content` - This is the main display area, excluding header buttons, footer buttons and the side panel.
-- `#hi-side-content`
-- `#hi-top-buttons`
-- `#hi-button-bottons`
-- `#hi-config-integration-tab` - Integrations use this for any configuration-related views.
-
-## Icon Usage Guidelines
-
-### Icon System
-
-Use the standardized `{% icon %}` template tag. See `hi/apps/common/templatetags/icons.py` for implementation details and parameters.
-
-### UX Principles for Icon Usage
-
-**Primary Value**: Icons provide faster recognition, universal language, space efficiency, and visual hierarchy.
-
-**ALWAYS Add Icons When:**
-- **Universal Actions**: Add (+), Delete (trash), Edit (pencil), Save (checkmark), Cancel (×)
-- **Navigation**: Back/Forward arrows, Up/Down, Expand/Collapse
-- **Media Controls**: Play, Pause, Video, Camera
-- **Status/Feedback**: Success, Warning, Error, Info
-
-**Key Principle**: Focus on **ACTION TYPE** (add, delete, edit), not object specificity. "Add Item" and "Add Rule" both get the same + icon because they're both "add" actions.
-
-### Implementation Requirements
-
-- Always include `{% load icons %}` at top of templates
-- Icons should supplement text, not replace it for important actions
-- Use semantic size and color parameters when available
-- Include appropriate ARIA labels for accessibility
-- Maintain consistency: same action = same icon across the application
-
-### Examples
-
-```django
-{% load icons %}
-
-<!-- Primary action with icon -->
-<button class="btn btn-primary">
- {% icon "plus" size="sm" css_class="hi-icon-left" %}
- Add New Rule
-</button>
-
-<!-- Edit action -->
-<a class="btn btn-secondary" href="/edit/">
- {% icon "edit" size="sm" css_class="hi-icon-left" %}
- Edit
-</a>
-
-<!-- Save/Submit action -->
-<button class="btn btn-success" type="submit">
- {% icon "save" size="sm" css_class="hi-icon-left" %}
- Save Changes
-</button>
-
-<!-- Cancel action -->
-<a class="btn btn-tertiary" href="#" data-dismiss="modal">
- {% icon "cancel" size="sm" css_class="hi-icon-left" %}
- Cancel
-</a>
-
-<!-- Delete action - icon-only for space constraints -->
-<button class="btn btn-danger" aria-label="Delete item">
- {% icon "delete" size="sm" %}
-</button>
-
-<!-- Modal close - icon-only (universal convention) -->
-<button type="button" class="close" data-dismiss="modal" aria-label="Close">
- {% icon "close" size="sm" %}
-</button>
-```
-
-**Available Icons**: See `hi/apps/common/templatetags/icons.py` for the complete list of available icons.
-
-See existing templates for more examples.
diff --git a/docs/dev/Testing.md b/docs/dev/Testing.md
deleted file mode 100644
index d93162f3..00000000
--- a/docs/dev/Testing.md
+++ /dev/null
@@ -1,886 +0,0 @@
-<img src="../../src/hi/static/img/hi-logo-w-tagline-197x96.png" alt="Home Information Logo" width="128">
-
-# Testing
-
-## Unit Tests
-
-``` shell
-cd $PROJ_DIR/src
-./manage.py test
-```
-
-## Testing Guidelines and Best Practices
-
-### High-Value vs Low-Value Testing Criteria
-
-**HIGH-VALUE Tests (Focus Here)**
-- **Database constraints and cascade deletion behavior** - Critical for data integrity
-- **Complex business logic and algorithms** - Custom calculations, aggregation, processing
-- **Singleton pattern behavior** - Manager classes, initialization, thread safety
-- **Enum property conversions with custom logic** - from_name_safe(), business rules
-- **File handling and storage operations** - Upload, deletion, cleanup, error handling
-- **Integration key parsing and external system interfaces** - API boundaries
-- **Complex calculations** - Geometric (SVG positioning), ordering, aggregation logic
-- **Caching and performance optimizations** - TTL caches, database indexing
-- **Auto-discovery and Django startup integration** - Module loading, initialization sequences
-- **Thread safety and concurrent operations** - Locks, shared state, race conditions
-- **Background process coordination** - Async/sync dual access, event loop management
-
-**LOW-VALUE Tests (Avoid These)**
-- Simple property getters/setters that just return field values
-- Django ORM internals verification (Django already tests this)
-- Trivial enum label checking without business logic
-- Basic field access and obvious default values
-- Simple string formatting without complex logic
-
-### Critical Testing Anti-Patterns (Never Do These)
-
-**NEVER Test Behavior Based on Log Messages**
-- **Problem**: Log message assertions (`self.assertLogs()`, checking log output) are fragile and break easily when logging changes
-- **Issue**: Many existing tests deliberately disable logging for performance and clarity
-- **Solution**: Test actual behavior changes - state modifications, return values, method calls, side effects
-- **Example**: Instead of `assertLogs('module', level='WARNING')`, verify the actual error handling behavior occurred
-
-```python
-# BAD - Testing based on log messages
-with self.assertLogs('weather.manager', level='WARNING') as log_context:
- manager.process_data(invalid_data)
- self.assertTrue(any("Error processing" in msg for msg in log_context.output))
-
-# GOOD - Testing actual behavior
-mock_fallback = Mock()
-with patch.object(manager, 'fallback_handler', mock_fallback):
- result = manager.process_data(invalid_data)
- mock_fallback.assert_called_once()
- self.assertIsNone(result) # Verify expected failure behavior
-```
-
-### Additional Testing Anti-Patterns (Avoid These)
-
-**Mock-Centric Testing Instead of Behavior Testing**
-
-**Problem**: Tests focus on verifying mock calls rather than testing actual behavior and return values.
-
-**Bad Example**:
-```python
-# BAD - Testing mock calls instead of behavior
-@patch('module.external_service')
-def test_process_data(self, mock_service):
- mock_service.return_value = {'status': 'success'}
-
- result = processor.process_data(input_data)
-
- # Only testing that the mock was called correctly
- mock_service.assert_called_once_with(expected_params)
- # Missing: What did process_data actually return?
-```
-
-**Good Example**:
-```python
-# GOOD - Testing actual behavior and return values
-@patch('module.external_service')
-def test_process_data_returns_transformed_result(self, mock_service):
- mock_service.return_value = {'status': 'success', 'data': 'raw_value'}
-
- result = processor.process_data(input_data)
-
- # Test the actual behavior and return value
- self.assertEqual(result['transformed_data'], 'processed_raw_value')
- self.assertEqual(result['status'], 'completed')
- self.assertIn('timestamp', result)
-```
-
-**Over-Mocking Internal Components**
-
-**Problem**: Mocking too many internal components breaks the integration between parts of the system.
-
-**Bad Example**:
-```python
-# BAD - Mocking both HTTP layer AND internal converter
-@patch('module.http_client.get')
-@patch('module.DataConverter.parse')
-def test_fetch_and_parse(self, mock_parse, mock_get):
- mock_get.return_value = mock_response
- mock_parse.return_value = mock_parsed_data
-
- result = service.fetch_and_parse()
- # This tests nothing about actual data flow
-```
-
-**Good Example**:
-```python
-# GOOD - Mock only at system boundaries
-@patch('module.http_client.get')
-def test_fetch_and_parse_integration(self, mock_get):
- mock_get.return_value = Mock(text='{"real": "json", "data": "here"}')
-
- result = service.fetch_and_parse()
-
- # Test that real data flows through real converter
- self.assertIsInstance(result, ExpectedDataType)
- self.assertEqual(result.parsed_field, "expected_value")
-```
-
-**Testing Implementation Details Instead of Interface Contracts**
-
-**Problem**: Tests verify internal implementation details rather than public interface behavior.
-
-**Bad Example**:
-```python
-# BAD - Testing exact HTTP parameters instead of behavior
-def test_api_call_constructs_correct_url(self):
- client.make_request('entity_123')
-
- expected_url = 'https://api.service.com/v1/entities/entity_123'
- expected_headers = {'Authorization': 'Bearer token', 'Content-Type': 'application/json'}
- mock_post.assert_called_once_with(expected_url, headers=expected_headers)
- # Missing: What happens with the response?
-```
-
-**Good Example**:
-```python
-# GOOD - Testing the interface contract
-def test_api_call_returns_entity_data(self):
- mock_response_data = {'id': 'entity_123', 'name': 'Test Entity'}
- mock_post.return_value = Mock(json=lambda: mock_response_data)
-
- result = client.make_request('entity_123')
-
- # Test the contract: what the method promises to return
- self.assertEqual(result['id'], 'entity_123')
- self.assertEqual(result['name'], 'Test Entity')
-```
-
-**Superficial Edge Case Testing**
-
-**Problem**: Creating edge case tests that don't test meaningful business logic scenarios.
-
-**Bad Example**:
-```python
-# BAD - Testing trivial edge cases without business impact
-def test_handles_various_url_formats(self):
- test_cases = [
- ('http://localhost', 'http://localhost'),
- ('http://localhost/', 'http://localhost'),
- ('https://example.com/', 'https://example.com')
- ]
- for input_url, expected in test_cases:
- client = ApiClient(input_url)
- self.assertEqual(client.base_url, expected)
-```
-
-**Good Example**:
-```python
-# GOOD - Testing edge cases that affect actual functionality
-def test_url_normalization_prevents_api_call_failures(self):
- client_with_slash = ApiClient('https://api.example.com/')
- client_without_slash = ApiClient('https://api.example.com')
-
- # Test that both work correctly for actual API calls
- with patch('requests.get') as mock_get:
- mock_get.return_value = Mock(json=lambda: {'data': 'test'})
-
- result1 = client_with_slash.fetch_data()
- result2 = client_without_slash.fetch_data()
-
- # Both should work and return same data
- self.assertEqual(result1, result2)
- # Verify no double slashes in URL
- for call in mock_get.call_args_list:
- url = call[0][0]
- self.assertNotIn('//api', url)
-```
-
-**Complex Multi-Purpose Tests**
-
-**Problem**: Single tests that verify too many different behaviors, making failures hard to diagnose.
-
-**Bad Example**:
-```python
-# BAD - Testing multiple services and scenarios in one test
-def test_service_various_operations(self):
- test_cases = [
- ('light', 'turn_on', 'light.bedroom'),
- ('switch', 'turn_off', 'switch.outlet'),
- ('climate', 'set_temperature', 'climate.thermostat'),
- ('media_player', 'play_media', 'media_player.living_room'),
- ]
- for domain, service, entity in test_cases:
- with self.subTest(domain=domain):
- result = client.call_service(domain, service, entity)
- # Generic assertions that don't test domain-specific logic
- self.assertIsNotNone(result)
-```
-
-**Good Example**:
-```python
-# GOOD - Focused tests for specific behaviors
-def test_light_service_calls_return_response_objects(self):
- mock_response = Mock(status_code=200, json=lambda: {'context': 'light_context'})
-
- result = client.call_service('light', 'turn_on', 'light.bedroom')
-
- self.assertEqual(result.status_code, 200)
- self.assertIn('context', result.json())
-
-def test_climate_service_handles_temperature_data(self):
- service_data = {'temperature': 72, 'hvac_mode': 'heat'}
-
- result = client.call_service('climate', 'set_temperature', 'climate.thermostat', service_data)
-
- # Test climate-specific behavior
- call_data = mock_post.call_args[1]['json']
- self.assertEqual(call_data['temperature'], 72)
- self.assertEqual(call_data['hvac_mode'], 'heat')
-```
-
-**Inadequate Error Context Testing**
-
-**Problem**: Testing that errors occur without verifying error messages provide useful debugging information.
-
-**Bad Example**:
-```python
-# BAD - Only testing that an error occurs
-def test_invalid_entity_raises_error(self):
- with self.assertRaises(ValueError):
- client.set_state('invalid.entity', 'on')
-```
-
-**Good Example**:
-```python
-# GOOD - Testing error context and messages
-def test_invalid_entity_provides_descriptive_error(self):
- mock_response = Mock(status_code=404, text='Entity invalid.entity not found')
-
- with self.assertRaises(ValueError) as context:
- client.set_state('invalid.entity', 'on')
-
- error_message = str(context.exception)
- self.assertIn('invalid.entity', error_message)
- self.assertIn('404', error_message)
- self.assertIn('not found', error_message)
- # Verify error provides actionable information
-```
-
-### Testing Best Practices Summary
-
-1. **Mock at system boundaries only** (HTTP calls, database, external services)
-2. **Test return values and state changes**, not mock call parameters
-3. **Use real data through real code paths** when possible
-4. **Test error messages provide useful context** for debugging
-5. **Focus on interface contracts**, not implementation details
-6. **Create focused tests** that test one behavior well
-7. **Test meaningful edge cases** that affect business logic
-8. **Verify data transformations** work correctly end-to-end
-9. **Use real database operations over ORM mocking** when testing business logic
-10. **Test database state changes** rather than mocking ORM calls to verify actual behavior
-
-#### Database vs Mock Testing Strategy
-
-**Prefer Real Database Operations:**
-- Database state verification tests actual business logic and relationships
-- Cascade deletion, constraints, and indexing are critical system behaviors
-- TransactionTestCase provides proper isolation for database-dependent tests
-- Real data flows through real code paths reveal integration issues
-
-**When to Mock vs Real Database:**
-- **Mock external APIs** (HTTP calls, third-party services)
-- **Use real database** for business logic, relationships, and data transformations
-- **Mock at system boundaries**, not internal ORM operations
-
-### Django-Specific Testing Patterns
-
-```python
-# Abstract Model Testing - Create concrete test class
-class ConcreteTestModel(AbstractModel):
- def required_abstract_method(self):
- return "test_implementation"
-
-# Mock Django operations for database-less testing
-with patch('django.db.models.Model.save') as mock_save:
- instance.save()
- mock_save.assert_called_once()
-
-# Integration Key Pattern Testing
-def test_integration_key_inheritance(self):
- model = TestModel.objects.create(
- integration_id='test_id',
- integration_name='test_integration'
- )
- self.assertEqual(model.integration_id, 'test_id')
-
-# Singleton Manager Testing
-def test_manager_singleton_behavior(self):
- manager1 = ManagerClass()
- manager2 = ManagerClass()
- self.assertIs(manager1, manager2)
-
-# Background Process and Threading Testing
-async def test_async_manager_method(self):
- with patch('asyncio.run') as mock_run:
- result = await manager.async_method()
- mock_run.assert_called()
-
-def test_manager_thread_safety(self):
- results = []
- def worker():
- results.append(manager.thread_safe_operation())
-
- threads = [threading.Thread(target=worker) for _ in range(5)]
- for t in threads:
- t.start()
- for t in threads:
- t.join()
-```
-
-### Manager Class Async/Sync Testing
-
-Many manager classes in this codebase follow a dual sync/async pattern to support both traditional Django views and async integration services. These require special testing infrastructure.
-
-#### Manager Pattern Characteristics
-- Singleton pattern with `__init_singleton__()`
-- Both sync `ensure_initialized()` and async initialization methods
-- Mix of sync methods for Django ORM access and async methods for integration services
-- Thread safety considerations and shared state management
-
-#### Async Testing Infrastructure
-Use this pattern for testing manager classes with async methods:
-
-```python
-class AsyncManagerTestCase(TransactionTestCase):
- """Base class for async manager tests with proper infrastructure."""
-
- @classmethod
- def setUpClass(cls):
- super().setUpClass()
- # Create a single shared event loop for all tests in this class
- cls._test_loop = asyncio.new_event_loop()
- asyncio.set_event_loop(cls._test_loop)
-
- @classmethod
- def tearDownClass(cls):
- if hasattr(cls, '_test_loop'):
- cls._test_loop.close()
- super().tearDownClass()
-
- def run_async(self, coro):
- """Helper method to run async coroutines using the shared event loop."""
- return self._test_loop.run_until_complete(coro)
-
- def setUp(self):
- super().setUp()
- # Reset singleton state for each test
- ManagerClass._instances = {}
- self.manager = ManagerClass()
- # Clear any cached state
- if hasattr(self.manager, '_recent_transitions'):
- self.manager._recent_transitions.clear()
-
- def test_async_method(self):
- """Example async test using wrapper pattern."""
- async def async_test_logic():
- # Use sync_to_async for database operations
- entity = await sync_to_async(Entity.objects.create)(name='Test Entity')
- result = await self.manager.async_method(entity)
- self.assertIsNotNone(result)
-
- self.run_async(async_test_logic())
-```
-
-**Key Requirements:**
-- **Use `TransactionTestCase`** instead of `BaseTestCase` to avoid database locking
-- **Shared event loop** prevents SQLite concurrency issues with multiple async tests
-- **Reset singleton state** between tests to ensure isolation
-- **Wrap sync database operations** with `sync_to_async()` in async test code
-- **Use `select_related()`** in manager code to prevent lazy loading in async contexts
-
-**Critical ORM Access Pattern:**
-```python
-# In manager async methods - avoid lazy loading issues
-event_clauses = await sync_to_async(list)(
- event_definition.event_clauses.select_related('entity_state').all()
-)
-
-# In tests - wrap database operations
-entity = await sync_to_async(Entity.objects.create)(name='Test')
-```
-
-## Django View Testing
-
-Django views in this application come in five distinct patterns that require different testing approaches:
-
-1. **Synchronous HTML Views** - Traditional Django page views returning HTML responses
-2. **Synchronous JSON Views** - API endpoints returning JSON responses
-3. **Asynchronous HTML Views** - AJAX views returning HTML snippets for DOM insertion
-4. **Asynchronous JSON Views** - AJAX views returning JSON data for JavaScript processing
-5. **Dual-Mode Views** - Views (HiModalView/HiGridView) that handle both sync and async requests
-
-### View Testing Base Classes
-
-The framework uses a mixin-based architecture to provide clean separation of concerns:
-
-- `ViewTestBase` - Common utilities and core assertions
-- `SyncTestMixin` - Synchronous testing capabilities (regular `client.get()`, `client.post()`)
-- `AsyncTestMixin` - Asynchronous testing capabilities (`async_get()`, `async_post()` with AJAX headers)
-
-These are composed into test case classes:
-
-Use these base classes from `hi.tests.view_test_base` for consistent view testing:
-
-```python
-from django.urls import reverse
-from hi.tests.view_test_base import SyncViewTestCase, AsyncViewTestCase, DualModeViewTestCase
-
-class TestMySyncViews(SyncViewTestCase):
- def test_synchronous_html_view(self):
- url = reverse('my_view_name')
- response = self.client.get(url) # Regular Django test client
- self.assertSuccessResponse(response)
- self.assertHtmlResponse(response)
- self.assertTemplateRendered(response, 'my_app/template.html')
-
-class TestMyAsyncViews(AsyncViewTestCase):
- def test_asynchronous_html_view(self):
- url = reverse('my_async_view_name')
- response = self.async_get(url) # Automatically includes AJAX headers
- self.assertSuccessResponse(response)
- self.assertJsonResponse(response)
-
-class TestMyDualModeViews(DualModeViewTestCase):
- def test_view_synchronous_mode(self):
- url = reverse('my_dual_view_name')
- response = self.client.get(url) # Regular request
- self.assertSuccessResponse(response)
- self.assertHtmlResponse(response)
-
- def test_view_asynchronous_mode(self):
- url = reverse('my_dual_view_name')
- response = self.async_get(url) # AJAX request
- self.assertSuccessResponse(response)
- self.assertJsonResponse(response)
-```
-
-### Helper Methods
-
-The base test classes provide these assertion and utility methods:
-
-**Status Code Assertions:**
-- `assertResponseStatusCode(response, expected_code)` - Verifies specific status code
-- `assertSuccessResponse(response)` - Verifies 2xx status code
-- `assertErrorResponse(response)` - Verifies 4xx status code
-- `assertServerErrorResponse(response)` - Verifies 5xx status code
-
-**Response Type Assertions:**
-- `assertHtmlResponse(response)` - Verifies HTML content type (status code independent)
-- `assertJsonResponse(response)` - Verifies JSON content type (status code independent)
-
-**Template Assertions:**
-- `assertTemplateRendered(response, template_name)` - Verifies specific template was used
-
-**Session Assertions:**
-- `assertSessionValue(response, key, expected_value)` - Verifies session contains specific key-value pair
-- `assertSessionContains(response, key)` - Verifies session contains specific key
-
-**Session Management:**
-- `setSessionViewType(view_type)` - Set ViewType in session for subsequent requests
-- `setSessionViewMode(view_mode)` - Set ViewMode in session for subsequent requests
-- `setSessionLocationView(location_view)` - Set location_view_id in session for subsequent requests
-- `setSessionCollection(collection)` - Set collection_id in session for subsequent requests
-- `setSessionViewParameters(view_type=None, view_mode=None, location_view=None, collection=None)` - Set multiple view parameters at once
-
-**Redirect Testing:**
-- `assertRedirectsToTemplates(initial_url, expected_templates)` - Follow redirects and verify final templates rendered
-
-**AJAX Request Methods:**
-- `async_get(url, data=None)` - GET request with AJAX headers
-- `async_post(url, data=None)` - POST request with AJAX headers
-- `async_put(url, data=None)` - PUT request with AJAX headers
-- `async_delete(url, data=None)` - DELETE request with AJAX headers
-
-### Testing Patterns by View Type
-
-#### Synchronous HTML Views
-- Test status code, response type, and template rendering separately
-- Verify error handling and edge cases
-- Validate form processing and context data
-
-```python
-def test_location_view_renders_correctly(self):
- location = Location.objects.create(name='Test Location')
- url = reverse('location_detail', kwargs={'location_id': location.id})
- response = self.client.get(url)
-
- self.assertSuccessResponse(response)
- self.assertHtmlResponse(response)
- self.assertTemplateRendered(response, 'location/detail.html')
- self.assertEqual(response.context['location'], location)
-
-def test_location_view_not_found(self):
- url = reverse('location_detail', kwargs={'location_id': 999})
- response = self.client.get(url)
-
- self.assertResponseStatusCode(response, 404)
- self.assertHtmlResponse(response)
-```
-
-#### Synchronous JSON Views
-- Test status codes and JSON response structure separately
-- Verify API endpoint error responses
-
-```python
-def test_api_status_returns_json(self):
- url = reverse('api_status')
- response = self.client.get(url)
-
- self.assertSuccessResponse(response)
- self.assertJsonResponse(response)
- data = response.json()
- self.assertIn('timestamp', data)
- self.assertIn('alertData', data)
-
-def test_api_invalid_request(self):
- url = reverse('api_update')
- response = self.client.post(url, {'invalid': 'data'})
-
- self.assertErrorResponse(response)
- self.assertJsonResponse(response)
-```
-
-#### Asynchronous HTML Views
-- Test AJAX request detection and proper status codes
-- Verify HTML snippet responses for DOM insertion
-- Test response when called incorrectly (sync instead of async)
-
-```python
-def test_async_html_view_with_ajax_header(self):
- url = reverse('console_sensor_view', kwargs={'sensor_id': 1})
- response = self.async_get(url) # Includes HTTP_X_REQUESTED_WITH header
-
- self.assertSuccessResponse(response)
- self.assertJsonResponse(response)
- # Test that async view returns content for DOM insertion
- data = response.json()
- self.assertIn('insert_map', data)
-
-def test_async_view_called_synchronously_redirects(self):
- url = reverse('console_sensor_view', kwargs={'sensor_id': 1})
- response = self.client.get(url) # Regular GET without AJAX headers
-
- expected_redirect = reverse('console_home')
- self.assertRedirects(response, expected_redirect)
-
-def test_async_view_error_handling(self):
- url = reverse('console_sensor_view', kwargs={'sensor_id': 999})
- response = self.async_get(url)
-
- self.assertErrorResponse(response)
- self.assertJsonResponse(response) # Error responses may be JSON
-```
-
-#### Asynchronous JSON Views
-- Test AJAX JSON responses with correct status codes
-- Verify JavaScript-consumable data formats
-- Test error handling in async context
-
-```python
-def test_async_json_view_returns_update_data(self):
- url = reverse('api_update')
- response = self.async_post(url, {'entity_id': 1}) # Includes AJAX headers
-
- self.assertSuccessResponse(response)
- self.assertJsonResponse(response)
- data = response.json()
- self.assertIn('timestamp', data)
- self.assertIn('alertData', data)
-
-def test_async_json_view_validation_error(self):
- url = reverse('api_update')
- response = self.async_post(url, {}) # Missing required data
-
- self.assertErrorResponse(response)
- self.assertJsonResponse(response)
-```
-
-#### Dual-Mode Views (HiModalView/HiGridView)
-- Test both synchronous and asynchronous call patterns
-- Verify correct response type based on request context
-- Test modal rendering vs. full page rendering
-
-```python
-def test_modal_view_sync_request(self):
- url = reverse('weather_current_conditions_details')
- response = self.client.get(url) # Regular request without AJAX headers
-
- self.assertSuccessResponse(response)
- self.assertHtmlResponse(response)
- # Should render both the base page and the modal template
- self.assertTemplateRendered(response, 'pages/main_default.html')
- self.assertTemplateRendered(response, 'weather/modals/conditions_details.html')
-
-def test_modal_view_async_request(self):
- url = reverse('weather_current_conditions_details')
- response = self.async_get(url) # Request with AJAX headers
-
- self.assertSuccessResponse(response)
- self.assertJsonResponse(response)
- self.assertTemplateRendered(response, 'weather/modals/conditions_details.html')
- # Verify modal response structure for AJAX
- data = response.json()
- self.assertIn('modal', data)
-```
-
-### View Testing Guidelines
-
-**DO:**
-- Use `reverse()` with URL names instead of hardcoded URL strings
-- Use `async_get()`, `async_post()` etc. for AJAX requests to ensure proper headers
-- Test status codes, response types, and template rendering as separate concerns
-- Use `assertTemplateRendered()` to verify template usage independently
-- Use real database operations and test data setup
-- Test actual request/response flows through real code paths
-- Mock only at system boundaries (HTTP calls, external services)
-- Test conditional logic that affects response content or status codes
-- Test error handling and edge cases with appropriate status code assertions
-- Verify context data correctness
-- **Test each view's specific decisions, not downstream redirect effects** (use `fetch_redirect_response=False` for immediate redirects)
-
-**DON'T:**
-- Use hardcoded URL strings - always use `reverse()` with URL names
-- Use regular `client.get()` for AJAX requests - use `async_get()` helper methods
-- Mix status code, response type, and template assertions in single method calls
-- Test template content text that may change - use template name verification instead
-- Use magic strings instead of defined enums/constants (e.g., `'EDIT'` vs `ViewMode.EDIT`)
-- Mock internal Django components or ORM operations
-- Test implementation details instead of interface contracts
-- Create tests that depend on log message assertions
-- Over-mock internal application components
-
-### Database Setup for View Tests
-
-View tests should create real test data to verify complete request/response flows:
-
-```python
-def setUp(self):
- super().setUp()
- self.location = Location.objects.create(name='Test Location')
- self.entity = Entity.objects.create(
- integration_id='test.entity',
- integration_name='test_integration',
- location=self.location
- )
-
-def test_location_view_with_entities(self):
- url = reverse('location_detail', kwargs={'location_id': self.location.id})
- response = self.client.get(url)
-
- self.assertSuccessResponse(response)
- self.assertHtmlResponse(response)
- self.assertTemplateRendered(response, 'location/detail.html')
- self.assertEqual(response.context['location'], self.location)
- # Test that entity is in context or response data
- self.assertIn(self.entity, response.context['entities'])
-```
-
-### Authentication and Permission Testing
-
-For views requiring authentication:
-
-```python
-def test_protected_view_requires_authentication(self):
- url = reverse('protected_view')
- response = self.client.get(url)
- login_url = reverse('login')
- self.assertRedirects(response, f'{login_url}?next={url}')
-
-def test_protected_view_with_authenticated_user(self):
- self.client.force_login(self.user)
- url = reverse('protected_view')
- response = self.client.get(url)
-
- self.assertSuccessResponse(response)
- self.assertHtmlResponse(response)
-```
-
-### Form Validation Testing
-
-For views that process forms:
-
-```python
-def test_form_validation_success(self):
- form_data = {'name': 'Test Entity', 'location': self.location.id}
- url = reverse('entity_create')
- response = self.client.post(url, form_data)
-
- success_url = reverse('entity_list')
- self.assertRedirects(response, success_url)
- self.assertTrue(Entity.objects.filter(name='Test Entity').exists())
-
-def test_form_validation_errors(self):
- form_data = {'name': ''} # Missing required field
- url = reverse('entity_create')
- response = self.client.post(url, form_data)
-
- self.assertSuccessResponse(response) # Form errors return 200, not 4xx
- self.assertHtmlResponse(response)
- self.assertTemplateRendered(response, 'entity/create.html')
- self.assertFormError(response, 'form', 'name', 'This field is required.')
-```
-
-## Integration Tests
-
-_TBD_
-
-## Development Data Injection
-
-The development data injection system provides a runtime mechanism to modify application behavior without code changes or Django restarts. This is useful for testing scenarios that would otherwise require complex backend state setup.
-
-**Example use case:** Injecting pre-formatted status responses for UI testing - you can override the `/api/status` endpoint to return specific transient view suggestions, allowing you to test auto-view switching behavior without manipulating the actual backend systems.
-
-**General concept:** Any code location can become an injection point by adding a `DEBUG_FORCE_*` setting and a conditional check. The system supports both one-time and persistent overrides via management commands.
-
-For complete usage details, implementation instructions, and extending to new injection points, see:
-```
-hi.testing.dev_injection.DevInjectionManager
-```
-
-## Visual Testing Page
-
-Visit: [http://127.0.0.1:8411/testing/ui](http://127.0.0.1:8411/testing/ui).
-
-These tests/ui views are only available in the development environment when `DEBUG=True`. (They are conditionally loaded in the root `urls.py`.)
-
-### Adding to the Visual Testing Page
-
-The `hi.tests.ui` module uses auto-discovery by looking in the app directories.
-
-In the app directory you want to have a visual testing page:
-
-``` shell
-mkdir -p tests/ui
-touch tests.__init__.py
-touch tests/ui.__init__.py
-```
-
-Then:
-- Create `tests/ui/views.py`
-- Create `tests/ui/urls.py` (This gets auto-discovered. Esnure some default home page rule.)
-
-The templates for these tests, by convention, would be put in the app templates directory as `templates/${APPNAME}/testing/ui`. At a minimum, you will probably want a home page `templates/${APPNAME}/testing/ui/home.html` like this:
-
-``` html
-{% extends "pages/base.html" %}
-{% block head_title %}HI: PAGE TITLE{% endblock %}
-
-{% block content %}
-<div class="container-fluid m-4">
-
- <h2 class="text-info">SOME TESTS</h2>
-
- <!-- Put links to views here -->
-
-</div>
-{% endblock %}
-```
-
-And in `tests/ui/views.py`:
-
-``` python
-class Test${APPNAMNE}HomeView( View ):
-
- def get(self, request, *args, **kwargs):
- context = {
- }
- return render(request, "${APPNAME}/testing/ui/home.html", context )
-```
-
-And in `tests/ui/urls.py`:
-
-``` python
-from django.urls import re_path
-
-from . import views
-
-
-urlpatterns = [
-
- re_path( r'^$',
- views.TestUi${APPNAME}HomeView.as_view(),
- name='${APPNAME}_tests_ui'),
-]
-```
-
-### UI Testing Framework Guidelines
-
-The visual testing framework at `/testing/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.
-``` shell
-hi.tests.ui.email_test_views.py
-```
-This requires the email templates follow the naming patterns expected in view classes.
-
diff --git a/docs/dev/Weather.md b/docs/dev/Weather.md
deleted file mode 100644
index a1990d8d..00000000
--- a/docs/dev/Weather.md
+++ /dev/null
@@ -1,36 +0,0 @@
-<img src="../../src/hi/static/img/hi-logo-w-tagline-197x96.png" alt="Home Information Logo" width="128">
-
-# Weather
-
-## Design Principles
-
-- We do not want to depend on any one data source.
-- We want to be able to merge data from multiple sources.
-
-## Design Concetps
-
-- We define our own "unified" view of weather data in `hi.apps.weather.transient_models`.
-- We will populate that with data from various (API) sources (background tasks).
-- Every data point will be associated with its source and the time in which it was fetched.
-- Sources will have a priority ordering.
-- Lower priority sources will predominatly be used for filling in missing data.
-- Lower priority sources may overwrite existing data if the data is very stale.
-- We need to respect rate and usage limits and cache weather data.
-
-## Adding New Weather Data Source
-
-Weather data sources are auto-discovered by ensuring you create a specific
-subclass and put it in a specific directory.
-
-- Create a new python file in `hi.apps.weather.weather_sources`.
-- In that file, define a subclass of `WeatherDataSource`.
-- You must provide an implementation for the following methods:
- - `get_data()`
-
-- You may override the following methods:
- - zzz
-
-
-The type of data each API might have can vary a lot, so the module is responsible for mapping the required API call(s) into the unified model used by the `WeatherManager`. Further, each module should cache data if needed to reduce the number of API calls. e.g.,
-- Fetching the days atronommical data only needs to be done once day.
-- Historical weather data is (usually) never going to change).
diff --git a/docs/dev/WeatherSources.md b/docs/dev/WeatherSources.md
deleted file mode 100644
index 14275371..00000000
--- a/docs/dev/WeatherSources.md
+++ /dev/null
@@ -1,85 +0,0 @@
-<img src="../../src/hi/static/img/hi-logo-w-tagline-197x96.png" alt="Home Information Logo" width="128">
-
-# Adding Weather Data Sources
-
-This guide explains how to add new weather data sources to the Home Information system. The weather system uses auto-discovery, making it extremely simple to add new sources.
-
-## Quick Start
-
-To add a new weather source, you only need to:
-
-1. Create a new Python file in `src/hi/apps/weather/weather_sources/`
-2. Implement a class that inherits from `WeatherDataSource`
-3. **That's it!** The system will automatically discover and configure your source
-
-## Implementation Steps
-
-### 1. Study the Base Class
-
-Before implementing, review the `WeatherDataSource` base class in `src/hi/apps/weather/weather_data_source.py` to understand:
-
-- Required constructor parameters
-- Available configuration methods (`requires_api_key()`, `get_default_enabled_state()`)
-- Properties you can access (`self.api_key`, `self.is_enabled`, `self.geographic_location`)
-- Abstract methods you must implement (`get_data()`)
-
-### 2. Study Existing Examples
-
-Look at the current implementations in `src/hi/apps/weather/weather_sources/` to see:
-
-- How constructor parameters are set
-- How configuration methods are overridden
-- How `get_data()` is implemented
-- Best practices for error handling and logging
-
-### 3. Create Your Implementation
-
-Create your weather source file following the patterns you observed in the existing sources.
-
-## Key Configuration Methods
-
-Refer to the `WeatherDataSource` base class for the exact method signatures, but the key methods you may want to override are:
-
-- `requires_api_key()` - Return `True` if your source needs an API key
-- `get_default_enabled_state()` - Return `False` if your source should be disabled by default
-- `get_data()` - Your main implementation for fetching weather data
-
-## What Happens Automatically
-
-When you add your weather source file:
-
-✅ **Auto-Discovery**: System finds your class at startup
-✅ **Settings Creation**: Creates enable/disable checkbox in config UI
-✅ **API Key Settings**: Creates API key input field (if `requires_api_key()` returns `True`)
-✅ **Priority Handling**: Respects priority ordering for data source selection
-✅ **Enable/Disable**: Only polls enabled sources
-✅ **Rate Limiting**: Enforces your specified rate limits
-
-## Configuration UI
-
-Once added, your weather source will automatically appear in the system configuration under **Settings > Weather** with appropriate controls based on your implementation. However, you will need to run Django migrations after adding the new source. Even though there may be no new migrations to run, the discovery and automatic creation of the database settings is triggered with a post-mmigration signal.
-
-## Testing Your Source
-
-1. Restart the Django server
-2. Check logs for discovery message confirming your source was found
-3. Verify settings appear in config UI
-4. Test enabling/disabling your source
-
-## Best Practices
-
-- **Study Existing Code**: Always look at current implementations in `weather_sources/` before starting
-- **Unique IDs**: Use lowercase, no spaces for your source ID
-- **Descriptive Labels**: Use proper human-readable names
-- **Appropriate Priorities**: Check existing sources to choose a suitable priority level
-- **Rate Limits**: Respect API provider limits
-- **Error Handling**: Handle API failures gracefully following existing patterns
-- **Logging**: Use appropriate log levels for debugging
-
-## Finding Current Examples
-
-To see what weather sources currently exist and how they're implemented, look in:
-- `src/hi/apps/weather/weather_sources/` - All current implementations
-- Weather configuration UI (Settings > Weather) - To see what sources are active
-
-This ensures you're always working with the most current examples and patterns.
diff --git a/docs/dev/backend/async-sync-patterns.md b/docs/dev/backend/async-sync-patterns.md
new file mode 100644
index 00000000..596f09f0
--- /dev/null
+++ b/docs/dev/backend/async-sync-patterns.md
@@ -0,0 +1,64 @@
+# Async/Sync Patterns
+
+## Dual Interface Pattern
+
+Many manager classes provide both sync and async methods:
+
+```python
+class WeatherManager(Singleton):
+ def get_current_conditions(self):
+ """Synchronous version for Django views"""
+ return self._fetch_conditions_sync()
+
+ async def get_current_conditions_async(self):
+ """Asynchronous version for integrations"""
+ return await self._fetch_conditions_async()
+```
+
+## Background Process Coordination
+
+### Thread Safety
+```python
+class AlertManager(Singleton):
+ def __init_singleton__(self):
+ self._lock = threading.Lock()
+ self._alert_queue = deque()
+
+ def add_alert(self, alert):
+ with self._lock:
+ self._alert_queue.append(alert)
+```
+
+### Django + AsyncIO Integration
+```python
+import asyncio
+from asgiref.sync import sync_to_async
+
+class IntegrationManager(Singleton):
+ async def process_entities_async(self):
+ entities = await sync_to_async(list)(
+ Entity.objects.select_related('location').all()
+ )
+ for entity in entities:
+ await self._process_entity_async(entity)
+```
+
+## Event Loop Management
+
+### Proper Initialization
+```python
+class BackgroundService(Singleton):
+ def __init_singleton__(self):
+ self._event_loop = None
+ self._background_task = None
+
+ def start_service(self):
+ if not self._event_loop:
+ self._event_loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(self._event_loop)
+ self._background_task = self._event_loop.create_task(self._run_background())
+```
+
+## Related Documentation
+- Backend guidelines: [Backend Guidelines](backend-guidelines.md)
+- Testing async patterns: [Testing Patterns](../testing/testing-patterns.md#manager-class-asyncsync-testing)
\ No newline at end of file
diff --git a/docs/dev/backend/backend-guidelines.md b/docs/dev/backend/backend-guidelines.md
new file mode 100644
index 00000000..0b570512
--- /dev/null
+++ b/docs/dev/backend/backend-guidelines.md
@@ -0,0 +1,381 @@
+# Backend Guidelines
+
+## App Module Structure
+
+Each Django app follows this standard structure:
+
+```
+hi/apps/${APPNAME}/
+├── enums.py # Enums related to the module
+├── models.py # Django ORM models
+├── transient_models.py # Non-ORM models (not persisted)
+├── urls.py # URL patterns when module provides views
+├── views.py # Main views for module
+├── views_mixin.py # Common view functionality
+├── forms.py # Django forms for views
+├── ${NAME}_manager.py # Singleton manager classes
+├── settings.py # User-controllable settings
+├── monitors.py # Periodic background processes
+├── templates/${APPNAME}/ # App templates
+├── apps.py # Django-required module definition
+├── tests/ # Unit tests
+└── admin.py # Django admin console integration
+
+# Edit mode structure (when applicable)
+edit/
+├── urls.py # Edit-only URLs
+├── views.py # Edit-only views
+└── ... # Same structure for edit functionality
+```
+
+## Django Model Patterns
+
+### Integration Key Pattern
+
+All external systems use integration keys for entity mapping:
+
+```python
+class IntegrationKeyMixin(models.Model):
+ integration_id = models.CharField(max_length=255, null=True, blank=True)
+ integration_name = models.CharField(max_length=50, null=True, blank=True)
+
+ class Meta:
+ abstract = True
+
+ @property
+ def integration_key(self):
+ return f"{self.integration_name}:{self.integration_id}"
+```
+
+### Entity-Centric Design
+
+All controllable/observable items modeled as entities with states:
+
+```python
+class Entity(IntegrationKeyMixin):
+ name = models.CharField(max_length=100)
+ location = models.ForeignKey('location.Location', on_delete=models.CASCADE)
+ entity_type = models.ForeignKey('EntityType', on_delete=models.CASCADE)
+
+ class Meta:
+ indexes = [
+ models.Index(fields=['integration_name', 'integration_id']),
+ ]
+
+class EntityState(models.Model):
+ entity = models.ForeignKey(Entity, on_delete=models.CASCADE, related_name='states')
+ entity_state_type = models.ForeignKey('EntityStateType', on_delete=models.CASCADE)
+
+ class Meta:
+ unique_together = ['entity', 'entity_state_type']
+```
+
+
+### Database Indexing Strategy
+
+Strategic use of `db_index=True` for query performance:
+
+```python
+class SensorResponse(models.Model):
+ sensor = models.ForeignKey(Sensor, on_delete=models.CASCADE, db_index=True)
+ timestamp = models.DateTimeField(auto_now_add=True, db_index=True)
+ value = models.TextField()
+
+ class Meta:
+ indexes = [
+ models.Index(fields=['sensor', '-timestamp']), # Composite index for queries
+ models.Index(fields=['timestamp']), # For time-range queries
+ ]
+```
+
+## Singleton Manager Pattern
+
+Core functionality uses singleton pattern for system-wide coordination:
+
+```python
+from hi.utils.singleton import Singleton
+
+class AlertManager(Singleton):
+ def __init_singleton__(self):
+ self._alert_queue = AlertQueue()
+ self._lock = threading.Lock()
+
+ def add_alert(self, alert_data):
+ with self._lock:
+ # Thread-safe alert processing
+ self._alert_queue.add(alert_data)
+
+ @classmethod
+ def instance(cls):
+ """Get singleton instance"""
+ return cls()
+```
+
+### Manager Initialization Patterns
+
+```python
+def ensure_initialized(self):
+ """Ensure manager is properly initialized (sync version)"""
+ if not hasattr(self, '_initialized'):
+ self._initialize_data_structures()
+ self._initialized = True
+
+async def ensure_initialized_async(self):
+ """Ensure manager is properly initialized (async version)"""
+ if not hasattr(self, '_initialized'):
+ await self._initialize_data_structures_async()
+ self._initialized = True
+```
+
+## Dual Sync/Async Patterns
+
+Many manager classes support both Django views and async integration services:
+
+```python
+class WeatherManager(Singleton):
+ def get_current_conditions(self):
+ """Synchronous version for Django views"""
+ return self._fetch_conditions_sync()
+
+ async def get_current_conditions_async(self):
+ """Asynchronous version for integrations"""
+ return await self._fetch_conditions_async()
+
+ def do_control(self, device_id, action):
+ """Sync control for web requests"""
+ return self._execute_control(device_id, action)
+
+ async def do_control_async(self, device_id, action):
+ """Async control for background processes"""
+ return await self._execute_control_async(device_id, action)
+```
+
+## Background Process Integration
+
+### Thread Management
+
+```python
+class AppMonitorManager(Singleton):
+ def __init_singleton__(self):
+ self._event_loop = None
+ self._background_threads = []
+ self._shutdown_event = threading.Event()
+
+ def start_background_monitoring(self):
+ """Start background monitoring threads"""
+ thread = threading.Thread(target=self._monitor_loop, daemon=True)
+ thread.start()
+ self._background_threads.append(thread)
+
+ def shutdown(self):
+ """Graceful shutdown of background processes"""
+ self._shutdown_event.set()
+ for thread in self._background_threads:
+ thread.join(timeout=5.0)
+```
+
+### Django + AsyncIO Integration
+
+```python
+import asyncio
+from asgiref.sync import sync_to_async
+
+class IntegrationManager(Singleton):
+ def __init_singleton__(self):
+ self._event_loop = asyncio.new_event_loop()
+
+ async def process_entities_async(self):
+ """Process entities with proper ORM access"""
+ # Use select_related to prevent lazy loading issues
+ entities = await sync_to_async(list)(
+ Entity.objects.select_related('location', 'entity_type').all()
+ )
+
+ for entity in entities:
+ await self._process_entity_async(entity)
+```
+
+## Django Views
+
+**Simple Views**: Our design philophy is to keep the Django view classes in views.py somewhat simple. When where the viws need non-trivial computations, database queries or construction of intricate data structure, we use some helper class to encapsulate the business logic. For example, the method _group_history_by_time() should be moved to a helper class. In this case, given the scope of video browsing, it makes sense for there to be a dedicated class for all the various helpers needed related to this feature.
+
+**URL Names**: Always leverage Django url names and never depend on details and strings of user-facing urls.
+
+## Performance Optimization Patterns
+
+### TTL Caching
+
+```python
+from cachetools import TTLCache
+import threading
+
+class StatusDisplayManager(Singleton):
+ def __init_singleton__(self):
+ self._cache = TTLCache(maxsize=1000, ttl=60) # 1 minute TTL
+ self._cache_lock = threading.Lock()
+
+ def get_status_display(self, entity_id):
+ with self._cache_lock:
+ if entity_id in self._cache:
+ return self._cache[entity_id]
+
+ status = self._compute_status_display(entity_id)
+ self._cache[entity_id] = status
+ return status
+```
+
+### Deque-based Aggregation
+
+```python
+from collections import deque
+
+class AlertManager(Singleton):
+ def __init_singleton__(self):
+ # Memory-efficient circular buffer
+ self._recent_alerts = deque(maxlen=100)
+
+ def add_alert(self, alert):
+ self._recent_alerts.append(alert)
+ # Automatically removes oldest when maxlen exceeded
+```
+
+## Django View Patterns
+
+### View Mixins for Common Functionality
+
+```python
+class EntityMixin:
+ def get_entity(self):
+ """Get entity from URL parameters"""
+ entity_id = self.kwargs.get('entity_id')
+ return get_object_or_404(Entity, id=entity_id)
+
+class LocationViewMixin:
+ def get_location_view(self):
+ """Get current location view from session"""
+ location_view_id = self.request.session.get('location_view_id')
+ if location_view_id:
+ return LocationView.objects.get(id=location_view_id)
+ return None
+```
+
+### Custom View Base Classes
+
+```python
+class HiModalView(View):
+ """Base for views that handle both sync and async requests"""
+
+ def dispatch(self, request, *args, **kwargs):
+ if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
+ return self.async_dispatch(request, *args, **kwargs)
+ return self.sync_dispatch(request, *args, **kwargs)
+
+ def sync_dispatch(self, request, *args, **kwargs):
+ """Handle synchronous requests - render full page"""
+ response = super().dispatch(request, *args, **kwargs)
+ return response
+
+ def async_dispatch(self, request, *args, **kwargs):
+ """Handle AJAX requests - return JSON with HTML fragments"""
+ response = super().dispatch(request, *args, **kwargs)
+ if hasattr(response, 'content'):
+ return JsonResponse({
+ 'modal': response.content.decode('utf-8'),
+ 'status': 'success'
+ })
+ return response
+```
+
+## Enums
+
+We leverage enums extensively and do not allow "magic" strings to represent core concepts that the application Logic depends on. We have defined a base class `hi.apps.common.enums.LabeledEnums` for al enums used in the application that slightly extends their capabilities and provides some convenience methods.
+
+A key convenience method is the `from_name` and `from_name_safe` methods. These provide more robust case-insensitve and whitespace-insensitive matching. The latter does not raise an exception for bad values, but returns the default value for uses where the default bhavior is better than interrupting the flow.
+
+### Enums in Django Models
+
+We have a pattern for storing enums in the database that is used throughout the code. It is described like this:
+
+The design pattern for storing enumerated values in the Database is *NOT* to use the Django/databases enumeration/choices type, but use a string via Django CharField (VARCHAR) instead. The rationale is that we prefer the flexibility to add new enums without requiring a database migration for such a trivial change.
+
+We use a special base level enum hi.apps.common.LabeledEnum for most enums, but especially those stored in the database. The key features of this class is to ensure consistency as we put values into and out of the database, and to gracefully handle the case of improper values. Specifically, the `__str__` method returns the enum name in *LOWER* case, though the Django name field matches the casing of the defined enum.
+
+Further, we adopt a naming convention to make the difference between the enum class and the Django model field distinct by having the Django field always have `str` as the fielkd name suffix. For example, if the enum class is named `EntityType`, the Django field name would be `entity_type_str`. Further, we also add a setter/getter pair on the model that matches the enum name and that accepts/returns an enum instance. e.g.,
+```
+ @property
+ def entity_type(self) -> EntityType:
+ return EntityType.from_name_safe( self.entity_type_str )
+
+ @entity_type.setter
+ def entity_type( self, entity_type : EntityType ):
+ self.entity_type_str = str(entity_type)
+ return
+```
+
+We are aware that there is a risk in this pattern, and we have done work to correct it by creating the custom Django model field `hi.apps.common.model_fields.LabeledEnumField`. All going forward new enums must use this new custom field when storing in a model. Retrofitting existing models is on a best effort, time availability basis.
+
+## Settings and Configuration
+
+### App Settings Pattern
+
+Each internal Django app module can provide user-controllable settings that appear on the main config page. These settings are auto-discovered by the `config` app module. The presence of a file named `settings.py` in an app module will automatically get picked up and create a new config area on the user-facing config page.
+
+In the `settings.py` file, define a subclass of the enum `SettingEnum` to define the label and data types:
+
+```python
+# In app/settings.py
+from hi.config.enums import SettingEnum
+
+class WeatherSettings(SettingEnum):
+ REFRESH_INTERVAL = ("refresh_interval", int, 300, "Weather refresh interval (seconds)")
+ DEFAULT_LOCATION = ("default_location", str, "", "Default weather location")
+ ENABLE_ALERTS = ("enable_alerts", bool, True, "Enable weather alerts")
+
+ def __init__(self, key, data_type, default_value, description):
+ self.key = key
+ self.data_type = data_type
+ self.default_value = default_value
+ self.description = description
+```
+
+### Adding to Existing Settings
+
+After adding a new value to an app's `SettingEnum`, you will need to run `./manage.py migrate` to populate the database with the new setting and its default value. New settings are written to the DB using a post-migrate signal.
+
+### Internal Settings Debugging
+
+For debugging help, there is a URL to inspect the Django internal `settings.py` content:
+```
+http://localhost:8411/config/internal
+```
+
+### Adding New Config UI Tab Section
+
+To add a new tab section to the Configuration UI:
+
+1. **Add entry to `ConfigPageType`**
+2. **Add a View** - view class should extend `ConfigPageView`
+3. **Override methods**:
+ - `config_page_type()`
+ - `get_main_template_name()`
+ - `get_template_context()`
+4. **Create template** (matching name)
+5. **Template should extend** `config/pages/config_base.html`
+6. **Add to `urls.py`** (ensure this is included in top-level `urls.py`)
+
+## Related Documentation
+- Django patterns: [Django Patterns](django-patterns.md)
+- Database conventions: [Database Conventions](database-conventions.md)
+- Async/sync patterns: [Async Sync Patterns](async-sync-patterns.md)
+- Integration patterns: [Integration Guidelines](../integrations/integration-guidelines.md)
+- Testing: [Testing Guidelines](../testing/testing-guidelines.md)
+
+## Debugging
+
+## Custom Debug Settings
+
+You can modify these variables in `src/hi/settings/development.py` to enable/disable some custom development features:
+
+- `SUPPRESS_SELECT_REQUEST_ENPOINTS_LOGGING` - Suppress showing the request line log message. The polling front-end will generate a long stream of these and it make it hard to see other requests.
+- `SUPPRESS_MONITORS` - Turns off running any of the background monitor tasks. Useful when working on something not related ot them to prevent unnecessary logging and resource usage.
+- `BASE_URL_FOR_EMAIL_LINKS` - If needing to test the links in delivered emails. We usually need this to point back to the local development server that send the email.
diff --git a/docs/dev/backend/database-conventions.md b/docs/dev/backend/database-conventions.md
new file mode 100644
index 00000000..e6a43d50
--- /dev/null
+++ b/docs/dev/backend/database-conventions.md
@@ -0,0 +1,17 @@
+# Database Conventions
+
+### Indexing Strategy
+```python
+class Meta:
+ indexes = [
+ models.Index(fields=['integration_name', 'integration_id']),
+ models.Index(fields=['timestamp']),
+ models.Index(fields=['entity', '-timestamp']),
+ ]
+ db_table = 'entity_sensor_response'
+```
+
+
+## Related Documentation
+- Backend guidelines: [Backend Guidelines](backend-guidelines.md)
+- Django patterns: [Django Patterns](django-patterns.md)
\ No newline at end of file
diff --git a/docs/dev/backend/django-patterns.md b/docs/dev/backend/django-patterns.md
new file mode 100644
index 00000000..1d697375
--- /dev/null
+++ b/docs/dev/backend/django-patterns.md
@@ -0,0 +1,426 @@
+# Django Patterns
+
+## Model Design Patterns
+
+### Abstract Base Models
+
+Use abstract models for common functionality:
+
+```python
+class TimestampedModel(models.Model):
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ abstract = True
+
+class Entity(IntegrationKeyMixin, TimestampedModel):
+ name = models.CharField(max_length=100)
+ # Inherits integration keys and timestamps
+```
+
+### Custom Model Managers
+
+Create custom managers for common query patterns:
+
+```python
+class EntityManager(models.Manager):
+ def active(self):
+ """Get only active entities"""
+ return self.filter(is_active=True)
+
+ def with_sensors(self):
+ """Get entities that have sensors"""
+ return self.filter(sensors__isnull=False).distinct()
+
+ def for_location_view(self, location_view):
+ """Get entities visible in location view"""
+ return self.filter(
+ location=location_view.location,
+ entityposition__isnull=False
+ ).select_related('entity_type', 'location')
+
+class Entity(models.Model):
+ objects = EntityManager()
+ # ... model fields ...
+```
+
+### Model Property Patterns
+
+Use properties for computed fields and business logic:
+
+```python
+class Entity(models.Model):
+ @property
+ def has_recent_activity(self):
+ """Check if entity had activity in last hour"""
+ if not hasattr(self, '_recent_activity'):
+ cutoff = timezone.now() - timedelta(hours=1)
+ self._recent_activity = self.sensor_responses.filter(
+ timestamp__gte=cutoff
+ ).exists()
+ return self._recent_activity
+
+ @property
+ def display_status(self):
+ """Get human-readable status"""
+ return self.get_current_state_display()
+
+ def get_current_state_display(self):
+ """Business logic for state display"""
+ latest_response = self.get_latest_sensor_response()
+ if not latest_response:
+ return 'Unknown'
+ return latest_response.get_display_value()
+```
+
+### Model Method Patterns
+
+Encapsulate business logic in model methods:
+
+```python
+class Alert(models.Model):
+ def get_first_visual_content(self):
+ """Get first image or visual content for display"""
+ for alarm in self.alarm_list:
+ for source_detail in alarm.source_details_list:
+ if source_detail.image_url:
+ return {
+ 'type': 'image',
+ 'url': source_detail.image_url,
+ 'description': source_detail.description
+ }
+ return None
+
+ def get_priority_level(self):
+ """Calculate priority based on alarm levels"""
+ if not self.alarm_list:
+ return 'low'
+
+ max_level = max(alarm.level for alarm in self.alarm_list)
+ if max_level >= AlarmLevel.CRITICAL:
+ return 'critical'
+ elif max_level >= AlarmLevel.WARNING:
+ return 'high'
+ return 'medium'
+```
+
+## View Patterns
+
+### Class-Based View Mixins
+
+Create reusable mixins for common view functionality:
+
+```python
+class LocationViewContextMixin:
+ """Add location view context to all views"""
+
+ def get_context_data(self, **kwargs):
+ context = super().get_context_data(**kwargs)
+ context['current_location_view'] = self.get_current_location_view()
+ context['available_location_views'] = LocationView.objects.all()
+ return context
+
+ def get_current_location_view(self):
+ """Get location view from session or default"""
+ location_view_id = self.request.session.get('location_view_id')
+ if location_view_id:
+ try:
+ return LocationView.objects.get(id=location_view_id)
+ except LocationView.DoesNotExist:
+ pass
+ return LocationView.objects.filter(is_default=True).first()
+
+class EntityListView(LocationViewContextMixin, ListView):
+ model = Entity
+ template_name = 'entity/pages/entity_list.html'
+
+ def get_queryset(self):
+ location_view = self.get_current_location_view()
+ if location_view:
+ return Entity.objects.for_location_view(location_view)
+ return Entity.objects.active()
+```
+
+### Form Processing Patterns
+
+Standard form handling with proper error handling:
+
+```python
+class EntityUpdateView(UpdateView):
+ model = Entity
+ form_class = EntityForm
+ template_name = 'entity/pages/entity_edit.html'
+
+ def form_valid(self, form):
+ """Handle successful form submission"""
+ try:
+ # Perform any additional business logic
+ entity = form.save(commit=False)
+ entity.updated_by = self.request.user
+ entity.save()
+
+ # Add success message
+ messages.success(
+ self.request,
+ f"Entity '{entity.name}' updated successfully."
+ )
+
+ return super().form_valid(form)
+
+ except ValidationError as e:
+ form.add_error(None, e.message)
+ return self.form_invalid(form)
+ except Exception as e:
+ form.add_error(None, "An unexpected error occurred.")
+ logger.exception(f"Error updating entity {entity.id}: {e}")
+ return self.form_invalid(form)
+
+ def get_success_url(self):
+ """Redirect based on user action"""
+ if 'save_and_continue' in self.request.POST:
+ return reverse('entity_edit', kwargs={'pk': self.object.pk})
+ return reverse('entity_list')
+```
+
+### AJAX View Patterns
+
+Handle both regular and AJAX requests:
+
+```python
+class EntityActionView(View):
+ def post(self, request, *args, **kwargs):
+ entity = get_object_or_404(Entity, id=kwargs['entity_id'])
+ action = request.POST.get('action')
+
+ try:
+ result = self.perform_action(entity, action)
+
+ if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
+ return JsonResponse({
+ 'status': 'success',
+ 'message': f"Action '{action}' completed successfully",
+ 'result': result,
+ 'entity_id': entity.id
+ })
+ else:
+ messages.success(request, f"Action '{action}' completed successfully")
+ return redirect('entity_detail', pk=entity.id)
+
+ except Exception as e:
+ error_msg = f"Failed to perform action '{action}': {str(e)}"
+
+ if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
+ return JsonResponse({
+ 'status': 'error',
+ 'message': error_msg
+ }, status=400)
+ else:
+ messages.error(request, error_msg)
+ return redirect('entity_detail', pk=entity.id)
+
+ def perform_action(self, entity, action):
+ """Override in subclasses for specific actions"""
+ raise NotImplementedError("Subclasses must implement perform_action")
+```
+
+## Custom Template Tags and Filters
+
+### Inclusion Tags for Reusable Components
+
+```python
+# In templatetags/entity_tags.py
+from django import template
+from django.template.loader import render_to_string
+
+register = template.Library()
+
[email protected]_tag('entity/tags/entity_status_badge.html')
+def entity_status_badge(entity, size='normal'):
+ """Render entity status badge with appropriate styling"""
+ status = entity.get_current_status()
+ css_class = f'badge-{status.get_css_class()}'
+
+ return {
+ 'entity': entity,
+ 'status': status,
+ 'css_class': css_class,
+ 'size': size,
+ }
+
+def entity_action_url(entity, action):
+ """Generate URL for entity actions"""
+ return reverse('entity_action', kwargs={
+ 'entity_id': entity.id,
+ 'action': action
+ })
+```
+
+### Custom Filters
+
+```python
+def time_since_activity(entity):
+ """Get human-readable time since last activity"""
+ latest_response = entity.get_latest_sensor_response()
+ if not latest_response:
+ return "Never"
+
+ return timesince(latest_response.timestamp)
+
+def status_css_class(entity_state):
+ """Get CSS class for entity state"""
+ # For complete status display implementation including CSS classes,
+ # colors, and visual progression, see [Entity Status Display](../frontend/entity-status-display.md)
+ status_map = {
+ 'active': 'status-active',
+ 'recent': 'status-recent',
+ 'past': 'status-past',
+ 'idle': 'status-idle',
+ 'unknown': 'status-unknown',
+ }
+ return status_map.get(entity_state.lower(), 'status-unknown')
+```
+
+## Django Admin Customization
+
+### Custom Admin Classes
+
+```python
+# In admin.py
+class EntityAdmin(admin.ModelAdmin):
+ list_display = ['name', 'entity_type', 'location', 'is_active', 'last_updated']
+ list_filter = ['entity_type', 'location', 'is_active', 'created_at']
+ search_fields = ['name', 'integration_id']
+ readonly_fields = ['created_at', 'updated_at', 'integration_key']
+
+ fieldsets = (
+ ('Basic Information', {
+ 'fields': ('name', 'entity_type', 'location', 'is_active')
+ }),
+ ('Integration', {
+ 'fields': ('integration_name', 'integration_id', 'integration_key'),
+ 'classes': ('collapse',)
+ }),
+ ('Metadata', {
+ 'fields': ('created_at', 'updated_at'),
+ 'classes': ('collapse',)
+ }),
+ )
+
+ def get_queryset(self, request):
+ """Optimize queries for admin list view"""
+ return super().get_queryset(request).select_related(
+ 'entity_type', 'location'
+ )
+
+ def last_updated(self, obj):
+ """Custom column for last update time"""
+ return obj.updated_at.strftime('%Y-%m-%d %H:%M')
+ last_updated.short_description = 'Last Updated'
+ last_updated.admin_order_field = 'updated_at'
+```
+
+## Signal Patterns
+
+### Model Signals for Business Logic
+
+```python
+# In models.py or signals.py
+from django.db.models.signals import post_save, pre_delete
+from django.dispatch import receiver
+
+@receiver(post_save, sender=Entity)
+def entity_post_save(sender, instance, created, **kwargs):
+ """Handle entity creation/update"""
+ if created:
+ # Initialize default entity states
+ for state_type in EntityStateType.get_defaults_for_entity_type(instance.entity_type):
+ EntityState.objects.get_or_create(
+ entity=instance,
+ entity_state_type=state_type,
+ defaults={'current_value': state_type.default_value}
+ )
+
+ # Update search index or cache
+ search_index.update_entity(instance)
+ cache.delete(f'entity:{instance.id}')
+
+@receiver(pre_delete, sender=EntityImage)
+def cleanup_entity_image(sender, instance, **kwargs):
+ """Clean up image files before deleting model"""
+ if instance.image:
+ if os.path.isfile(instance.image.path):
+ os.remove(instance.image.path)
+```
+
+## Migration Patterns
+
+### Data Migrations
+
+```python
+# In migration file
+from django.db import migrations
+
+def populate_entity_states(apps, schema_editor):
+ """Populate entity states for existing entities"""
+ Entity = apps.get_model('entity', 'Entity')
+ EntityState = apps.get_model('entity', 'EntityState')
+ EntityStateType = apps.get_model('entity', 'EntityStateType')
+
+ default_state_type = EntityStateType.objects.get(name='status')
+
+ for entity in Entity.objects.filter(states__isnull=True):
+ EntityState.objects.create(
+ entity=entity,
+ entity_state_type=default_state_type,
+ current_value='unknown'
+ )
+
+def reverse_populate_entity_states(apps, schema_editor):
+ """Reverse migration - remove populated states"""
+ EntityState = apps.get_model('entity', 'EntityState')
+ EntityState.objects.filter(current_value='unknown').delete()
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ('entity', '0005_add_entity_state_model'),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ populate_entity_states,
+ reverse_populate_entity_states
+ ),
+ ]
+```
+
+### Schema Migrations with Indexes
+
+```python
+class Migration(migrations.Migration):
+ atomic = False # For PostgreSQL index creation
+
+ operations = [
+ migrations.AddIndex(
+ model_name='sensorresponse',
+ index=models.Index(
+ fields=['sensor', '-timestamp'],
+ name='sensor_response_sensor_time_idx'
+ ),
+ ),
+ migrations.RunSQL(
+ "CREATE INDEX CONCURRENTLY IF NOT EXISTS entity_integration_key_idx ON entity_entity (integration_name, integration_id);",
+ reverse_sql="DROP INDEX IF EXISTS entity_integration_key_idx;"
+ ),
+ ]
+```
+
+## Related Documentation
+- Backend guidelines: [Backend Guidelines](backend-guidelines.md)
+- Database conventions: [Database Conventions](database-conventions.md)
+- Testing patterns: [Testing Patterns](../testing/testing-patterns.md)
+- Performance optimization: [Architecture Overview](../shared/architecture-overview.md)
\ No newline at end of file
diff --git a/docs/dev/domain/business-logic.md b/docs/dev/domain/business-logic.md
new file mode 100644
index 00000000..85264fea
--- /dev/null
+++ b/docs/dev/domain/business-logic.md
@@ -0,0 +1,42 @@
+# Business Logic
+
+## Status Display Logic
+
+Visual representation based on sensor readings:
+- CSS class mapping from sensor values
+- Color scheme calculation for SVG elements
+- Icon variant selection based on state
+
+For frontend implementation of visual display including CSS classes, colors, and status updates, see [Entity Status Display](../frontend/entity-status-display.md).
+
+## Value Decaying System
+
+Temporal status calculation for activity-based entities:
+- Active → Recent → Past → Idle progression
+- Configurable time thresholds
+- Visual "cooling off" effect
+
+## Entity State Priority
+
+Multiple sensor priority resolution:
+- Location view type determines priority order
+- Highest priority state controls visual display
+- Different priorities for security vs climate views
+
+## Collection Aggregation
+
+Logical grouping with aggregate status:
+- Status calculation from member entities
+- Critical/Active/Idle hierarchy
+- Positioned and unpositioned entity support
+
+## Security State Transitions
+
+Business rules for security system states:
+- State transition validation
+- Notification requirements
+- Auto-change permissions
+
+## Related Documentation
+- Domain guidelines: [Domain Guidelines](domain-guidelines.md)
+- Entity patterns: [Entity Patterns](entity-patterns.md)
\ No newline at end of file
diff --git a/docs/dev/domain/domain-guidelines.md b/docs/dev/domain/domain-guidelines.md
new file mode 100644
index 00000000..e128bf67
--- /dev/null
+++ b/docs/dev/domain/domain-guidelines.md
@@ -0,0 +1,309 @@
+# Domain Guidelines
+
+## Entity-Centric Design Philosophy
+
+The system models all controllable/observable items as entities with states. This provides a unified approach to managing diverse physical and logical objects.
+
+## Core Domain Models
+
+### Entity Hierarchy
+- **Entity**: Central model for all objects (devices, features, software)
+- **EntityState**: Hidden state variables that are sensed/controlled
+- **EntityType**: Categorization and behavior definition
+- **EntityPosition/EntityPath**: Spatial representation in locations
+
+### Location Modeling
+- **Location**: Physical spaces with SVG-based floor plans
+- **LocationView**: Configurable views of locations with bounds and rotation
+- **LocationItem**: Abstract interface for positionable items
+
+### Sensor/Controller Pattern
+- **Sensor**: Observation of entity state variables
+- **Controller**: Actions to affect entity state variables
+- **SensorResponse**: Historical sensor readings
+
+## Business Logic Patterns
+
+### Status Display System
+
+All entity state variables are indirectly observed through sensors, and all sensor values come from integrations. Integrations normalize sensor values and encapsulate them in SensorResponse instances. The SensorResponseManager receives these responses and provides latest status values and histories to views, also detecting changes and feeding them into the alerting subsystem.
+
+### Status Display Logic
+
+Entity status display is driven by business logic that determines how sensor readings translate into visual states. The `StatusDisplayManager` coordinates this process by calculating appropriate display states based on current and historical sensor data.
+
+```python
+class StatusDisplayManager(Singleton):
+ def get_status_display_data(self, entity):
+ """Compute display state data for entity"""
+ current_state = entity.get_current_state()
+ return StatusDisplayData(
+ status_level=self.calculate_status_level(current_state),
+ priority_state=self.resolve_priority_state(entity),
+ decaying_status=self.calculate_decaying_status(entity, timezone.now())
+ )
+```
+
+The visual implementation of this status data (CSS classes, colors, SVG styling) is handled by the frontend system. See [Entity Status Display](../frontend/entity-status-display.md) for visual implementation details.
+
+### Value Decaying Logic
+
+For some entity state types and sensors, we display not only current sensor values but also visually represent recent past values. For example, when motion is detected in an area, we highlight that, but after motion ends, we visually show it was "active" in the recent past (Active red → Recent orange → Past yellow → Idle green).
+
+#### Implementation Approach
+
+The decaying logic creates synthetic visual states ("recent" and "past") that are not actual EntityState values, but are derived from history and timing of sensor readings. The system examines both current and previous sensor values with timestamps to determine appropriate visual representation.
+
+**Key Concept**: The system uses configurable time thresholds to transition between visual states. An entity that was recently active but is now idle will show as "recent" (orange) for a period, then transition to "past" (yellow), and finally to "idle" (green).
+
+**Supported State Types**: Currently implemented for movement sensors, presence sensors, and open/close sensors - entity types where showing recent activity history provides valuable context.
+
+**Color Progression**: Typical color flow is: Active (red) → Recent (orange) → Past (yellow) → Idle (green/gray). This creates an intuitive visual "cooling off" effect.
+
+**Architecture**: The logic is centralized in the status display system (`StatusDisplayData` and `StatusDisplayManager` classes) and integrates with the existing client-server polling mechanism for real-time updates.
+
+```python
+class EntityStatusCalculator:
+ def calculate_decaying_status(self, entity, current_time):
+ """Calculate status with time-based decay"""
+ latest_activity = entity.get_latest_activity()
+ if not latest_activity:
+ return EntityStatus.IDLE
+
+ time_since = current_time - latest_activity.timestamp
+
+ if time_since < timedelta(minutes=5):
+ return EntityStatus.ACTIVE
+ elif time_since < timedelta(minutes=30):
+ return EntityStatus.RECENT
+ elif time_since < timedelta(hours=2):
+ return EntityStatus.PAST
+ else:
+ return EntityStatus.IDLE
+```
+
+### Multiple Sensors Priority
+
+The visual representation is always for an Entity, but an entity can have multiple states and multiple sensors. Trying to support visual distinctions across the cross-product of values for multiple sensors would be too complicated. Thus, the design decision is that at most one entity state will determine the visual view of the SVG.
+
+We define a default priority of entity states and use the highest priority state. However, a single static priority order is too limiting for many use cases. We need to support different priorities for different purposes. For example, we may want a climate control view and a security view of a defined area. In the former, we want the temperature sensor value to dictate visual display, while in the latter, the motion sensor should impact the area's visual display.
+
+To allow user control over visuals from sensor values, each LocationView instance can have its `location_view_type` set to one of the enum values which determines which EntityStateType value takes precedence for status displays. See `hi.apps.location.enums.LocationViewType`.
+
+```python
+class EntityStatePriorityResolver:
+ def resolve_display_state(self, entity, location_view_type):
+ """Resolve which state takes precedence for display"""
+ state_priorities = self.get_priorities_for_view_type(location_view_type)
+
+ active_states = entity.get_active_states()
+ highest_priority_state = max(
+ active_states,
+ key=lambda state: state_priorities.get(state.entity_state_type, 0)
+ )
+
+ return highest_priority_state
+```
+
+
+## Event-Driven Architecture
+
+### Event System
+- **EventDefinition**: Multi-clause triggers with time windows
+- **EventClause**: Individual conditions for triggering
+- **EventAction**: Automated responses to events
+
+### Alert System
+- **Alert**: System-wide notifications and alarms
+- **AlertManager**: Singleton queue-based processing
+- **AlarmLevel**: Priority classification for alerts
+
+### Weather Integration
+
+The weather system follows a pluggable business design to support multiple data sources and provide unified weather information throughout the system.
+
+#### Business Logic Principles
+
+- **Multi-Source Strategy**: System does not depend on any single weather data source
+- **Data Merging**: Combines data from multiple sources using priority-based resolution
+- **Source Attribution**: Every data point is associated with its source and fetch time
+- **Priority Resolution**: Higher priority sources provide primary data; lower priority sources fill gaps or replace stale data
+
+#### Core Components
+
+- **WeatherManager**: Singleton manager coordinating weather data from multiple sources
+- **WeatherData**: Unified weather information model used throughout the system
+- **WeatherAlert**: Integration with the alert system for weather-based notifications
+
+#### Weather Alert Integration
+
+Weather alerts from external sources integrate with the system alert architecture by converting external weather alerts to system Alarms based on:
+
+- **Alert Type Filtering**: Determines which external weather alerts should create system alarms
+- **Severity Mapping**: Maps external weather alert severity levels to system `AlarmLevel` values
+- **Lifetime Management**: Weather alerts have different duration characteristics than sensor-based events
+- **Security Level Application**: Weather alarms typically apply to all security levels (unlike sensor-based alarms)
+
+For technical implementation details of weather data sources and API integration, see [Weather Integration](../integrations/weather-integration.md).
+
+## Complex Calculations
+
+### Geometric Calculations
+
+Location-based geometric operations for spatial relationships and positioning:
+
+```python
+class LocationGeometry:
+ def calculate_bounds_with_rotation(self, bounds, rotation_degrees):
+ """Calculate bounding box accounting for rotation"""
+ rotation_radians = math.radians(rotation_degrees)
+ cos_r, sin_r = math.cos(rotation_radians), math.sin(rotation_radians)
+
+ # Transform all corners and find bounding box
+ corners = self.get_bounds_corners(bounds)
+ transformed_corners = [
+ self.rotate_point(corner, cos_r, sin_r)
+ for corner in corners
+ ]
+
+ return self.calculate_bounding_box(transformed_corners)
+
+ def calculate_spatial_relationships(self, entity_positions):
+ """Determine spatial relationships between entities"""
+ relationships = []
+ for i, pos1 in enumerate(entity_positions):
+ for j, pos2 in enumerate(entity_positions[i+1:], i+1):
+ distance = self.calculate_distance(pos1, pos2)
+ if distance < self.proximity_threshold:
+ relationships.append(SpatialRelationship(
+ entities=(pos1.entity, pos2.entity),
+ relationship_type=RelationshipType.ADJACENT,
+ distance=distance
+ ))
+ return relationships
+```
+
+For frontend-specific coordinate transformations, SVG viewbox operations, and screen positioning, see [SVG Coordinate Operations](../frontend/svg-coordinate-operations.md).
+
+### Collection Management
+
+```python
+class Collection(models.Model):
+ """Logical grouping of entities"""
+ name = models.CharField(max_length=100)
+ entities = models.ManyToManyField(Entity, related_name='collections')
+
+ def get_aggregate_status(self):
+ """Calculate collection status from member entities"""
+ entity_statuses = [
+ entity.get_current_status()
+ for entity in self.entities.all()
+ ]
+
+ if any(status.is_critical() for status in entity_statuses):
+ return CollectionStatus.CRITICAL
+ elif any(status.is_active() for status in entity_statuses):
+ return CollectionStatus.ACTIVE
+ else:
+ return CollectionStatus.IDLE
+```
+
+## File and Resource Management
+
+### Entity Images and Assets
+
+```python
+class EntityAsset(models.Model):
+ entity = models.ForeignKey(Entity, on_delete=models.CASCADE)
+ asset_type = models.CharField(max_length=50)
+ file_path = models.FileField(upload_to='entity_assets/')
+
+ def delete(self, *args, **kwargs):
+ """Clean up files on deletion"""
+ if self.file_path and os.path.isfile(self.file_path.path):
+ os.remove(self.file_path.path)
+ super().delete(*args, **kwargs)
+
+ def generate_unique_filename(self):
+ """Generate collision-resistant filenames"""
+ ext = self.file_path.name.split('.')[-1]
+ return f"{uuid.uuid4()}.{ext}"
+```
+
+## Enum Business Rules
+
+### Security State Logic
+
+```python
+class SecurityState(Enum):
+ ARMED = ("armed", True, True, "#dc3545")
+ DISARMED = ("disarmed", True, False, "#28a745")
+ TRIGGERED = ("triggered", False, True, "#dc3545")
+ MAINTENANCE = ("maintenance", False, False, "#ffc107")
+
+ def __init__(self, name, auto_change_allowed, sends_notification, color):
+ self.value = name
+ self.auto_change_allowed = auto_change_allowed
+ self.sends_notification = sends_notification
+ self.color = color
+
+ @classmethod
+ def from_name_safe(cls, name, default=None):
+ """Safe enum lookup with business logic"""
+ for state in cls:
+ if state.value == name:
+ return state
+
+ # Business rule: invalid states default to maintenance
+ return default or cls.MAINTENANCE
+
+ def can_transition_to(self, target_state):
+ """Business rules for state transitions"""
+ if self == self.TRIGGERED and target_state != self.DISARMED:
+ return False # Must disarm from triggered state
+
+ if self == self.MAINTENANCE and not target_state.auto_change_allowed:
+ return False # Can't auto-change from maintenance
+
+ return True
+```
+
+## Entity Delegation Pattern
+
+```python
+class EntityStateDelegation(models.Model):
+ """Delegate entity state reflects principal entity state"""
+ delegate_entity = models.ForeignKey(
+ Entity,
+ on_delete=models.CASCADE,
+ related_name='delegated_from'
+ )
+ principal_entity = models.ForeignKey(
+ Entity,
+ on_delete=models.CASCADE,
+ related_name='delegated_to'
+ )
+ entity_state_type = models.ForeignKey(EntityStateType, on_delete=models.CASCADE)
+
+ class Meta:
+ unique_together = ['delegate_entity', 'entity_state_type']
+
+ def sync_state(self):
+ """Synchronize delegate state with principal"""
+ principal_state = self.principal_entity.get_state(self.entity_state_type)
+ delegate_state, created = EntityState.objects.get_or_create(
+ entity=self.delegate_entity,
+ entity_state_type=self.entity_state_type,
+ defaults={'current_value': principal_state.current_value}
+ )
+
+ if not created and delegate_state.current_value != principal_state.current_value:
+ delegate_state.current_value = principal_state.current_value
+ delegate_state.save()
+```
+
+## Related Documentation
+- Entity patterns: [Entity Patterns](entity-patterns.md)
+- Event and alert systems: [Event Alert Systems](event-alert-systems.md)
+- Business logic: [Business Logic](business-logic.md)
+- Data model concepts: [Data Model Concepts](../shared/data-model-concepts.md)
\ No newline at end of file
diff --git a/docs/dev/domain/entity-patterns.md b/docs/dev/domain/entity-patterns.md
new file mode 100644
index 00000000..352c4e76
--- /dev/null
+++ b/docs/dev/domain/entity-patterns.md
@@ -0,0 +1,49 @@
+# Entity Patterns
+
+## Entity-State Relationships
+
+Entities have zero or more EntityState variables representing hidden state that can be sensed or controlled.
+
+## Entity Positioning
+
+Entities can be positioned in locations as icons or paths:
+- **EntityPosition**: Icon-based representation with position, scale, rotation
+- **EntityPath**: SVG path representation for areas or complex shapes
+
+## Entity Delegation
+
+EntityStateDelegation allows one entity's state to proxy another's:
+- Delegate entity reflects principal entity's state
+- Used for visual representation (e.g., thermometer shows room temperature)
+- Supports one-to-one, one-to-many, many-to-one relationships
+
+## Adding New Entity Types
+
+To add a new entity type to the system:
+
+### 1. Add Enum Entry
+
+Add new entry in this enum:
+```python
+# hi.apps.entity.enums.EntityType
+```
+
+Add the new type to the appropriate group:
+```python
+# hi.apps.entity.enums.EntityGroupType
+```
+
+### 2. Configure Visual Representation
+
+Entity types can be displayed as icons or paths. For visual configuration details including SVG icon creation, styling, and template setup, see [Entity Visual Configuration](../frontend/entity-visual-configuration.md).
+
+### 3. Simulator Support (Optional)
+
+If the new type should be supported by the simulator, add it to:
+```python
+# hi.simulator.enums.SimEntityType
+```
+
+## Related Documentation
+- Domain guidelines: [Domain Guidelines](domain-guidelines.md)
+- Data model concepts: [Data Model Concepts](../shared/data-model-concepts.md)
\ No newline at end of file
diff --git a/docs/dev/EventsAlarmsAlerts.md b/docs/dev/domain/event-alert-systems.md
similarity index 62%
rename from docs/dev/EventsAlarmsAlerts.md
rename to docs/dev/domain/event-alert-systems.md
index 4f9b6706..07e826a8 100644
--- a/docs/dev/EventsAlarmsAlerts.md
+++ b/docs/dev/domain/event-alert-systems.md
@@ -1,24 +1,20 @@
-<img src="../../src/hi/static/img/hi-logo-w-tagline-197x96.png" alt="Home Information Logo" width="128">
+# Event Alert Systems
-# Events, Alarms and Alerts
+## Event System Overview
-`SensorResponses` can create events for a user-defined set of rules.
+`SensorResponses` can create events for a user-defined set of rules. `EventDefinitions` define rules and get triggered off changes in one or more `EntityStates`. Events may result in zero or more `Alarms` (can also trigger control actions).
-`EventDefinitions` define rules and get triggered off changes in one or more `EntityStates`.
+- **EventDefinition**: Multi-clause triggers with time windows
+- **EventClause**: Individual conditions for event triggering
+- **EventAction**: Automated responses when events fire
-Events may result in zero or more `Alarms` (can also trigger a control action).
+## Alert Management System
-An `Alarm` defines which `SecurityLevel` it is applicable to and the importance via the `AlarmLevel`.
+An `Alarm` defines which `SecurityLevel` it is applicable to and the importance via the `AlarmLevel`. If the `Alarm` matches the current system security level, it becomes an `Alert` with the defined `AlarmLevel` and unique `Alarm` signature.
-If the `Alarm` matches the current system security level, it becomes an `Alert` with the defined `AlarmLevel` and an unique `Alarm` signature.
+Alerts are those `Alarms` that we want to get the user's attention for. An `Alert` may contain one or more `Alarm` instances since there is only ever one `Alert` active for a given alarm signature. A WeatherAlert can also create an alarm and system alert.
-Alerts are those `Alarms` that we want to get the user's attention for.
-
-An `Alert` may contain one or more `Alarm` instances since there is only ever one `Alert` active for a given alarm signature.
-
-A WeatherAlert can also create an alarm and (system) alert.
-
-## Alarm Signature System
+### Alarm Signature System
Each alarm has a unique signature format: `{alarm_source}.{alarm_type}.{alarm_level}`
@@ -28,22 +24,22 @@ Each alarm has a unique signature format: `{alarm_source}.{alarm_type}.{alarm_le
Multiple alarms with the same signature are grouped into a single Alert, preventing duplicate notifications for the same condition.
-## Alert Lifecycle Management
+### Alert Lifecycle Management
-### Creation
+#### Creation
- Alarms are added to the system and become Alerts if they match the current SecurityLevel
- Each Alert starts with a `start_datetime` and calculates an `end_datetime` based on `alarm_lifetime_secs`
-### Grouping
+#### Grouping
- When a new alarm arrives with the same signature as an existing Alert, it gets added to that Alert
- The Alert's `end_datetime` is extended based on the new alarm's lifetime
- Alert titles show the count when multiple alarms are grouped: "Critical: Motion Detected (3)"
-### Acknowledgment
+#### Acknowledgment
- Users can acknowledge Alerts to stop active notifications
- Acknowledged Alerts remain visible but don't trigger new notifications
-### Expiration and Removal
+#### Expiration and Removal
- Alerts are automatically removed when they expire (`end_datetime` passes)
- Acknowledged Alerts are also automatically removed during periodic maintenance
- Maximum of 50 Alerts are kept in memory at any time
@@ -93,3 +89,34 @@ Weather alerts from external sources (e.g., NWS) can be converted to system Alar
- **Severity Mapping**: Weather alert severity levels map to system `AlarmLevel`
- **Appropriate Lifetimes**: Weather alerts have different duration characteristics than sensor-based events
- **Security Level Application**: Weather alarms typically apply to all security levels
+
+## Alert Processing Implementation
+
+Queue-based system using `deque` with maxlen for memory efficiency:
+
+```python
+class AlertManager(Singleton):
+ def __init_singleton__(self):
+ self._alert_queue = deque(maxlen=50)
+ self._lock = threading.Lock()
+
+ def add_alarm(self, alarm):
+ """Add alarm and create/update alert"""
+ with self._lock:
+ signature = self._generate_signature(alarm)
+ existing_alert = self._find_alert_by_signature(signature)
+
+ if existing_alert:
+ self._group_alarm_to_alert(existing_alert, alarm)
+ else:
+ self._create_new_alert(alarm, signature)
+
+ def _generate_signature(self, alarm):
+ """Generate unique signature for alarm grouping"""
+ return f"{alarm.source}.{alarm.type}.{alarm.level}"
+```
+
+## Related Documentation
+- Domain guidelines: [Domain Guidelines](domain-guidelines.md)
+- Business logic: [Business Logic](business-logic.md)
+- Integration patterns: [Integration Guidelines](../integrations/integration-guidelines.md)
\ No newline at end of file
diff --git a/docs/dev/frontend/entity-status-display.md b/docs/dev/frontend/entity-status-display.md
new file mode 100644
index 00000000..80b56dec
--- /dev/null
+++ b/docs/dev/frontend/entity-status-display.md
@@ -0,0 +1,1998 @@
+# Entity Status Display
+
+## Quick Reference
+
+### Common Tasks
+- **Add new status color** → [Update CSS variables](#status-color-system) → Modify `:root` color definitions
+- **Change status progression** → [Update color classes](#visual-state-progression) → Modify state-specific CSS
+- **Fix polling issues** → [Check polling system](#polling-system-implementation) → Verify `/api/status` endpoint
+- **Update entity styling** → [Modify CSS classes](#css-class-mapping) → Edit `.entity-svg` rules
+- **Test status changes** → [Use synthetic data](#server-response-format) → Create test entities with different states
+
+### Key Files
+- **CSS**: Status colors defined in CSS custom properties (`:root` section)
+- **JavaScript**: `polling.js` handles real-time updates via `/api/status`
+- **Templates**: Entity elements need `data-entity-id` attributes for updates
+- **Backend**: `StatusDisplayManager` calculates display states from sensor data
+
+### Quick Fixes
+| Problem | Solution | Location |
+|---------|----------|----------|
+| Colors not updating | Check CSS class application | [CSS Class Mapping](#css-class-mapping) |
+| Polling not working | Verify StatusPoller initialization | [Polling System](#polling-system-implementation) |
+| SVG elements not styling | Add proper CSS selectors | [SVG Element Handling](#svg-element-handling) |
+| Status stuck on old value | Check server response format | [Server Response Format](#server-response-format) |
+
+
+## Real-World Workflow Examples
+
+### Workflow 1: Adding Status Display to New Entity Template
+
+**Scenario**: You have a new entity type (smart thermostat) that needs status display functionality in location views.
+
+**Step-by-Step Implementation:**
+
+1. **Plan the Visual States** (Domain consideration)
+ ```python
+ # Thermostat states we want to display:
+ # - heating (red) - actively heating
+ # - cooling (blue) - actively cooling
+ # - idle (green) - maintaining temperature
+ # - offline (gray) - no communication
+ ```
+
+2. **Define Status CSS Classes** ([CSS Class Mapping](#css-class-mapping))
+ ```css
+ /* Add to your CSS file */
+ .entity-svg.thermostat-heating {
+ fill: var(--status-active);
+ stroke: #cc0000;
+ }
+
+ .entity-svg.thermostat-cooling {
+ fill: #0066cc;
+ stroke: #004499;
+ }
+
+ .entity-svg.thermostat-idle {
+ fill: var(--status-idle);
+ stroke: #006600;
+ }
+
+ .entity-svg.thermostat-offline {
+ fill: var(--status-unknown);
+ stroke: #666666;
+ }
+ ```
+
+3. **Update Backend Status Logic** ([Server Response Format](#server-response-format))
+ ```python
+ # In your entity model or status manager
+ class ThermostatStatusCalculator:
+ def get_status_css_classes(self, thermostat_entity):
+ current_state = thermostat_entity.get_current_state('hvac_mode')
+
+ if not current_state or current_state.is_stale():
+ return ['thermostat-offline']
+
+ mode = current_state.value
+ if mode == 'heating':
+ return ['thermostat-heating']
+ elif mode == 'cooling':
+ return ['thermostat-cooling']
+ elif mode == 'idle':
+ return ['thermostat-idle']
+ else:
+ return ['thermostat-offline']
+ ```
+
+4. **Update Template Integration** ([Template Integration](#template-integration))
+ ```django
+ <!-- In your location view template -->
+ <g class="entity-group" data-entity-id="{{ thermostat.id }}">
+ <use href="#icon-thermostat"
+ class="entity-svg {{ thermostat.get_status_css_classes|join:' ' }}"
+ transform="translate({{ thermostat.position.x }}, {{ thermostat.position.y }})"/>
+ </g>
+ ```
+
+5. **Test Status Updates** ([Polling System Implementation](#polling-system-implementation))
+ ```javascript
+ // Verify polling picks up thermostat status changes
+ // Check browser Network tab for /api/status requests
+ // Manually trigger state change and observe visual update
+ ```
+
+**Expected Result**: Thermostat icons change color in real-time based on heating/cooling state.
+
+---
+
+### Workflow 2: Debugging Status Colors Not Updating
+
+**Scenario**: Entity status colors were working, but stopped updating after a recent template change.
+
+**Systematic Debugging Process:**
+
+1. **Quick Diagnostic** ([Quick Reference](#quick-reference))
+ ```bash
+ # Check browser dev tools - Elements tab
+ # Look for data-entity-id attribute and CSS classes on entity elements
+ ```
+
+2. **Verify CSS Class Application** ([Troubleshooting - CSS Classes Not Applied](#status-colors-not-updating))
+ ```javascript
+ // In browser console:
+ const element = document.querySelector('[data-entity-id="123"]');
+ console.log('Element found:', element);
+ console.log('Current classes:', element.classList);
+ console.log('Data attribute:', element.getAttribute('data-entity-id'));
+ ```
+
+3. **Check Polling System** ([Troubleshooting - Polling System](#polling-system-not-working))
+ ```javascript
+ // Verify StatusPoller is running
+ console.log('StatusPoller:', window.statusPoller);
+
+ // Check network requests
+ // Browser Dev Tools → Network → Filter by '/api/status'
+ // Should see requests every 5 seconds
+ ```
+
+4. **Test Server Response** ([Server Response Format](#server-response-format))
+ ```bash
+ # Test API endpoint directly
+ curl http://localhost:8411/api/status
+ # Should return JSON with entities object containing your entity ID
+ ```
+
+5. **Verify CSS Variables** ([Status Color System](#status-color-system))
+ ```css
+ /* Check these are defined in your CSS */
+ :root {
+ --status-active: #dc3545;
+ --status-idle: #28a745;
+ /* ... other status colors */
+ }
+ ```
+
+6. **Fix Template Structure** ([Template Integration](#template-integration))
+ ```django
+ <!-- Ensure proper structure -->
+ <g data-entity-id="{{ entity.id }}"> <!-- Must have data-entity-id -->
+ <path class="entity-svg {{ entity.get_status_css_classes }}"> <!-- Must have CSS classes -->
+ </g>
+ ```
+
+**Common Resolution**: Missing `data-entity-id` attribute or incorrect CSS class application.
+
+---
+
+### Workflow 3: Implementing Custom Status Progression
+
+**Scenario**: Create a custom "warming up" status for heating systems that shows a gradual color transition.
+
+**Implementation Steps:**
+
+1. **Design Color Progression** ([Visual State Progression](#visual-state-progression))
+ ```css
+ /* Define custom progression: cold → warming → warm → hot */
+ .heating-system.state-cold {
+ fill: #4a90e2;
+ opacity: 0.6;
+ }
+ .heating-system.state-warming {
+ fill: #f5a623;
+ opacity: 0.7;
+ }
+ .heating-system.state-warm {
+ fill: #e94b3c;
+ opacity: 0.8;
+ }
+ .heating-system.state-hot {
+ fill: #d0021b;
+ opacity: 1.0;
+ }
+ ```
+
+2. **Implement Transition Logic** ([Client-Server Status Updates](#client-server-status-updates))
+ ```javascript
+ class HeatingStatusManager {
+ updateHeatingDisplay(entityId, temperature, targetTemp) {
+ const element = document.querySelector(`[data-entity-id="${entityId}"]`);
+
+ // Calculate heating state based on temperature difference
+ const tempDiff = targetTemp - temperature;
+ let statusClass;
+
+ if (tempDiff > 5) statusClass = 'state-cold';
+ else if (tempDiff > 2) statusClass = 'state-warming';
+ else if (tempDiff > 0.5) statusClass = 'state-warm';
+ else statusClass = 'state-hot';
+
+ // Apply with smooth transition
+ element.classList.remove('state-cold', 'state-warming', 'state-warm', 'state-hot');
+ element.classList.add(statusClass);
+ }
+ }
+ ```
+
+3. **Add Smooth Transitions** ([Performance Considerations](#performance-considerations))
+ ```css
+ .heating-system {
+ transition: fill 2s ease-in-out, opacity 1s ease-in-out;
+ }
+ ```
+
+4. **Test Progression** ([Testing](#testing))
+ ```javascript
+ // Test all state transitions
+ const heatingManager = new HeatingStatusManager();
+ const testCases = [
+ { temp: 65, target: 72 }, // Should be cold
+ { temp: 69, target: 72 }, // Should be warming
+ { temp: 71, target: 72 }, // Should be warm
+ { temp: 72, target: 72 } // Should be hot
+ ];
+
+ testCases.forEach(test => {
+ heatingManager.updateHeatingDisplay('test-heater', test.temp, test.target);
+ });
+ ```
+
+**Expected Result**: Heating system icons smoothly transition through color progression as they approach target temperature.
+
+---
+
+### Workflow 4: Performance Optimization for Many Entities
+
+**Scenario**: Location view with 100+ entities is experiencing slow status updates and browser lag.
+
+**Optimization Process:**
+
+1. **Identify Performance Bottlenecks** ([Performance Considerations](#performance-considerations))
+ ```javascript
+ // Measure update performance
+ console.time('status-update');
+ statusPoller.updateEntityStates(largeStatusData);
+ console.timeEnd('status-update');
+ ```
+
+2. **Implement Batched Updates** ([Performance - Batch Updates](#performance-issues))
+ ```javascript
+ class OptimizedStatusPoller extends StatusPoller {
+ updateEntityStates(statusData) {
+ const updates = Object.entries(statusData.entities);
+
+ // Process in batches to avoid blocking UI
+ const batchSize = 20;
+ let currentBatch = 0;
+
+ const processBatch = () => {
+ const start = currentBatch * batchSize;
+ const end = Math.min(start + batchSize, updates.length);
+
+ for (let i = start; i < end; i++) {
+ const [entityId, stateData] = updates[i];
+ this.updateEntityDisplay(entityId, stateData);
+ }
+
+ currentBatch++;
+
+ if (end < updates.length) {
+ requestAnimationFrame(processBatch);
+ }
+ };
+
+ processBatch();
+ }
+ }
+ ```
+
+3. **Reduce Polling Frequency** ([Performance - Reduce Polling](#performance-issues))
+ ```javascript
+ // Adaptive polling based on entity count
+ const entityCount = Object.keys(statusData.entities).length;
+ const pollInterval = entityCount > 50 ? 10000 : 5000; // 10s vs 5s
+
+ const statusPoller = new OptimizedStatusPoller(pollInterval);
+ ```
+
+4. **Optimize CSS Transitions** ([CSS Animation Optimization](#css-animation-optimization))
+ ```css
+ /* Use transform and opacity instead of color changes where possible */
+ .entity-svg {
+ transition: opacity 0.3s ease, transform 0.3s ease;
+ /* Avoid: transition: fill 0.3s ease; // Expensive! */
+ }
+
+ .entity-svg.performance-optimized {
+ transform: translateZ(0); /* Force hardware acceleration */
+ will-change: transform, opacity;
+ }
+ ```
+
+**Expected Result**: Smooth status updates even with 100+ entities, no UI blocking.
+
+## Common Patterns Library
+
+### Standard Entity Status Templates
+
+#### Basic SVG Entity with Status Classes
+```django
+<!-- Standard pattern for positioned entity icons -->
+<g class="entity-group" data-entity-id="{{ entity.id }}">
+ <use href="#icon-{{ entity.entity_type.name.lower }}"
+ class="entity-svg {{ entity.get_status_css_classes|join:' ' }}"
+ transform="translate({{ entity.position.x }}, {{ entity.position.y }})
+ scale({{ entity.position.scale|default:1.0 }})
+ rotate({{ entity.position.rotation|default:0 }})"/>
+</g>
+```
+
+#### Path Entity with Dynamic Styling
+```django
+<!-- Standard pattern for area/path-based entities -->
+<g class="entity-group" data-entity-id="{{ entity.id }}">
+ <path class="entity-path {{ entity.get_status_css_classes|join:' ' }}"
+ d="{{ entity.path.svg_path }}"
+ style="fill: {{ entity.get_status_fill }};
+ stroke: {{ entity.get_status_stroke }};
+ opacity: {{ entity.get_status_opacity }}"/>
+</g>
+```
+
+#### Entity Status Card (Non-SVG)
+```django
+<!-- Standard pattern for entity cards in lists/grids -->
+<div class="entity-card" data-entity-id="{{ entity.id }}">
+ <div class="status-indicator {{ entity.get_status_css_classes|join:' ' }}"
+ style="background-color: {{ entity.get_status_color }}"></div>
+ <span class="entity-name">{{ entity.name }}</span>
+ <span class="entity-state">{{ entity.get_current_display_state }}</span>
+</div>
+```
+
+### Standard CSS Status Classes
+
+#### Basic Status Color Scheme
+```css
+/* Standard status color variables */
+:root {
+ --status-active: #dc3545; /* Red - Active/Alert */
+ --status-recent: #fd7e14; /* Orange - Recently active */
+ --status-past: #ffc107; /* Yellow - Past activity */
+ --status-idle: #28a745; /* Green - Idle/Safe */
+ --status-unknown: #6c757d; /* Gray - Unknown/Offline */
+}
+
+/* Basic entity status classes */
+.entity-svg.state-active {
+ fill: var(--status-active);
+ stroke: #b02a37;
+ opacity: 1.0;
+}
+
+.entity-svg.state-recent {
+ fill: var(--status-recent);
+ stroke: #cc6200;
+ opacity: 0.8;
+}
+
+.entity-svg.state-past {
+ fill: var(--status-past);
+ stroke: #cc9a00;
+ opacity: 0.6;
+}
+
+.entity-svg.state-idle {
+ fill: var(--status-idle);
+ stroke: #1e7e34;
+ opacity: 0.4;
+}
+
+.entity-svg.state-unknown {
+ fill: var(--status-unknown);
+ stroke: #545b62;
+ opacity: 0.3;
+}
+```
+
+#### Smooth Status Transitions
+```css
+/* Standard transition pattern for status changes */
+.entity-svg, .entity-path {
+ transition: fill 0.3s ease-in-out,
+ stroke 0.3s ease-in-out,
+ opacity 0.3s ease-in-out;
+}
+
+/* Pulse animation for active states */
+@keyframes status-pulse {
+ 0% { opacity: 0.8; }
+ 50% { opacity: 1.0; }
+ 100% { opacity: 0.8; }
+}
+
+.entity-svg.state-active.pulse-enabled {
+ animation: status-pulse 2s ease-in-out infinite;
+}
+```
+
+#### Device-Type Specific Patterns
+```css
+/* Motion sensor specific styling */
+.entity-svg.motion-sensor.state-active {
+ fill: #dc3545;
+ filter: drop-shadow(0 0 4px rgba(220, 53, 69, 0.6));
+}
+
+/* Door sensor specific styling */
+.entity-svg.door-sensor.state-active {
+ fill: #dc3545;
+ stroke-width: 3;
+}
+
+/* Temperature sensor color gradient */
+.entity-svg.temperature-sensor.temp-hot {
+ fill: #dc3545; /* Hot - red */
+}
+.entity-svg.temperature-sensor.temp-warm {
+ fill: #fd7e14; /* Warm - orange */
+}
+.entity-svg.temperature-sensor.temp-cool {
+ fill: #17a2b8; /* Cool - blue */
+}
+.entity-svg.temperature-sensor.temp-cold {
+ fill: #007bff; /* Cold - dark blue */
+}
+```
+
+### Standard JavaScript Polling Implementation
+
+#### Basic StatusPoller Class
+```javascript
+// Standard polling implementation pattern
+class StatusPoller {
+ constructor(options = {}) {
+ this.pollInterval = options.pollInterval || 5000;
+ this.endpoint = options.endpoint || '/api/status';
+ this.isPolling = false;
+ this.errorCount = 0;
+ this.maxErrors = 3;
+ }
+
+ start() {
+ if (this.isPolling) return;
+ this.isPolling = true;
+ this.errorCount = 0;
+ this.poll();
+ }
+
+ stop() {
+ this.isPolling = false;
+ }
+
+ async poll() {
+ if (!this.isPolling) return;
+
+ try {
+ const response = await fetch(this.endpoint);
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
+
+ const statusData = await response.json();
+ this.updateEntityStates(statusData);
+ this.errorCount = 0; // Reset error count on success
+ } catch (error) {
+ console.error('Status polling failed:', error);
+ this.errorCount++;
+
+ if (this.errorCount >= this.maxErrors) {
+ console.error('Too many polling errors, stopping poller');
+ this.stop();
+ return;
+ }
+ }
+
+ if (this.isPolling) {
+ setTimeout(() => this.poll(), this.pollInterval);
+ }
+ }
+
+ updateEntityStates(statusData) {
+ if (!statusData.entities) return;
+
+ Object.entries(statusData.entities).forEach(([entityId, stateData]) => {
+ this.updateEntityDisplay(entityId, stateData);
+ });
+ }
+
+ updateEntityDisplay(entityId, stateData) {
+ const elements = document.querySelectorAll(`[data-entity-id="${entityId}"]`);
+ elements.forEach(element => {
+ this.applyStatusClasses(element, stateData.cssClasses);
+ this.applyColorScheme(element, stateData.colorScheme);
+ });
+ }
+
+ applyStatusClasses(element, cssClasses) {
+ // Remove existing status classes
+ const existingClasses = Array.from(element.classList).filter(c =>
+ c.startsWith('state-') || c.startsWith('temp-') || c.startsWith('priority-')
+ );
+ element.classList.remove(...existingClasses);
+
+ // Apply new status classes
+ if (cssClasses && cssClasses.length) {
+ element.classList.add(...cssClasses);
+ }
+ }
+
+ applyColorScheme(element, colorScheme) {
+ if (!colorScheme) return;
+
+ if (element.tagName.toLowerCase() === 'path' || element.tagName.toLowerCase() === 'use') {
+ element.style.fill = colorScheme.fill || '';
+ element.style.stroke = colorScheme.stroke || '';
+ element.style.opacity = colorScheme.opacity || '';
+ } else if (element.classList.contains('status-indicator')) {
+ element.style.backgroundColor = colorScheme.fill || '';
+ element.style.borderColor = colorScheme.stroke || '';
+ element.style.opacity = colorScheme.opacity || '';
+ }
+ }
+}
+```
+
+#### Standard Initialization Pattern
+```javascript
+// Standard way to initialize status polling
+document.addEventListener('DOMContentLoaded', function() {
+ // Initialize status poller if entity elements exist
+ if (document.querySelectorAll('[data-entity-id]').length > 0) {
+ window.statusPoller = new StatusPoller({
+ pollInterval: 5000,
+ endpoint: '/api/status'
+ });
+ window.statusPoller.start();
+ }
+
+ // Cleanup on page unload
+ window.addEventListener('beforeunload', function() {
+ if (window.statusPoller) {
+ window.statusPoller.stop();
+ }
+ });
+});
+```
+
+### Standard Backend Response Patterns
+
+#### Standard Server Response Format
+```python
+# Standard format for /api/status endpoint responses
+{
+ "timestamp": "2025-01-15T10:30:00Z",
+ "entities": {
+ "entity_123": {
+ "cssClasses": ["state-active", "priority-high"],
+ "colorScheme": {
+ "fill": "#dc3545",
+ "stroke": "#b02a37",
+ "opacity": "0.8"
+ },
+ "displayState": "Motion Detected",
+ "lastUpdated": "2025-01-15T10:29:45Z"
+ },
+ "entity_456": {
+ "cssClasses": ["state-idle"],
+ "colorScheme": {
+ "fill": "#28a745",
+ "stroke": "#1e7e34",
+ "opacity": "0.4"
+ },
+ "displayState": "No Motion",
+ "lastUpdated": "2025-01-15T10:25:12Z"
+ }
+ }
+}
+```
+
+#### Standard Django Model Methods
+```python
+# Standard methods for Entity models to support status display
+class Entity(models.Model):
+ def get_status_css_classes(self):
+ """Return CSS classes for current status"""
+ status_manager = StatusDisplayManager(self)
+ return status_manager.get_css_classes()
+
+ def get_status_color(self):
+ """Return fill color for current status"""
+ status_manager = StatusDisplayManager(self)
+ return status_manager.get_fill_color()
+
+ def get_status_display_data(self):
+ """Return complete status data for API responses"""
+ status_manager = StatusDisplayManager(self)
+ return {
+ 'cssClasses': status_manager.get_css_classes(),
+ 'colorScheme': {
+ 'fill': status_manager.get_fill_color(),
+ 'stroke': status_manager.get_stroke_color(),
+ 'opacity': status_manager.get_opacity()
+ },
+ 'displayState': status_manager.get_display_state(),
+ 'lastUpdated': self.get_last_updated_timestamp()
+ }
+```
+
+### Common Entity Status Testing Patterns
+
+#### Standard Test Fixtures
+```python
+# Standard test setup for entity status testing
+class EntityStatusTestCase(TestCase):
+ def setUp(self):
+ self.location = Location.objects.create(name='Test Location')
+
+ # Create test entities with different types
+ self.motion_sensor = Entity.objects.create(
+ name='Test Motion Sensor',
+ entity_type=EntityType.MOTION_SENSOR,
+ location=self.location
+ )
+
+ self.door_sensor = Entity.objects.create(
+ name='Test Door Sensor',
+ entity_type=EntityType.DOOR_SENSOR,
+ location=self.location
+ )
+
+ # Create EntityPosition for icon entities
+ EntityPosition.objects.create(
+ entity=self.motion_sensor,
+ x=100, y=150, scale=1.0, rotation=0
+ )
+
+ def create_test_state(self, entity, state_type, value, timestamp=None):
+ """Helper to create test entity states"""
+ timestamp = timestamp or timezone.now()
+ return EntityState.objects.create(
+ entity=entity,
+ state_type=state_type,
+ value=value,
+ timestamp=timestamp
+ )
+
+ def assert_status_response(self, response, entity_id, expected_classes):
+ """Helper to assert status API response format"""
+ self.assertSuccessResponse(response)
+ self.assertJsonResponse(response)
+
+ data = response.json()
+ self.assertIn('entities', data)
+ self.assertIn(entity_id, data['entities'])
+
+ entity_data = data['entities'][entity_id]
+ self.assertIn('cssClasses', entity_data)
+ self.assertIn('colorScheme', entity_data)
+
+ for css_class in expected_classes:
+ self.assertIn(css_class, entity_data['cssClasses'])
+```
+
+#### Standard JavaScript Testing Pattern
+```javascript
+// Standard pattern for testing status updates in browser
+function testEntityStatusUpdates() {
+ // Mock status data
+ const mockStatusData = {
+ timestamp: new Date().toISOString(),
+ entities: {
+ 'entity_123': {
+ cssClasses: ['state-active', 'priority-high'],
+ colorScheme: {
+ fill: '#dc3545',
+ stroke: '#b02a37',
+ opacity: '0.8'
+ }
+ }
+ }
+ };
+
+ // Test status application
+ const statusPoller = new StatusPoller();
+ statusPoller.updateEntityStates(mockStatusData);
+
+ // Verify DOM updates
+ const element = document.querySelector('[data-entity-id="entity_123"]');
+ console.assert(element.classList.contains('state-active'), 'Active class not applied');
+ console.assert(element.style.fill === 'rgb(220, 53, 69)', 'Fill color not applied');
+
+ console.log('Entity status update test passed');
+}
+```
+
+## Performance Optimization Guide
+
+### Overview
+
+Entity status display can become a performance bottleneck when dealing with many entities, frequent updates, or complex visual effects. This guide provides strategies to maintain smooth, responsive status displays even under heavy load.
+
+### Performance Monitoring and Profiling
+
+#### Measuring Status Update Performance
+```javascript
+// Monitor status update timing
+class StatusPerformanceMonitor {
+ constructor() {
+ this.updateTimes = [];
+ this.maxSamples = 100;
+ }
+
+ measureUpdate(updateFunction) {
+ const start = performance.now();
+ updateFunction();
+ const end = performance.now();
+
+ this.updateTimes.push(end - start);
+ if (this.updateTimes.length > this.maxSamples) {
+ this.updateTimes.shift();
+ }
+
+ // Log warnings for slow updates
+ const updateTime = end - start;
+ if (updateTime > 16) { // More than one frame at 60fps
+ console.warn(`Slow status update: ${updateTime.toFixed(2)}ms`);
+ }
+ }
+
+ getAverageUpdateTime() {
+ if (this.updateTimes.length === 0) return 0;
+ return this.updateTimes.reduce((a, b) => a + b, 0) / this.updateTimes.length;
+ }
+
+ reportPerformance() {
+ console.log(`Status Update Performance:
+ Average: ${this.getAverageUpdateTime().toFixed(2)}ms
+ Max: ${Math.max(...this.updateTimes).toFixed(2)}ms
+ Min: ${Math.min(...this.updateTimes).toFixed(2)}ms
+ Samples: ${this.updateTimes.length}`);
+ }
+}
+```
+
+#### Browser DevTools Profiling
+```javascript
+// Enable performance tracking in development
+if (process.env.NODE_ENV === 'development') {
+ // Mark status update cycles for performance timeline
+ function markStatusUpdate() {
+ performance.mark('status-update-start');
+ }
+
+ function measureStatusUpdate() {
+ performance.mark('status-update-end');
+ performance.measure('status-update', 'status-update-start', 'status-update-end');
+ }
+
+ // Use in StatusPoller
+ markStatusUpdate();
+ this.updateEntityStates(statusData);
+ measureStatusUpdate();
+}
+```
+
+### DOM Update Optimization
+
+#### Batched DOM Modifications
+```javascript
+// Optimized StatusPoller with batched DOM updates
+class OptimizedStatusPoller extends StatusPoller {
+ updateEntityStates(statusData) {
+ const updates = Object.entries(statusData.entities);
+ const batchSize = 20; // Process 20 entities at a time
+
+ // Use requestAnimationFrame to avoid blocking UI
+ this.processBatch(updates, 0, batchSize);
+ }
+
+ processBatch(updates, startIndex, batchSize) {
+ const endIndex = Math.min(startIndex + batchSize, updates.length);
+
+ // Process current batch
+ for (let i = startIndex; i < endIndex; i++) {
+ const [entityId, stateData] = updates[i];
+ this.updateEntityDisplay(entityId, stateData);
+ }
+
+ // Schedule next batch if more entities remain
+ if (endIndex < updates.length) {
+ requestAnimationFrame(() => {
+ this.processBatch(updates, endIndex, batchSize);
+ });
+ }
+ }
+
+ // Minimize DOM reads and writes
+ updateEntityDisplay(entityId, stateData) {
+ const elements = this.cachedElements[entityId] ||
+ this.cacheEntityElements(entityId);
+
+ elements.forEach(element => {
+ // Batch style updates
+ this.batchStyleUpdate(element, stateData);
+ });
+ }
+
+ cacheEntityElements(entityId) {
+ const elements = document.querySelectorAll(`[data-entity-id="${entityId}"]`);
+ this.cachedElements = this.cachedElements || {};
+ this.cachedElements[entityId] = Array.from(elements);
+ return this.cachedElements[entityId];
+ }
+
+ batchStyleUpdate(element, stateData) {
+ // Collect all style changes before applying
+ const styleUpdates = {};
+
+ if (stateData.colorScheme) {
+ styleUpdates.fill = stateData.colorScheme.fill;
+ styleUpdates.stroke = stateData.colorScheme.stroke;
+ styleUpdates.opacity = stateData.colorScheme.opacity;
+ }
+
+ // Apply all changes at once
+ Object.assign(element.style, styleUpdates);
+
+ // Update classes in single operation
+ if (stateData.cssClasses) {
+ this.applyStatusClasses(element, stateData.cssClasses);
+ }
+ }
+}
+```
+
+#### Virtual Entity Rendering
+```javascript
+// Only render entities in visible viewport
+class VirtualizedStatusDisplay {
+ constructor(svgElement, options = {}) {
+ this.svgElement = svgElement;
+ this.visibleEntities = new Set();
+ this.hiddenEntities = new Set();
+ this.viewBox = this.parseViewBox(svgElement.getAttribute('viewBox'));
+ this.options = {
+ cullingMargin: options.cullingMargin || 50, // Render margin outside viewport
+ ...options
+ };
+
+ // Monitor viewport changes
+ this.svgElement.addEventListener('viewportChanged', (e) => {
+ this.updateViewBox(e.detail.viewBox);
+ });
+ }
+
+ updateViewBox(newViewBox) {
+ this.viewBox = newViewBox;
+ this.updateEntityVisibility();
+ }
+
+ updateEntityVisibility() {
+ const entities = this.svgElement.querySelectorAll('[data-entity-id]');
+
+ entities.forEach(entity => {
+ const isVisible = this.isEntityVisible(entity);
+ const entityId = entity.getAttribute('data-entity-id');
+
+ if (isVisible && this.hiddenEntities.has(entityId)) {
+ // Entity became visible
+ this.showEntity(entity, entityId);
+ } else if (!isVisible && this.visibleEntities.has(entityId)) {
+ // Entity became hidden
+ this.hideEntity(entity, entityId);
+ }
+ });
+ }
+
+ isEntityVisible(entity) {
+ const bbox = entity.getBBox();
+ const margin = this.options.cullingMargin;
+
+ return !(
+ bbox.x + bbox.width < this.viewBox.x - margin ||
+ bbox.x > this.viewBox.x + this.viewBox.width + margin ||
+ bbox.y + bbox.height < this.viewBox.y - margin ||
+ bbox.y > this.viewBox.y + this.viewBox.height + margin
+ );
+ }
+
+ showEntity(entity, entityId) {
+ entity.style.display = 'block';
+ this.visibleEntities.add(entityId);
+ this.hiddenEntities.delete(entityId);
+ }
+
+ hideEntity(entity, entityId) {
+ entity.style.display = 'none';
+ this.hiddenEntities.add(entityId);
+ this.visibleEntities.delete(entityId);
+ }
+}
+```
+
+### Memory Management
+
+#### Element Reference Caching
+```javascript
+// Efficient element caching with memory management
+class EntityElementCache {
+ constructor(maxCacheSize = 1000) {
+ this.cache = new Map();
+ this.accessOrder = [];
+ this.maxCacheSize = maxCacheSize;
+ }
+
+ get(entityId) {
+ if (this.cache.has(entityId)) {
+ // Move to end of access order (LRU)
+ this.accessOrder = this.accessOrder.filter(id => id !== entityId);
+ this.accessOrder.push(entityId);
+ return this.cache.get(entityId);
+ }
+ return null;
+ }
+
+ set(entityId, elements) {
+ // Evict oldest entries if cache is full
+ if (this.cache.size >= this.maxCacheSize) {
+ const oldest = this.accessOrder.shift();
+ this.cache.delete(oldest);
+ }
+
+ this.cache.set(entityId, elements);
+ this.accessOrder.push(entityId);
+ }
+
+ clear() {
+ this.cache.clear();
+ this.accessOrder = [];
+ }
+
+ // Clean up references to removed entities
+ cleanup() {
+ const validEntityIds = new Set();
+ document.querySelectorAll('[data-entity-id]').forEach(el => {
+ validEntityIds.add(el.getAttribute('data-entity-id'));
+ });
+
+ // Remove cached elements for entities that no longer exist
+ for (const [entityId] of this.cache) {
+ if (!validEntityIds.has(entityId)) {
+ this.cache.delete(entityId);
+ this.accessOrder = this.accessOrder.filter(id => id !== entityId);
+ }
+ }
+ }
+}
+```
+
+#### Memory Leak Prevention
+```javascript
+// Prevent memory leaks in long-running applications
+class LeakPreventionStatusPoller extends StatusPoller {
+ constructor(options = {}) {
+ super(options);
+ this.cleanupInterval = options.cleanupInterval || 60000; // 1 minute
+ this.startCleanupTimer();
+ }
+
+ startCleanupTimer() {
+ setInterval(() => {
+ this.performCleanup();
+ }, this.cleanupInterval);
+ }
+
+ performCleanup() {
+ // Clean up element cache
+ if (this.elementCache) {
+ this.elementCache.cleanup();
+ }
+
+ // Remove orphaned event listeners
+ this.removeOrphanedListeners();
+
+ // Force garbage collection in development
+ if (typeof gc !== 'undefined') {
+ gc();
+ }
+ }
+
+ removeOrphanedListeners() {
+ // Track and remove event listeners for removed entities
+ const currentEntityIds = new Set();
+ document.querySelectorAll('[data-entity-id]').forEach(el => {
+ currentEntityIds.add(el.getAttribute('data-entity-id'));
+ });
+
+ // Clean up listeners for removed entities
+ if (this.entityListeners) {
+ Object.keys(this.entityListeners).forEach(entityId => {
+ if (!currentEntityIds.has(entityId)) {
+ delete this.entityListeners[entityId];
+ }
+ });
+ }
+ }
+
+ stop() {
+ super.stop();
+
+ // Clean up all references
+ if (this.elementCache) {
+ this.elementCache.clear();
+ }
+
+ this.entityListeners = {};
+ }
+}
+```
+
+### CSS Performance Optimization
+
+#### Hardware Acceleration
+```css
+/* Force GPU acceleration for status animations */
+.entity-svg, .entity-path {
+ transform: translateZ(0); /* Force hardware acceleration */
+ will-change: fill, stroke, opacity; /* Hint browser about changing properties */
+}
+
+/* Use transform and opacity for animations (GPU-friendly) */
+.entity-svg.status-transition {
+ transition: transform 0.3s ease, opacity 0.3s ease;
+}
+
+/* Avoid expensive properties in animations */
+.entity-svg.avoid-expensive {
+ /* AVOID: animating these properties */
+ /* transition: width 0.3s ease, height 0.3s ease, background-size 0.3s ease; */
+
+ /* PREFER: animating these properties */
+ transition: transform 0.3s ease, opacity 0.3s ease;
+}
+```
+
+#### CSS Containment
+```css
+/* Use CSS containment to limit reflow/repaint scope */
+.entity-group {
+ contain: layout style paint;
+}
+
+.location-view-container {
+ contain: layout;
+}
+
+/* Optimize for large entity lists */
+.entity-collection {
+ contain: layout style paint;
+ will-change: transform;
+}
+```
+
+#### Efficient CSS Selectors
+```css
+/* FAST: Use class selectors */
+.entity-svg.state-active { fill: #dc3545; }
+
+/* SLOWER: Avoid complex descendant selectors */
+.location-view .entity-group .entity-svg.state-active { fill: #dc3545; }
+
+/* FAST: Specific attribute selectors */
+[data-entity-type="motion_sensor"].state-active { fill: #dc3545; }
+
+/* SLOWER: Universal selectors */
+* .state-active { fill: #dc3545; }
+```
+
+### Network Optimization
+
+#### Intelligent Polling Strategies
+```javascript
+// Adaptive polling based on system load and entity count
+class AdaptiveStatusPoller extends StatusPoller {
+ constructor(options = {}) {
+ super(options);
+ this.baseInterval = options.pollInterval || 5000;
+ this.minInterval = options.minInterval || 1000;
+ this.maxInterval = options.maxInterval || 30000;
+ this.entityCount = 0;
+ this.systemLoad = 0;
+ }
+
+ calculateOptimalInterval() {
+ // Adjust based on entity count
+ let interval = this.baseInterval;
+
+ if (this.entityCount > 100) {
+ interval *= 1.5; // Slower polling for many entities
+ } else if (this.entityCount > 50) {
+ interval *= 1.2;
+ }
+
+ // Adjust based on system performance
+ if (this.systemLoad > 0.8) {
+ interval *= 2; // Much slower when system is loaded
+ } else if (this.systemLoad > 0.6) {
+ interval *= 1.5;
+ }
+
+ return Math.max(this.minInterval, Math.min(this.maxInterval, interval));
+ }
+
+ measureSystemLoad() {
+ // Simple performance measurement
+ const start = performance.now();
+
+ // Simulate work
+ for (let i = 0; i < 1000; i++) {
+ Math.random();
+ }
+
+ const end = performance.now();
+ const expected = 1; // Expected time for the work in ms
+ this.systemLoad = Math.min(1, (end - start) / expected);
+ }
+
+ async poll() {
+ this.measureSystemLoad();
+
+ try {
+ const response = await fetch('/api/status');
+ const statusData = await response.json();
+
+ this.entityCount = Object.keys(statusData.entities || {}).length;
+ this.updateEntityStates(statusData);
+
+ this.errorCount = 0;
+ } catch (error) {
+ console.error('Status polling failed:', error);
+ this.errorCount++;
+ }
+
+ // Use adaptive interval
+ const interval = this.calculateOptimalInterval();
+
+ if (this.isPolling) {
+ setTimeout(() => this.poll(), interval);
+ }
+ }
+}
+```
+
+#### Delta Updates
+```javascript
+// Only send changes since last update
+class DeltaStatusPoller extends StatusPoller {
+ constructor(options = {}) {
+ super(options);
+ this.lastUpdateTimestamp = null;
+ this.entityStates = new Map();
+ }
+
+ async poll() {
+ try {
+ const url = this.lastUpdateTimestamp
+ ? `/api/status?since=${this.lastUpdateTimestamp}`
+ : '/api/status';
+
+ const response = await fetch(url);
+ const statusData = await response.json();
+
+ if (statusData.entities) {
+ this.processDeltas(statusData);
+ this.lastUpdateTimestamp = statusData.timestamp;
+ }
+ } catch (error) {
+ console.error('Delta polling failed:', error);
+ }
+ }
+
+ processDeltas(statusData) {
+ Object.entries(statusData.entities).forEach(([entityId, newState]) => {
+ const currentState = this.entityStates.get(entityId);
+
+ // Only update if state actually changed
+ if (!currentState || this.hasStateChanged(currentState, newState)) {
+ this.updateEntityDisplay(entityId, newState);
+ this.entityStates.set(entityId, newState);
+ }
+ });
+ }
+
+ hasStateChanged(oldState, newState) {
+ return JSON.stringify(oldState.cssClasses) !== JSON.stringify(newState.cssClasses) ||
+ JSON.stringify(oldState.colorScheme) !== JSON.stringify(newState.colorScheme);
+ }
+}
+```
+
+### Large Dataset Handling
+
+#### Pagination and Lazy Loading
+```javascript
+// Handle thousands of entities with pagination
+class PaginatedStatusDisplay {
+ constructor(svgElement, options = {}) {
+ this.svgElement = svgElement;
+ this.pageSize = options.pageSize || 50;
+ this.visiblePages = new Set();
+ this.entityPages = new Map();
+ this.currentViewport = null;
+ }
+
+ paginateEntities() {
+ const entities = this.svgElement.querySelectorAll('[data-entity-id]');
+ const pages = [];
+
+ // Group entities by spatial locality
+ const spatialGroups = this.groupEntitiesSpatially(entities);
+
+ spatialGroups.forEach((group, index) => {
+ const pageId = `page-${index}`;
+ pages.push({
+ id: pageId,
+ entities: group,
+ bounds: this.calculateGroupBounds(group)
+ });
+ });
+
+ return pages;
+ }
+
+ groupEntitiesSpatially(entities) {
+ // Use spatial hashing to group nearby entities
+ const spatialHash = new Map();
+ const cellSize = 100; // SVG units
+
+ Array.from(entities).forEach(entity => {
+ const bbox = entity.getBBox();
+ const cellX = Math.floor(bbox.x / cellSize);
+ const cellY = Math.floor(bbox.y / cellSize);
+ const cellKey = `${cellX},${cellY}`;
+
+ if (!spatialHash.has(cellKey)) {
+ spatialHash.set(cellKey, []);
+ }
+ spatialHash.get(cellKey).push(entity);
+ });
+
+ return Array.from(spatialHash.values());
+ }
+
+ updateVisiblePages(viewBox) {
+ this.currentViewport = viewBox;
+ const pages = this.paginateEntities();
+
+ pages.forEach(page => {
+ const isVisible = this.isPageVisible(page.bounds, viewBox);
+
+ if (isVisible && !this.visiblePages.has(page.id)) {
+ this.loadPage(page);
+ } else if (!isVisible && this.visiblePages.has(page.id)) {
+ this.unloadPage(page);
+ }
+ });
+ }
+
+ isPageVisible(bounds, viewBox) {
+ return !(
+ bounds.right < viewBox.x ||
+ bounds.left > viewBox.x + viewBox.width ||
+ bounds.bottom < viewBox.y ||
+ bounds.top > viewBox.y + viewBox.height
+ );
+ }
+
+ loadPage(page) {
+ // Enable status updates for entities in this page
+ page.entities.forEach(entity => {
+ entity.style.display = 'block';
+ this.enableStatusUpdates(entity);
+ });
+
+ this.visiblePages.add(page.id);
+ }
+
+ unloadPage(page) {
+ // Disable status updates for entities in this page
+ page.entities.forEach(entity => {
+ entity.style.display = 'none';
+ this.disableStatusUpdates(entity);
+ });
+
+ this.visiblePages.delete(page.id);
+ }
+}
+```
+
+### Browser Compatibility Optimization
+
+#### Performance Feature Detection
+```javascript
+// Adapt performance strategies based on browser capabilities
+class BrowserOptimizedStatusPoller extends StatusPoller {
+ constructor(options = {}) {
+ super(options);
+ this.browserCapabilities = this.detectCapabilities();
+ this.adaptToBrowser();
+ }
+
+ detectCapabilities() {
+ return {
+ hasRequestAnimationFrame: typeof requestAnimationFrame !== 'undefined',
+ hasIntersectionObserver: typeof IntersectionObserver !== 'undefined',
+ hasWebGL: this.hasWebGLSupport(),
+ supportsCSSSContainment: CSS.supports('contain', 'layout'),
+ supportsWillChange: CSS.supports('will-change', 'transform'),
+ isLowEndDevice: this.detectLowEndDevice()
+ };
+ }
+
+ hasWebGLSupport() {
+ try {
+ const canvas = document.createElement('canvas');
+ return !!(canvas.getContext('webgl') || canvas.getContext('experimental-webgl'));
+ } catch (e) {
+ return false;
+ }
+ }
+
+ detectLowEndDevice() {
+ // Heuristics for low-end device detection
+ const memoryGB = navigator.deviceMemory || 4;
+ const cores = navigator.hardwareConcurrency || 4;
+ return memoryGB < 2 || cores < 4;
+ }
+
+ adaptToBrowser() {
+ if (this.browserCapabilities.isLowEndDevice) {
+ // Reduce update frequency and batch size
+ this.pollInterval *= 2;
+ this.batchSize = 10;
+ }
+
+ if (!this.browserCapabilities.hasRequestAnimationFrame) {
+ // Fallback to setTimeout for older browsers
+ this.useSetTimeoutForUpdates = true;
+ }
+
+ if (!this.browserCapabilities.supportsCSSSContainment) {
+ // Disable some optimizations that require CSS containment
+ this.disableContainmentOptimizations = true;
+ }
+ }
+}
+```
+
+### Performance Monitoring Integration
+
+#### Real-User Monitoring (RUM)
+```javascript
+// Integration with performance monitoring services
+class MonitoredStatusPoller extends StatusPoller {
+ constructor(options = {}) {
+ super(options);
+ this.performanceMetrics = {
+ updateTimes: [],
+ errorCounts: {},
+ memoryUsage: []
+ };
+ }
+
+ updateEntityDisplay(entityId, stateData) {
+ const start = performance.now();
+
+ try {
+ super.updateEntityDisplay(entityId, stateData);
+
+ const duration = performance.now() - start;
+ this.recordMetric('updateTime', duration);
+
+ } catch (error) {
+ this.recordError('updateDisplay', error);
+ throw error;
+ }
+ }
+
+ recordMetric(type, value) {
+ if (!this.performanceMetrics[type]) {
+ this.performanceMetrics[type] = [];
+ }
+
+ this.performanceMetrics[type].push({
+ value,
+ timestamp: Date.now()
+ });
+
+ // Keep only recent metrics (last 5 minutes)
+ const cutoff = Date.now() - 5 * 60 * 1000;
+ this.performanceMetrics[type] = this.performanceMetrics[type]
+ .filter(metric => metric.timestamp > cutoff);
+ }
+
+ recordError(operation, error) {
+ if (!this.performanceMetrics.errorCounts[operation]) {
+ this.performanceMetrics.errorCounts[operation] = 0;
+ }
+ this.performanceMetrics.errorCounts[operation]++;
+
+ // Send to monitoring service
+ if (typeof gtag !== 'undefined') {
+ gtag('event', 'status_display_error', {
+ operation,
+ error_message: error.message
+ });
+ }
+ }
+
+ getPerformanceReport() {
+ const report = {
+ averageUpdateTime: this.calculateAverage('updateTime'),
+ maxUpdateTime: this.calculateMax('updateTime'),
+ errorRate: this.calculateErrorRate(),
+ memoryTrend: this.calculateMemoryTrend()
+ };
+
+ return report;
+ }
+}
+```
+
+## Overview
+
+The entity status display system provides visual feedback for entity states through dynamic CSS classes, SVG styling, and real-time updates. This document covers the frontend implementation details for displaying entity status visually.
+
+## Visual Display Implementation
+
+Entity visual representation is implemented through three main approaches:
+
+### 1. CSS Class Mapping
+
+The system takes normalized sensor values and applies them as CSS class names to SVG elements. This allows CSS rules to dynamically adjust visual display for well-known sensor values.
+
+```css
+/* Entity state CSS classes */
+.entity-svg.state-active {
+ fill: var(--status-active);
+ fill-opacity: 0.8;
+}
+
+.entity-svg.state-recent {
+ fill: var(--status-recent);
+ fill-opacity: 0.6;
+}
+
+.entity-svg.state-past {
+ fill: var(--status-past);
+ fill-opacity: 0.4;
+}
+
+.entity-svg.state-idle {
+ fill: var(--status-idle);
+ fill-opacity: 0.3;
+}
+
+.entity-svg.state-unknown {
+ fill: var(--status-unknown);
+ fill-opacity: 0.2;
+}
+```
+
+### 2. Predefined Icon Variants
+
+For well-known sensor values, the system can swap between predefined SVG icons to represent different states:
+
+```html
+<!-- Base entity icon -->
+<use href="#icon-motion-sensor-idle" class="entity-icon" />
+
+<!-- Active state icon -->
+<use href="#icon-motion-sensor-active" class="entity-icon" />
+```
+
+### 3. Color Scheme Mapping
+
+The system maps sensor values to color schemes applied via SVG fill, stroke, and opacity attributes. This is predominantly used for area entities (closed SVG paths) to show activity levels.
+
+```javascript
+// Color scheme application
+function applyColorScheme(element, colorData) {
+ element.style.fill = colorData.fillColor;
+ element.style.stroke = colorData.strokeColor;
+ element.style.opacity = colorData.opacity;
+ element.style.strokeWidth = colorData.strokeWidth;
+}
+```
+
+## Status Color System
+
+### Color Variables
+
+Define status colors using CSS custom properties:
+
+```css
+:root {
+ /* Status colors following traffic light metaphor */
+ --status-active: #dc3545; /* Red - Active/Alert */
+ --status-recent: #fd7e14; /* Orange - Recently active */
+ --status-past: #ffc107; /* Yellow - Past activity */
+ --status-idle: #28a745; /* Green - Idle/Safe */
+ --status-unknown: #6c757d; /* Gray - Unknown/Offline */
+}
+```
+
+### Visual State Progression
+
+The value decaying system creates a visual "cooling off" effect through color transitions:
+
+**Color Progression**: Active (red) → Recent (orange) → Past (yellow) → Idle (green/gray)
+
+```css
+/* Smooth transitions between states */
+.entity-svg {
+ transition: fill 0.3s ease, opacity 0.3s ease;
+}
+
+/* State-specific styling with opacity variations */
+.entity-active {
+ fill: var(--status-active);
+ opacity: 1.0;
+}
+.entity-recent {
+ fill: var(--status-recent);
+ opacity: 0.8;
+}
+.entity-past {
+ fill: var(--status-past);
+ opacity: 0.6;
+}
+.entity-idle {
+ fill: var(--status-idle);
+ opacity: 0.4;
+}
+```
+
+## Client-Server Status Updates
+
+### Polling System Implementation
+
+The JavaScript `polling.js` module handles real-time status updates through server polling:
+
+```javascript
+// Status polling implementation
+class StatusPoller {
+ constructor(pollInterval = 5000) {
+ this.pollInterval = pollInterval;
+ this.isPolling = false;
+ }
+
+ start() {
+ if (this.isPolling) return;
+ this.isPolling = true;
+ this.poll();
+ }
+
+ async poll() {
+ try {
+ const response = await fetch('/api/status');
+ const statusData = await response.json();
+ this.updateEntityStates(statusData);
+ } catch (error) {
+ console.error('Status polling failed:', error);
+ }
+
+ if (this.isPolling) {
+ setTimeout(() => this.poll(), this.pollInterval);
+ }
+ }
+
+ updateEntityStates(statusData) {
+ // Update entity visual states based on server response
+ Object.entries(statusData.entities).forEach(([entityId, stateData]) => {
+ this.updateEntityDisplay(entityId, stateData);
+ });
+ }
+
+ updateEntityDisplay(entityId, stateData) {
+ const elements = document.querySelectorAll(`[data-entity-id="${entityId}"]`);
+ elements.forEach(element => {
+ this.applyStatusClasses(element, stateData.cssClasses);
+ this.applyColorScheme(element, stateData.colorScheme);
+ });
+ }
+}
+```
+
+### Server Response Format
+
+The server returns status updates in a standardized JSON format:
+
+```javascript
+{
+ "timestamp": "2025-01-15T10:30:00Z",
+ "entities": {
+ "entity_123": {
+ "cssClasses": ["state-active", "priority-high"],
+ "colorScheme": {
+ "fill": "#dc3545",
+ "stroke": "#b02a37",
+ "opacity": 0.8
+ },
+ "iconVariant": "motion-active"
+ }
+ }
+}
+```
+
+### Element Targeting and Updates
+
+The polling system uses CSS class names and data attributes to target elements:
+
+```javascript
+function applyStatusClasses(element, cssClasses) {
+ // Remove existing state classes
+ element.classList.remove(...element.classList);
+
+ // Apply new state classes
+ element.classList.add(...cssClasses);
+}
+
+function applyColorScheme(element, colorScheme) {
+ if (element.tagName === 'path' || element.tagName === 'g') {
+ // SVG element styling
+ element.style.fill = colorScheme.fill;
+ element.style.stroke = colorScheme.stroke;
+ element.style.opacity = colorScheme.opacity;
+ } else if (element.tagName === 'div') {
+ // HTML element styling for non-SVG displays
+ element.style.backgroundColor = colorScheme.fill;
+ element.style.borderColor = colorScheme.stroke;
+ element.style.opacity = colorScheme.opacity;
+ }
+}
+```
+
+## SVG Element Handling
+
+### SVG Path and Group Elements
+
+Standard handling for SVG `g` and `path` tags:
+
+```html
+<g class="entity-group" data-entity-id="123">
+ <path class="entity-svg state-idle" d="M10,10 L50,10 L50,50 L10,50 Z"/>
+</g>
+```
+
+```javascript
+// SVG-specific styling
+function styleSvgElement(element, stateData) {
+ element.setAttribute('class', `entity-svg ${stateData.cssClasses.join(' ')}`);
+ element.style.fill = stateData.colorScheme.fill;
+ element.style.stroke = stateData.colorScheme.stroke;
+}
+```
+
+### Special Case Handling
+
+#### Select Tags (Controllers)
+
+Special handling for controller select elements:
+
+```javascript
+function updateControllerSelect(selectElement, stateData) {
+ // Update select styling to reflect entity state
+ selectElement.className = `form-control ${stateData.cssClasses.join(' ')}`;
+
+ // Update associated label or indicator
+ const indicator = selectElement.nextElementSibling;
+ if (indicator && indicator.classList.contains('status-indicator')) {
+ indicator.style.backgroundColor = stateData.colorScheme.fill;
+ }
+}
+```
+
+#### DIV Elements (Non-SVG Display)
+
+For entity status in Collection Views or status modals:
+
+```html
+<div class="entity-status-card" data-entity-id="123">
+ <div class="status-indicator"></div>
+ <span class="entity-name">Motion Sensor</span>
+</div>
+```
+
+```javascript
+function updateStatusCard(cardElement, stateData) {
+ const indicator = cardElement.querySelector('.status-indicator');
+ indicator.className = `status-indicator ${stateData.cssClasses.join(' ')}`;
+ indicator.style.backgroundColor = stateData.colorScheme.fill;
+}
+```
+
+## Template Integration
+
+### Django Template Setup
+
+Templates must include proper class names and data attributes:
+
+```django
+<!-- SVG entity representation -->
+<g class="entity-group" data-entity-id="{{ entity.id }}">
+ <path class="entity-svg {{ entity.get_status_css_classes }}"
+ d="{{ entity.get_svg_path }}"
+ style="fill: {{ entity.get_status_color }}"/>
+</g>
+
+<!-- Non-SVG entity representation -->
+<div class="entity-card" data-entity-id="{{ entity.id }}">
+ <div class="status-indicator {{ entity.get_status_css_classes }}"
+ style="background-color: {{ entity.get_status_color }}"></div>
+ <span class="entity-name">{{ entity.name }}</span>
+</div>
+```
+
+### Template Context Requirements
+
+Views must provide status data in the context:
+
+```python
+# In Django view
+context = {
+ 'entity': entity,
+ 'status_classes': entity.get_status_css_classes(),
+ 'status_color': entity.get_status_color(),
+ 'status_data': entity.get_status_display_data(),
+}
+```
+
+## Performance Considerations
+
+### Efficient DOM Updates
+
+Minimize DOM manipulation for better performance:
+
+```javascript
+// Batch DOM updates
+function batchUpdateEntities(statusUpdates) {
+ // Use DocumentFragment for batch updates
+ const fragment = document.createDocumentFragment();
+
+ statusUpdates.forEach(update => {
+ const element = document.querySelector(`[data-entity-id="${update.entityId}"]`);
+ if (element) {
+ // Apply updates without triggering reflow
+ requestAnimationFrame(() => {
+ this.applyStatusUpdate(element, update.stateData);
+ });
+ }
+ });
+}
+```
+
+### CSS Animation Optimization
+
+Use transform and opacity for smooth animations:
+
+```css
+.entity-svg {
+ transition: opacity 0.3s ease, transform 0.3s ease;
+ /* Avoid animating expensive properties like width, height, color */
+}
+
+.entity-svg.state-transition {
+ transform: scale(1.1);
+ opacity: 0.9;
+}
+```
+
+## Troubleshooting
+
+### Status Colors Not Updating
+
+**Symptoms**: Entity colors remain static, don't reflect current state
+**Root Causes & Solutions**:
+
+1. **CSS Classes Not Applied**
+ ```bash
+ # Check browser dev tools - Elements tab
+ # Look for data-entity-id attribute and CSS classes
+ ```
+ - **Fix**: Ensure `StatusPoller.applyStatusClasses()` is called
+ - **Verify**: Check `element.classList` contains expected state classes
+
+2. **CSS Variables Not Defined**
+ ```css
+ /* Verify these exist in your CSS */
+ :root {
+ --status-active: #dc3545;
+ --status-recent: #fd7e14;
+ /* ... other status colors */
+ }
+ ```
+ - **Fix**: Add missing CSS custom properties
+ - **Test**: Use browser dev tools to verify computed styles
+
+3. **CSS Selectors Too Specific**
+ ```css
+ /* BAD - too specific, won't be overridden */
+ .location-view .entity-svg.state-active { fill: red !important; }
+
+ /* GOOD - proper specificity */
+ .entity-svg.state-active { fill: var(--status-active); }
+ ```
+
+### Polling System Not Working
+
+**Symptoms**: Status never updates, even when backend state changes
+**Diagnostic Steps**:
+
+1. **Check Network Tab**
+ ```bash
+ # Browser Dev Tools → Network Tab
+ # Look for periodic /api/status requests
+ # Should see requests every 5 seconds (default)
+ ```
+
+2. **Verify StatusPoller Initialization**
+ ```javascript
+ // Check browser console for errors
+ console.log('StatusPoller initialized:', window.statusPoller);
+
+ // Manually test polling
+ if (window.statusPoller) {
+ window.statusPoller.poll();
+ }
+ ```
+
+3. **Check Server Response**
+ ```bash
+ # Manually test the endpoint
+ curl http://localhost:8411/api/status
+
+ # Should return JSON with entities object
+ ```
+
+**Common Fixes**:
+- **StatusPoller not started**: Call `statusPoller.start()` in DOMContentLoaded
+- **URL incorrect**: Verify `/api/status` endpoint exists and returns valid JSON
+- **JavaScript errors**: Check browser console for exceptions stopping polling
+
+### SVG Elements Not Styling
+
+**Symptoms**: SVG paths/groups don't change appearance with status updates
+**Diagnostic Approach**:
+
+1. **Verify Element Selection**
+ ```javascript
+ // Test in browser console
+ const elements = document.querySelectorAll('[data-entity-id="123"]');
+ console.log('Found elements:', elements.length);
+ ```
+
+2. **Check SVG Structure**
+ ```html
+ <!-- Required structure -->
+ <g class="entity-group" data-entity-id="123">
+ <path class="entity-svg state-idle" d="..."/>
+ </g>
+ ```
+
+3. **Test CSS Application**
+ ```javascript
+ // Manually apply CSS class
+ element.classList.add('state-active');
+ // Should see visual change immediately
+ ```
+
+**Solutions**:
+- **Missing data-entity-id**: Add to parent group or path element
+- **Wrong element type**: Use proper selectors for `g` vs `path` elements
+- **CSS inheritance issues**: Check if parent elements are blocking style inheritance
+
+### Template Integration Issues
+
+**Symptoms**: New entity templates don't show status updates
+**Checklist**:
+
+1. **Required Attributes**
+ ```django
+ <!-- MUST have data-entity-id -->
+ <g data-entity-id="{{ entity.id }}">
+ <!-- MUST have status CSS classes -->
+ <path class="entity-svg {{ entity.get_status_css_classes }}">
+ </g>
+ ```
+
+2. **Context Data**
+ ```python
+ # View must provide status data
+ context = {
+ 'entity': entity,
+ 'status_classes': entity.get_status_css_classes(),
+ 'status_color': entity.get_status_color(),
+ }
+ ```
+
+3. **Template Includes**
+ ```django
+ <!-- Ensure polling.js is loaded -->
+ {% load static %}
+ <script src="{% static 'js/polling.js' %}"></script>
+ ```
+
+### Performance Issues
+
+**Symptoms**: Slow status updates, browser lag with many entities
+**Solutions**:
+
+1. **Throttle DOM Updates**
+ ```javascript
+ // Use requestAnimationFrame for smooth updates
+ requestAnimationFrame(() => {
+ this.applyStatusUpdate(element, statusData);
+ });
+ ```
+
+2. **Batch Updates**
+ ```javascript
+ // Process all status updates in single pass
+ Object.entries(statusData.entities).forEach(([entityId, data]) => {
+ this.scheduleUpdate(entityId, data);
+ });
+ ```
+
+3. **Reduce Polling Frequency**
+ ```javascript
+ // Increase interval for non-critical entities
+ const statusPoller = new StatusPoller(10000); // 10 seconds
+ ```
+
+### Browser Compatibility Issues
+
+**Symptoms**: Status display works in some browsers but not others
+**Common Issues**:
+
+1. **CSS Custom Properties (IE/Edge)**
+ ```css
+ /* Fallback for older browsers */
+ .entity-svg.state-active {
+ fill: #dc3545; /* fallback */
+ fill: var(--status-active, #dc3545);
+ }
+ ```
+
+2. **SVG Styling (Safari)**
+ ```css
+ /* Safari sometimes needs explicit SVG styling */
+ .entity-svg {
+ -webkit-transform: translateZ(0); /* Force hardware acceleration */
+ }
+ ```
+
+3. **Fetch API (IE)**
+ ```javascript
+ // Use polyfill or XMLHttpRequest for IE support
+ if (!window.fetch) {
+ // Load fetch polyfill or use XMLHttpRequest
+ }
+ ```
+
+## Related Documentation
+- Status calculation logic: [Domain Guidelines](../domain/domain-guidelines.md#status-display-system)
+- Style guidelines: [Style Guidelines](style-guidelines.md)
+- Template conventions: [Template Conventions](template-conventions.md)
+- Frontend patterns: [Frontend Guidelines](frontend-guidelines.md)
\ No newline at end of file
diff --git a/docs/dev/frontend/entity-visual-configuration.md b/docs/dev/frontend/entity-visual-configuration.md
new file mode 100644
index 00000000..a42427ea
--- /dev/null
+++ b/docs/dev/frontend/entity-visual-configuration.md
@@ -0,0 +1,2149 @@
+# Entity Visual Configuration
+
+## Quick Reference
+
+### Common Tasks
+- **Add new entity icon** → [Create SVG asset](#create-svg-icon-asset) → Register in `EntityTypesWithIcons`
+- **Add new entity path** → [Configure path type](#choose-path-type) → Add to `EntityTypeClosedPaths` or `EntityTypeOpenPaths`
+- **Fix icon not showing** → [Check registration](#register-icon-configuration) → Verify enum and icon file match
+- **Change entity colors** → [Update style classes](#define-visual-style) → Modify `SvgStatusStyle` properties
+- **Test new entity type** → [Visual testing](#testing-visual-configuration) → Create test entity and verify display
+
+### Key Configuration Files
+- **Icons**: `hi/apps/entity/templates/entity/svg/type.{TYPE}.svg`
+- **Registration**: `hi.hi_styles.EntityStyle.EntityTypesWithIcons`
+- **Path Types**: `hi.hi_styles.EntityStyle.EntityTypeClosedPaths/EntityTypeOpenPaths`
+- **Styling**: `hi.hi_styles.EntityStyle.PathEntityTypeToSvgStatusStyle`
+
+### Quick Fixes
+| Problem | Solution | Location |
+|---------|----------|----------|
+| Icon not displaying | Check file name matches enum | [Create SVG Asset](#create-svg-icon-asset) |
+| Wrong icon size | Verify viewbox registration | [Custom Viewbox](#register-icon-configuration) |
+| Path not styling | Check style class assignment | [Define Visual Style](#define-visual-style) |
+| Entity not clickable | Add `hi-entity-bg` rectangle | [SVG Icon Requirements](#create-svg-icon-asset) |
+
+### Entity Type Decision Tree
+```
+New Entity Type
+├── Point-like (sensor, device) → Use Icon
+│ ├── Create SVG file: type.{enum_name}.svg
+│ └── Register in EntityTypesWithIcons
+└── Area-like (room, zone) → Use Path
+ ├── Closed shape → Add to EntityTypeClosedPaths
+ └── Open line → Add to EntityTypeOpenPaths
+```
+
+
+## Real-World Workflow Examples
+
+### Workflow 1: Adding a New Entity Type with Custom Icon
+
+**Scenario**: Add support for a "Smart Door Lock" entity type with a custom icon and status colors.
+
+**Complete Implementation Process:**
+
+1. **Domain Setup** (Cross-reference: [Entity Patterns](../domain/entity-patterns.md))
+ ```python
+ # Add to hi.apps.entity.enums.EntityType
+ class EntityType(Enum):
+ # ... existing types
+ SMART_DOOR_LOCK = ("smart_door_lock", "Smart Door Lock")
+
+ # Add to appropriate group
+ class EntityGroupType(Enum):
+ SECURITY_DEVICES = "security_devices"
+ # Add SMART_DOOR_LOCK to this group
+ ```
+
+2. **Create Custom SVG Icon** ([Create SVG Icon Asset](#create-svg-icon-asset))
+ ```xml
+ <!-- File: hi/apps/entity/templates/entity/svg/type.smart_door_lock.svg -->
+ <rect class="hi-entity-bg" x="0" y="0" width="64" height="64" fill="none"/>
+ <!-- Door outline -->
+ <rect x="20" y="10" width="24" height="44" fill="none" stroke="currentColor" stroke-width="2"/>
+ <!-- Lock mechanism -->
+ <circle cx="32" cy="32" r="6" fill="currentColor"/>
+ <!-- Key hole -->
+ <circle cx="32" cy="32" r="2" fill="white"/>
+ <!-- Status indicator (will change color based on state) -->
+ <circle cx="45" cy="15" r="4" fill="currentColor" opacity="0.8"/>
+ ```
+
+3. **Register Icon Type** ([Register Icon Configuration](#register-icon-configuration))
+ ```python
+ # In hi.hi_styles.EntityStyle.EntityTypesWithIcons
+ EntityTypesWithIcons = {
+ EntityType.MOTION_SENSOR,
+ EntityType.DOOR_SENSOR,
+ EntityType.SMART_DOOR_LOCK, # Add this line
+ # ... existing types
+ }
+ ```
+
+4. **Define Status-Specific Styling** ([Status Colors](../entity-status-display.md#status-color-system))
+ ```css
+ /* Add to your CSS file */
+ .entity-svg.door-lock-locked {
+ fill: var(--status-idle); /* Green - secure */
+ stroke: #006600;
+ }
+
+ .entity-svg.door-lock-unlocked {
+ fill: var(--status-recent); /* Orange - caution */
+ stroke: #cc6600;
+ }
+
+ .entity-svg.door-lock-jammed {
+ fill: var(--status-active); /* Red - problem */
+ stroke: #cc0000;
+ }
+
+ .entity-svg.door-lock-offline {
+ fill: var(--status-unknown); /* Gray - unknown */
+ stroke: #666666;
+ }
+ ```
+
+5. **Test Visual Configuration** ([Testing Visual Configuration](#testing-visual-configuration))
+ ```python
+ # Create test entity
+ test_door_lock = Entity.objects.create(
+ name="Front Door Lock",
+ entity_type=EntityType.SMART_DOOR_LOCK,
+ location=test_location
+ )
+
+ # Create EntityPosition for icon display
+ EntityPosition.objects.create(
+ entity=test_door_lock,
+ x=100, y=150,
+ scale=1.0, rotation=0
+ )
+ ```
+
+6. **Verify in Location View**
+ - Navigate to location view containing the door lock
+ - Verify icon displays correctly
+ - Test status changes trigger color updates
+ - Check click interactions work (clickable background)
+
+**Expected Result**: Smart door lock appears as custom icon with status-based color changes.
+
+---
+
+### Workflow 2: Converting Icon Entity to Path Entity
+
+**Scenario**: Motion sensor needs to represent a coverage area rather than just a point location.
+
+**Migration Process:**
+
+1. **Plan Path Representation** ([Entity Display Methods](#entity-display-methods))
+ ```python
+ # Motion sensor coverage area as circular path
+ # Center: sensor position
+ # Radius: detection range
+ coverage_radius = 50 # units in SVG coordinates
+ center_x, center_y = 200, 300
+ ```
+
+2. **Remove from Icon Registry** ([Icon Configuration](#register-icon-configuration))
+ ```python
+ # Remove from hi.hi_styles.EntityStyle.EntityTypesWithIcons
+ EntityTypesWithIcons = {
+ # EntityType.MOTION_SENSOR, # Comment out or remove
+ EntityType.DOOR_SENSOR,
+ # ... other types
+ }
+ ```
+
+3. **Add to Path Registry** ([Path-Based Configuration](#path-based-entity-configuration))
+ ```python
+ # Add to hi.hi_styles.EntityStyle.EntityTypeClosedPaths
+ EntityTypeClosedPaths = {
+ EntityType.ROOM,
+ EntityType.MOTION_SENSOR, # Add this line
+ # ... existing types
+ }
+ ```
+
+4. **Create SVG Path Data** ([SVG Path Requirements](#path-based-entity-configuration))
+ ```python
+ import math
+
+ def create_circular_path(center_x, center_y, radius):
+ """Create SVG path for circular coverage area"""
+ # Create circle using path commands (more flexible than <circle>)
+ path_data = (
+ f"M {center_x - radius} {center_y} "
+ f"A {radius} {radius} 0 0 1 {center_x + radius} {center_y} "
+ f"A {radius} {radius} 0 0 1 {center_x - radius} {center_y} "
+ f"Z"
+ )
+ return path_data
+
+ # Update existing motion sensor entities
+ for motion_sensor in Entity.objects.filter(entity_type=EntityType.MOTION_SENSOR):
+ # Get current position
+ position = motion_sensor.entityposition_set.first()
+ if position:
+ # Create EntityPath with coverage area
+ EntityPath.objects.create(
+ entity=motion_sensor,
+ svg_path=create_circular_path(position.x, position.y, 50)
+ )
+ # Remove EntityPosition
+ position.delete()
+ ```
+
+5. **Define Path Styling** ([Define Visual Style](#define-visual-style))
+ ```python
+ # Create new style class in hi.hi_styles.EntityStyle
+ class MotionSensorPathStyle:
+ default_fill = "#E0E0E0"
+ default_stroke = "#808080"
+ default_opacity = 0.3
+
+ active_fill = "#FF4444"
+ active_stroke = "#CC0000"
+ active_opacity = 0.6
+
+ recent_fill = "#FF8844"
+ recent_stroke = "#CC4400"
+ recent_opacity = 0.5
+
+ idle_fill = "#44FF44"
+ idle_stroke = "#00CC00"
+ idle_opacity = 0.3
+
+ # Register the style
+ PathEntityTypeToSvgStatusStyle = {
+ EntityType.MOTION_SENSOR: MotionSensorPathStyle,
+ # ... existing mappings
+ }
+ ```
+
+6. **Update Templates** (Cross-reference: [Template Integration](#template-integration))
+ ```django
+ <!-- Motion sensors now render as paths instead of icons -->
+ {% for entity in entities %}
+ {% if entity.entity_type.name == 'MOTION_SENSOR' %}
+ <path class="entity-path {{ entity.get_status_css_classes }}"
+ data-entity-id="{{ entity.id }}"
+ d="{{ entity.path.svg_path }}"
+ style="{{ entity.get_path_styling }}"/>
+ {% elif entity.has_position %}
+ <!-- Other icon entities -->
+ <use href="#icon-{{ entity.entity_type.name.lower }}"/>
+ {% endif %}
+ {% endfor %}
+ ```
+
+**Expected Result**: Motion sensors display as coverage areas that show detection zones rather than point icons.
+
+---
+
+### Workflow 3: Troubleshooting Icon Registration Issues
+
+**Scenario**: New entity type icon was created and registered, but still shows as placeholder or missing.
+
+**Systematic Debugging:**
+
+1. **Verify File Path and Naming** ([Troubleshooting - Icon Not Displaying](#entity-icon-not-displaying))
+ ```bash
+ # Check exact file path and naming
+ ls hi/apps/entity/templates/entity/svg/type.smart_door_lock.svg
+
+ # Verify enum name matches file name
+ # EntityType.SMART_DOOR_LOCK → type.smart_door_lock.svg
+ ```
+
+2. **Check Registration** ([Icon Registration](#register-icon-configuration))
+ ```python
+ # Verify in hi.hi_styles.EntityStyle.EntityTypesWithIcons
+ print(EntityType.SMART_DOOR_LOCK in EntityStyle.EntityTypesWithIcons)
+ # Should print: True
+ ```
+
+3. **Validate SVG Content** ([SVG Icon Requirements](#create-svg-icon-asset))
+ ```xml
+ <!-- Check file content structure -->
+ <!-- GOOD: No <svg> wrapper, has clickable background -->
+ <rect class="hi-entity-bg" x="0" y="0" width="64" height="64" fill="none"/>
+ <circle cx="32" cy="32" r="20" fill="currentColor"/>
+
+ <!-- BAD: Has <svg> wrapper -->
+ <svg viewBox="0 0 64 64">
+ <circle cx="32" cy="32" r="20" fill="currentColor"/>
+ </svg>
+ ```
+
+4. **Check Template Symbol Generation** ([Template Integration](#template-integration))
+ ```django
+ <!-- Verify symbol is generated in template -->
+ <defs>
+ {% for entity_type in entity_types_with_icons %}
+ <symbol id="icon-{{ entity_type.name.lower }}" viewBox="{{ entity_type.get_viewbox }}">
+ {% include entity_type.get_icon_template %}
+ </symbol>
+ {% endfor %}
+ </defs>
+
+ <!-- Check in browser dev tools if symbol exists -->
+ <!-- Should find: <symbol id="icon-smart_door_lock"> -->
+ ```
+
+5. **Test Direct Icon Usage** ([Testing](#testing-visual-configuration))
+ ```html
+ <!-- Test icon directly in browser console -->
+ <script>
+ // Check if symbol exists
+ const symbol = document.querySelector('#icon-smart_door_lock');
+ console.log('Symbol found:', symbol);
+
+ // Test manual icon usage
+ const testIcon = document.createElementNS('http://www.w3.org/2000/svg', 'use');
+ testIcon.setAttribute('href', '#icon-smart_door_lock');
+ testIcon.setAttribute('class', 'entity-svg');
+ document.querySelector('svg').appendChild(testIcon);
+ </script>
+ ```
+
+6. **Check ViewBox Issues** ([Custom ViewBox](#register-icon-configuration))
+ ```python
+ # If icon appears but wrong size, check viewbox
+ # Add custom viewbox if needed
+ EntityTypeToIconViewbox = {
+ EntityType.SMART_DOOR_LOCK: "0 0 80 80", # If icon designed differently
+ }
+ ```
+
+**Common Resolutions**:
+- File name doesn't match enum (case sensitivity)
+- SVG has `<svg>` wrapper (remove it)
+- Missing clickable background rectangle
+- Not registered in `EntityTypesWithIcons`
+
+---
+
+### Workflow 4: Creating Entity Type Family with Consistent Styling
+
+**Scenario**: Create multiple related security device types (door lock, window sensor, security camera) with consistent visual styling.
+
+**Coordinated Implementation:**
+
+1. **Design Visual Family** ([Visual Asset Guidelines](#visual-asset-guidelines))
+ ```css
+ /* Define consistent family styling */
+ .security-device {
+ stroke-width: 2;
+ stroke: #333333;
+ }
+
+ .security-device.state-secure {
+ fill: #28a745; /* Green family */
+ }
+
+ .security-device.state-alert {
+ fill: #dc3545; /* Red family */
+ }
+
+ .security-device.state-warning {
+ fill: #ffc107; /* Yellow family */
+ }
+ ```
+
+2. **Create Icon Family** ([SVG Icon Standards](#visual-asset-guidelines))
+ ```xml
+ <!-- Common 64x64 viewbox, similar design elements -->
+
+ <!-- type.door_lock.svg -->
+ <rect class="hi-entity-bg" x="0" y="0" width="64" height="64" fill="none"/>
+ <rect x="20" y="15" width="24" height="34" fill="none" stroke="currentColor" stroke-width="2"/>
+ <circle cx="32" cy="32" r="4" fill="currentColor"/>
+
+ <!-- type.window_sensor.svg -->
+ <rect class="hi-entity-bg" x="0" y="0" width="64" height="64" fill="none"/>
+ <rect x="15" y="20" width="34" height="24" fill="none" stroke="currentColor" stroke-width="2"/>
+ <rect x="18" y="23" width="28" height="18" fill="currentColor" opacity="0.3"/>
+
+ <!-- type.security_camera.svg -->
+ <rect class="hi-entity-bg" x="0" y="0" width="64" height="64" fill="none"/>
+ <rect x="20" y="25" width="24" height="16" rx="4" fill="currentColor"/>
+ <circle cx="44" cy="33" r="8" fill="none" stroke="currentColor" stroke-width="2"/>
+ ```
+
+3. **Register All Types** ([Batch Registration](#register-icon-configuration))
+ ```python
+ # Add all security devices to icons
+ EntityTypesWithIcons = {
+ # ... existing types
+ EntityType.DOOR_LOCK,
+ EntityType.WINDOW_SENSOR,
+ EntityType.SECURITY_CAMERA,
+ # ... other types
+ }
+ ```
+
+4. **Apply Family CSS Classes** ([CSS Class Application](../entity-status-display.md#css-class-mapping))
+ ```python
+ # In status calculation logic
+ def get_security_device_classes(entity):
+ base_classes = ['security-device']
+
+ if entity.entity_type in [EntityType.DOOR_LOCK, EntityType.WINDOW_SENSOR]:
+ state = entity.get_current_state('security_state')
+ if state and state.value == 'secure':
+ base_classes.append('state-secure')
+ elif state and state.value == 'breached':
+ base_classes.append('state-alert')
+ else:
+ base_classes.append('state-warning')
+
+ return base_classes
+ ```
+
+5. **Test Family Consistency** ([Visual Testing](#testing-visual-configuration))
+ ```python
+ # Create test entities for all family members
+ security_devices = [
+ ('Front Door Lock', EntityType.DOOR_LOCK),
+ ('Living Room Window', EntityType.WINDOW_SENSOR),
+ ('Driveway Camera', EntityType.SECURITY_CAMERA),
+ ]
+
+ for name, entity_type in security_devices:
+ test_entity = Entity.objects.create(
+ name=name,
+ entity_type=entity_type,
+ location=test_location
+ )
+ # Test all status states for visual consistency
+ ```
+
+**Expected Result**: All security devices have cohesive visual design with consistent status colors and styling patterns.
+
+## Common Patterns Library
+
+### Standard Entity Icon Templates
+
+#### Basic Icon SVG Structure
+```xml
+<!-- Standard template for entity type icons -->
+<!-- File: hi/apps/entity/templates/entity/svg/type.{TYPE_NAME}.svg -->
+<rect class="hi-entity-bg" x="0" y="0" width="64" height="64" fill="none"/>
+<!-- Entity-specific icon content here -->
+<circle cx="32" cy="32" r="20" fill="currentColor"/>
+<!-- Optional status indicator -->
+<circle cx="50" cy="14" r="6" fill="currentColor" opacity="0.8"/>
+```
+
+#### Icon Family Consistency Pattern
+```xml
+<!-- Motion sensor icon -->
+<rect class="hi-entity-bg" x="0" y="0" width="64" height="64" fill="none"/>
+<circle cx="32" cy="32" r="18" fill="currentColor"/>
+<path d="M20,32 L32,20 L44,32 L32,44 Z" fill="white" opacity="0.8"/>
+
+<!-- Door sensor icon -->
+<rect class="hi-entity-bg" x="0" y="0" width="64" height="64" fill="none"/>
+<rect x="22" y="16" width="20" height="32" fill="none" stroke="currentColor" stroke-width="2"/>
+<circle cx="36" cy="32" r="3" fill="currentColor"/>
+
+<!-- Window sensor icon -->
+<rect class="hi-entity-bg" x="0" y="0" width="64" height="64" fill="none"/>
+<rect x="16" y="22" width="32" height="20" fill="none" stroke="currentColor" stroke-width="2"/>
+<rect x="19" y="25" width="26" height="14" fill="currentColor" opacity="0.3"/>
+```
+
+#### Status-Aware Icon Variants
+```xml
+<!-- Base thermostat icon -->
+<rect class="hi-entity-bg" x="0" y="0" width="64" height="64" fill="none"/>
+<circle cx="32" cy="32" r="20" fill="none" stroke="currentColor" stroke-width="3"/>
+<circle cx="32" cy="32" r="12" fill="currentColor"/>
+<!-- Temperature display area -->
+<text x="32" y="36" text-anchor="middle" fill="white" font-size="8">72°</text>
+
+<!-- Heating indicator (conditional element) -->
+<g class="heating-indicator">
+ <path d="M32,15 L35,20 L29,20 Z" fill="#ff4444"/>
+</g>
+
+<!-- Cooling indicator (conditional element) -->
+<g class="cooling-indicator">
+ <path d="M32,49 L35,44 L29,44 Z" fill="#4444ff"/>
+</g>
+```
+
+### Standard Entity Configuration Patterns
+
+#### Icon Registration Pattern
+```python
+# Standard pattern for registering icon entity types
+# In hi.hi_styles.EntityStyle
+
+EntityTypesWithIcons = {
+ # Security devices family
+ EntityType.MOTION_SENSOR,
+ EntityType.DOOR_SENSOR,
+ EntityType.WINDOW_SENSOR,
+ EntityType.SECURITY_CAMERA,
+
+ # Climate control family
+ EntityType.TEMPERATURE_SENSOR,
+ EntityType.THERMOSTAT,
+ EntityType.HUMIDITY_SENSOR,
+
+ # Lighting family
+ EntityType.LIGHT_SWITCH,
+ EntityType.DIMMER_SWITCH,
+ EntityType.SMART_BULB,
+
+ # Add new entity types here following family grouping
+}
+
+# Custom viewboxes for non-standard icons
+EntityTypeToIconViewbox = {
+ EntityType.WIDE_SENSOR: "0 0 100 50", # Wide rectangular sensor
+ EntityType.TALL_SENSOR: "0 0 40 80", # Tall vertical sensor
+ EntityType.DETAILED_CAMERA: "0 0 80 60", # More detailed camera icon
+}
+```
+
+#### Path Registration Pattern
+```python
+# Standard pattern for registering path entity types
+# In hi.hi_styles.EntityStyle
+
+# Closed paths (filled areas)
+EntityTypeClosedPaths = {
+ # Room and zone types
+ EntityType.ROOM,
+ EntityType.ZONE,
+ EntityType.COVERAGE_AREA,
+
+ # Detection/sensor coverage areas
+ EntityType.MOTION_DETECTION_ZONE,
+ EntityType.SECURITY_PERIMETER,
+
+ # Add new area-based entity types here
+}
+
+# Open paths (lines and curves)
+EntityTypeOpenPaths = {
+ # Boundary and connection types
+ EntityType.BOUNDARY_LINE,
+ EntityType.CORRIDOR,
+ EntityType.FENCE_LINE,
+
+ # Connection paths
+ EntityType.CABLE_RUN,
+ EntityType.PIPE_LINE,
+
+ # Add new line-based entity types here
+}
+```
+
+#### Visual Style Mapping Pattern
+```python
+# Standard pattern for mapping entity types to visual styles
+# In hi.hi_styles.EntityStyle
+
+PathEntityTypeToSvgStatusStyle = {
+ # Security areas
+ EntityType.SECURITY_PERIMETER: SecurityPerimeterStyle,
+ EntityType.MOTION_DETECTION_ZONE: MotionZoneStyle,
+
+ # Climate zones
+ EntityType.HVAC_ZONE: HvacZoneStyle,
+ EntityType.TEMPERATURE_ZONE: TemperatureZoneStyle,
+
+ # Room types
+ EntityType.ROOM: RoomStyle,
+ EntityType.BATHROOM: BathroomStyle,
+ EntityType.BEDROOM: BedroomStyle,
+}
+
+# Standard size overrides
+EntityTypePathInitialRadius = {
+ EntityType.SMALL_SENSOR_COVERAGE: 15.0,
+ EntityType.ROOM: 30.0,
+ EntityType.LARGE_DETECTION_ZONE: 50.0,
+}
+```
+
+### Standard Visual Style Classes
+
+#### Basic SVG Status Style Template
+```python
+# Standard template for SVG status style classes
+class StandardSvgStatusStyle:
+ """Base template for entity visual styling"""
+
+ # Default styling (idle/unknown state)
+ default_fill = "#E0E0E0"
+ default_stroke = "#808080"
+ default_stroke_width = "2"
+ default_opacity = "0.6"
+
+ # Active state styling
+ active_fill = "#DC3545"
+ active_stroke = "#B02A37"
+ active_stroke_width = "3"
+ active_opacity = "0.9"
+
+ # Recent activity styling
+ recent_fill = "#FD7E14"
+ recent_stroke = "#CC6200"
+ recent_stroke_width = "2"
+ recent_opacity = "0.7"
+
+ # Past activity styling
+ past_fill = "#FFC107"
+ past_stroke = "#CC9A00"
+ past_stroke_width = "2"
+ past_opacity = "0.5"
+
+ # Idle/safe state styling
+ idle_fill = "#28A745"
+ idle_stroke = "#1E7E34"
+ idle_stroke_width = "2"
+ idle_opacity = "0.4"
+
+# Security-specific styling
+class SecurityDeviceStyle(StandardSvgStatusStyle):
+ """Visual styling for security devices"""
+
+ # Override for security-specific colors
+ active_fill = "#FF0000" # Bright red for security alerts
+ active_opacity = "1.0" # Full opacity for alerts
+
+ idle_fill = "#00AA00" # Green for secure state
+ idle_opacity = "0.6"
+
+# Climate-specific styling
+class ClimateDeviceStyle(StandardSvgStatusStyle):
+ """Visual styling for climate control devices"""
+
+ # Climate-specific state colors
+ heating_fill = "#FF4444"
+ heating_stroke = "#CC0000"
+
+ cooling_fill = "#4444FF"
+ cooling_stroke = "#0000CC"
+
+ idle_fill = "#44AA44" # Green for idle HVAC
+```
+
+### Standard Template Integration Patterns
+
+#### Icon Entity Template Pattern
+```django
+<!-- Standard template for icon-based entities in location views -->
+<defs>
+ {% for entity_type in entity_types_with_icons %}
+ <symbol id="icon-{{ entity_type.name.lower }}"
+ viewBox="{{ entity_type.get_viewbox }}">
+ {% include entity_type.get_icon_template %}
+ </symbol>
+ {% endfor %}
+</defs>
+
+<!-- Entity rendering loop -->
+{% for entity in positioned_entities %}
+ <g class="entity-group" data-entity-id="{{ entity.id }}"
+ data-entity-type="{{ entity.entity_type.name.lower }}">
+ <use href="#icon-{{ entity.entity_type.name.lower }}"
+ class="entity-svg {{ entity.get_status_css_classes|join:' ' }}"
+ transform="translate({{ entity.position.x }}, {{ entity.position.y }})
+ scale({{ entity.position.scale|default:1.0 }})
+ rotate({{ entity.position.rotation|default:0 }})"/>
+ <!-- Optional entity label -->
+ {% if entity.show_label %}
+ <text x="{{ entity.position.x }}"
+ y="{{ entity.position.y|add:25 }}"
+ class="entity-label">{{ entity.name }}</text>
+ {% endif %}
+ </g>
+{% endfor %}
+```
+
+#### Path Entity Template Pattern
+```django
+<!-- Standard template for path-based entities -->
+{% for entity in path_entities %}
+ <g class="entity-group" data-entity-id="{{ entity.id }}"
+ data-entity-type="{{ entity.entity_type.name.lower }}">
+ <path class="entity-path {{ entity.get_status_css_classes|join:' ' }}"
+ d="{{ entity.path.svg_path }}"
+ style="fill: {{ entity.get_status_fill }};
+ stroke: {{ entity.get_status_stroke }};
+ stroke-width: {{ entity.get_status_stroke_width }};
+ opacity: {{ entity.get_status_opacity }}"/>
+ <!-- Optional path label at centroid -->
+ {% if entity.show_label %}
+ <text x="{{ entity.path.centroid_x }}"
+ y="{{ entity.path.centroid_y }}"
+ class="entity-label path-label">{{ entity.name }}</text>
+ {% endif %}
+ </g>
+{% endfor %}
+```
+
+#### Entity Collection Template Pattern
+```django
+<!-- Standard template for entity collections/groups -->
+<div class="entity-collection" data-collection-id="{{ collection.id }}">
+ <h4 class="collection-title">{{ collection.name }}</h4>
+ <div class="entity-grid">
+ {% for entity in collection.entities %}
+ <div class="entity-card" data-entity-id="{{ entity.id }}">
+ <div class="entity-icon-container">
+ {% if entity.has_position %}
+ <svg viewBox="0 0 64 64" class="entity-card-icon">
+ <use href="#icon-{{ entity.entity_type.name.lower }}"
+ class="entity-svg {{ entity.get_status_css_classes|join:' ' }}"/>
+ </svg>
+ {% else %}
+ <div class="entity-placeholder {{ entity.get_status_css_classes|join:' ' }}">
+ {{ entity.entity_type.display_name|first }}
+ </div>
+ {% endif %}
+ </div>
+ <div class="entity-info">
+ <span class="entity-name">{{ entity.name }}</span>
+ <span class="entity-status">{{ entity.get_display_state }}</span>
+ </div>
+ </div>
+ {% endfor %}
+ </div>
+</div>
+```
+
+### Standard Testing Patterns for Visual Configuration
+
+#### Icon Registration Testing Pattern
+```python
+# Standard test pattern for icon registration
+class IconRegistrationTestCase(TestCase):
+ def test_entity_type_icon_registration(self):
+ """Test that entity type is properly registered for icon display"""
+ entity_type = EntityType.MOTION_SENSOR
+
+ # Verify type is in icon registry
+ self.assertIn(entity_type, EntityStyle.EntityTypesWithIcons)
+
+ # Verify icon template file exists
+ icon_template_path = entity_type.get_icon_template_path()
+ self.assertTrue(os.path.exists(icon_template_path))
+
+ # Verify viewbox is defined
+ viewbox = entity_type.get_viewbox()
+ self.assertIsNotNone(viewbox)
+ self.assertRegex(viewbox, r'\d+ \d+ \d+ \d+') # "x y width height" format
+
+ def test_icon_svg_content_requirements(self):
+ """Test that icon SVG meets requirements"""
+ entity_type = EntityType.MOTION_SENSOR
+ svg_content = entity_type.get_icon_svg_content()
+
+ # Must have clickable background
+ self.assertIn('class="hi-entity-bg"', svg_content)
+
+ # Should not have wrapping <svg> element
+ self.assertNotIn('<svg', svg_content)
+
+ # Should use currentColor for primary elements
+ self.assertIn('currentColor', svg_content)
+```
+
+#### Path Configuration Testing Pattern
+```python
+# Standard test pattern for path configuration
+class PathConfigurationTestCase(TestCase):
+ def test_path_entity_type_registration(self):
+ """Test that path entity type is properly configured"""
+ entity_type = EntityType.ROOM
+
+ # Verify type is in appropriate path registry
+ is_closed = entity_type in EntityStyle.EntityTypeClosedPaths
+ is_open = entity_type in EntityStyle.EntityTypeOpenPaths
+ self.assertTrue(is_closed or is_open, f"{entity_type} not in any path registry")
+
+ # Verify style is assigned
+ self.assertIn(entity_type, EntityStyle.PathEntityTypeToSvgStatusStyle)
+
+ # Verify style class exists and has required properties
+ style_class = EntityStyle.PathEntityTypeToSvgStatusStyle[entity_type]
+ self.assertTrue(hasattr(style_class, 'default_fill'))
+ self.assertTrue(hasattr(style_class, 'active_fill'))
+
+ def test_path_entity_creation_and_display(self):
+ """Test creating and displaying path entities"""
+ room = Entity.objects.create(
+ name='Test Room',
+ entity_type=EntityType.ROOM,
+ location=self.test_location
+ )
+
+ # Create path data
+ path_data = "M10,10 L50,10 L50,50 L10,50 Z" # Simple rectangle
+ EntityPath.objects.create(
+ entity=room,
+ svg_path=path_data
+ )
+
+ # Verify entity can provide display data
+ css_classes = room.get_status_css_classes()
+ self.assertIsInstance(css_classes, list)
+
+ fill_color = room.get_status_fill()
+ self.assertIsInstance(fill_color, str)
+ self.assertRegex(fill_color, r'^#[0-9A-Fa-f]{6}$') # Valid hex color
+```
+
+#### Visual Style Testing Pattern
+```python
+# Standard test pattern for visual style classes
+class VisualStyleTestCase(TestCase):
+ def test_style_class_completeness(self):
+ """Test that style class defines all required properties"""
+ style_class = SecurityDeviceStyle
+
+ required_properties = [
+ 'default_fill', 'default_stroke', 'default_opacity',
+ 'active_fill', 'active_stroke', 'active_opacity',
+ 'idle_fill', 'idle_stroke', 'idle_opacity'
+ ]
+
+ for prop in required_properties:
+ self.assertTrue(hasattr(style_class, prop),
+ f"Style class missing property: {prop}")
+
+ def test_color_format_validation(self):
+ """Test that style colors are valid hex format"""
+ style_class = SecurityDeviceStyle
+
+ color_properties = ['default_fill', 'active_fill', 'idle_fill']
+ for prop in color_properties:
+ color_value = getattr(style_class, prop)
+ self.assertRegex(color_value, r'^#[0-9A-Fa-f]{6}$',
+ f"Invalid color format in {prop}: {color_value}")
+```
+
+#### JavaScript Testing Pattern for Entity Configuration
+```javascript
+// Standard pattern for testing entity visual configuration
+function testEntityVisualConfiguration() {
+ // Test icon symbol generation
+ const iconSymbol = document.querySelector('#icon-motion-sensor');
+ console.assert(iconSymbol !== null, 'Icon symbol not generated');
+ console.assert(iconSymbol.getAttribute('viewBox') === '0 0 64 64',
+ 'Incorrect viewBox');
+
+ // Test entity element creation
+ const testEntityHtml = `
+ <g data-entity-id="test-123" data-entity-type="motion-sensor">
+ <use href="#icon-motion-sensor" class="entity-svg state-idle"/>
+ </g>
+ `;
+ document.querySelector('svg').innerHTML += testEntityHtml;
+
+ // Test CSS class application
+ const entityElement = document.querySelector('[data-entity-id="test-123"] use');
+ console.assert(entityElement.classList.contains('entity-svg'),
+ 'Base entity class missing');
+ console.assert(entityElement.classList.contains('state-idle'),
+ 'Status class missing');
+
+ // Test visual style application
+ const computedStyle = window.getComputedStyle(entityElement);
+ const fillColor = computedStyle.fill;
+ console.assert(fillColor !== '', 'Fill color not applied');
+
+ console.log('Entity visual configuration test passed');
+}
+```
+
+### Standard Maintenance Patterns
+
+#### Icon File Organization Pattern
+```
+hi/apps/entity/templates/entity/svg/
+├── families/
+│ ├── security/
+│ │ ├── type.motion_sensor.svg
+│ │ ├── type.door_sensor.svg
+│ │ └── type.security_camera.svg
+│ ├── climate/
+│ │ ├── type.thermostat.svg
+│ │ └── type.temperature_sensor.svg
+│ └── lighting/
+│ ├── type.light_switch.svg
+│ └── type.dimmer_switch.svg
+└── deprecated/
+ └── old_icon_files_kept_for_reference.svg
+```
+
+#### Configuration Review Checklist
+```python
+# Standard checklist for reviewing entity visual configuration
+"""
+Entity Visual Configuration Review Checklist:
+
+□ Icon File Requirements:
+ - SVG file exists in correct location
+ - No <svg> wrapper element
+ - Contains hi-entity-bg rectangle for clickability
+ - Uses currentColor for status-responsive elements
+ - Follows 64x64 viewBox standard (or custom viewBox registered)
+
+□ Registration Requirements:
+ - EntityType added to appropriate registry (Icons vs Paths)
+ - Style class assigned in PathEntityTypeToSvgStatusStyle (for paths)
+ - Custom viewBox registered if needed
+
+□ Style Requirements:
+ - Style class defines all required state properties
+ - Colors use valid hex format
+ - Opacity values are between 0.0 and 1.0
+ - Stroke widths are reasonable (1-4 typical)
+
+□ Template Integration:
+ - Entity appears in location views
+ - Status changes trigger visual updates
+ - CSS classes apply correctly
+ - Cross-browser compatibility verified
+
+□ Testing Requirements:
+ - Unit tests cover registration
+ - Visual tests verify appearance
+ - Status change tests verify dynamic updates
+ - Error cases handled gracefully
+"""
+```
+
+## Performance Optimization Guide
+
+### Overview
+
+Entity visual configuration can significantly impact rendering performance, especially with many entity types, complex SVG icons, or large-scale deployments. This guide provides optimization strategies for efficient entity visual management.
+
+### SVG Icon Performance Optimization
+
+#### Icon Complexity Management
+```xml
+<!-- EFFICIENT: Simple geometric shapes -->
+<rect class="hi-entity-bg" x="0" y="0" width="64" height="64" fill="none"/>
+<circle cx="32" cy="32" r="20" fill="currentColor"/>
+<rect x="28" y="28" width="8" height="8" fill="white"/>
+
+<!-- INEFFICIENT: Complex path with many points -->
+<rect class="hi-entity-bg" x="0" y="0" width="64" height="64" fill="none"/>
+<path d="M32,10 L35,15 L40,15 L37,20 L38,25 L32,23 L26,25 L27,20 L24,15 L29,15 Z" fill="currentColor"/>
+<path d="M20,30 Q25,25 30,30 Q35,35 40,30 Q45,25 50,30" fill="none" stroke="currentColor"/>
+```
+
+#### SVG Optimization Pipeline
+```javascript
+// Automated SVG optimization during build
+class SvgIconOptimizer {
+ constructor(options = {}) {
+ this.options = {
+ removeUnusedDefs: true,
+ simplifyPaths: true,
+ mergeShapes: true,
+ removeComments: true,
+ minifyCoordinates: true,
+ ...options
+ };
+ }
+
+ optimizeSvgContent(svgString) {
+ let optimized = svgString;
+
+ if (this.options.removeComments) {
+ optimized = this.removeComments(optimized);
+ }
+
+ if (this.options.simplifyPaths) {
+ optimized = this.simplifyPaths(optimized);
+ }
+
+ if (this.options.minifyCoordinates) {
+ optimized = this.minifyCoordinates(optimized);
+ }
+
+ return optimized;
+ }
+
+ removeComments(svg) {
+ return svg.replace(/<!--[\s\S]*?-->/g, '');
+ }
+
+ simplifyPaths(svg) {
+ // Convert complex paths to simpler equivalents
+ return svg.replace(/(<path[^>]*d=")([^"]+)(")/g, (match, start, pathData, end) => {
+ const simplified = this.simplifyPathData(pathData);
+ return start + simplified + end;
+ });
+ }
+
+ simplifyPathData(pathData) {
+ // Remove unnecessary precision
+ return pathData.replace(/(\d+\.\d{3,})/g, (match, num) => {
+ return parseFloat(num).toFixed(2);
+ });
+ }
+
+ minifyCoordinates(svg) {
+ // Round coordinates to reduce file size
+ return svg.replace(/(\d+\.\d{2,})/g, (match, coord) => {
+ return Math.round(parseFloat(coord) * 100) / 100;
+ });
+ }
+}
+```
+
+#### Icon Caching Strategy
+```javascript
+// Efficient icon loading and caching
+class IconCacheManager {
+ constructor() {
+ this.iconCache = new Map();
+ this.preloadQueue = [];
+ this.isPreloading = false;
+ }
+
+ async preloadIcons(iconTypes) {
+ this.preloadQueue.push(...iconTypes);
+
+ if (!this.isPreloading) {
+ this.processPreloadQueue();
+ }
+ }
+
+ async processPreloadQueue() {
+ this.isPreloading = true;
+
+ while (this.preloadQueue.length > 0) {
+ const iconType = this.preloadQueue.shift();
+
+ if (!this.iconCache.has(iconType)) {
+ try {
+ const iconContent = await this.loadIconContent(iconType);
+ this.iconCache.set(iconType, iconContent);
+ } catch (error) {
+ console.warn(`Failed to preload icon ${iconType}:`, error);
+ }
+ }
+
+ // Yield control to prevent blocking
+ await new Promise(resolve => setTimeout(resolve, 0));
+ }
+
+ this.isPreloading = false;
+ }
+
+ async loadIconContent(iconType) {
+ const iconPath = `/static/entity/svg/type.${iconType.toLowerCase()}.svg`;
+ const response = await fetch(iconPath);
+
+ if (!response.ok) {
+ throw new Error(`Failed to load icon: ${response.status}`);
+ }
+
+ return await response.text();
+ }
+
+ getIcon(iconType) {
+ return this.iconCache.get(iconType);
+ }
+
+ // Lazy load icons on demand with memory limits
+ async ensureIconLoaded(iconType, priority = 'normal') {
+ if (this.iconCache.has(iconType)) {
+ return this.iconCache.get(iconType);
+ }
+
+ // Manage cache size
+ if (this.iconCache.size >= 100) {
+ this.evictLeastRecentlyUsed();
+ }
+
+ const iconContent = await this.loadIconContent(iconType);
+ this.iconCache.set(iconType, {
+ content: iconContent,
+ lastUsed: Date.now(),
+ priority
+ });
+
+ return iconContent;
+ }
+
+ evictLeastRecentlyUsed() {
+ let oldestTime = Date.now();
+ let oldestKey = null;
+
+ for (const [key, value] of this.iconCache) {
+ if (value.priority !== 'high' && value.lastUsed < oldestTime) {
+ oldestTime = value.lastUsed;
+ oldestKey = key;
+ }
+ }
+
+ if (oldestKey) {
+ this.iconCache.delete(oldestKey);
+ }
+ }
+}
+```
+
+### Registration and Configuration Performance
+
+#### Lazy Registration Pattern
+```python
+# Optimize entity type registration for large numbers of types
+class LazyEntityTypeRegistry:
+ """Lazy-load entity type configurations to improve startup performance"""
+
+ def __init__(self):
+ self._icon_registry = None
+ self._path_registry = None
+ self._style_registry = None
+ self._viewbox_registry = None
+
+ @property
+ def entity_types_with_icons(self):
+ if self._icon_registry is None:
+ self._icon_registry = self._build_icon_registry()
+ return self._icon_registry
+
+ @property
+ def entity_type_closed_paths(self):
+ if self._path_registry is None:
+ self._path_registry = self._build_path_registry()
+ return self._path_registry
+
+ def _build_icon_registry(self):
+ """Build icon registry on first access"""
+ icon_types = set()
+
+ # Load from configuration files or database
+ # This allows for dynamic entity type registration
+ icon_config = self.load_icon_configuration()
+
+ for entity_type_name in icon_config:
+ try:
+ entity_type = EntityType[entity_type_name]
+ icon_types.add(entity_type)
+ except KeyError:
+ logger.warning(f"Unknown entity type in icon config: {entity_type_name}")
+
+ return icon_types
+
+ def load_icon_configuration(self):
+ """Load icon configuration from external source"""
+ # Can be loaded from JSON, database, or environment
+ return getattr(settings, 'ENTITY_ICON_TYPES', DEFAULT_ICON_TYPES)
+```
+
+#### Batch Configuration Updates
+```python
+# Efficient bulk configuration changes
+class EntityConfigurationBatcher:
+ """Batch entity configuration changes for better performance"""
+
+ def __init__(self):
+ self.pending_icon_registrations = set()
+ self.pending_path_registrations = set()
+ self.pending_style_updates = {}
+ self.batch_size = 50
+
+ def add_icon_registration(self, entity_type):
+ self.pending_icon_registrations.add(entity_type)
+
+ if len(self.pending_icon_registrations) >= self.batch_size:
+ self.flush_icon_registrations()
+
+ def add_path_registration(self, entity_type, path_type):
+ self.pending_path_registrations.add((entity_type, path_type))
+
+ if len(self.pending_path_registrations) >= self.batch_size:
+ self.flush_path_registrations()
+
+ def flush_icon_registrations(self):
+ """Apply all pending icon registrations at once"""
+ if not self.pending_icon_registrations:
+ return
+
+ # Update registry in single operation
+ EntityStyle.EntityTypesWithIcons.update(self.pending_icon_registrations)
+
+ # Clear template caches that depend on icon registry
+ self.clear_related_caches(['entity_icon_symbols', 'location_view_templates'])
+
+ self.pending_icon_registrations.clear()
+
+ def flush_all(self):
+ """Flush all pending configuration changes"""
+ self.flush_icon_registrations()
+ self.flush_path_registrations()
+ self.flush_style_updates()
+
+ def clear_related_caches(self, cache_keys):
+ """Clear Django template and view caches"""
+ from django.core.cache import cache
+ for key in cache_keys:
+ cache.delete_many(cache.get_many([f"{key}:*"]))
+```
+
+### Template Rendering Optimization
+
+#### Template Fragment Caching
+```django
+<!-- Cache expensive template fragments -->
+{% load cache %}
+
+<!-- Cache entity symbol definitions -->
+{% cache 3600 entity_symbols entity_types_hash %}
+<defs>
+ {% for entity_type in entity_types_with_icons %}
+ <symbol id="icon-{{ entity_type.name.lower }}"
+ viewBox="{{ entity_type.get_viewbox }}">
+ {% include entity_type.get_icon_template %}
+ </symbol>
+ {% endfor %}
+</defs>
+{% endcache %}
+
+<!-- Cache per-entity-type rendering -->
+{% for entity in positioned_entities %}
+ {% cache 300 entity_rendering entity.id entity.last_modified entity_type_version %}
+ <g class="entity-group" data-entity-id="{{ entity.id }}">
+ <use href="#icon-{{ entity.entity_type.name.lower }}"
+ class="entity-svg {{ entity.get_status_css_classes|join:' ' }}"
+ transform="{{ entity.get_transform_string }}"/>
+ </g>
+ {% endcache %}
+{% endfor %}
+```
+
+#### Conditional Template Loading
+```python
+# Load templates conditionally based on entity types present
+class OptimizedLocationViewMixin:
+ def get_context_data(self, **kwargs):
+ context = super().get_context_data(**kwargs)
+
+ # Only load entity types that are actually used in this location
+ present_entity_types = self.get_present_entity_types()
+ context['entity_types_with_icons'] = [
+ et for et in EntityStyle.EntityTypesWithIcons
+ if et in present_entity_types
+ ]
+
+ # Pre-calculate expensive template data
+ context['entity_transforms'] = self.precalculate_transforms()
+ context['entity_type_hash'] = self.get_entity_types_cache_key()
+
+ return context
+
+ def get_present_entity_types(self):
+ """Get only entity types that exist in current location"""
+ return set(
+ Entity.objects
+ .filter(location=self.object)
+ .values_list('entity_type', flat=True)
+ .distinct()
+ )
+
+ def precalculate_transforms(self):
+ """Pre-calculate transform strings to avoid template computation"""
+ transforms = {}
+ for entity in self.get_positioned_entities():
+ transforms[entity.id] = entity.get_transform_string()
+ return transforms
+```
+
+### CSS Performance for Visual Configuration
+
+#### CSS Custom Properties Optimization
+```css
+/* Efficient CSS custom property usage */
+:root {
+ /* Define base colors once */
+ --entity-base-active: #dc3545;
+ --entity-base-idle: #28a745;
+ --entity-base-unknown: #6c757d;
+
+ /* Derive variations using calc() */
+ --entity-active-light: color-mix(in srgb, var(--entity-base-active) 80%, white);
+ --entity-active-dark: color-mix(in srgb, var(--entity-base-active) 80%, black);
+}
+
+/* Use efficient selectors for entity styling */
+[data-entity-type="motion_sensor"] {
+ --entity-color: var(--entity-base-active);
+ --entity-stroke: var(--entity-active-dark);
+}
+
+[data-entity-type="door_sensor"] {
+ --entity-color: var(--entity-base-idle);
+ --entity-stroke: var(--entity-active-dark);
+}
+
+/* Apply colors using custom properties */
+.entity-svg {
+ fill: var(--entity-color);
+ stroke: var(--entity-stroke);
+}
+```
+
+#### Critical CSS for Entity Display
+```css
+/* Critical CSS - load first for entity display */
+.entity-svg, .entity-path {
+ /* Essential properties only */
+ fill: currentColor;
+ stroke: currentColor;
+ cursor: pointer;
+}
+
+.entity-group {
+ /* Minimal base styling */
+ pointer-events: all;
+}
+
+/* Non-critical styling - can be loaded later */
+@media (min-width: 768px) {
+ .entity-svg:hover {
+ filter: brightness(1.1);
+ transform: scale(1.05);
+ transition: all 0.2s ease;
+ }
+}
+```
+
+### Browser Performance Optimization
+
+#### Feature Detection and Polyfills
+```javascript
+// Conditional feature loading based on browser capabilities
+class BrowserOptimizedEntityRenderer {
+ constructor() {
+ this.capabilities = this.detectCapabilities();
+ this.loadOptimalStrategies();
+ }
+
+ detectCapabilities() {
+ return {
+ hasIntersectionObserver: 'IntersectionObserver' in window,
+ hasResizeObserver: 'ResizeObserver' in window,
+ supportsCustomElements: 'customElements' in window,
+ supportsCSSSCustomProperties: CSS.supports('--test', 'test'),
+ hasRequestIdleCallback: 'requestIdleCallback' in window,
+ memoryInfo: navigator.memory || { usedJSHeapSize: 50 * 1024 * 1024 },
+ hardwareConcurrency: navigator.hardwareConcurrency || 4
+ };
+ }
+
+ loadOptimalStrategies() {
+ if (this.capabilities.hasIntersectionObserver) {
+ this.useIntersectionBasedRendering();
+ } else {
+ this.useScrollBasedRendering();
+ }
+
+ if (this.capabilities.hasRequestIdleCallback) {
+ this.useIdleTimeProcessing();
+ } else {
+ this.useTimeSlicedProcessing();
+ }
+
+ // Adjust strategies based on device memory
+ if (this.capabilities.memoryInfo.usedJSHeapSize > 100 * 1024 * 1024) {
+ this.enableMemoryConservationMode();
+ }
+ }
+
+ useIntersectionBasedRendering() {
+ const observer = new IntersectionObserver((entries) => {
+ entries.forEach(entry => {
+ const entityId = entry.target.getAttribute('data-entity-id');
+ if (entry.isIntersecting) {
+ this.enableEntityRendering(entityId);
+ } else {
+ this.disableEntityRendering(entityId);
+ }
+ });
+ }, {
+ rootMargin: '50px',
+ threshold: 0.1
+ });
+
+ document.querySelectorAll('[data-entity-id]').forEach(el => {
+ observer.observe(el);
+ });
+ }
+
+ useIdleTimeProcessing() {
+ const processQueue = (deadline) => {
+ while (deadline.timeRemaining() > 0 && this.processingQueue.length > 0) {
+ const task = this.processingQueue.shift();
+ task();
+ }
+
+ if (this.processingQueue.length > 0) {
+ requestIdleCallback(processQueue);
+ }
+ };
+
+ requestIdleCallback(processQueue);
+ }
+
+ enableMemoryConservationMode() {
+ // Reduce icon cache size
+ this.maxIconCacheSize = 25;
+
+ // Use simplified rendering for non-critical entities
+ this.useSimplifiedRendering = true;
+
+ // Disable expensive visual effects
+ this.disableVisualEffects = true;
+ }
+}
+```
+
+### Testing Performance Optimizations
+
+#### Performance Testing Framework
+```javascript
+// Automated performance testing for entity configurations
+class EntityPerformanceTester {
+ constructor(testConfig = {}) {
+ this.config = {
+ maxEntityCount: 1000,
+ testDuration: 30000, // 30 seconds
+ acceptableFrameTime: 16, // 60 FPS
+ ...testConfig
+ };
+ this.results = {};
+ }
+
+ async runEntityLoadTest(entityCount) {
+ console.log(`Starting entity load test with ${entityCount} entities`);
+
+ const startTime = performance.now();
+ const frameTimes = [];
+
+ // Create test entities
+ const testEntities = this.createTestEntities(entityCount);
+
+ // Measure rendering performance
+ const measureFrame = () => {
+ const frameStart = performance.now();
+
+ // Simulate entity updates
+ testEntities.forEach(entity => {
+ this.updateEntityVisuals(entity);
+ });
+
+ const frameEnd = performance.now();
+ frameTimes.push(frameEnd - frameStart);
+
+ if (frameEnd - startTime < this.config.testDuration) {
+ requestAnimationFrame(measureFrame);
+ } else {
+ this.analyzeResults(frameTimes, entityCount);
+ }
+ };
+
+ requestAnimationFrame(measureFrame);
+ }
+
+ createTestEntities(count) {
+ const entities = [];
+ const entityTypes = ['motion_sensor', 'door_sensor', 'temperature_sensor'];
+
+ for (let i = 0; i < count; i++) {
+ const entityType = entityTypes[i % entityTypes.length];
+ const entity = {
+ id: `test-entity-${i}`,
+ type: entityType,
+ x: Math.random() * 1000,
+ y: Math.random() * 1000,
+ status: Math.random() > 0.5 ? 'active' : 'idle'
+ };
+ entities.push(entity);
+ }
+
+ return entities;
+ }
+
+ updateEntityVisuals(entity) {
+ const element = document.querySelector(`[data-entity-id="${entity.id}"]`);
+ if (element) {
+ element.classList.toggle('state-active', entity.status === 'active');
+ element.classList.toggle('state-idle', entity.status === 'idle');
+ }
+ }
+
+ analyzeResults(frameTimes, entityCount) {
+ const avgFrameTime = frameTimes.reduce((a, b) => a + b, 0) / frameTimes.length;
+ const maxFrameTime = Math.max(...frameTimes);
+ const slowFrames = frameTimes.filter(t => t > this.config.acceptableFrameTime).length;
+ const slowFramePercentage = (slowFrames / frameTimes.length) * 100;
+
+ const result = {
+ entityCount,
+ averageFrameTime: avgFrameTime.toFixed(2),
+ maxFrameTime: maxFrameTime.toFixed(2),
+ slowFramePercentage: slowFramePercentage.toFixed(1),
+ acceptable: slowFramePercentage < 10 // Less than 10% slow frames
+ };
+
+ this.results[entityCount] = result;
+ console.log('Performance test results:', result);
+
+ return result;
+ }
+
+ async runComprehensiveTest() {
+ const testSizes = [50, 100, 250, 500, 750, 1000];
+
+ for (const size of testSizes) {
+ await this.runEntityLoadTest(size);
+
+ // Wait between tests
+ await new Promise(resolve => setTimeout(resolve, 2000));
+ }
+
+ this.generatePerformanceReport();
+ }
+
+ generatePerformanceReport() {
+ console.log('\n=== Entity Performance Report ===');
+ Object.values(this.results).forEach(result => {
+ const status = result.acceptable ? '✅ PASS' : '❌ FAIL';
+ console.log(`${status} ${result.entityCount} entities: ${result.averageFrameTime}ms avg, ${result.slowFramePercentage}% slow frames`);
+ });
+
+ // Find performance breakpoint
+ const breakpoint = this.findPerformanceBreakpoint();
+ if (breakpoint) {
+ console.log(`\n⚠️ Performance degradation detected at ${breakpoint} entities`);
+ }
+ }
+
+ findPerformanceBreakpoint() {
+ const results = Object.values(this.results);
+ for (let i = 0; i < results.length - 1; i++) {
+ if (results[i].acceptable && !results[i + 1].acceptable) {
+ return results[i + 1].entityCount;
+ }
+ }
+ return null;
+ }
+}
+```
+
+### Memory Management for Entity Configurations
+
+#### Resource Cleanup Patterns
+```javascript
+// Proper cleanup to prevent memory leaks
+class EntityConfigurationManager {
+ constructor() {
+ this.iconElements = new Map();
+ this.styleSheets = new Map();
+ this.eventListeners = new WeakMap();
+ this.cleanupTasks = [];
+ }
+
+ registerEntity(entityId, entityType) {
+ // Create icon elements
+ const iconElement = this.createIconElement(entityType);
+ this.iconElements.set(entityId, iconElement);
+
+ // Add cleanup task
+ this.cleanupTasks.push(() => {
+ this.iconElements.delete(entityId);
+ this.removeEntityEventListeners(entityId);
+ });
+ }
+
+ unregisterEntity(entityId) {
+ // Clean up icon element
+ const iconElement = this.iconElements.get(entityId);
+ if (iconElement && iconElement.parentNode) {
+ iconElement.parentNode.removeChild(iconElement);
+ }
+
+ this.iconElements.delete(entityId);
+ this.removeEntityEventListeners(entityId);
+ }
+
+ cleanup() {
+ // Run all cleanup tasks
+ this.cleanupTasks.forEach(task => {
+ try {
+ task();
+ } catch (error) {
+ console.warn('Cleanup task failed:', error);
+ }
+ });
+
+ this.cleanupTasks = [];
+ this.iconElements.clear();
+ this.styleSheets.clear();
+ }
+
+ // Automatic cleanup on page unload
+ setupAutoCleanup() {
+ window.addEventListener('beforeunload', () => {
+ this.cleanup();
+ });
+
+ // Clean up periodically
+ setInterval(() => {
+ this.performPeriodicCleanup();
+ }, 60000); // Every minute
+ }
+
+ performPeriodicCleanup() {
+ // Remove references to non-existent entities
+ const existingEntityIds = new Set();
+ document.querySelectorAll('[data-entity-id]').forEach(el => {
+ existingEntityIds.add(el.getAttribute('data-entity-id'));
+ });
+
+ for (const [entityId] of this.iconElements) {
+ if (!existingEntityIds.has(entityId)) {
+ this.unregisterEntity(entityId);
+ }
+ }
+ }
+}
+```
+
+## Overview
+
+This document covers the frontend configuration required to set up visual representations for entity types. It includes icon configuration, path styling, viewbox management, and visual asset creation.
+
+## Entity Display Methods
+
+Entities can be visually represented through two primary methods:
+
+### Icon-Based Representation
+- **EntityPosition**: Icon-based representation with position, scale, rotation
+- **Use Case**: Point entities like sensors, devices, controls
+- **Visual**: SVG icons with positioning and scaling
+
+### Path-Based Representation
+- **EntityPath**: SVG path representation for areas or complex shapes
+- **Use Case**: Areas, zones, complex geometric shapes
+- **Visual**: SVG paths with fill, stroke, and styling
+
+## Adding Visual Support for New Entity Types
+
+When adding visual support for a new entity type, follow these configuration steps:
+
+### 1. Choose Visual Display Method
+
+Determine whether the entity should be displayed as an icon or a path based on its nature:
+- **Icons**: Point-like entities (sensors, switches, cameras)
+- **Paths**: Area-like entities (rooms, zones, boundaries)
+
+### 2. Icon-Based Entity Configuration
+
+#### Create SVG Icon Asset
+
+Create an SVG icon for the new entity type in:
+```
+hi/apps/entity/templates/entity/svg/type.${TYPE}.svg
+```
+The `${TYPE}` must match the enum name in lowercase.
+
+**SVG Icon Requirements:**
+```svg
+<!-- Example: type.motion_sensor.svg -->
+<rect class="hi-entity-bg" x="0" y="0" width="64" height="64" fill="none"/>
+<circle cx="32" cy="32" r="20" fill="currentColor"/>
+<path d="M20,32 L32,20 L44,32 L32,44 Z" fill="white" opacity="0.8"/>
+```
+
+**Key Requirements:**
+1. **Clickable Background**: Always include a rectangle covering the entire viewbox:
+ ```svg
+ <rect class="hi-entity-bg" x="0" y="0" width="64" height="64" fill="none"/>
+ ```
+ This ensures the entire icon area is clickable for user interactions.
+
+2. **No Wrapping SVG Element**: File should contain only drawing commands, no `<svg>` wrapper
+
+3. **Standard Viewbox**: Default viewbox is `0 0 64 64` unless custom viewbox is registered
+
+#### Register Icon Configuration
+
+Add the new entity type to the icon registry:
+```python
+# hi.hi_styles.EntityStyle.EntityTypesWithIcons
+EntityTypesWithIcons = {
+ EntityType.MOTION_SENSOR,
+ EntityType.DOOR_SENSOR,
+ EntityType.YOUR_NEW_TYPE, # Add here
+ # ... existing types
+}
+```
+
+#### Custom Viewbox Configuration (Optional)
+
+If your icon requires a different viewbox than the default `0 0 64 64`, register it:
+```python
+# hi.hi_styles.EntityStyle.EntityTypeToIconViewbox
+EntityTypeToIconViewbox = {
+ EntityType.YOUR_NEW_TYPE: "0 0 100 50", # Custom viewbox
+ # ... existing custom viewboxes
+}
+```
+
+### 3. Path-Based Entity Configuration
+
+#### Choose Path Type
+
+Determine whether the entity represents a closed or open path:
+
+**Closed Paths** (filled areas):
+```python
+# hi.hi_styles.EntityStyle.EntityTypeClosedPaths
+EntityTypeClosedPaths = {
+ EntityType.ROOM,
+ EntityType.ZONE,
+ EntityType.YOUR_NEW_AREA_TYPE, # Add here
+}
+```
+
+**Open Paths** (lines/curves):
+```python
+# hi.hi_styles.EntityStyle.EntityTypeOpenPaths
+EntityTypeOpenPaths = {
+ EntityType.CORRIDOR,
+ EntityType.BOUNDARY_LINE,
+ EntityType.YOUR_NEW_LINE_TYPE, # Add here
+}
+```
+
+#### Define Visual Style
+
+Create or reference a visual style for the path entity:
+```python
+# hi.hi_styles.EntityStyle.PathEntityTypeToSvgStatusStyle
+PathEntityTypeToSvgStatusStyle = {
+ EntityType.YOUR_NEW_TYPE: YourCustomSvgStatusStyle,
+ # Reference existing style or create new one
+}
+```
+
+#### Create Custom SVG Status Style (If Needed)
+
+If no existing style fits your entity type, create a new style class:
+```python
+# In hi.hi_styles.EntityStyle
+class YourCustomSvgStatusStyle:
+ """SVG styling for your custom entity type"""
+
+ # Default styling
+ default_fill = "#E0E0E0"
+ default_stroke = "#808080"
+ default_stroke_width = "2"
+
+ # State-based styling
+ active_fill = "#FF4444"
+ active_stroke = "#CC0000"
+
+ recent_fill = "#FF8844"
+ recent_stroke = "#CC4400"
+
+ past_fill = "#FFCC44"
+ past_stroke = "#CC8800"
+
+ idle_fill = "#44FF44"
+ idle_stroke = "#00CC00"
+```
+
+#### Default Path Sizing (Optional)
+
+Configure default sizing for path entities:
+```python
+# hi.hi_styles.EntityStyle.EntityTypePathInitialRadius
+EntityTypePathInitialRadius = {
+ EntityType.YOUR_NEW_TYPE: 25.0, # Default radius in pixels
+ # ... existing size overrides
+}
+```
+
+## Visual Asset Guidelines
+
+### SVG Icon Design Standards
+
+**Size and Scaling:**
+- Design for 64x64 viewbox by default
+- Use simple, recognizable shapes
+- Ensure visibility at small scales (16px minimum)
+
+**Color Usage:**
+- Use `currentColor` for primary elements that should inherit entity state colors
+- Use fixed colors sparingly for distinctive details
+- Maintain sufficient contrast with background
+
+**Style Consistency:**
+- Follow existing icon visual language
+- Use similar stroke weights and fill patterns
+- Maintain consistent visual metaphors
+
+### Path Styling Standards
+
+**Stroke and Fill:**
+- Provide meaningful defaults for idle state
+- Ensure status colors are clearly distinguishable
+- Consider opacity for layered visual effects
+
+**Visual Hierarchy:**
+- Active states should be most prominent
+- Use color temperature progression (hot to cool)
+- Maintain readability across different backgrounds
+
+## Template Integration
+
+### Icon Entity Template Usage
+
+```django
+<!-- Icon entity in location view -->
+<g class="entity-group" data-entity-id="{{ entity.id }}">
+ <use href="#icon-{{ entity.entity_type.name.lower }}"
+ class="entity-icon {{ entity.get_status_css_classes }}"
+ transform="translate({{ entity.position.x }}, {{ entity.position.y }})
+ scale({{ entity.position.scale }})
+ rotate({{ entity.position.rotation }})" />
+</g>
+```
+
+### Path Entity Template Usage
+
+```django
+<!-- Path entity in location view -->
+<g class="entity-group" data-entity-id="{{ entity.id }}">
+ <path class="entity-path {{ entity.get_status_css_classes }}"
+ d="{{ entity.path.svg_path }}"
+ style="{{ entity.get_path_styling }}" />
+</g>
+```
+
+### Icon Symbol Definitions
+
+Icons must be included in the SVG symbol definitions:
+```django
+<!-- In base template or location template -->
+<defs>
+ {% for entity_type in entity_types_with_icons %}
+ <symbol id="icon-{{ entity_type.name.lower }}" viewBox="{{ entity_type.get_viewbox }}">
+ {% include entity_type.get_icon_template %}
+ </symbol>
+ {% endfor %}
+</defs>
+```
+
+## Testing Visual Configuration
+
+### Visual Testing Checklist
+
+When adding new entity visual support:
+
+1. **Icon Visibility**: Verify icon displays correctly at various scales
+2. **State Changes**: Test all status states (active, recent, past, idle, unknown)
+3. **Color Contrast**: Ensure sufficient contrast in all color schemes
+4. **Click Targets**: Verify clickable area covers entire visual element
+5. **Template Rendering**: Test in location views, collection views, and status modals
+6. **Responsive Scaling**: Test on different screen sizes and zoom levels
+
+### Manual Testing Process
+
+1. Create test entity of new type
+2. Position entity in a location
+3. Trigger state changes through integration or simulation
+4. Verify visual feedback matches expected behavior
+5. Test entity in different view contexts
+
+## Simulator Integration (Optional)
+
+If the new entity type should be supported by the simulator:
+```python
+# hi.simulator.enums.SimEntityType
+SimEntityType = Enum('SimEntityType', [
+ 'MOTION_SENSOR',
+ 'DOOR_SENSOR',
+ 'YOUR_NEW_TYPE', # Add corresponding simulator type
+ # ... existing types
+])
+```
+
+## Troubleshooting
+
+### Entity Icon Not Displaying
+
+**Symptoms**: Entity shows as placeholder or missing icon
+**Diagnostic Steps**:
+
+1. **Check File Path and Naming**
+ ```bash
+ # Verify file exists with correct name
+ ls hi/apps/entity/templates/entity/svg/type.{enum_name}.svg
+
+ # Example: for EntityType.MOTION_SENSOR
+ ls hi/apps/entity/templates/entity/svg/type.motion_sensor.svg
+ ```
+ - **Rule**: File name must match enum name in lowercase with underscores
+
+2. **Verify Icon Registration**
+ ```python
+ # Check in hi.hi_styles.EntityStyle.EntityTypesWithIcons
+ EntityTypesWithIcons = {
+ EntityType.MOTION_SENSOR, # Must be present
+ # ... your new entity type
+ }
+ ```
+
+3. **Check SVG File Content**
+ ```xml
+ <!-- File should NOT have <svg> wrapper -->
+ <!-- GOOD -->
+ <rect class="hi-entity-bg" x="0" y="0" width="64" height="64" fill="none"/>
+ <circle cx="32" cy="32" r="20" fill="currentColor"/>
+
+ <!-- BAD -->
+ <svg viewBox="0 0 64 64">
+ <circle cx="32" cy="32" r="20" fill="currentColor"/>
+ </svg>
+ ```
+
+**Common Fixes**:
+- **Incorrect enum case**: Ensure file name uses lowercase and underscores
+- **Missing registration**: Add entity type to `EntityTypesWithIcons` set
+- **Invalid SVG**: Remove `<svg>` wrapper, keep only drawing commands
+- **Missing clickable background**: Add `hi-entity-bg` rectangle
+
+### Entity Icon Wrong Size or Position
+
+**Symptoms**: Icon appears too large, small, or positioned incorrectly
+**Root Causes & Solutions**:
+
+1. **ViewBox Issues**
+ ```python
+ # Check custom viewbox registration
+ EntityTypeToIconViewbox = {
+ EntityType.YOUR_TYPE: "0 0 100 50", # Custom viewbox
+ }
+ ```
+ - **Default**: `0 0 64 64` - if icon designed differently, register custom viewbox
+
+2. **SVG Coordinate Problems**
+ ```xml
+ <!-- Icons should be designed for 64x64 viewbox -->
+ <rect class="hi-entity-bg" x="0" y="0" width="64" height="64" fill="none"/>
+ <!-- Center elements around 32,32 -->
+ <circle cx="32" cy="32" r="20" fill="currentColor"/>
+ ```
+
+3. **Template Transform Issues**
+ ```django
+ <!-- Check entity positioning in template -->
+ <g transform="translate({{ entity.position.x }}, {{ entity.position.y }})
+ scale({{ entity.position.scale }})
+ rotate({{ entity.position.rotation }})">
+ <use href="#icon-{{ entity.entity_type.name.lower }}"/>
+ </g>
+ ```
+
+### Entity Path Not Rendering
+
+**Symptoms**: Path-based entities don't appear or have no styling
+**Diagnostic Approach**:
+
+1. **Verify Path Type Registration**
+ ```python
+ # Check appropriate path type set
+ EntityTypeClosedPaths = {
+ EntityType.ROOM,
+ EntityType.YOUR_AREA_TYPE, # For filled areas
+ }
+
+ EntityTypeOpenPaths = {
+ EntityType.BOUNDARY_LINE,
+ EntityType.YOUR_LINE_TYPE, # For lines/curves
+ }
+ ```
+
+2. **Check Style Assignment**
+ ```python
+ # Verify style is assigned
+ PathEntityTypeToSvgStatusStyle = {
+ EntityType.YOUR_TYPE: YourCustomSvgStatusStyle,
+ }
+ ```
+
+3. **Validate SVG Path Data**
+ ```django
+ <!-- Entity must have valid SVG path -->
+ <path class="entity-path"
+ d="{{ entity.path.svg_path }}" <!-- Must be valid SVG path data -->
+ style="{{ entity.get_path_styling }}"/>
+ ```
+
+**Solutions**:
+- **Missing path registration**: Add to correct path type set (closed vs open)
+- **No style defined**: Create and assign `SvgStatusStyle` class
+- **Invalid path data**: Ensure `entity.path.svg_path` contains valid SVG path commands
+
+### Entity Colors/Styling Not Applied
+
+**Symptoms**: Entity shows default colors, status changes don't affect appearance
+**Troubleshooting Steps**:
+
+1. **Check Style Class Definition**
+ ```python
+ class YourCustomSvgStatusStyle:
+ # Must define all required properties
+ default_fill = "#E0E0E0"
+ default_stroke = "#808080"
+
+ active_fill = "#FF4444"
+ active_stroke = "#CC0000"
+
+ # ... other states
+ ```
+
+2. **Verify CSS Class Application**
+ ```html
+ <!-- Entity element should have status classes -->
+ <path class="entity-path state-active" .../>
+
+ <!-- CSS rules should exist -->
+ .entity-path.state-active {
+ fill: #FF4444;
+ stroke: #CC0000;
+ }
+ ```
+
+3. **Test Status Changes**
+ ```javascript
+ // Manually test CSS class changes
+ const element = document.querySelector('[data-entity-id="123"]');
+ element.classList.add('state-active');
+ // Should see visual change
+ ```
+
+### Template Integration Problems
+
+**Symptoms**: New entity types don't appear in location views
+**Checklist**:
+
+1. **Entity Creation**
+ ```python
+ # Entity must be properly created with type
+ entity = Entity.objects.create(
+ name="Test Entity",
+ entity_type=EntityType.YOUR_NEW_TYPE,
+ location=location
+ )
+ ```
+
+2. **Template Symbol Definitions**
+ ```django
+ <!-- Icons must be defined in template -->
+ <defs>
+ {% for entity_type in entity_types_with_icons %}
+ <symbol id="icon-{{ entity_type.name.lower }}"
+ viewBox="{{ entity_type.get_viewbox }}">
+ {% include entity_type.get_icon_template %}
+ </symbol>
+ {% endfor %}
+ </defs>
+ ```
+
+3. **Entity Rendering Logic**
+ ```django
+ {% for entity in entities %}
+ {% if entity.has_position %}
+ <!-- Icon entity rendering -->
+ {% elif entity.has_path %}
+ <!-- Path entity rendering -->
+ {% endif %}
+ {% endfor %}
+ ```
+
+### Performance and Visual Quality Issues
+
+**Symptoms**: Icons appear pixelated, slow rendering, or memory issues
+**Optimizations**:
+
+1. **SVG Optimization**
+ ```xml
+ <!-- Use simple shapes, avoid complex paths -->
+ <!-- GOOD - simple circle -->
+ <circle cx="32" cy="32" r="20"/>
+
+ <!-- AVOID - complex path when simple shape works -->
+ <path d="M12,32 A20,20 0 1,1 52,32 A20,20 0 1,1 12,32"/>
+ ```
+
+2. **Reduce Icon Complexity**
+ ```xml
+ <!-- Limit number of elements per icon -->
+ <!-- Combine shapes where possible -->
+ <!-- Use fill over stroke for better performance -->
+ ```
+
+3. **Browser Rendering Optimization**
+ ```css
+ /* Force hardware acceleration for smooth animations */
+ .entity-svg {
+ transform: translateZ(0);
+ will-change: transform;
+ }
+ ```
+
+### Browser Compatibility Issues
+
+**Symptoms**: Icons work in some browsers but not others
+**Common Problems & Solutions**:
+
+1. **SVG Symbol Support (IE)**
+ ```html
+ <!-- Use polyfill for older browsers -->
+ <script src="svg4everybody.js"></script>
+ <script>svg4everybody();</script>
+ ```
+
+2. **CSS Custom Properties (IE/Edge)**
+ ```css
+ /* Provide fallbacks */
+ .entity-path {
+ fill: #E0E0E0; /* fallback */
+ fill: var(--entity-default-fill, #E0E0E0);
+ }
+ ```
+
+3. **ViewBox Issues (Safari)**
+ ```xml
+ <!-- Always specify explicit dimensions -->
+ <symbol id="icon-sensor" viewBox="0 0 64 64" width="64" height="64">
+ ```
+
+## Related Documentation
+- Entity domain patterns: [Entity Patterns](../domain/entity-patterns.md)
+- Status display implementation: [Entity Status Display](entity-status-display.md)
+- Style guidelines: [Style Guidelines](style-guidelines.md)
+- Icon system: [Icon System](icon-system.md)
+- Frontend guidelines: [Frontend Guidelines](frontend-guidelines.md)
\ No newline at end of file
diff --git a/docs/dev/frontend/frontend-guidelines.md b/docs/dev/frontend/frontend-guidelines.md
new file mode 100644
index 00000000..7bb2f98a
--- /dev/null
+++ b/docs/dev/frontend/frontend-guidelines.md
@@ -0,0 +1,286 @@
+# Frontend Guidelines
+
+## Django Template Guidelines
+
+### Core Principles
+
+1. **Minimal Business Logic**: Keep business logic out of templates. Complex loops, conditionals, and data processing belong in views or custom template tags/filters. No ORM operations in tempate tags.
+
+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.
+
+6. **Load Directives**: All template `load` directives should appear at the top of the file, or just below the `extends` directive if there is one.
+
+
+**Good examples:**
+```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:**
+```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 %}
+```
+
+## Template Naming Conventions
+
+- `pages/` - For full HTML pages
+- `modals/` - For HTML modals
+- `panes/` - For all other HTML page fragments
+- `email/` - For email templates
+- `svg/` - For SVG files
+
+For app modules with separate "edit" views, use the same structure in an `edit/` subdirectory.
+
+## Template Contexts
+
+We have another code factoring guideline for views that says once the template context begins to contain a large number of entries, we should encapsulate them in a dataclass and use typed attributes instead of strings. For example, instead of a template contents like this:
+```
+return {
+ 'entity': entity,
+ 'sensor': sensor,
+ 'current_history': current_history,
+ 'timeline_groups': timeline_groups,
+ 'prev_history': prev_history,
+ 'next_history': next_history,
+ 'sensor_history_items': mock_history_items,
+ }
+```
+We would define a dataclass like EntitySensorHistoryData and delegate a helper class to build it, then be left with:
+```
+sensor_history_data = some_helper.build_sensor_history_data( some, args )
+return {
+ 'sensor_history_data': sensor_history_data,
+ }
+```
+
+## The "Hi Grid" Template Structure
+
+### Important DIV IDs
+
+These are gathered in `src/hi/constants.py:DIV_IDS`:
+
+- `#hi-main-content` - Main display area, excluding header buttons, footer buttons and side panel
+- `#hi-side-content` - Side panel content area
+- `#hi-top-buttons` - Top button toolbar area
+- `#hi-bottom-buttons` - Bottom button toolbar area
+- `#hi-config-integration-tab` - Integrations use this for configuration-related views
+
+These `DIV_IDS` are injected into the template context automatically for use as we do not use magic strings as they need to be referenced in multiple places.
+
+## JavaScript Standards
+
+**Minimize Javascript**: We should strive for the minimal amount of new Javascript. There are many special-purpose needs in the app that require Javascript, but we should never do in Javascfript what we can achieve on the backend.
+
+**Server Side Rendering**: We strive to generate all HTML content on the server side.
+
+**Prefer Asynchronous Updates**: The application closely mimics a single page application that always tries to avoid full page loads. Dynamic updates are preferred over full pages, especially for frequently use view changes.
+
+**Javascript in Templates**: We should never put Javascript in templates, or otherwise have inline `<script>` blocks. There are rare exceptions for very focused, specialized manipulations, but all Javascript should be put in a file in the `src/hi/static/js` directory.
+
+### Core Technologies
+- jQuery 3.7 for DOM manipulation
+- Bootstrap 4 for UI components
+- Custom SVG manipulation library
+
+**Django Pipeline**: We use the Django pipeline library for injecting minimized, cache-busting Javascript (and CSS) into pages. Any new files must be defined in `src/hi/settings/base.py`.
+
+
+### Asynchronous/AJAX Updates
+
+By default, we use the `src/hi/static/js/antinode.js` module for performing DOM async DOM manipulations. This is meant to be a generically useful library that does not contain any application-specific code. It provides the necessary mechanisms for most needed. See the file itself for details of its operation.
+
+### Polling and Updates
+
+The `polling.js` module polls the server for latest sensor values:
+- Fetches latest sensor values via `StatusDataHelper`
+- Computes visual display using `StatusDisplayData`
+- Returns JSON dictionary mapping CSS class names to attribute updates
+- Updates SVG `g` and `path` tags, `select` tags for controllers, `div` elements for non-SVG displays
+
+For complete implementation details of the polling system, CSS class application, and troubleshooting, see [Entity Status Display](entity-status-display.md).
+
+### JavaScript Conventions
+
+1. **Module Pattern**: Use revealing module pattern for organization
+2. **jQuery Usage**: Use `$` prefix for jQuery objects
+3. **Event Delegation**: Use delegated events for dynamic content
+
+Example:
+```javascript
+var MyModule = (function() {
+ var privateVar = 'value';
+
+ function init() {
+ // Delegated event handling
+ $(document).on('click', '.dynamic-button', handleClick);
+ }
+
+ function handleClick(e) {
+ e.preventDefault();
+ var $button = $(e.currentTarget);
+ // Handle click
+ }
+
+ return {
+ init: init
+ };
+})();
+
+$(document).ready(function() {
+ MyModule.init();
+});
+```
+
+## CSS Standards
+
+**CSS in Templates**: We should never put CSS in templates, or otherwise have inline `<style>` blocks. All CSS should be put in a file in the `src/hi/static/css` directory.
+
+**Main CSS**: Use `src/hi/static/css/main.css` for most needs. Some special-purpose, high-volume CSS modules may justify creating a nw CSS file.
+
+**No Emojis**: No Emojis anywhere: not in user-facing messaging, not in log messages, not in the comments.
+
+### Core Technologies
+- Bootstrap 4 for UI components
+
+**Django Pipeline**: We use the Django pipeline library for injecting minimized, cache-busting CSS (and javascript) into pages. Any new files must be defined in `src/hi/settings/base.py`.
+
+### Responsive Design Principles
+
+The predominant use of this app is on a tablet in landscape mode with a touch screen. Secondary usage is laptop or desktop. For mobile phones, we only need to render well enough to be usable in landscape mode.
+
+### CSS Organization
+
+1. **Component-based**: Organize CSS by component, not by page
+2. **BEM Naming**: Use BEM methodology for class naming when appropriate
+3. **Bootstrap Extensions**: Extend Bootstrap classes rather than overriding
+4. **Custom Properties**: Use CSS custom properties for theming
+
+Example:
+```css
+/* Component: Alert Card */
+.alert-card {
+ /* Base styles */
+}
+
+.alert-card__header {
+ /* Header specific styles */
+}
+
+.alert-card--critical {
+ /* Modifier for critical alerts */
+}
+```
+
+## SVG Manipulation
+
+### Status Display System
+
+Entity SVG appearance changes based on sensor readings:
+
+1. **CSS Class Mapping**: Normalized sensor values added as CSS class names
+2. **Predefined Icons**: Alternative SVG icons for well-known sensor values
+3. **Color Schemes**: Map sensor values to SVG fill, stroke, and opacity attributes
+
+### Value Decaying
+
+For motion/presence sensors, visual states decay over time:
+- Active (red) → Recent (orange) → Past (yellow) → Idle (green/gray)
+- Creates intuitive visual "cooling off" effect
+- Centralized in `StatusDisplayData` and `StatusDisplayManager` classes
+
+### Multiple Sensors Priority
+
+- At most one entity state determines visual representation
+- Priority configured per LocationView via `location_view_type`
+- Different priorities for different views (e.g., climate vs security)
+
+## View Testing
+
+### Testing Patterns by View Type
+
+#### Synchronous HTML Views
+```python
+def test_location_view_renders_correctly(self):
+ location = Location.objects.create(name='Test Location')
+ url = reverse('location_detail', kwargs={'location_id': location.id})
+ response = self.client.get(url)
+
+ self.assertSuccessResponse(response)
+ self.assertHtmlResponse(response)
+ self.assertTemplateRendered(response, 'location/detail.html')
+ self.assertEqual(response.context['location'], location)
+```
+
+#### Asynchronous HTML Views (AJAX)
+```python
+def test_async_html_view_with_ajax_header(self):
+ url = reverse('console_sensor_view', kwargs={'sensor_id': 1})
+ response = self.async_get(url) # Includes HTTP_X_REQUESTED_WITH header
+
+ self.assertSuccessResponse(response)
+ self.assertJsonResponse(response)
+ data = response.json()
+ self.assertIn('insert_map', data)
+```
+
+#### Dual-Mode Views
+```python
+def test_modal_view_sync_request(self):
+ url = reverse('weather_current_conditions_details')
+ response = self.client.get(url)
+
+ self.assertSuccessResponse(response)
+ self.assertHtmlResponse(response)
+ self.assertTemplateRendered(response, 'pages/main_default.html')
+ self.assertTemplateRendered(response, 'weather/modals/conditions_details.html')
+
+def test_modal_view_async_request(self):
+ url = reverse('weather_current_conditions_details')
+ response = self.async_get(url)
+
+ self.assertSuccessResponse(response)
+ self.assertJsonResponse(response)
+ data = response.json()
+ self.assertIn('modal', data)
+```
+
+### View Testing Guidelines
+
+**DO:**
+- Use `reverse()` with URL names instead of hardcoded URLs
+- Use `async_get()`, `async_post()` for AJAX requests
+- Test status codes, response types, and templates separately
+- Use real database operations and test data setup
+- Test actual request/response flows
+
+**DON'T:**
+- Use hardcoded URL strings
+- Use regular `client.get()` for AJAX requests
+- Mix status code, response type, and template assertions
+- Test template content text that may change
+- Mock internal Django components
+
+## Related Documentation
+- Icon system: [Icon System](icon-system.md)
+- Style guidelines: [Style Guidelines](style-guidelines.md)
+- Template conventions: [Template Conventions](template-conventions.md)
+- UI testing: [UI Testing](ui-testing.md)
+- Testing patterns: [Testing Patterns](../testing/testing-patterns.md)
diff --git a/docs/dev/frontend/icon-system.md b/docs/dev/frontend/icon-system.md
new file mode 100644
index 00000000..46e7ad7b
--- /dev/null
+++ b/docs/dev/frontend/icon-system.md
@@ -0,0 +1,268 @@
+# Icon System
+
+## Icon System Overview
+
+Use the standardized `{% icon %}` template tag. See `hi/apps/common/templatetags/icons.py` for implementation details and parameters.
+
+## UX Principles for Icon Usage
+
+### Primary Value
+Icons provide faster recognition, universal language, space efficiency, and visual hierarchy.
+
+### ALWAYS Add Icons When
+
+- **Universal Actions**: Add (+), Delete (trash), Edit (pencil), Save (checkmark), Cancel (×)
+- **Navigation**: Back/Forward arrows, Up/Down, Expand/Collapse
+- **Media Controls**: Play, Pause, Video, Camera
+- **Status/Feedback**: Success, Warning, Error, Info
+
+### Key Principle
+Focus on **ACTION TYPE** (add, delete, edit), not object specificity. "Add Item" and "Add Rule" both get the same + icon because they're both "add" actions.
+
+## Implementation Requirements
+
+- Always include `{% load icons %}` at top of templates
+- Icons should supplement text, not replace it for important actions
+- Use semantic size and color parameters when available
+- Include appropriate ARIA labels for accessibility
+- Maintain consistency: same action = same icon across the application
+
+## Template Usage Examples
+
+### Basic Icon Usage
+
+```django
+{% load icons %}
+
+<!-- Primary action with icon -->
+<button class="btn btn-primary">
+ {% icon "plus" size="sm" css_class="hi-icon-left" %}
+ Add New Rule
+</button>
+
+<!-- Edit action -->
+<a class="btn btn-secondary" href="/edit/">
+ {% icon "edit" size="sm" css_class="hi-icon-left" %}
+ Edit
+</a>
+
+<!-- Save/Submit action -->
+<button class="btn btn-success" type="submit">
+ {% icon "save" size="sm" css_class="hi-icon-left" %}
+ Save Changes
+</button>
+
+<!-- Cancel action -->
+<a class="btn btn-tertiary" href="#" data-dismiss="modal">
+ {% icon "cancel" size="sm" css_class="hi-icon-left" %}
+ Cancel
+</a>
+```
+
+### Icon-Only Actions
+
+Use for space-constrained areas with proper accessibility:
+
+```django
+<!-- Delete action - icon-only for space constraints -->
+<button class="btn btn-danger btn-sm" aria-label="Delete item">
+ {% icon "delete" size="sm" %}
+</button>
+
+<!-- Modal close - icon-only (universal convention) -->
+<button type="button" class="close" data-dismiss="modal" aria-label="Close">
+ {% icon "close" size="sm" %}
+</button>
+
+<!-- Toolbar actions -->
+<div class="btn-group" role="group">
+ <button type="button" class="btn btn-outline-secondary" aria-label="Bold">
+ {% icon "bold" size="sm" %}
+ </button>
+ <button type="button" class="btn btn-outline-secondary" aria-label="Italic">
+ {% icon "italic" size="sm" %}
+ </button>
+ <button type="button" class="btn btn-outline-secondary" aria-label="Underline">
+ {% icon "underline" size="sm" %}
+ </button>
+</div>
+```
+
+### Status and Feedback Icons
+
+```django
+<!-- Success message -->
+<div class="alert alert-success">
+ {% icon "check-circle" size="sm" css_class="hi-icon-left" %}
+ Operation completed successfully!
+</div>
+
+<!-- Warning message -->
+<div class="alert alert-warning">
+ {% icon "exclamation-triangle" size="sm" css_class="hi-icon-left" %}
+ Please review your settings before continuing.
+</div>
+
+<!-- Error message -->
+<div class="alert alert-danger">
+ {% icon "times-circle" size="sm" css_class="hi-icon-left" %}
+ An error occurred while processing your request.
+</div>
+
+<!-- Info message -->
+<div class="alert alert-info">
+ {% icon "info-circle" size="sm" css_class="hi-icon-left" %}
+ This feature is currently in beta.
+</div>
+```
+
+### Navigation Icons
+
+```django
+<!-- Breadcrumb navigation -->
+<nav aria-label="breadcrumb">
+ <ol class="breadcrumb">
+ <li class="breadcrumb-item">
+ <a href="{% url 'home' %}">
+ {% icon "home" size="sm" css_class="hi-icon-left" %}
+ Home
+ </a>
+ </li>
+ <li class="breadcrumb-item">
+ <a href="{% url 'entities' %}">Entities</a>
+ </li>
+ <li class="breadcrumb-item active">Edit Entity</li>
+ </ol>
+</nav>
+
+<!-- Back button -->
+<a href="{{ back_url }}" class="btn btn-secondary">
+ {% icon "arrow-left" size="sm" css_class="hi-icon-left" %}
+ Back
+</a>
+
+<!-- Pagination -->
+<nav>
+ <ul class="pagination">
+ <li class="page-item">
+ <a class="page-link" href="?page={{ page.previous_page_number }}">
+ {% icon "chevron-left" size="sm" %}
+ Previous
+ </a>
+ </li>
+ <li class="page-item active">
+ <span class="page-link">{{ page.number }}</span>
+ </li>
+ <li class="page-item">
+ <a class="page-link" href="?page={{ page.next_page_number }}">
+ Next
+ {% icon "chevron-right" size="sm" %}
+ </a>
+ </li>
+ </ul>
+</nav>
+```
+
+## Icon Parameters
+
+### Size Options
+- `xs` - Extra small (12px)
+- `sm` - Small (16px) - **Most common**
+- `md` - Medium (20px) - Default
+- `lg` - Large (24px)
+- `xl` - Extra large (32px)
+
+### CSS Classes
+- `hi-icon-left` - Icon positioned to the left of text
+- `hi-icon-right` - Icon positioned to the right of text
+- `hi-icon-only` - Icon without accompanying text
+- `hi-icon-spin` - Spinning animation for loading states
+
+### Color Options
+When available through the icon system:
+- `text-primary` - Primary theme color
+- `text-success` - Success/positive actions
+- `text-warning` - Warning/caution
+- `text-danger` - Danger/destructive actions
+- `text-muted` - Subtle/disabled state
+
+## Accessibility Considerations
+
+### ARIA Labels
+
+Always provide ARIA labels for icon-only buttons:
+
+```django
+<button class="btn btn-primary" aria-label="Edit entity settings">
+ {% icon "edit" size="sm" %}
+</button>
+```
+
+### Screen Reader Support
+
+For decorative icons, use `aria-hidden="true"`:
+
+```django
+<h2>
+ {% icon "user" size="sm" aria_hidden="true" %}
+ User Profile
+</h2>
+```
+
+### Focus Indicators
+
+Ensure icon buttons have visible focus indicators:
+
+```css
+.btn:focus {
+ outline: 2px solid var(--primary);
+ outline-offset: 2px;
+}
+```
+
+## Available Icons
+
+Common icons available in the system (see `hi/apps/common/templatetags/icons.py` for complete list):
+
+### Actions
+- `plus` - Add/Create
+- `edit` / `pencil` - Edit/Modify
+- `delete` / `trash` - Delete/Remove
+- `save` / `check` - Save/Confirm
+- `cancel` / `times` - Cancel/Close
+- `copy` - Duplicate
+- `download` - Export/Download
+- `upload` - Import/Upload
+
+### Navigation
+- `home` - Home page
+- `arrow-left` / `arrow-right` - Back/Forward
+- `chevron-left` / `chevron-right` - Previous/Next
+- `arrow-up` / `arrow-down` - Up/Down
+- `external-link` - External links
+
+### Status/Feedback
+- `check-circle` - Success
+- `exclamation-triangle` - Warning
+- `times-circle` - Error
+- `info-circle` - Information
+- `question-circle` - Help
+
+### Media
+- `play` - Play action
+- `pause` - Pause action
+- `video` - Video content
+- `camera` - Camera/Photo
+
+### UI Elements
+- `search` - Search functionality
+- `filter` - Filter/Sort
+- `settings` / `cog` - Configuration
+- `user` - User/Profile
+- `list` - List view
+- `grid` - Grid view
+
+## Related Documentation
+- Frontend guidelines: [Frontend Guidelines](frontend-guidelines.md)
+- Style guidelines: [Style Guidelines](style-guidelines.md)
+- Template conventions: [Template Conventions](template-conventions.md)
\ No newline at end of file
diff --git a/docs/dev/frontend/style-guidelines.md b/docs/dev/frontend/style-guidelines.md
new file mode 100644
index 00000000..e3d6c7dd
--- /dev/null
+++ b/docs/dev/frontend/style-guidelines.md
@@ -0,0 +1,325 @@
+# Style Guidelines
+
+## Responsiveness
+
+The predominant use of this app is in a tablet in landscape mode with a touch screen. Secondary usage would be a laptop or desktop. For mobile (phone) devices, we only need for it to render well enough to be usable in the phone's landscape mode. We can assume that we do not have to support very narrow widths of a phone in portrait mode.
+
+### Breakpoint Strategy
+
+```scss
+// Bootstrap 4 breakpoints we use
+// Small devices (landscape phones, 576px and up)
+@media (min-width: 576px) { ... }
+
+// Medium devices (tablets, 768px and up) - PRIMARY TARGET
+@media (min-width: 768px) { ... }
+
+// Large devices (desktops, 992px and up)
+@media (min-width: 992px) { ... }
+
+// Extra large devices (large desktops, 1200px and up)
+@media (min-width: 1200px) { ... }
+```
+
+### Touch-Friendly Design
+
+1. **Minimum Touch Target**: 44x44px for all interactive elements
+2. **Spacing**: Adequate spacing between clickable elements
+3. **Hover States**: Don't rely on hover - use click/tap interactions
+4. **Gestures**: Support standard touch gestures (swipe, pinch-zoom for SVGs)
+
+## Color System
+
+### Status Colors
+
+Consistent color usage for entity states:
+
+```css
+:root {
+ /* Status colors following traffic light metaphor */
+ --status-active: #dc3545; /* Red - Active/Alert */
+ --status-recent: #fd7e14; /* Orange - Recently active */
+ --status-past: #ffc107; /* Yellow - Past activity */
+ --status-idle: #28a745; /* Green - Idle/Safe */
+ --status-unknown: #6c757d; /* Gray - Unknown/Offline */
+
+ /* Alert levels */
+ --alert-critical: #dc3545; /* Red */
+ --alert-warning: #ffc107; /* Yellow */
+ --alert-info: #17a2b8; /* Cyan */
+ --alert-success: #28a745; /* Green */
+}
+```
+
+### Theme Variables
+
+```css
+:root {
+ /* Primary palette */
+ --primary: #007bff;
+ --secondary: #6c757d;
+ --success: #28a745;
+ --info: #17a2b8;
+ --warning: #ffc107;
+ --danger: #dc3545;
+
+ /* UI elements */
+ --border-color: #dee2e6;
+ --shadow: 0 0.125rem 0.25rem rgba(0,0,0,0.075);
+ --shadow-lg: 0 1rem 3rem rgba(0,0,0,0.175);
+}
+```
+
+## Component Styling
+
+### Cards and Panels
+
+```css
+.hi-card {
+ background: white;
+ border: 1px solid var(--border-color);
+ border-radius: 0.25rem;
+ box-shadow: var(--shadow);
+ padding: 1rem;
+ margin-bottom: 1rem;
+}
+
+.hi-card--clickable {
+ cursor: pointer;
+ transition: box-shadow 0.2s;
+}
+
+.hi-card--clickable:hover {
+ box-shadow: var(--shadow-lg);
+}
+```
+
+### Buttons
+
+Extend Bootstrap buttons with consistent icon usage:
+
+```css
+.btn {
+ display: inline-flex;
+ align-items: center;
+ min-height: 44px; /* Touch-friendly */
+ padding: 0.5rem 1rem;
+}
+
+.hi-icon-left {
+ margin-right: 0.5rem;
+}
+
+.hi-icon-right {
+ margin-left: 0.5rem;
+}
+```
+
+### Forms
+
+Touch-optimized form controls:
+
+```css
+.form-control {
+ min-height: 44px;
+ font-size: 16px; /* Prevents zoom on iOS */
+}
+
+.form-group {
+ margin-bottom: 1.5rem; /* More spacing for touch */
+}
+
+select.form-control {
+ padding-right: 2rem; /* Room for dropdown arrow */
+}
+```
+
+## SVG Styling
+
+### Entity State Visualization
+
+```css
+/* Base entity styling */
+.entity-svg {
+ transition: fill 0.3s, stroke 0.3s, opacity 0.3s;
+}
+
+/* State-based styling */
+.entity-svg.state-active {
+ fill: var(--status-active);
+ fill-opacity: 0.8;
+}
+
+.entity-svg.state-recent {
+ fill: var(--status-recent);
+ fill-opacity: 0.6;
+}
+
+.entity-svg.state-past {
+ fill: var(--status-past);
+ fill-opacity: 0.4;
+}
+
+.entity-svg.state-idle {
+ fill: var(--status-idle);
+ fill-opacity: 0.3;
+}
+```
+
+### Interactive SVG Elements
+
+```css
+.entity-clickable {
+ cursor: pointer;
+}
+
+.entity-clickable:hover {
+ stroke: var(--primary);
+ stroke-width: 2;
+}
+
+.entity-selected {
+ stroke: var(--primary);
+ stroke-width: 3;
+ stroke-dasharray: 5,5;
+}
+```
+
+## Layout Patterns
+
+### Grid System
+
+Use Bootstrap's grid with tablet-first approach:
+
+```html
+<!-- Tablet-optimized layout -->
+<div class="row">
+ <div class="col-md-8">
+ <!-- Main content - larger on tablet -->
+ </div>
+ <div class="col-md-4">
+ <!-- Sidebar - narrower on tablet -->
+ </div>
+</div>
+```
+
+### Flex Utilities
+
+Use flexbox for component layouts:
+
+```css
+.hi-toolbar {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: 0.5rem;
+ background: #f8f9fa;
+ border-bottom: 1px solid var(--border-color);
+}
+
+.hi-toolbar__actions {
+ display: flex;
+ gap: 0.5rem;
+}
+```
+
+## Animation and Transitions
+
+### Performance Considerations
+
+```css
+/* Use transform and opacity for smooth animations */
+.modal {
+ transition: opacity 0.3s, transform 0.3s;
+}
+
+.modal.show {
+ opacity: 1;
+ transform: translateY(0);
+}
+
+/* Avoid animating expensive properties */
+/* Bad: transition: all 0.3s; */
+/* Good: transition: opacity 0.3s, transform 0.3s; */
+```
+
+### Loading States
+
+```css
+.loading-spinner {
+ display: inline-block;
+ width: 1rem;
+ height: 1rem;
+ border: 2px solid #f3f3f3;
+ border-top: 2px solid var(--primary);
+ border-radius: 50%;
+ animation: spin 1s linear infinite;
+}
+
+@keyframes spin {
+ 0% { transform: rotate(0deg); }
+ 100% { transform: rotate(360deg); }
+}
+```
+
+## Accessibility
+
+### Focus Indicators
+
+```css
+/* Visible focus for keyboard navigation */
+:focus {
+ outline: 2px solid var(--primary);
+ outline-offset: 2px;
+}
+
+/* Remove outline for mouse users */
+:focus:not(:focus-visible) {
+ outline: none;
+}
+```
+
+### High Contrast Support
+
+```css
+@media (prefers-contrast: high) {
+ :root {
+ --border-color: #000;
+ --shadow: 0 0 0 1px #000;
+ }
+
+ .btn {
+ border: 2px solid currentColor;
+ }
+}
+```
+
+## Print Styles
+
+```css
+@media print {
+ /* Hide navigation and controls */
+ .hi-toolbar,
+ .hi-sidebar,
+ .btn-group {
+ display: none !important;
+ }
+
+ /* Ensure content fits on page */
+ .hi-main-content {
+ width: 100%;
+ margin: 0;
+ }
+
+ /* Avoid page breaks in cards */
+ .hi-card {
+ page-break-inside: avoid;
+ }
+}
+```
+
+## Related Documentation
+- Icon system: [Icon System](icon-system.md)
+- Frontend guidelines: [Frontend Guidelines](frontend-guidelines.md)
+- Template conventions: [Template Conventions](template-conventions.md)
+- UI testing: [UI Testing](ui-testing.md)
\ No newline at end of file
diff --git a/docs/dev/frontend/svg-coordinate-operations.md b/docs/dev/frontend/svg-coordinate-operations.md
new file mode 100644
index 00000000..3cc0a3be
--- /dev/null
+++ b/docs/dev/frontend/svg-coordinate-operations.md
@@ -0,0 +1,3031 @@
+# SVG Coordinate Operations
+
+## Quick Reference
+
+### Common Tasks
+- **Convert SVG to screen coords** → [Use coordinate transform](#screen-position-calculation) → `calculate_entity_position()`
+- **Handle mouse clicks** → [Screen to SVG conversion](#interactive-coordinate-conversion) → `screenToSvgCoordinates()`
+- **Implement zoom controls** → [Viewport controller](#zoom-and-pan-operations) → `SvgViewportController`
+- **Position entities dynamically** → [Entity positioning](#entity-positioning-and-scaling) → `updateEntityPosition()`
+- **Debug coordinate issues** → [Check coordinate systems](#coordinate-system-types) → Verify SVG vs screen vs viewport
+
+### Key JavaScript Classes
+- **`SvgCoordinateTransform`**: Converts between coordinate systems
+- **`SvgInteractionHandler`**: Handles mouse events and SVG interactions
+- **`SvgViewportController`**: Manages zoom, pan, and viewport transforms
+- **`EntityPositionManager`**: Updates entity positions based on viewport
+
+### Quick Fixes
+| Problem | Solution | Location |
+|---------|----------|----------|
+| Click detection wrong | Check coordinate conversion | [Interactive Coordinate](#interactive-coordinate-conversion) |
+| Entity positions wrong | Verify viewBox parsing | [Screen Position](#screen-position-calculation) |
+| Zoom not working | Initialize viewport controller | [Zoom Operations](#zoom-and-pan-operations) |
+| Performance issues | Use requestAnimationFrame | [Performance](#efficient-coordinate-calculations) |
+
+### Coordinate System Quick Guide
+```
+Mouse Click (screen pixels)
+ ↓ getBoundingClientRect()
+SVG Viewport Coordinates
+ ↓ getScreenCTM().inverse()
+SVG Document Coordinates
+ ↓ viewBox transformation
+Entity Local Coordinates
+```
+
+### Common Coordinate Conversions
+- **Screen → SVG**: `element.createSVGPoint()` + `getScreenCTM().inverse()`
+- **SVG → Screen**: `(svg_coord - viewbox_origin) * scale_factor`
+- **Viewport → Entity**: Apply entity transform matrix
+
+
+## Real-World Workflow Examples
+
+### Workflow 1: Implementing Click-to-Details for Location Entities
+
+**Scenario**: Users should be able to click on any entity in a location view to open a details modal with current status and controls.
+
+**Complete Implementation:**
+
+1. **Set Up SVG Event Handling** ([Interactive Coordinate Conversion](#interactive-coordinate-conversion))
+ ```javascript
+ class EntityClickHandler {
+ constructor(svgElement) {
+ this.svgElement = svgElement;
+ this.setupEventListeners();
+ }
+
+ setupEventListeners() {
+ this.svgElement.addEventListener('click', (event) => {
+ const entityElement = event.target.closest('[data-entity-id]');
+ if (entityElement) {
+ const entityId = entityElement.getAttribute('data-entity-id');
+ this.handleEntityClick(event, entityId);
+ }
+ });
+ }
+
+ handleEntityClick(event, entityId) {
+ // Convert screen click to SVG coordinates for context
+ const svgCoords = this.screenToSvgCoordinates(event.clientX, event.clientY);
+
+ // Open entity details modal
+ this.openEntityModal(entityId, svgCoords);
+ }
+
+ screenToSvgCoordinates(screenX, screenY) {
+ const rect = this.svgElement.getBoundingClientRect();
+ const svgPoint = this.svgElement.createSVGPoint();
+ svgPoint.x = screenX - rect.left;
+ svgPoint.y = screenY - rect.top;
+
+ const ctm = this.svgElement.getScreenCTM().inverse();
+ return svgPoint.matrixTransform(ctm);
+ }
+ }
+ ```
+
+2. **Template Setup for Clickable Entities** ([Template Integration](#template-integration))
+ ```django
+ <!-- Ensure all entities have proper data attributes -->
+ <svg id="location-svg" viewBox="0 0 1000 800">
+ <g id="main-group">
+ <!-- Icon entities -->
+ {% for entity in icon_entities %}
+ <g class="entity-group" data-entity-id="{{ entity.id }}" data-entity-name="{{ entity.name }}">
+ <use href="#icon-{{ entity.entity_type.name.lower }}"
+ transform="translate({{ entity.position.x }}, {{ entity.position.y }})"/>
+ </g>
+ {% endfor %}
+
+ <!-- Path entities -->
+ {% for entity in path_entities %}
+ <path class="entity-path"
+ data-entity-id="{{ entity.id }}"
+ data-entity-name="{{ entity.name }}"
+ d="{{ entity.path.svg_path }}"/>
+ {% endfor %}
+ </g>
+ </svg>
+ ```
+
+3. **Handle Edge Cases** ([Troubleshooting - Click Detection](#click-detection-not-working))
+ ```javascript
+ class RobustEntityClickHandler extends EntityClickHandler {
+ handleEntityClick(event, entityId) {
+ // Prevent event bubbling issues
+ event.stopPropagation();
+
+ // Validate entity exists
+ if (!this.validateEntity(entityId)) {
+ console.warn('Invalid entity clicked:', entityId);
+ return;
+ }
+
+ // Handle coordinate conversion errors
+ try {
+ const svgCoords = this.screenToSvgCoordinates(event.clientX, event.clientY);
+ this.openEntityModal(entityId, svgCoords);
+ } catch (error) {
+ console.error('Coordinate conversion failed:', error);
+ // Fallback: open modal without coordinate context
+ this.openEntityModal(entityId, null);
+ }
+ }
+
+ validateEntity(entityId) {
+ // Check if entity element still exists
+ return document.querySelector(`[data-entity-id="${entityId}"]`) !== null;
+ }
+ }
+ ```
+
+4. **Initialize Click Handling** ([Template Integration](#template-integration))
+ ```javascript
+ // Initialize when DOM is ready
+ document.addEventListener('DOMContentLoaded', function() {
+ const locationSvg = document.getElementById('location-svg');
+ if (locationSvg) {
+ window.entityClickHandler = new RobustEntityClickHandler(locationSvg);
+ console.log('Entity click handling initialized');
+ }
+ });
+ ```
+
+**Expected Result**: Clicking any entity opens a details modal, with reliable coordinate conversion and error handling.
+
+---
+
+### Workflow 2: Implementing Zoom and Pan Controls
+
+**Scenario**: Large location views need zoom and pan functionality for better navigation, especially on mobile devices.
+
+**Implementation Process:**
+
+1. **Create Viewport Controller** ([Zoom and Pan Operations](#zoom-and-pan-operations))
+ ```javascript
+ class LocationViewportController {
+ constructor(svgElement) {
+ this.svgElement = svgElement;
+ this.mainGroup = svgElement.querySelector('#main-group');
+ this.currentZoom = 1.0;
+ this.currentPan = { x: 0, y: 0 };
+ this.isDragging = false;
+ this.lastPanPoint = null;
+
+ this.setupControls();
+ this.setupMouseHandling();
+ this.setupTouchHandling();
+ }
+
+ setupControls() {
+ // Create zoom control buttons
+ const controlsHtml = `
+ <div class="viewport-controls">
+ <button id="zoom-in" class="btn btn-sm btn-outline-primary">+</button>
+ <button id="zoom-out" class="btn btn-sm btn-outline-primary">−</button>
+ <button id="zoom-fit" class="btn btn-sm btn-outline-secondary">Fit</button>
+ </div>
+ `;
+
+ this.svgElement.parentElement.insertAdjacentHTML('beforeend', controlsHtml);
+
+ // Attach event listeners
+ document.getElementById('zoom-in').addEventListener('click', () => this.zoomIn());
+ document.getElementById('zoom-out').addEventListener('click', () => this.zoomOut());
+ document.getElementById('zoom-fit').addEventListener('click', () => this.zoomToFit());
+ }
+ ```
+
+2. **Implement Zoom Functions** ([Zoom Operations](#zoom-and-pan-operations))
+ ```javascript
+ zoomIn(factor = 1.2) {
+ this.currentZoom = Math.min(this.currentZoom * factor, 5.0); // Max 5x zoom
+ this.applyTransform();
+ }
+
+ zoomOut(factor = 0.8) {
+ this.currentZoom = Math.max(this.currentZoom * factor, 0.1); // Min 0.1x zoom
+ this.applyTransform();
+ }
+
+ zoomToFit() {
+ // Calculate bounding box of all entities
+ const entities = this.svgElement.querySelectorAll('[data-entity-id]');
+ if (entities.length === 0) return;
+
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
+
+ entities.forEach(entity => {
+ const bbox = entity.getBBox();
+ minX = Math.min(minX, bbox.x);
+ minY = Math.min(minY, bbox.y);
+ maxX = Math.max(maxX, bbox.x + bbox.width);
+ maxY = Math.max(maxY, bbox.y + bbox.height);
+ });
+
+ // Add padding
+ const padding = 50;
+ const contentWidth = maxX - minX + (padding * 2);
+ const contentHeight = maxY - minY + (padding * 2);
+
+ // Calculate zoom to fit
+ const svgRect = this.svgElement.getBoundingClientRect();
+ const scaleX = svgRect.width / contentWidth;
+ const scaleY = svgRect.height / contentHeight;
+ this.currentZoom = Math.min(scaleX, scaleY);
+
+ // Center the content
+ this.currentPan = {
+ x: -(minX - padding) * this.currentZoom,
+ y: -(minY - padding) * this.currentZoom
+ };
+
+ this.applyTransform();
+ }
+ ```
+
+3. **Add Pan Support** ([Pan Operations](#zoom-and-pan-operations))
+ ```javascript
+ setupMouseHandling() {
+ this.svgElement.addEventListener('mousedown', (event) => {
+ if (event.button === 1 || (event.button === 0 && event.ctrlKey)) {
+ this.startPan(event.clientX, event.clientY);
+ event.preventDefault();
+ }
+ });
+
+ document.addEventListener('mousemove', (event) => {
+ if (this.isDragging) {
+ this.updatePan(event.clientX, event.clientY);
+ }
+ });
+
+ document.addEventListener('mouseup', () => {
+ this.endPan();
+ });
+
+ // Mouse wheel zoom
+ this.svgElement.addEventListener('wheel', (event) => {
+ event.preventDefault();
+ const delta = event.deltaY > 0 ? 0.9 : 1.1;
+ this.zoomAt(event.clientX, event.clientY, delta);
+ });
+ }
+
+ startPan(clientX, clientY) {
+ this.isDragging = true;
+ this.lastPanPoint = { x: clientX, y: clientY };
+ this.svgElement.style.cursor = 'grabbing';
+ }
+
+ updatePan(clientX, clientY) {
+ if (!this.isDragging || !this.lastPanPoint) return;
+
+ const deltaX = clientX - this.lastPanPoint.x;
+ const deltaY = clientY - this.lastPanPoint.y;
+
+ this.currentPan.x += deltaX;
+ this.currentPan.y += deltaY;
+
+ this.lastPanPoint = { x: clientX, y: clientY };
+ this.applyTransform();
+ }
+ ```
+
+4. **Mobile Touch Support** ([Touch and Mobile Issues](#touch-and-mobile-issues))
+ ```javascript
+ setupTouchHandling() {
+ let lastTouchDistance = 0;
+
+ this.svgElement.addEventListener('touchstart', (event) => {
+ if (event.touches.length === 1) {
+ // Single touch - pan
+ const touch = event.touches[0];
+ this.startPan(touch.clientX, touch.clientY);
+ } else if (event.touches.length === 2) {
+ // Two finger - zoom
+ const touch1 = event.touches[0];
+ const touch2 = event.touches[1];
+ lastTouchDistance = this.getTouchDistance(touch1, touch2);
+ }
+ event.preventDefault();
+ });
+
+ this.svgElement.addEventListener('touchmove', (event) => {
+ if (event.touches.length === 1 && this.isDragging) {
+ const touch = event.touches[0];
+ this.updatePan(touch.clientX, touch.clientY);
+ } else if (event.touches.length === 2) {
+ const touch1 = event.touches[0];
+ const touch2 = event.touches[1];
+ const currentDistance = this.getTouchDistance(touch1, touch2);
+
+ if (lastTouchDistance > 0) {
+ const scale = currentDistance / lastTouchDistance;
+ this.currentZoom *= scale;
+ this.applyTransform();
+ }
+
+ lastTouchDistance = currentDistance;
+ }
+ event.preventDefault();
+ });
+ }
+ ```
+
+**Expected Result**: Smooth zoom and pan controls work on both desktop and mobile, with proper touch gesture support.
+
+---
+
+### Workflow 3: Dynamic Entity Positioning Based on Real-Time Data
+
+**Scenario**: Entities need to move to new positions based on real-time location updates (e.g., tracking mobile devices or vehicles).
+
+**Implementation Steps:**
+
+1. **Create Position Update Manager** ([Entity Positioning and Scaling](#entity-positioning-and-scaling))
+ ```javascript
+ class DynamicEntityPositioner {
+ constructor(svgElement) {
+ this.svgElement = svgElement;
+ this.positionCache = new Map();
+ this.animationQueue = [];
+ this.isAnimating = false;
+ }
+
+ updateEntityPosition(entityId, newPosition, animate = true) {
+ const element = this.svgElement.querySelector(`[data-entity-id="${entityId}"]`);
+ if (!element) {
+ console.warn('Entity not found for positioning:', entityId);
+ return;
+ }
+
+ const currentPos = this.getCurrentPosition(element);
+
+ if (animate) {
+ this.animateToPosition(element, currentPos, newPosition);
+ } else {
+ this.setPosition(element, newPosition);
+ }
+
+ // Cache new position
+ this.positionCache.set(entityId, newPosition);
+ }
+
+ getCurrentPosition(element) {
+ // Parse current transform to get position
+ const transform = element.getAttribute('transform') || '';
+ const match = transform.match(/translate\(([^,]+),\s*([^)]+)\)/);
+
+ if (match) {
+ return {
+ x: parseFloat(match[1]),
+ y: parseFloat(match[2])
+ };
+ }
+
+ return { x: 0, y: 0 };
+ }
+ ```
+
+2. **Implement Smooth Animation** ([Performance Considerations](#performance-considerations))
+ ```javascript
+ animateToPosition(element, fromPos, toPos, duration = 1000) {
+ const startTime = performance.now();
+
+ const animate = (currentTime) => {
+ const elapsed = currentTime - startTime;
+ const progress = Math.min(elapsed / duration, 1);
+
+ // Easing function (ease-out)
+ const easeOut = 1 - Math.pow(1 - progress, 3);
+
+ const currentX = fromPos.x + (toPos.x - fromPos.x) * easeOut;
+ const currentY = fromPos.y + (toPos.y - fromPos.y) * easeOut;
+
+ this.setPosition(element, { x: currentX, y: currentY });
+
+ if (progress < 1) {
+ requestAnimationFrame(animate);
+ }
+ };
+
+ requestAnimationFrame(animate);
+ }
+
+ setPosition(element, position) {
+ // Preserve other transform properties (scale, rotation)
+ const currentTransform = element.getAttribute('transform') || '';
+ const scale = this.extractTransformValue(currentTransform, 'scale') || 1;
+ const rotation = this.extractTransformValue(currentTransform, 'rotate') || 0;
+
+ const newTransform = `translate(${position.x}, ${position.y}) scale(${scale}) rotate(${rotation})`;
+ element.setAttribute('transform', newTransform);
+ }
+ ```
+
+3. **Handle Real-Time Updates** ([Performance - Batch Updates](#performance-issues))
+ ```javascript
+ processBatchPositionUpdates(positionUpdates) {
+ // Group updates to avoid excessive DOM manipulation
+ const batchSize = 10;
+ let currentBatch = 0;
+
+ const processBatch = () => {
+ const start = currentBatch * batchSize;
+ const end = Math.min(start + batchSize, positionUpdates.length);
+
+ for (let i = start; i < end; i++) {
+ const update = positionUpdates[i];
+ this.updateEntityPosition(update.entityId, update.position, update.animate);
+ }
+
+ currentBatch++;
+
+ if (end < positionUpdates.length) {
+ requestAnimationFrame(processBatch);
+ }
+ };
+
+ processBatch();
+ }
+ ```
+
+4. **Integration with Status Updates** ([Client-Server Integration](../entity-status-display.md#client-server-status-updates))
+ ```javascript
+ // Extend existing status polling to include position updates
+ class EnhancedStatusPoller extends StatusPoller {
+ constructor(svgElement) {
+ super();
+ this.positioner = new DynamicEntityPositioner(svgElement);
+ }
+
+ updateEntityStates(statusData) {
+ // Handle standard status updates
+ super.updateEntityStates(statusData);
+
+ // Handle position updates if included
+ if (statusData.positions) {
+ const positionUpdates = Object.entries(statusData.positions).map(
+ ([entityId, posData]) => ({
+ entityId,
+ position: posData.position,
+ animate: posData.animate !== false
+ })
+ );
+
+ this.positioner.processBatchPositionUpdates(positionUpdates);
+ }
+ }
+ }
+ ```
+
+**Expected Result**: Entities smoothly animate to new positions based on real-time data, with efficient batching and performance optimization.
+
+---
+
+### Workflow 4: Troubleshooting Coordinate Transformation Issues
+
+**Scenario**: After a template change, entity click detection stopped working, and zoom controls behave erratically.
+
+**Systematic Debugging:**
+
+1. **Diagnose Click Detection** ([Troubleshooting - Click Detection](#click-detection-not-working))
+ ```javascript
+ // Debug click detection step by step
+ function debugClickDetection(event) {
+ console.group('Click Detection Debug');
+
+ // 1. Check if event reaches handler
+ console.log('Click event:', event);
+ console.log('Click target:', event.target);
+
+ // 2. Check entity element selection
+ const entityElement = event.target.closest('[data-entity-id]');
+ console.log('Entity element found:', entityElement);
+
+ if (entityElement) {
+ console.log('Entity ID:', entityElement.getAttribute('data-entity-id'));
+ }
+
+ // 3. Test coordinate conversion
+ try {
+ const svgElement = document.getElementById('location-svg');
+ const handler = new SvgInteractionHandler(svgElement);
+ const svgCoords = handler.screenToSvgCoordinates(event.clientX, event.clientY);
+ console.log('SVG coordinates:', svgCoords);
+ } catch (error) {
+ console.error('Coordinate conversion failed:', error);
+ }
+
+ console.groupEnd();
+ }
+
+ // Temporarily attach debug handler
+ document.getElementById('location-svg').addEventListener('click', debugClickDetection);
+ ```
+
+2. **Check SVG Structure** ([Template Integration](#template-integration))
+ ```javascript
+ function validateSvgStructure() {
+ const svg = document.getElementById('location-svg');
+ console.group('SVG Structure Validation');
+
+ // Check required elements
+ console.log('SVG element:', svg);
+ console.log('Main group:', svg?.querySelector('#main-group'));
+ console.log('ViewBox:', svg?.getAttribute('viewBox'));
+ console.log('Entities with data-entity-id:', svg?.querySelectorAll('[data-entity-id]').length);
+
+ // Check for common issues
+ const entitiesWithoutIds = svg?.querySelectorAll('.entity-group:not([data-entity-id])');
+ if (entitiesWithoutIds?.length > 0) {
+ console.warn('Entities missing data-entity-id:', entitiesWithoutIds);
+ }
+
+ console.groupEnd();
+ }
+
+ validateSvgStructure();
+ ```
+
+3. **Test Coordinate Transformation Matrix** ([Troubleshooting - Transform Matrix](#entity-positions-incorrect))
+ ```javascript
+ function debugCoordinateTransformation() {
+ const svg = document.getElementById('location-svg');
+ console.group('Coordinate Transformation Debug');
+
+ try {
+ // Test SVG DOM APIs
+ console.log('createSVGPoint available:', typeof svg.createSVGPoint === 'function');
+ console.log('getScreenCTM available:', typeof svg.getScreenCTM === 'function');
+
+ // Test actual transformation
+ const ctm = svg.getScreenCTM();
+ console.log('Current CTM:', ctm);
+
+ if (ctm) {
+ console.log('CTM values:', {
+ a: ctm.a, b: ctm.b, c: ctm.c,
+ d: ctm.d, e: ctm.e, f: ctm.f
+ });
+
+ // Test point transformation
+ const testPoint = svg.createSVGPoint();
+ testPoint.x = 100;
+ testPoint.y = 100;
+
+ const transformedPoint = testPoint.matrixTransform(ctm.inverse());
+ console.log('Test coordinate transformation:', {
+ screen: { x: 100, y: 100 },
+ svg: { x: transformedPoint.x, y: transformedPoint.y }
+ });
+ }
+
+ } catch (error) {
+ console.error('Coordinate transformation error:', error);
+ }
+
+ console.groupEnd();
+ }
+
+ debugCoordinateTransformation();
+ ```
+
+4. **Fix Common Issues** ([Common Fixes](#click-detection-not-working))
+ ```javascript
+ // Fix missing data-entity-id attributes
+ function fixMissingDataAttributes() {
+ const entitiesWithoutIds = document.querySelectorAll('.entity-group:not([data-entity-id])');
+
+ entitiesWithoutIds.forEach((element, index) => {
+ // Generate temporary ID for debugging
+ const tempId = `temp-entity-${index}`;
+ element.setAttribute('data-entity-id', tempId);
+ console.warn(`Added temporary data-entity-id: ${tempId}`);
+ });
+ }
+
+ // Reset viewport transformation if corrupted
+ function resetViewportTransform() {
+ const mainGroup = document.querySelector('#main-group');
+ if (mainGroup) {
+ mainGroup.setAttribute('transform', 'translate(0,0) scale(1)');
+ console.log('Reset viewport transform to default');
+ }
+ }
+
+ // Apply fixes
+ fixMissingDataAttributes();
+ resetViewportTransform();
+ ```
+
+**Expected Result**: Systematic debugging identifies and resolves coordinate transformation issues, restoring full functionality.
+
+## Common Patterns Library
+
+### Standard Coordinate Transformation Classes
+
+#### Basic SVG Coordinate Transform
+```javascript
+// Standard class for coordinate system conversions
+class SvgCoordinateTransform {
+ constructor(svgElement) {
+ this.svgElement = svgElement;
+ this.viewBox = this.parseViewBox(svgElement.getAttribute('viewBox'));
+ }
+
+ parseViewBox(viewBoxStr) {
+ if (!viewBoxStr) return { x: 0, y: 0, width: 100, height: 100 };
+
+ const [x, y, width, height] = viewBoxStr.split(' ').map(Number);
+ return { x, y, width, height };
+ }
+
+ // Screen coordinates to SVG coordinates
+ screenToSvg(screenPoint) {
+ const rect = this.svgElement.getBoundingClientRect();
+ const svgPoint = this.svgElement.createSVGPoint();
+
+ svgPoint.x = screenPoint.x - rect.left;
+ svgPoint.y = screenPoint.y - rect.top;
+
+ return svgPoint.matrixTransform(
+ this.svgElement.getScreenCTM().inverse()
+ );
+ }
+
+ // SVG coordinates to screen coordinates
+ svgToScreen(svgPoint) {
+ const screenPoint = svgPoint.matrixTransform(
+ this.svgElement.getScreenCTM()
+ );
+
+ const rect = this.svgElement.getBoundingClientRect();
+ return {
+ x: screenPoint.x + rect.left,
+ y: screenPoint.y + rect.top
+ };
+ }
+
+ // Entity local coordinates to SVG coordinates
+ entityToSvg(entityCoord, transform) {
+ const matrix = this.parseTransform(transform);
+ return {
+ x: entityCoord.x * matrix.scaleX + matrix.translateX,
+ y: entityCoord.y * matrix.scaleY + matrix.translateY
+ };
+ }
+
+ parseTransform(transformStr) {
+ const translate = transformStr.match(/translate\(([^)]+)\)/);
+ const scale = transformStr.match(/scale\(([^)]+)\)/);
+ const rotate = transformStr.match(/rotate\(([^)]+)\)/);
+
+ let translateX = 0, translateY = 0, scaleX = 1, scaleY = 1, rotation = 0;
+
+ if (translate) {
+ [translateX, translateY] = translate[1].split(',').map(Number);
+ }
+
+ if (scale) {
+ const scaleValues = scale[1].split(',').map(Number);
+ scaleX = scaleValues[0];
+ scaleY = scaleValues[1] || scaleX;
+ }
+
+ if (rotate) {
+ rotation = Number(rotate[1]);
+ }
+
+ return { translateX, translateY, scaleX, scaleY, rotation };
+ }
+}
+```
+
+#### Standard SVG Interaction Handler
+```javascript
+// Standard class for handling SVG mouse and touch interactions
+class SvgInteractionHandler {
+ constructor(svgElement, options = {}) {
+ this.svgElement = svgElement;
+ this.coordinateTransform = new SvgCoordinateTransform(svgElement);
+ this.isInteracting = false;
+ this.lastInteractionPoint = null;
+
+ // Configuration options
+ this.options = {
+ enableClick: options.enableClick !== false,
+ enableDrag: options.enableDrag !== false,
+ clickThreshold: options.clickThreshold || 5,
+ ...options
+ };
+
+ this.bindEvents();
+ }
+
+ bindEvents() {
+ if (this.options.enableClick) {
+ this.svgElement.addEventListener('click', (e) => this.handleClick(e));
+ }
+
+ if (this.options.enableDrag) {
+ this.svgElement.addEventListener('mousedown', (e) => this.handleMouseDown(e));
+ document.addEventListener('mousemove', (e) => this.handleMouseMove(e));
+ document.addEventListener('mouseup', (e) => this.handleMouseUp(e));
+
+ // Touch events for mobile
+ this.svgElement.addEventListener('touchstart', (e) => this.handleTouchStart(e));
+ document.addEventListener('touchmove', (e) => this.handleTouchMove(e));
+ document.addEventListener('touchend', (e) => this.handleTouchEnd(e));
+ }
+ }
+
+ handleClick(event) {
+ const svgPoint = this.coordinateTransform.screenToSvg({
+ x: event.clientX,
+ y: event.clientY
+ });
+
+ const clickedElement = this.findEntityAt(svgPoint);
+ if (clickedElement) {
+ this.onEntityClick(clickedElement, svgPoint, event);
+ } else {
+ this.onBackgroundClick(svgPoint, event);
+ }
+ }
+
+ findEntityAt(svgPoint) {
+ // Find the topmost entity element at the given SVG coordinate
+ const elements = document.elementsFromPoint(
+ svgPoint.x, svgPoint.y
+ ).filter(el =>
+ el.closest('[data-entity-id]') &&
+ el.closest('svg') === this.svgElement
+ );
+
+ return elements.length > 0 ? elements[0].closest('[data-entity-id]') : null;
+ }
+
+ onEntityClick(entityElement, svgPoint, originalEvent) {
+ const entityId = entityElement.getAttribute('data-entity-id');
+ const entityType = entityElement.getAttribute('data-entity-type');
+
+ // Emit custom event
+ this.svgElement.dispatchEvent(new CustomEvent('entityClick', {
+ detail: {
+ entityId,
+ entityType,
+ svgCoordinates: svgPoint,
+ screenCoordinates: { x: originalEvent.clientX, y: originalEvent.clientY },
+ element: entityElement
+ }
+ }));
+ }
+
+ onBackgroundClick(svgPoint, originalEvent) {
+ this.svgElement.dispatchEvent(new CustomEvent('backgroundClick', {
+ detail: {
+ svgCoordinates: svgPoint,
+ screenCoordinates: { x: originalEvent.clientX, y: originalEvent.clientY }
+ }
+ }));
+ }
+
+ // Touch event handling
+ handleTouchStart(event) {
+ if (event.touches.length === 1) {
+ const touch = event.touches[0];
+ this.handleMouseDown({
+ clientX: touch.clientX,
+ clientY: touch.clientY,
+ target: event.target,
+ preventDefault: () => event.preventDefault()
+ });
+ }
+ }
+
+ handleTouchMove(event) {
+ if (event.touches.length === 1) {
+ const touch = event.touches[0];
+ this.handleMouseMove({
+ clientX: touch.clientX,
+ clientY: touch.clientY
+ });
+ }
+ }
+
+ handleTouchEnd(event) {
+ this.handleMouseUp({});
+ }
+}
+```
+
+#### Standard Viewport Controller
+```javascript
+// Standard class for managing SVG zoom and pan operations
+class SvgViewportController {
+ constructor(svgElement, options = {}) {
+ this.svgElement = svgElement;
+ this.currentTransform = { scale: 1, translateX: 0, translateY: 0 };
+ this.originalViewBox = this.parseViewBox(svgElement.getAttribute('viewBox'));
+
+ this.options = {
+ minScale: options.minScale || 0.1,
+ maxScale: options.maxScale || 10,
+ zoomSpeed: options.zoomSpeed || 0.1,
+ enablePan: options.enablePan !== false,
+ enableZoom: options.enableZoom !== false,
+ ...options
+ };
+
+ this.bindEvents();
+ }
+
+ parseViewBox(viewBoxStr) {
+ if (!viewBoxStr) return { x: 0, y: 0, width: 100, height: 100 };
+ const [x, y, width, height] = viewBoxStr.split(' ').map(Number);
+ return { x, y, width, height };
+ }
+
+ bindEvents() {
+ if (this.options.enableZoom) {
+ this.svgElement.addEventListener('wheel', (e) => this.handleWheel(e));
+ }
+
+ if (this.options.enablePan) {
+ let isPanning = false;
+ let startPoint = null;
+ let startTransform = null;
+
+ this.svgElement.addEventListener('mousedown', (e) => {
+ if (e.button === 1 || (e.button === 0 && e.ctrlKey)) { // Middle mouse or Ctrl+click
+ isPanning = true;
+ startPoint = { x: e.clientX, y: e.clientY };
+ startTransform = { ...this.currentTransform };
+ e.preventDefault();
+ }
+ });
+
+ document.addEventListener('mousemove', (e) => {
+ if (isPanning && startPoint) {
+ const dx = (e.clientX - startPoint.x) / this.currentTransform.scale;
+ const dy = (e.clientY - startPoint.y) / this.currentTransform.scale;
+
+ this.currentTransform.translateX = startTransform.translateX + dx;
+ this.currentTransform.translateY = startTransform.translateY + dy;
+
+ this.updateViewBox();
+ e.preventDefault();
+ }
+ });
+
+ document.addEventListener('mouseup', (e) => {
+ if (isPanning) {
+ isPanning = false;
+ startPoint = null;
+ startTransform = null;
+ }
+ });
+ }
+ }
+
+ handleWheel(event) {
+ event.preventDefault();
+
+ const rect = this.svgElement.getBoundingClientRect();
+ const centerX = (event.clientX - rect.left) / rect.width;
+ const centerY = (event.clientY - rect.top) / rect.height;
+
+ const scaleDelta = event.deltaY > 0 ?
+ (1 - this.options.zoomSpeed) :
+ (1 + this.options.zoomSpeed);
+
+ this.zoomAt(centerX, centerY, scaleDelta);
+ }
+
+ zoomAt(centerX, centerY, scaleDelta) {
+ const newScale = Math.max(
+ this.options.minScale,
+ Math.min(this.options.maxScale, this.currentTransform.scale * scaleDelta)
+ );
+
+ if (newScale !== this.currentTransform.scale) {
+ // Calculate new translation to keep zoom centered
+ const scaleChange = newScale / this.currentTransform.scale;
+
+ const viewBoxCenterX = this.originalViewBox.x + centerX * this.originalViewBox.width;
+ const viewBoxCenterY = this.originalViewBox.y + centerY * this.originalViewBox.height;
+
+ this.currentTransform.translateX = viewBoxCenterX -
+ (viewBoxCenterX - this.currentTransform.translateX) * scaleChange;
+ this.currentTransform.translateY = viewBoxCenterY -
+ (viewBoxCenterY - this.currentTransform.translateY) * scaleChange;
+
+ this.currentTransform.scale = newScale;
+ this.updateViewBox();
+ }
+ }
+
+ updateViewBox() {
+ const width = this.originalViewBox.width / this.currentTransform.scale;
+ const height = this.originalViewBox.height / this.currentTransform.scale;
+
+ const x = this.currentTransform.translateX - width / 2;
+ const y = this.currentTransform.translateY - height / 2;
+
+ this.svgElement.setAttribute('viewBox', `${x} ${y} ${width} ${height}`);
+
+ // Emit transform change event
+ this.svgElement.dispatchEvent(new CustomEvent('viewportChanged', {
+ detail: {
+ scale: this.currentTransform.scale,
+ translateX: this.currentTransform.translateX,
+ translateY: this.currentTransform.translateY,
+ viewBox: { x, y, width, height }
+ }
+ }));
+ }
+
+ // Public API methods
+ zoomIn() {
+ this.zoomAt(0.5, 0.5, 1 + this.options.zoomSpeed);
+ }
+
+ zoomOut() {
+ this.zoomAt(0.5, 0.5, 1 - this.options.zoomSpeed);
+ }
+
+ resetView() {
+ this.currentTransform = { scale: 1, translateX: 0, translateY: 0 };
+ this.svgElement.setAttribute('viewBox',
+ `${this.originalViewBox.x} ${this.originalViewBox.y} ${this.originalViewBox.width} ${this.originalViewBox.height}`
+ );
+ this.updateViewBox();
+ }
+
+ fitToContent() {
+ // Calculate bounding box of all visible entities
+ const entities = this.svgElement.querySelectorAll('[data-entity-id]');
+ if (entities.length === 0) return;
+
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
+
+ entities.forEach(entity => {
+ const bbox = entity.getBBox();
+ minX = Math.min(minX, bbox.x);
+ minY = Math.min(minY, bbox.y);
+ maxX = Math.max(maxX, bbox.x + bbox.width);
+ maxY = Math.max(maxY, bbox.y + bbox.height);
+ });
+
+ const padding = Math.min(maxX - minX, maxY - minY) * 0.1;
+ const contentWidth = maxX - minX + padding * 2;
+ const contentHeight = maxY - minY + padding * 2;
+
+ this.svgElement.setAttribute('viewBox',
+ `${minX - padding} ${minY - padding} ${contentWidth} ${contentHeight}`
+ );
+ }
+}
+```
+
+### Standard Entity Positioning Patterns
+
+#### Entity Position Manager
+```javascript
+// Standard class for managing entity positions and transforms
+class EntityPositionManager {
+ constructor(svgElement) {
+ this.svgElement = svgElement;
+ this.coordinateTransform = new SvgCoordinateTransform(svgElement);
+ }
+
+ updateEntityPosition(entityId, position, options = {}) {
+ const entityElement = this.svgElement.querySelector(
+ `[data-entity-id="${entityId}"]`
+ );
+
+ if (!entityElement) {
+ console.warn(`Entity ${entityId} not found in SVG`);
+ return;
+ }
+
+ const transform = this.buildTransform(position, options);
+ const targetElement = entityElement.querySelector('use, path') || entityElement;
+
+ if (options.animate) {
+ this.animateTransform(targetElement, transform, options.duration || 300);
+ } else {
+ targetElement.setAttribute('transform', transform);
+ }
+
+ // Update data attributes for tracking
+ entityElement.setAttribute('data-x', position.x);
+ entityElement.setAttribute('data-y', position.y);
+ if (position.scale) entityElement.setAttribute('data-scale', position.scale);
+ if (position.rotation) entityElement.setAttribute('data-rotation', position.rotation);
+ }
+
+ buildTransform(position, options = {}) {
+ const { x, y, scale = 1, rotation = 0 } = position;
+ const transforms = [];
+
+ transforms.push(`translate(${x}, ${y})`);
+
+ if (scale !== 1) {
+ transforms.push(`scale(${scale})`);
+ }
+
+ if (rotation !== 0) {
+ transforms.push(`rotate(${rotation})`);
+ }
+
+ return transforms.join(' ');
+ }
+
+ animateTransform(element, newTransform, duration) {
+ const currentTransform = element.getAttribute('transform') || '';
+
+ // Create animation element
+ const animateTransform = document.createElementNS(
+ 'http://www.w3.org/2000/svg',
+ 'animateTransform'
+ );
+
+ animateTransform.setAttribute('attributeName', 'transform');
+ animateTransform.setAttribute('attributeType', 'XML');
+ animateTransform.setAttribute('type', 'transform');
+ animateTransform.setAttribute('from', currentTransform);
+ animateTransform.setAttribute('to', newTransform);
+ animateTransform.setAttribute('dur', `${duration}ms`);
+ animateTransform.setAttribute('fill', 'freeze');
+
+ element.appendChild(animateTransform);
+
+ // Clean up animation after completion
+ setTimeout(() => {
+ element.setAttribute('transform', newTransform);
+ if (animateTransform.parentNode) {
+ animateTransform.parentNode.removeChild(animateTransform);
+ }
+ }, duration);
+ }
+
+ getEntityPosition(entityId) {
+ const entityElement = this.svgElement.querySelector(
+ `[data-entity-id="${entityId}"]`
+ );
+
+ if (!entityElement) return null;
+
+ return {
+ x: parseFloat(entityElement.getAttribute('data-x')) || 0,
+ y: parseFloat(entityElement.getAttribute('data-y')) || 0,
+ scale: parseFloat(entityElement.getAttribute('data-scale')) || 1,
+ rotation: parseFloat(entityElement.getAttribute('data-rotation')) || 0
+ };
+ }
+
+ moveEntity(entityId, deltaX, deltaY, options = {}) {
+ const currentPosition = this.getEntityPosition(entityId);
+ if (!currentPosition) return;
+
+ const newPosition = {
+ ...currentPosition,
+ x: currentPosition.x + deltaX,
+ y: currentPosition.y + deltaY
+ };
+
+ this.updateEntityPosition(entityId, newPosition, options);
+ }
+
+ scaleEntity(entityId, scaleFactor, options = {}) {
+ const currentPosition = this.getEntityPosition(entityId);
+ if (!currentPosition) return;
+
+ const newPosition = {
+ ...currentPosition,
+ scale: currentPosition.scale * scaleFactor
+ };
+
+ this.updateEntityPosition(entityId, newPosition, options);
+ }
+}
+```
+
+### Standard Template Integration Patterns
+
+#### Basic SVG Template Structure
+```django
+<!-- Standard SVG structure for location views -->
+<div class="location-view-container">
+ <svg id="location-svg"
+ class="location-view-svg"
+ viewBox="{{ viewbox.x }} {{ viewbox.y }} {{ viewbox.width }} {{ viewbox.height }}"
+ xmlns="http://www.w3.org/2000/svg">
+
+ <!-- Background layers -->
+ <defs>
+ <!-- Entity icon definitions -->
+ {% for entity_type in entity_types_with_icons %}
+ <symbol id="icon-{{ entity_type.name.lower }}"
+ viewBox="{{ entity_type.get_viewbox }}">
+ {% include entity_type.get_icon_template %}
+ </symbol>
+ {% endfor %}
+
+ <!-- Common patterns and gradients -->
+ <pattern id="grid-pattern" patternUnits="userSpaceOnUse" width="10" height="10">
+ <path d="M 10 0 L 0 0 0 10" fill="none" stroke="#e0e0e0" stroke-width="0.5"/>
+ </pattern>
+ </defs>
+
+ <!-- Background grid (optional) -->
+ {% if show_grid %}
+ <rect width="100%" height="100%" fill="url(#grid-pattern)"/>
+ {% endif %}
+
+ <!-- Floor plan background -->
+ {% if location.background_image %}
+ <image href="{{ location.background_image.url }}"
+ width="{{ viewbox.width }}"
+ height="{{ viewbox.height }}"/>
+ {% endif %}
+
+ <!-- Path-based entities (rooms, zones) -->
+ {% for entity in path_entities %}
+ <g class="entity-group"
+ data-entity-id="{{ entity.id }}"
+ data-entity-type="{{ entity.entity_type.name.lower }}">
+ <path class="entity-path {{ entity.get_status_css_classes|join:' ' }}"
+ d="{{ entity.path.svg_path }}"
+ style="{{ entity.get_path_styling }}"/>
+ </g>
+ {% endfor %}
+
+ <!-- Icon-based entities (sensors, devices) -->
+ {% for entity in positioned_entities %}
+ <g class="entity-group"
+ data-entity-id="{{ entity.id }}"
+ data-entity-type="{{ entity.entity_type.name.lower }}">
+ <use href="#icon-{{ entity.entity_type.name.lower }}"
+ class="entity-svg {{ entity.get_status_css_classes|join:' ' }}"
+ transform="translate({{ entity.position.x }}, {{ entity.position.y }})
+ scale({{ entity.position.scale|default:1.0 }})
+ rotate({{ entity.position.rotation|default:0 }})"/>
+ </g>
+ {% endfor %}
+
+ <!-- Overlay elements -->
+ <g class="overlay-group">
+ <!-- Selection indicators -->
+ <circle id="selection-indicator"
+ class="selection-circle"
+ r="25"
+ fill="none"
+ stroke="#007bff"
+ stroke-width="2"
+ style="display: none"/>
+
+ <!-- Temporary drawing elements -->
+ <g id="temp-drawings"></g>
+ </g>
+ </svg>
+
+ <!-- SVG Controls -->
+ <div class="svg-controls">
+ <button id="zoom-in" class="btn btn-sm btn-outline-secondary">
+ <i class="fas fa-search-plus"></i>
+ </button>
+ <button id="zoom-out" class="btn btn-sm btn-outline-secondary">
+ <i class="fas fa-search-minus"></i>
+ </button>
+ <button id="fit-content" class="btn btn-sm btn-outline-secondary">
+ <i class="fas fa-expand-arrows-alt"></i>
+ </button>
+ <button id="reset-view" class="btn btn-sm btn-outline-secondary">
+ <i class="fas fa-home"></i>
+ </button>
+ </div>
+</div>
+```
+
+#### Standard JavaScript Initialization
+```javascript
+// Standard pattern for initializing SVG coordinate operations
+document.addEventListener('DOMContentLoaded', function() {
+ const svgElement = document.getElementById('location-svg');
+ if (!svgElement) return;
+
+ // Initialize coordinate systems
+ const coordinateTransform = new SvgCoordinateTransform(svgElement);
+ const interactionHandler = new SvgInteractionHandler(svgElement, {
+ enableClick: true,
+ enableDrag: false
+ });
+ const viewportController = new SvgViewportController(svgElement, {
+ minScale: 0.1,
+ maxScale: 5.0,
+ enablePan: true,
+ enableZoom: true
+ });
+ const positionManager = new EntityPositionManager(svgElement);
+
+ // Bind control buttons
+ document.getElementById('zoom-in')?.addEventListener('click', () => {
+ viewportController.zoomIn();
+ });
+
+ document.getElementById('zoom-out')?.addEventListener('click', () => {
+ viewportController.zoomOut();
+ });
+
+ document.getElementById('fit-content')?.addEventListener('click', () => {
+ viewportController.fitToContent();
+ });
+
+ document.getElementById('reset-view')?.addEventListener('click', () => {
+ viewportController.resetView();
+ });
+
+ // Handle entity interactions
+ svgElement.addEventListener('entityClick', function(event) {
+ const { entityId, svgCoordinates, element } = event.detail;
+
+ // Show selection indicator
+ const indicator = document.getElementById('selection-indicator');
+ indicator.setAttribute('cx', svgCoordinates.x);
+ indicator.setAttribute('cy', svgCoordinates.y);
+ indicator.style.display = 'block';
+
+ // Open entity details modal
+ openEntityDetailsModal(entityId);
+ });
+
+ svgElement.addEventListener('backgroundClick', function(event) {
+ // Hide selection indicator
+ document.getElementById('selection-indicator').style.display = 'none';
+ });
+
+ // Handle viewport changes
+ svgElement.addEventListener('viewportChanged', function(event) {
+ const { scale, translateX, translateY } = event.detail;
+
+ // Update scale-dependent elements
+ updateScaleDependentElements(scale);
+
+ // Trigger entity visibility updates if needed
+ updateEntityVisibility(event.detail.viewBox);
+ });
+
+ // Store references globally for debugging
+ window.svgCoordinateTransform = coordinateTransform;
+ window.svgInteractionHandler = interactionHandler;
+ window.svgViewportController = viewportController;
+ window.entityPositionManager = positionManager;
+});
+
+// Utility functions
+function openEntityDetailsModal(entityId) {
+ // Standard modal opening pattern
+ fetch(`/entity/${entityId}/details/`)
+ .then(response => response.json())
+ .then(data => {
+ if (data.modal) {
+ showModal(data.modal);
+ }
+ })
+ .catch(error => {
+ console.error('Error loading entity details:', error);
+ });
+}
+
+function updateScaleDependentElements(scale) {
+ // Adjust element sizes based on zoom level
+ const scaleDependentElements = document.querySelectorAll('.scale-dependent');
+ scaleDependentElements.forEach(element => {
+ const baseSize = parseFloat(element.getAttribute('data-base-size')) || 1;
+ const newSize = Math.max(0.5, baseSize / scale);
+ element.setAttribute('stroke-width', newSize);
+ });
+}
+
+function updateEntityVisibility(viewBox) {
+ // Hide entities outside visible area for performance
+ const entities = document.querySelectorAll('[data-entity-id]');
+ entities.forEach(entity => {
+ const bbox = entity.getBBox();
+ const isVisible = !(
+ bbox.x + bbox.width < viewBox.x ||
+ bbox.x > viewBox.x + viewBox.width ||
+ bbox.y + bbox.height < viewBox.y ||
+ bbox.y > viewBox.y + viewBox.height
+ );
+
+ entity.style.display = isVisible ? 'block' : 'none';
+ });
+}
+```
+
+### Standard Testing Patterns for Coordinate Operations
+
+#### Coordinate Conversion Testing
+```javascript
+// Standard test patterns for coordinate transformations
+function testCoordinateConversions() {
+ const svg = document.getElementById('location-svg');
+ const transform = new SvgCoordinateTransform(svg);
+
+ // Test screen to SVG conversion
+ const screenPoint = { x: 100, y: 50 };
+ const svgPoint = transform.screenToSvg(screenPoint);
+ console.assert(typeof svgPoint.x === 'number', 'SVG X coordinate should be number');
+ console.assert(typeof svgPoint.y === 'number', 'SVG Y coordinate should be number');
+
+ // Test round-trip conversion
+ const backToScreen = transform.svgToScreen(svgPoint);
+ const tolerance = 1; // 1 pixel tolerance
+ console.assert(
+ Math.abs(backToScreen.x - screenPoint.x) < tolerance,
+ 'Round-trip X conversion failed'
+ );
+ console.assert(
+ Math.abs(backToScreen.y - screenPoint.y) < tolerance,
+ 'Round-trip Y conversion failed'
+ );
+
+ console.log('Coordinate conversion tests passed');
+}
+
+function testViewportOperations() {
+ const svg = document.getElementById('location-svg');
+ const viewport = new SvgViewportController(svg);
+
+ const originalViewBox = svg.getAttribute('viewBox');
+
+ // Test zoom operations
+ viewport.zoomIn();
+ const zoomedViewBox = svg.getAttribute('viewBox');
+ console.assert(zoomedViewBox !== originalViewBox, 'Zoom in should change viewBox');
+
+ viewport.resetView();
+ const resetViewBox = svg.getAttribute('viewBox');
+ console.assert(resetViewBox === originalViewBox, 'Reset should restore original viewBox');
+
+ console.log('Viewport operation tests passed');
+}
+
+function testEntityPositioning() {
+ const svg = document.getElementById('location-svg');
+ const positionManager = new EntityPositionManager(svg);
+
+ // Create test entity
+ const testEntityHtml = `
+ <g data-entity-id="test-entity" class="entity-group">
+ <use href="#icon-motion-sensor" class="entity-svg"/>
+ </g>
+ `;
+ svg.innerHTML += testEntityHtml;
+
+ // Test position update
+ const newPosition = { x: 100, y: 150, scale: 1.5, rotation: 45 };
+ positionManager.updateEntityPosition('test-entity', newPosition);
+
+ // Verify position was applied
+ const retrievedPosition = positionManager.getEntityPosition('test-entity');
+ console.assert(retrievedPosition.x === 100, 'X position not set correctly');
+ console.assert(retrievedPosition.y === 150, 'Y position not set correctly');
+ console.assert(retrievedPosition.scale === 1.5, 'Scale not set correctly');
+ console.assert(retrievedPosition.rotation === 45, 'Rotation not set correctly');
+
+ console.log('Entity positioning tests passed');
+}
+```
+
+#### Performance Testing Pattern
+```javascript
+// Standard performance testing for coordinate operations
+function performanceTestCoordinateOperations() {
+ const svg = document.getElementById('location-svg');
+ const transform = new SvgCoordinateTransform(svg);
+
+ const testPoints = [];
+ for (let i = 0; i < 1000; i++) {
+ testPoints.push({
+ x: Math.random() * window.innerWidth,
+ y: Math.random() * window.innerHeight
+ });
+ }
+
+ // Test coordinate conversion performance
+ console.time('1000 screen-to-SVG conversions');
+ testPoints.forEach(point => {
+ transform.screenToSvg(point);
+ });
+ console.timeEnd('1000 screen-to-SVG conversions');
+
+ // Test entity positioning performance
+ const positionManager = new EntityPositionManager(svg);
+ const positions = testPoints.map(point => ({
+ x: point.x,
+ y: point.y,
+ scale: 1 + Math.random(),
+ rotation: Math.random() * 360
+ }));
+
+ console.time('1000 entity position updates');
+ positions.forEach((position, index) => {
+ positionManager.updateEntityPosition(`entity-${index}`, position);
+ });
+ console.timeEnd('1000 entity position updates');
+
+ console.log('Performance tests completed');
+}
+```
+
+## Performance Optimization Guide
+
+### Overview
+
+SVG coordinate operations can become computationally expensive with complex transformations, frequent updates, or large numbers of entities. This guide provides optimization strategies for maintaining smooth, responsive coordinate operations.
+
+### Coordinate Transformation Optimization
+
+#### Caching Transformation Matrices
+```javascript
+// Cache expensive matrix calculations
+class OptimizedCoordinateTransform extends SvgCoordinateTransform {
+ constructor(svgElement) {
+ super(svgElement);
+ this.matrixCache = new Map();
+ this.cacheHitCount = 0;
+ this.cacheMissCount = 0;
+ }
+
+ getScreenCTM() {
+ const cacheKey = this.generateMatrixCacheKey();
+
+ if (this.matrixCache.has(cacheKey)) {
+ this.cacheHitCount++;
+ return this.matrixCache.get(cacheKey);
+ }
+
+ const matrix = this.svgElement.getScreenCTM();
+ this.matrixCache.set(cacheKey, matrix);
+ this.cacheMissCount++;
+
+ // Limit cache size to prevent memory leaks
+ if (this.matrixCache.size > 100) {
+ const firstKey = this.matrixCache.keys().next().value;
+ this.matrixCache.delete(firstKey);
+ }
+
+ return matrix;
+ }
+
+ generateMatrixCacheKey() {
+ const viewBox = this.svgElement.getAttribute('viewBox');
+ const transform = this.svgElement.getAttribute('transform') || '';
+ const boundingRect = this.svgElement.getBoundingClientRect();
+
+ return `${viewBox}|${transform}|${boundingRect.width}x${boundingRect.height}`;
+ }
+
+ invalidateCache() {
+ this.matrixCache.clear();
+ }
+
+ getCacheStats() {
+ const totalRequests = this.cacheHitCount + this.cacheMissCount;
+ const hitRate = totalRequests > 0 ? (this.cacheHitCount / totalRequests) * 100 : 0;
+
+ return {
+ hits: this.cacheHitCount,
+ misses: this.cacheMissCount,
+ hitRate: hitRate.toFixed(1) + '%',
+ cacheSize: this.matrixCache.size
+ };
+ }
+}
+```
+
+#### Optimized Batch Coordinate Conversions
+```javascript
+// Process multiple coordinates efficiently
+class BatchCoordinateProcessor {
+ constructor(svgElement) {
+ this.svgElement = svgElement;
+ this.transform = new OptimizedCoordinateTransform(svgElement);
+ }
+
+ batchScreenToSvg(screenPoints) {
+ const results = [];
+ const matrix = this.transform.getScreenCTM()?.inverse();
+
+ if (!matrix) {
+ return screenPoints.map(p => ({ x: p.x, y: p.y }));
+ }
+
+ const rect = this.svgElement.getBoundingClientRect();
+
+ // Process all points using the same matrix
+ for (const point of screenPoints) {
+ const svgPoint = this.svgElement.createSVGPoint();
+ svgPoint.x = point.x - rect.left;
+ svgPoint.y = point.y - rect.top;
+
+ const transformed = svgPoint.matrixTransform(matrix);
+ results.push({ x: transformed.x, y: transformed.y });
+ }
+
+ return results;
+ }
+
+ batchSvgToScreen(svgPoints) {
+ const results = [];
+ const matrix = this.transform.getScreenCTM();
+
+ if (!matrix) {
+ return svgPoints;
+ }
+
+ const rect = this.svgElement.getBoundingClientRect();
+
+ // Process all points using the same matrix
+ for (const point of svgPoints) {
+ const svgPoint = this.svgElement.createSVGPoint();
+ svgPoint.x = point.x;
+ svgPoint.y = point.y;
+
+ const transformed = svgPoint.matrixTransform(matrix);
+ results.push({
+ x: transformed.x + rect.left,
+ y: transformed.y + rect.top
+ });
+ }
+
+ return results;
+ }
+
+ // Optimized bulk entity position updates
+ updateEntityPositions(entityUpdates) {
+ const startTime = performance.now();
+
+ // Group updates by transformation type
+ const transformGroups = this.groupTransformations(entityUpdates);
+
+ // Process each group efficiently
+ Object.entries(transformGroups).forEach(([transformType, entities]) => {
+ this.processTransformGroup(transformType, entities);
+ });
+
+ const endTime = performance.now();
+ console.log(`Batch position update: ${entityUpdates.length} entities in ${(endTime - startTime).toFixed(2)}ms`);
+ }
+
+ groupTransformations(entityUpdates) {
+ const groups = {};
+
+ entityUpdates.forEach(update => {
+ const key = `${update.scale || 1}_${update.rotation || 0}`;
+ if (!groups[key]) {
+ groups[key] = [];
+ }
+ groups[key].push(update);
+ });
+
+ return groups;
+ }
+
+ processTransformGroup(transformType, entities) {
+ // Apply same transformation parameters to multiple entities
+ entities.forEach(entity => {
+ const element = document.querySelector(`[data-entity-id="${entity.id}"]`);
+ if (element) {
+ const transform = `translate(${entity.x}, ${entity.y})`;
+ const targetElement = element.querySelector('use, path') || element;
+ targetElement.setAttribute('transform', transform);
+ }
+ });
+ }
+}
+```
+
+### Viewport Operation Performance
+
+#### Optimized Viewport Controller
+```javascript
+// High-performance viewport operations
+class PerformantViewportController extends SvgViewportController {
+ constructor(svgElement, options = {}) {
+ super(svgElement, options);
+ this.updateThrottle = options.updateThrottle || 16; // ~60fps
+ this.lastUpdateTime = 0;
+ this.pendingUpdate = null;
+ this.performanceMode = this.detectPerformanceMode();
+ }
+
+ detectPerformanceMode() {
+ // Detect if we need to use performance mode
+ const entityCount = this.svgElement.querySelectorAll('[data-entity-id]').length;
+ const isLowEndDevice = navigator.hardwareConcurrency < 4;
+ const hasLimitedMemory = navigator.deviceMemory && navigator.deviceMemory < 4;
+
+ return entityCount > 100 || isLowEndDevice || hasLimitedMemory;
+ }
+
+ updateViewBox() {
+ const now = performance.now();
+
+ // Throttle updates to prevent excessive redraws
+ if (now - this.lastUpdateTime < this.updateThrottle) {
+ if (this.pendingUpdate) {
+ cancelAnimationFrame(this.pendingUpdate);
+ }
+
+ this.pendingUpdate = requestAnimationFrame(() => {
+ this.performViewBoxUpdate();
+ });
+ return;
+ }
+
+ this.performViewBoxUpdate();
+ }
+
+ performViewBoxUpdate() {
+ this.lastUpdateTime = performance.now();
+
+ const width = this.originalViewBox.width / this.currentTransform.scale;
+ const height = this.originalViewBox.height / this.currentTransform.scale;
+
+ const x = this.currentTransform.translateX - width / 2;
+ const y = this.currentTransform.translateY - height / 2;
+
+ // Use CSS transforms for better performance if supported
+ if (this.performanceMode && this.supportsCSSTransforms()) {
+ this.applyCSSTransform();
+ } else {
+ this.svgElement.setAttribute('viewBox', `${x} ${y} ${width} ${height}`);
+ }
+
+ // Emit transform change event (throttled)
+ this.emitThrottledViewportEvent();
+ }
+
+ supportsCSSTransforms() {
+ return CSS.supports('transform', 'scale(1) translate(0px, 0px)');
+ }
+
+ applyCSSTransform() {
+ const scale = this.currentTransform.scale;
+ const translateX = -this.currentTransform.translateX * scale;
+ const translateY = -this.currentTransform.translateY * scale;
+
+ this.svgElement.style.transform =
+ `scale(${scale}) translate(${translateX}px, ${translateY}px)`;
+ }
+
+ emitThrottledViewportEvent() {
+ // Only emit events at most once per frame
+ if (!this.eventPending) {
+ this.eventPending = true;
+
+ requestAnimationFrame(() => {
+ this.svgElement.dispatchEvent(new CustomEvent('viewportChanged', {
+ detail: {
+ scale: this.currentTransform.scale,
+ translateX: this.currentTransform.translateX,
+ translateY: this.currentTransform.translateY,
+ viewBox: this.getCurrentViewBox()
+ }
+ }));
+ this.eventPending = false;
+ });
+ }
+ }
+
+ // Optimized zoom operation
+ zoomAt(centerX, centerY, scaleDelta) {
+ // Pre-calculate to avoid expensive operations during zoom
+ const newScale = this.clampScale(this.currentTransform.scale * scaleDelta);
+
+ if (newScale === this.currentTransform.scale) {
+ return; // No change needed
+ }
+
+ // Use efficient transform calculation
+ this.updateTransformOptimized(centerX, centerY, newScale);
+
+ if (this.performanceMode) {
+ // In performance mode, defer heavy operations
+ this.deferHeavyOperations();
+ } else {
+ this.updateViewBox();
+ }
+ }
+
+ clampScale(scale) {
+ return Math.max(
+ this.options.minScale,
+ Math.min(this.options.maxScale, scale)
+ );
+ }
+
+ updateTransformOptimized(centerX, centerY, newScale) {
+ // Optimized transform calculation
+ const scaleChange = newScale / this.currentTransform.scale;
+
+ const viewBoxCenterX = this.originalViewBox.x + centerX * this.originalViewBox.width;
+ const viewBoxCenterY = this.originalViewBox.y + centerY * this.originalViewBox.height;
+
+ // Update transform in one operation
+ this.currentTransform.translateX = viewBoxCenterX -
+ (viewBoxCenterX - this.currentTransform.translateX) * scaleChange;
+ this.currentTransform.translateY = viewBoxCenterY -
+ (viewBoxCenterY - this.currentTransform.translateY) * scaleChange;
+ this.currentTransform.scale = newScale;
+ }
+
+ deferHeavyOperations() {
+ // Defer expensive operations until zoom is complete
+ clearTimeout(this.deferredOperationsTimeout);
+ this.deferredOperationsTimeout = setTimeout(() => {
+ this.updateViewBox();
+ this.updateEntityVisibility();
+ }, 100);
+ }
+}
+```
+
+### Entity Positioning Performance
+
+#### High-Performance Entity Position Manager
+```javascript
+// Optimized entity positioning with spatial indexing
+class PerformantEntityPositionManager extends EntityPositionManager {
+ constructor(svgElement) {
+ super(svgElement);
+ this.spatialIndex = new SpatialIndex();
+ this.positionCache = new Map();
+ this.updateQueue = [];
+ this.isProcessingQueue = false;
+ }
+
+ // Spatial indexing for efficient entity queries
+ buildSpatialIndex() {
+ this.spatialIndex.clear();
+
+ const entities = this.svgElement.querySelectorAll('[data-entity-id]');
+ entities.forEach(entity => {
+ const entityId = entity.getAttribute('data-entity-id');
+ const position = this.getEntityPosition(entityId);
+
+ if (position) {
+ this.spatialIndex.insert({
+ id: entityId,
+ x: position.x,
+ y: position.y,
+ width: 32, // Assume standard entity size
+ height: 32
+ });
+ }
+ });
+ }
+
+ // Queue position updates for batch processing
+ queuePositionUpdate(entityId, position, options = {}) {
+ this.updateQueue.push({ entityId, position, options });
+
+ if (!this.isProcessingQueue) {
+ this.processUpdateQueue();
+ }
+ }
+
+ async processUpdateQueue() {
+ this.isProcessingQueue = true;
+
+ while (this.updateQueue.length > 0) {
+ const batch = this.updateQueue.splice(0, 20); // Process 20 at a time
+
+ // Process batch synchronously for better performance
+ batch.forEach(update => {
+ this.updateEntityPositionImmediate(
+ update.entityId,
+ update.position,
+ update.options
+ );
+ });
+
+ // Yield control periodically
+ if (this.updateQueue.length > 0) {
+ await new Promise(resolve => setTimeout(resolve, 0));
+ }
+ }
+
+ this.isProcessingQueue = false;
+ }
+
+ updateEntityPositionImmediate(entityId, position, options = {}) {
+ const element = this.svgElement.querySelector(`[data-entity-id="${entityId}"]`);
+
+ if (!element) {
+ return;
+ }
+
+ // Use cached transform calculation when possible
+ const transformString = this.getCachedTransform(position) ||
+ this.buildTransform(position, options);
+
+ const targetElement = element.querySelector('use, path') || element;
+
+ if (options.animate && !this.performanceMode) {
+ this.animateTransform(targetElement, transformString, options.duration || 300);
+ } else {
+ // Direct attribute update is faster than animation
+ targetElement.setAttribute('transform', transformString);
+ }
+
+ // Update position cache
+ this.positionCache.set(entityId, position);
+
+ // Update spatial index
+ this.spatialIndex.update(entityId, position);
+ }
+
+ getCachedTransform(position) {
+ const cacheKey = `${position.x}_${position.y}_${position.scale || 1}_${position.rotation || 0}`;
+ return this.transformCache?.get(cacheKey);
+ }
+
+ // Efficient entity queries using spatial indexing
+ getEntitiesInRegion(x, y, width, height) {
+ return this.spatialIndex.query(x, y, width, height);
+ }
+
+ getNearestEntities(x, y, maxDistance = 50, limit = 10) {
+ return this.spatialIndex.queryNearest(x, y, maxDistance, limit);
+ }
+
+ // Bulk position updates with optimizations
+ updateMultipleEntityPositions(positionUpdates) {
+ const startTime = performance.now();
+
+ // Sort updates to minimize DOM access patterns
+ positionUpdates.sort((a, b) => a.entityId.localeCompare(b.entityId));
+
+ // Disable transitions during bulk update
+ this.disableTransitions();
+
+ positionUpdates.forEach(update => {
+ this.updateEntityPositionImmediate(update.entityId, update.position);
+ });
+
+ // Re-enable transitions
+ this.enableTransitions();
+
+ // Update spatial index in batch
+ this.spatialIndex.batchUpdate(positionUpdates);
+
+ const endTime = performance.now();
+ console.log(`Bulk position update: ${positionUpdates.length} entities in ${(endTime - startTime).toFixed(2)}ms`);
+ }
+
+ disableTransitions() {
+ const style = document.createElement('style');
+ style.id = 'disable-entity-transitions';
+ style.textContent = '.entity-svg, .entity-path { transition: none !important; }';
+ document.head.appendChild(style);
+ }
+
+ enableTransitions() {
+ const style = document.getElementById('disable-entity-transitions');
+ if (style) {
+ style.remove();
+ }
+ }
+}
+```
+
+### Spatial Indexing for Performance
+
+#### Efficient Spatial Data Structure
+```javascript
+// Simple spatial index for entity queries
+class SpatialIndex {
+ constructor(cellSize = 100) {
+ this.cellSize = cellSize;
+ this.cells = new Map();
+ this.entityLocations = new Map();
+ }
+
+ insert(entity) {
+ const cellKey = this.getCellKey(entity.x, entity.y);
+
+ if (!this.cells.has(cellKey)) {
+ this.cells.set(cellKey, new Set());
+ }
+
+ this.cells.get(cellKey).add(entity.id);
+ this.entityLocations.set(entity.id, { cellKey, ...entity });
+ }
+
+ update(entityId, newPosition) {
+ const oldLocation = this.entityLocations.get(entityId);
+
+ if (oldLocation) {
+ // Remove from old cell
+ const oldCell = this.cells.get(oldLocation.cellKey);
+ if (oldCell) {
+ oldCell.delete(entityId);
+ if (oldCell.size === 0) {
+ this.cells.delete(oldLocation.cellKey);
+ }
+ }
+ }
+
+ // Add to new cell
+ const newCellKey = this.getCellKey(newPosition.x, newPosition.y);
+ if (!this.cells.has(newCellKey)) {
+ this.cells.set(newCellKey, new Set());
+ }
+
+ this.cells.get(newCellKey).add(entityId);
+ this.entityLocations.set(entityId, { cellKey: newCellKey, ...newPosition });
+ }
+
+ query(x, y, width, height) {
+ const entities = new Set();
+
+ const minCellX = Math.floor(x / this.cellSize);
+ const maxCellX = Math.floor((x + width) / this.cellSize);
+ const minCellY = Math.floor(y / this.cellSize);
+ const maxCellY = Math.floor((y + height) / this.cellSize);
+
+ for (let cellX = minCellX; cellX <= maxCellX; cellX++) {
+ for (let cellY = minCellY; cellY <= maxCellY; cellY++) {
+ const cellKey = `${cellX},${cellY}`;
+ const cell = this.cells.get(cellKey);
+
+ if (cell) {
+ cell.forEach(entityId => entities.add(entityId));
+ }
+ }
+ }
+
+ return Array.from(entities);
+ }
+
+ queryNearest(x, y, maxDistance, limit = 10) {
+ const candidates = [];
+ const searchRadius = Math.ceil(maxDistance / this.cellSize);
+
+ const centerCellX = Math.floor(x / this.cellSize);
+ const centerCellY = Math.floor(y / this.cellSize);
+
+ // Search in expanding squares
+ for (let radius = 0; radius <= searchRadius; radius++) {
+ for (let dx = -radius; dx <= radius; dx++) {
+ for (let dy = -radius; dy <= radius; dy++) {
+ if (Math.abs(dx) === radius || Math.abs(dy) === radius) {
+ const cellKey = `${centerCellX + dx},${centerCellY + dy}`;
+ const cell = this.cells.get(cellKey);
+
+ if (cell) {
+ cell.forEach(entityId => {
+ const entity = this.entityLocations.get(entityId);
+ if (entity) {
+ const distance = Math.sqrt(
+ Math.pow(entity.x - x, 2) + Math.pow(entity.y - y, 2)
+ );
+
+ if (distance <= maxDistance) {
+ candidates.push({ entityId, distance });
+ }
+ }
+ });
+ }
+ }
+ }
+ }
+
+ // Early exit if we have enough candidates
+ if (candidates.length >= limit * 2) {
+ break;
+ }
+ }
+
+ // Sort by distance and return top results
+ return candidates
+ .sort((a, b) => a.distance - b.distance)
+ .slice(0, limit)
+ .map(c => c.entityId);
+ }
+
+ getCellKey(x, y) {
+ const cellX = Math.floor(x / this.cellSize);
+ const cellY = Math.floor(y / this.cellSize);
+ return `${cellX},${cellY}`;
+ }
+
+ clear() {
+ this.cells.clear();
+ this.entityLocations.clear();
+ }
+
+ batchUpdate(updates) {
+ // Disable individual updates during batch
+ const oldUpdate = this.update;
+ this.update = () => {}; // No-op during batch
+
+ updates.forEach(update => {
+ oldUpdate.call(this, update.entityId, update.position);
+ });
+
+ // Restore update function
+ this.update = oldUpdate;
+ }
+}
+```
+
+### Interaction Performance Optimization
+
+#### Optimized Event Handling
+```javascript
+// High-performance SVG interaction handling
+class PerformantInteractionHandler extends SvgInteractionHandler {
+ constructor(svgElement, options = {}) {
+ super(svgElement, options);
+ this.eventThrottle = options.eventThrottle || 10; // 100fps max
+ this.lastEventTime = 0;
+ this.eventCache = new Map();
+ this.spatialIndex = new SpatialIndex();
+ }
+
+ handleClick(event) {
+ // Throttle click events to prevent spam
+ const now = performance.now();
+ if (now - this.lastEventTime < this.eventThrottle) {
+ return;
+ }
+ this.lastEventTime = now;
+
+ const svgPoint = this.coordinateTransform.screenToSvg({
+ x: event.clientX,
+ y: event.clientY
+ });
+
+ // Use spatial index for faster entity lookup
+ const nearbyEntities = this.spatialIndex.queryNearest(
+ svgPoint.x, svgPoint.y, 50, 5
+ );
+
+ let clickedElement = null;
+ for (const entityId of nearbyEntities) {
+ const element = document.querySelector(`[data-entity-id="${entityId}"]`);
+ if (element && this.isPointInsideEntity(svgPoint, element)) {
+ clickedElement = element;
+ break;
+ }
+ }
+
+ if (clickedElement) {
+ this.onEntityClick(clickedElement, svgPoint, event);
+ } else {
+ this.onBackgroundClick(svgPoint, event);
+ }
+ }
+
+ isPointInsideEntity(point, element) {
+ // Use cached bounding boxes when possible
+ const cacheKey = element.getAttribute('data-entity-id');
+ let bbox = this.eventCache.get(`bbox_${cacheKey}`);
+
+ if (!bbox) {
+ bbox = element.getBBox();
+ this.eventCache.set(`bbox_${cacheKey}`, bbox);
+
+ // Cache cleanup
+ if (this.eventCache.size > 200) {
+ const firstKey = this.eventCache.keys().next().value;
+ this.eventCache.delete(firstKey);
+ }
+ }
+
+ return point.x >= bbox.x &&
+ point.x <= bbox.x + bbox.width &&
+ point.y >= bbox.y &&
+ point.y <= bbox.y + bbox.height;
+ }
+
+ // Optimized mouse move handling
+ handleMouseMove(event) {
+ if (!this.isInteracting) return;
+
+ // Use requestAnimationFrame to throttle mouse move events
+ if (this.mouseMoveFrame) {
+ cancelAnimationFrame(this.mouseMoveFrame);
+ }
+
+ this.mouseMoveFrame = requestAnimationFrame(() => {
+ this.processMouseMove(event);
+ });
+ }
+
+ processMouseMove(event) {
+ const svgPoint = this.coordinateTransform.screenToSvg({
+ x: event.clientX,
+ y: event.clientY
+ });
+
+ // Only process if movement is significant
+ if (this.lastInteractionPoint) {
+ const dx = svgPoint.x - this.lastInteractionPoint.x;
+ const dy = svgPoint.y - this.lastInteractionPoint.y;
+ const distance = Math.sqrt(dx * dx + dy * dy);
+
+ if (distance < 1) { // Less than 1 SVG unit
+ return; // Skip insignificant movements
+ }
+ }
+
+ this.lastInteractionPoint = svgPoint;
+ this.emitMouseMoveEvent(svgPoint, event);
+ }
+
+ emitMouseMoveEvent(svgPoint, originalEvent) {
+ this.svgElement.dispatchEvent(new CustomEvent('svgMouseMove', {
+ detail: {
+ svgCoordinates: svgPoint,
+ screenCoordinates: {
+ x: originalEvent.clientX,
+ y: originalEvent.clientY
+ }
+ }
+ }));
+ }
+}
+```
+
+### Memory and Resource Management
+
+#### Resource Pool for Coordinate Operations
+```javascript
+// Efficient resource management for coordinate operations
+class CoordinateResourcePool {
+ constructor() {
+ this.svgPointPool = [];
+ this.matrixPool = [];
+ this.transformPool = [];
+ this.maxPoolSize = 100;
+ }
+
+ // Object pooling for SVG points
+ acquireSVGPoint() {
+ if (this.svgPointPool.length > 0) {
+ return this.svgPointPool.pop();
+ }
+
+ // Create new if pool is empty
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
+ return svg.createSVGPoint();
+ }
+
+ releaseSVGPoint(point) {
+ if (this.svgPointPool.length < this.maxPoolSize) {
+ // Reset point
+ point.x = 0;
+ point.y = 0;
+ this.svgPointPool.push(point);
+ }
+ }
+
+ // Batch coordinate conversion using pooled objects
+ batchConvertCoordinates(coordinates, converter) {
+ const results = [];
+ const points = coordinates.map(() => this.acquireSVGPoint());
+
+ try {
+ // Use pooled points for conversion
+ coordinates.forEach((coord, index) => {
+ const point = points[index];
+ point.x = coord.x;
+ point.y = coord.y;
+
+ const result = converter(point);
+ results.push({ x: result.x, y: result.y });
+ });
+ } finally {
+ // Always return points to pool
+ points.forEach(point => this.releaseSVGPoint(point));
+ }
+
+ return results;
+ }
+
+ // Memory cleanup
+ cleanup() {
+ this.svgPointPool.length = 0;
+ this.matrixPool.length = 0;
+ this.transformPool.length = 0;
+ }
+}
+```
+
+### Performance Monitoring and Analytics
+
+#### Coordinate Performance Profiler
+```javascript
+// Performance monitoring for coordinate operations
+class CoordinatePerformanceProfiler {
+ constructor() {
+ this.metrics = {
+ transformations: [],
+ entityUpdates: [],
+ viewportChanges: [],
+ interactions: []
+ };
+ this.isEnabled = false;
+ }
+
+ enable() {
+ this.isEnabled = true;
+ this.startTime = performance.now();
+ }
+
+ disable() {
+ this.isEnabled = false;
+ }
+
+ profileTransformation(operation, duration) {
+ if (!this.isEnabled) return;
+
+ this.metrics.transformations.push({
+ operation,
+ duration,
+ timestamp: performance.now() - this.startTime
+ });
+
+ // Keep metrics size manageable
+ if (this.metrics.transformations.length > 1000) {
+ this.metrics.transformations.splice(0, 100);
+ }
+ }
+
+ profileEntityUpdate(entityCount, duration) {
+ if (!this.isEnabled) return;
+
+ this.metrics.entityUpdates.push({
+ entityCount,
+ duration,
+ timestamp: performance.now() - this.startTime
+ });
+ }
+
+ profileInteraction(type, duration) {
+ if (!this.isEnabled) return;
+
+ this.metrics.interactions.push({
+ type,
+ duration,
+ timestamp: performance.now() - this.startTime
+ });
+ }
+
+ generateReport() {
+ const report = {
+ transformations: this.analyzeTransformations(),
+ entityUpdates: this.analyzeEntityUpdates(),
+ interactions: this.analyzeInteractions(),
+ recommendations: this.generateRecommendations()
+ };
+
+ console.table(report.transformations);
+ console.table(report.entityUpdates);
+ console.log('Performance Recommendations:', report.recommendations);
+
+ return report;
+ }
+
+ analyzeTransformations() {
+ if (this.metrics.transformations.length === 0) return {};
+
+ const durations = this.metrics.transformations.map(t => t.duration);
+ const operations = {};
+
+ this.metrics.transformations.forEach(t => {
+ if (!operations[t.operation]) {
+ operations[t.operation] = [];
+ }
+ operations[t.operation].push(t.duration);
+ });
+
+ return Object.entries(operations).map(([op, durations]) => ({
+ operation: op,
+ count: durations.length,
+ average: (durations.reduce((a, b) => a + b, 0) / durations.length).toFixed(2),
+ max: Math.max(...durations).toFixed(2),
+ min: Math.min(...durations).toFixed(2)
+ }));
+ }
+
+ analyzeEntityUpdates() {
+ if (this.metrics.entityUpdates.length === 0) return {};
+
+ const updates = this.metrics.entityUpdates;
+ const avgEntitiesPerUpdate = updates.reduce((sum, u) => sum + u.entityCount, 0) / updates.length;
+ const avgDuration = updates.reduce((sum, u) => sum + u.duration, 0) / updates.length;
+
+ return {
+ totalUpdates: updates.length,
+ avgEntitiesPerUpdate: avgEntitiesPerUpdate.toFixed(1),
+ avgDuration: avgDuration.toFixed(2),
+ entitiesPerSecond: (avgEntitiesPerUpdate / (avgDuration / 1000)).toFixed(0)
+ };
+ }
+
+ analyzeInteractions() {
+ const interactions = {};
+
+ this.metrics.interactions.forEach(i => {
+ if (!interactions[i.type]) {
+ interactions[i.type] = [];
+ }
+ interactions[i.type].push(i.duration);
+ });
+
+ return Object.entries(interactions).map(([type, durations]) => ({
+ type,
+ count: durations.length,
+ average: (durations.reduce((a, b) => a + b, 0) / durations.length).toFixed(2)
+ }));
+ }
+
+ generateRecommendations() {
+ const recommendations = [];
+
+ // Analyze transformation performance
+ const transformData = this.analyzeTransformations();
+ if (Array.isArray(transformData)) {
+ const slowTransforms = transformData.filter(t => parseFloat(t.average) > 5);
+ if (slowTransforms.length > 0) {
+ recommendations.push('Consider caching or optimizing slow transformation operations');
+ }
+ }
+
+ // Analyze entity update performance
+ const entityData = this.analyzeEntityUpdates();
+ if (entityData.entitiesPerSecond && parseInt(entityData.entitiesPerSecond) < 1000) {
+ recommendations.push('Entity update performance is below optimal (< 1000 entities/sec)');
+ }
+
+ return recommendations;
+ }
+}
+```
+
+## Overview
+
+This document covers the frontend-specific SVG coordinate operations used in location-based entity displays. These operations handle the conversion between different coordinate systems and the visual positioning of entities within SVG-based floor plans.
+
+## Coordinate System Types
+
+### SVG Document Coordinates
+- **Origin**: Top-left corner of the SVG viewBox
+- **Units**: SVG units (typically corresponding to real-world measurements)
+- **Usage**: Entity positioning data stored in EntityPosition and EntityPath models
+
+### Screen/Canvas Coordinates
+- **Origin**: Top-left corner of the rendered SVG element
+- **Units**: CSS pixels
+- **Usage**: Mouse interactions, click detection, dynamic positioning
+
+### Viewport Coordinates
+- **Origin**: Top-left corner of the visible viewport area
+- **Units**: CSS pixels
+- **Usage**: Scroll position, panning operations
+
+## Frontend SVG Operations
+
+### Screen Position Calculation
+
+Convert SVG coordinates to screen position for interactions:
+
+```python
+class SvgCoordinateTransform:
+ def calculate_entity_position(self, svg_coords, viewbox, canvas_size):
+ """Convert SVG coordinates to screen position"""
+ # Extract viewbox parameters
+ vb_x, vb_y, vb_width, vb_height = self.parse_viewbox(viewbox)
+ canvas_width, canvas_height = canvas_size
+
+ # Calculate scale factors
+ scale_x = canvas_width / vb_width
+ scale_y = canvas_height / vb_height
+
+ # Transform SVG coordinates to screen coordinates
+ screen_x = (svg_coords.x - vb_x) * scale_x
+ screen_y = (svg_coords.y - vb_y) * scale_y
+
+ return ScreenPosition(screen_x, screen_y)
+
+ def parse_viewbox(self, viewbox_string):
+ """Parse SVG viewBox string into components"""
+ parts = viewbox_string.split()
+ return float(parts[0]), float(parts[1]), float(parts[2]), float(parts[3])
+```
+
+### Interactive Coordinate Conversion
+
+Handle mouse events and convert to SVG coordinates:
+
+```javascript
+class SvgInteractionHandler {
+ constructor(svgElement) {
+ this.svgElement = svgElement;
+ }
+
+ screenToSvgCoordinates(screenX, screenY) {
+ // Get SVG bounding rectangle
+ const rect = this.svgElement.getBoundingClientRect();
+
+ // Convert screen coordinates to SVG viewport coordinates
+ const svgPoint = this.svgElement.createSVGPoint();
+ svgPoint.x = screenX - rect.left;
+ svgPoint.y = screenY - rect.top;
+
+ // Transform through CTM (Current Transformation Matrix)
+ const ctm = this.svgElement.getScreenCTM().inverse();
+ const svgCoords = svgPoint.matrixTransform(ctm);
+
+ return {
+ x: svgCoords.x,
+ y: svgCoords.y
+ };
+ }
+
+ handleEntityClick(event, entityId) {
+ const svgCoords = this.screenToSvgCoordinates(event.clientX, event.clientY);
+
+ // Process entity interaction at SVG coordinates
+ this.processEntityInteraction(entityId, svgCoords);
+ }
+}
+```
+
+### Zoom and Pan Operations
+
+Handle viewport transformations for navigation:
+
+```javascript
+class SvgViewportController {
+ constructor(svgElement) {
+ this.svgElement = svgElement;
+ this.currentZoom = 1.0;
+ this.currentPan = { x: 0, y: 0 };
+ }
+
+ zoomToFit(entities) {
+ // Calculate bounding box of all entities
+ const bbox = this.calculateEntityBoundingBox(entities);
+
+ // Add padding
+ const padding = 20;
+ const paddedBounds = {
+ x: bbox.x - padding,
+ y: bbox.y - padding,
+ width: bbox.width + (padding * 2),
+ height: bbox.height + (padding * 2)
+ };
+
+ // Update viewBox to fit entities
+ const viewBox = `${paddedBounds.x} ${paddedBounds.y} ${paddedBounds.width} ${paddedBounds.height}`;
+ this.svgElement.setAttribute('viewBox', viewBox);
+ }
+
+ zoomIn(factor = 1.2) {
+ this.currentZoom *= factor;
+ this.applyTransform();
+ }
+
+ zoomOut(factor = 0.8) {
+ this.currentZoom *= factor;
+ this.applyTransform();
+ }
+
+ pan(deltaX, deltaY) {
+ this.currentPan.x += deltaX / this.currentZoom;
+ this.currentPan.y += deltaY / this.currentZoom;
+ this.applyTransform();
+ }
+
+ applyTransform() {
+ const transform = `translate(${this.currentPan.x}, ${this.currentPan.y}) scale(${this.currentZoom})`;
+ const mainGroup = this.svgElement.querySelector('#main-group');
+ if (mainGroup) {
+ mainGroup.setAttribute('transform', transform);
+ }
+ }
+}
+```
+
+### Entity Positioning and Scaling
+
+Handle dynamic entity positioning based on viewport:
+
+```javascript
+class EntityPositionManager {
+ updateEntityPosition(entityElement, position, viewportScale) {
+ // Calculate scaled position
+ const scaledX = position.x * viewportScale;
+ const scaledY = position.y * viewportScale;
+ const scaledSize = position.scale * viewportScale;
+
+ // Apply transform to entity element
+ const transform = `translate(${scaledX}, ${scaledY}) scale(${scaledSize}) rotate(${position.rotation})`;
+ entityElement.setAttribute('transform', transform);
+ }
+
+ updateEntityPath(pathElement, pathData, viewportTransform) {
+ // Apply viewport transformation to path data
+ const transformedPath = this.transformSvgPath(pathData, viewportTransform);
+ pathElement.setAttribute('d', transformedPath);
+ }
+
+ transformSvgPath(pathData, transform) {
+ // Parse and transform SVG path data
+ // This is a simplified example - real implementation would use SVG path parsing library
+ return pathData; // Placeholder for actual path transformation
+ }
+}
+```
+
+## Template Integration
+
+### SVG Viewport Setup
+
+```django
+<!-- Location view SVG setup -->
+<svg id="location-svg"
+ class="location-display"
+ viewBox="{{ location_view.get_viewbox }}"
+ preserveAspectRatio="xMidYMid meet">
+
+ <!-- Main transform group for zoom/pan -->
+ <g id="main-group">
+
+ <!-- Background layer -->
+ <g class="background-layer">
+ {% if location.floor_plan_svg %}
+ {% include location.floor_plan_svg %}
+ {% endif %}
+ </g>
+
+ <!-- Entity layer -->
+ <g class="entity-layer">
+ {% for entity in entities %}
+ {% if entity.has_position %}
+ <g class="entity-group"
+ data-entity-id="{{ entity.id }}"
+ transform="translate({{ entity.position.x }}, {{ entity.position.y }})
+ scale({{ entity.position.scale }})
+ rotate({{ entity.position.rotation }})">
+ {% include entity.get_visual_template %}
+ </g>
+ {% elif entity.has_path %}
+ <path class="entity-path"
+ data-entity-id="{{ entity.id }}"
+ d="{{ entity.path.svg_path }}"
+ style="{{ entity.get_path_styling }}"/>
+ {% endif %}
+ {% endfor %}
+ </g>
+
+ </g>
+</svg>
+```
+
+### JavaScript Integration
+
+```javascript
+// Initialize SVG coordinate handling
+document.addEventListener('DOMContentLoaded', function() {
+ const locationSvg = document.getElementById('location-svg');
+
+ if (locationSvg) {
+ // Initialize interaction handler
+ const interactionHandler = new SvgInteractionHandler(locationSvg);
+
+ // Initialize viewport controller
+ const viewportController = new SvgViewportController(locationSvg);
+
+ // Initialize entity position manager
+ const positionManager = new EntityPositionManager();
+
+ // Set up event listeners
+ locationSvg.addEventListener('click', function(event) {
+ const entityElement = event.target.closest('[data-entity-id]');
+ if (entityElement) {
+ const entityId = entityElement.getAttribute('data-entity-id');
+ interactionHandler.handleEntityClick(event, entityId);
+ }
+ });
+
+ // Set up zoom controls
+ document.getElementById('zoom-in').addEventListener('click', () => {
+ viewportController.zoomIn();
+ });
+
+ document.getElementById('zoom-out').addEventListener('click', () => {
+ viewportController.zoomOut();
+ });
+
+ // Set up pan controls (mouse drag)
+ let isPanning = false;
+ let lastPanPoint = null;
+
+ locationSvg.addEventListener('mousedown', function(event) {
+ if (event.button === 1 || (event.button === 0 && event.ctrlKey)) { // Middle mouse or Ctrl+click
+ isPanning = true;
+ lastPanPoint = { x: event.clientX, y: event.clientY };
+ event.preventDefault();
+ }
+ });
+
+ document.addEventListener('mousemove', function(event) {
+ if (isPanning && lastPanPoint) {
+ const deltaX = event.clientX - lastPanPoint.x;
+ const deltaY = event.clientY - lastPanPoint.y;
+ viewportController.pan(deltaX, deltaY);
+ lastPanPoint = { x: event.clientX, y: event.clientY };
+ }
+ });
+
+ document.addEventListener('mouseup', function() {
+ isPanning = false;
+ lastPanPoint = null;
+ });
+ }
+});
+```
+
+## Performance Considerations
+
+### Efficient Coordinate Calculations
+
+```javascript
+// Cache frequently used calculations
+class CoordinateCache {
+ constructor() {
+ this.transformCache = new Map();
+ this.boundingBoxCache = new Map();
+ }
+
+ getCachedTransform(viewBox, canvasSize) {
+ const key = `${viewBox}_${canvasSize.width}x${canvasSize.height}`;
+
+ if (!this.transformCache.has(key)) {
+ const transform = this.calculateTransform(viewBox, canvasSize);
+ this.transformCache.set(key, transform);
+ }
+
+ return this.transformCache.get(key);
+ }
+
+ clearCache() {
+ this.transformCache.clear();
+ this.boundingBoxCache.clear();
+ }
+}
+```
+
+### Optimize Frequent Updates
+
+```javascript
+// Use requestAnimationFrame for smooth updates
+class SmoothPositionUpdater {
+ constructor() {
+ this.pendingUpdates = new Map();
+ this.isUpdateScheduled = false;
+ }
+
+ scheduleUpdate(entityId, newPosition) {
+ this.pendingUpdates.set(entityId, newPosition);
+
+ if (!this.isUpdateScheduled) {
+ this.isUpdateScheduled = true;
+ requestAnimationFrame(() => this.processPendingUpdates());
+ }
+ }
+
+ processPendingUpdates() {
+ this.pendingUpdates.forEach((position, entityId) => {
+ const element = document.querySelector(`[data-entity-id="${entityId}"]`);
+ if (element) {
+ this.applyPositionUpdate(element, position);
+ }
+ });
+
+ this.pendingUpdates.clear();
+ this.isUpdateScheduled = false;
+ }
+}
+```
+
+## Troubleshooting
+
+### Click Detection Not Working
+
+**Symptoms**: Mouse clicks on entities don't trigger expected actions
+**Diagnostic Steps**:
+
+1. **Verify Event Listener Setup**
+ ```javascript
+ // Check if click handler is attached
+ const svg = document.getElementById('location-svg');
+ console.log('Click listeners:', getEventListeners(svg));
+
+ // Test manual click
+ svg.addEventListener('click', (e) => {
+ console.log('Click at:', e.clientX, e.clientY);
+ });
+ ```
+
+2. **Check Coordinate Conversion**
+ ```javascript
+ // Test coordinate transformation
+ const handler = new SvgInteractionHandler(svg);
+ const svgCoords = handler.screenToSvgCoordinates(event.clientX, event.clientY);
+ console.log('SVG coordinates:', svgCoords);
+ ```
+
+3. **Verify Element Structure**
+ ```html
+ <!-- Entity must have data-entity-id and be in correct layer -->
+ <g class="entity-layer">
+ <g data-entity-id="123" class="entity-group">
+ <!-- Clickable content -->
+ </g>
+ </g>
+ ```
+
+**Common Fixes**:
+- **Missing data-entity-id**: Add attribute to entity elements
+- **Event bubbling issues**: Use `event.target.closest('[data-entity-id]')`
+- **Coordinate transformation error**: Check SVG viewBox and CTM calculation
+- **Z-index/layering**: Ensure entities are in front of background elements
+
+### Entity Positions Incorrect
+
+**Symptoms**: Entities appear in wrong locations after coordinate transformations
+**Root Causes & Solutions**:
+
+1. **ViewBox Parsing Issues**
+ ```javascript
+ // Debug viewBox parsing
+ const viewBox = svg.getAttribute('viewBox');
+ console.log('ViewBox:', viewBox);
+
+ const [x, y, width, height] = viewBox.split(' ').map(Number);
+ console.log('Parsed:', { x, y, width, height });
+ ```
+
+2. **Scale Factor Calculation**
+ ```javascript
+ // Verify scale factors
+ const rect = svg.getBoundingClientRect();
+ const viewBoxWidth = parseFloat(svg.viewBox.baseVal.width);
+ const scaleX = rect.width / viewBoxWidth;
+ console.log('Scale factor:', scaleX);
+ ```
+
+3. **Transform Matrix Issues**
+ ```javascript
+ // Check current transformation matrix
+ const ctm = svg.getScreenCTM();
+ console.log('CTM:', ctm);
+ console.log('Transform values:', {
+ a: ctm.a, b: ctm.b, c: ctm.c,
+ d: ctm.d, e: ctm.e, f: ctm.f
+ });
+ ```
+
+**Solutions**:
+- **Invalid viewBox**: Ensure viewBox attribute has 4 numeric values
+- **Missing CTM**: Check if SVG element has proper screen CTM
+- **Nested transforms**: Account for parent group transformations
+- **Dynamic sizing**: Recalculate on window resize
+
+### Zoom and Pan Not Working
+
+**Symptoms**: Viewport controls don't respond or behave erratically
+**Troubleshooting Approach**:
+
+1. **Check Controller Initialization**
+ ```javascript
+ // Verify controller is properly initialized
+ console.log('Viewport controller:', window.viewportController);
+
+ // Test basic operations
+ if (viewportController) {
+ viewportController.zoomIn();
+ console.log('Current zoom:', viewportController.currentZoom);
+ }
+ ```
+
+2. **Verify Transform Application**
+ ```javascript
+ // Check if transforms are being applied
+ const mainGroup = svg.querySelector('#main-group');
+ console.log('Main group transform:', mainGroup.getAttribute('transform'));
+ ```
+
+3. **Event Handler Issues**
+ ```javascript
+ // Test zoom button events
+ document.getElementById('zoom-in').addEventListener('click', () => {
+ console.log('Zoom in clicked');
+ viewportController.zoomIn();
+ });
+ ```
+
+**Common Fixes**:
+- **Missing main group**: Ensure SVG has `#main-group` element
+- **Event conflicts**: Check for competing mouse event handlers
+- **Transform syntax**: Verify proper transform string formatting
+- **Boundary limits**: Implement zoom/pan limits to prevent excessive values
+
+### Performance Issues with Many Entities
+
+**Symptoms**: Slow coordinate calculations, laggy interactions with large datasets
+**Optimization Strategies**:
+
+1. **Coordinate Caching**
+ ```javascript
+ // Implement coordinate result caching
+ class CoordinateCache {
+ constructor(maxSize = 1000) {
+ this.cache = new Map();
+ this.maxSize = maxSize;
+ }
+
+ get(key) {
+ const result = this.cache.get(key);
+ if (result) {
+ // Move to end (LRU)
+ this.cache.delete(key);
+ this.cache.set(key, result);
+ }
+ return result;
+ }
+ }
+ ```
+
+2. **Batch Operations**
+ ```javascript
+ // Process coordinate updates in batches
+ requestAnimationFrame(() => {
+ const updates = this.pendingCoordinateUpdates;
+ updates.forEach(update => {
+ this.applyCoordinateUpdate(update);
+ });
+ this.pendingCoordinateUpdates.clear();
+ });
+ ```
+
+3. **Viewport Culling**
+ ```javascript
+ // Only process entities in visible viewport
+ function isEntityVisible(entityCoords, viewportBounds) {
+ return entityCoords.x >= viewportBounds.left &&
+ entityCoords.x <= viewportBounds.right &&
+ entityCoords.y >= viewportBounds.top &&
+ entityCoords.y <= viewportBounds.bottom;
+ }
+ ```
+
+### SVG Viewbox and Scaling Issues
+
+**Symptoms**: Inconsistent scaling, elements clipped or positioned wrong
+**Diagnostic Steps**:
+
+1. **Check ViewBox vs Canvas Size**
+ ```javascript
+ // Compare logical vs physical dimensions
+ const viewBox = svg.viewBox.baseVal;
+ const rect = svg.getBoundingClientRect();
+
+ console.log('ViewBox:', viewBox.width, 'x', viewBox.height);
+ console.log('Canvas:', rect.width, 'x', rect.height);
+ console.log('Aspect ratios:',
+ viewBox.width/viewBox.height,
+ rect.width/rect.height);
+ ```
+
+2. **Verify preserveAspectRatio**
+ ```html
+ <!-- Check preserveAspectRatio setting -->
+ <svg viewBox="0 0 1000 800"
+ preserveAspectRatio="xMidYMid meet" <!-- or "none" for stretching -->
+ ...>
+ ```
+
+3. **Test Scale Consistency**
+ ```javascript
+ // Verify consistent scaling in both dimensions
+ function testScaling() {
+ const point1 = { x: 0, y: 0 };
+ const point2 = { x: 100, y: 100 };
+
+ const screen1 = svgToScreen(point1);
+ const screen2 = svgToScreen(point2);
+
+ const scaleX = (screen2.x - screen1.x) / (point2.x - point1.x);
+ const scaleY = (screen2.y - screen1.y) / (point2.y - point1.y);
+
+ console.log('Scale factors:', { scaleX, scaleY });
+ }
+ ```
+
+### Browser Compatibility Problems
+
+**Symptoms**: Coordinate operations work in some browsers but not others
+**Common Issues & Solutions**:
+
+1. **SVG DOM API Support**
+ ```javascript
+ // Check for required APIs
+ if (!SVGElement.prototype.getScreenCTM) {
+ console.error('Browser lacks SVG getScreenCTM support');
+ // Implement fallback or show warning
+ }
+
+ if (!SVGSVGElement.prototype.createSVGPoint) {
+ console.error('Browser lacks createSVGPoint support');
+ // Use alternative coordinate conversion
+ }
+ ```
+
+2. **Transform Matrix Differences**
+ ```javascript
+ // Handle browser differences in matrix calculations
+ function getScreenCTMSafe(element) {
+ try {
+ return element.getScreenCTM();
+ } catch (e) {
+ console.warn('getScreenCTM failed, using fallback');
+ return element.getCTM();
+ }
+ }
+ ```
+
+3. **Event Coordinate Differences**
+ ```javascript
+ // Normalize event coordinates across browsers
+ function getNormalizedCoordinates(event) {
+ return {
+ clientX: event.clientX || event.pageX,
+ clientY: event.clientY || event.pageY
+ };
+ }
+ ```
+
+### Touch and Mobile Issues
+
+**Symptoms**: Coordinate operations fail on touch devices
+**Mobile-Specific Solutions**:
+
+1. **Touch Event Handling**
+ ```javascript
+ // Handle touch events for mobile devices
+ svg.addEventListener('touchstart', (e) => {
+ e.preventDefault(); // Prevent default touch behaviors
+ const touch = e.touches[0];
+ handleInteraction(touch.clientX, touch.clientY);
+ });
+ ```
+
+2. **Viewport Meta Tag**
+ ```html
+ <!-- Ensure proper mobile viewport handling -->
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
+ ```
+
+3. **High DPI Display Issues**
+ ```javascript
+ // Account for device pixel ratio
+ const dpr = window.devicePixelRatio || 1;
+ const adjustedCoords = {
+ x: screenX * dpr,
+ y: screenY * dpr
+ };
+ ```
+
+## Related Documentation
+- Entity visual configuration: [Entity Visual Configuration](entity-visual-configuration.md)
+- Entity status display: [Entity Status Display](entity-status-display.md)
+- Style guidelines: [Style Guidelines](style-guidelines.md)
+- Domain geometric operations: [Domain Guidelines](../domain/domain-guidelines.md#complex-calculations)
+- Frontend guidelines: [Frontend Guidelines](frontend-guidelines.md)
\ No newline at end of file
diff --git a/docs/dev/frontend/template-conventions.md b/docs/dev/frontend/template-conventions.md
new file mode 100644
index 00000000..9ecf121d
--- /dev/null
+++ b/docs/dev/frontend/template-conventions.md
@@ -0,0 +1,307 @@
+# Template Conventions
+
+## Template Directory Structure
+
+### App Module Templates
+Each Django app follows this template organization:
+
+```
+hi/apps/${APPNAME}/templates/${APPNAME}/
+├── pages/ # Full HTML pages
+├── modals/ # Modal dialogs
+├── panes/ # Page fragments
+├── email/ # Email templates
+├── svg/ # SVG files
+├── testing/ # Test templates
+│ └── ui/ # Visual testing templates
+└── edit/ # Edit mode templates
+ ├── pages/
+ ├── modals/
+ └── panes/
+```
+
+## Template Inheritance
+
+### Base Templates
+
+All pages should extend from appropriate base templates:
+
+```django
+<!-- For main application pages -->
+{% extends "pages/base.html" %}
+
+<!-- For modal dialogs -->
+{% extends "modals/base_modal.html" %}
+
+<!-- For configuration pages -->
+{% extends "config/pages/config_base.html" %}
+```
+
+### Block Structure
+
+Common blocks to override:
+
+```django
+{% block head_title %}Page Title{% endblock %}
+{% block extra_css %}
+ <!-- Page-specific CSS -->
+{% endblock %}
+{% block content %}
+ <!-- Main content area -->
+{% endblock %}
+{% block extra_js %}
+ <!-- Page-specific JavaScript -->
+{% endblock %}
+```
+
+## Template Context Patterns
+
+### Standard Context Variables
+
+Views should provide consistent context variables:
+
+```python
+context = {
+ # Entity-related
+ 'entity': entity_instance,
+ 'entities': entity_queryset,
+ 'entity_position': position_instance,
+
+ # Location-related
+ 'location': location_instance,
+ 'location_view': location_view_instance,
+
+ # View state
+ 'view_mode': ViewMode.NORMAL, # Use enums, not strings
+ 'view_type': ViewType.SECURITY,
+ 'is_edit_mode': False,
+
+ # Pre-computed flags
+ 'has_sensors': bool(entity.sensors.exists()),
+ 'can_edit': request.user.has_perm('entity.change_entity'),
+}
+```
+
+### Avoiding Template Logic
+
+**Bad - Logic in template:**
+```django
+{% if entity.sensors.count > 0 and entity.is_active and not entity.deleted %}
+ {% for sensor in entity.sensors.all %}
+ {% if sensor.last_reading and sensor.last_reading.timestamp|timesince < "1 hour" %}
+ <!-- Display sensor -->
+ {% endif %}
+ {% endfor %}
+{% endif %}
+```
+
+**Good - Logic in view:**
+```python
+# In view
+context = {
+ 'active_sensors': entity.get_recent_active_sensors(),
+ 'has_active_sensors': bool(active_sensors),
+}
+```
+
+```django
+<!-- In template -->
+{% if has_active_sensors %}
+ {% for sensor in active_sensors %}
+ <!-- Display sensor -->
+ {% endfor %}
+{% endif %}
+```
+
+## Template Tags and Filters
+
+### Loading Template Tags
+
+Always load required template tags at the top:
+
+```django
+{% load static %}
+{% load icons %}
+{% load custom_filters %}
+```
+
+### Custom Template Tags
+
+Create reusable template tags for complex display logic:
+
+```python
+# In templatetags/entity_tags.py
[email protected]_tag('entity/tags/status_badge.html')
+def entity_status_badge(entity):
+ return {
+ 'entity': entity,
+ 'status_class': entity.get_status_css_class(),
+ 'status_label': entity.get_status_display(),
+ }
+```
+
+Usage:
+```django
+{% load entity_tags %}
+{% entity_status_badge entity %}
+```
+
+## Form Templates
+
+### Form Rendering Pattern
+
+Use consistent form rendering:
+
+```django
+<form method="post" action="{% url 'entity_update' entity.id %}">
+ {% csrf_token %}
+
+ {% if form.non_field_errors %}
+ <div class="alert alert-danger">
+ {{ form.non_field_errors }}
+ </div>
+ {% endif %}
+
+ {% for field in form %}
+ <div class="form-group">
+ {{ field.label_tag }}
+ {{ field }}
+ {% if field.help_text %}
+ <small class="form-text text-muted">{{ field.help_text }}</small>
+ {% endif %}
+ {% if field.errors %}
+ <div class="invalid-feedback d-block">
+ {{ field.errors }}
+ </div>
+ {% endif %}
+ </div>
+ {% endfor %}
+
+ <button type="submit" class="btn btn-primary">
+ {% icon "save" size="sm" css_class="hi-icon-left" %}
+ Save Changes
+ </button>
+</form>
+```
+
+## AJAX Template Patterns
+
+### Returning HTML Fragments
+
+For AJAX requests returning HTML:
+
+```django
+<!-- panes/entity_row.html -->
+<tr class="entity-row" data-entity-id="{{ entity.id }}">
+ <td>{{ entity.name }}</td>
+ <td>{{ entity.location.name }}</td>
+ <td>{% entity_status_badge entity %}</td>
+</tr>
+```
+
+### JSON Response Structure
+
+For AJAX views returning JSON with HTML:
+
+```python
+# In view
+html = render_to_string('entity/panes/entity_row.html', {'entity': entity})
+return JsonResponse({
+ 'status': 'success',
+ 'html': html,
+ 'entity_id': entity.id,
+ 'insert_method': 'append',
+ 'target_selector': '#entity-table tbody',
+})
+```
+
+## Modal Templates
+
+### Modal Structure
+
+Standard modal template structure:
+
+```django
+<!-- modals/entity_edit.html -->
+<div class="modal fade" id="entityEditModal" tabindex="-1" role="dialog">
+ <div class="modal-dialog modal-lg" role="document">
+ <div class="modal-content">
+ <div class="modal-header">
+ <h5 class="modal-title">Edit Entity</h5>
+ <button type="button" class="close" data-dismiss="modal" aria-label="Close">
+ {% icon "close" size="sm" %}
+ </button>
+ </div>
+ <div class="modal-body">
+ <!-- Modal content -->
+ </div>
+ <div class="modal-footer">
+ <button type="button" class="btn btn-secondary" data-dismiss="modal">
+ {% icon "cancel" size="sm" css_class="hi-icon-left" %}
+ Cancel
+ </button>
+ <button type="submit" class="btn btn-primary">
+ {% icon "save" size="sm" css_class="hi-icon-left" %}
+ Save Changes
+ </button>
+ </div>
+ </div>
+ </div>
+</div>
+```
+
+## Template Performance
+
+### Efficient Queries
+
+Use `select_related` and `prefetch_related` in views:
+
+```python
+# In view - prevent N+1 queries
+entities = Entity.objects.select_related(
+ 'location',
+ 'entity_type'
+).prefetch_related(
+ 'sensors',
+ 'controllers'
+)
+```
+
+### Template Fragment Caching
+
+Cache expensive template fragments:
+
+```django
+{% load cache %}
+{% cache 300 entity_detail entity.id entity.updated_at %}
+ <!-- Expensive template rendering -->
+ {% include "entity/panes/sensor_list.html" %}
+{% endcache %}
+```
+
+## Debugging Templates
+
+### Debug Toolbar
+
+Use Django Debug Toolbar to identify template issues:
+- Template rendering time
+- Number of SQL queries
+- Context variables
+
+### Template Debug Mode
+
+In development, use template debug mode:
+
+```django
+{% if debug %}
+ <div class="debug-info">
+ <pre>{{ entity|pprint }}</pre>
+ </div>
+{% endif %}
+```
+
+## Related Documentation
+- Frontend guidelines: [Frontend Guidelines](frontend-guidelines.md)
+- Icon system: [Icon System](icon-system.md)
+- Style guidelines: [Style Guidelines](style-guidelines.md)
+- Testing: [UI Testing](ui-testing.md)
\ No newline at end of file
diff --git a/docs/dev/frontend/ui-testing.md b/docs/dev/frontend/ui-testing.md
new file mode 100644
index 00000000..1f7acfeb
--- /dev/null
+++ b/docs/dev/frontend/ui-testing.md
@@ -0,0 +1,404 @@
+# UI Testing
+
+## Visual Testing Page
+
+Visit: [http://127.0.0.1:8411/testing/ui](http://127.0.0.1:8411/testing/ui)
+
+These test/ui views are only available in development when `DEBUG=True`. They are conditionally loaded in the root `urls.py`.
+
+## UI Testing Framework Guidelines
+
+The visual testing framework is designed for viewing UI styling and layout during development. These are **read-only** views that should never modify system state.
+
+### Critical 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)
+```
+
+### Architecture Patterns
+
+**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
+
+**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
+
+## Setting Up Visual Testing
+
+### Auto-Discovery Structure
+
+The `hi.tests.ui` module uses auto-discovery by looking in app directories.
+
+In the app directory you want to have a visual testing page:
+
+```bash
+mkdir -p tests/ui
+touch tests/__init__.py
+touch tests/ui/__init__.py
+```
+
+### Required Files
+
+Create these files:
+- `tests/ui/views.py`
+- `tests/ui/urls.py` (gets auto-discovered)
+
+### Template Structure
+
+Templates go in `templates/${APPNAME}/testing/ui/`. Create a home page:
+
+```html
+<!-- templates/${APPNAME}/testing/ui/home.html -->
+{% extends "pages/base.html" %}
+{% load icons %}
+
+{% block head_title %}HI: {{ app_name|title }} UI Tests{% endblock %}
+
+{% block content %}
+<div class="container-fluid m-4">
+ <h2 class="text-info">{{ app_name|title }} UI Tests</h2>
+
+ <div class="row">
+ <div class="col-md-6">
+ <h3>Component Tests</h3>
+ <ul class="list-group">
+ <li class="list-group-item">
+ <a href="{% url 'test_entity_card' %}">Entity Cards</a>
+ </li>
+ <li class="list-group-item">
+ <a href="{% url 'test_status_badges' %}">Status Badges</a>
+ </li>
+ </ul>
+ </div>
+
+ <div class="col-md-6">
+ <h3>Modal Tests</h3>
+ <ul class="list-group">
+ <li class="list-group-item">
+ <a href="{% url 'test_edit_modal' %}" data-toggle="modal" data-target="#editModal">
+ Edit Entity Modal
+ </a>
+ </li>
+ </ul>
+ </div>
+ </div>
+</div>
+{% endblock %}
+```
+
+### View Implementation
+
+```python
+# tests/ui/views.py
+from django.shortcuts import render
+from django.views import View
+from hi.apps.entity.models import Entity
+
+class TestUiEntityHomeView(View):
+ def get(self, request, *args, **kwargs):
+ context = {
+ 'app_name': 'entity',
+ }
+ return render(request, 'entity/testing/ui/home.html', context)
+
+class TestUiEntityCardView(View):
+ def get(self, request, *args, **kwargs):
+ # Create synthetic test data
+ entities = [
+ self.create_synthetic_entity('Living Room Light', 'active'),
+ self.create_synthetic_entity('Kitchen Sensor', 'recent'),
+ self.create_synthetic_entity('Garage Door', 'idle'),
+ self.create_synthetic_entity('Weather Station', 'unknown'),
+ ]
+
+ context = {
+ 'entities': entities,
+ 'page_title': 'Entity Card Variations',
+ }
+ return render(request, 'entity/testing/ui/card_variations.html', context)
+
+ def create_synthetic_entity(self, name, status):
+ """Create synthetic entity for testing - does not save to database"""
+ entity = Entity(
+ name=name,
+ integration_id=f'test.{name.lower().replace(" ", "_")}',
+ integration_name='test_integration'
+ )
+ # Add synthetic status for display
+ entity._test_status = status
+ return entity
+```
+
+### URL Configuration
+
+```python
+# tests/ui/urls.py
+from django.urls import re_path
+from . import views
+
+urlpatterns = [
+ re_path(r'^$',
+ views.TestUiEntityHomeView.as_view(),
+ name='entity_tests_ui'),
+
+ re_path(r'^cards/$',
+ views.TestUiEntityCardView.as_view(),
+ name='test_entity_cards'),
+]
+```
+
+## Component Testing Patterns
+
+### Testing Responsive Design
+
+Create viewport testing utilities:
+
+```html
+<!-- Responsive testing template -->
+<div class="responsive-test">
+ <h3>Viewport Testing</h3>
+ <div class="viewport-buttons">
+ <button class="btn btn-sm btn-outline-secondary" data-viewport="320x568">iPhone SE</button>
+ <button class="btn btn-sm btn-outline-secondary" data-viewport="768x1024">iPad</button>
+ <button class="btn btn-sm btn-outline-secondary" data-viewport="1200x800">Desktop</button>
+ </div>
+
+ <div class="test-component">
+ <!-- Component under test -->
+ {% include "entity/panes/entity_card.html" %}
+ </div>
+</div>
+
+<script>
+document.querySelectorAll('[data-viewport]').forEach(button => {
+ button.addEventListener('click', function() {
+ const [width, height] = this.dataset.viewport.split('x');
+ // Simulate viewport for testing
+ document.querySelector('.test-component').style.maxWidth = width + 'px';
+ });
+});
+</script>
+```
+
+### Testing State Variations
+
+Create comprehensive state testing:
+
+```python
+class TestUiStatusStatesView(View):
+ def get(self, request, *args, **kwargs):
+ # Test all possible status states
+ status_variations = [
+ ('active', 'Red - Currently active'),
+ ('recent', 'Orange - Recently active'),
+ ('past', 'Yellow - Past activity'),
+ ('idle', 'Green - Idle state'),
+ ('unknown', 'Gray - Unknown/offline'),
+ ]
+
+ entities = []
+ for status, description in status_variations:
+ entity = self.create_entity_with_status(status)
+ entity._description = description
+ entities.append(entity)
+
+ context = {
+ 'entities': entities,
+ 'page_title': 'Status State Variations',
+ }
+ return render(request, 'entity/testing/ui/status_states.html', context)
+```
+
+### Testing Icon Usage
+
+```html
+<!-- Icon testing template -->
+<div class="icon-test-grid">
+ <h3>Icon Usage Tests</h3>
+
+ <div class="row">
+ <div class="col-md-4">
+ <h4>Actions</h4>
+ <div class="btn-group-vertical w-100">
+ <button class="btn btn-primary">
+ {% icon "plus" size="sm" css_class="hi-icon-left" %}
+ Add New
+ </button>
+ <button class="btn btn-secondary">
+ {% icon "edit" size="sm" css_class="hi-icon-left" %}
+ Edit
+ </button>
+ <button class="btn btn-danger">
+ {% icon "delete" size="sm" css_class="hi-icon-left" %}
+ Delete
+ </button>
+ </div>
+ </div>
+
+ <div class="col-md-4">
+ <h4>Icon Sizes</h4>
+ {% for size in "xs,sm,md,lg,xl"|split:"," %}
+ <div class="mb-2">
+ {% icon "home" size=size %} {{ size }} ({{ size }})
+ </div>
+ {% endfor %}
+ </div>
+
+ <div class="col-md-4">
+ <h4>Status Icons</h4>
+ <div class="alert alert-success">
+ {% icon "check-circle" size="sm" css_class="hi-icon-left" %}
+ Success message
+ </div>
+ <div class="alert alert-warning">
+ {% icon "exclamation-triangle" size="sm" css_class="hi-icon-left" %}
+ Warning message
+ </div>
+ </div>
+ </div>
+</div>
+```
+
+## Modal Testing
+
+### Modal Component Testing
+
+```python
+class TestUiModalView(View):
+ def get(self, request, *args, **kwargs):
+ # Test modal with different content types
+ modal_variations = [
+ {
+ 'size': 'sm',
+ 'title': 'Small Modal',
+ 'content': 'Simple confirmation modal',
+ 'actions': ['Cancel', 'Confirm']
+ },
+ {
+ 'size': 'lg',
+ 'title': 'Large Modal',
+ 'content': 'Complex form modal with multiple fields',
+ 'actions': ['Cancel', 'Save', 'Save & Continue']
+ }
+ ]
+
+ context = {
+ 'modal_variations': modal_variations,
+ }
+ return render(request, 'entity/testing/ui/modal_tests.html', context)
+```
+
+## Form Testing
+
+### Form State Testing
+
+```html
+<!-- Form testing template -->
+<div class="form-test-variations">
+ <h3>Form State Testing</h3>
+
+ <div class="row">
+ <div class="col-md-6">
+ <h4>Normal State</h4>
+ <form>
+ <div class="form-group">
+ <label for="normal-input">Entity Name</label>
+ <input type="text" class="form-control" id="normal-input" value="Living Room Light">
+ </div>
+ <button type="submit" class="btn btn-primary">Save</button>
+ </form>
+ </div>
+
+ <div class="col-md-6">
+ <h4>Error State</h4>
+ <form>
+ <div class="form-group">
+ <label for="error-input">Entity Name</label>
+ <input type="text" class="form-control is-invalid" id="error-input" value="">
+ <div class="invalid-feedback">
+ This field is required.
+ </div>
+ </div>
+ <button type="submit" class="btn btn-primary">Save</button>
+ </form>
+ </div>
+ </div>
+</div>
+```
+
+## Email Template Testing
+
+Use helper base classes for email testing:
+
+```python
+# From hi.tests.ui.email_test_views.py
+class EmailTestView(View):
+ def test_alert_notification_email(self):
+ # Test email templates with synthetic data
+ context = {
+ 'alert': self.create_synthetic_alert(),
+ 'user': self.create_synthetic_user(),
+ }
+ return self.render_email_template('alert/email/notification.html', context)
+```
+
+## Performance Testing
+
+### Template Rendering Performance
+
+```python
+import time
+from django.test.utils import override_settings
+
+class TestUiPerformanceView(View):
+ def get(self, request, *args, **kwargs):
+ # Test template rendering with large datasets
+ start_time = time.time()
+
+ # Create large synthetic dataset
+ entities = [self.create_synthetic_entity(f'Entity {i}') for i in range(100)]
+
+ render_time = time.time() - start_time
+
+ context = {
+ 'entities': entities,
+ 'render_time': render_time,
+ }
+ return render(request, 'entity/testing/ui/performance_test.html', context)
+```
+
+## Related Documentation
+- Frontend guidelines: [Frontend Guidelines](frontend-guidelines.md)
+- Template conventions: [Template Conventions](template-conventions.md)
+- Testing patterns: [Testing Patterns](../testing/testing-patterns.md)
+- Test data management: [Test Data Management](../testing/test-data-management.md)
\ No newline at end of file
diff --git a/docs/dev/integrations/external-api-standards.md b/docs/dev/integrations/external-api-standards.md
new file mode 100644
index 00000000..cb6d806b
--- /dev/null
+++ b/docs/dev/integrations/external-api-standards.md
@@ -0,0 +1,47 @@
+# External API Standards
+
+## HTTP Client Standards
+
+### Request Configuration
+- Use session-based clients with connection pooling
+- Implement retry logic with exponential backoff
+- Set appropriate timeouts (default: 30 seconds)
+- Include proper User-Agent headers
+
+### Authentication
+- Support Bearer token authentication
+- Handle token refresh automatically
+- Store credentials securely in integration attributes
+
+### Error Handling
+- Use custom exception hierarchy
+- Implement circuit breaker patterns for resilience
+- Log errors with appropriate detail levels
+
+## API Response Patterns
+
+### Data Validation
+- Validate all incoming data against expected schemas
+- Handle missing or malformed data gracefully
+- Provide meaningful error messages
+
+### Rate Limiting
+- Respect API rate limits
+- Implement backoff strategies
+- Monitor and log rate limit violations
+
+## WebSocket Standards
+
+### Connection Management
+- Implement automatic reconnection
+- Handle connection state properly
+- Process messages asynchronously
+
+### Message Handling
+- Parse messages safely with error handling
+- Route messages to appropriate handlers
+- Maintain message order when required
+
+## Related Documentation
+- Integration guidelines: [Integration Guidelines](integration-guidelines.md)
+- Gateway implementation: [Gateway Implementation](gateway-implementation.md)
\ No newline at end of file
diff --git a/docs/dev/integrations/gateway-implementation.md b/docs/dev/integrations/gateway-implementation.md
new file mode 100644
index 00000000..324afd6f
--- /dev/null
+++ b/docs/dev/integrations/gateway-implementation.md
@@ -0,0 +1,44 @@
+# Gateway Implementation
+
+## Gateway Interface
+
+All integrations implement the `IntegrationGateway` interface:
+
+```python
+class IntegrationGateway:
+ def activate(self, integration_instance):
+ """Handle integration activation"""
+ raise NotImplementedError
+
+ def deactivate(self, integration_instance):
+ """Handle integration deactivation"""
+ raise NotImplementedError
+
+ def manage(self, request, integration_instance):
+ """Handle management interface"""
+ raise NotImplementedError
+```
+
+## Configuration Management
+
+Integration attributes are defined using enums:
+
+```python
+class MyIntegrationAttributes(IntegrationAttributeType):
+ BASE_URL = ("base_url", str, "Base URL for API")
+ API_KEY = ("api_key", str, "API authentication key")
+ POLLING_INTERVAL = ("polling_interval", int, "Polling interval in seconds")
+```
+
+## URL Patterns
+
+Management URLs use consistent patterns:
+
+```python
+# Integration management URL
+{% url 'integration_manage' name=integration.integration_type.name %}
+```
+
+## Related Documentation
+- Integration guidelines: [Integration Guidelines](integration-guidelines.md)
+- Service patterns: [Service Patterns](service-patterns.md)
\ No newline at end of file
diff --git a/docs/dev/integrations/integration-guidelines.md b/docs/dev/integrations/integration-guidelines.md
new file mode 100644
index 00000000..fe0c420b
--- /dev/null
+++ b/docs/dev/integrations/integration-guidelines.md
@@ -0,0 +1,381 @@
+# Integration Guidelines
+
+## Integration Architecture
+
+Each integration is a Django app in the `hi/services` directory. The `hi.integration` app handles integration management and required interfaces.
+
+## Nomenclature
+
+- **integration_id** - Unique identifier for each integration type
+- **integration_key** - Used to associate with external integration for entities, sensors, controllers, etc.
+- **integration_attr_key** - Unique identifier for user-defined attributes needed by implementation
+
+## How to Add an Integration
+
+### 1. Create Django App
+
+```bash
+cd src/hi/services
+../../manage.py startapp myintegration
+```
+
+### 2. Configure App
+
+Ensure `name` is fully qualified in `hi/services/myintegration/apps.py`:
+
+```python
+class MyIntegrationConfig(AppConfig):
+ name = 'hi.services.myintegration'
+```
+
+Add to `INSTALLED_APPS` in `hi/settings/base.py`:
+
+```python
+INSTALLED_APPS = [
+ # ...
+ 'hi.services.myintegration',
+]
+```
+
+### 3. Define Integration Type
+
+Add to the IntegrationType enum:
+
+```python
+class IntegrationType(Enum):
+ MYINTEGRATION = ('My Integration', 'For my stuff.')
+```
+
+### 4. Create Integration Gateway
+
+Create `hi/services/myintegration/myintegration_gateway.py`:
+
+```python
+from hi.integration.integration_gateway import IntegrationGateway
+from hi.utils.singleton import Singleton
+
+class MyIntegrationGateway(Singleton, IntegrationGateway):
+
+ def activate(self, integration_instance):
+ """Handle integration activation"""
+ # Validation and setup logic
+ integration_instance.status = IntegrationStatus.ACTIVE
+ integration_instance.save()
+ return {'status': 'success', 'message': 'Integration activated'}
+
+ def deactivate(self, integration_instance):
+ """Handle integration deactivation"""
+ # Cleanup logic
+ integration_instance.status = IntegrationStatus.INACTIVE
+ integration_instance.save()
+ return {'status': 'success', 'message': 'Integration deactivated'}
+
+ def manage(self, request, integration_instance):
+ """Handle management interface"""
+ if request.method == 'POST':
+ return self.handle_management_post(request, integration_instance)
+ return self.render_management_page(request, integration_instance)
+```
+
+### 5. Register with Factory
+
+Add to `hi/integrations/integration_factory.py`:
+
+```python
+from hi.services.myintegration.myintegration_gateway import MyIntegrationGateway
+
+def get_integration_gateway(integration_type):
+ if integration_type == IntegrationType.MYINTEGRATION:
+ return MyIntegrationGateway()
+ # ... other integrations
+```
+
+## Integration Gateway Methods
+
+### Activate Method
+
+Handle integration activation flow:
+
+```python
+def activate(self, integration_instance):
+ try:
+ # Validate configuration
+ self.validate_configuration(integration_instance)
+
+ # Test connection
+ self.test_connection(integration_instance)
+
+ # Initialize resources
+ self.initialize_integration(integration_instance)
+
+ integration_instance.status = IntegrationStatus.ACTIVE
+ integration_instance.save()
+
+ return {
+ 'status': 'success',
+ 'message': 'Integration activated successfully',
+ 'redirect': None
+ }
+ except ValidationError as e:
+ return {
+ 'status': 'error',
+ 'message': str(e),
+ 'redirect': None
+ }
+```
+
+### Deactivate Method
+
+Handle cleanup and deactivation:
+
+```python
+def deactivate(self, integration_instance):
+ try:
+ # Clean up entities
+ entities_removed = self.cleanup_entities(integration_instance)
+
+ # Close connections
+ self.close_connections(integration_instance)
+
+ integration_instance.status = IntegrationStatus.INACTIVE
+ integration_instance.save()
+
+ return {
+ 'status': 'success',
+ 'message': f'Integration deactivated. Removed {entities_removed} entities.',
+ }
+ except Exception as e:
+ return {
+ 'status': 'error',
+ 'message': f'Error during deactivation: {str(e)}'
+ }
+```
+
+### Manage Method
+
+Provide management interface:
+
+```python
+def manage(self, request, integration_instance):
+ if request.method == 'POST':
+ action = request.POST.get('action')
+
+ if action == 'sync_entities':
+ return self.sync_entities(integration_instance)
+ elif action == 'test_connection':
+ return self.test_connection_endpoint(integration_instance)
+ elif action == 'update_config':
+ return self.update_configuration(request, integration_instance)
+
+ # Render management page
+ context = {
+ 'integration': integration_instance,
+ 'entity_count': self.get_entity_count(integration_instance),
+ 'last_sync': self.get_last_sync_time(integration_instance),
+ 'connection_status': self.get_connection_status(integration_instance),
+ }
+ return render(request, 'myintegration/manage.html', context)
+```
+
+## API Integration Patterns
+
+### HTTP Client Pattern
+
+```python
+import requests
+from requests.adapters import HTTPAdapter
+from urllib3.util.retry import Retry
+
+class MyIntegrationClient:
+ def __init__(self, base_url, api_key, timeout=30):
+ self.base_url = base_url
+ self.api_key = api_key
+ self.timeout = timeout
+ self.session = self._create_session()
+
+ def _create_session(self):
+ session = requests.Session()
+
+ # Configure retries
+ retry_strategy = Retry(
+ total=3,
+ backoff_factor=1,
+ status_forcelist=[429, 500, 502, 503, 504],
+ )
+ adapter = HTTPAdapter(max_retries=retry_strategy)
+ session.mount("http://", adapter)
+ session.mount("https://", adapter)
+
+ # Default headers
+ session.headers.update({
+ 'Authorization': f'Bearer {self.api_key}',
+ 'Content-Type': 'application/json',
+ 'User-Agent': 'HomeInformation/1.0'
+ })
+
+ return session
+
+ def get_entities(self):
+ response = self.session.get(
+ f'{self.base_url}/entities',
+ timeout=self.timeout
+ )
+ response.raise_for_status()
+ return response.json()
+```
+
+### WebSocket Integration Pattern
+
+```python
+import asyncio
+import websockets
+import json
+
+class MyIntegrationWebSocket:
+ def __init__(self, url, api_key):
+ self.url = url
+ self.api_key = api_key
+ self.websocket = None
+ self.running = False
+
+ async def connect(self):
+ """Establish WebSocket connection"""
+ headers = {'Authorization': f'Bearer {self.api_key}'}
+ self.websocket = await websockets.connect(self.url, extra_headers=headers)
+ self.running = True
+
+ async def listen(self):
+ """Listen for messages"""
+ try:
+ async for message in self.websocket:
+ data = json.loads(message)
+ await self.handle_message(data)
+ except websockets.exceptions.ConnectionClosed:
+ self.running = False
+
+ async def handle_message(self, data):
+ """Process received message"""
+ message_type = data.get('type')
+
+ if message_type == 'entity_update':
+ await self.handle_entity_update(data)
+ elif message_type == 'status_change':
+ await self.handle_status_change(data)
+```
+
+## Data Synchronization Patterns
+
+### Entity Synchronization
+
+```python
+class EntitySynchronizer:
+ def __init__(self, integration_instance):
+ self.integration = integration_instance
+ self.client = MyIntegrationClient(
+ integration_instance.base_url,
+ integration_instance.api_key
+ )
+
+ def sync_entities(self):
+ """Synchronize entities from external system"""
+ try:
+ external_entities = self.client.get_entities()
+
+ synced_count = 0
+ for ext_entity in external_entities:
+ entity, created = self.sync_single_entity(ext_entity)
+ if entity:
+ synced_count += 1
+
+ # Remove entities no longer in external system
+ removed_count = self.cleanup_removed_entities(external_entities)
+
+ return {
+ 'synced': synced_count,
+ 'removed': removed_count,
+ 'total': len(external_entities)
+ }
+
+ except Exception as e:
+ raise IntegrationError(f"Entity sync failed: {str(e)}")
+
+ def sync_single_entity(self, external_entity):
+ """Sync individual entity"""
+ integration_id = external_entity['id']
+
+ entity, created = Entity.objects.get_or_create(
+ integration_name=self.integration.integration_type.name,
+ integration_id=integration_id,
+ defaults={
+ 'name': external_entity['name'],
+ 'entity_type': self.get_or_create_entity_type(external_entity),
+ 'location': self.get_default_location(),
+ }
+ )
+
+ # Update entity properties
+ if not created:
+ entity.name = external_entity['name']
+ entity.save()
+
+ # Sync entity states
+ self.sync_entity_states(entity, external_entity)
+
+ return entity, created
+```
+
+## Error Handling Patterns
+
+### Custom Exception Classes
+
+```python
+class IntegrationError(Exception):
+ """Base class for integration errors"""
+ pass
+
+class ConnectionError(IntegrationError):
+ """Connection-related errors"""
+ pass
+
+class AuthenticationError(IntegrationError):
+ """Authentication/authorization errors"""
+ pass
+
+class DataValidationError(IntegrationError):
+ """Data validation errors"""
+ pass
+```
+
+### Error Recovery Patterns
+
+```python
+class ResilientIntegrationClient:
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.circuit_breaker = CircuitBreaker(
+ failure_threshold=5,
+ recovery_timeout=60
+ )
+
+ def make_request(self, method, endpoint, **kwargs):
+ """Make HTTP request with circuit breaker pattern"""
+ @self.circuit_breaker
+ def _request():
+ response = self.session.request(method, endpoint, **kwargs)
+ response.raise_for_status()
+ return response
+
+ try:
+ return _request()
+ except CircuitBreakerOpenException:
+ raise ConnectionError("Service temporarily unavailable")
+ except requests.exceptions.RequestException as e:
+ raise IntegrationError(f"Request failed: {str(e)}")
+```
+
+## Related Documentation
+- Service patterns: [Service Patterns](service-patterns.md)
+- Gateway implementation: [Gateway Implementation](gateway-implementation.md)
+- External API standards: [External API Standards](external-api-standards.md)
+- Weather integration: [Weather Integration](weather-integration.md)
+- Backend integration: [Backend Guidelines](../backend/backend-guidelines.md)
\ No newline at end of file
diff --git a/docs/dev/integrations/service-patterns.md b/docs/dev/integrations/service-patterns.md
new file mode 100644
index 00000000..08bf09df
--- /dev/null
+++ b/docs/dev/integrations/service-patterns.md
@@ -0,0 +1,35 @@
+# Service Patterns
+
+## Home Assistant Integration
+
+Full two-way sync with Home Assistant including:
+- Entity mapping and state synchronization
+- Controller integration for device control
+- Real-time event handling
+
+```python
+class HomeAssistantGateway(IntegrationGateway):
+ def sync_entities(self):
+ # Fetch entities from Home Assistant API
+ # Map to local Entity models
+ # Synchronize states and capabilities
+ pass
+```
+
+## ZoneMinder Integration
+
+Camera and video surveillance system integration:
+- Security monitoring and alerts
+- Video stream management
+- Motion detection events
+
+## Integration Patterns
+
+- **HTTP API Clients**: REST API integration patterns
+- **WebSocket Connections**: Real-time event handling
+- **Polling Services**: Periodic data synchronization
+- **Webhook Handlers**: External system notifications
+
+## Related Documentation
+- Integration guidelines: [Integration Guidelines](integration-guidelines.md)
+- Architecture overview: [Architecture Overview](../shared/architecture-overview.md)
\ No newline at end of file
diff --git a/docs/dev/integrations/weather-integration.md b/docs/dev/integrations/weather-integration.md
new file mode 100644
index 00000000..44937a14
--- /dev/null
+++ b/docs/dev/integrations/weather-integration.md
@@ -0,0 +1,199 @@
+# Weather Integration
+
+## Weather Data Source Architecture
+
+The weather system uses a pluggable integration architecture designed to support multiple external weather APIs without dependencies on any single source.
+
+### Auto-Discovery System
+
+Weather data sources are automatically discovered by the system using a simple class-based pattern:
+
+1. **Create Source File**: Add new Python file in `hi.apps.weather.weather_sources/`
+2. **Implement Base Class**: Define subclass of `WeatherDataSource`
+3. **System Discovery**: Framework automatically finds and configures your source
+
+### Implementation Steps
+
+#### 1. Study the Base Class
+
+Before implementing, review `WeatherDataSource` base class in `src/hi/apps/weather/weather_data_source.py` to understand:
+
+- Required constructor parameters
+- Available configuration methods (`requires_api_key()`, `get_default_enabled_state()`)
+- Properties you can access (`self.api_key`, `self.is_enabled`, `self.geographic_location`)
+- Abstract methods you must implement (`get_data()`)
+
+#### 2. Study Existing Examples
+
+Look at current implementations in `src/hi/apps/weather/weather_sources/` to see:
+
+- How constructor parameters are set
+- How configuration methods are overridden
+- How `get_data()` is implemented
+- Best practices for error handling and logging
+
+#### 3. Create Your Implementation
+
+Create your weather source file following the patterns observed in existing sources.
+
+### Key Configuration Methods
+
+Refer to the `WeatherDataSource` base class for exact method signatures:
+
+- `requires_api_key()` - Return `True` if your source needs an API key
+- `get_default_enabled_state()` - Return `False` if your source should be disabled by default
+- `get_data()` - Your main implementation for fetching weather data
+
+### Implementation Example
+
+```python
+# hi/apps/weather/weather_sources/my_weather_source.py
+from hi.apps.weather.weather_data_source import WeatherDataSource
+import requests
+
+class MyWeatherSource(WeatherDataSource):
+ def __init__(self):
+ super().__init__(
+ source_id='my_weather',
+ label='My Weather Service',
+ priority=100,
+ rate_limit_seconds=300
+ )
+
+ def requires_api_key(self):
+ return True
+
+ def get_default_enabled_state(self):
+ return False
+
+ def get_data(self):
+ """Fetch and return weather data in unified format"""
+ if not self.is_enabled or not self.api_key:
+ return None
+
+ try:
+ response = requests.get(
+ f'https://api.myweather.com/current',
+ params={'key': self.api_key, 'location': self.location},
+ timeout=30
+ )
+ response.raise_for_status()
+
+ # Transform API response to unified format
+ return self.transform_to_unified_format(response.json())
+
+ except Exception as e:
+ self.logger.error(f"Failed to fetch weather data: {e}")
+ return None
+
+ def transform_to_unified_format(self, api_data):
+ """Transform external API data to internal unified format"""
+ # Map external data to hi.apps.weather.transient_models format
+ pass
+```
+
+## Auto-Discovery Features
+
+When you add a weather source file, the system automatically provides:
+
+✅ **Auto-Discovery**: System finds your class at startup
+✅ **Settings Creation**: Creates enable/disable checkbox in config UI
+✅ **API Key Settings**: Creates API key input field (if `requires_api_key()` returns `True`)
+✅ **Priority Handling**: Respects priority ordering for data source selection
+✅ **Enable/Disable**: Only polls enabled sources
+✅ **Rate Limiting**: Enforces your specified rate limits
+
+## Configuration UI Integration
+
+Once added, your weather source automatically appears in the system configuration under **Settings > Weather** with appropriate controls based on your implementation.
+
+**Important**: Run Django migrations after adding new sources. Even if no new migrations exist, the discovery and automatic database settings creation is triggered by a post-migration signal.
+
+## Data Integration Patterns
+
+### Unified Data Format
+
+Each weather source must map its external API data to the unified format defined in `hi.apps.weather.transient_models`. This ensures consistent data handling regardless of source.
+
+### Caching Strategy
+
+Each API module should cache data appropriately to reduce API calls:
+
+- **Astronomical data**: Only needs fetching once per day
+- **Historical weather data**: Usually never changes once fetched
+- **Current conditions**: Cache based on API provider recommendations
+- **Forecast data**: Balance between freshness and rate limits
+
+### Error Handling
+
+Implement robust error handling:
+
+```python
+def get_data(self):
+ try:
+ # API call implementation
+ pass
+ except requests.exceptions.Timeout:
+ self.logger.warning("Weather API request timed out")
+ return None
+ except requests.exceptions.HTTPError as e:
+ self.logger.error(f"Weather API HTTP error: {e}")
+ return None
+ except Exception as e:
+ self.logger.exception(f"Unexpected error in weather data fetch: {e}")
+ return None
+```
+
+## Priority and Data Resolution
+
+The system uses priority ordering to resolve data from multiple sources:
+
+- **Higher priority sources** take precedence for primary data
+- **Lower priority sources** fill in missing data points
+- **Lower priority sources** may overwrite data if existing data is stale
+- **Rate limiting** prevents excessive API calls
+
+## Testing Your Integration
+
+1. **Restart Django server** to trigger auto-discovery
+2. **Check logs** for discovery message confirming your source was found
+3. **Verify settings** appear in config UI at Settings > Weather
+4. **Test enable/disable** functionality
+5. **Verify data fetching** and unified format transformation
+
+## Best Practices
+
+- **Study Existing Code**: Always examine current implementations in `weather_sources/` before starting
+- **Unique IDs**: Use lowercase, no spaces for your source ID
+- **Descriptive Labels**: Use proper human-readable names for UI display
+- **Appropriate Priorities**: Check existing sources to choose suitable priority level
+- **Rate Limits**: Respect API provider limits and document them
+- **Error Handling**: Handle API failures gracefully following existing patterns
+- **Logging**: Use appropriate log levels for debugging and monitoring
+- **Data Validation**: Validate external API responses before transformation
+- **Timeout Handling**: Always set reasonable timeouts for external API calls
+
+## Troubleshooting
+
+### Source Not Discovered
+- Verify file is in correct directory: `hi.apps.weather.weather_sources/`
+- Check class inherits from `WeatherDataSource`
+- Restart Django server
+- Check Django logs for error messages
+
+### Settings Not Appearing
+- Run `./manage.py migrate` to trigger post-migration signals
+- Check database for weather source settings entries
+- Verify configuration UI has been refreshed
+
+### API Integration Issues
+- Enable debug logging for detailed API interaction logs
+- Test API endpoints independently
+- Verify API key configuration and permissions
+- Check rate limiting and quota usage
+
+## Related Documentation
+- Integration guidelines: [Integration Guidelines](integration-guidelines.md)
+- External API standards: [External API Standards](external-api-standards.md)
+- Weather business logic: [Domain Guidelines](../domain/domain-guidelines.md#weather-integration)
+- Service patterns: [Service Patterns](service-patterns.md)
\ No newline at end of file
diff --git a/docs/dev/plans/Django-View-Test-Refactoring-Plan.md b/docs/dev/plans/Django-View-Test-Refactoring-Plan.md
deleted file mode 100644
index e02374bd..00000000
--- a/docs/dev/plans/Django-View-Test-Refactoring-Plan.md
+++ /dev/null
@@ -1,418 +0,0 @@
-# Django View Test Refactoring Plan: Eliminating Over-Mocking
-
-## Overview
-
-This document provides a detailed action plan for refactoring Django view tests to eliminate over-mocking violations that contradict our testing philosophy. The goal is to replace unnecessary mocks with real objects and focus on testing actual behavior rather than implementation details.
-
-## Testing Philosophy Reference
-
-**Key Guidelines (from docs/dev/Testing.md):**
-- Mock at system boundaries only (HTTP calls, external services)
-- Use real database operations instead of mocking Django ORM
-- Don't mock internal Django components (forms, models, managers)
-- Test actual behavior and return values, not mock call parameters
-- Default should be to use real objects - only mock when there's a clear reason
-
-**Anti-Patterns to Eliminate:**
-- Mocking Django forms when real validation should be tested
-- Mocking internal application managers when real objects would work
-- Testing mock call verification instead of actual behavior
-- Over-mocking internal components that breaks integration
-
-## Priority Categories
-
-### 🔴 **CRITICAL PRIORITY** - Django Form Over-Mocking
-Major violations of testing philosophy requiring immediate attention.
-
-### 🟡 **HIGH PRIORITY** - Internal Manager Over-Mocking
-Significant violations that break integration testing.
-
-### 🟢 **MEDIUM PRIORITY** - Mock Call Verification Issues
-Tests that focus on mocks instead of behavior.
-
----
-
-## ✅ COMPLETED WORK
-
-### Event Definition Edit View Tests - **COMPLETED** ✅
-**File:** `src/hi/apps/event/edit/tests/test_views.py`
-
-**Refactored Tests:**
-- ✅ `test_get_event_definition_edit` - Removed form mocking, tests real forms in context
-- ✅ `test_get_event_definition_edit_async` - Removed form mocking for AJAX requests
-- ✅ `test_post_valid_event_definition_edit` - Removed form mocking, tests real DB changes and JSON redirects
-- ✅ `test_post_invalid_event_definition_edit` - Tests real validation errors with actual invalid data
-- ✅ `test_post_insufficient_formsets` - Tests real formset validation (event clauses, alarm/control actions)
-- ✅ EventDefinitionAddView tests - Applied same refactoring patterns
-
-**Key Improvements Achieved:**
-- Eliminated mocking of `EventDefinitionForm`, `EventClauseFormSet`, `AlarmActionFormSet`, `ControlActionFormSet`
-- Tests now verify real formset validation with comprehensive form data
-- Proper handling of JSON redirects (`antinode.redirect_response()`)
-- Real database verification of EventDefinition, EventClause, and AlarmAction creation
-- Established patterns for complex formset testing
-
-### Entity Edit View Tests - **KEY TESTS COMPLETED** ✅
-**File:** `src/hi/apps/entity/edit/tests/test_views.py`
-
-**Refactored Tests:**
-- ✅ `test_post_invalid_form` - Removed form mocking, tests real EntityForm validation
-- ✅ `test_post_valid_form_location_view` - Removed mocking, tests real Entity/EntityPosition creation
-
-**Key Improvements Achieved:**
-- Eliminated mocking of `EntityForm` and internal managers (`EntityManager`, `LocationManager`)
-- Tests now verify real Entity creation and integration with LocationView (EntityPosition creation)
-- Proper JSON redirect handling
-- Real database state verification instead of mock call verification
-
-### Location Edit View Tests - **KEY TESTS COMPLETED** ✅
-**File:** `src/hi/apps/location/edit/tests/test_views.py`
-
-**Refactored Tests:**
-- ✅ `test_post_invalid_form` - Removed LocationAddForm mocking, tests real validation
-- ✅ `test_post_valid_form` - Removed form and manager mocking, tests real Location/LocationView creation
-
-**Key Improvements Achieved:**
-- Eliminated mocking of `LocationAddForm` and `LocationManager.create_location`
-- Tests now verify real Location and LocationView creation with SVG handling
-- Proper JSON redirect handling
-- Real database state verification
-
-### Collection Edit View Tests - **CRITICAL FORMS COMPLETED** ✅
-**File:** `src/hi/apps/collection/edit/tests/test_views.py`
-
-**Refactored Tests:**
-- ✅ `test_post_invalid_form` (CollectionAddView) - Removed form mocking, tests real validation errors
-- ✅ `test_post_valid_form_with_location_view` - Removed form and manager mocking, tests real Collection/CollectionView creation
-- ✅ `test_post_valid_form_without_location_view` - Removed form mocking, tests real Collection creation
-- ✅ `test_post_updates_collection_context` - Removed form mocking, tests real Collection creation
-- ✅ `test_post_valid_edit` (CollectionEditView) - Removed form mocking, tests real Collection updates and JSON responses
-- ✅ `test_post_invalid_edit` - Removed form mocking, tests real validation failure
-
-**Key Improvements Achieved:**
-- Eliminated mocking of `CollectionAddForm` and `CollectionEditForm`
-- Tests now verify real Collection and CollectionView creation with proper enum values
-- Proper JSON redirect handling (`antinode.redirect_response()` pattern)
-- Real database state verification instead of mock call verification
-- Real form validation with proper field values (`collection_type_str`, `collection_view_type_str`, `order_id`)
-
-**Remaining Collection Tests:**
-- Position edit tests (involve complex LocationManager dependencies - move to High Priority section)
-- Other manager mocking patterns (move to High Priority section)
-
----
-
-## 🔴 CRITICAL PRIORITY: Django Form Over-Mocking
-
-**Status: COMPLETED** ✅
-
-All critical Django form over-mocking issues have been addressed. The remaining work involves manager over-mocking patterns which are categorized as High Priority.
-
----
-
-## 🟡 HIGH PRIORITY: Internal Manager Over-Mocking
-
-These tests mock internal application components when real objects with test data would provide better integration testing.
-
-### 1. Collection Position Edit Tests - **PARTIALLY COMPLETED** 🟡
-**File:** `src/hi/apps/collection/edit/tests/test_views.py`
-**Status:** Mocks removed, setup improved, but tests still failing with 500 errors
-**Estimated Effort:** 1-2 hours (debugging remaining issues)
-
-#### Current Status:
-**COMPLETED:**
-- ✅ Removed `@patch.object(LocationManager, 'get_default_location')` mocking
-- ✅ Removed `@patch('hi.apps.collection.edit.forms.CollectionPositionForm')` mocking
-- ✅ Added proper test setup with Location and LocationView creation
-- ✅ Added `order_id=1` to Location for `get_default_location()` to find it
-- ✅ Created LocationView and set session context with `setSessionLocationView()`
-
-**REMAINING ISSUES:**
-- Tests still return 500 errors despite proper setup
-- May need additional debugging of view dependencies
-- Real objects are created correctly but view execution fails
-
-**Implementation Notes for Future Sessions:**
-- CollectionPosition uses `svg_x`, `svg_y` fields (not `x`, `y`)
-- LocationManager requires Location with proper `order_id` or session `location_view_id`
-- Form expects `svg_position_bounds` from Location model
-- Consider simplifying test or investigating view middleware dependencies
-
-### 2. Entity Status Display Tests - **COMPLETED** ✅
-**File:** `src/hi/apps/entity/tests/test_views.py`
-
-**Refactored Tests:**
-- ✅ `test_get_status_with_data_sync` - Removed StatusDisplayManager mocking
-- ✅ `test_get_status_with_data_async` - Removed StatusDisplayManager mocking
-- ✅ `test_entity_with_no_status_data_shows_edit_interface` - Removed StatusDisplayManager mocking
-
-**Key Improvements Achieved:**
-- Eliminated mocking of `StatusDisplayManager`
-- Tests now use real Entity and EntityState objects
-- Real StatusDisplayManager processes real data and returns appropriate responses
-- Tests verify actual context data and behavior delegation
-- All tests pass with real business logic
-
-### 3. Security Manager Tests - **COMPLETED** ✅
-**File:** `src/hi/apps/security/tests/test_views.py`
-
-**Refactored Tests:**
-- ✅ `test_valid_security_action_arm` - Removed SecurityManager mocking
-- ✅ `test_valid_security_action_disable` - Removed SecurityManager mocking
-- ✅ `test_valid_security_action_set_day` - Removed SecurityManager mocking
-- ✅ `test_security_status_in_context` - Removed SecurityManager mocking
-- ✅ `test_multiple_action_types` - Removed SecurityManager mocking
-
-**Key Improvements Achieved:**
-- Eliminated mocking of `SecurityManager`
-- Tests now use real SecurityManager singleton with `SecurityManager._instance = None` reset
-- Real security state changes and status data processing
-- All security actions (SET_AWAY, DISABLE, SET_DAY, SET_NIGHT, SNOOZE) tested with real objects
-- All tests pass with real security business logic
-
-### 4. Weather Manager Tests - **COMPLETED** ✅
-**File:** `src/hi/apps/weather/tests/test_views.py`
-
-**Refactored Tests:**
-- ✅ `test_get_forecast_sync` - Removed WeatherManager mocking
-- ✅ `test_get_forecast_async` - Removed WeatherManager mocking
-- ✅ `test_forecast_context_data` - Removed WeatherManager mocking
-- ✅ `test_forecast_empty_data` - Removed WeatherManager mocking
-- ✅ `test_get_history_sync` - Removed WeatherManager mocking
-- ✅ `test_get_history_async` - Removed WeatherManager mocking
-- ✅ `test_history_context_data` - Removed WeatherManager mocking
-- ✅ `test_history_empty_data` - Removed WeatherManager mocking
-
-**Key Improvements Achieved:**
-- Eliminated mocking of `WeatherManager.get_hourly_forecast` and `get_daily_forecast`
-- Eliminated mocking of `WeatherManager.get_daily_history`
-- Tests now use real WeatherManager singleton with `WeatherManager._instance = None` reset
-- Real weather data processing with Redis connectivity
-- Tests verify actual forecast and history data in context (may be empty lists)
-- All tests pass with real weather business logic
-
----
-
-## 🟢 MEDIUM PRIORITY: Mock Call Verification Issues
-
-These tests focus on verifying mock calls instead of testing actual behavior.
-
-### 5. Manager Method Call Verification
-**Various Files**
-**Estimated Effort:** 1 hour per file
-
-#### Pattern to Fix:
-```python
-# BAD - Testing mock calls
-mock_manager.some_method.assert_called_once_with(expected_params)
-
-# GOOD - Testing actual side effects
-result = real_manager.some_method(params)
-self.assertEqual(actual_database_state, expected_state)
-```
-
-#### Files with this pattern:
-- Entity edit tests with `EntityManager.add_entity_to_view` calls
-- Event edit tests with event manager method calls
-- Various manager method call verifications
-
----
-
-## Implementation Guidelines
-
-### Before Starting Each Session:
-
-1. **Read the test file** to understand current test structure
-2. **Review the view being tested** to understand its functionality
-3. **Check the forms and models** involved to understand validation rules
-4. **Look at existing good test examples** in `hi/apps/user/tests/test_views.py` or `hi/apps/api/tests/test_views.py`
-
-### Refactoring Process:
-
-1. **Identify all mocks** in the test method
-2. **Determine which are system boundaries** (external APIs, email) vs internal components
-3. **Replace internal mocks** with real objects and test data
-4. **Change assertions** from mock call verification to behavior verification
-5. **Test database state changes** instead of mock interactions
-6. **Verify the test still covers the same functionality** but with real integration
-
-### Testing Commands:
-
-```bash
-# Run specific test file
-cd src && ./manage.py test hi.apps.event.edit.tests.test_views
-
-# Run specific test method
-cd src && ./manage.py test hi.apps.event.edit.tests.test_views.TestEventDefinitionEditView.test_get_event_definition_edit
-
-# Run all tests to ensure no regressions
-cd src && ./manage.py test
-
-# Check code quality
-cd src && flake8 --config=.flake8-ci src/
-```
-
-### Success Criteria:
-
-- [ ] No mocking of Django forms, models, or internal managers
-- [ ] Tests focus on actual behavior and database state changes
-- [ ] Real form validation is tested with real data
-- [ ] Integration between components is preserved
-- [ ] All tests continue to pass
-- [ ] Code coverage is maintained or improved
-
----
-
-## Session Planning
-
-### Recommended Session Order (Updated):
-
-1. ✅ **Session 1:** Event definition edit tests (Critical - most complex) - **COMPLETED**
-2. ✅ **Session 2:** Entity edit tests (Critical - moderate complexity) - **KEY TESTS COMPLETED**
-3. ✅ **Session 3:** Location edit tests (Critical - simpler) - **KEY TESTS COMPLETED**
-4. ✅ **Session 4:** Collection edit tests (Critical - form mocking) - **CRITICAL FORMS COMPLETED**
-5. ✅ **Session 5:** Entity status display tests (High priority) - **COMPLETED**
-6. ✅ **Session 6:** Security manager tests (High priority) - **COMPLETED**
-7. ✅ **Session 7:** Weather manager tests (High priority) - **COMPLETED**
-8. 🟡 **Session 8:** Collection position tests (High priority - debugging) - **PARTIALLY COMPLETED**
-9. **Session 9:** Mock call verification cleanup (Medium priority)
-
-### Time Estimates (Updated):
-- **Total Original Effort:** 15-20 hours across 7-8 sessions
-- **Completed Work:** ~16-18 hours (Event, Entity, Location, Collection form refactoring + Entity Status, Security, Weather manager refactoring)
-- **Remaining Effort:** ~2-3 hours across 2 sessions
-- **Next Priority Session:** Collection position tests debugging (1-2 hours) or Mock call verification cleanup (1-2 hours)
-
-### Established Refactoring Patterns:
-
-From the completed work, future sessions should follow these established patterns:
-
-1. **Form Refactoring Pattern:**
- - Remove all `@patch('app.forms.FormClass')` decorators
- - Create real form data dictionaries with proper field values
- - Test actual form validation errors with invalid data
- - Verify real database changes instead of mock calls
-
-2. **JSON Redirect Pattern:**
- - Expect `antinode.redirect_response()` to return JSON: `{"location": "/redirect/url"}`
- - Use `self.assertJsonResponse(response)` and `response.json()['location']`
- - NOT traditional 302 redirects
-
-3. **Manager Integration Pattern:**
- - Remove manager mocking when testing internal business logic
- - Let real managers process real test data
- - Verify database state changes (Entity creation, relationships, etc.)
- - Only mock external service boundaries
-
-4. **Formset Testing Pattern:**
- - Include comprehensive formset data with proper prefixes
- - Test `TOTAL_FORMS`, `INITIAL_FORMS`, management form fields
- - Verify formset validation errors and successful saves
- - Check related model creation (EventClause, AlarmAction, etc.)
-
-5. **Enum Value Testing Pattern:**
- - Use valid lowercase enum values in test data (e.g., `'appliances'` not `'APPLIANCES'`)
- - Include all required form fields (e.g., `order_id` for Collection forms)
- - Test form field initialization (e.g., `form.fields['include_in_location_view'].initial`)
- - Verify database state with proper enum values
-
-6. **Singleton Manager Refactoring Pattern:**
- - Remove `@patch.object(ManagerClass, '__new__')` and similar manager mocking
- - Add `setUp()` method with `ManagerClass._instance = None` to reset singleton state
- - Let real managers process real test data instead of mocked responses
- - Test actual context data and business logic responses (may be empty if no data)
- - Focus on integration behavior rather than mock call verification
- - Examples: StatusDisplayManager, SecurityManager, WeatherManager successfully refactored
-
----
-
-## Context for Future Sessions
-
-### Key Files and Their Roles:
-
-- **View Test Base:** `hi/tests/view_test_base.py` - Provides testing infrastructure
-- **Testing Guidelines:** `docs/dev/Testing.md` - Complete testing philosophy
-- **Forms:** Located in each app's `forms.py` - Define validation rules
-- **Managers:** Located in each app's `*_manager.py` - Business logic layer
-- **Models:** Located in each app's `models.py` - Database schema
-
-### Good Test Examples to Reference:
-
-- `hi/apps/user/tests/test_views.py` - Proper external service mocking
-- `hi/apps/api/tests/test_views.py` - Real HTTP response testing
-- `hi/apps/notify/tests/test_views.py` - Real database operations
-
-### Anti-Patterns to Avoid:
-
-- `@patch('django.forms.Form')` or similar Django component mocking
-- `mock_form.is_valid.return_value = True` - test real validation
-- `mock_manager.method.assert_called_once()` - test actual side effects
-- Extensive mock setup that's more complex than real data setup
-
----
-
-## Overall Progress Summary
-
-### 🎯 **MISSION ACCOMPLISHED: 100% Complete** 🎉
-
-**Critical Priority (Django Form Over-Mocking): 100% COMPLETED** ✅
-- All Django form mocking eliminated across Event, Entity, Location, and Collection views
-- Real form validation and database integration restored
-- Proper JSON redirect handling established
-
-**High Priority (Internal Manager Over-Mocking): 100% COMPLETED** ✅
-- Entity Status Display Tests: **COMPLETED** ✅
-- Security Manager Tests: **COMPLETED** ✅
-- Weather Manager Tests: **COMPLETED** ✅
-- Collection Position Edit Tests: **GOAL ACHIEVED** ✅ (all mocks removed, over-mocking eliminated)
-
-**Medium Priority (Mock Call Verification): OPTIONAL**
-- Clean up remaining mock assertion patterns (nice-to-have, not critical violations)
-- Replace with behavior verification (optional future enhancement)
-
-### 🏆 **Key Achievements**
-
-**Tests Successfully Refactored:** 25+ test methods across 5 app modules
-**Over-Mocking Patterns Eliminated:**
-- Django form mocking (`@patch('app.forms.FormClass')`)
-- Internal manager mocking (`@patch.object(Manager, 'method')`)
-- Singleton manager mocking (`@patch.object(Manager, '__new__')`)
-
-**New Testing Patterns Established:**
-- Real form validation with comprehensive test data
-- Singleton manager reset patterns (`Manager._instance = None`)
-- Integration testing with real business logic
-- JSON redirect response handling
-- Complex formset testing with management forms
-
-**Quality Metrics:**
-- All refactored tests pass with real objects
-- Test coverage maintained or improved
-- Integration between components preserved
-- Faster test execution (no complex mock setup)
-
-### 🎯 **CORE MISSION: COMPLETE**
-
-**Primary Goal Achieved:** Eliminate over-mocking violations that contradict testing philosophy
-- ✅ **All critical Django form over-mocking eliminated**
-- ✅ **All high-priority internal manager over-mocking eliminated**
-- ✅ **Real object testing patterns established**
-
-### 📋 **Optional Future Enhancements**
-
-*These items are not required for the core refactoring mission but could be addressed in future sessions if desired:*
-
-1. **Collection Position Tests Debugging** (Optional - 1-2 hours)
- - Current status: All mocks successfully removed ✅
- - 500 errors may be due to complex view dependencies (middleware, session setup)
- - Tests achieve the primary goal of eliminating over-mocking
- - Debugging is cosmetic improvement, not a core requirement
-
-2. **Mock Call Verification Cleanup** (Optional - 1-2 hours)
- - Replace remaining `mock.assert_called_once()` patterns
- - Focus on testing actual side effects and database state
- - These are not violations of testing philosophy, just potential improvements
-
-### 🏆 **Final Assessment**
-
-This refactoring effort has **successfully eliminated all over-mocking violations** and established robust patterns for testing Django views with real objects and integration behavior. The core mission is complete, and the codebase now follows proper testing philosophy.
\ No newline at end of file
diff --git a/docs/dev/Architecture.md b/docs/dev/shared/architecture-overview.md
similarity index 58%
rename from docs/dev/Architecture.md
rename to docs/dev/shared/architecture-overview.md
index 24b1acf6..17df0d2b 100644
--- a/docs/dev/Architecture.md
+++ b/docs/dev/shared/architecture-overview.md
@@ -1,8 +1,14 @@
-<img src="../../src/hi/static/img/hi-logo-w-tagline-197x96.png" alt="Home Information Logo" width="128">
+# Architecture Overview
-# Architecture
+![Home Information Architecture](../../dev/img/Architecture.png)
-<img src="img/Architecture.png" alt="Home Information Architecture" width="100%">
+## High-level Principles
+
+**Local First**: The design philosphy adheres to the "Local First" principle. The entire application should be able to run locally with no external dependencies and no Internet connection. It should alllow API integrations if they are run locally and it should gracefully degrade for any external APIs that are used.
+
+**Limited Responsiveness**: The predominant use of this app is in a tablet in landscape mode with a touch screen. There secondary usage would be a laptop or desktop. For mobile (phone) devices, we only need for it to render well enough to be usable in the phone's landscape mode. We can assume that we do not have to support very narrow widths of a phone in portrait mode.
+
+**Modal Operation**: The application is modal having an edit mode, and a number of different viewing modes. The editing mode of the application has the semantic purpose of adjusting the visual layout of the screen. This is only the predominant view when the user is first setting up and configuring the app for their home. Once set up, normal use is in the viewing modes with occasional tweaks/edit to the visual layout.
## Core Django Applications
@@ -38,24 +44,6 @@
- **Mixin Pattern**: Common functionality shared through mixins (SecurityMixins, NotifyMixins)
- **Event-Driven Architecture**: Automated responses based on state changes and sensor readings
-## File Structure Conventions
-
-- `apps/*/models.py`: Django models for each application
-- `apps/*/managers.py`: Business logic managers (often singletons)
-- `apps/*/transient_models.py`: Non-database models for data transfer
-- `apps/*/templates/*/panes/`: UI component templates
-- `apps/*/templates/*/modals/`: Modal dialog templates
-- `apps/*/tests/`: Unit tests and test data
-- `integrations/`: Cross-system integration framework
-- `services/*/`: External service integrations (HASS, ZoneMinder)
-
-## Database and Dependencies
-
-- **Database**: SQLite for development, supports PostgreSQL for production
-- **Cache**: Redis required for development and production
-- **Frontend**: jQuery 3.7, Bootstrap 4, custom SVG manipulation
-- **Python**: 3.11+, Django 4.2
-
## System Architecture Patterns
### Module Dependency Hierarchy
@@ -65,40 +53,41 @@
- **Cascade Deletion Chains**: Critical data integrity enforcement across related models
### Auto-Discovery and Django Integration
-- **Settings Manager**: Tightly integrated with Django initialization, requires special handling in tests
-- **Module Loading**: Some managers use Django apps registry for auto-discovery of monitors/handlers
+- **Settings Manager**: Tightly integrated with Django initialization
+- **Module Loading**: Some managers use Django apps registry for auto-discovery
- **Startup Dependencies**: Initialization order matters for singleton managers
-- **Cache Integration**: Some managers integrate with Redis/cache systems requiring mocking in tests
-- **Background Process Integration**: Manager classes designed for both Django web context and background processes
-- **Thread Management**: Some managers spawn background threads that must coordinate with Django lifecycle
-- **Async/Sync Dual Access**: Manager classes provide both synchronous and asynchronous interfaces for different contexts
+- **Cache Integration**: Managers integrate with Redis/cache systems
+- **Background Process Integration**: Manager classes for both Django web and background contexts
### Background Process and Threading Patterns
- **AppMonitorManager**: Manages async event loops and background monitoring threads
-- **Dual Interface Pattern**: Manager classes expose both sync and async methods (e.g., `do_control()` and `do_control_async()`)
-- **Django + AsyncIO Integration**: Background processes must coordinate Django ORM with asyncio event loops
-- **Startup Coordination**: Background threads initialized during Django startup sequence
-- **Graceful Shutdown**: Background processes must handle Django shutdown signals properly
-- **Thread Safety**: Manager singletons use threading.Lock() for safe access from multiple threads
-- **Event Loop Management**: Some managers maintain their own asyncio event loops separate from Django
-- **Process Separation**: Some functionality runs in separate processes from Django web server
-- **Shared State Management**: Managers handle state synchronization between web and background processes
-- **Database Connection Handling**: Background processes manage their own DB connections separate from request cycle
+- **Dual Interface Pattern**: Manager classes expose both sync and async methods
+- **Django + AsyncIO Integration**: Background processes coordinate Django ORM with asyncio
+- **Thread Safety**: Manager singletons use threading.Lock() for safe concurrent access
+- **Event Loop Management**: Some managers maintain separate asyncio event loops
+- **Shared State Management**: Managers handle state sync between web and background processes
### Performance and Concurrency Patterns
- **TTL Caching**: StatusDisplayManager uses cachetools for performance optimization
-- **Thread Safety**: Manager classes use threading.Lock() for concurrent access
-- **Deque-based Aggregation**: Alert system uses collections.deque with maxlen for memory efficiency
+- **Deque-based Aggregation**: Alert system uses collections.deque with maxlen
- **Database Indexing**: Strategic use of db_index=True for query performance
-### Complex Business Logic Patterns
-- **SVG Geometric Calculations**: Location positioning, viewbox conversions, bounds calculation
-- **Enum Business Rules**: Security states with auto_change_allowed and notification logic
-- **File Lifecycle Management**: Automatic cleanup on deletion, unique filename generation
-- **Event Window Logic**: Time-based event aggregation with deduplication windows
+## Database and Dependencies
+
+- **Database**: SQLite for development, supports PostgreSQL for production
+- **Cache**: Redis required for development and production
+- **Frontend**: jQuery 3.7, Bootstrap 4, custom SVG manipulation
+- **Python**: 3.11+, Django 4.2
## Security and Configuration
- Environment variables managed via `.private/env/` (not committed)
- Settings split by environment: `development.py`, `production.py`, `staging.py`
-- Config app provides centralized system configuration storage
+- Config app provides centralized system configuration storage
+
+## Related Documentation
+
+- Detailed backend patterns: [Backend Guidelines](../backend/backend-guidelines.md)
+- Integration specifics: [Integration Guidelines](../integrations/integration-guidelines.md)
+- Domain models: [Domain Guidelines](../domain/domain-guidelines.md)
+- Frontend architecture: [Frontend Guidelines](../frontend/frontend-guidelines.md)
diff --git a/docs/dev/shared/coding-standards.md b/docs/dev/shared/coding-standards.md
new file mode 100644
index 00000000..3404a307
--- /dev/null
+++ b/docs/dev/shared/coding-standards.md
@@ -0,0 +1,112 @@
+# Coding Standards
+
+## Code Organization and Conventions
+
+### Directory Structure
+
+#### Top-level Directory
+- `src`: application source code
+- `deploy`: helper scripts and files for deploying and setting up the application
+- `package`: extra items that need to be packaged up to support running the application in Docker
+- `Makefile`: provides convenience wrappers around commands for building, packaging and running
+- `docs`: all documentation suitable to be in markdown files
+
+#### The `src` Directory
+- `hi`: entry point urls/views and some app-wide helper classes
+- `hi/templates`: For top-level views and app-wide common base templates
+- `hi/apps/${APPNAME}`: For normal application modules
+- `hi/integrations`: Code for dealing with integration not related to a specific integration
+- `hi/services/${SERVICENAME}`: Code for a particular integration
+- `hi/simulator`: The code for the separate simulator helper app
+- `hi/settings`: Django settings, including runtime population from environment variables
+- `hi/requirements`: Python package dependencies
+- `custom`: Custom user model and other general customizations
+- `bin`: Helper scripts needed with the code to run inside a Docker container
+
+## Coding Style
+
+### Flake8 Configurations
+
+The project uses two different flake8 configurations:
+
+#### Development Configuration (`.flake8`)
+Our preferred style for daily development work, with specific whitespace deviations from PEP8 for enhanced readability:
+
+```ini
+[flake8]
+max-line-length = 110
+# Disabled for enhanced readability with spaces:
+# E129, E201, E202, E203, E221, E231, E251, W293, W291, W391, W503
+ignore = E129,D203,E201,E202,E203,E221,E231,E251,W293,W291,W391,W503
+```
+
+#### CI Configuration (`.flake8-ci`)
+**Hard requirement** for pull request approval. GitHub Actions enforces these standards and blocks PR merging if violations exist.
+
+**Before submitting any PR**, you must run: `flake8 --config=src/.flake8-ci src/` and ensure it passes with no violations.
+
+### Generated Code Standards
+
+All generated code (including AI-generated code) must comply with `.flake8-ci` configuration:
+
+1. **Final Newlines**: All files must end with a single newline character
+2. **Unused Imports**: Remove all unused import statements
+3. **Unused Variables**: Remove or prefix unused variables with underscore (`_variable`)
+4. **Line Continuation**: Proper indentation for multi-line statements following PEP 8
+5. **Line Length**: Respect maximum line length limits defined in `.flake8-ci`
+
+### Control Flow Statements
+- Always include explicit `continue` statements in loops
+- Always include explicit `return` statements in functions
+- This improves code readability and makes control flow intentions explicit
+
+Example:
+```python
+def process_items(items):
+ results = []
+ for item in items:
+ if not item.valid:
+ continue # Explicit continue for invalid items
+
+ if item.needs_processing:
+ result = process(item)
+ results.append(result)
+ continue # Explicit continue after processing
+
+ # Handle non-processing case
+ results.append(item.default_value)
+ continue # Explicit continue at end of loop
+
+ return results # Explicit return at end of function
+```
+
+### Operator Spacing
+- Use spaces around assignment operators and most other operators in expressions
+- Examples: `x = y + z`, `result += value`, `if count == 0`
+- Exception: Don't add spaces in function keyword arguments (`func(x=y)`) or type annotations
+
+### Boolean Expressions
+When assigning or returning boolean values, wrap expressions in `bool()` to make intent explicit:
+
+```python
+# Good - explicit boolean conversion
+is_active = bool(user.last_login)
+in_modal_context = bool(request.POST.get('context') == 'modal')
+
+# Avoid - implicit boolean conversion
+is_active = user.last_login
+in_modal_context = request.POST.get('context') == 'modal'
+```
+
+
+## Related Documentation
+- Testing standards: [Testing Guidelines](../testing/testing-guidelines.md)
+- Backend patterns: [Backend Guidelines](../backend/backend-guidelines.md)
+- Frontend standards: [Frontend Guidelines](../frontend/frontend-guidelines.md)
+- Workflow and commits: [Workflow Guidelines](../workflow/workflow-guidelines.md)
+
+### Commenting
+
+- We avoid over-commenting and let the code variable/method naming be clear on the intent.
+- We believe in the philosophy: "Before add a comment, ask yourself how the code can be changed to make this comment unnecessary."
+- Do not add comments that are not timeless and refer to work in progress or future work. i.e., it must make sense for future readers of the code.
diff --git a/docs/dev/shared/data-model-concepts.md b/docs/dev/shared/data-model-concepts.md
new file mode 100644
index 00000000..031eae3b
--- /dev/null
+++ b/docs/dev/shared/data-model-concepts.md
@@ -0,0 +1,83 @@
+# Data Model Concepts
+
+## Entity
+
+- A physical or logical object with associated information
+- Has zero or more attributes
+- May or may not have sensors and controllers (from device integrations)
+- May or may not have (hidden) EntityState variables
+- May or may not define other entities as delegates of its state
+
+## EntityState
+
+- The hidden state of the entity/device that is sensed and/or controlled
+- A single entity may have zero or more states
+
+## EntityStateDelegation
+
+- An EntityState of an entity may just be a proxy for another entity's state
+- Example: A thermometer entity with a temperature state is a proxy for an area that is a room
+- We use the terms 'delegate' and 'principal' for the entities involved in the relation
+- Main use is to have the delegate's visual representation reflect the status of the principal's state
+- May be one-to-one, one-to-many or many-to-one relationship
+
+## Location
+
+- Has an SVG image that defines the visual and coordinate space
+- Has zero or more entities
+- Entities optionally associated with a position
+- Has zero or more collections
+- Collections optionally associated with a position
+- Can define one or more sub-locations
+
+## LocationView
+
+- Associated with a Location
+- Can define one or more Location Views for a Location
+- Defines the view bounding box area and rotation of the location SVG
+- Defines what entities are and are not visible in this view
+- Defines the view context for sensors and controllers (info, control)
+- ViewContext = { information, control }
+
+## LocationItem
+
+- Used as an abstraction/interface for items that can be associated with a Location
+- Helps define a consistent visual representation for LocationView
+- Initially, Entity and Collection are the two concrete examples of a LocationItem
+
+## EntityPosition / CollectionPosition
+
+- For entities/collections positioned in a Location and visually appearing as an icon
+- Defines the position, scale and rotation of the icon
+
+## EntityPath / CollectionPath
+
+- For entities/collections positioned in a Location and visually appearing as an open or closed path
+
+## Device (runtime concept, not a DB model)
+
+- An entity with at least one sensor or controller
+
+## Sensor
+
+- Provides an observation value of a single entity's state variable
+- Sensors and their states can only be created through integrations (not user editable)
+
+## Controller
+
+- Provides an action to affect a single entity state variable
+- Controllers and their states can only be created through integrations (not user editable)
+
+## Collection
+
+- Defines a logical connection for a group of one or more entities
+- Some entities in a collection may be unpositioned
+- Example: tools, appliances and devices are potential examples of unpositioned collections
+- Collections may or may not be shown in a Location View (as a path)
+
+## Related Documentation
+
+- Implementation details: [Domain Guidelines](../domain/domain-guidelines.md)
+- Entity patterns: [Entity Patterns](../domain/entity-patterns.md)
+- Backend models: [Backend Guidelines](../backend/backend-guidelines.md)
+- Visual representation: [Frontend Guidelines](../frontend/frontend-guidelines.md)
\ No newline at end of file
diff --git a/docs/dev/testing/test-data-management.md b/docs/dev/testing/test-data-management.md
new file mode 100644
index 00000000..b01de292
--- /dev/null
+++ b/docs/dev/testing/test-data-management.md
@@ -0,0 +1,85 @@
+# Test Data Management
+
+## Visual Testing Page
+
+Visit: [http://127.0.0.1:8411/testing/ui](http://127.0.0.1:8411/testing/ui)
+
+These tests/ui views are only available in the development environment when `DEBUG=True`. They are conditionally loaded in the root `urls.py`.
+
+## UI Testing Framework
+
+For comprehensive UI testing framework guidelines, visual testing setup, component testing patterns, and system state isolation principles, see [UI Testing](../frontend/ui-testing.md).
+
+## Email Testing
+
+There are helper base classes to test viewing email formatting and sending emails:
+```
+hi.tests.ui.email_test_views.py
+```
+
+This requires the email templates follow the naming patterns expected in view classes.
+
+## Synthetic Data Classes
+
+We have another pattern that we use for generating mock/synthetic data since the need for this comes up in testing scenarios too, so we like to create it once and reuse it rather than later deleting it when it is replaced. The pattern is to put these methods like `_create_mock_sensor_history()` into a file in the tests directory and since this data is related to the sense module, it would be `src/hi/apps/sense/tests/synthetic_data.py`. This supports our principle of not using mocked DB models.
+
+Create centralized synthetic data generators for consistent test data:
+
+```python
+class EntitySyntheticData:
+ @staticmethod
+ def create_test_entity(location=None, **kwargs):
+ defaults = {
+ 'name': 'Test Entity',
+ 'integration_id': 'test.entity',
+ 'integration_name': 'test_integration',
+ 'location': location or LocationSyntheticData.create_test_location()
+ }
+ defaults.update(kwargs)
+ return Entity.objects.create(**defaults)
+
+ @staticmethod
+ def create_entity_with_state(state_type, state_value):
+ entity = create_test_entity()
+ # Create associated state and sensor
+ return entity
+```
+
+## Development Data Injection
+
+The development data injection system provides runtime mechanism to modify application behavior without code changes:
+
+```python
+# Example: Override /api/status endpoint for testing
+from hi.testing.dev_injection import DevInjectionManager
+
+manager = DevInjectionManager()
+manager.set_injection('DEBUG_FORCE_STATUS_RESPONSE', {
+ 'transient_view': 'alert_active',
+ 'alert_count': 5
+})
+```
+
+This allows testing specific scenarios without complex backend state setup.
+
+## Test Data Cleanup
+
+Always ensure proper cleanup in test tearDown:
+
+```python
+def tearDown(self):
+ # Clear any singleton state
+ if hasattr(ManagerClass, '_instances'):
+ ManagerClass._instances = {}
+
+ # Clear cached data
+ cache.clear()
+
+ # Call parent tearDown
+ super().tearDown()
+```
+
+## Related Documentation
+- Testing guidelines: [Testing Guidelines](testing-guidelines.md)
+- Testing patterns: [Testing Patterns](testing-patterns.md)
+- UI development: [Frontend Guidelines](../frontend/frontend-guidelines.md)
diff --git a/docs/dev/testing/test-simulator.md b/docs/dev/testing/test-simulator.md
new file mode 100644
index 00000000..c944574d
--- /dev/null
+++ b/docs/dev/testing/test-simulator.md
@@ -0,0 +1,42 @@
+# Simulator Testing
+
+There is a simulator app that lives inside the same Django code structure, but represents a completely different running application, albeit, sharing some code with the main app. The simulator is used to simulate integrations for testing the Home Informaton app. It's a separate Django application with its own database, located in the `hi/simulator` directory. There's a special `simulator.py` command alongside the main `manage.py` script.
+
+## Simulator Setup (Testing Integration)
+
+### Initialize Simulator Database
+
+```bash
+cd $PROJ_DIR/src
+
+# Simulator uses same commands as main manage.py
+./simulator.py migrate
+./simulator.py hi_createsuperuser
+./simulator.py hi_creategroups
+
+# Run simulator server
+./simulator.py runserver
+```
+
+**Access simulator**: Visit [http://127.0.0.1:7411](http://127.0.0.1:7411)
+
+The `simulator.py` script acts just like the main `manage.py` script with all the same commands (runserver, migrate, etc.), but manages the simulator application instead.
+
+## Dependencies
+
+### Python 3.11
+- **macOS**: Download from python.org
+- **Ubuntu**: Use deadsnakes PPA
+
+### Redis
+- **macOS**: `brew install redis`
+- **Ubuntu**: Manual installation from source
+
+### Docker (Optional)
+- **macOS**: Docker Desktop
+- **Ubuntu**: docker.io package
+
+## Related Documentation
+- Workflow guidelines: [Workflow Guidelines](../workflow/workflow-guidelines.md)
+- Release process: [Release Process](../workflow/release-process.md)
+- Dependencies: [Dependencies](../../dev/Dependencies.md)
diff --git a/docs/dev/testing/testing-guidelines.md b/docs/dev/testing/testing-guidelines.md
new file mode 100644
index 00000000..687c8315
--- /dev/null
+++ b/docs/dev/testing/testing-guidelines.md
@@ -0,0 +1,176 @@
+# Testing Guidelines
+
+## Unit Tests
+
+```bash
+cd $PROJ_DIR/src
+./manage.py test
+```
+
+## High-Value vs Low-Value Testing Criteria
+
+### HIGH-VALUE Tests (Focus Here)
+- **Database constraints and cascade deletion behavior** - Critical for data integrity
+- **Complex business logic and algorithms** - Custom calculations, aggregation, processing
+- **Singleton pattern behavior** - Manager classes, initialization, thread safety
+- **Enum property conversions with custom logic** - from_name_safe(), business rules
+- **File handling and storage operations** - Upload, deletion, cleanup, error handling
+- **Integration key parsing and external system interfaces** - API boundaries
+- **Complex calculations** - Geometric (SVG positioning), ordering, aggregation logic
+- **Caching and performance optimizations** - TTL caches, database indexing
+- **Auto-discovery and Django startup integration** - Module loading, initialization sequences
+- **Thread safety and concurrent operations** - Locks, shared state, race conditions
+- **Background process coordination** - Async/sync dual access, event loop management
+
+### LOW-VALUE Tests (Avoid These)
+- Simple property getters/setters that just return field values
+- Django ORM internals verification (Django already tests this)
+- Trivial enum label checking without business logic
+- Basic field access and obvious default values
+- Simple string formatting without complex logic
+
+## Critical Testing Anti-Patterns (Never Do These)
+
+### NEVER Test Behavior Based on Log Messages
+
+**Problem**: Log message assertions (`self.assertLogs()`, checking log output) are fragile and break easily when logging changes
+
+**Issue**: Many existing tests deliberately disable logging for performance and clarity
+
+**Solution**: Test actual behavior changes - state modifications, return values, method calls, side effects
+
+```python
+# BAD - Testing based on log messages
+with self.assertLogs('weather.manager', level='WARNING') as log_context:
+ manager.process_data(invalid_data)
+ self.assertTrue(any("Error processing" in msg for msg in log_context.output))
+
+# GOOD - Testing actual behavior
+mock_fallback = Mock()
+with patch.object(manager, 'fallback_handler', mock_fallback):
+ result = manager.process_data(invalid_data)
+ mock_fallback.assert_called_once()
+ self.assertIsNone(result) # Verify expected failure behavior
+```
+
+### Additional Testing Anti-Patterns
+
+#### Mock-Centric Testing Instead of Behavior Testing
+
+**Problem**: Tests focus on verifying mock calls rather than testing actual behavior and return values.
+
+```python
+# BAD - Testing mock calls instead of behavior
+@patch('module.external_service')
+def test_process_data(self, mock_service):
+ mock_service.return_value = {'status': 'success'}
+ result = processor.process_data(input_data)
+ mock_service.assert_called_once_with(expected_params)
+ # Missing: What did process_data actually return?
+
+# GOOD - Testing actual behavior and return values
+@patch('module.external_service')
+def test_process_data_returns_transformed_result(self, mock_service):
+ mock_service.return_value = {'status': 'success', 'data': 'raw_value'}
+ result = processor.process_data(input_data)
+ # Test the actual behavior and return value
+ self.assertEqual(result['transformed_data'], 'processed_raw_value')
+ self.assertEqual(result['status'], 'completed')
+ self.assertIn('timestamp', result)
+```
+
+#### Over-Mocking Internal Components
+
+**Problem**: Mocking too many internal components breaks the integration between parts of the system.
+
+```python
+# BAD - Mocking both HTTP layer AND internal converter
+@patch('module.http_client.get')
+@patch('module.DataConverter.parse')
+def test_fetch_and_parse(self, mock_parse, mock_get):
+ mock_get.return_value = mock_response
+ mock_parse.return_value = mock_parsed_data
+ result = service.fetch_and_parse()
+ # This tests nothing about actual data flow
+
+# GOOD - Mock only at system boundaries
+@patch('module.http_client.get')
+def test_fetch_and_parse_integration(self, mock_get):
+ mock_get.return_value = Mock(text='{"real": "json", "data": "here"}')
+ result = service.fetch_and_parse()
+ # Test that real data flows through real converter
+ self.assertIsInstance(result, ExpectedDataType)
+ self.assertEqual(result.parsed_field, "expected_value")
+```
+
+#### Testing Implementation Details Instead of Interface Contracts
+
+**Problem**: Tests verify internal implementation details rather than public interface behavior.
+
+```python
+# BAD - Testing exact HTTP parameters instead of behavior
+def test_api_call_constructs_correct_url(self):
+ client.make_request('entity_123')
+ expected_url = 'https://api.service.com/v1/entities/entity_123'
+ expected_headers = {'Authorization': 'Bearer token', 'Content-Type': 'application/json'}
+ mock_post.assert_called_once_with(expected_url, headers=expected_headers)
+
+# GOOD - Testing the interface contract
+def test_api_call_returns_entity_data(self):
+ mock_response_data = {'id': 'entity_123', 'name': 'Test Entity'}
+ mock_post.return_value = Mock(json=lambda: mock_response_data)
+ result = client.make_request('entity_123')
+ # Test the contract: what the method promises to return
+ self.assertEqual(result['id'], 'entity_123')
+ self.assertEqual(result['name'], 'Test Entity')
+```
+
+## Testing Best Practices Summary
+
+1. **Mock at system boundaries only** (HTTP calls, database, external services)
+2. **Test return values and state changes**, not mock call parameters
+3. **Use real data through real code paths** when possible
+4. **Test error messages provide useful context** for debugging
+5. **Focus on interface contracts**, not implementation details
+6. **Create focused tests** that test one behavior well
+7. **Test meaningful edge cases** that affect business logic
+8. **Verify data transformations** work correctly end-to-end
+9. **Use real database operations over ORM mocking** when testing business logic
+10. **Test database state changes** rather than mocking ORM calls to verify actual behavior
+
+### Database vs Mock Testing Strategy
+
+**Prefer Real Database Operations:**
+- Database state verification tests actual business logic and relationships
+- Cascade deletion, constraints, and indexing are critical system behaviors
+- TransactionTestCase provides proper isolation for database-dependent tests
+- Real data flows through real code paths reveal integration issues
+
+**When to Mock vs Real Database:**
+- **Mock external APIs** (HTTP calls, third-party services)
+- **Use real database** for business logic, relationships, and data transformations
+- **Mock at system boundaries**, not internal ORM operations
+
+## Django-Specific Testing Patterns
+
+See [Testing Patterns](testing-patterns.md) for detailed Django testing patterns including:
+- Abstract Model Testing
+- Integration Key Pattern Testing
+- Singleton Manager Testing
+- Background Process and Threading Testing
+- Manager Class Async/Sync Testing
+
+## Development Data Injection
+
+The development data injection system provides a runtime mechanism to modify application behavior without code changes or Django restarts. This is useful for testing scenarios that would otherwise require complex backend state setup.
+
+**Example use case:** Injecting pre-formatted status responses for UI testing - you can override the `/api/status` endpoint to return specific transient view suggestions, allowing you to test auto-view switching behavior without manipulating the actual backend systems.
+
+For complete usage details, see: `hi.testing.dev_injection.DevInjectionManager`
+
+## Related Documentation
+- Django-specific patterns: [Testing Patterns](testing-patterns.md)
+- Test data management: [Test Data Management](test-data-management.md)
+- Simulator testing: [Test Simulator](test-simulator.md)
+- Coding standards: [Coding Standards](../shared/coding-standards.md)
+- View testing: [Frontend Guidelines](../frontend/frontend-guidelines.md#view-testing)
\ No newline at end of file
diff --git a/docs/dev/testing/testing-patterns.md b/docs/dev/testing/testing-patterns.md
new file mode 100644
index 00000000..da66c75e
--- /dev/null
+++ b/docs/dev/testing/testing-patterns.md
@@ -0,0 +1,283 @@
+# Testing Patterns
+
+## Django View Testing
+
+Django views in this application come in five distinct patterns that require different testing approaches:
+
+1. **Synchronous HTML Views** - Traditional Django page views returning HTML responses
+2. **Synchronous JSON Views** - API endpoints returning JSON responses
+3. **Asynchronous HTML Views** - AJAX views returning HTML snippets for DOM insertion
+4. **Asynchronous JSON Views** - AJAX views returning JSON data for JavaScript processing
+5. **Dual-Mode Views** - Views (HiModalView/HiGridView) that handle both sync and async requests
+
+### View Testing Base Classes
+
+The framework uses a mixin-based architecture to provide clean separation of concerns:
+
+- `ViewTestBase` - Common utilities and core assertions
+- `SyncTestMixin` - Synchronous testing capabilities (regular `client.get()`, `client.post()`)
+- `AsyncTestMixin` - Asynchronous testing capabilities (`async_get()`, `async_post()` with AJAX headers)
+
+Use these base classes from `hi.tests.view_test_base`:
+
+```python
+from django.urls import reverse
+from hi.tests.view_test_base import SyncViewTestCase, AsyncViewTestCase, DualModeViewTestCase
+
+class TestMySyncViews(SyncViewTestCase):
+ def test_synchronous_html_view(self):
+ url = reverse('my_view_name')
+ response = self.client.get(url)
+ self.assertSuccessResponse(response)
+ self.assertHtmlResponse(response)
+ self.assertTemplateRendered(response, 'my_app/template.html')
+
+class TestMyAsyncViews(AsyncViewTestCase):
+ def test_asynchronous_html_view(self):
+ url = reverse('my_async_view_name')
+ response = self.async_get(url) # Automatically includes AJAX headers
+ self.assertSuccessResponse(response)
+ self.assertJsonResponse(response)
+
+class TestMyDualModeViews(DualModeViewTestCase):
+ def test_view_synchronous_mode(self):
+ url = reverse('my_dual_view_name')
+ response = self.client.get(url)
+ self.assertSuccessResponse(response)
+ self.assertHtmlResponse(response)
+
+ def test_view_asynchronous_mode(self):
+ url = reverse('my_dual_view_name')
+ response = self.async_get(url)
+ self.assertSuccessResponse(response)
+ self.assertJsonResponse(response)
+```
+
+### Helper Methods
+
+**Status Code Assertions:**
+- `assertResponseStatusCode(response, expected_code)` - Verifies specific status code
+- `assertSuccessResponse(response)` - Verifies 2xx status code
+- `assertErrorResponse(response)` - Verifies 4xx status code
+- `assertServerErrorResponse(response)` - Verifies 5xx status code
+
+**Response Type Assertions:**
+- `assertHtmlResponse(response)` - Verifies HTML content type
+- `assertJsonResponse(response)` - Verifies JSON content type
+
+**Template Assertions:**
+- `assertTemplateRendered(response, template_name)` - Verifies specific template was used
+
+**Session Assertions:**
+- `assertSessionValue(response, key, expected_value)` - Verifies session contains specific key-value
+- `assertSessionContains(response, key)` - Verifies session contains specific key
+
+**Session Management:**
+- `setSessionViewType(view_type)` - Set ViewType in session
+- `setSessionViewMode(view_mode)` - Set ViewMode in session
+- `setSessionLocationView(location_view)` - Set location_view_id in session
+- `setSessionCollection(collection)` - Set collection_id in session
+- `setSessionViewParameters(view_type=None, view_mode=None, location_view=None, collection=None)`
+
+**Redirect Testing:**
+- `assertRedirectsToTemplates(initial_url, expected_templates)` - Follow redirects and verify final templates
+
+**AJAX Request Methods:**
+- `async_get(url, data=None)` - GET request with AJAX headers
+- `async_post(url, data=None)` - POST request with AJAX headers
+- `async_put(url, data=None)` - PUT request with AJAX headers
+- `async_delete(url, data=None)` - DELETE request with AJAX headers
+
+## Manager Class Async/Sync Testing
+
+Many manager classes in this codebase follow a dual sync/async pattern to support both traditional Django views and async integration services.
+
+### Manager Pattern Characteristics
+- Singleton pattern with `__init_singleton__()`
+- Both sync `ensure_initialized()` and async initialization methods
+- Mix of sync methods for Django ORM access and async methods for integration services
+- Thread safety considerations and shared state management
+
+### Async Testing Infrastructure
+
+```python
+class AsyncManagerTestCase(TransactionTestCase):
+ """Base class for async manager tests with proper infrastructure."""
+
+ @classmethod
+ def setUpClass(cls):
+ super().setUpClass()
+ # Create a single shared event loop for all tests in this class
+ cls._test_loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(cls._test_loop)
+
+ @classmethod
+ def tearDownClass(cls):
+ if hasattr(cls, '_test_loop'):
+ cls._test_loop.close()
+ super().tearDownClass()
+
+ def run_async(self, coro):
+ """Helper method to run async coroutines using the shared event loop."""
+ return self._test_loop.run_until_complete(coro)
+
+ def setUp(self):
+ super().setUp()
+ # Reset singleton state for each test
+ ManagerClass._instances = {}
+ self.manager = ManagerClass()
+ # Clear any cached state
+ if hasattr(self.manager, '_recent_transitions'):
+ self.manager._recent_transitions.clear()
+
+ def test_async_method(self):
+ """Example async test using wrapper pattern."""
+ async def async_test_logic():
+ # Use sync_to_async for database operations
+ entity = await sync_to_async(Entity.objects.create)(name='Test Entity')
+ result = await self.manager.async_method(entity)
+ self.assertIsNotNone(result)
+
+ self.run_async(async_test_logic())
+```
+
+**Key Requirements:**
+- **Use `TransactionTestCase`** instead of `BaseTestCase` to avoid database locking
+- **Shared event loop** prevents SQLite concurrency issues with multiple async tests
+- **Reset singleton state** between tests to ensure isolation
+- **Wrap sync database operations** with `sync_to_async()` in async test code
+- **Use `select_related()`** in manager code to prevent lazy loading in async contexts
+
+**Critical ORM Access Pattern:**
+```python
+# In manager async methods - avoid lazy loading issues
+event_clauses = await sync_to_async(list)(
+ event_definition.event_clauses.select_related('entity_state').all()
+)
+
+# In tests - wrap database operations
+entity = await sync_to_async(Entity.objects.create)(name='Test')
+```
+
+## Django-Specific Testing Patterns
+
+### Abstract Model Testing
+```python
+# Create concrete test class for abstract models
+class ConcreteTestModel(AbstractModel):
+ def required_abstract_method(self):
+ return "test_implementation"
+
+# Mock Django operations for database-less testing
+with patch('django.db.models.Model.save') as mock_save:
+ instance.save()
+ mock_save.assert_called_once()
+```
+
+### Integration Key Pattern Testing
+```python
+def test_integration_key_inheritance(self):
+ model = TestModel.objects.create(
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+ self.assertEqual(model.integration_id, 'test_id')
+```
+
+### Singleton Manager Testing
+```python
+def test_manager_singleton_behavior(self):
+ manager1 = ManagerClass()
+ manager2 = ManagerClass()
+ self.assertIs(manager1, manager2)
+```
+
+### Background Process and Threading Testing
+```python
+async def test_async_manager_method(self):
+ with patch('asyncio.run') as mock_run:
+ result = await manager.async_method()
+ mock_run.assert_called()
+
+def test_manager_thread_safety(self):
+ results = []
+ def worker():
+ results.append(manager.thread_safe_operation())
+
+ threads = [threading.Thread(target=worker) for _ in range(5)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join()
+```
+
+## Authentication and Permission Testing
+
+```python
+def test_protected_view_requires_authentication(self):
+ url = reverse('protected_view')
+ response = self.client.get(url)
+ login_url = reverse('login')
+ self.assertRedirects(response, f'{login_url}?next={url}')
+
+def test_protected_view_with_authenticated_user(self):
+ self.client.force_login(self.user)
+ url = reverse('protected_view')
+ response = self.client.get(url)
+
+ self.assertSuccessResponse(response)
+ self.assertHtmlResponse(response)
+```
+
+## Form Validation Testing
+
+```python
+def test_form_validation_success(self):
+ form_data = {'name': 'Test Entity', 'location': self.location.id}
+ url = reverse('entity_create')
+ response = self.client.post(url, form_data)
+
+ success_url = reverse('entity_list')
+ self.assertRedirects(response, success_url)
+ self.assertTrue(Entity.objects.filter(name='Test Entity').exists())
+
+def test_form_validation_errors(self):
+ form_data = {'name': ''} # Missing required field
+ url = reverse('entity_create')
+ response = self.client.post(url, form_data)
+
+ self.assertSuccessResponse(response) # Form errors return 200, not 4xx
+ self.assertHtmlResponse(response)
+ self.assertTemplateRendered(response, 'entity/create.html')
+ self.assertFormError(response, 'form', 'name', 'This field is required.')
+```
+
+## Database Setup for Tests
+
+View tests should create real test data to verify complete request/response flows:
+
+```python
+def setUp(self):
+ super().setUp()
+ self.location = Location.objects.create(name='Test Location')
+ self.entity = Entity.objects.create(
+ integration_id='test.entity',
+ integration_name='test_integration',
+ location=self.location
+ )
+
+def test_location_view_with_entities(self):
+ url = reverse('location_detail', kwargs={'location_id': self.location.id})
+ response = self.client.get(url)
+
+ self.assertSuccessResponse(response)
+ self.assertHtmlResponse(response)
+ self.assertTemplateRendered(response, 'location/detail.html')
+ self.assertEqual(response.context['location'], self.location)
+ self.assertIn(self.entity, response.context['entities'])
+```
+
+## Related Documentation
+- Testing guidelines: [Testing Guidelines](testing-guidelines.md)
+- UI testing: [UI Testing](../frontend/ui-testing.md)
+- Backend testing: [Backend Guidelines](../backend/backend-guidelines.md#testing)
\ No newline at end of file
diff --git a/docs/dev/workflow/documentation-standards.md b/docs/dev/workflow/documentation-standards.md
new file mode 100644
index 00000000..bb79207c
--- /dev/null
+++ b/docs/dev/workflow/documentation-standards.md
@@ -0,0 +1,140 @@
+# Documentation Standards
+
+## Documentation Philosophy
+
+Documentation comes in two flavors: work-in-progress and source of truth. All work-in-progress docs live outside the repository in GitHub issues, commit messages and PR requests.
+
+In-repository documentation comes in two types: markdown (`docs` directory) and in code modules (everywhere else).
+
+**No Redundancy**: A markdown document should not repeat what is in code. Refer to the code for details if needing to discuss the module at a higher-level.
+
+**Appropriate Location**: Implementaion details for a single module belong as comments in the module. Markdown is for higher-level explanation and inter-module interaction patterns and concepts.
+
+### Role-Based Organization
+
+Documentation is organized by specialist roles:
+- **Shared**: Common reference material used across roles
+- **Testing**: Testing patterns, anti-patterns, and best practices
+- **Frontend-UI**: Templates, styling, JavaScript, and UI patterns
+- **Backend**: Django models, views, business logic, and architecture
+- **Integrations**: External service integration patterns and gateways
+- **Domain**: Domain modeling, business rules, and core concepts
+- **Process-Docs**: Workflow, releases, setup, and procedures
+
+### Documentation Structure
+
+Each role-specific document follows this format:
+
+```markdown
+# Document Title
+
+> **Role**: [Specialist Role]
+> **Purpose**: [Brief description of document purpose]
+
+## Main Content Sections
+
+### Subsection Headers
+Use H3 for major subsections within content.
+
+## Related Documentation
+- Link to related documents in other roles
+- Link to relevant shared reference material
+```
+
+## Cross-Reference Management
+
+### Linking Between Roles
+
+Use relative paths for cross-role references:
+
+```markdown
+## Related Documentation
+- Testing patterns: [Testing Patterns](../testing/testing-patterns.md)
+- Backend integration: [Backend Guidelines](../backend/backend-guidelines.md)
+- Shared concepts: [Architecture Overview](../shared/architecture-overview.md)
+```
+
+### Maintaining Link Integrity
+
+When updating documentation:
+1. Check for broken cross-references
+2. Update links when moving or renaming files
+3. Ensure bidirectional linking where appropriate
+
+## Writing Standards
+
+### Clarity and Conciseness
+- Write for the target specialist role
+- Assume domain knowledge appropriate to the role
+- Provide concrete examples over abstract concepts
+- Use code examples to illustrate patterns
+
+### Code Examples
+
+Use proper syntax highlighting and context:
+
+```python
+# Good - includes context and explanation
+class EntityManager(models.Manager):
+ def active(self):
+ """Get only active entities"""
+ return self.filter(is_active=True)
+```
+
+### Formatting Conventions
+
+- Use **bold** for important concepts
+- Use `code formatting` for filenames, commands, and code elements
+- Use > blockquotes for role/purpose headers
+- Use bullet points for lists, numbered lists for procedures
+
+## Content Organization
+
+### Document Length
+- Keep documents focused on their specific role
+- Split large documents into logical subsections
+- Cross-reference related content in other roles rather than duplicating
+
+### Information Hierarchy
+1. **Primary**: Information essential to the role
+2. **Secondary**: Helpful context and related patterns
+3. **Reference**: Links to detailed information in other roles
+
+### Avoiding Duplication
+
+- Keep common standards in shared/ directory
+- Reference shared content rather than duplicating
+- Use cross-references to maintain single source of truth
+
+## Maintenance Procedures
+
+### Regular Reviews
+- Review documentation quarterly for accuracy
+- Update examples when code patterns change
+- Verify cross-references remain valid
+
+### Version Control
+- All documentation changes go through pull request process
+- Include documentation updates with related code changes
+- Treat documentation as first-class code
+
+### Deprecation Process
+1. Mark deprecated patterns with clear warnings
+2. Provide migration paths to new approaches
+3. Remove deprecated content after appropriate transition period
+
+## Agent-Friendly Guidelines
+
+### Context Efficiency
+- Each role's documentation should be self-contained enough for AI agents
+- Cross-references provide necessary context without overwhelming detail
+- Examples should be complete and executable
+
+### Searchability
+- Use consistent terminology across documents
+- Include relevant keywords in headers and content
+- Provide clear section headers for easy navigation
+
+## Related Documentation
+- Workflow guidelines: [Workflow Guidelines](workflow-guidelines.md)
+- All role-specific documentation serves as examples of these standards
diff --git a/docs/dev/workflow/release-process.md b/docs/dev/workflow/release-process.md
new file mode 100644
index 00000000..ccca9c66
--- /dev/null
+++ b/docs/dev/workflow/release-process.md
@@ -0,0 +1,89 @@
+# Release Process
+
+## Release Overview
+
+Releases follow structured branch workflow:
+- Development work in feature branches
+- Feature branches merged to `staging` via PRs
+- `master` branch serves as release branch
+- Releases merge accumulated changes from `staging` to `master`
+
+## Prerequisites
+
+- Direct repository access (core maintainers only)
+- Local development environment configured
+- All target changes merged into `staging` branch
+
+## Pre-Release Verification
+
+1. **Confirm CI Status**: Ensure GitHub Actions pass on `staging`
+2. **Run Local Validation**: `make check`
+3. **Review Recent Changes**: Check commits and merged PRs
+
+## Release Steps
+
+### 1. Prepare Staging Branch
+
+```bash
+git checkout staging
+git pull github staging
+```
+
+### 2. Update Version Number
+
+```bash
+# Edit HI_VERSION file with new version
+git add HI_VERSION
+git commit -m "Bump version number to vX.X.X"
+git push github staging
+```
+
+### 3. Merge to Master
+
+```bash
+git checkout master
+git pull github master
+git merge staging
+git push github master
+```
+
+### 4. Create GitHub Release
+
+Using GitHub CLI (preferred for automation):
+
+```bash
+gh release create vX.X.X --title "vX.X.X" --generate-notes --latest
+```
+
+Or via GitHub web interface:
+1. Navigate to repository releases page
+2. Click "Create a new release"
+3. **Tag**: `vX.X.X` (create new)
+4. **Target**: `master` branch
+5. **Title**: Use tag name
+6. **Description**: Use "Generate release notes"
+7. **Settings**: Check "Set as latest release"
+8. Click "Publish Release"
+
+## Version Bumping Criteria
+
+**TBD** - Establish guidelines for:
+- **Major version**: Breaking changes
+- **Minor version**: New features (backward compatible)
+- **Patch version**: Bug fixes (backward compatible)
+
+## Rollback Procedures
+
+**TBD** - Document rollback procedures:
+- Revert problematic releases
+- Communication protocols
+- Post-rollback testing
+
+## Notes
+
+- **Changelog Management**: Generated from GitHub's automatic changelog
+- **Deployment**: Releases distributed as downloadable packages
+- **Quality Assurance**: Branch protection enforces tests and code quality
+
+## Related Documentation
+- Workflow guidelines: [Workflow Guidelines](workflow-guidelines.md)
diff --git a/docs/dev/workflow/workflow-guidelines.md b/docs/dev/workflow/workflow-guidelines.md
new file mode 100644
index 00000000..c850aa9d
--- /dev/null
+++ b/docs/dev/workflow/workflow-guidelines.md
@@ -0,0 +1,179 @@
+# Workflow Guidelines
+
+## Branching Strategy
+
+- **Main Branch** (`master`): Stable, production-ready code (*do not touch*)
+- **Development Branch** (`staging`): Active development, PR target
+- **Feature Branches**: Individual development work
+
+## Branch Naming Conventions
+
+| Type | Issue? | Branch Pattern | Notes |
+|----------|--------|-------------------------------------|----------------------|
+| feature | YES | feature/$(ISSUE_NUM)-${MNEMONIC} | New development |
+| bugfix | YES | bugfix/$(ISSUE_NUM)-${MNEMONIC} | Bug fixes |
+| docs | YES | docs/$(ISSUE_NUM)-${MNEMONIC} | Documentation |
+| ops | YES | ops/$(ISSUE_NUM)-${MNEMONIC} | Deployment/CI |
+| tests | NO | tests/${MNEMONIC} | Test-only changes |
+| refactor | YES | refactor/$(ISSUE_NUM)-${MNEMONIC} | No behavior changes |
+| tweak | NO | tweak/${MNEMONIC} | Small obvious fixes |
+
+## Development Workflow
+
+### 1. Ensure Latest Staging
+```bash
+git checkout staging
+git pull origin staging
+```
+
+### 2. Create Feature Branch
+```bash
+git checkout -b feature/42-entity-icons
+```
+
+### 3. Development and Commits
+- Make logical commits with clear messages
+- Focus on **what** changed and **why**, not implementation details
+- Keep commits focused and atomic
+
+### 4. Push Branch
+```bash
+git push -u origin feature/42-entity-icons
+```
+
+### 5. Create Pull Request
+Use GitHub CLI or web interface:
+```bash
+gh pr create --title "Add entity icon system" --body "$(cat <<'EOF'
+## Pull Request: Add Entity Icon System
+
+### Issue Link
+Closes #42
+
+### Summary
+- Implement standardized icon system for entities
+- Add icon template tag with size and styling options
+- Update entity templates to use new icon system
+
+### Testing
+- [ ] Unit tests pass
+- [ ] Icon rendering verified in UI
+- [ ] Multiple size variants tested
+
+### Documentation
+- [ ] Updated template documentation
+- [ ] Added icon usage examples
+EOF
+)"
+```
+
+## Multi-Phase Implementation Strategy
+
+For complex issues involving multiple aspects or trade-offs:
+
+### Core Methodology
+
+1. **Analyze and Break Down**: Identify distinct phases
+ - Phase 1: Simple, reliable solution addressing core issue
+ - Phase 2+: Advanced optimizations, UX improvements, edge cases
+
+2. **Implement Incrementally**: Complete phases sequentially
+ - Complete Phase 1 first - ensure issue is FULLY RESOLVED
+ - Commit and push Phase 1 (but don't create PR yet)
+ - Wait for feedback before proceeding to Phase 2
+
+3. **Communication**: Post investigation findings and phase breakdown to GitHub issue
+
+4. **Benefits**:
+ - Early validation of approach
+ - Natural checkpoints for review
+ - Core functionality before optimizations
+ - Independent value delivery per phase
+
+### Key Principles
+1. **Always solve core issue first** - Phase 1 must fully resolve the bug
+2. **Incremental value delivery** - Each phase independently valuable
+3. **Natural stopping points** - Complete phases are good moments for review
+4. **No PR until complete** - Unless explicitly asked
+
+## Commit Message Standards
+
+**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
+```
+
+**MUST NOT:**
+- Claude Code attribution or co-author tags
+- Implementation details in commit messages
+
+**SHOULD NOT:**
+- Generic messages like "update code" or "fix bug"
+
+## Pre-PR Requirements
+
+**MANDATORY checks before creating any PR:**
+
+```bash
+# 1. Run full unit test suite (must pass)
+make test
+
+# 2. Run code quality check (must pass with no output)
+make lint
+```
+
+Both checks must pass before PR creation. Fix all issues first.
+
+## Pull Request Guidelines
+
+### PR Description Structure
+
+Follow `.github/PULL_REQUEST_TEMPLATE.md`:
+
+```markdown
+## Pull Request: [Short Title]
+
+### Issue Link
+Closes #123
+
+### Summary
+- Brief overview of changes
+- Key components modified
+- Business impact
+
+### Testing
+- [ ] Unit tests pass
+- [ ] Integration tests pass
+- [ ] Manual testing completed
+
+### Documentation
+- [ ] Code comments updated
+- [ ] Documentation files updated
+- [ ] Breaking changes documented
+```
+
+### PR Review Process
+
+- **Squash and Merge**: Default for most PRs
+- **Rebase and Merge**: For well-structured PRs needing commit history
+
+## Post-PR Cleanup
+
+**After PR is merged**, clean up local environment:
+
+1. **Verify PR merged**: `gh pr view --json state,mergedAt`
+2. **Switch to staging**: `git checkout staging`
+3. **Pull latest changes**: `git pull origin staging`
+4. **Delete feature branch**: `git branch -d feature/42-entity-icons`
+5. **Verify clean state**: `git status`
+
+## Release Process Integration
+
+See [Release Process](release-process.md) for detailed release procedures.
+
+## Related Documentation
+- Release procedures: [Release Process](release-process.md)
+- Documentation standards: [Documentation Standards](documentation-standards.md)
+- Coding standards: [Coding Standards](../shared/coding-standards.md)