Compare commits
26 Commits
77483c2186
...
v0.11.0
| Author | SHA1 | Date | |
|---|---|---|---|
| f4fd1c943d | |||
| ba9cdb4347 | |||
| f063383e61 | |||
| 17c988c1ee | |||
| d297412d8a | |||
| 52dd6c3e32 | |||
| 295f9637b3 | |||
| ad55d4ca09 | |||
| ba1f28ee53 | |||
| c48c6e5bca | |||
| ef0008822e | |||
| f13158e7bf | |||
| 3f0ec8f30b | |||
| d5a0163852 | |||
| fd37425f1c | |||
| 4378290c9c | |||
| 9775dca114 | |||
| 904ff04440 | |||
| 155f0b007a | |||
| 583af1948e | |||
| 449e031589 | |||
| 18fd0472a5 | |||
| e15481884a | |||
| 737901c962 | |||
| 2cf5bf47d3 | |||
| 32d2a57bc9 |
+101
@@ -5,6 +5,107 @@ All notable changes to Terra-View will be documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [0.11.0] - 2026-05-15
|
||||
|
||||
Operator-facing polish release. All work builds on the v0.10.0 SFM integration foundation — this release is about making the day-to-day workflows (managing locations, cleaning up bad attributions, browsing deployments) faster and less error-prone.
|
||||
|
||||
### Added
|
||||
- **Soft-remove monitoring locations** (`POST /api/projects/{p}/locations/{l}/remove` + `/restore`): mark a location as no longer actively monitored without destroying historical events. Cascade-closes active unit assignments and cancels pending scheduled actions at the location. Restored locations rejoin the active list (assignments are NOT auto-reopened — operator creates new ones if resuming). Project page splits locations into Active and Removed sections; removed cards are greyed out, badged with the removal date + reason, and offer a Restore button.
|
||||
- **Per-unit deployment Gantt chart** above the existing Deployment Timeline list on every seismograph unit detail page. Plain-SVG rendering, color per location, today marker (orange dashed line), reduced-opacity bars for closed assignments, blue outlines on metadata-backfilled assignments, dashed blue underlines marking mergeable groups. Click a bar to scroll the matching list row into view with a flash highlight.
|
||||
- **Merge consecutive same-location assignments** (`POST /api/projects/{p}/assignments/merge`): operators often end up with several rows representing one continuous deployment (after remove/restore, or metadata-backfill adjacent to a manual record). Now auto-detected and surfaceable in the timeline header — one click combines them into a single record. Preserves the earliest record's notes + ingest source, writes an `assignment_merged` audit entry, deletes the others.
|
||||
- **Delete assignment for mis-clicks** (`DELETE /api/projects/{p}/assignments/{a}`): hard-deletes a bogus assignment row that was never a real deployment. Trash icon in each row of the location's Deployment History panel. Refuses the delete if any `MonitoringSession` exists in the assignment's window — those should go through Unassign instead, which preserves audit history. Writes an `assignment_deleted` UnitHistory row.
|
||||
- **Drag-to-reorder location cards**: each active card has a six-dot drag handle on the left. Drag/drop reorders the DOM and persists via `POST /api/projects/{p}/locations/reorder`. Implementation uses native HTML5 drag-and-drop (no library). New locations land at the end (`sort_order = max + 1`); removed locations stay sorted by removal date.
|
||||
- **Three-dot kebab menu on location cards**: replaces the four inline pill buttons (Unassign / Edit / Remove / Delete) with a single ⋮ menu. Click ⋮ to open; click outside or Escape to close; only one menu open at a time.
|
||||
- **Event count on vibration location cards**: vibration cards now show "{N} events" sourced from SFM via concurrent fan-out, instead of "Sessions: 0" (sessions don't exist under the watcher-forward pipeline). Sound locations still show session counts.
|
||||
- **Project overview location map**: right column of every project's overview replaces the lightly-used Upcoming Actions panel with a Leaflet map. One pin per active monitoring location (parsed from the `coordinates` field). Click pin → scrolls + flashes the matching card. Tooltip on hover. Locations without coordinates surface as an inline hint below the map. If the project has pending scheduled actions, a small "{N} upcoming actions →" link appears in the card header that switches to the Schedules tab.
|
||||
|
||||
### Changed
|
||||
- **Backfill location fuzzy matcher is now stricter**: `rapidfuzz.WRatio` was over-confident on location names because their shared boilerplate vocabulary ("Area", "Loc", numbers) inflated scores. Example false positive that prompted the change: `"Area 2 - Brookville Dam - Loc 2 East"` vs `"Area 1 - Loc 1 - 87 Jenks"` scored 86% via WRatio. Now uses `token_set_ratio` as the base scorer plus a 0.30 penalty when the two strings have disjoint multi-digit numeric tokens. Catches the "same project, different address number" case (`"68 Jenks"` vs `"87 Jenks"`) that pure token-set scoring still rated above 0.90. Project matching keeps WRatio (where its leniency is desirable for typos like `1-80` vs `I-80`).
|
||||
|
||||
### Fixed
|
||||
- **Three separate JSON.stringify quote-collision bugs**: any inline `onclick="...({...} | tojson)"` or `onclick="...${JSON.stringify(x)}..."` where `x` contained any character that JSON quotes (essentially every real-world string) broke the HTML attribute and silently un-bound the click handler. Surfaced in three places this release; all fixed by switching to `data-*` attributes plus a trampoline function reading from `this.dataset`:
|
||||
- **Location Remove button** on the project page
|
||||
- **Metadata-backfill typeahead dropdown** (existing project + location pickers)
|
||||
- **Project-merge typeahead dropdown** (in the per-project header)
|
||||
- **Project-merge modal too short to show typeahead options without scrolling**: modal body's `flex-1 overflow-y-auto` collapsed tight; added `min-height: 480px` to the modal container + `min-h-[320px]` to the body so the dropdown always has room.
|
||||
- **Project location map covered modals**: Leaflet's internal panes carry z-indexes 200–800 by default and the map container didn't establish a stacking context, so those z-indexes leaked into the root and outranked modals' `z-50`. Fixed by adding `isolation: isolate` to the map container.
|
||||
- **`delete_assignment` crashed with `AttributeError`**: the safety check queried `MonitoringSession.start_time` but the actual column is `started_at`. Every DELETE call to `/assignments/{id}` failed with 500 before doing anything.
|
||||
|
||||
### Migration Notes
|
||||
Run on each database before deploying. Both migrations are idempotent and non-destructive.
|
||||
|
||||
```bash
|
||||
docker exec terra-view-terra-view-1 python3 /app/backend/migrate_add_location_removed.py
|
||||
docker exec terra-view-terra-view-1 python3 /app/backend/migrate_add_location_sort_order.py
|
||||
```
|
||||
|
||||
Or sweep all migrations at once (safe — already-applied ones no-op):
|
||||
|
||||
```bash
|
||||
for f in backend/migrate_*.py; do
|
||||
docker exec terra-view-terra-view-1 python3 "/app/backend/$(basename $f)"
|
||||
done
|
||||
```
|
||||
|
||||
New columns added this release:
|
||||
- `monitoring_locations.removed_at` (DATETIME, nullable) — NULL means active
|
||||
- `monitoring_locations.removal_reason` (TEXT, nullable)
|
||||
- `monitoring_locations.sort_order` (INTEGER, default 0) — seeded to alphabetical-index per project on first migration
|
||||
|
||||
**Deploy order matters**: migrations must run BEFORE the new code is up, otherwise the running app will throw 500s on the unrecognized columns. Idempotent migrations make this recoverable but it's better avoided — the v0.11.0 deploy on prod hit this exact window after the v0.10.0 release.
|
||||
|
||||
---
|
||||
|
||||
## [0.10.0] - 2026-05-14
|
||||
|
||||
This release brings terra-view onto the SFM (Seismograph Field Module) event pipeline. Triggered events forwarded by series3-watcher now land in SFM, and terra-view reads from that store as the authoritative source for vibration data. The watcher heartbeat is preserved as a transparent fallback signal.
|
||||
|
||||
### Added
|
||||
- **SFM Integration**: New fleet-wide events page at `/sfm` listing every event ingested by SFM, with filters for serial, date range, false-trigger flag, and limit. Unit detail pages and project-location pages show their own attributed subsets of the same event stream.
|
||||
- **Event Detail Modal**: Shared across `/sfm`, unit detail, and project-location pages — clicking any event opens a rich modal showing peaks per channel (PVS color-coded by magnitude), microphone dB(L) + ZC frequency + time of peak, sensor self-check table with pass/fail per channel, device/recording metadata (firmware, battery, calibration date, geo range), and download buttons for the original Blastware binary and the sidecar JSON. Includes an inline pretty-printed JSON viewer with copy-to-clipboard.
|
||||
- **Events Attribution Engine** (`backend/services/sfm_events.py`): Per-event attribution against `UnitAssignment` time windows. Events outside any assignment window surface in an "Unattributed" bucket with the nearest-assignment diagnostic (which location, signed delta in days).
|
||||
- **Metadata Backfill Tool** (`/tools` → Backfill from event metadata): Scans operator-typed `project` and `sensor_location` strings in event sidecars, fuzzy-clusters them via `rapidfuzz.WRatio`, and proposes retroactive `UnitAssignment` records to attribute orphan events. Tracks operator decisions per cluster across re-scans.
|
||||
- **Project Tidy Tool** (`/tools` → Project Tidy): Fuzzy-detect duplicate projects and bulk-merge them with a single click. Source projects soft-deleted with full audit trail.
|
||||
- **Vibration Summary on Project Pages**: New roll-up card on vibration project detail pages showing per-location event counts, the project's "Overall Peak" PVS (false triggers excluded), last event timestamp, and a Top Locations by Activity list.
|
||||
- **SFM-Primary Seismograph Status**: `emit_status_snapshot()` now consults SFM's `/db/units` (cached 15s) before falling back to `Emitter.last_seen` for each seismograph. The fresher signal wins; the choice is recorded in a new per-unit `last_seen_source` field. A small `SFM` (orange) or `HB` (gray) badge on each unit's active-table row shows which path is currently driving the status.
|
||||
- **Dashboard Rework**: Top row reordered to Recent Alerts → Recent Call-Ins (double-wide) → Fleet Summary. Today's Schedule moved to a horizontal collapsible card below the Fleet Map, auto-expanding only when pending actions exist. Recent Call-Ins now sources from a new `/api/recent-event-callins` endpoint backed by SFM event forwards instead of the watcher-heartbeat endpoint.
|
||||
- **Sortable Events Tables**: `/sfm` and unit-detail SFM Events tables now have clickable column headers with ↕/↓/↑ indicators. Default sort is Timestamp DESC. Click same column to toggle direction; click different column to switch and reset to DESC. Pure client-side over cached rows — no re-fetches.
|
||||
- **Developer → SFM Admin** (`/admin/sfm`): Health banner with reachability indicator, terra-view↔SFM connection panel, 4 KPI tiles (known units, total events, stale `monitor_log` rows, stale `ach_sessions` rows), per-unit roll-up table, recent-events table with color-coded forwarding latency (so stale watcher forwards stand out), and a raw API tester for any `/api/sfm/*` path.
|
||||
- **Developer → SLMM Admin** (`/admin/slmm`): Stripped-down companion page — health, connection info, raw API tester.
|
||||
- **Tools Workflow Hub** (`/tools`): New top-level sidebar entry consolidating Pair Devices, Project Tidy, Metadata Backfill, Reports (info card), and Swap Detection (placeholder).
|
||||
- **Sidebar Reorganization**: Devices → Projects → Events → Tools → Job Planner → Settings. Devices is now a single entry with internal tabs (All Devices / Seismographs / Sound Level Meters / Modems / Pair Devices) replacing five separate sidebar items.
|
||||
- **Synology Deployment Doc** (`docs/SYNOLOGY_DEPLOYMENT.md`): End-to-end playbook for migrating the stack to an always-on office NAS — phased rollout (pre-stage, data rsync, watcher repoint, external access, decommission), Tailscale vs reverse-proxy options, rollback plan, and gotchas.
|
||||
|
||||
### Changed
|
||||
- **Overall Peak excludes false triggers**: The project-level "Overall Peak" KPI tile (and the underlying `_compute_stats()` function in `sfm_events.py`) now skip events flagged as false triggers when computing the highest PVS, so operators see the highest real event rather than the biggest sensor glitch. `false_trigger_count` still includes flagged events so operators can see how many were filtered out.
|
||||
- **`RosterUnit.note` Editing**: Inline edit on seismograph cards is more forgiving and now auto-saves on blur.
|
||||
- **Sidebar Nav Renamed**: Old "Fleet" sidebar entry → "Devices" (renamed because it always meant the device list, not the broader fleet view).
|
||||
|
||||
### Fixed
|
||||
- **Status drift between watcher heartbeat and actual event arrivals**: Seismographs are now reported with whichever signal is more recent — eliminates the case where a unit had recent SFM events but a stale heartbeat (or vice-versa) showed the wrong status.
|
||||
- **Event modal: Record Type always showed "Waveform"**: Workaround client-side — Record Type now derived from the Blastware filename's last-char code (`H`=Histogram, `W`=Waveform, `M`=Manual, `E`=Event, `C`=Combo). The proper fix lives in SFM's sidecar parser; tracked separately.
|
||||
- **Event modal: Mic PSI tile removed**: Operators only care about dB(L); the redundant PSI tile was dropped.
|
||||
|
||||
### Migration Notes
|
||||
Run on each database before deploying. Every migration is idempotent.
|
||||
|
||||
```bash
|
||||
# Cleanest: re-run all migrations in chronological order.
|
||||
# Already-applied migrations no-op safely.
|
||||
for f in backend/migrate_*.py; do
|
||||
docker exec terra-view-terra-view-1 python3 "/app/backend/$(basename $f)"
|
||||
done
|
||||
```
|
||||
|
||||
Migrations new in this release:
|
||||
- `migrate_add_metadata_backfill.py` — adds `unit_assignments.source` column and `metadata_backfill_decisions` table for the Metadata Backfill tool
|
||||
|
||||
### Deployment Notes
|
||||
- **`SFM_BASE_URL`**: Confirm prod's `docker-compose.yml` sets this for the terra-view service (typically `http://sfm:8200` for the in-stack SFM container, or an external URL if SFM lives elsewhere).
|
||||
- **Watcher repoint**: series3-watcher's `sfm_forward_url` should point at `https://<your-terra-view-host>/api/sfm` (proxy-based — no second port forward needed). Watcher composes the full path `/db/import/blastware_file` itself.
|
||||
|
||||
---
|
||||
|
||||
## [0.9.4] - 2026-04-06
|
||||
|
||||
### Added
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# Terra-View v0.9.4
|
||||
# Terra-View v0.11.0
|
||||
Backend API and HTMX-powered web interface for managing a mixed fleet of seismographs and field modems. Track deployments, monitor health in real time, merge roster intent with incoming telemetry, and control your fleet through a unified database and dashboard.
|
||||
|
||||
## Features
|
||||
@@ -496,6 +496,32 @@ docker compose down -v
|
||||
|
||||
## Release Highlights
|
||||
|
||||
### v0.11.0 — 2026-05-15
|
||||
- **Soft-Remove Monitoring Locations**: Mark a location as no longer actively monitored without destroying history. Closes active unit assignments and cancels pending scheduled actions; historical events stay attributed. Restore brings it back. Surfaces as a Removed Locations collapsed section on the project page.
|
||||
- **Per-Unit Deployment Gantt**: Visual timeline above the deployment history list on each unit detail page. Color-coded bars per location, today marker, mergeable-group dashed underlines, click a bar to scroll its detail row into view.
|
||||
- **Merge Consecutive Deployments**: Auto-detects runs of same-location assignments within a 7-day gap and offers a one-click "Merge into one" button. Preserves notes, ingest source, and writes an `assignment_merged` audit entry.
|
||||
- **Delete Assignment for Mis-Clicks**: Trash icon on each row of the location's Deployment History panel. Hard-deletes the assignment with a safety check that refuses if real MonitoringSessions sit inside the window (those should go through Unassign instead).
|
||||
- **Drag-to-Reorder Location Cards**: Six-dot drag handle on each card; drop order persists via a new `/locations/reorder` endpoint. Removed locations stay sorted by removal date (their order is historical).
|
||||
- **Three-Dot Kebab Menu**: Replaces the inline Unassign / Edit / Remove / Delete pill row with a single ⋮ menu. Much cleaner card layout, especially for projects with many locations.
|
||||
- **Event Count on Vibration Cards**: Vibration locations now show "{N} events" instead of "Sessions: 0" (sessions don't exist under the watcher-forward pipeline). Sound locations are unchanged.
|
||||
- **Project Location Map**: Right column of the project overview is now a Leaflet map with a pin per location. Click pin → scrolls + flashes the matching card. Replaces the lightly-used Upcoming Actions panel (still discoverable via a link to the Schedules tab when actions exist).
|
||||
- **Stricter Location Fuzzy Matching**: Metadata-backfill no longer suggests obviously-wrong matches. WRatio was over-confident on location names ("Area 2 - Brookville Dam - Loc 2" vs "Area 1 - Loc 1 - 87 Jenks" used to score 86%); now uses `token_set_ratio` + a multi-digit penalty so disjoint address numbers correctly demote the score.
|
||||
- **Fixed: Multiple typeahead dropdowns weren't clickable**: Same JSON.stringify quote-collision bug surfaced in three places (location Remove button, backfill typeahead, project-merge dropdown). All three fixed by switching to `data-*` attributes + trampoline functions.
|
||||
- **Fixed: Merge-project modal had to be scrolled to see options**: Modal body's `flex-1 overflow-y-auto` collapsed too tight; added `min-height` so the dropdown has room to render below the input.
|
||||
|
||||
### v0.10.0 — 2026-05-14
|
||||
- **SFM Integration**: terra-view now consumes events from the SFM (Seismograph Field Module) backend in real time, with a fleet-wide events page at `/sfm`, per-unit attribution against project assignment windows, and a project-level vibration roll-up that uses SFM data as the single source of truth.
|
||||
- **SFM-Primary Seismograph Status**: Deployed seismograph status (OK/Pending/Missing) now flows from SFM event forwards first; the watcher heartbeat stays as a transparent backup. Each unit's active table row shows a small `SFM` or `HB` badge so operators can see at a glance which signal is currently driving the status.
|
||||
- **Dashboard Rework**: Top row reordered to Recent Alerts → Recent Call-Ins (double-wide) → Fleet Summary. Today's Schedule moves to a horizontal collapsible card below the Fleet Map, auto-expanding only when there's a pending action. Recent Call-Ins now sources from SFM event forwards instead of the legacy watcher-heartbeat endpoint.
|
||||
- **Event Detail Modal**: Click any event anywhere in the app to open a rich detail modal showing peak particle velocity per channel, microphone dB(L), sensor self-check results, device/recording metadata, and download buttons for the original Blastware binary and sidecar JSON. Includes an inline JSON viewer with one-click copy.
|
||||
- **Sortable Events Tables**: Every events table (project events, unit-detail events, fleet-wide /sfm) now supports clickable column-header sorting with directional indicators. Defaults to newest-first.
|
||||
- **Events Attribution & Backfill**: Each SFM event is automatically attributed to a project/location based on `UnitAssignment` time windows. Unattributed events get a diagnostic showing the nearest assignment and a delta-days gap. The metadata-backfill tool in `/tools` scans operator-typed project/sensor-location strings in event sidecars and clusters them via fuzzy matching to propose new assignment retroactives.
|
||||
- **Projects Tools**: New `/tools` workflow hub consolidates Pair Devices, Project Tidy (fuzzy-detect + merge duplicate projects), Metadata Backfill, Reports, and Swap Detection (placeholder).
|
||||
- **Sidebar Reorganization**: Devices → Projects → Events → Tools → Job Planner → Settings. Devices is now a single entry with internal tabs (All Devices / Seismographs / Sound Level Meters / Modems / Pair Devices).
|
||||
- **Developer → SFM Admin**: New `/admin/sfm` page surfacing SFM health, per-unit roll-up from `/db/units`, recent-events table with forwarding latency (so operators can spot stale watcher forwards), stale-table counts, and a raw API tester. Companion `/admin/slmm` page covers SLMM health + raw API.
|
||||
- **"Overall Peak" excludes False Triggers**: The project-level Overall Peak KPI tile now excludes events flagged as false triggers — operators see the highest real event, not the biggest sensor glitch.
|
||||
- **Synology Deployment Doc**: New `docs/SYNOLOGY_DEPLOYMENT.md` covers migrating the stack to an always-on office NAS, including phased rollout, data rsync, watcher repoint, external-access (Tailscale or reverse-proxy), and rollback plan.
|
||||
|
||||
### v0.8.0 — 2026-03-18
|
||||
- **Watcher Manager**: Admin page for monitoring field watcher agents with live status cards, log tails, and one-click update triggering
|
||||
- **Watcher Status Fix**: Agent status now reflects heartbeat connectivity (missing if not heard from in >60 min) rather than unit-level data staleness
|
||||
@@ -599,9 +625,23 @@ MIT
|
||||
|
||||
## Version
|
||||
|
||||
**Current: 0.8.0** — Watcher Manager admin page, live agent status refresh, watcher connectivity-based status (2026-03-18)
|
||||
**Current: 0.11.0** — Soft-remove locations, per-unit Gantt, merge/delete assignments, drag-to-reorder, three-dot kebab menu, event count on vibration cards, project location map, stricter backfill fuzzy match, modal/typeahead bug fixes (2026-05-15)
|
||||
|
||||
Previous: 0.7.1 — Out-for-calibration status, reservation modal, migration fixes (2026-03-12)
|
||||
Previous: 0.10.0 — SFM integration, SFM-primary seismograph status, dashboard rework, sortable events tables, event detail modal, /admin/sfm + /admin/slmm diagnostic pages, Tools workflow hub (2026-05-14)
|
||||
|
||||
0.9.4 — Modular project types, deleted project management, swap modal search, roster auto-refresh fix (2026-04-06)
|
||||
|
||||
0.9.3 — Monitoring session detail page, configurable period windows, vibration project redesign, modem assignment on locations (2026-03-28)
|
||||
|
||||
0.9.2 — Deployment records, allocated status, quick-info unit modal, inline seismograph editing (2026-03-27)
|
||||
|
||||
0.9.1 — Fix location slots not persisting on save/reload (2026-03-20)
|
||||
|
||||
0.9.0 — Job Planner redesign, monitoring locations, estimated units, smart color picker, calendar bar tooltips, toast notifications (2026-03-19)
|
||||
|
||||
0.8.0 — Watcher Manager admin page, live agent status refresh, watcher connectivity-based status (2026-03-18)
|
||||
|
||||
0.7.1 — Out-for-calibration status, reservation modal, migration fixes (2026-03-12)
|
||||
|
||||
0.7.0 — Project status management, manual SD card upload, combined report wizard, NL32 support, MonitoringSession rename (2026-03-07)
|
||||
|
||||
|
||||
+12
-1
@@ -30,7 +30,7 @@ Base.metadata.create_all(bind=engine)
|
||||
ENVIRONMENT = os.getenv("ENVIRONMENT", "production")
|
||||
|
||||
# Initialize FastAPI app
|
||||
VERSION = "0.9.4"
|
||||
VERSION = "0.11.0"
|
||||
if ENVIRONMENT == "development":
|
||||
_build = os.getenv("BUILD_NUMBER", "0")
|
||||
if _build and _build != "0":
|
||||
@@ -106,6 +106,9 @@ app.include_router(settings.router)
|
||||
from backend.routers import watcher_manager
|
||||
app.include_router(watcher_manager.router)
|
||||
|
||||
from backend.routers import admin_modules
|
||||
app.include_router(admin_modules.router)
|
||||
|
||||
# Projects system routers
|
||||
app.include_router(projects.router)
|
||||
app.include_router(project_locations.router)
|
||||
@@ -258,6 +261,14 @@ async def project_tidy_page(request: Request):
|
||||
return templates.TemplateResponse("admin/project_tidy.html", {"request": request})
|
||||
|
||||
|
||||
@app.get("/tools", response_class=HTMLResponse)
|
||||
async def tools_page(request: Request):
|
||||
"""Tools / workflow hub. Active operator workflows (device pairing,
|
||||
project tidy, metadata backfill, future swap detection, report
|
||||
generators) all live here in card form."""
|
||||
return templates.TemplateResponse("tools.html", {"request": request})
|
||||
|
||||
|
||||
@app.get("/modems", response_class=HTMLResponse)
|
||||
async def modems_page(request: Request):
|
||||
"""Field modems management dashboard"""
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
"""
|
||||
Migration: add `removed_at` + `removal_reason` columns to `monitoring_locations`.
|
||||
|
||||
Lets operators mark a location as no longer actively monitored without
|
||||
deleting it (so historical events stay attributed correctly). Mirrors
|
||||
the timestamp-based "closed state" pattern already used by
|
||||
`unit_assignments.assigned_until`.
|
||||
|
||||
Behavior:
|
||||
- `removed_at IS NULL` → location is active (default for all existing
|
||||
rows after this migration)
|
||||
- `removed_at` set → location is removed; historical events still
|
||||
attribute to it but it's hidden from active
|
||||
surfaces (assign dropdowns, calendar, etc.)
|
||||
- `removal_reason` → optional operator note (e.g. "client dropped
|
||||
from scope")
|
||||
|
||||
Idempotent — safe to re-run. Non-destructive — adds only.
|
||||
|
||||
Run with:
|
||||
docker exec terra-view-terra-view-1 python3 /app/backend/migrate_add_location_removed.py
|
||||
"""
|
||||
|
||||
import os
|
||||
import sqlite3
|
||||
|
||||
DB_PATH = "./data/seismo_fleet.db"
|
||||
|
||||
|
||||
def _has_column(cur: sqlite3.Cursor, table: str, column: str) -> bool:
|
||||
cur.execute(f"PRAGMA table_info({table})")
|
||||
return any(row[1] == column for row in cur.fetchall())
|
||||
|
||||
|
||||
def migrate_database() -> None:
|
||||
if not os.path.exists(DB_PATH):
|
||||
print(f"Database not found at {DB_PATH}")
|
||||
return
|
||||
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
cur = conn.cursor()
|
||||
|
||||
added = []
|
||||
if not _has_column(cur, "monitoring_locations", "removed_at"):
|
||||
cur.execute("ALTER TABLE monitoring_locations ADD COLUMN removed_at DATETIME")
|
||||
added.append("removed_at")
|
||||
if not _has_column(cur, "monitoring_locations", "removal_reason"):
|
||||
cur.execute("ALTER TABLE monitoring_locations ADD COLUMN removal_reason TEXT")
|
||||
added.append("removal_reason")
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
if added:
|
||||
print(f" Added columns to monitoring_locations: {', '.join(added)}")
|
||||
else:
|
||||
print(" monitoring_locations already has removed_at + removal_reason — nothing to do.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("Running migration: add removed_at + removal_reason to monitoring_locations")
|
||||
migrate_database()
|
||||
print("Done.")
|
||||
@@ -0,0 +1,76 @@
|
||||
"""
|
||||
Migration: add `sort_order` column to `monitoring_locations` and seed
|
||||
existing rows.
|
||||
|
||||
Lets operators reorder location cards via drag-and-drop on the project
|
||||
detail page. Lower sort_order renders first; ties fall back to name.
|
||||
|
||||
Seed strategy: for each existing project, assign sort_order = 0, 1, 2, …
|
||||
to its locations in their current alphabetical-by-name order. After
|
||||
this migration, the visible card order on every existing project will
|
||||
be unchanged.
|
||||
|
||||
Idempotent — safe to re-run. Non-destructive — adds only.
|
||||
|
||||
Run with:
|
||||
docker exec terra-view-terra-view-1 python3 /app/backend/migrate_add_location_sort_order.py
|
||||
"""
|
||||
|
||||
import os
|
||||
import sqlite3
|
||||
|
||||
DB_PATH = "./data/seismo_fleet.db"
|
||||
|
||||
|
||||
def _has_column(cur: sqlite3.Cursor, table: str, column: str) -> bool:
|
||||
cur.execute(f"PRAGMA table_info({table})")
|
||||
return any(row[1] == column for row in cur.fetchall())
|
||||
|
||||
|
||||
def migrate_database() -> None:
|
||||
if not os.path.exists(DB_PATH):
|
||||
print(f"Database not found at {DB_PATH}")
|
||||
return
|
||||
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
cur = conn.cursor()
|
||||
|
||||
added_column = False
|
||||
if not _has_column(cur, "monitoring_locations", "sort_order"):
|
||||
cur.execute("ALTER TABLE monitoring_locations ADD COLUMN sort_order INTEGER DEFAULT 0")
|
||||
added_column = True
|
||||
print(" Added column: monitoring_locations.sort_order")
|
||||
|
||||
# Seed: for each project, set sort_order to its alphabetical index.
|
||||
# Re-runs are harmless — operator-edited orderings can be re-seeded by
|
||||
# passing FORCE_RESEED=1, but the default behavior leaves existing
|
||||
# nonzero sort_order values alone so we don't clobber user choices.
|
||||
force_reseed = os.environ.get("FORCE_RESEED") == "1"
|
||||
if added_column or force_reseed:
|
||||
cur.execute("SELECT DISTINCT project_id FROM monitoring_locations")
|
||||
projects = [r[0] for r in cur.fetchall()]
|
||||
seeded = 0
|
||||
for project_id in projects:
|
||||
cur.execute(
|
||||
"SELECT id FROM monitoring_locations WHERE project_id = ? ORDER BY name",
|
||||
(project_id,),
|
||||
)
|
||||
for idx, (loc_id,) in enumerate(cur.fetchall()):
|
||||
cur.execute(
|
||||
"UPDATE monitoring_locations SET sort_order = ? WHERE id = ?",
|
||||
(idx, loc_id),
|
||||
)
|
||||
seeded += 1
|
||||
print(f" Seeded sort_order for {seeded} location(s) across {len(projects)} project(s).")
|
||||
else:
|
||||
print(" monitoring_locations.sort_order already present — leaving existing values alone.")
|
||||
print(" (Set FORCE_RESEED=1 to re-seed by alphabetical order.)")
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("Running migration: add sort_order to monitoring_locations")
|
||||
migrate_database()
|
||||
print("Done.")
|
||||
@@ -235,6 +235,20 @@ class MonitoringLocation(Base):
|
||||
# For vibration: {"ground_type": "bedrock", "depth": "10m"}
|
||||
location_metadata = Column(Text, nullable=True)
|
||||
|
||||
# Soft-removal: NULL means active. When set, the location is hidden from
|
||||
# active surfaces (assign dropdowns, calendar, scheduler, dashboard
|
||||
# vibration summary) but historical events generated before this time
|
||||
# still attribute to it. Mirrors the closed-state pattern used by
|
||||
# UnitAssignment.assigned_until.
|
||||
removed_at = Column(DateTime, nullable=True)
|
||||
removal_reason = Column(Text, nullable=True)
|
||||
|
||||
# Display order within the project's location list. Operators can
|
||||
# drag-and-drop to reorder cards on the project detail page. Lower
|
||||
# values render first; ties fall back to name (alphabetical). Seeded
|
||||
# to alphabetical-index on migration; new locations get max+1.
|
||||
sort_order = Column(Integer, default=0, nullable=False)
|
||||
|
||||
created_at = Column(DateTime, default=datetime.utcnow)
|
||||
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
|
||||
@@ -4,11 +4,29 @@ from sqlalchemy import desc
|
||||
from pathlib import Path
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import List, Dict, Any
|
||||
import os
|
||||
import logging
|
||||
import httpx
|
||||
from backend.database import get_db
|
||||
from backend.models import UnitHistory, Emitter, RosterUnit
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api", tags=["activity"])
|
||||
|
||||
SFM_BASE_URL = os.getenv("SFM_BASE_URL", "http://localhost:8200")
|
||||
|
||||
|
||||
def _humanize_age(seconds: float) -> str:
|
||||
if seconds < 60:
|
||||
return "just now"
|
||||
if seconds < 3600:
|
||||
return f"{int(seconds / 60)}m ago"
|
||||
if seconds < 86400:
|
||||
hrs = seconds / 3600
|
||||
return f"{int(hrs)}h {int((hrs % 1) * 60)}m ago"
|
||||
return f"{int(seconds / 86400)}d ago"
|
||||
|
||||
PHOTOS_BASE_DIR = Path("data/photos")
|
||||
|
||||
|
||||
@@ -144,3 +162,86 @@ def get_recent_callins(hours: int = 6, limit: int = None, db: Session = Depends(
|
||||
"hours": hours,
|
||||
"time_threshold": time_threshold.isoformat()
|
||||
}
|
||||
|
||||
|
||||
@router.get("/recent-event-callins")
|
||||
async def get_recent_event_callins(limit: int = 10, db: Session = Depends(get_db)):
|
||||
"""
|
||||
Recent unit call-ins derived from SFM event forwards.
|
||||
|
||||
Architecture context: the live ACH replacement is on hold, so call-homes
|
||||
arrive as Blastware ACH event files forwarded by series3-watcher and
|
||||
landed in the SFM events store. One event ≈ one call-in. This is the
|
||||
forward-looking source of "recent call-ins" that will eventually replace
|
||||
the heartbeat-based /recent-callins endpoint entirely.
|
||||
|
||||
Each row represents one event; multiple consecutive events from the same
|
||||
serial are intentionally NOT collapsed — each one is a distinct call-home.
|
||||
"""
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=10.0) as client:
|
||||
resp = await client.get(
|
||||
f"{SFM_BASE_URL}/db/events",
|
||||
params={"limit": limit},
|
||||
)
|
||||
resp.raise_for_status()
|
||||
payload = resp.json()
|
||||
except httpx.HTTPError as e:
|
||||
log.warning("SFM /db/events failed for recent-event-callins: %s", e)
|
||||
return {"call_ins": [], "total": 0, "error": str(e)}
|
||||
|
||||
events = payload.get("events", []) or []
|
||||
|
||||
# Bulk-resolve serials → roster (single query, no N+1)
|
||||
serials = list({ev.get("serial") for ev in events if ev.get("serial")})
|
||||
roster_map: Dict[str, RosterUnit] = {}
|
||||
if serials:
|
||||
roster_map = {
|
||||
r.id: r
|
||||
for r in db.query(RosterUnit).filter(RosterUnit.id.in_(serials)).all()
|
||||
}
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
call_ins: List[Dict[str, Any]] = []
|
||||
|
||||
for ev in events:
|
||||
serial = ev.get("serial")
|
||||
if not serial:
|
||||
continue
|
||||
|
||||
roster = roster_map.get(serial)
|
||||
|
||||
# created_at = when SFM received the forward. Falls back to the event
|
||||
# timestamp if the SFM payload didn't carry created_at (older rows).
|
||||
created_at_str = ev.get("created_at") or ev.get("timestamp")
|
||||
time_ago = "—"
|
||||
if created_at_str:
|
||||
try:
|
||||
ts = datetime.fromisoformat(created_at_str.replace("Z", "+00:00"))
|
||||
if ts.tzinfo is None:
|
||||
ts = ts.replace(tzinfo=timezone.utc)
|
||||
time_ago = _humanize_age((now - ts).total_seconds())
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
call_ins.append({
|
||||
"unit_id": serial,
|
||||
"serial": serial,
|
||||
"event_id": ev.get("id"),
|
||||
"event_timestamp": ev.get("timestamp"),
|
||||
"created_at": ev.get("created_at"),
|
||||
"time_ago": time_ago,
|
||||
"peak_vector_sum": ev.get("peak_vector_sum"),
|
||||
"false_trigger": bool(ev.get("false_trigger")),
|
||||
"sensor_location": ev.get("sensor_location") or "",
|
||||
"project": ev.get("project") or "",
|
||||
"device_type": roster.device_type if roster else "seismograph",
|
||||
"in_roster": roster is not None,
|
||||
"note": (roster.note if roster else "") or "",
|
||||
})
|
||||
|
||||
return {
|
||||
"call_ins": call_ins,
|
||||
"total": len(call_ins),
|
||||
"source": "sfm-events",
|
||||
}
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
"""
|
||||
Admin / diagnostic pages for the device modules (SFM, SLMM).
|
||||
|
||||
These pages live under /admin/{module} and exist purely so an operator can
|
||||
peek under the hood and confirm the module is reachable, what data it's
|
||||
holding, and whether the proxy from terra-view is healthy.
|
||||
|
||||
Routes:
|
||||
GET /admin/sfm — SFM diagnostic page
|
||||
GET /admin/slmm — SLMM diagnostic page
|
||||
|
||||
API helpers (called by the HTML pages via fetch):
|
||||
GET /api/admin/sfm/overview — aggregated SFM health + db stats in one call
|
||||
GET /api/admin/slmm/overview — aggregated SLMM health + device count
|
||||
|
||||
The pages are intentionally read-only. Any actual administration of SFM
|
||||
or SLMM happens in those modules directly.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict
|
||||
|
||||
import httpx
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from fastapi.responses import HTMLResponse, JSONResponse
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from backend.database import get_db
|
||||
from backend.templates_config import templates
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
SFM_BASE_URL = os.getenv("SFM_BASE_URL", "http://localhost:8200")
|
||||
SLMM_BASE_URL = os.getenv("SLMM_BASE_URL", "http://localhost:8100")
|
||||
|
||||
|
||||
# ── SFM ───────────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@router.get("/admin/sfm", response_class=HTMLResponse)
|
||||
def admin_sfm_page(request: Request):
|
||||
return templates.TemplateResponse("admin_sfm.html", {
|
||||
"request": request,
|
||||
"sfm_base_url": SFM_BASE_URL,
|
||||
})
|
||||
|
||||
|
||||
@router.get("/api/admin/sfm/overview")
|
||||
async def admin_sfm_overview() -> JSONResponse:
|
||||
"""Aggregated SFM diagnostic snapshot.
|
||||
|
||||
Returns health, db stats, stale-table counts, per-unit summary, and
|
||||
recent events with forwarding latency. Tolerant of partial failures:
|
||||
any individual sub-fetch error is captured into its section, so a flaky
|
||||
sub-endpoint doesn't break the whole page.
|
||||
"""
|
||||
overview: Dict[str, Any] = {
|
||||
"sfm_base_url": SFM_BASE_URL,
|
||||
"checked_at": datetime.now(timezone.utc).isoformat(),
|
||||
"health": None,
|
||||
"reachable": False,
|
||||
"units": [],
|
||||
"events": [],
|
||||
"stale": {
|
||||
"monitor_log": None,
|
||||
"sessions": None,
|
||||
},
|
||||
"cache_stats": None,
|
||||
"errors": {},
|
||||
}
|
||||
|
||||
async with httpx.AsyncClient(timeout=5.0) as client:
|
||||
# Health
|
||||
try:
|
||||
r = await client.get(f"{SFM_BASE_URL}/health")
|
||||
r.raise_for_status()
|
||||
overview["health"] = r.json()
|
||||
overview["reachable"] = overview["health"].get("status") == "ok"
|
||||
except Exception as e: # noqa: BLE001
|
||||
overview["errors"]["health"] = str(e)
|
||||
overview["reachable"] = False
|
||||
|
||||
# If SFM is down, no point hitting the rest.
|
||||
if not overview["reachable"]:
|
||||
return JSONResponse(overview)
|
||||
|
||||
# Units
|
||||
try:
|
||||
r = await client.get(f"{SFM_BASE_URL}/db/units")
|
||||
r.raise_for_status()
|
||||
overview["units"] = r.json() or []
|
||||
except Exception as e: # noqa: BLE001
|
||||
overview["errors"]["units"] = str(e)
|
||||
|
||||
# Recent events (newest 25 — bigger sample of the call-home stream)
|
||||
try:
|
||||
r = await client.get(f"{SFM_BASE_URL}/db/events", params={"limit": 25})
|
||||
r.raise_for_status()
|
||||
payload = r.json() or {}
|
||||
events = payload.get("events", []) or []
|
||||
# Compute forwarding latency: created_at (SFM ingest) − timestamp (event).
|
||||
now = datetime.now(timezone.utc)
|
||||
for ev in events:
|
||||
ev.pop("waveform_blob", None)
|
||||
ev.pop("a5_pickle_filename", None)
|
||||
ts_str = ev.get("timestamp")
|
||||
ca_str = ev.get("created_at")
|
||||
latency_seconds = None
|
||||
try:
|
||||
if ts_str and ca_str:
|
||||
ts = datetime.fromisoformat(ts_str.replace("Z", "+00:00"))
|
||||
ca = datetime.fromisoformat(ca_str.replace("Z", "+00:00"))
|
||||
if ts.tzinfo is None: ts = ts.replace(tzinfo=timezone.utc)
|
||||
if ca.tzinfo is None: ca = ca.replace(tzinfo=timezone.utc)
|
||||
latency_seconds = (ca - ts).total_seconds()
|
||||
except ValueError:
|
||||
pass
|
||||
ev["forwarding_latency_seconds"] = latency_seconds
|
||||
overview["events"] = events
|
||||
except Exception as e: # noqa: BLE001
|
||||
overview["errors"]["events"] = str(e)
|
||||
|
||||
# Stale tables (deprecated by the watcher-forward pipeline but still
|
||||
# present in SFM's SQLite). Surface as counts only.
|
||||
for key, path in (("monitor_log", "/db/monitor_log"),
|
||||
("sessions", "/db/sessions")):
|
||||
try:
|
||||
r = await client.get(f"{SFM_BASE_URL}{path}", params={"limit": 1})
|
||||
r.raise_for_status()
|
||||
payload = r.json() or {}
|
||||
# SFM returns count = total when limit covers all rows; we
|
||||
# query with limit=1 just to be polite, then ask again with
|
||||
# a high limit if we need the real total.
|
||||
first_count = payload.get("count")
|
||||
if first_count is None:
|
||||
overview["stale"][key] = None
|
||||
continue
|
||||
# Re-query with high limit to get the true total.
|
||||
r2 = await client.get(f"{SFM_BASE_URL}{path}", params={"limit": 100000})
|
||||
r2.raise_for_status()
|
||||
overview["stale"][key] = (r2.json() or {}).get("count")
|
||||
except Exception as e: # noqa: BLE001
|
||||
overview["errors"][f"stale_{key}"] = str(e)
|
||||
|
||||
# Cache stats (in-memory device cache on SFM)
|
||||
try:
|
||||
r = await client.get(f"{SFM_BASE_URL}/cache/stats")
|
||||
r.raise_for_status()
|
||||
overview["cache_stats"] = r.json()
|
||||
except Exception as e: # noqa: BLE001
|
||||
overview["errors"]["cache_stats"] = str(e)
|
||||
|
||||
# Aggregate counts the UI can render without re-walking arrays
|
||||
overview["totals"] = {
|
||||
"units": len(overview["units"]),
|
||||
"events_total": sum(u.get("total_events", 0) for u in overview["units"]),
|
||||
"stale_monitor_log": overview["stale"]["monitor_log"],
|
||||
"stale_sessions": overview["stale"]["sessions"],
|
||||
}
|
||||
|
||||
return JSONResponse(overview)
|
||||
|
||||
|
||||
# ── SLMM ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@router.get("/admin/slmm", response_class=HTMLResponse)
|
||||
def admin_slmm_page(request: Request):
|
||||
return templates.TemplateResponse("admin_slmm.html", {
|
||||
"request": request,
|
||||
"slmm_base_url": SLMM_BASE_URL,
|
||||
})
|
||||
|
||||
|
||||
@router.get("/api/admin/slmm/overview")
|
||||
async def admin_slmm_overview() -> JSONResponse:
|
||||
"""Aggregated SLMM diagnostic snapshot."""
|
||||
overview: Dict[str, Any] = {
|
||||
"slmm_base_url": SLMM_BASE_URL,
|
||||
"checked_at": datetime.now(timezone.utc).isoformat(),
|
||||
"health": None,
|
||||
"reachable": False,
|
||||
"devices": [],
|
||||
"errors": {},
|
||||
}
|
||||
|
||||
async with httpx.AsyncClient(timeout=5.0) as client:
|
||||
try:
|
||||
r = await client.get(f"{SLMM_BASE_URL}/health")
|
||||
r.raise_for_status()
|
||||
overview["health"] = r.json()
|
||||
overview["reachable"] = True
|
||||
except Exception as e: # noqa: BLE001
|
||||
overview["errors"]["health"] = str(e)
|
||||
return JSONResponse(overview)
|
||||
|
||||
# Pull a roster of configured devices (SLMM exposes per-unit
|
||||
# config + status under /api/nl43/*). This is a best-effort probe
|
||||
# — SLMM doesn't expose a "list all devices" endpoint, so we ask
|
||||
# terra-view's RosterUnit table what serials it knows about for
|
||||
# SLMs and just check each one. For now, just surface the health
|
||||
# payload and let the operator click through to /sound-level-meters
|
||||
# for the per-device details.
|
||||
|
||||
return JSONResponse(overview)
|
||||
@@ -361,6 +361,9 @@ def locations_search(
|
||||
db.query(MonitoringLocation)
|
||||
.filter(MonitoringLocation.project_id == project_id)
|
||||
.filter(MonitoringLocation.location_type == "vibration")
|
||||
# Don't propose creating assignments at removed locations — they
|
||||
# were intentionally decommissioned and shouldn't be backfill targets.
|
||||
.filter(MonitoringLocation.removed_at == None) # noqa: E711
|
||||
.all()
|
||||
)
|
||||
|
||||
@@ -373,7 +376,11 @@ def locations_search(
|
||||
if q_norm in l_norm:
|
||||
scored.append((l, 1.0))
|
||||
continue
|
||||
score = svc.similarity(q_norm, l_norm)
|
||||
# Use the location-specific scorer (token_set_ratio + multi-digit
|
||||
# penalty) instead of WRatio — same reason as the cluster-match
|
||||
# path: location names share too much boilerplate vocabulary for
|
||||
# WRatio to discriminate reliably.
|
||||
score = svc.location_similarity(q_norm, l_norm)
|
||||
if score >= 0.50:
|
||||
scored.append((l, score))
|
||||
|
||||
|
||||
@@ -31,6 +31,7 @@ from backend.models import (
|
||||
MonitoringSession,
|
||||
DataFile,
|
||||
UnitHistory,
|
||||
ScheduledAction,
|
||||
)
|
||||
from backend.templates_config import templates
|
||||
from backend.utils.timezone import local_to_utc
|
||||
@@ -138,7 +139,7 @@ async def get_project_locations(
|
||||
):
|
||||
"""
|
||||
Get all monitoring locations for a project.
|
||||
Returns HTML partial with location list.
|
||||
Returns HTML partial with location list, split into active + removed.
|
||||
"""
|
||||
project = db.query(Project).filter_by(id=project_id).first()
|
||||
if not project:
|
||||
@@ -150,12 +151,35 @@ async def get_project_locations(
|
||||
if location_type:
|
||||
query = query.filter_by(location_type=location_type)
|
||||
|
||||
locations = query.order_by(MonitoringLocation.name).all()
|
||||
# Order by operator-set sort_order, then name as a stable tie-breaker.
|
||||
locations = query.order_by(MonitoringLocation.sort_order, MonitoringLocation.name).all()
|
||||
|
||||
# Enrich with assignment info
|
||||
locations_data = []
|
||||
# For vibration locations, fan out event counts via SFM concurrently
|
||||
# so the card layout can show "{N} events" instead of "Sessions: 0"
|
||||
# (sessions don't really exist for the watcher-forward pipeline).
|
||||
# Sound locations skip this and keep showing session counts.
|
||||
event_counts: dict[str, int] = {}
|
||||
vibration_locations = [l for l in locations if l.location_type == "vibration"]
|
||||
if vibration_locations:
|
||||
import asyncio
|
||||
from backend.services.sfm_events import events_for_location
|
||||
results = await asyncio.gather(
|
||||
*(events_for_location(db, l.id, limit=1) for l in vibration_locations),
|
||||
return_exceptions=True,
|
||||
)
|
||||
for loc, res in zip(vibration_locations, results):
|
||||
if isinstance(res, Exception):
|
||||
continue # leave event_counts[loc.id] unset → template falls back
|
||||
event_counts[loc.id] = (res.get("stats") or {}).get("event_count", 0) or 0
|
||||
|
||||
# Enrich with assignment info, splitting active vs removed.
|
||||
active_data: list = []
|
||||
removed_data: list = []
|
||||
for location in locations:
|
||||
# Get active assignment (active = assigned_until IS NULL)
|
||||
# Get active assignment (active = assigned_until IS NULL). For
|
||||
# removed locations this will normally be None because the
|
||||
# /remove cascade closes them, but check anyway for resilience
|
||||
# against legacy data.
|
||||
assignment = db.query(UnitAssignment).filter(
|
||||
and_(
|
||||
UnitAssignment.location_id == location.id,
|
||||
@@ -172,17 +196,25 @@ async def get_project_locations(
|
||||
location_id=location.id
|
||||
).count()
|
||||
|
||||
locations_data.append({
|
||||
"location": location,
|
||||
"assignment": assignment,
|
||||
item = {
|
||||
"location": location,
|
||||
"assignment": assignment,
|
||||
"assigned_unit": assigned_unit,
|
||||
"session_count": session_count,
|
||||
})
|
||||
}
|
||||
if location.id in event_counts:
|
||||
item["event_count"] = event_counts[location.id]
|
||||
if location.removed_at is None:
|
||||
active_data.append(item)
|
||||
else:
|
||||
removed_data.append(item)
|
||||
|
||||
return templates.TemplateResponse("partials/projects/location_list.html", {
|
||||
"request": request,
|
||||
"project": project,
|
||||
"locations": locations_data,
|
||||
"request": request,
|
||||
"project": project,
|
||||
"locations": active_data, # back-compat alias
|
||||
"active_locations": active_data,
|
||||
"removed_locations": removed_data,
|
||||
})
|
||||
|
||||
|
||||
@@ -191,10 +223,15 @@ async def get_project_locations_json(
|
||||
project_id: str,
|
||||
db: Session = Depends(get_db),
|
||||
location_type: Optional[str] = Query(None),
|
||||
include_removed: bool = Query(False),
|
||||
):
|
||||
"""
|
||||
Get all monitoring locations for a project as JSON.
|
||||
Used by the schedule modal to populate location dropdown.
|
||||
|
||||
Removed locations are filtered out by default (you can't schedule
|
||||
a new action at a removed location). Pass `include_removed=true`
|
||||
to get them too — useful for historical / reporting views.
|
||||
"""
|
||||
project = db.query(Project).filter_by(id=project_id).first()
|
||||
if not project:
|
||||
@@ -205,16 +242,21 @@ async def get_project_locations_json(
|
||||
if location_type:
|
||||
query = query.filter_by(location_type=location_type)
|
||||
|
||||
locations = query.order_by(MonitoringLocation.name).all()
|
||||
if not include_removed:
|
||||
query = query.filter(MonitoringLocation.removed_at == None) # noqa: E711
|
||||
|
||||
locations = query.order_by(MonitoringLocation.sort_order, MonitoringLocation.name).all()
|
||||
|
||||
return [
|
||||
{
|
||||
"id": loc.id,
|
||||
"name": loc.name,
|
||||
"location_type": loc.location_type,
|
||||
"description": loc.description,
|
||||
"address": loc.address,
|
||||
"coordinates": loc.coordinates,
|
||||
"id": loc.id,
|
||||
"name": loc.name,
|
||||
"location_type": loc.location_type,
|
||||
"description": loc.description,
|
||||
"address": loc.address,
|
||||
"coordinates": loc.coordinates,
|
||||
"removed_at": loc.removed_at.isoformat() if loc.removed_at else None,
|
||||
"removal_reason": loc.removal_reason,
|
||||
}
|
||||
for loc in locations
|
||||
]
|
||||
@@ -235,6 +277,13 @@ async def create_location(
|
||||
|
||||
form_data = await request.form()
|
||||
|
||||
# Compute next sort_order so new locations land at the END of the
|
||||
# project's list rather than getting interleaved alphabetically.
|
||||
from sqlalchemy import func
|
||||
max_sort = db.query(func.max(MonitoringLocation.sort_order))\
|
||||
.filter_by(project_id=project_id).scalar()
|
||||
next_sort_order = (max_sort or 0) + 1 if max_sort is not None else 0
|
||||
|
||||
location = MonitoringLocation(
|
||||
id=str(uuid.uuid4()),
|
||||
project_id=project_id,
|
||||
@@ -244,6 +293,7 @@ async def create_location(
|
||||
coordinates=form_data.get("coordinates"),
|
||||
address=form_data.get("address"),
|
||||
location_metadata=form_data.get("location_metadata"), # JSON string
|
||||
sort_order=next_sort_order,
|
||||
)
|
||||
|
||||
db.add(location)
|
||||
@@ -335,6 +385,216 @@ async def delete_location(
|
||||
return {"success": True, "message": "Location deleted successfully"}
|
||||
|
||||
|
||||
@router.post("/locations/reorder")
|
||||
async def reorder_locations(
|
||||
project_id: str,
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Persist a new sort order for a project's monitoring locations.
|
||||
|
||||
Body JSON: { "location_ids": [uuid, uuid, ...] }
|
||||
The list MUST contain location ids in the desired display order.
|
||||
Locations not included in the list keep their current sort_order
|
||||
(useful for the "active locations only — leave removed alone"
|
||||
drag-and-drop UX).
|
||||
|
||||
Updates `sort_order` to the index of each id in the list. Ties
|
||||
between included and excluded locations fall back to the existing
|
||||
sort_order.
|
||||
"""
|
||||
try:
|
||||
payload = await request.json()
|
||||
except Exception:
|
||||
raise HTTPException(status_code=400, detail="Invalid JSON body")
|
||||
|
||||
ids = payload.get("location_ids") or []
|
||||
if not isinstance(ids, list) or len(ids) == 0:
|
||||
raise HTTPException(status_code=400, detail="location_ids must be a non-empty list")
|
||||
|
||||
# Fetch only the locations being reordered and validate ownership.
|
||||
locations = db.query(MonitoringLocation).filter(
|
||||
MonitoringLocation.project_id == project_id,
|
||||
MonitoringLocation.id.in_(ids),
|
||||
).all()
|
||||
|
||||
found_ids = {l.id for l in locations}
|
||||
missing = [i for i in ids if i not in found_ids]
|
||||
if missing:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"Some locations not found in this project: {missing[:3]}…",
|
||||
)
|
||||
|
||||
# Apply 0-indexed sort_order matching the operator's chosen order.
|
||||
by_id = {l.id: l for l in locations}
|
||||
for idx, loc_id in enumerate(ids):
|
||||
by_id[loc_id].sort_order = idx
|
||||
|
||||
db.commit()
|
||||
return {"success": True, "reordered": len(ids)}
|
||||
|
||||
|
||||
@router.post("/locations/{location_id}/remove")
|
||||
async def remove_location(
|
||||
project_id: str,
|
||||
location_id: str,
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Soft-remove a monitoring location — mark it as no longer actively
|
||||
monitored without destroying it.
|
||||
|
||||
Use case: a client drops a location from scope mid-project, but the
|
||||
historical events recorded there should remain attributed. Deleting
|
||||
would orphan those events; this preserves them.
|
||||
|
||||
Cascading side-effects:
|
||||
1. All active UnitAssignment rows at this location are closed
|
||||
(assigned_until = effective_date, status = "completed").
|
||||
Units become available for other deployments.
|
||||
2. All pending ScheduledAction rows at this location are cancelled
|
||||
(execution_status = "cancelled").
|
||||
3. Historical events stay attributed (attribution is window-based;
|
||||
events with timestamp < effective_date still match the
|
||||
now-closed assignment windows).
|
||||
|
||||
Accepts JSON body:
|
||||
- effective_date: ISO datetime (optional, defaults to now)
|
||||
- reason: operator note (optional)
|
||||
"""
|
||||
location = db.query(MonitoringLocation).filter_by(
|
||||
id=location_id,
|
||||
project_id=project_id,
|
||||
).first()
|
||||
|
||||
if not location:
|
||||
raise HTTPException(status_code=404, detail="Location not found")
|
||||
|
||||
if location.removed_at is not None:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Location is already removed (as of {location.removed_at.isoformat()}).",
|
||||
)
|
||||
|
||||
# Body is optional — POST with no body is fine and means "remove now,
|
||||
# no reason given."
|
||||
try:
|
||||
payload = await request.json()
|
||||
except Exception:
|
||||
payload = {}
|
||||
|
||||
# Effective date: accept "YYYY-MM-DDTHH:MM" from datetime-local inputs or
|
||||
# full ISO. Defaults to now if absent/empty.
|
||||
raw_eff = payload.get("effective_date")
|
||||
if raw_eff:
|
||||
try:
|
||||
effective_date = datetime.fromisoformat(raw_eff)
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Invalid effective_date: {raw_eff!r}",
|
||||
)
|
||||
else:
|
||||
effective_date = datetime.utcnow()
|
||||
|
||||
reason = (payload.get("reason") or "").strip() or None
|
||||
|
||||
# 1. Close active assignments at this location.
|
||||
active_assignments = db.query(UnitAssignment).filter(
|
||||
and_(
|
||||
UnitAssignment.location_id == location_id,
|
||||
UnitAssignment.assigned_until == None, # noqa: E711 — SQL NULL
|
||||
)
|
||||
).all()
|
||||
|
||||
for a in active_assignments:
|
||||
a.status = "completed"
|
||||
a.assigned_until = effective_date
|
||||
_record_assignment_history(
|
||||
db,
|
||||
unit_id=a.unit_id,
|
||||
change_type="assignment_ended",
|
||||
old_value=location.name,
|
||||
new_value="location removed",
|
||||
notes=f"Location '{location.name}' marked as removed"
|
||||
+ (f" — {reason}" if reason else ""),
|
||||
)
|
||||
|
||||
# 2. Cancel pending scheduled actions at this location.
|
||||
pending_actions = db.query(ScheduledAction).filter(
|
||||
and_(
|
||||
ScheduledAction.location_id == location_id,
|
||||
ScheduledAction.execution_status == "pending",
|
||||
ScheduledAction.scheduled_time >= effective_date,
|
||||
)
|
||||
).all()
|
||||
|
||||
for sa in pending_actions:
|
||||
sa.execution_status = "cancelled"
|
||||
sa.error_message = (
|
||||
f"Cancelled: location '{location.name}' marked as removed"
|
||||
+ (f" — {reason}" if reason else "")
|
||||
)
|
||||
|
||||
# 3. Mark the location itself as removed.
|
||||
location.removed_at = effective_date
|
||||
location.removal_reason = reason
|
||||
location.updated_at = datetime.utcnow()
|
||||
|
||||
db.commit()
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"message": f"Location '{location.name}' marked as removed",
|
||||
"effective_date": effective_date.isoformat(),
|
||||
"assignments_closed": len(active_assignments),
|
||||
"actions_cancelled": len(pending_actions),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/locations/{location_id}/restore")
|
||||
async def restore_location(
|
||||
project_id: str,
|
||||
location_id: str,
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Restore a previously-removed monitoring location to active.
|
||||
|
||||
Clears `removed_at` and `removal_reason`. Does NOT automatically
|
||||
re-open the assignments or scheduled actions that were closed when
|
||||
the location was removed — those stay closed and the operator can
|
||||
create new ones if they want to resume monitoring.
|
||||
"""
|
||||
location = db.query(MonitoringLocation).filter_by(
|
||||
id=location_id,
|
||||
project_id=project_id,
|
||||
).first()
|
||||
|
||||
if not location:
|
||||
raise HTTPException(status_code=404, detail="Location not found")
|
||||
|
||||
if location.removed_at is None:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Location is already active.",
|
||||
)
|
||||
|
||||
location.removed_at = None
|
||||
location.removal_reason = None
|
||||
location.updated_at = datetime.utcnow()
|
||||
|
||||
db.commit()
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"message": f"Location '{location.name}' restored to active",
|
||||
}
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Unit Assignments
|
||||
# ============================================================================
|
||||
@@ -650,6 +910,228 @@ async def update_assignment(
|
||||
}
|
||||
|
||||
|
||||
@router.delete("/assignments/{assignment_id}")
|
||||
async def delete_assignment(
|
||||
project_id: str,
|
||||
assignment_id: str,
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Hard-delete an assignment record.
|
||||
|
||||
Use case: operator clicked Assign by mistake (or 8 times in a row) and
|
||||
wants the bogus records gone — not just closed with an `assigned_until`
|
||||
timestamp. The standard close-via-unassign path is for legitimate
|
||||
deployments that ended; this is for mis-clicks that never actually
|
||||
happened.
|
||||
|
||||
Safety:
|
||||
- Refuses if any MonitoringSession exists for the same (unit, location)
|
||||
within this assignment's window — that suggests the deployment was
|
||||
real, and the operator should use unassign instead.
|
||||
- Refuses if the assignment is the ONLY active assignment for a unit
|
||||
currently shown as deployed AND a recording session is in progress.
|
||||
|
||||
Audit:
|
||||
- Records UnitHistory `assignment_deleted` so the unit's deployment
|
||||
timeline shows the deletion happened (even though the row itself
|
||||
is gone).
|
||||
"""
|
||||
assignment = db.query(UnitAssignment).filter_by(
|
||||
id=assignment_id,
|
||||
project_id=project_id,
|
||||
).first()
|
||||
|
||||
if not assignment:
|
||||
raise HTTPException(status_code=404, detail="Assignment not found")
|
||||
|
||||
# Safety: is there a real recording history for this (unit, location)
|
||||
# within the assignment's time window? If so, this isn't a mis-click —
|
||||
# the operator should close it via unassign, not delete it.
|
||||
window_start = assignment.assigned_at
|
||||
window_end = assignment.assigned_until or datetime.utcnow()
|
||||
real_sessions = db.query(MonitoringSession).filter(
|
||||
and_(
|
||||
MonitoringSession.location_id == assignment.location_id,
|
||||
MonitoringSession.unit_id == assignment.unit_id,
|
||||
MonitoringSession.started_at >= window_start,
|
||||
MonitoringSession.started_at <= window_end,
|
||||
)
|
||||
).count()
|
||||
|
||||
if real_sessions > 0:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=(
|
||||
f"Cannot delete this assignment — {real_sessions} monitoring "
|
||||
f"session(s) were recorded under it. Use Unassign to close "
|
||||
f"the window instead, which preserves the audit trail."
|
||||
),
|
||||
)
|
||||
|
||||
# Resolve location name for audit log before deletion.
|
||||
location = db.query(MonitoringLocation).filter_by(
|
||||
id=assignment.location_id
|
||||
).first()
|
||||
location_label = location.name if location else assignment.location_id
|
||||
|
||||
_record_assignment_history(
|
||||
db,
|
||||
unit_id=assignment.unit_id,
|
||||
change_type="assignment_deleted",
|
||||
old_value=f"{location_label} ({assignment.assigned_at:%Y-%m-%d} → "
|
||||
f"{assignment.assigned_until and assignment.assigned_until.strftime('%Y-%m-%d') or 'active'})",
|
||||
new_value="deleted",
|
||||
notes=(
|
||||
"Assignment row removed — created in error or accidental duplicate."
|
||||
),
|
||||
)
|
||||
|
||||
db.delete(assignment)
|
||||
db.commit()
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"message": "Assignment deleted.",
|
||||
}
|
||||
|
||||
|
||||
@router.post("/assignments/merge")
|
||||
async def merge_assignments(
|
||||
project_id: str,
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Merge multiple consecutive UnitAssignment rows for the same (unit, location)
|
||||
into a single record spanning their combined window.
|
||||
|
||||
Use case: a unit's deployment timeline shows 3 stacked rows for the
|
||||
same location because the assignment was closed-and-reopened (e.g. via
|
||||
location remove + restore) or because metadata-backfill auto-created
|
||||
a retroactive window adjacent to a manual one. Operator sees three
|
||||
rows but they represent one continuous deployment.
|
||||
|
||||
Body JSON:
|
||||
{ "assignment_ids": ["<uuid>", "<uuid>", ...] }
|
||||
|
||||
Validation:
|
||||
- All assignments must belong to project_id
|
||||
- All must share the same unit_id AND location_id
|
||||
- At least 2 ids must be provided
|
||||
|
||||
Merge rules:
|
||||
- Keeps the EARLIEST-starting assignment as the surviving row
|
||||
- assigned_at = min(assigned_at across all)
|
||||
- assigned_until = max(assigned_until), or NULL if any input was active
|
||||
- status = "active" if any input was active, else "completed"
|
||||
- source = source of the earliest record (preserves original ingest provenance)
|
||||
- notes = earliest's notes + "Merged N records (<sources>)"
|
||||
- Other records are DELETED
|
||||
- One UnitHistory `assignment_merged` row is written for audit
|
||||
|
||||
No tolerance check — the operator is asking for the merge, so we trust
|
||||
the intent. The UI can pre-filter to only offer "consecutive" merges
|
||||
if it wants.
|
||||
"""
|
||||
try:
|
||||
payload = await request.json()
|
||||
except Exception:
|
||||
raise HTTPException(status_code=400, detail="Invalid JSON body")
|
||||
|
||||
ids = payload.get("assignment_ids") or []
|
||||
if not isinstance(ids, list) or len(ids) < 2:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Need at least 2 assignment_ids to merge.",
|
||||
)
|
||||
|
||||
assignments = (
|
||||
db.query(UnitAssignment)
|
||||
.filter(UnitAssignment.project_id == project_id)
|
||||
.filter(UnitAssignment.id.in_(ids))
|
||||
.all()
|
||||
)
|
||||
|
||||
if len(assignments) != len(set(ids)):
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"Some assignments not found (got {len(assignments)} of {len(set(ids))}).",
|
||||
)
|
||||
|
||||
unit_ids = {a.unit_id for a in assignments}
|
||||
loc_ids = {a.location_id for a in assignments}
|
||||
if len(unit_ids) > 1 or len(loc_ids) > 1:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Can only merge assignments that share the same unit and location.",
|
||||
)
|
||||
|
||||
# Order chronologically.
|
||||
assignments.sort(key=lambda a: a.assigned_at)
|
||||
earliest = assignments[0]
|
||||
others = assignments[1:]
|
||||
|
||||
# Compute merged window.
|
||||
any_active = any(a.assigned_until is None for a in assignments)
|
||||
if any_active:
|
||||
merged_until = None
|
||||
else:
|
||||
merged_until = max(a.assigned_until for a in assignments)
|
||||
|
||||
# Build a brief audit-style note describing what got merged.
|
||||
bits = []
|
||||
for a in assignments:
|
||||
win = (
|
||||
f"{a.assigned_at:%Y-%m-%d}"
|
||||
f"→{(a.assigned_until and a.assigned_until.strftime('%Y-%m-%d')) or 'active'}"
|
||||
)
|
||||
bits.append(f"{win} [{a.source}]")
|
||||
merge_note_suffix = f"Merged {len(assignments)} records: " + " + ".join(bits)
|
||||
new_notes = (earliest.notes + " • " + merge_note_suffix) if earliest.notes else merge_note_suffix
|
||||
|
||||
# Resolve names for the audit log before mutating.
|
||||
location = db.query(MonitoringLocation).filter_by(id=earliest.location_id).first()
|
||||
location_label = location.name if location else earliest.location_id
|
||||
|
||||
# Mutate the survivor.
|
||||
earliest.assigned_at = min(a.assigned_at for a in assignments)
|
||||
earliest.assigned_until = merged_until
|
||||
earliest.status = "active" if any_active else "completed"
|
||||
earliest.notes = new_notes
|
||||
|
||||
# Delete the rest.
|
||||
deleted_ids = [a.id for a in others]
|
||||
for a in others:
|
||||
db.delete(a)
|
||||
|
||||
_record_assignment_history(
|
||||
db,
|
||||
unit_id=earliest.unit_id,
|
||||
change_type="assignment_merged",
|
||||
old_value=f"{len(assignments)} rows at {location_label}",
|
||||
new_value=(
|
||||
f"1 row {earliest.assigned_at:%Y-%m-%d}"
|
||||
f"→{(merged_until and merged_until.strftime('%Y-%m-%d')) or 'active'}"
|
||||
),
|
||||
notes=merge_note_suffix,
|
||||
)
|
||||
|
||||
db.commit()
|
||||
db.refresh(earliest)
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"message": f"Merged {len(assignments)} assignments into one.",
|
||||
"kept_id": earliest.id,
|
||||
"deleted_ids": deleted_ids,
|
||||
"merged_window": {
|
||||
"assigned_at": earliest.assigned_at.isoformat(),
|
||||
"assigned_until": earliest.assigned_until.isoformat() if earliest.assigned_until else None,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.post("/locations/{location_id}/swap")
|
||||
async def swap_unit_on_location(
|
||||
project_id: str,
|
||||
|
||||
@@ -46,6 +46,13 @@ log = logging.getLogger("backend.services.deployment_timeline")
|
||||
# clutter from a sub-second handoff during a swap workflow.
|
||||
_MIN_GAP_SECONDS = 24 * 3600 # 1 day
|
||||
|
||||
# When detecting "mergeable" groups of consecutive same-location assignments,
|
||||
# treat assignments separated by no more than this many seconds as adjacent.
|
||||
# Generous enough to catch overnight handoffs and weekend gaps where the
|
||||
# operator forgot to log, but tight enough that genuinely separate
|
||||
# deployments months apart don't get suggested for merging.
|
||||
_MERGE_GAP_TOLERANCE_SECONDS = 7 * 24 * 3600 # 7 days
|
||||
|
||||
# Per-call timeout when querying SFM for the event overlay.
|
||||
_SFM_TIMEOUT = 10.0
|
||||
_SFM_FETCH_CEILING = 5000
|
||||
@@ -245,12 +252,41 @@ async def deployment_timeline_for_unit(
|
||||
"history_notes": h.notes,
|
||||
})
|
||||
|
||||
# 6. Sort newest first. Active assignments (no end) sort by start time,
|
||||
# 6. Detect mergeable groups — runs of consecutive assignments to the
|
||||
# same location with small gaps between them. Each group becomes a
|
||||
# list of assignment_ids; the UI offers a "Merge into one" action
|
||||
# on any group >= 2.
|
||||
merge_groups: list[list[str]] = []
|
||||
if len(assignments) >= 2:
|
||||
# Sort ascending for the linear scan.
|
||||
sorted_assignments = sorted(assignments, key=lambda a: a.assigned_at)
|
||||
cur_group: list[UnitAssignment] = [sorted_assignments[0]]
|
||||
for a in sorted_assignments[1:]:
|
||||
prev = cur_group[-1]
|
||||
same_location = a.location_id == prev.location_id
|
||||
prev_end = prev.assigned_until or now
|
||||
gap_seconds = (a.assigned_at - prev_end).total_seconds() if a.assigned_at else 0
|
||||
# Within tolerance and same location → extend the current group.
|
||||
# Negative gaps (overlap) also count as adjacent.
|
||||
if same_location and gap_seconds <= _MERGE_GAP_TOLERANCE_SECONDS:
|
||||
cur_group.append(a)
|
||||
else:
|
||||
if len(cur_group) >= 2:
|
||||
merge_groups.append([x.id for x in cur_group])
|
||||
cur_group = [a]
|
||||
if len(cur_group) >= 2:
|
||||
merge_groups.append([x.id for x in cur_group])
|
||||
|
||||
# 7. Sort newest first. Active assignments (no end) sort by start time,
|
||||
# same as everything else.
|
||||
entries.sort(key=lambda e: e.get("starts_at") or "", reverse=True)
|
||||
|
||||
return {
|
||||
"unit_id": unit.id,
|
||||
"device_type": unit.device_type,
|
||||
"entries": entries,
|
||||
"unit_id": unit.id,
|
||||
"device_type": unit.device_type,
|
||||
"entries": entries,
|
||||
# List of assignment_id lists; each inner list is a mergeable group.
|
||||
# Empty if nothing is mergeable. UI shows a "Merge" button on any
|
||||
# row whose assignment_id appears in a group.
|
||||
"merge_groups": merge_groups,
|
||||
}
|
||||
|
||||
@@ -162,6 +162,11 @@ def similarity(a: str, b: str) -> float:
|
||||
too short to fuzzy-match safely (see _MIN_FUZZY_LEN comment) AND the
|
||||
strings don't exact-match. This guardrails the 'one common word
|
||||
inside a longer phrase' false positive.
|
||||
|
||||
USE FOR: project names (where typos like '1-80' vs 'I-80' should
|
||||
still match). For location names use `location_similarity()` —
|
||||
WRatio is too lenient on the shared boilerplate vocabulary in
|
||||
location strings ('Area', 'Loc', 'Bridge', 'Dam', etc.).
|
||||
"""
|
||||
if not a or not b:
|
||||
return 0.0
|
||||
@@ -172,6 +177,50 @@ def similarity(a: str, b: str) -> float:
|
||||
return rapidfuzz.fuzz.WRatio(a, b) / 100.0
|
||||
|
||||
|
||||
# Multi-digit penalty applied when two location names have completely
|
||||
# disjoint multi-digit numeric tokens (e.g. "87 Jenks" vs "68 Jenks").
|
||||
# Single-digit numbers ("Loc 1", "Area 2") are often shared coincidentally,
|
||||
# but address-style multi-digit numbers are strong identifiers — if they
|
||||
# differ, the locations are usually different physical places.
|
||||
_LOCATION_DIGIT_MISMATCH_PENALTY = 0.30
|
||||
|
||||
|
||||
def location_similarity(a: str, b: str) -> float:
|
||||
"""Stricter similarity score for location-name matching.
|
||||
|
||||
Location names share so much boilerplate vocabulary ('Area', 'Loc',
|
||||
'Bridge', 'Dam') that rapidfuzz.WRatio inflates obvious mismatches.
|
||||
Example: 'Area 2 - Brookville Dam - Loc 2 East' vs 'Area 1 - Loc 1 -
|
||||
87 Jenks' scores 85.5 via WRatio despite being unrelated locations.
|
||||
|
||||
This scorer uses `token_set_ratio` as the base (sensitive to actual
|
||||
word overlap, not just substring containment). It then applies a
|
||||
multi-digit penalty: if both strings contain 2+-digit numbers and
|
||||
none overlap, subtract 0.30. Catches the "same project, different
|
||||
address-style identifier" case ('87 Jenks' vs '68 Jenks') that pure
|
||||
token-set scoring still rates above 0.90.
|
||||
|
||||
Single-digit numbers ('Loc 1', 'Area 2') are excluded from the
|
||||
penalty because they're often shared boilerplate ("Loc 1" in every
|
||||
project) rather than discriminating identifiers.
|
||||
"""
|
||||
if not a or not b:
|
||||
return 0.0
|
||||
if a == b:
|
||||
return 1.0
|
||||
if min(len(a), len(b)) < _MIN_FUZZY_LEN:
|
||||
return 0.0
|
||||
|
||||
base = rapidfuzz.fuzz.token_set_ratio(a, b) / 100.0
|
||||
|
||||
multidigits_a = set(re.findall(r"\d{2,}", a))
|
||||
multidigits_b = set(re.findall(r"\d{2,}", b))
|
||||
if multidigits_a and multidigits_b and not (multidigits_a & multidigits_b):
|
||||
base = max(0.0, base - _LOCATION_DIGIT_MISMATCH_PENALTY)
|
||||
|
||||
return base
|
||||
|
||||
|
||||
# ── Cluster + Suggestion dataclasses ───────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -572,15 +621,24 @@ async def _scan_clusters(
|
||||
def _find_best_match(
|
||||
candidate_norm: str,
|
||||
candidates: list[tuple[str, str]], # (id, normalised_name)
|
||||
*,
|
||||
kind: str = "project", # "project" | "location"
|
||||
) -> tuple[Optional[str], Optional[float], str]:
|
||||
"""Return (best_id, best_score, classification).
|
||||
|
||||
classification ∈ {"exact", "fuzzy", "ambiguous", "no_match"}
|
||||
|
||||
The `kind` parameter selects the scorer. Project matching uses
|
||||
rapidfuzz.WRatio (lenient — catches typos like '1-80' vs 'I-80').
|
||||
Location matching uses `location_similarity` (stricter — catches
|
||||
boilerplate-shared-but-actually-different strings like 'Loc 2 - 68
|
||||
Jenks' vs 'Loc 1 - 87 Jenks').
|
||||
"""
|
||||
if not candidate_norm or not candidates:
|
||||
return None, None, "no_match"
|
||||
|
||||
scored = [(cid, similarity(candidate_norm, cnorm)) for cid, cnorm in candidates]
|
||||
scorer = location_similarity if kind == "location" else similarity
|
||||
scored = [(cid, scorer(candidate_norm, cnorm)) for cid, cnorm in candidates]
|
||||
scored.sort(key=lambda x: x[1], reverse=True)
|
||||
best_id, best_score = scored[0]
|
||||
|
||||
@@ -725,7 +783,7 @@ def _build_suggestion(db: Session, cluster: Cluster) -> Suggestion:
|
||||
)
|
||||
location_candidates = [(l.id, _normalise(l.name)) for l in location_candidates_objs]
|
||||
if cluster.location_norm:
|
||||
loc_id, loc_score, loc_match = _find_best_match(cluster.location_norm, location_candidates)
|
||||
loc_id, loc_score, loc_match = _find_best_match(cluster.location_norm, location_candidates, kind="location")
|
||||
else:
|
||||
loc_id, loc_score, loc_match = None, None, "create_new"
|
||||
else:
|
||||
|
||||
@@ -318,13 +318,18 @@ async def events_for_unit(
|
||||
loc = loc_map.get(a.location_id)
|
||||
proj = proj_map.get(a.project_id)
|
||||
return {
|
||||
"assignment_id": a.id,
|
||||
"location_id": a.location_id,
|
||||
"location_name": loc.name if loc else None,
|
||||
"project_id": a.project_id,
|
||||
"project_name": proj.name if proj else None,
|
||||
"assigned_at": _iso_utc(a.assigned_at),
|
||||
"assigned_until": _iso_utc(a.assigned_until),
|
||||
"assignment_id": a.id,
|
||||
"location_id": a.location_id,
|
||||
"location_name": loc.name if loc else None,
|
||||
# Soft-removal indicator so the UI can render a "(removed)"
|
||||
# badge next to historical attributions whose location is no
|
||||
# longer actively monitored.
|
||||
"location_removed_at": (loc.removed_at.isoformat()
|
||||
if loc and loc.removed_at else None),
|
||||
"project_id": a.project_id,
|
||||
"project_name": proj.name if proj else None,
|
||||
"assigned_at": _iso_utc(a.assigned_at),
|
||||
"assigned_until": _iso_utc(a.assigned_until),
|
||||
}
|
||||
|
||||
# 2. Fetch all events for this serial in one shot.
|
||||
@@ -515,6 +520,10 @@ async def vibration_summary_for_project(
|
||||
"event_count": ec,
|
||||
"peak_pvs": ev_peak,
|
||||
"last_event": ev_last,
|
||||
# Soft-removal state — UI can show a "(removed)" badge in the
|
||||
# per-location list so operators see at a glance that a row's
|
||||
# numbers are historical-only.
|
||||
"removed_at": loc.removed_at.isoformat() if loc.removed_at else None,
|
||||
})
|
||||
|
||||
per_location.sort(key=lambda r: r["event_count"], reverse=True)
|
||||
@@ -548,7 +557,14 @@ def _empty_stats() -> dict:
|
||||
|
||||
|
||||
def _compute_stats(events: list[dict]) -> dict:
|
||||
"""Roll up summary stats from a merged event list. Cheap O(N) pass."""
|
||||
"""Roll up summary stats from a merged event list. Cheap O(N) pass.
|
||||
|
||||
The "Overall Peak" stat (peak_pvs) EXCLUDES events flagged as false
|
||||
triggers — operators care about the highest REAL event, not the
|
||||
biggest sensor glitch. false_trigger_count still includes them so
|
||||
operators can see how many were filtered out. last_event uses
|
||||
every event regardless (it's about activity recency, not magnitude).
|
||||
"""
|
||||
if not events:
|
||||
return _empty_stats()
|
||||
|
||||
@@ -559,19 +575,22 @@ def _compute_stats(events: list[dict]) -> dict:
|
||||
false_trigger_count = 0
|
||||
|
||||
for ev in events:
|
||||
pvs = ev.get("peak_vector_sum")
|
||||
if pvs is not None and (peak_pvs is None or pvs > peak_pvs):
|
||||
peak_pvs = pvs
|
||||
peak_pvs_at = ev.get("timestamp")
|
||||
peak_pvs_serial = ev.get("serial")
|
||||
is_false_trigger = bool(ev.get("false_trigger"))
|
||||
if is_false_trigger:
|
||||
false_trigger_count += 1
|
||||
|
||||
# Peak calculation: skip flagged false triggers.
|
||||
if not is_false_trigger:
|
||||
pvs = ev.get("peak_vector_sum")
|
||||
if pvs is not None and (peak_pvs is None or pvs > peak_pvs):
|
||||
peak_pvs = pvs
|
||||
peak_pvs_at = ev.get("timestamp")
|
||||
peak_pvs_serial = ev.get("serial")
|
||||
|
||||
ts = ev.get("timestamp")
|
||||
if ts and (last_event is None or ts > last_event):
|
||||
last_event = ts
|
||||
|
||||
if ev.get("false_trigger"):
|
||||
false_trigger_count += 1
|
||||
|
||||
return {
|
||||
"event_count": len(events),
|
||||
"peak_pvs": peak_pvs,
|
||||
|
||||
@@ -1,9 +1,77 @@
|
||||
from datetime import datetime, timezone
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from backend.database import get_db_session
|
||||
from backend.models import Emitter, RosterUnit, IgnoredUnit
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
SFM_BASE_URL = os.getenv("SFM_BASE_URL", "http://localhost:8200")
|
||||
|
||||
# Tiny module-level cache: /api/status-snapshot is polled every 10s by the
|
||||
# dashboard, and we don't want to hammer SFM with one /db/units roundtrip per
|
||||
# call. 15s TTL keeps the cache mostly hot, with occasional refreshes.
|
||||
_SFM_CACHE_TTL_SECONDS = 15.0
|
||||
_sfm_cache_lock = threading.Lock()
|
||||
_sfm_cache: dict = {"fetched_at": 0.0, "data": None, "reachable": False}
|
||||
|
||||
|
||||
def _parse_sfm_timestamp(ts_str: Optional[str]) -> Optional[datetime]:
|
||||
"""SFM /db/units returns naive ISO timestamps (no tz suffix). Treat them
|
||||
as UTC, mirroring how the watcher heartbeat stores Emitter.last_seen."""
|
||||
if not ts_str:
|
||||
return None
|
||||
try:
|
||||
ts = datetime.fromisoformat(ts_str.replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
return None
|
||||
if ts.tzinfo is None:
|
||||
ts = ts.replace(tzinfo=timezone.utc)
|
||||
return ts
|
||||
|
||||
|
||||
def fetch_sfm_unit_last_seen() -> tuple[dict[str, datetime], bool]:
|
||||
"""Return ({serial: last_seen_utc}, sfm_reachable).
|
||||
|
||||
Cached for _SFM_CACHE_TTL_SECONDS. On any HTTP error returns ({}, False)
|
||||
so callers transparently fall back to the watcher-heartbeat path.
|
||||
"""
|
||||
now = time.monotonic()
|
||||
with _sfm_cache_lock:
|
||||
if _sfm_cache["data"] is not None and (now - _sfm_cache["fetched_at"]) < _SFM_CACHE_TTL_SECONDS:
|
||||
return _sfm_cache["data"], _sfm_cache["reachable"]
|
||||
|
||||
data: dict[str, datetime] = {}
|
||||
reachable = False
|
||||
try:
|
||||
with httpx.Client(timeout=4.0) as client:
|
||||
resp = client.get(f"{SFM_BASE_URL}/db/units")
|
||||
resp.raise_for_status()
|
||||
payload = resp.json() or []
|
||||
for row in payload:
|
||||
serial = row.get("serial")
|
||||
ts = _parse_sfm_timestamp(row.get("last_seen"))
|
||||
if serial and ts is not None:
|
||||
data[serial] = ts
|
||||
reachable = True
|
||||
except httpx.HTTPError as e:
|
||||
log.warning("SFM /db/units unreachable for status snapshot: %s", e)
|
||||
except Exception as e: # noqa: BLE001 — defensive against malformed payload
|
||||
log.warning("SFM /db/units parse error: %s", e)
|
||||
|
||||
with _sfm_cache_lock:
|
||||
_sfm_cache["fetched_at"] = now
|
||||
_sfm_cache["data"] = data
|
||||
_sfm_cache["reachable"] = reachable
|
||||
return data, reachable
|
||||
|
||||
|
||||
def ensure_utc(dt):
|
||||
if dt is None:
|
||||
@@ -69,6 +137,11 @@ def emit_status_snapshot():
|
||||
emitters = {e.id: e for e in db.query(Emitter).all()}
|
||||
ignored = {i.id for i in db.query(IgnoredUnit).all()}
|
||||
|
||||
# SFM event-forwards are now the primary "last seen" signal for
|
||||
# seismographs. Watcher heartbeats stay as a backup — if SFM is down
|
||||
# or hasn't seen a serial, we fall back to Emitter.last_seen.
|
||||
sfm_last_seen_map, sfm_reachable = fetch_sfm_unit_last_seen()
|
||||
|
||||
units = {}
|
||||
|
||||
# --- Merge roster entries first ---
|
||||
@@ -93,24 +166,49 @@ def emit_status_snapshot():
|
||||
last_seen = None
|
||||
fname = ""
|
||||
else:
|
||||
if e:
|
||||
last_seen = ensure_utc(e.last_seen)
|
||||
# RECALCULATE status based on current time, not stored value
|
||||
device_type = r.device_type or "seismograph"
|
||||
emitter_last_seen = ensure_utc(e.last_seen) if e else None
|
||||
fname = e.last_file if e else ""
|
||||
|
||||
# SFM-primary, heartbeat-backup logic — only for seismographs.
|
||||
# (SLMs / modems aren't forwarded into SFM's events store.)
|
||||
sfm_last_seen = sfm_last_seen_map.get(unit_id) if device_type == "seismograph" else None
|
||||
|
||||
if sfm_last_seen and emitter_last_seen:
|
||||
# Both sources reported — use whichever is more recent.
|
||||
if sfm_last_seen >= emitter_last_seen:
|
||||
last_seen = sfm_last_seen
|
||||
last_seen_source = "sfm"
|
||||
else:
|
||||
last_seen = emitter_last_seen
|
||||
last_seen_source = "heartbeat"
|
||||
elif sfm_last_seen:
|
||||
last_seen = sfm_last_seen
|
||||
last_seen_source = "sfm"
|
||||
elif emitter_last_seen:
|
||||
last_seen = emitter_last_seen
|
||||
# If SFM was reachable but doesn't have this serial, it
|
||||
# means the unit is calling home to the watcher but not
|
||||
# being forwarded — still a working state for now.
|
||||
last_seen_source = "heartbeat"
|
||||
else:
|
||||
last_seen = None
|
||||
last_seen_source = "none"
|
||||
|
||||
if last_seen is not None:
|
||||
status = calculate_status(last_seen, status_ok_threshold, status_pending_threshold)
|
||||
age = format_age(last_seen)
|
||||
fname = e.last_file
|
||||
else:
|
||||
# Rostered but no emitter data
|
||||
status = "Missing"
|
||||
last_seen = None
|
||||
age = "N/A"
|
||||
fname = ""
|
||||
|
||||
units[unit_id] = {
|
||||
"id": unit_id,
|
||||
"status": status,
|
||||
"age": age,
|
||||
"last": last_seen.isoformat() if last_seen else None,
|
||||
"last_seen_source": last_seen_source,
|
||||
"sfm_reachable": sfm_reachable,
|
||||
"fname": fname,
|
||||
"deployed": r.deployed,
|
||||
"note": r.note or "",
|
||||
@@ -136,14 +234,23 @@ def emit_status_snapshot():
|
||||
# --- Add unexpected emitter-only units ---
|
||||
for unit_id, e in emitters.items():
|
||||
if unit_id not in roster:
|
||||
last_seen = ensure_utc(e.last_seen)
|
||||
emitter_last_seen = ensure_utc(e.last_seen)
|
||||
sfm_last_seen = sfm_last_seen_map.get(unit_id)
|
||||
if sfm_last_seen and (not emitter_last_seen or sfm_last_seen >= emitter_last_seen):
|
||||
last_seen = sfm_last_seen
|
||||
last_seen_source = "sfm"
|
||||
else:
|
||||
last_seen = emitter_last_seen
|
||||
last_seen_source = "heartbeat"
|
||||
# RECALCULATE status for unknown units too
|
||||
status = calculate_status(last_seen, status_ok_threshold, status_pending_threshold)
|
||||
units[unit_id] = {
|
||||
"id": unit_id,
|
||||
"status": status,
|
||||
"age": format_age(last_seen),
|
||||
"last": last_seen.isoformat(),
|
||||
"last": last_seen.isoformat() if last_seen else None,
|
||||
"last_seen_source": last_seen_source,
|
||||
"sfm_reachable": sfm_reachable,
|
||||
"fname": e.last_file,
|
||||
"deployed": False, # default
|
||||
"note": "",
|
||||
@@ -192,6 +299,7 @@ def emit_status_snapshot():
|
||||
unit_data["status"] = paired_unit.get("status", "Missing")
|
||||
unit_data["age"] = paired_unit.get("age", "N/A")
|
||||
unit_data["last"] = paired_unit.get("last")
|
||||
unit_data["last_seen_source"] = paired_unit.get("last_seen_source", "none")
|
||||
unit_data["derived_from"] = paired_unit_id
|
||||
|
||||
# Separate buckets for UI
|
||||
|
||||
@@ -62,6 +62,27 @@
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function _deriveRecordType(filename, fallback) {
|
||||
// SFM currently hardcodes record_type="Waveform" for every event.
|
||||
// The actual type is encoded in the LAST character of the Blastware
|
||||
// filename's extension (e.g. "O121LL5E.IS0H" → "H" → Histogram).
|
||||
// We derive it client-side until SFM is fixed; if the suffix isn't
|
||||
// a known code we fall back to whatever SFM reported.
|
||||
if (!filename) return fallback || '—';
|
||||
const dotIdx = filename.lastIndexOf('.');
|
||||
if (dotIdx < 0 || dotIdx === filename.length - 1) return fallback || '—';
|
||||
const ext = filename.slice(dotIdx + 1);
|
||||
const lastChar = ext.slice(-1).toUpperCase();
|
||||
const typeMap = {
|
||||
'H': 'Histogram',
|
||||
'W': 'Waveform',
|
||||
'M': 'Manual',
|
||||
'E': 'Event',
|
||||
'C': 'Combo',
|
||||
};
|
||||
return typeMap[lastChar] || (fallback || '—');
|
||||
}
|
||||
|
||||
function _sectionHeader(title, sub) {
|
||||
return `<h4 class="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider mb-3 mt-5 first:mt-0">
|
||||
${_esc(title)}${sub ? ` <span class="text-xs text-gray-400 normal-case font-normal ml-2">${_esc(sub)}</span>` : ''}
|
||||
@@ -72,20 +93,25 @@
|
||||
|
||||
function _renderEventHeader(s) {
|
||||
const ev = s.event || {};
|
||||
const bw = s.blastware || {};
|
||||
const ts = ev.timestamp ? ev.timestamp.replace('T', ' ').slice(0, 19) : '—';
|
||||
const recType = _deriveRecordType(bw.filename || ev.blastware_filename, ev.record_type);
|
||||
return `<div class="grid grid-cols-1 sm:grid-cols-3 gap-x-6 gap-y-2 text-sm">
|
||||
<div><span class="text-gray-500">Serial</span> <span class="font-mono font-semibold text-seismo-orange ml-1">${_esc(ev.serial)}</span></div>
|
||||
<div><span class="text-gray-500">Timestamp</span> <span class="font-medium ml-1">${ts}</span></div>
|
||||
<div><span class="text-gray-500">Record Type</span> <span class="font-medium ml-1">${_esc(ev.record_type || '—')}</span></div>
|
||||
<div><span class="text-gray-500">Record Type</span> <span class="font-medium ml-1">${_esc(recType)}</span></div>
|
||||
<div><span class="text-gray-500">Sample Rate</span> <span class="font-medium ml-1">${ev.sample_rate ?? '—'} sps</span></div>
|
||||
<div><span class="text-gray-500">Rec Time</span> <span class="font-medium ml-1">${ev.rectime_seconds != null ? ev.rectime_seconds + ' s' : '—'}</span></div>
|
||||
<div><span class="text-gray-500">Waveform Key</span> <span class="font-mono text-xs ml-1">${_esc(ev.waveform_key || '—')}</span></div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function _renderProjectInfo(s) {
|
||||
function _renderUserNotes(s) {
|
||||
// The "user notes" metadata the operator typed into the BW device.
|
||||
// These are the strings the future metadata-driven parser will use.
|
||||
// NOTE: SFM's sidecar JSON still names this block `project_info` —
|
||||
// we render it as "User Notes" (the actual BW term) but read the
|
||||
// field by its SFM-API name. Rename in SFM is a future cleanup.
|
||||
const p = s.project_info || {};
|
||||
return `<div class="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-2 text-sm">
|
||||
<div><span class="text-gray-500">Project</span> <span class="font-medium ml-1">${_esc(p.project || '—')}</span></div>
|
||||
@@ -120,20 +146,21 @@
|
||||
}
|
||||
|
||||
function _renderMic(s) {
|
||||
// Operators only care about dB(L); PSI tile was dropped 2026-05.
|
||||
// We still render the row if any mic data is present so ZC freq /
|
||||
// time-of-peak stay visible even when bw_report.mic is missing.
|
||||
const mic = (s.bw_report && s.bw_report.mic) || null;
|
||||
const pv = s.peak_values || {};
|
||||
|
||||
if (!mic && pv.mic_psi == null) return '';
|
||||
|
||||
const dbl = mic?.pspl_dbl;
|
||||
const psi = pv.mic_psi;
|
||||
const zcHz = mic?.zc_freq_hz;
|
||||
const tPk = mic?.time_of_peak_s;
|
||||
const wt = mic?.weighting;
|
||||
|
||||
return `<div class="grid grid-cols-2 sm:grid-cols-4 gap-3">
|
||||
return `<div class="grid grid-cols-1 sm:grid-cols-3 gap-3">
|
||||
${_kvCard('Peak Mic dB(L)', _fmt(dbl, 1), { sub: wt || '' })}
|
||||
${_kvCard('Peak Mic psi', _fmt(psi, 4))}
|
||||
${_kvCard('ZC Frequency', _fmt(zcHz, 1, 'Hz'))}
|
||||
${_kvCard('Time of Peak', tPk != null ? _fmt(tPk, 2, 's') : '—')}
|
||||
</div>`;
|
||||
@@ -223,6 +250,14 @@
|
||||
Blastware file unavailable
|
||||
</span>
|
||||
`}
|
||||
<button type="button"
|
||||
onclick="window.toggleEventJsonViewer()"
|
||||
class="inline-flex items-center gap-2 px-3 py-2 border border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg text-sm transition-colors">
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"></path>
|
||||
</svg>
|
||||
<span id="event-json-toggle-label">View JSON</span>
|
||||
</button>
|
||||
<a href="/api/sfm/db/events/${encodeURIComponent(eventId)}/sidecar"
|
||||
download="${_esc((bw.filename || 'event') + '.sfm.json')}"
|
||||
class="inline-flex items-center gap-2 px-3 py-2 border border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg text-sm transition-colors">
|
||||
@@ -232,6 +267,16 @@
|
||||
Download sidecar JSON
|
||||
</a>
|
||||
</div>
|
||||
<div id="event-json-viewer" class="hidden mb-4">
|
||||
<div class="flex items-center justify-between mb-2">
|
||||
<span class="text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wider">Sidecar JSON</span>
|
||||
<button type="button" onclick="window.copyEventJson()"
|
||||
class="text-xs text-seismo-orange hover:text-seismo-navy">
|
||||
<span id="event-json-copy-label">Copy</span>
|
||||
</button>
|
||||
</div>
|
||||
<pre id="event-json-pre" class="bg-gray-900 dark:bg-black text-gray-200 font-mono text-xs p-4 rounded-lg max-h-96 overflow-auto whitespace-pre">${_esc(JSON.stringify(s, null, 2))}</pre>
|
||||
</div>
|
||||
`;
|
||||
|
||||
return `${downloadButtons}
|
||||
@@ -294,8 +339,8 @@
|
||||
${_sectionHeader('Event')}
|
||||
${_renderEventHeader(s)}
|
||||
|
||||
${_sectionHeader('Project Info', '(operator-typed at session start)')}
|
||||
${_renderProjectInfo(s)}
|
||||
${_sectionHeader('User Notes')}
|
||||
${_renderUserNotes(s)}
|
||||
|
||||
${_sectionHeader('Peak Particle Velocity')}
|
||||
${_renderPeakValues(s)}
|
||||
@@ -323,6 +368,32 @@
|
||||
if (modal) modal.classList.add('hidden');
|
||||
};
|
||||
|
||||
window.toggleEventJsonViewer = function () {
|
||||
const viewer = document.getElementById('event-json-viewer');
|
||||
const label = document.getElementById('event-json-toggle-label');
|
||||
if (!viewer) return;
|
||||
const isHidden = viewer.classList.toggle('hidden');
|
||||
if (label) label.textContent = isHidden ? 'View JSON' : 'Hide JSON';
|
||||
};
|
||||
|
||||
window.copyEventJson = function () {
|
||||
const pre = document.getElementById('event-json-pre');
|
||||
const label = document.getElementById('event-json-copy-label');
|
||||
if (!pre) return;
|
||||
navigator.clipboard.writeText(pre.textContent).then(() => {
|
||||
if (label) {
|
||||
label.textContent = 'Copied!';
|
||||
setTimeout(() => { label.textContent = 'Copy'; }, 1500);
|
||||
}
|
||||
}).catch(err => {
|
||||
console.error('clipboard write failed', err);
|
||||
if (label) {
|
||||
label.textContent = 'Failed';
|
||||
setTimeout(() => { label.textContent = 'Copy'; }, 1500);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// Close on Escape.
|
||||
document.addEventListener('keydown', function (e) {
|
||||
if (e.key === 'Escape') window.closeEventDetailModal();
|
||||
|
||||
@@ -0,0 +1,436 @@
|
||||
# Synology NAS Deployment Guide
|
||||
|
||||
This guide covers migrating the terra-view stack from a generic Linux host
|
||||
(currently the home server at `10.0.0.44`) to an always-on Synology NAS in
|
||||
the office, including data migration and the minimal external-access
|
||||
networking layer.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
1. [Architecture overview](#architecture-overview)
|
||||
2. [Pre-requisites](#pre-requisites)
|
||||
3. [Phase 1 — Pre-stage on the NAS (no downtime)](#phase-1--pre-stage-on-the-nas-no-downtime)
|
||||
4. [Phase 2 — Data migration (~10 min window)](#phase-2--data-migration-10-min-window)
|
||||
5. [Phase 3 — Repoint the watcher (download2-PC)](#phase-3--repoint-the-watcher-download2-pc)
|
||||
6. [Phase 4 — External access for remote operators](#phase-4--external-access-for-remote-operators)
|
||||
7. [Phase 5 — Decommission home server](#phase-5--decommission-home-server)
|
||||
8. [Verification checklist](#verification-checklist)
|
||||
9. [Rollback plan](#rollback-plan)
|
||||
10. [Gotchas](#gotchas)
|
||||
|
||||
---
|
||||
|
||||
## Architecture overview
|
||||
|
||||
The terra-view stack is three containers:
|
||||
|
||||
| Service | Port | What writes to it | Where it lives |
|
||||
|---------------|-------|-----------------------------|----------------|
|
||||
| terra-view | 8001 | Operators (UI), watchers (heartbeat) | Synology NAS |
|
||||
| SFM | 8200 | Watchers (Blastware ACH forwards) | Synology NAS |
|
||||
| SLMM | 8100 | terra-view (proxied), SLMs on LAN | Synology NAS |
|
||||
|
||||
Everything that **writes** to the stack lives inside the office LAN:
|
||||
|
||||
- **download2-PC** is the series3-watcher host. It has a static office IP and
|
||||
POSTs to terra-view's heartbeat endpoint plus SFM's Blastware import
|
||||
endpoint. Both flows are LAN-internal.
|
||||
- **Sound level meters (NL-43)** sit on the office LAN; SLMM reaches them
|
||||
via `network_mode: host`.
|
||||
|
||||
The **only** thing that needs to cross the office firewall is operator UI
|
||||
access from outside the office (laptops, phones, working from home). That
|
||||
makes the external networking layer trivial — see Phase 4.
|
||||
|
||||
---
|
||||
|
||||
## Pre-requisites
|
||||
|
||||
On the Synology side:
|
||||
|
||||
- **DSM 7.2+** with **Container Manager** installed (Package Center).
|
||||
Older "Docker" package works too — same engine, different menu names.
|
||||
- **x86_64 model** (Plus / Value / XS series). ARM j-series will build but
|
||||
expect a slower first build.
|
||||
- **Static LAN IP** reserved for the NAS in the office router's DHCP table.
|
||||
Devices on the LAN must have a stable target.
|
||||
- **SSH enabled** — Control Panel → Terminal & SNMP → Enable SSH service.
|
||||
- **Shared folder** for the stack — e.g. `/volume1/docker/`.
|
||||
|
||||
On the home server side:
|
||||
|
||||
- Working terra-view / SFM / SLMM stack you want to migrate.
|
||||
- `rsync` available (it almost certainly is).
|
||||
|
||||
You will also need:
|
||||
|
||||
- An admin account on the Synology with sudo privileges.
|
||||
- Network access between the home server and the NAS during the migration
|
||||
window (or USB-drive shuttle if not).
|
||||
|
||||
---
|
||||
|
||||
## Phase 1 — Pre-stage on the NAS (no downtime)
|
||||
|
||||
Goal: get the NAS booting an empty stack so you can validate the build and
|
||||
networking *before* touching any production data.
|
||||
|
||||
### 1.1 Clone the repos
|
||||
|
||||
SSH to the NAS as admin:
|
||||
|
||||
```bash
|
||||
sudo mkdir -p /volume1/docker
|
||||
cd /volume1/docker
|
||||
sudo git clone <your-terra-view-remote> terra-view
|
||||
sudo git clone <your-slmm-remote> slmm
|
||||
sudo git clone <your-seismo-relay-remote> seismo-relay
|
||||
cd terra-view
|
||||
sudo git checkout main # or whichever branch you ship from
|
||||
```
|
||||
|
||||
### 1.2 Build images
|
||||
|
||||
```bash
|
||||
cd /volume1/docker/terra-view
|
||||
sudo docker compose build
|
||||
```
|
||||
|
||||
First build takes 5–15 min depending on model.
|
||||
|
||||
### 1.3 Boot the empty stack
|
||||
|
||||
```bash
|
||||
sudo docker compose up -d
|
||||
```
|
||||
|
||||
Hit `http://<nas-lan-ip>:1001` (dev profile) or `:8001` (prod profile) from
|
||||
another office machine. You should see an empty fleet roster. If that
|
||||
works, the NAS can run the stack — proven before any production data is
|
||||
at risk.
|
||||
|
||||
### 1.4 Stop the NAS stack again
|
||||
|
||||
```bash
|
||||
sudo docker compose stop
|
||||
```
|
||||
|
||||
We're ready for the data migration.
|
||||
|
||||
---
|
||||
|
||||
## Phase 2 — Data migration (~10 min window)
|
||||
|
||||
The terra-view stack is stateful in three places. All three must be moved
|
||||
together for consistency.
|
||||
|
||||
| Service | Data location (home server) |
|
||||
|------------|----------------------------------------------|
|
||||
| terra-view | `/home/serversdown/terra-view/data/` |
|
||||
| SLMM | `/home/serversdown/slmm/data/` |
|
||||
| SFM | `/home/serversdown/seismo-relay/data/` |
|
||||
|
||||
### 2.1 Stop writes on both sides
|
||||
|
||||
On the NAS:
|
||||
|
||||
```bash
|
||||
cd /volume1/docker/terra-view
|
||||
sudo docker compose stop
|
||||
```
|
||||
|
||||
On the home server:
|
||||
|
||||
```bash
|
||||
cd /home/serversdown/terra-view
|
||||
docker compose stop terra-view slmm sfm
|
||||
```
|
||||
|
||||
### 2.2 rsync the data dirs
|
||||
|
||||
From the home server (or anywhere with SSH access to both):
|
||||
|
||||
```bash
|
||||
rsync -avh /home/serversdown/terra-view/data/ admin@<nas-lan-ip>:/volume1/docker/terra-view/data/
|
||||
rsync -avh /home/serversdown/slmm/data/ admin@<nas-lan-ip>:/volume1/docker/slmm/data/
|
||||
rsync -avh /home/serversdown/seismo-relay/data/ admin@<nas-lan-ip>:/volume1/docker/seismo-relay/data/
|
||||
```
|
||||
|
||||
### 2.3 Fix ownership on the NAS
|
||||
|
||||
Synology admin is usually UID `1026`, GID `100`. Inside containers running
|
||||
as root, this doesn't matter — but if you've configured `user:` in any
|
||||
compose file it will. Safe default:
|
||||
|
||||
```bash
|
||||
ssh admin@<nas-lan-ip> "sudo chown -R 1026:100 \
|
||||
/volume1/docker/terra-view/data \
|
||||
/volume1/docker/slmm/data \
|
||||
/volume1/docker/seismo-relay/data"
|
||||
```
|
||||
|
||||
### 2.4 Run any pending migrations
|
||||
|
||||
Some earlier feature work added migration scripts that need to run once
|
||||
per database. After the rsync, before starting the stack, check what's
|
||||
pending:
|
||||
|
||||
```bash
|
||||
ssh admin@<nas-lan-ip>
|
||||
cd /volume1/docker/terra-view
|
||||
ls backend/migrate_*.py
|
||||
```
|
||||
|
||||
Run each one inside the container (after starting it temporarily) or apply
|
||||
them on the host with the same Python environment. Idempotent migrations
|
||||
re-run safely.
|
||||
|
||||
### 2.5 Start the NAS stack
|
||||
|
||||
```bash
|
||||
ssh admin@<nas-lan-ip> \
|
||||
"cd /volume1/docker/terra-view && sudo docker compose up -d"
|
||||
```
|
||||
|
||||
### 2.6 Spot-check
|
||||
|
||||
- Dashboard loads with real units
|
||||
- `/sfm` page lists historical events
|
||||
- A photo loads on a unit detail page
|
||||
- SFM/HB badge mix on the active table matches what you saw on the home
|
||||
server
|
||||
|
||||
If anything's off, see [Rollback plan](#rollback-plan).
|
||||
|
||||
---
|
||||
|
||||
## Phase 3 — Repoint the watcher (download2-PC)
|
||||
|
||||
The download2-PC is the one client we have to reconfigure. It currently
|
||||
POSTs to the home server. Two endpoints to change:
|
||||
|
||||
1. **terra-view heartbeat URL** —
|
||||
`http://<old-home-ip>:8001/api/series3/heartbeat`
|
||||
→ `http://<new-nas-lan-ip>:8001/api/series3/heartbeat`
|
||||
|
||||
2. **SFM Blastware import URL** —
|
||||
`http://<old-home-ip>:8200/db/import/blastware_file`
|
||||
→ `http://<new-nas-lan-ip>:8200/db/import/blastware_file`
|
||||
|
||||
Or, if you want to keep SFM container-internal and not publish 8200 on
|
||||
the LAN at all, point it through terra-view's existing SFM proxy:
|
||||
→ `http://<new-nas-lan-ip>:8001/api/sfm/db/import/blastware_file`
|
||||
|
||||
Update the config, restart the watcher service, and confirm the next
|
||||
heartbeat lands in the NAS DB (check the Recent Call-Ins card on the
|
||||
dashboard).
|
||||
|
||||
> **Tip:** keep the home server running in parallel for 1–2 days. If you
|
||||
> forget to repoint something, it'll still flow into the old DB and you
|
||||
> can resync.
|
||||
|
||||
---
|
||||
|
||||
## Phase 4 — External access for remote operators
|
||||
|
||||
Only the terra-view UI needs to be reachable from outside the office. Two
|
||||
clean options — pick one.
|
||||
|
||||
### Option A — Tailscale (recommended for small teams)
|
||||
|
||||
Zero port forwards, zero certs, zero public DNS, zero reverse proxy.
|
||||
|
||||
1. Install Tailscale from Synology Package Center, sign in.
|
||||
2. Install Tailscale on each operator's laptop/phone, sign in to the same
|
||||
tailnet.
|
||||
3. Operators access `http://<nas-tailscale-ip>:8001` from anywhere.
|
||||
|
||||
That's the whole setup. The office network has no external exposure at
|
||||
all.
|
||||
|
||||
### Option B — Reverse proxy with Let's Encrypt
|
||||
|
||||
If you want a `https://terraview.yourdomain.com` URL that any browser can
|
||||
reach:
|
||||
|
||||
#### B.1 Port forward on the office router
|
||||
|
||||
```
|
||||
WAN 443 → <nas-lan-ip>:443
|
||||
WAN 80 → <nas-lan-ip>:80 (only needed for Let's Encrypt HTTP-01;
|
||||
skip if you use DNS-01 challenge)
|
||||
```
|
||||
|
||||
Do **not** forward 1001, 8001, 8100, or 8200.
|
||||
|
||||
#### B.2 Public DNS
|
||||
|
||||
- Free: Synology DDNS (Control Panel → External Access → DDNS) — gives
|
||||
you `something.synology.me`.
|
||||
- Better: your own domain with an A record → office WAN IP, or a CNAME →
|
||||
Synology DDNS hostname (handles dynamic IPs automatically).
|
||||
|
||||
#### B.3 Let's Encrypt certificate
|
||||
|
||||
Control Panel → Security → Certificate → Add → "Get a certificate from
|
||||
Let's Encrypt." DSM handles renewal.
|
||||
|
||||
#### B.4 Synology reverse proxy
|
||||
|
||||
Control Panel → Login Portal → Advanced → Reverse Proxy → Create:
|
||||
|
||||
```
|
||||
Source: Hostname terraview.yourdomain.com
|
||||
Protocol HTTPS
|
||||
Port 443
|
||||
Destination: Hostname localhost
|
||||
Protocol HTTP
|
||||
Port 8001
|
||||
```
|
||||
|
||||
Under "Custom Header", add:
|
||||
|
||||
| Header | Value |
|
||||
|---------------------|------------------------------------|
|
||||
| `X-Forwarded-For` | `$proxy_add_x_forwarded_for` |
|
||||
| `X-Forwarded-Proto` | `$scheme` |
|
||||
| `Host` | `$host` |
|
||||
|
||||
Tick the WebSocket support checkbox.
|
||||
|
||||
#### B.5 DSM firewall
|
||||
|
||||
Control Panel → Security → Firewall → enable:
|
||||
|
||||
- 443/TCP from `Anywhere` — allow
|
||||
- 80/TCP from `Anywhere` — allow (cert renewal only)
|
||||
- Everything else from WAN — deny
|
||||
- All from LAN — allow
|
||||
|
||||
Optional: geo-block to your country if your operators are domestic only.
|
||||
Big reduction in scanning noise.
|
||||
|
||||
---
|
||||
|
||||
## Phase 5 — Decommission home server
|
||||
|
||||
After 1–2 weeks of stable NAS operation:
|
||||
|
||||
1. Take a final `docker compose down` on the home server.
|
||||
2. Archive `/home/serversdown/{terra-view,slmm,seismo-relay}/data/` to a
|
||||
backup volume.
|
||||
3. Free the home server hardware.
|
||||
|
||||
---
|
||||
|
||||
## Verification checklist
|
||||
|
||||
After Phase 2 (data migration):
|
||||
|
||||
- [ ] `http://<nas-lan-ip>:8001/` loads dashboard with real units
|
||||
- [ ] Recent Alerts, Call-Ins (2 cols), Fleet Summary across the top
|
||||
- [ ] SFM/HB badge mix on the active table looks sane
|
||||
- [ ] `/sfm` page lists historical events (the same count as before)
|
||||
- [ ] A unit detail page loads with photos rendering
|
||||
- [ ] `/api/recent-event-callins` returns 200 with real data
|
||||
- [ ] `/api/status-snapshot` returns 200, `sfm_reachable: true`
|
||||
|
||||
After Phase 3 (watcher cutover):
|
||||
|
||||
- [ ] Next heartbeat from download2-PC lands in NAS DB
|
||||
- [ ] A new event arrives in `/sfm` page on the NAS within the next
|
||||
Blastware ACH cycle
|
||||
- [ ] No errors in `docker logs terra-view-terra-view-1`
|
||||
|
||||
After Phase 4 (external access):
|
||||
|
||||
- [ ] (Option A) Operator laptop on tailnet can reach
|
||||
`http://<nas-tailscale-ip>:8001`
|
||||
- [ ] (Option B) `https://terraview.yourdomain.com` resolves, cert is
|
||||
valid, dashboard loads
|
||||
- [ ] (Option B) Office DSM admin (5001) is **not** reachable from outside
|
||||
|
||||
---
|
||||
|
||||
## Rollback plan
|
||||
|
||||
The home server stays alive in parallel through Phases 2–3 as a safety
|
||||
net. If anything goes wrong on the NAS:
|
||||
|
||||
1. On the home server:
|
||||
```bash
|
||||
cd /home/serversdown/terra-view
|
||||
docker compose up -d
|
||||
```
|
||||
2. Point download2-PC back at the home server IP.
|
||||
3. NAS data isn't lost — it's just sitting idle. Investigate, fix, retry.
|
||||
|
||||
The "irreversible" point is when you decommission the home server in
|
||||
Phase 5. Until then, you can always fall back.
|
||||
|
||||
---
|
||||
|
||||
## Gotchas
|
||||
|
||||
1. **Synology UID/GID quirks.** Synology admin is usually `1026:100`.
|
||||
Containers running as root inside don't care, but if your compose
|
||||
files set `user:`, mismatched UIDs cause SQLite "readonly database"
|
||||
errors. Easiest fix: omit `user:` and let containers run as root.
|
||||
|
||||
2. **`network_mode: host` for SLMM.** Required for LAN-direct comms with
|
||||
sound level meters. On Synology this binds to the NAS's interface —
|
||||
confirm nothing else on the NAS uses ports 8100 or 21 (FTP).
|
||||
|
||||
3. **Auto-start on boot.** Container Manager → Project → Settings →
|
||||
enable "Auto-restart". Otherwise a DSM update or NAS reboot drops the
|
||||
stack.
|
||||
|
||||
4. **`restart: unless-stopped` in compose.** Verify every service has it.
|
||||
DSM occasionally restarts Docker during DSM updates — this flag
|
||||
ensures everything comes back.
|
||||
|
||||
5. **Hyper Backup.** Schedule a daily snapshot of
|
||||
`/volume1/docker/terra-view/data/` to a USB drive or off-site. SQLite
|
||||
+ small photo dir = trivially small backups. The DB-Management UI's
|
||||
built-in snapshots are an additional layer but not a replacement.
|
||||
|
||||
6. **NAT loopback (Option B only).** If your office router doesn't
|
||||
support hairpinning, machines INSIDE the office can't reach the NAS
|
||||
by its public hostname — they have to use the LAN IP. Most modern
|
||||
routers handle this; some ISP-provided ones don't. Test from a laptop
|
||||
on the office Wi-Fi.
|
||||
|
||||
7. **Let's Encrypt rate limits (Option B only).** 5 issuances per domain
|
||||
per week. Don't fat-finger DNS or you'll be locked out. Test with the
|
||||
staging endpoint first if unsure.
|
||||
|
||||
8. **`host.docker.internal` resolution.** terra-view's
|
||||
`SFM_BASE_URL=http://host.docker.internal:8200` relies on Docker's
|
||||
internal DNS. Works on DSM 7.2+ in bridge mode. If you see "name not
|
||||
resolved" errors, fall back to explicit container names with a custom
|
||||
network in compose.
|
||||
|
||||
9. **SFM stale rows.** The SFM SQLite has a few rows in `monitor_log`
|
||||
and `ach_sessions` from earlier Python-ACH experiments. Harmless
|
||||
to bring over — invisible to terra-view's UI under the
|
||||
watcher-forward pipeline.
|
||||
|
||||
---
|
||||
|
||||
## Suggested timeline
|
||||
|
||||
For a low-risk migration:
|
||||
|
||||
- **Week 1**: Phase 1. Get the NAS booting an empty stack. No production
|
||||
touch.
|
||||
- **Week 2, day 1**: Phase 2. Migrate data. 10-min window. Keep home
|
||||
server alive in parallel.
|
||||
- **Week 2, day 1**: Phase 3. Repoint download2-PC. Watch heartbeats
|
||||
land on the NAS for the rest of the day.
|
||||
- **Week 3**: Phase 4. Add Tailscale or reverse-proxy access for remote
|
||||
operators.
|
||||
- **Week 4–5**: Monitor. Confirm everything's stable. Then Phase 5
|
||||
(decommission home server).
|
||||
|
||||
Splitting "make it work on LAN" from "expose it remotely" means you
|
||||
debug one thing at a time.
|
||||
@@ -275,7 +275,13 @@ async function _fetchTypeahead(input, fieldKind) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Args go in data-* attributes (not inline onclick) to avoid the quote
|
||||
// collision when location names contain characters JSON.stringify quotes
|
||||
// (e.g. anything with spaces/punctuation — basically every real name).
|
||||
// _esc() escapes for HTML attribute context (entities for <>&"), then
|
||||
// the browser decodes them when reading the dataset value.
|
||||
dropdown.innerHTML = items.map((it, idx) => {
|
||||
const cid = _esc(input.dataset.clusterId);
|
||||
if (it.kind === 'match') {
|
||||
const m = it.payload;
|
||||
const scoreBadge = m.score >= 0.99
|
||||
@@ -291,16 +297,24 @@ async function _fetchTypeahead(input, fieldKind) {
|
||||
}
|
||||
const metaLine = meta.length ? `<div class="text-xs text-gray-500 dark:text-gray-400">${meta.join(' · ')}</div>` : '';
|
||||
return `<button type="button"
|
||||
data-cid="${cid}"
|
||||
data-field-kind="${fieldKind}"
|
||||
data-entity-id="${_esc(m.id)}"
|
||||
data-entity-name="${_esc(m.name)}"
|
||||
onmousedown="event.preventDefault()"
|
||||
onclick="onTypeaheadPick(event, '${_esc(input.dataset.clusterId)}', '${fieldKind}', '${_esc(m.id)}', ${JSON.stringify(m.name)})"
|
||||
onclick="_typeaheadPickFromButton(this)"
|
||||
class="w-full text-left px-3 py-2 hover:bg-gray-50 dark:hover:bg-slate-700 border-b border-gray-100 dark:border-gray-700 last:border-b-0">
|
||||
<div class="text-sm font-medium text-gray-900 dark:text-white">${_esc(m.name)}${scoreBadge}</div>
|
||||
${metaLine}
|
||||
</button>`;
|
||||
}
|
||||
return `<button type="button"
|
||||
data-cid="${cid}"
|
||||
data-field-kind="${fieldKind}"
|
||||
data-entity-id=""
|
||||
data-entity-name="${_esc(it.name)}"
|
||||
onmousedown="event.preventDefault()"
|
||||
onclick="onTypeaheadPick(event, '${_esc(input.dataset.clusterId)}', '${fieldKind}', '', ${JSON.stringify(it.name)})"
|
||||
onclick="_typeaheadPickFromButton(this)"
|
||||
class="w-full text-left px-3 py-2 hover:bg-orange-50 dark:hover:bg-orange-900/20 border-t border-gray-200 dark:border-gray-700 text-seismo-orange font-medium text-sm">
|
||||
+ ${_esc(it.label)}
|
||||
</button>`;
|
||||
@@ -308,6 +322,19 @@ async function _fetchTypeahead(input, fieldKind) {
|
||||
dropdown.classList.remove('hidden');
|
||||
}
|
||||
|
||||
// Trampoline — reads the click target's data-* attributes and forwards
|
||||
// to onTypeaheadPick. Keeps the inline onclick attribute free of any
|
||||
// string interpolation that could collide with HTML quoting.
|
||||
function _typeaheadPickFromButton(btn) {
|
||||
onTypeaheadPick(
|
||||
null,
|
||||
btn.dataset.cid,
|
||||
btn.dataset.fieldKind,
|
||||
btn.dataset.entityId || '',
|
||||
btn.dataset.entityName || ''
|
||||
);
|
||||
}
|
||||
|
||||
function onTypeaheadPick(event, clusterId, fieldKind, entityId, name) {
|
||||
// entityId is empty string for "create new", or a UUID for matched existing.
|
||||
const inputs = document.querySelectorAll(`input[data-cluster-id="${clusterId}"]`);
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}SFM Admin - Seismo Fleet Manager{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="mb-8 flex items-center justify-between">
|
||||
<div>
|
||||
<a href="/settings#developer" class="text-sm text-seismo-orange hover:text-seismo-burgundy">← Back to Developer Tools</a>
|
||||
<h1 class="text-3xl font-bold text-gray-900 dark:text-white mt-1">SFM Admin</h1>
|
||||
<p class="text-gray-600 dark:text-gray-400 mt-1">Diagnostics for the Seismograph Field Module (SFM) backend.</p>
|
||||
</div>
|
||||
<button onclick="loadSfmOverview()"
|
||||
class="px-4 py-2 bg-seismo-orange hover:bg-orange-600 text-white text-sm font-medium rounded-lg">
|
||||
<span id="refresh-label">↻ Refresh</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Health Banner -->
|
||||
<div id="health-banner" class="rounded-xl p-4 mb-6 bg-gray-100 dark:bg-slate-800 border border-gray-200 dark:border-gray-700">
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400">Loading SFM status…</p>
|
||||
</div>
|
||||
|
||||
<!-- Connection Info -->
|
||||
<div class="rounded-xl bg-white dark:bg-slate-800 shadow-lg p-4 mb-6">
|
||||
<h2 class="text-sm font-semibold text-gray-700 dark:text-gray-300 uppercase tracking-wider mb-2">Connection</h2>
|
||||
<div class="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm">
|
||||
<div>
|
||||
<span class="text-gray-500 dark:text-gray-400">terra-view → SFM URL</span>
|
||||
<div class="font-mono text-gray-900 dark:text-white mt-0.5">{{ sfm_base_url }}</div>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-gray-500 dark:text-gray-400">Last checked</span>
|
||||
<div class="font-mono text-gray-900 dark:text-white mt-0.5" id="checked-at">—</div>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-gray-500 dark:text-gray-400">Version</span>
|
||||
<div class="font-mono text-gray-900 dark:text-white mt-0.5" id="sfm-version">—</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Stats Grid -->
|
||||
<div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
|
||||
<div class="bg-white dark:bg-slate-800 rounded-xl shadow-lg p-4">
|
||||
<div class="text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wider">Known Units</div>
|
||||
<div class="text-2xl font-bold text-gray-900 dark:text-white mt-1" id="stat-units">—</div>
|
||||
</div>
|
||||
<div class="bg-white dark:bg-slate-800 rounded-xl shadow-lg p-4">
|
||||
<div class="text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wider">Total Events</div>
|
||||
<div class="text-2xl font-bold text-gray-900 dark:text-white mt-1" id="stat-events">—</div>
|
||||
</div>
|
||||
<div class="bg-white dark:bg-slate-800 rounded-xl shadow-lg p-4">
|
||||
<div class="text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wider" title="Rows in SFM's deprecated monitor_log table (from paused Python-ACH experiment)">Stale: monitor_log</div>
|
||||
<div class="text-2xl font-bold text-gray-400 dark:text-gray-500 mt-1" id="stat-stale-monitor">—</div>
|
||||
</div>
|
||||
<div class="bg-white dark:bg-slate-800 rounded-xl shadow-lg p-4">
|
||||
<div class="text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wider" title="Rows in SFM's deprecated ach_sessions table (from paused Python-ACH experiment)">Stale: ach_sessions</div>
|
||||
<div class="text-2xl font-bold text-gray-400 dark:text-gray-500 mt-1" id="stat-stale-sessions">—</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Units Table -->
|
||||
<div class="rounded-xl bg-white dark:bg-slate-800 shadow-lg p-4 mb-6">
|
||||
<h2 class="text-sm font-semibold text-gray-700 dark:text-gray-300 uppercase tracking-wider mb-3">Per-Unit Roll-up</h2>
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mb-3">All seismograph serials SFM has ever seen, with their last-event timestamp and total event count. Sourced from <code class="font-mono">GET /db/units</code>.</p>
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-left text-sm">
|
||||
<thead class="bg-gray-50 dark:bg-slate-700">
|
||||
<tr>
|
||||
<th class="px-3 py-2 text-xs font-medium text-gray-600 dark:text-gray-400 uppercase">Serial</th>
|
||||
<th class="px-3 py-2 text-xs font-medium text-gray-600 dark:text-gray-400 uppercase">Last Seen</th>
|
||||
<th class="px-3 py-2 text-xs font-medium text-gray-600 dark:text-gray-400 uppercase text-right">Events</th>
|
||||
<th class="px-3 py-2 text-xs font-medium text-gray-600 dark:text-gray-400 uppercase text-right">Monitor (stale)</th>
|
||||
<th class="px-3 py-2 text-xs font-medium text-gray-600 dark:text-gray-400 uppercase text-right">Sessions (stale)</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="units-tbody" class="divide-y divide-gray-200 dark:divide-gray-700">
|
||||
<tr><td colspan="5" class="px-3 py-6 text-center text-gray-500">Loading…</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Recent Events with Latency -->
|
||||
<div class="rounded-xl bg-white dark:bg-slate-800 shadow-lg p-4 mb-6">
|
||||
<h2 class="text-sm font-semibold text-gray-700 dark:text-gray-300 uppercase tracking-wider mb-3">Recent Events — Forwarding Latency</h2>
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mb-3">The last 25 events SFM ingested, with the gap between the event's recorded timestamp and when SFM received the forward. Large latencies indicate the watcher is forwarding stale files (e.g. after a network outage).</p>
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-left text-sm">
|
||||
<thead class="bg-gray-50 dark:bg-slate-700">
|
||||
<tr>
|
||||
<th class="px-3 py-2 text-xs font-medium text-gray-600 dark:text-gray-400 uppercase">Recorded</th>
|
||||
<th class="px-3 py-2 text-xs font-medium text-gray-600 dark:text-gray-400 uppercase">Serial</th>
|
||||
<th class="px-3 py-2 text-xs font-medium text-gray-600 dark:text-gray-400 uppercase">Forwarded</th>
|
||||
<th class="px-3 py-2 text-xs font-medium text-gray-600 dark:text-gray-400 uppercase">Latency</th>
|
||||
<th class="px-3 py-2 text-xs font-medium text-gray-600 dark:text-gray-400 uppercase">File</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="events-tbody" class="divide-y divide-gray-200 dark:divide-gray-700">
|
||||
<tr><td colspan="5" class="px-3 py-6 text-center text-gray-500">Loading…</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Raw API tester -->
|
||||
<div class="rounded-xl bg-white dark:bg-slate-800 shadow-lg p-4 mb-6">
|
||||
<h2 class="text-sm font-semibold text-gray-700 dark:text-gray-300 uppercase tracking-wider mb-3">Raw API Tester</h2>
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mb-3">Send a GET request to any SFM endpoint via the terra-view <code class="font-mono">/api/sfm/*</code> proxy. Path is relative to SFM root (no leading slash).</p>
|
||||
<div class="flex gap-2 mb-3">
|
||||
<span class="px-3 py-2 text-sm bg-gray-100 dark:bg-slate-700 text-gray-700 dark:text-gray-300 font-mono rounded-l-lg">/api/sfm/</span>
|
||||
<input id="raw-path" type="text" placeholder="db/units" value="db/units"
|
||||
class="flex-1 px-3 py-2 text-sm bg-white dark:bg-slate-900 text-gray-900 dark:text-white border border-gray-300 dark:border-gray-600 rounded font-mono"
|
||||
onkeydown="if(event.key==='Enter') sendRaw();">
|
||||
<button onclick="sendRaw()"
|
||||
class="px-4 py-2 bg-seismo-orange hover:bg-orange-600 text-white text-sm rounded-lg">
|
||||
GET
|
||||
</button>
|
||||
</div>
|
||||
<pre id="raw-response" class="bg-gray-900 dark:bg-black text-gray-200 font-mono text-xs p-3 rounded-lg max-h-96 overflow-auto whitespace-pre hidden"></pre>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function _fmtAge(seconds) {
|
||||
if (seconds == null) return '—';
|
||||
const abs = Math.abs(seconds);
|
||||
if (abs < 60) return seconds.toFixed(0) + 's';
|
||||
if (abs < 3600) return (seconds / 60).toFixed(1) + 'm';
|
||||
if (abs < 86400) return (seconds / 3600).toFixed(1) + 'h';
|
||||
return (seconds / 86400).toFixed(1) + 'd';
|
||||
}
|
||||
|
||||
function _latencyClass(seconds) {
|
||||
if (seconds == null) return 'text-gray-400';
|
||||
if (seconds < 600) return 'text-green-600 dark:text-green-400'; // <10 min
|
||||
if (seconds < 3600) return 'text-amber-600 dark:text-amber-400'; // <1 hr
|
||||
return 'text-red-600 dark:text-red-400 font-semibold'; // 1hr+
|
||||
}
|
||||
|
||||
function _esc(s) {
|
||||
if (s == null) return '';
|
||||
return String(s).replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"');
|
||||
}
|
||||
|
||||
async function loadSfmOverview() {
|
||||
const lbl = document.getElementById('refresh-label');
|
||||
lbl.textContent = '↻ Loading…';
|
||||
try {
|
||||
const r = await fetch('/api/admin/sfm/overview');
|
||||
if (!r.ok) throw new Error('HTTP ' + r.status);
|
||||
const d = await r.json();
|
||||
renderOverview(d);
|
||||
} catch (e) {
|
||||
document.getElementById('health-banner').innerHTML = `
|
||||
<div class="text-red-600 dark:text-red-400 text-sm font-medium">
|
||||
Failed to load SFM overview: ${_esc(e.message)}
|
||||
</div>`;
|
||||
} finally {
|
||||
lbl.textContent = '↻ Refresh';
|
||||
}
|
||||
}
|
||||
|
||||
function renderOverview(d) {
|
||||
// Banner
|
||||
const banner = document.getElementById('health-banner');
|
||||
if (d.reachable) {
|
||||
banner.className = 'rounded-xl p-4 mb-6 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800';
|
||||
banner.innerHTML = `
|
||||
<div class="flex items-center gap-3">
|
||||
<span class="w-3 h-3 rounded-full bg-green-500"></span>
|
||||
<div>
|
||||
<div class="font-semibold text-green-800 dark:text-green-300">SFM reachable</div>
|
||||
<div class="text-xs text-green-700 dark:text-green-400">${_esc(d.health?.service || 'sfm')} v${_esc(d.health?.version || '?')}</div>
|
||||
</div>
|
||||
</div>`;
|
||||
} else {
|
||||
banner.className = 'rounded-xl p-4 mb-6 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800';
|
||||
const errs = Object.entries(d.errors || {}).map(([k, v]) => `${k}: ${v}`).join('; ');
|
||||
banner.innerHTML = `
|
||||
<div class="flex items-center gap-3">
|
||||
<span class="w-3 h-3 rounded-full bg-red-500"></span>
|
||||
<div>
|
||||
<div class="font-semibold text-red-800 dark:text-red-300">SFM unreachable</div>
|
||||
<div class="text-xs text-red-700 dark:text-red-400">${_esc(errs || 'no details')}</div>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
// Header info
|
||||
document.getElementById('checked-at').textContent = d.checked_at ? d.checked_at.slice(0, 19).replace('T', ' ') : '—';
|
||||
document.getElementById('sfm-version').textContent = d.health?.version || '—';
|
||||
|
||||
// Stats
|
||||
const t = d.totals || {};
|
||||
document.getElementById('stat-units').textContent = (t.units ?? 0).toLocaleString();
|
||||
document.getElementById('stat-events').textContent = (t.events_total ?? 0).toLocaleString();
|
||||
document.getElementById('stat-stale-monitor').textContent = t.stale_monitor_log != null ? t.stale_monitor_log.toLocaleString() : '—';
|
||||
document.getElementById('stat-stale-sessions').textContent = t.stale_sessions != null ? t.stale_sessions.toLocaleString() : '—';
|
||||
|
||||
// Units table
|
||||
const unitsBody = document.getElementById('units-tbody');
|
||||
if (!d.units || d.units.length === 0) {
|
||||
unitsBody.innerHTML = `<tr><td colspan="5" class="px-3 py-6 text-center text-gray-500">No units in SFM yet.</td></tr>`;
|
||||
} else {
|
||||
const sorted = [...d.units].sort((a, b) => (b.last_seen || '').localeCompare(a.last_seen || ''));
|
||||
unitsBody.innerHTML = sorted.map(u => {
|
||||
const ls = u.last_seen ? u.last_seen.replace('T', ' ').slice(0, 19) : '—';
|
||||
return `<tr class="hover:bg-gray-50 dark:hover:bg-slate-700/50">
|
||||
<td class="px-3 py-2 font-mono text-seismo-orange"><a href="/unit/${encodeURIComponent(u.serial)}" class="hover:underline">${_esc(u.serial)}</a></td>
|
||||
<td class="px-3 py-2 text-gray-900 dark:text-gray-200">${_esc(ls)}</td>
|
||||
<td class="px-3 py-2 text-right text-gray-900 dark:text-gray-200">${(u.total_events || 0).toLocaleString()}</td>
|
||||
<td class="px-3 py-2 text-right text-gray-500">${(u.total_monitor_entries || 0).toLocaleString()}</td>
|
||||
<td class="px-3 py-2 text-right text-gray-500">${(u.total_sessions || 0).toLocaleString()}</td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
// Events table
|
||||
const evBody = document.getElementById('events-tbody');
|
||||
if (!d.events || d.events.length === 0) {
|
||||
evBody.innerHTML = `<tr><td colspan="5" class="px-3 py-6 text-center text-gray-500">No events.</td></tr>`;
|
||||
} else {
|
||||
evBody.innerHTML = d.events.map(ev => {
|
||||
const ts = ev.timestamp ? ev.timestamp.replace('T', ' ').slice(0, 19) : '—';
|
||||
const ca = ev.created_at ? ev.created_at.replace('T', ' ').slice(0, 19) : '—';
|
||||
const lat = ev.forwarding_latency_seconds;
|
||||
return `<tr class="hover:bg-gray-50 dark:hover:bg-slate-700/50">
|
||||
<td class="px-3 py-2 text-gray-900 dark:text-gray-200 whitespace-nowrap">${_esc(ts)}</td>
|
||||
<td class="px-3 py-2 font-mono text-seismo-orange">${_esc(ev.serial)}</td>
|
||||
<td class="px-3 py-2 text-gray-600 dark:text-gray-400 whitespace-nowrap">${_esc(ca)}</td>
|
||||
<td class="px-3 py-2 font-mono ${_latencyClass(lat)}">${_fmtAge(lat)}</td>
|
||||
<td class="px-3 py-2 font-mono text-xs text-gray-500 dark:text-gray-400">${_esc(ev.blastware_filename || '—')}</td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
}
|
||||
}
|
||||
|
||||
async function sendRaw() {
|
||||
const path = document.getElementById('raw-path').value.trim().replace(/^\//, '');
|
||||
if (!path) return;
|
||||
const pre = document.getElementById('raw-response');
|
||||
pre.classList.remove('hidden');
|
||||
pre.textContent = 'Loading…';
|
||||
try {
|
||||
const r = await fetch('/api/sfm/' + path);
|
||||
const text = await r.text();
|
||||
try {
|
||||
const j = JSON.parse(text);
|
||||
pre.textContent = `HTTP ${r.status}\n\n${JSON.stringify(j, null, 2)}`;
|
||||
} catch {
|
||||
pre.textContent = `HTTP ${r.status}\n\n${text.slice(0, 8000)}`;
|
||||
}
|
||||
} catch (e) {
|
||||
pre.textContent = 'Error: ' + e.message;
|
||||
}
|
||||
}
|
||||
|
||||
loadSfmOverview();
|
||||
setInterval(loadSfmOverview, 30000);
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,138 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}SLMM Admin - Seismo Fleet Manager{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="mb-8 flex items-center justify-between">
|
||||
<div>
|
||||
<a href="/settings#developer" class="text-sm text-seismo-orange hover:text-seismo-burgundy">← Back to Developer Tools</a>
|
||||
<h1 class="text-3xl font-bold text-gray-900 dark:text-white mt-1">SLMM Admin</h1>
|
||||
<p class="text-gray-600 dark:text-gray-400 mt-1">Diagnostics for the Sound Level Meter Manager (SLMM) backend.</p>
|
||||
</div>
|
||||
<button onclick="loadSlmmOverview()"
|
||||
class="px-4 py-2 bg-seismo-orange hover:bg-orange-600 text-white text-sm font-medium rounded-lg">
|
||||
<span id="refresh-label">↻ Refresh</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Health Banner -->
|
||||
<div id="health-banner" class="rounded-xl p-4 mb-6 bg-gray-100 dark:bg-slate-800 border border-gray-200 dark:border-gray-700">
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400">Loading SLMM status…</p>
|
||||
</div>
|
||||
|
||||
<!-- Connection Info -->
|
||||
<div class="rounded-xl bg-white dark:bg-slate-800 shadow-lg p-4 mb-6">
|
||||
<h2 class="text-sm font-semibold text-gray-700 dark:text-gray-300 uppercase tracking-wider mb-2">Connection</h2>
|
||||
<div class="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm">
|
||||
<div>
|
||||
<span class="text-gray-500 dark:text-gray-400">terra-view → SLMM URL</span>
|
||||
<div class="font-mono text-gray-900 dark:text-white mt-0.5">{{ slmm_base_url }}</div>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-gray-500 dark:text-gray-400">Last checked</span>
|
||||
<div class="font-mono text-gray-900 dark:text-white mt-0.5" id="checked-at">—</div>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-gray-500 dark:text-gray-400">Version</span>
|
||||
<div class="font-mono text-gray-900 dark:text-white mt-0.5" id="slmm-version">—</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-3 text-xs text-gray-500 dark:text-gray-400">
|
||||
For per-device SLM control, see the <a href="/sound-level-meters" class="text-seismo-orange hover:text-seismo-burgundy underline">Sound Level Meters dashboard</a>.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Raw API tester -->
|
||||
<div class="rounded-xl bg-white dark:bg-slate-800 shadow-lg p-4 mb-6">
|
||||
<h2 class="text-sm font-semibold text-gray-700 dark:text-gray-300 uppercase tracking-wider mb-3">Raw API Tester</h2>
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mb-3">Send a GET request to any SLMM endpoint via the terra-view <code class="font-mono">/api/slmm/*</code> proxy.</p>
|
||||
<div class="flex gap-2 mb-3">
|
||||
<span class="px-3 py-2 text-sm bg-gray-100 dark:bg-slate-700 text-gray-700 dark:text-gray-300 font-mono rounded-l-lg">/api/slmm/</span>
|
||||
<input id="raw-path" type="text" placeholder="health" value="health"
|
||||
class="flex-1 px-3 py-2 text-sm bg-white dark:bg-slate-900 text-gray-900 dark:text-white border border-gray-300 dark:border-gray-600 rounded font-mono"
|
||||
onkeydown="if(event.key==='Enter') sendRaw();">
|
||||
<button onclick="sendRaw()"
|
||||
class="px-4 py-2 bg-seismo-orange hover:bg-orange-600 text-white text-sm rounded-lg">
|
||||
GET
|
||||
</button>
|
||||
</div>
|
||||
<pre id="raw-response" class="bg-gray-900 dark:bg-black text-gray-200 font-mono text-xs p-3 rounded-lg max-h-96 overflow-auto whitespace-pre hidden"></pre>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function _esc(s) {
|
||||
if (s == null) return '';
|
||||
return String(s).replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"');
|
||||
}
|
||||
|
||||
async function loadSlmmOverview() {
|
||||
const lbl = document.getElementById('refresh-label');
|
||||
lbl.textContent = '↻ Loading…';
|
||||
try {
|
||||
const r = await fetch('/api/admin/slmm/overview');
|
||||
if (!r.ok) throw new Error('HTTP ' + r.status);
|
||||
const d = await r.json();
|
||||
|
||||
document.getElementById('checked-at').textContent = d.checked_at ? d.checked_at.slice(0, 19).replace('T', ' ') : '—';
|
||||
document.getElementById('slmm-version').textContent = d.health?.version || '—';
|
||||
|
||||
const banner = document.getElementById('health-banner');
|
||||
if (d.reachable) {
|
||||
banner.className = 'rounded-xl p-4 mb-6 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800';
|
||||
banner.innerHTML = `
|
||||
<div class="flex items-center gap-3">
|
||||
<span class="w-3 h-3 rounded-full bg-green-500"></span>
|
||||
<div>
|
||||
<div class="font-semibold text-green-800 dark:text-green-300">SLMM reachable</div>
|
||||
<div class="text-xs text-green-700 dark:text-green-400">${_esc(d.health?.service || 'slmm')}</div>
|
||||
</div>
|
||||
</div>`;
|
||||
} else {
|
||||
const errs = Object.entries(d.errors || {}).map(([k, v]) => `${k}: ${v}`).join('; ');
|
||||
banner.className = 'rounded-xl p-4 mb-6 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800';
|
||||
banner.innerHTML = `
|
||||
<div class="flex items-center gap-3">
|
||||
<span class="w-3 h-3 rounded-full bg-red-500"></span>
|
||||
<div>
|
||||
<div class="font-semibold text-red-800 dark:text-red-300">SLMM unreachable</div>
|
||||
<div class="text-xs text-red-700 dark:text-red-400">${_esc(errs || 'no details')}</div>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
} catch (e) {
|
||||
document.getElementById('health-banner').innerHTML = `
|
||||
<div class="text-red-600 dark:text-red-400 text-sm font-medium">
|
||||
Failed to load SLMM overview: ${_esc(e.message)}
|
||||
</div>`;
|
||||
} finally {
|
||||
lbl.textContent = '↻ Refresh';
|
||||
}
|
||||
}
|
||||
|
||||
async function sendRaw() {
|
||||
const path = document.getElementById('raw-path').value.trim().replace(/^\//, '');
|
||||
if (!path) return;
|
||||
const pre = document.getElementById('raw-response');
|
||||
pre.classList.remove('hidden');
|
||||
pre.textContent = 'Loading…';
|
||||
try {
|
||||
const r = await fetch('/api/slmm/' + path);
|
||||
const text = await r.text();
|
||||
try {
|
||||
const j = JSON.parse(text);
|
||||
pre.textContent = `HTTP ${r.status}\n\n${JSON.stringify(j, null, 2)}`;
|
||||
} catch {
|
||||
pre.textContent = `HTTP ${r.status}\n\n${text.slice(0, 8000)}`;
|
||||
}
|
||||
} catch (e) {
|
||||
pre.textContent = 'Error: ' + e.message;
|
||||
}
|
||||
}
|
||||
|
||||
loadSlmmOverview();
|
||||
setInterval(loadSlmmOverview, 30000);
|
||||
</script>
|
||||
{% endblock %}
|
||||
+40
-35
@@ -109,47 +109,24 @@
|
||||
Dashboard
|
||||
</a>
|
||||
|
||||
<a href="/roster" class="flex items-center px-4 py-3 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 {% if request.url.path == '/roster' %}bg-gray-100 dark:bg-gray-700{% endif %}">
|
||||
{# Devices — single sidebar entry covering all device-type
|
||||
pages. Lands on /roster (the unified all-devices view);
|
||||
the tab strip on each underlying page lets the operator
|
||||
drill into seismograph / SLM / modem specifics.
|
||||
Active when on any /seismographs, /sound-level-meters,
|
||||
/modems, /roster, /pair-devices, /unit/* page. #}
|
||||
{% set _is_devices = (
|
||||
request.url.path in ('/seismographs', '/sound-level-meters', '/modems', '/roster', '/pair-devices')
|
||||
or request.url.path.startswith('/unit/')
|
||||
or request.url.path.startswith('/slm/')
|
||||
) %}
|
||||
<a href="/roster" class="flex items-center px-4 py-3 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 {% if _is_devices %}bg-gray-100 dark:bg-gray-700{% endif %}">
|
||||
<svg class="w-5 h-5 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path>
|
||||
</svg>
|
||||
Devices
|
||||
</a>
|
||||
|
||||
<a href="/seismographs" class="flex items-center px-4 py-3 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 {% if request.url.path == '/seismographs' %}bg-gray-100 dark:bg-gray-700{% endif %}">
|
||||
<svg class="w-5 h-5 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"></path>
|
||||
</svg>
|
||||
Seismographs
|
||||
</a>
|
||||
<a href="/sfm" class="flex items-center px-4 py-3 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 {% if request.url.path == '/sfm' %}bg-gray-100 dark:bg-gray-700{% endif %}">
|
||||
<svg class="w-5 h-5 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path>
|
||||
</svg>
|
||||
SFM Events
|
||||
</a>
|
||||
|
||||
<a href="/sound-level-meters" class="flex items-center px-4 py-3 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 {% if request.url.path == '/sound-level-meters' %}bg-gray-100 dark:bg-gray-700{% endif %}">
|
||||
<svg class="w-5 h-5 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"></path>
|
||||
</svg>
|
||||
Sound Level Meters
|
||||
</a>
|
||||
|
||||
<a href="/modems" class="flex items-center px-4 py-3 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 {% if request.url.path == '/modems' %}bg-gray-100 dark:bg-gray-700{% endif %}">
|
||||
<svg class="w-5 h-5 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.111 16.404a5.5 5.5 0 017.778 0M12 20h.01m-7.08-7.071c3.904-3.905 10.236-3.905 14.141 0M1.394 9.393c5.857-5.857 15.355-5.857 21.213 0"></path>
|
||||
</svg>
|
||||
Modems
|
||||
</a>
|
||||
|
||||
<a href="/pair-devices" class="flex items-center px-4 py-3 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 {% if request.url.path == '/pair-devices' %}bg-gray-100 dark:bg-gray-700{% endif %}">
|
||||
<svg class="w-5 h-5 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"></path>
|
||||
</svg>
|
||||
Pair Devices
|
||||
</a>
|
||||
|
||||
<a href="/projects" class="flex items-center px-4 py-3 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 {% if request.url.path.startswith('/projects') %}bg-gray-100 dark:bg-gray-700{% endif %}">
|
||||
<svg class="w-5 h-5 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"></path>
|
||||
@@ -157,6 +134,34 @@
|
||||
Projects
|
||||
</a>
|
||||
|
||||
{# Events — fleet-wide event database (SFM). Cross-project
|
||||
sortable/filterable event list. Day-to-day event browsing
|
||||
for a specific location or unit lives on those detail
|
||||
pages; this is the firehose for cross-cutting queries. #}
|
||||
<a href="/sfm" class="flex items-center px-4 py-3 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 {% if request.url.path == '/sfm' %}bg-gray-100 dark:bg-gray-700{% endif %}">
|
||||
<svg class="w-5 h-5 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path>
|
||||
</svg>
|
||||
Events
|
||||
</a>
|
||||
|
||||
{# Tools — operator workflow hub. Active when on /tools
|
||||
itself or any of the workflow pages it links into
|
||||
(project tidy, metadata backfill, pair devices). #}
|
||||
{% set _is_tools = (
|
||||
request.url.path == '/tools'
|
||||
or request.url.path == '/pair-devices'
|
||||
or request.url.path == '/settings/developer/project-tidy'
|
||||
or request.url.path == '/settings/developer/metadata-backfill'
|
||||
) %}
|
||||
<a href="/tools" class="flex items-center px-4 py-3 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 {% if _is_tools %}bg-gray-100 dark:bg-gray-700{% endif %}">
|
||||
<svg class="w-5 h-5 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"/>
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
|
||||
</svg>
|
||||
Tools
|
||||
</a>
|
||||
|
||||
<a href="/fleet-calendar" class="flex items-center px-4 py-3 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 {% if request.url.path.startswith('/fleet-calendar') %}bg-gray-100 dark:bg-gray-700{% endif %}">
|
||||
<svg class="w-5 h-5 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
|
||||
|
||||
+209
-137
@@ -29,7 +29,55 @@
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
|
||||
|
||||
<!-- Fleet Summary Card -->
|
||||
<!-- Recent Alerts Card (col 1) -->
|
||||
<div class="rounded-xl shadow-lg bg-white dark:bg-slate-700 p-6" id="recent-alerts-card">
|
||||
<div class="flex items-center justify-between mb-4 cursor-pointer md:cursor-default" onclick="toggleCard('recent-alerts')">
|
||||
<h2 class="text-lg font-semibold text-gray-900 dark:text-white">Recent Alerts</h2>
|
||||
<div class="flex items-center gap-2">
|
||||
<svg class="w-6 h-6 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
||||
d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z">
|
||||
</path>
|
||||
</svg>
|
||||
<svg class="w-5 h-5 text-gray-500 transition-transform md:hidden chevron" id="recent-alerts-chevron" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<div id="alerts-list" class="space-y-3 card-content" id-content="recent-alerts-content">
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400">Loading alerts...</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Recent Call-Ins Card (cols 2-3, double-wide) -->
|
||||
<div class="rounded-xl shadow-lg bg-white dark:bg-slate-700 p-6 md:col-span-2 lg:col-span-2" id="recent-callins-card">
|
||||
<div class="flex items-center justify-between mb-4 cursor-pointer md:cursor-default" onclick="toggleCard('recent-callins')">
|
||||
<div class="flex items-center gap-2">
|
||||
<h2 class="text-lg font-semibold text-gray-900 dark:text-white">Recent Call-Ins</h2>
|
||||
<span class="text-xs text-gray-500 dark:text-gray-400 hidden sm:inline">from SFM event forwards</span>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<svg class="w-6 h-6 text-seismo-burgundy" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
||||
d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z">
|
||||
</path>
|
||||
</svg>
|
||||
<svg class="w-5 h-5 text-gray-500 transition-transform md:hidden chevron" id="recent-callins-chevron" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-content" id="recent-callins-content">
|
||||
<div id="recent-callins-list" class="space-y-2">
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400">Loading recent call-ins...</p>
|
||||
</div>
|
||||
<a href="/sfm" class="block mt-3 text-center text-sm text-seismo-orange hover:text-seismo-burgundy font-medium">
|
||||
View all events →
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Fleet Summary Card (col 4) -->
|
||||
<div class="rounded-xl shadow-lg bg-white dark:bg-slate-700 p-6" id="fleet-summary-card">
|
||||
<div class="flex items-center justify-between mb-4 cursor-pointer md:cursor-default" onclick="toggleCard('fleet-summary')">
|
||||
<h2 class="text-lg font-semibold text-gray-900 dark:text-white">Fleet Summary</h2>
|
||||
@@ -121,74 +169,6 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Recent Alerts Card -->
|
||||
<div class="rounded-xl shadow-lg bg-white dark:bg-slate-700 p-6" id="recent-alerts-card">
|
||||
<div class="flex items-center justify-between mb-4 cursor-pointer md:cursor-default" onclick="toggleCard('recent-alerts')">
|
||||
<h2 class="text-lg font-semibold text-gray-900 dark:text-white">Recent Alerts</h2>
|
||||
<div class="flex items-center gap-2">
|
||||
<svg class="w-6 h-6 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
||||
d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z">
|
||||
</path>
|
||||
</svg>
|
||||
<svg class="w-5 h-5 text-gray-500 transition-transform md:hidden chevron" id="recent-alerts-chevron" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<div id="alerts-list" class="space-y-3 card-content" id-content="recent-alerts-content">
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400">Loading alerts...</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Recently Called In Units Card -->
|
||||
<div class="rounded-xl shadow-lg bg-white dark:bg-slate-700 p-6" id="recent-callins-card">
|
||||
<div class="flex items-center justify-between mb-4 cursor-pointer md:cursor-default" onclick="toggleCard('recent-callins')">
|
||||
<h2 class="text-lg font-semibold text-gray-900 dark:text-white">Recent Call-Ins</h2>
|
||||
<div class="flex items-center gap-2">
|
||||
<svg class="w-6 h-6 text-seismo-burgundy" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
||||
d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z">
|
||||
</path>
|
||||
</svg>
|
||||
<svg class="w-5 h-5 text-gray-500 transition-transform md:hidden chevron" id="recent-callins-chevron" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-content" id="recent-callins-content">
|
||||
<div id="recent-callins-list" class="space-y-2">
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400">Loading recent call-ins...</p>
|
||||
</div>
|
||||
<button id="show-all-callins" class="hidden mt-3 w-full text-center text-sm text-seismo-orange hover:text-seismo-burgundy font-medium">
|
||||
Show all recent call-ins
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Today's Scheduled Actions Card -->
|
||||
<div class="rounded-xl shadow-lg bg-white dark:bg-slate-700 p-6" id="todays-actions-card">
|
||||
<div class="flex items-center justify-between mb-4 cursor-pointer md:cursor-default" onclick="toggleCard('todays-actions')">
|
||||
<h2 class="text-lg font-semibold text-gray-900 dark:text-white">Today's Schedule</h2>
|
||||
<div class="flex items-center gap-2">
|
||||
<svg class="w-6 h-6 text-seismo-orange" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
||||
d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z">
|
||||
</path>
|
||||
</svg>
|
||||
<svg class="w-5 h-5 text-gray-500 transition-transform md:hidden chevron" id="todays-actions-chevron" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-content" id="todays-actions-content"
|
||||
hx-get="/dashboard/todays-actions"
|
||||
hx-trigger="load, every 30s"
|
||||
hx-swap="innerHTML">
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400">Loading scheduled actions...</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<!-- Dashboard Filters -->
|
||||
@@ -269,6 +249,36 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Today's Schedule — horizontal collapsible card.
|
||||
Default collapsed; auto-expands when an upcoming action is detected
|
||||
(pending + scheduled within the next 4h). JS reads
|
||||
data-has-upcoming on the inner partial after htmx swap. -->
|
||||
<div class="rounded-xl shadow-lg bg-white dark:bg-slate-700 p-4 mb-8" id="todays-actions-card">
|
||||
<div class="flex items-center justify-between cursor-pointer" onclick="toggleTodaysSchedule()">
|
||||
<div class="flex items-center gap-3">
|
||||
<svg class="w-5 h-5 text-seismo-orange" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
||||
d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
|
||||
</svg>
|
||||
<h2 class="text-base font-semibold text-gray-900 dark:text-white">Today's Schedule</h2>
|
||||
<span id="todays-actions-badge"
|
||||
class="hidden text-xs font-medium px-2 py-0.5 rounded-full bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-200">
|
||||
</span>
|
||||
</div>
|
||||
<svg class="w-5 h-5 text-gray-500 transition-transform collapsed" id="todays-actions-chevron"
|
||||
fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
|
||||
</svg>
|
||||
</div>
|
||||
<div class="card-content collapsed mt-4" id="todays-actions-content"
|
||||
hx-get="/dashboard/todays-actions"
|
||||
hx-trigger="load, every 30s"
|
||||
hx-swap="innerHTML"
|
||||
hx-on::after-swap="onTodaysActionsSwap(this)">
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400">Loading scheduled actions...</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Recent Photos Section -->
|
||||
<div class="rounded-xl shadow-lg bg-white dark:bg-slate-700 p-6 mb-8" id="recent-photos-card">
|
||||
<div class="flex items-center justify-between mb-4 cursor-pointer md:cursor-default" onclick="toggleCard('recent-photos')">
|
||||
@@ -364,6 +374,17 @@
|
||||
transform: rotate(-90deg);
|
||||
}
|
||||
}
|
||||
|
||||
/* Today's Schedule — horizontal collapsible at all breakpoints. */
|
||||
#todays-actions-content.collapsed {
|
||||
display: none;
|
||||
}
|
||||
#todays-actions-chevron.collapsed {
|
||||
transform: rotate(-90deg);
|
||||
}
|
||||
#todays-actions-chevron {
|
||||
transition: transform 0.2s ease-in-out;
|
||||
}
|
||||
</style>
|
||||
|
||||
|
||||
@@ -654,7 +675,8 @@ function toggleCard(cardName) {
|
||||
// Restore card states from localStorage on page load
|
||||
function restoreCardStates() {
|
||||
const cardStates = JSON.parse(localStorage.getItem('dashboardCardStates') || '{}');
|
||||
const cardNames = ['fleet-summary', 'recent-alerts', 'recent-callins', 'todays-actions', 'fleet-map', 'fleet-status'];
|
||||
// Note: todays-actions has its own collapse handling (see toggleTodaysSchedule / onTodaysActionsSwap)
|
||||
const cardNames = ['fleet-summary', 'recent-alerts', 'recent-callins', 'fleet-map', 'fleet-status'];
|
||||
|
||||
cardNames.forEach(cardName => {
|
||||
const content = document.getElementById(`${cardName}-content`);
|
||||
@@ -839,89 +861,139 @@ async function loadRecentPhotos() {
|
||||
loadRecentPhotos();
|
||||
setInterval(loadRecentPhotos, 30000);
|
||||
|
||||
// Load and display recent call-ins
|
||||
let showingAllCallins = false;
|
||||
const DEFAULT_CALLINS_DISPLAY = 5;
|
||||
|
||||
// Load and display recent call-ins.
|
||||
// Source: SFM events (forwarded by series3-watcher from Blastware ACH).
|
||||
// Each event = one call-home. Heartbeat-derived endpoint /api/recent-callins
|
||||
// is being phased out but kept as a backup.
|
||||
async function loadRecentCallins() {
|
||||
const callinsList = document.getElementById('recent-callins-list');
|
||||
try {
|
||||
const response = await fetch('/api/recent-callins?hours=6');
|
||||
const response = await fetch('/api/recent-event-callins?limit=10');
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to load recent call-ins');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
const callinsList = document.getElementById('recent-callins-list');
|
||||
const showAllButton = document.getElementById('show-all-callins');
|
||||
|
||||
if (data.call_ins && data.call_ins.length > 0) {
|
||||
// Determine how many to show
|
||||
const displayCount = showingAllCallins ? data.call_ins.length : Math.min(DEFAULT_CALLINS_DISPLAY, data.call_ins.length);
|
||||
const callinsToDisplay = data.call_ins.slice(0, displayCount);
|
||||
|
||||
// Build HTML for call-ins list
|
||||
let html = '';
|
||||
callinsToDisplay.forEach(callin => {
|
||||
// Status color
|
||||
const statusColor = callin.status === 'OK' ? 'green' : callin.status === 'Pending' ? 'yellow' : 'red';
|
||||
const statusClass = callin.status === 'OK' ? 'bg-green-500' : callin.status === 'Pending' ? 'bg-yellow-500' : 'bg-red-500';
|
||||
|
||||
// Build location/note line
|
||||
let subtitle = '';
|
||||
if (callin.location) {
|
||||
subtitle = callin.location;
|
||||
} else if (callin.note) {
|
||||
subtitle = callin.note;
|
||||
}
|
||||
|
||||
html += `
|
||||
<div class="flex items-center justify-between py-2 border-b border-gray-200 dark:border-gray-700 last:border-0">
|
||||
<div class="flex items-center space-x-3">
|
||||
<span class="w-2 h-2 rounded-full ${statusClass}"></span>
|
||||
<div>
|
||||
<a href="/unit/${callin.unit_id}" class="font-medium text-gray-900 dark:text-white hover:text-seismo-orange">
|
||||
${callin.unit_id}
|
||||
</a>
|
||||
${subtitle ? `<p class="text-xs text-gray-500 dark:text-gray-400">${subtitle}</p>` : ''}
|
||||
</div>
|
||||
</div>
|
||||
<span class="text-sm text-gray-600 dark:text-gray-400">${callin.time_ago}</span>
|
||||
</div>`;
|
||||
});
|
||||
|
||||
callinsList.innerHTML = html;
|
||||
|
||||
// Show/hide the "Show all" button
|
||||
if (data.call_ins.length > DEFAULT_CALLINS_DISPLAY) {
|
||||
showAllButton.classList.remove('hidden');
|
||||
showAllButton.textContent = showingAllCallins
|
||||
? `Show fewer (${DEFAULT_CALLINS_DISPLAY})`
|
||||
: `Show all (${data.call_ins.length})`;
|
||||
} else {
|
||||
showAllButton.classList.add('hidden');
|
||||
}
|
||||
} else {
|
||||
callinsList.innerHTML = '<p class="text-sm text-gray-500 dark:text-gray-400">No units have called in within the past 6 hours</p>';
|
||||
showAllButton.classList.add('hidden');
|
||||
if (!data.call_ins || data.call_ins.length === 0) {
|
||||
callinsList.innerHTML = '<p class="text-sm text-gray-500 dark:text-gray-400">No recent event call-ins from SFM</p>';
|
||||
return;
|
||||
}
|
||||
|
||||
// Two-column dense grid on lg+, single column below.
|
||||
let html = '<div class="grid grid-cols-1 lg:grid-cols-2 gap-x-4 gap-y-1">';
|
||||
data.call_ins.forEach(c => {
|
||||
const isFalse = c.false_trigger;
|
||||
const pvs = c.peak_vector_sum;
|
||||
const pvsStr = (pvs !== null && pvs !== undefined)
|
||||
? Number(pvs).toFixed(3) + ' in/s'
|
||||
: '—';
|
||||
|
||||
// Subtitle: prefer sensor_location, fallback to project.
|
||||
const subtitle = c.sensor_location || c.project || '';
|
||||
|
||||
// Status dot: amber for false trigger, green for real event,
|
||||
// gray if unit not in roster.
|
||||
const dotClass = !c.in_roster
|
||||
? 'bg-gray-400'
|
||||
: (isFalse ? 'bg-amber-400' : 'bg-green-500');
|
||||
|
||||
// Format event timestamp short (e.g. "05-13 05:00").
|
||||
let tsShort = '';
|
||||
if (c.event_timestamp) {
|
||||
const ts = c.event_timestamp.replace('T', ' ');
|
||||
// "2026-05-13 05:00:13" → "05-13 05:00"
|
||||
tsShort = ts.length >= 16 ? ts.slice(5, 16) : ts;
|
||||
}
|
||||
|
||||
const unitLink = c.in_roster
|
||||
? `<a href="/unit/${c.unit_id}" class="font-medium text-gray-900 dark:text-white hover:text-seismo-orange">${c.unit_id}</a>`
|
||||
: `<span class="font-medium text-gray-500 dark:text-gray-400" title="Not in roster">${c.unit_id}</span>`;
|
||||
|
||||
html += `
|
||||
<div class="flex items-center justify-between py-1.5 border-b border-gray-100 dark:border-gray-700/50 last:border-0">
|
||||
<div class="flex items-center gap-2 min-w-0 flex-1">
|
||||
<span class="w-2 h-2 rounded-full ${dotClass} flex-shrink-0" title="${isFalse ? 'False trigger' : 'Event'}"></span>
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex items-center gap-2">
|
||||
${unitLink}
|
||||
${isFalse ? '<span class="text-[10px] uppercase tracking-wide text-amber-600 dark:text-amber-400">false</span>' : ''}
|
||||
<span class="text-xs text-gray-500 dark:text-gray-400">${pvsStr}</span>
|
||||
</div>
|
||||
${subtitle ? `<p class="text-xs text-gray-500 dark:text-gray-400 truncate" title="${subtitle.replace(/"/g, '"')}">${subtitle}</p>` : ''}
|
||||
</div>
|
||||
</div>
|
||||
<div class="text-right ml-2 flex-shrink-0">
|
||||
<span class="text-xs text-gray-600 dark:text-gray-400 block">${c.time_ago}</span>
|
||||
${tsShort ? `<span class="text-[10px] text-gray-400 dark:text-gray-500 block font-mono">${tsShort}</span>` : ''}
|
||||
</div>
|
||||
</div>`;
|
||||
});
|
||||
html += '</div>';
|
||||
callinsList.innerHTML = html;
|
||||
} catch (error) {
|
||||
console.error('Error loading recent call-ins:', error);
|
||||
document.getElementById('recent-callins-list').innerHTML = '<p class="text-sm text-red-500">Failed to load recent call-ins</p>';
|
||||
callinsList.innerHTML = '<p class="text-sm text-red-500">Failed to load recent call-ins</p>';
|
||||
}
|
||||
}
|
||||
|
||||
// Toggle show all/show fewer
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const showAllButton = document.getElementById('show-all-callins');
|
||||
showAllButton.addEventListener('click', function() {
|
||||
showingAllCallins = !showingAllCallins;
|
||||
loadRecentCallins();
|
||||
});
|
||||
});
|
||||
|
||||
// Load recent call-ins on page load and refresh every 30 seconds
|
||||
// Load recent call-ins on page load and refresh every 30 seconds.
|
||||
loadRecentCallins();
|
||||
setInterval(loadRecentCallins, 30000);
|
||||
|
||||
// ===== Today's Schedule horizontal card =====
|
||||
function toggleTodaysSchedule() {
|
||||
const content = document.getElementById('todays-actions-content');
|
||||
const chevron = document.getElementById('todays-actions-chevron');
|
||||
if (!content || !chevron) return;
|
||||
const isCollapsed = content.classList.toggle('collapsed');
|
||||
chevron.classList.toggle('collapsed', isCollapsed);
|
||||
// Remember the user's explicit choice so we don't fight them on the next
|
||||
// 30s htmx refresh.
|
||||
localStorage.setItem('todaysScheduleUserToggled', '1');
|
||||
localStorage.setItem('todaysScheduleCollapsed', isCollapsed ? '1' : '0');
|
||||
}
|
||||
|
||||
function onTodaysActionsSwap(el) {
|
||||
// Read pending/total counts from the rendered partial to drive
|
||||
// auto-expand + the header badge.
|
||||
const badge = document.getElementById('todays-actions-badge');
|
||||
const content = document.getElementById('todays-actions-content');
|
||||
const chevron = document.getElementById('todays-actions-chevron');
|
||||
if (!content || !chevron) return;
|
||||
|
||||
// Count yellow status indicators in the rendered partial as a proxy for
|
||||
// "pending action present today".
|
||||
const pendingDots = el.querySelectorAll('.bg-yellow-400').length;
|
||||
const pendingTimes = el.querySelectorAll('.text-yellow-600').length;
|
||||
const hasPending = pendingDots > 0 || pendingTimes > 0;
|
||||
|
||||
if (badge) {
|
||||
if (hasPending) {
|
||||
const n = Math.max(pendingDots, pendingTimes);
|
||||
badge.textContent = `${n} pending today`;
|
||||
badge.classList.remove('hidden');
|
||||
} else {
|
||||
badge.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-expand only if the user hasn't manually toggled this session AND
|
||||
// there's something pending. Once the user collapses/expands manually,
|
||||
// their preference sticks.
|
||||
const userToggled = localStorage.getItem('todaysScheduleUserToggled') === '1';
|
||||
if (!userToggled && hasPending) {
|
||||
content.classList.remove('collapsed');
|
||||
chevron.classList.remove('collapsed');
|
||||
} else if (!userToggled && !hasPending) {
|
||||
content.classList.add('collapsed');
|
||||
chevron.classList.add('collapsed');
|
||||
} else if (userToggled) {
|
||||
const stored = localStorage.getItem('todaysScheduleCollapsed') === '1';
|
||||
content.classList.toggle('collapsed', stored);
|
||||
chevron.classList.toggle('collapsed', stored);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
{% endblock %}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
{% block title %}Field Modems - Terra-View{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
{% include "partials/fleet_tab_strip.html" %}
|
||||
<div class="mb-8">
|
||||
<h1 class="text-3xl font-bold text-gray-900 dark:text-white flex items-center">
|
||||
<svg class="w-8 h-8 mr-3 text-seismo-orange" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
|
||||
@@ -36,7 +36,14 @@
|
||||
</div>
|
||||
|
||||
<!-- Age -->
|
||||
<div class="text-right flex-shrink-0">
|
||||
<div class="text-right flex-shrink-0 flex items-center gap-2">
|
||||
{% if unit.last_seen_source == 'sfm' %}
|
||||
<span class="text-[10px] uppercase tracking-wider px-1.5 py-0.5 rounded bg-seismo-orange/10 text-seismo-orange font-semibold"
|
||||
title="Status sourced from SFM event forwards (primary)">SFM</span>
|
||||
{% elif unit.last_seen_source == 'heartbeat' %}
|
||||
<span class="text-[10px] uppercase tracking-wider px-1.5 py-0.5 rounded bg-gray-100 dark:bg-gray-600 text-gray-500 dark:text-gray-300"
|
||||
title="Status sourced from watcher heartbeat (backup)">HB</span>
|
||||
{% endif %}
|
||||
<span class="text-sm {% if unit.status == 'Missing' %}text-red-600 dark:text-red-400 font-semibold{% elif unit.status == 'Pending' %}text-yellow-600 dark:text-yellow-400{% else %}text-gray-500 dark:text-gray-400{% endif %}">
|
||||
{{ unit.age }}
|
||||
</span>
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
{# Fleet tab strip.
|
||||
|
||||
Shared header for every page under the "Fleet" sidebar section. Each
|
||||
underlying page (/roster, /seismographs, /sound-level-meters, /modems)
|
||||
keeps its own custom layout — this partial just provides the tab
|
||||
navigation across the top so they feel like one logical area.
|
||||
|
||||
The active tab is detected from request.url.path so deep links work.
|
||||
|
||||
Usage at top of any Fleet-section template:
|
||||
{% include 'partials/fleet_tab_strip.html' %}
|
||||
#}
|
||||
{% set _path = request.url.path %}
|
||||
<div class="mb-6 border-b border-gray-200 dark:border-gray-700">
|
||||
<div class="flex items-end justify-between flex-wrap gap-3 mb-0">
|
||||
<nav class="flex gap-1">
|
||||
<a href="/roster"
|
||||
class="px-4 py-2 -mb-px border-b-2 text-sm font-medium transition-colors {% if _path == '/roster' %}border-seismo-orange text-seismo-orange{% else %}border-transparent text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:border-gray-300 dark:hover:border-gray-600{% endif %}">
|
||||
<svg class="w-4 h-4 inline -mt-0.5 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 10h16M4 14h16M4 18h16"/>
|
||||
</svg>
|
||||
All Devices
|
||||
</a>
|
||||
<a href="/seismographs"
|
||||
class="px-4 py-2 -mb-px border-b-2 text-sm font-medium transition-colors {% if _path == '/seismographs' %}border-seismo-orange text-seismo-orange{% else %}border-transparent text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:border-gray-300 dark:hover:border-gray-600{% endif %}">
|
||||
<svg class="w-4 h-4 inline -mt-0.5 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M22 12h-4l-3 9L9 3l-3 9H2"/>
|
||||
</svg>
|
||||
Seismographs
|
||||
</a>
|
||||
<a href="/sound-level-meters"
|
||||
class="px-4 py-2 -mb-px border-b-2 text-sm font-medium transition-colors {% if _path == '/sound-level-meters' %}border-seismo-orange text-seismo-orange{% else %}border-transparent text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:border-gray-300 dark:hover:border-gray-600{% endif %}">
|
||||
<svg class="w-4 h-4 inline -mt-0.5 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.536 8.464a5 5 0 010 7.072M12 6v12M9 8.464a5 5 0 000 7.072"/>
|
||||
</svg>
|
||||
Sound Level Meters
|
||||
</a>
|
||||
<a href="/modems"
|
||||
class="px-4 py-2 -mb-px border-b-2 text-sm font-medium transition-colors {% if _path == '/modems' %}border-seismo-orange text-seismo-orange{% else %}border-transparent text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:border-gray-300 dark:hover:border-gray-600{% endif %}">
|
||||
<svg class="w-4 h-4 inline -mt-0.5 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.111 16.404a5.5 5.5 0 017.778 0M12 20h.01m-7.08-7.071c3.904-3.905 10.236-3.905 14.141 0M1.394 9.393c5.857-5.857 15.355-5.857 21.213 0"/>
|
||||
</svg>
|
||||
Modems
|
||||
</a>
|
||||
</nav>
|
||||
<a href="/pair-devices"
|
||||
class="mb-1 inline-flex items-center gap-1.5 px-3 py-1.5 text-sm border border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg transition-colors">
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"/>
|
||||
</svg>
|
||||
Pair Devices
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1,64 +1,302 @@
|
||||
<!-- Project Locations List -->
|
||||
{% if locations %}
|
||||
<div class="space-y-3">
|
||||
{% for item in locations %}
|
||||
<div class="border border-gray-200 dark:border-gray-700 rounded-lg p-4 hover:border-seismo-orange transition-colors">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex items-center gap-2">
|
||||
<a href="/projects/{{ project.id }}/nrl/{{ item.location.id }}"
|
||||
class="font-semibold text-gray-900 dark:text-white hover:text-seismo-orange truncate">
|
||||
{{ item.location.name }}
|
||||
</a>
|
||||
</div>
|
||||
{% if item.location.description %}
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">{{ item.location.description }}</p>
|
||||
{% endif %}
|
||||
{% if item.location.address %}
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">{{ item.location.address }}</p>
|
||||
{% endif %}
|
||||
{% if item.location.coordinates %}
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">{{ item.location.coordinates }}</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
<!-- Project Locations List — Active + Removed sections.
|
||||
|
||||
<div class="flex items-center gap-2">
|
||||
{% if item.assignment %}
|
||||
<button onclick="unassignUnit('{{ item.assignment.id }}')" class="text-xs px-3 py-1 rounded-full bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-300">
|
||||
Unassign
|
||||
</button>
|
||||
{% else %}
|
||||
<button onclick="openAssignModal('{{ item.location.id }}', '{{ item.location.location_type or 'sound' }}')" class="text-xs px-3 py-1 rounded-full bg-seismo-orange text-white hover:bg-seismo-navy">
|
||||
Assign
|
||||
</button>
|
||||
{% endif %}
|
||||
<button data-location='{{ {"id": item.location.id, "name": item.location.name, "description": item.location.description, "address": item.location.address, "coordinates": item.location.coordinates, "location_type": item.location.location_type} | tojson }}'
|
||||
onclick="openEditLocationModal(this)"
|
||||
class="text-xs px-3 py-1 rounded-full bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300">
|
||||
Edit
|
||||
</button>
|
||||
<button onclick="deleteLocation('{{ item.location.id }}')" class="text-xs px-3 py-1 rounded-full bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300">
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
Card layout:
|
||||
[drag handle] [location info] [unit pill] [⋮ menu]
|
||||
(name link, description, address, sessions/events, coords)
|
||||
|
||||
<div class="mt-3 text-xs text-gray-500 dark:text-gray-400 flex flex-wrap gap-4">
|
||||
<span>Sessions: {{ item.session_count }}</span>
|
||||
{% if item.assignment and item.assigned_unit %}
|
||||
<span>Assigned: {{ item.assigned_unit.id }}</span>
|
||||
{% else %}
|
||||
<span>No active assignment</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% else %}
|
||||
Active cards are draggable to reorder. Drop reorders the DOM
|
||||
immediately and posts the new order to /api/projects/{p}/locations/reorder.
|
||||
|
||||
Removed cards are NOT reorderable (their order is historical) but
|
||||
show a Restore button.
|
||||
|
||||
The three-dot menu replaces the inline Unassign/Edit/Remove/Delete
|
||||
pill buttons. Click ⋮ to open; click outside closes.
|
||||
-->
|
||||
|
||||
{% if not active_locations and not removed_locations %}
|
||||
<div class="text-center py-8 text-gray-500 dark:text-gray-400">
|
||||
<svg class="w-12 h-12 mx-auto mb-3 opacity-50" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4"></path>
|
||||
</svg>
|
||||
<p>No locations added yet</p>
|
||||
</div>
|
||||
{% else %}
|
||||
|
||||
{# ─── Active locations (draggable) ─── #}
|
||||
{% if active_locations %}
|
||||
<div class="space-y-3" id="active-locations-list" data-project-id="{{ project.id }}">
|
||||
{% for item in active_locations %}
|
||||
<div class="border border-gray-200 dark:border-gray-700 rounded-lg p-4 hover:border-seismo-orange transition-colors location-card"
|
||||
draggable="true"
|
||||
data-location-id="{{ item.location.id }}"
|
||||
data-location-type="{{ item.location.location_type or 'sound' }}"
|
||||
data-location-name="{{ item.location.name | e }}"
|
||||
data-coordinates="{{ item.location.coordinates or '' }}"
|
||||
ondragstart="onLocationDragStart(event)"
|
||||
ondragover="onLocationDragOver(event)"
|
||||
ondragleave="onLocationDragLeave(event)"
|
||||
ondrop="onLocationDrop(event)"
|
||||
ondragend="onLocationDragEnd(event)">
|
||||
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<!-- Drag handle + info -->
|
||||
<div class="flex items-start gap-3 min-w-0 flex-1">
|
||||
<div class="shrink-0 pt-0.5 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 cursor-grab active:cursor-grabbing select-none"
|
||||
title="Drag to reorder">
|
||||
<svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path d="M7 4a1 1 0 110 2 1 1 0 010-2zm6 0a1 1 0 110 2 1 1 0 010-2zM7 9a1 1 0 110 2 1 1 0 010-2zm6 0a1 1 0 110 2 1 1 0 010-2zM7 14a1 1 0 110 2 1 1 0 010-2zm6 0a1 1 0 110 2 1 1 0 010-2z"/>
|
||||
</svg>
|
||||
</div>
|
||||
<div class="min-w-0 flex-1">
|
||||
<a href="/projects/{{ project.id }}/nrl/{{ item.location.id }}"
|
||||
class="font-semibold text-gray-900 dark:text-white hover:text-seismo-orange truncate">
|
||||
{{ item.location.name }}
|
||||
</a>
|
||||
{% if item.location.description %}
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">{{ item.location.description }}</p>
|
||||
{% endif %}
|
||||
{% if item.location.address %}
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">{{ item.location.address }}</p>
|
||||
{% endif %}
|
||||
{% if item.location.coordinates %}
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">{{ item.location.coordinates }}</p>
|
||||
{% endif %}
|
||||
|
||||
<div class="mt-3 text-xs text-gray-500 dark:text-gray-400 flex flex-wrap gap-4">
|
||||
{% if item.event_count is defined and item.location.location_type == 'vibration' %}
|
||||
<span><strong class="text-gray-700 dark:text-gray-300">{{ "{:,}".format(item.event_count) }}</strong> event{{ '' if item.event_count == 1 else 's' }}</span>
|
||||
{% else %}
|
||||
<span>Sessions: {{ item.session_count }}</span>
|
||||
{% endif %}
|
||||
{% if item.assignment and item.assigned_unit %}
|
||||
<span>Assigned: <a href="/unit/{{ item.assigned_unit.id }}" class="text-seismo-orange hover:text-seismo-navy font-mono">{{ item.assigned_unit.id }}</a></span>
|
||||
{% else %}
|
||||
<span class="italic text-gray-400 dark:text-gray-500">No active assignment</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Right column: small assign/unassign pill + 3-dot menu -->
|
||||
<div class="flex items-center gap-2 shrink-0">
|
||||
{% if not item.assignment %}
|
||||
<!-- Primary action: visible because the unassigned card
|
||||
is most likely getting clicked on right after creation -->
|
||||
<button onclick="openAssignModal('{{ item.location.id }}', '{{ item.location.location_type or 'sound' }}')"
|
||||
class="text-xs px-3 py-1 rounded-full bg-seismo-orange text-white hover:bg-seismo-navy">
|
||||
Assign
|
||||
</button>
|
||||
{% endif %}
|
||||
|
||||
<!-- Three-dot kebab menu -->
|
||||
<div class="relative inline-block location-menu-wrapper">
|
||||
<button onclick="toggleLocationMenu(event, this)"
|
||||
class="p-1.5 rounded-full text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700"
|
||||
title="More actions">
|
||||
<svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path d="M10 6a2 2 0 110-4 2 2 0 010 4zm0 6a2 2 0 110-4 2 2 0 010 4zm0 6a2 2 0 110-4 2 2 0 010 4z"/>
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<div class="location-menu hidden absolute right-0 mt-1 w-40 z-30 bg-white dark:bg-slate-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg py-1">
|
||||
{% if item.assignment %}
|
||||
<button onclick="unassignUnit('{{ item.assignment.id }}'); closeAllLocationMenus()"
|
||||
class="w-full text-left px-3 py-1.5 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700">
|
||||
Unassign
|
||||
</button>
|
||||
{% endif %}
|
||||
<button data-location='{{ {"id": item.location.id, "name": item.location.name, "description": item.location.description, "address": item.location.address, "coordinates": item.location.coordinates, "location_type": item.location.location_type} | tojson }}'
|
||||
onclick="openEditLocationModal(this); closeAllLocationMenus()"
|
||||
class="w-full text-left px-3 py-1.5 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700">
|
||||
Edit
|
||||
</button>
|
||||
<button data-loc-id="{{ item.location.id }}"
|
||||
data-loc-name="{{ item.location.name | e }}"
|
||||
onclick="openRemoveLocationModal(this.dataset.locId, this.dataset.locName); closeAllLocationMenus()"
|
||||
class="w-full text-left px-3 py-1.5 text-sm text-amber-700 dark:text-amber-300 hover:bg-amber-50 dark:hover:bg-amber-900/20"
|
||||
title="Mark as no longer monitored — preserves events">
|
||||
Remove
|
||||
</button>
|
||||
<div class="border-t border-gray-100 dark:border-gray-700 my-1"></div>
|
||||
<button onclick="deleteLocation('{{ item.location.id }}'); closeAllLocationMenus()"
|
||||
class="w-full text-left px-3 py-1.5 text-sm text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20"
|
||||
title="Permanently delete — only allowed if no history">
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
{# ─── Removed locations (collapsed by default) ─── #}
|
||||
{% if removed_locations %}
|
||||
<details class="mt-6 group" {% if not active_locations %}open{% endif %}>
|
||||
<summary class="cursor-pointer text-sm font-medium text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 select-none list-none">
|
||||
<span class="inline-flex items-center gap-2">
|
||||
<svg class="w-4 h-4 transition-transform group-open:rotate-90" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
|
||||
</svg>
|
||||
Removed locations
|
||||
<span class="text-xs px-1.5 py-0.5 rounded bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400">{{ removed_locations | length }}</span>
|
||||
</span>
|
||||
<p class="ml-6 mt-1 text-xs text-gray-400 dark:text-gray-500">Historical only — events stay attributed, but no new assignments or schedules can be created here.</p>
|
||||
</summary>
|
||||
|
||||
<div class="space-y-3 mt-3">
|
||||
{% for item in removed_locations %}
|
||||
<div class="border border-gray-200 dark:border-gray-700 rounded-lg p-4 bg-gray-50 dark:bg-slate-900/30 opacity-75">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex items-center gap-2 flex-wrap">
|
||||
<a href="/projects/{{ project.id }}/nrl/{{ item.location.id }}"
|
||||
class="font-semibold text-gray-700 dark:text-gray-300 hover:text-seismo-orange truncate">
|
||||
{{ item.location.name }}
|
||||
</a>
|
||||
<span class="text-[10px] uppercase tracking-wider px-1.5 py-0.5 rounded bg-gray-200 dark:bg-gray-700 text-gray-600 dark:text-gray-300 font-semibold">
|
||||
Removed
|
||||
</span>
|
||||
<span class="text-xs text-gray-500 dark:text-gray-400">
|
||||
{{ item.location.removed_at.strftime('%Y-%m-%d') if item.location.removed_at else '—' }}
|
||||
</span>
|
||||
</div>
|
||||
{% if item.location.removal_reason %}
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1 italic">"{{ item.location.removal_reason }}"</p>
|
||||
{% endif %}
|
||||
{% if item.location.description %}
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">{{ item.location.description }}</p>
|
||||
{% endif %}
|
||||
{% if item.location.address %}
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">{{ item.location.address }}</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-2">
|
||||
<button data-loc-id="{{ item.location.id }}"
|
||||
data-loc-name="{{ item.location.name | e }}"
|
||||
onclick="restoreLocation(this.dataset.locId, this.dataset.locName)"
|
||||
class="text-xs px-3 py-1 rounded-full bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300 hover:bg-green-200"
|
||||
title="Restore to active monitoring">
|
||||
Restore
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 text-xs text-gray-500 dark:text-gray-400 flex flex-wrap gap-4">
|
||||
{% if item.event_count is defined and item.location.location_type == 'vibration' %}
|
||||
<span>{{ "{:,}".format(item.event_count) }} historical event{{ '' if item.event_count == 1 else 's' }}</span>
|
||||
{% else %}
|
||||
<span>Historical sessions: {{ item.session_count }}</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</details>
|
||||
{% endif %}
|
||||
|
||||
{% endif %}
|
||||
|
||||
<!-- Drag-and-drop + menu handlers, scoped to this partial (re-defined
|
||||
on every htmx swap, which is harmless — function declarations
|
||||
overwrite). -->
|
||||
<script>
|
||||
let _dragSrcCard = null;
|
||||
|
||||
function onLocationDragStart(e) {
|
||||
_dragSrcCard = e.currentTarget;
|
||||
e.dataTransfer.effectAllowed = 'move';
|
||||
// Required for Firefox to start the drag.
|
||||
e.dataTransfer.setData('text/plain', _dragSrcCard.dataset.locationId);
|
||||
e.currentTarget.classList.add('opacity-40');
|
||||
}
|
||||
|
||||
function onLocationDragOver(e) {
|
||||
if (!_dragSrcCard || e.currentTarget === _dragSrcCard) return;
|
||||
e.preventDefault();
|
||||
e.dataTransfer.dropEffect = 'move';
|
||||
e.currentTarget.classList.add('ring-2', 'ring-seismo-orange');
|
||||
}
|
||||
|
||||
function onLocationDragLeave(e) {
|
||||
e.currentTarget.classList.remove('ring-2', 'ring-seismo-orange');
|
||||
}
|
||||
|
||||
function onLocationDrop(e) {
|
||||
e.preventDefault();
|
||||
e.currentTarget.classList.remove('ring-2', 'ring-seismo-orange');
|
||||
if (!_dragSrcCard || e.currentTarget === _dragSrcCard) return;
|
||||
|
||||
const list = document.getElementById('active-locations-list');
|
||||
if (!list) return;
|
||||
|
||||
// Drop AFTER the target by default; if mouse is in top half, drop BEFORE.
|
||||
const rect = e.currentTarget.getBoundingClientRect();
|
||||
const dropBefore = (e.clientY - rect.top) < rect.height / 2;
|
||||
if (dropBefore) {
|
||||
list.insertBefore(_dragSrcCard, e.currentTarget);
|
||||
} else {
|
||||
list.insertBefore(_dragSrcCard, e.currentTarget.nextSibling);
|
||||
}
|
||||
|
||||
_persistLocationOrder(list);
|
||||
}
|
||||
|
||||
function onLocationDragEnd(e) {
|
||||
e.currentTarget.classList.remove('opacity-40');
|
||||
document.querySelectorAll('.location-card').forEach(c => {
|
||||
c.classList.remove('ring-2', 'ring-seismo-orange');
|
||||
});
|
||||
_dragSrcCard = null;
|
||||
}
|
||||
|
||||
async function _persistLocationOrder(list) {
|
||||
const projectId = list.dataset.projectId;
|
||||
const ids = Array.from(list.querySelectorAll('.location-card'))
|
||||
.map(c => c.dataset.locationId);
|
||||
try {
|
||||
const r = await fetch(`/api/projects/${projectId}/locations/reorder`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ location_ids: ids }),
|
||||
});
|
||||
if (!r.ok) {
|
||||
const err = await r.json().catch(() => ({ detail: 'HTTP ' + r.status }));
|
||||
throw new Error(err.detail || 'reorder failed');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to save new order:', err);
|
||||
if (typeof showToast === 'function') showToast('Failed to save new order: ' + err.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
// ── Three-dot menu ─────────────────────────────────────────────────
|
||||
function toggleLocationMenu(e, btn) {
|
||||
e.stopPropagation();
|
||||
const menu = btn.parentElement.querySelector('.location-menu');
|
||||
const wasOpen = !menu.classList.contains('hidden');
|
||||
closeAllLocationMenus();
|
||||
if (!wasOpen) {
|
||||
menu.classList.remove('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
function closeAllLocationMenus() {
|
||||
document.querySelectorAll('.location-menu').forEach(m => m.classList.add('hidden'));
|
||||
}
|
||||
|
||||
// Close menus on outside click (only register once globally).
|
||||
if (!window._locationMenuOutsideClickRegistered) {
|
||||
document.addEventListener('click', (e) => {
|
||||
if (!e.target.closest('.location-menu-wrapper')) closeAllLocationMenus();
|
||||
});
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Escape') closeAllLocationMenus();
|
||||
});
|
||||
window._locationMenuOutsideClickRegistered = true;
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -78,22 +78,128 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="bg-white dark:bg-slate-800 rounded-xl shadow-lg p-6">
|
||||
<h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">Upcoming Actions</h3>
|
||||
{% if upcoming_actions %}
|
||||
<div class="space-y-3">
|
||||
{% for action in upcoming_actions %}
|
||||
<div class="border border-gray-200 dark:border-gray-700 rounded-lg p-3">
|
||||
<p class="font-medium text-gray-900 dark:text-white">{{ action.action_type }}</p>
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">{{ action.scheduled_time|local_datetime }} {{ timezone_abbr() }}</p>
|
||||
{% if action.description %}
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">{{ action.description }}</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% else %}
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400">No scheduled actions.</p>
|
||||
{% endif %}
|
||||
<!-- Location Map — replaces the old Upcoming Actions panel for the
|
||||
overview. Operators get a quick visual of where their locations
|
||||
sit relative to each other. Pins clickable → scroll to + flash
|
||||
the matching card. Locations without coordinates land in a
|
||||
"missing coords" hint below the map.
|
||||
For projects with scheduled monitoring activity, the full
|
||||
Upcoming Actions list is still available on the Schedules tab. -->
|
||||
<div class="bg-white dark:bg-slate-800 rounded-xl shadow-lg p-4">
|
||||
<div class="flex items-center justify-between mb-3">
|
||||
<h3 class="text-lg font-semibold text-gray-900 dark:text-white">Location Map</h3>
|
||||
{% if upcoming_actions %}
|
||||
<a href="javascript:void(0)" onclick="switchTab('schedules')"
|
||||
class="text-xs text-seismo-orange hover:text-seismo-navy whitespace-nowrap">
|
||||
{{ upcoming_actions | length }} upcoming action{{ '' if upcoming_actions | length == 1 else 's' }} →
|
||||
</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
<!-- `isolation: isolate` forces a new stacking context so Leaflet's
|
||||
internal z-indexes (panes at 200-700, controls at 800) stay
|
||||
contained inside this div instead of leaking into the root
|
||||
stacking context and rendering over modals (which have z-50). -->
|
||||
<div id="project-location-map" class="w-full rounded-lg border border-gray-200 dark:border-gray-700"
|
||||
style="height: 320px; background: rgba(0,0,0,0.05); isolation: isolate;"></div>
|
||||
<div id="project-location-map-empty" class="hidden text-xs text-gray-500 dark:text-gray-400 mt-2 italic text-center">
|
||||
No location coordinates set. Edit a location and add a <code class="font-mono">lat,lon</code> pair to see it here.
|
||||
</div>
|
||||
<div id="project-location-map-missing" class="hidden text-xs text-gray-500 dark:text-gray-400 mt-2"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
(function () {
|
||||
// Build location data from server-side render. Skip removed
|
||||
// locations (their pins would clutter the active operations view)
|
||||
// and skip ones without parseable coordinates.
|
||||
const locationsRaw = [
|
||||
{% for loc in locations %}
|
||||
{% if not loc.removed_at %}
|
||||
{
|
||||
id: {{ loc.id | tojson }},
|
||||
name: {{ loc.name | tojson }},
|
||||
coords: {{ loc.coordinates | tojson if loc.coordinates else 'null' }},
|
||||
}{% if not loop.last %},{% endif %}
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
];
|
||||
|
||||
function parseCoords(s) {
|
||||
if (!s) return null;
|
||||
const parts = String(s).split(',').map(x => parseFloat(x.trim()));
|
||||
if (parts.length !== 2 || parts.some(isNaN)) return null;
|
||||
const [lat, lon] = parts;
|
||||
if (lat < -90 || lat > 90 || lon < -180 || lon > 180) return null;
|
||||
return [lat, lon];
|
||||
}
|
||||
|
||||
const withCoords = [];
|
||||
const withoutCoords = [];
|
||||
for (const loc of locationsRaw) {
|
||||
const xy = parseCoords(loc.coords);
|
||||
if (xy) withCoords.push({ ...loc, latlon: xy });
|
||||
else withoutCoords.push(loc);
|
||||
}
|
||||
|
||||
const emptyMsg = document.getElementById('project-location-map-empty');
|
||||
const missingMsg = document.getElementById('project-location-map-missing');
|
||||
const mapEl = document.getElementById('project-location-map');
|
||||
if (!mapEl) return;
|
||||
|
||||
if (withCoords.length === 0) {
|
||||
// Hide the map block and show a hint. Don't init Leaflet at all.
|
||||
mapEl.classList.add('hidden');
|
||||
emptyMsg.classList.remove('hidden');
|
||||
return;
|
||||
}
|
||||
|
||||
// Initialise Leaflet. `L` is loaded globally by base.html.
|
||||
const map = L.map(mapEl, { scrollWheelZoom: false });
|
||||
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
|
||||
attribution: '© OpenStreetMap',
|
||||
maxZoom: 18,
|
||||
}).addTo(map);
|
||||
|
||||
const markers = [];
|
||||
const bounds = [];
|
||||
withCoords.forEach(loc => {
|
||||
const marker = L.circleMarker(loc.latlon, {
|
||||
radius: 8,
|
||||
fillColor: '#f48b1c',
|
||||
color: '#fff',
|
||||
weight: 2,
|
||||
opacity: 1,
|
||||
fillOpacity: 0.9,
|
||||
}).addTo(map);
|
||||
marker.bindTooltip(loc.name, { direction: 'top', offset: [0, -6] });
|
||||
marker.on('click', () => _flashLocationCard(loc.id));
|
||||
markers.push(marker);
|
||||
bounds.push(loc.latlon);
|
||||
});
|
||||
|
||||
if (bounds.length === 1) {
|
||||
map.setView(bounds[0], 14);
|
||||
} else {
|
||||
map.fitBounds(bounds, { padding: [20, 20] });
|
||||
}
|
||||
// Without this the map renders into a 0×0 area when the partial
|
||||
// first lands via htmx (container size not yet stable).
|
||||
setTimeout(() => map.invalidateSize(), 100);
|
||||
|
||||
if (withoutCoords.length > 0) {
|
||||
const names = withoutCoords.map(l => l.name).join(', ');
|
||||
missingMsg.textContent = `${withoutCoords.length} location${withoutCoords.length === 1 ? '' : 's'} not shown (no coordinates): ${names}`;
|
||||
missingMsg.classList.remove('hidden');
|
||||
}
|
||||
|
||||
// Briefly highlight the matching card to confirm the click.
|
||||
function _flashLocationCard(locId) {
|
||||
const card = document.querySelector(`.location-card[data-location-id="${locId}"]`);
|
||||
if (!card) return;
|
||||
card.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
card.classList.add('ring-2', 'ring-seismo-orange');
|
||||
setTimeout(() => card.classList.remove('ring-2', 'ring-seismo-orange'), 1500);
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
|
||||
@@ -87,9 +87,14 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Merge Modal -->
|
||||
<!-- Merge Modal —
|
||||
min-h on the body ensures the typeahead dropdown has room to render
|
||||
below the input without forcing the operator to scroll inside the
|
||||
modal. overflow-visible on the body lets the dropdown extend
|
||||
beyond the body's natural height when needed. -->
|
||||
<div id="merge-modal" class="hidden fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm">
|
||||
<div class="bg-white dark:bg-slate-800 rounded-xl shadow-2xl w-full max-w-2xl mx-4 max-h-[90vh] flex flex-col">
|
||||
<div class="bg-white dark:bg-slate-800 rounded-xl shadow-2xl w-full max-w-2xl mx-4 max-h-[90vh] flex flex-col"
|
||||
style="min-height: 480px;">
|
||||
<!-- Header -->
|
||||
<div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
|
||||
<div>
|
||||
@@ -104,7 +109,7 @@
|
||||
</div>
|
||||
|
||||
<!-- Body -->
|
||||
<div class="px-6 py-4 overflow-y-auto flex-1">
|
||||
<div class="px-6 py-4 overflow-y-auto flex-1 min-h-[320px]">
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||
Target project
|
||||
</label>
|
||||
@@ -202,6 +207,10 @@ async function _mergeFetchTargets() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Stash target id + name in data-* attributes (NOT inline JS args)
|
||||
// to avoid the quote-collision that breaks click binding when the
|
||||
// project name contains characters JSON.stringify quotes. Same
|
||||
// pattern as the backfill typeahead dropdown.
|
||||
dropdown.innerHTML = candidates.map(m => {
|
||||
const scoreBadge = m.score >= 0.99
|
||||
? '<span class="text-xs text-green-600 dark:text-green-400 ml-2">exact</span>'
|
||||
@@ -212,8 +221,10 @@ async function _mergeFetchTargets() {
|
||||
if (m.location_count > 0) meta.push(`${m.location_count} location${m.location_count === 1 ? '' : 's'}`);
|
||||
const metaLine = meta.length ? `<div class="text-xs text-gray-500 dark:text-gray-400">${meta.join(' · ')}</div>` : '';
|
||||
return `<button type="button"
|
||||
data-target-id="${_mergeEsc(m.id)}"
|
||||
data-target-name="${_mergeEsc(m.name)}"
|
||||
onmousedown="event.preventDefault()"
|
||||
onclick="onMergePickTarget('${_mergeEsc(m.id)}', ${JSON.stringify(m.name)})"
|
||||
onclick="_mergePickFromButton(this)"
|
||||
class="w-full text-left px-3 py-2 hover:bg-gray-50 dark:hover:bg-slate-700 border-b border-gray-100 dark:border-gray-700 last:border-b-0">
|
||||
<div class="text-sm font-medium text-gray-900 dark:text-white">${_mergeEsc(m.name)}${scoreBadge}</div>
|
||||
${metaLine}
|
||||
@@ -222,6 +233,13 @@ async function _mergeFetchTargets() {
|
||||
dropdown.classList.remove('hidden');
|
||||
}
|
||||
|
||||
// Trampoline — reads the button's data attributes and forwards. Keeps
|
||||
// the inline onclick free of any string interpolation that could break
|
||||
// HTML quoting (see notes on the same pattern in metadata_backfill.html).
|
||||
function _mergePickFromButton(btn) {
|
||||
onMergePickTarget(btn.dataset.targetId, btn.dataset.targetName);
|
||||
}
|
||||
|
||||
async function onMergePickTarget(targetId, targetName) {
|
||||
document.getElementById('merge-target-input').value = targetName;
|
||||
document.getElementById('merge-target-id').value = targetId;
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
<span class="text-2xl font-bold text-gray-900 dark:text-white mt-1">{{ "{:,}".format(summary.total_events) }}</span>
|
||||
</div>
|
||||
<div class="bg-gray-50 dark:bg-slate-900/50 rounded-lg p-3 flex flex-col">
|
||||
<span class="text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wider">Peak PVS</span>
|
||||
<span class="text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wider">Overall Peak</span>
|
||||
{% if summary.peak_pvs is not none %}
|
||||
<span class="text-2xl font-bold text-gray-900 dark:text-white mt-1">{{ "%.4f"|format(summary.peak_pvs) }} <span class="text-sm font-normal">in/s</span></span>
|
||||
<a href="/projects/{{ summary.project_id }}/nrl/{{ summary.peak_pvs_location_id }}"
|
||||
@@ -60,6 +60,10 @@
|
||||
class="flex items-center justify-between py-1.5 px-3 rounded hover:bg-gray-50 dark:hover:bg-slate-700/50 transition-colors">
|
||||
<span class="text-sm font-medium text-gray-900 dark:text-white truncate">
|
||||
📍 {{ loc.location_name }}
|
||||
{% if loc.removed_at %}
|
||||
<span class="ml-1 text-[10px] uppercase tracking-wider px-1 py-0.5 rounded bg-gray-200 dark:bg-gray-700 text-gray-600 dark:text-gray-300 font-semibold align-middle"
|
||||
title="Location no longer actively monitored — events shown are historical">removed</span>
|
||||
{% endif %}
|
||||
</span>
|
||||
<span class="flex items-center gap-4 text-sm text-gray-600 dark:text-gray-400 whitespace-nowrap ml-3">
|
||||
<span>{{ "{:,}".format(loc.event_count) }} event{{ '' if loc.event_count == 1 else 's' }}</span>
|
||||
|
||||
@@ -778,6 +778,61 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Remove Location Confirmation Modal —
|
||||
Soft-removal: preserves historical events, closes active assignments,
|
||||
cancels pending scheduled actions. Distinct from Delete (which is
|
||||
permanent and only allowed when there's no history). -->
|
||||
<div id="remove-location-modal" class="hidden fixed inset-0 bg-black bg-opacity-60 z-50 flex items-center justify-center">
|
||||
<div class="bg-white dark:bg-slate-800 rounded-xl shadow-2xl w-full max-w-md m-4 p-6">
|
||||
<div class="flex items-center gap-3 mb-4">
|
||||
<div class="p-2 bg-amber-100 dark:bg-amber-900/40 rounded-lg">
|
||||
<svg class="w-6 h-6 text-amber-600 dark:text-amber-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 17v-2a4 4 0 014-4h6m0 0l-3-3m3 3l-3 3M5 7h8a2 2 0 012 2v10a2 2 0 01-2 2H5a2 2 0 01-2-2V9a2 2 0 012-2z"/>
|
||||
</svg>
|
||||
</div>
|
||||
<h3 class="text-lg font-semibold text-gray-900 dark:text-white">Remove location</h3>
|
||||
</div>
|
||||
<p class="text-sm text-gray-600 dark:text-gray-400 mb-4">
|
||||
Mark <span id="remove-location-name" class="font-semibold text-gray-900 dark:text-white">…</span> as no longer actively monitored.
|
||||
</p>
|
||||
<ul class="text-xs text-gray-500 dark:text-gray-400 mb-4 space-y-1 ml-4 list-disc">
|
||||
<li>Closes any active unit assignment at this location</li>
|
||||
<li>Cancels pending scheduled actions at this location</li>
|
||||
<li>Historical events stay attributed (visible in reports + event lists)</li>
|
||||
<li>Can be restored later if needed</li>
|
||||
</ul>
|
||||
|
||||
<input type="hidden" id="remove-location-id">
|
||||
|
||||
<div class="mb-3">
|
||||
<label class="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">Effective date</label>
|
||||
<input type="datetime-local" id="remove-location-effective"
|
||||
class="w-full px-3 py-1.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm">
|
||||
<p class="text-[10px] text-gray-500 dark:text-gray-400 mt-1">Defaults to now. Backdate if the location was physically removed earlier.</p>
|
||||
</div>
|
||||
|
||||
<div class="mb-4">
|
||||
<label class="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">Reason (optional)</label>
|
||||
<input type="text" id="remove-location-reason" maxlength="200"
|
||||
placeholder="e.g. client dropped from scope"
|
||||
class="w-full px-3 py-1.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm">
|
||||
</div>
|
||||
|
||||
<div id="remove-location-error" class="hidden text-sm text-red-600 mb-3"></div>
|
||||
|
||||
<div class="flex justify-end gap-2">
|
||||
<button onclick="closeRemoveLocationModal()"
|
||||
class="px-4 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded-lg text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700">
|
||||
Cancel
|
||||
</button>
|
||||
<button onclick="confirmRemoveLocation()"
|
||||
class="px-4 py-1.5 text-sm bg-amber-600 hover:bg-amber-700 text-white rounded-lg font-medium">
|
||||
Remove
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Delete Project Confirmation Modal -->
|
||||
<div id="delete-project-modal" class="hidden fixed inset-0 bg-black bg-opacity-60 z-50 flex items-center justify-center">
|
||||
<div class="bg-white dark:bg-slate-800 rounded-xl shadow-2xl w-full max-w-md m-4 p-6">
|
||||
@@ -1213,6 +1268,94 @@ async function deleteLocation(locationId) {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Remove / Restore location ────────────────────────────────────────
|
||||
// Soft-removal: marks a location as no longer actively monitored without
|
||||
// destroying it. Historical events stay attributed; active assignments
|
||||
// are auto-closed and pending scheduled actions are auto-cancelled.
|
||||
|
||||
function openRemoveLocationModal(locationId, locationName) {
|
||||
document.getElementById('remove-location-id').value = locationId;
|
||||
document.getElementById('remove-location-name').textContent = locationName;
|
||||
document.getElementById('remove-location-reason').value = '';
|
||||
// Default effective_date to "now" in local datetime-input format.
|
||||
const now = new Date();
|
||||
const tzOffsetMin = now.getTimezoneOffset();
|
||||
const local = new Date(now.getTime() - tzOffsetMin * 60000);
|
||||
document.getElementById('remove-location-effective').value =
|
||||
local.toISOString().slice(0, 16);
|
||||
document.getElementById('remove-location-error').classList.add('hidden');
|
||||
document.getElementById('remove-location-modal').classList.remove('hidden');
|
||||
}
|
||||
|
||||
function closeRemoveLocationModal() {
|
||||
document.getElementById('remove-location-modal').classList.add('hidden');
|
||||
}
|
||||
|
||||
async function confirmRemoveLocation() {
|
||||
const locationId = document.getElementById('remove-location-id').value;
|
||||
const reason = document.getElementById('remove-location-reason').value.trim();
|
||||
const effective = document.getElementById('remove-location-effective').value;
|
||||
const errBox = document.getElementById('remove-location-error');
|
||||
errBox.classList.add('hidden');
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/projects/${projectId}/locations/${locationId}/remove`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
reason: reason || null,
|
||||
effective_date: effective || null,
|
||||
}),
|
||||
}
|
||||
);
|
||||
if (!response.ok) {
|
||||
const data = await response.json().catch(() => ({}));
|
||||
throw new Error(data.detail || 'Failed to remove location');
|
||||
}
|
||||
const result = await response.json();
|
||||
closeRemoveLocationModal();
|
||||
refreshLocationLists();
|
||||
refreshProjectDashboard();
|
||||
// Lightweight feedback — the UI refresh already shows the location
|
||||
// moving to the Removed section, but a toast confirms the cascade.
|
||||
if (typeof showToast === 'function') {
|
||||
const bits = [];
|
||||
if (result.assignments_closed) bits.push(`${result.assignments_closed} assignment(s) closed`);
|
||||
if (result.actions_cancelled) bits.push(`${result.actions_cancelled} action(s) cancelled`);
|
||||
const tail = bits.length ? ` (${bits.join(', ')})` : '';
|
||||
showToast(`Location removed${tail}`, 'success');
|
||||
}
|
||||
} catch (err) {
|
||||
errBox.textContent = err.message || 'Failed to remove location.';
|
||||
errBox.classList.remove('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
async function restoreLocation(locationId, locationName) {
|
||||
if (!confirm(`Restore "${locationName}" to active monitoring?\n\nNote: previously-closed assignments are NOT automatically re-opened — you'll need to re-assign units if you want to resume monitoring.`)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/projects/${projectId}/locations/${locationId}/restore`,
|
||||
{ method: 'POST' }
|
||||
);
|
||||
if (!response.ok) {
|
||||
const data = await response.json().catch(() => ({}));
|
||||
throw new Error(data.detail || 'Failed to restore location');
|
||||
}
|
||||
refreshLocationLists();
|
||||
refreshProjectDashboard();
|
||||
if (typeof showToast === 'function') {
|
||||
showToast(`"${locationName}" restored to active`, 'success');
|
||||
}
|
||||
} catch (err) {
|
||||
alert(err.message || 'Failed to restore location.');
|
||||
}
|
||||
}
|
||||
|
||||
// Assign modal functions
|
||||
function openAssignModal(locationId, locationType) {
|
||||
const safeType = locationType || 'sound';
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
{% block title %}Devices - Seismo Fleet Manager{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
{% include "partials/fleet_tab_strip.html" %}
|
||||
<div class="mb-8">
|
||||
<div class="flex justify-between items-start">
|
||||
<div>
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
{% block title %}Seismographs - Seismo Fleet Manager{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
{% include "partials/fleet_tab_strip.html" %}
|
||||
<div class="mb-8">
|
||||
<h1 class="text-3xl font-bold text-gray-900 dark:text-white">Seismographs</h1>
|
||||
<p class="text-gray-600 dark:text-gray-400 mt-1">Manage and monitor seismograph units</p>
|
||||
|
||||
+12
-8
@@ -561,33 +561,37 @@
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<!-- Metadata Backfill (Phase 5a) -->
|
||||
<!-- SFM Admin -->
|
||||
<div class="flex items-center justify-between p-4 bg-gray-50 dark:bg-slate-700 rounded-lg">
|
||||
<div>
|
||||
<div class="font-medium text-gray-900 dark:text-white">Backfill from event metadata</div>
|
||||
<div class="font-medium text-gray-900 dark:text-white">SFM Admin</div>
|
||||
<div class="text-sm text-gray-500 dark:text-gray-400 mt-0.5">
|
||||
Auto-create projects, locations, and unit assignments from the operator-typed metadata baked into SFM events. Skip the manual entry.
|
||||
Diagnose the SFM backend — health, per-unit event counts, forwarding latency, stale tables, raw API probe.
|
||||
</div>
|
||||
</div>
|
||||
<a href="/settings/developer/metadata-backfill"
|
||||
<a href="/admin/sfm"
|
||||
class="ml-6 px-4 py-2 bg-seismo-orange hover:bg-orange-600 text-white text-sm font-medium rounded-lg transition-colors whitespace-nowrap">
|
||||
Open
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<!-- Project Tidy (Phase 5b) -->
|
||||
<!-- SLMM Admin -->
|
||||
<div class="flex items-center justify-between p-4 bg-gray-50 dark:bg-slate-700 rounded-lg">
|
||||
<div>
|
||||
<div class="font-medium text-gray-900 dark:text-white">Project Tidy</div>
|
||||
<div class="font-medium text-gray-900 dark:text-white">SLMM Admin</div>
|
||||
<div class="text-sm text-gray-500 dark:text-gray-400 mt-0.5">
|
||||
Find duplicate-looking projects via fuzzy name match (typos, abbreviations, spacing variations) and bulk-merge them.
|
||||
Diagnose the SLMM backend — health check + raw API probe. For per-device control use the SLM dashboard.
|
||||
</div>
|
||||
</div>
|
||||
<a href="/settings/developer/project-tidy"
|
||||
<a href="/admin/slmm"
|
||||
class="ml-6 px-4 py-2 bg-seismo-orange hover:bg-orange-600 text-white text-sm font-medium rounded-lg transition-colors whitespace-nowrap">
|
||||
Open
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{# Metadata Backfill + Project Tidy moved to Tools (they're
|
||||
operator workflows, not admin/dev surfaces). Find them
|
||||
at /tools. #}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+61
-13
@@ -5,8 +5,8 @@
|
||||
{% block content %}
|
||||
<div class="mb-6 flex items-center justify-between">
|
||||
<div>
|
||||
<h1 class="text-3xl font-bold text-gray-900 dark:text-white">SFM Event Data</h1>
|
||||
<p class="text-gray-600 dark:text-gray-400 mt-1">Blastware ACH events forwarded by series3-watcher</p>
|
||||
<h1 class="text-3xl font-bold text-gray-900 dark:text-white">Events</h1>
|
||||
<p class="text-gray-600 dark:text-gray-400 mt-1">Fleet-wide event database. Filter by serial, date, false-trigger, or browse the units roster.</p>
|
||||
</div>
|
||||
<div class="flex items-center gap-3">
|
||||
<span id="sfm-status-badge" class="px-3 py-1 rounded-full text-sm font-medium bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400">
|
||||
@@ -220,6 +220,12 @@ async function loadStats() {
|
||||
}
|
||||
|
||||
// ── Events tab ───────────────────────────────────────────────────────────────
|
||||
// Module-level cache so sort can re-render without re-fetching.
|
||||
let _eventsCache = [];
|
||||
let _eventsTotal = 0;
|
||||
let _eventsSortKey = 'timestamp';
|
||||
let _eventsSortDir = 'desc'; // 'asc' | 'desc'
|
||||
|
||||
async function loadEvents() {
|
||||
const container = document.getElementById('events-container');
|
||||
container.innerHTML = '<div class="text-center py-8 text-gray-500"><div class="animate-spin rounded-full h-8 w-8 border-b-2 border-seismo-orange mx-auto mb-3"></div>Loading events…</div>';
|
||||
@@ -241,19 +247,61 @@ async function loadEvents() {
|
||||
const r = await fetch('/api/sfm/db/events?' + params.toString());
|
||||
if (!r.ok) { throw new Error('HTTP ' + r.status); }
|
||||
const d = await r.json();
|
||||
renderEventsTable(d.events, d.count, container);
|
||||
_eventsCache = d.events || [];
|
||||
_eventsTotal = d.count || 0;
|
||||
renderEventsTable(_eventsCache, _eventsTotal, container);
|
||||
} catch (e) {
|
||||
container.innerHTML = `<div class="text-center py-8 text-red-500">Failed to load events: ${e.message}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
function sortEvents(key) {
|
||||
// Toggle direction if same column clicked; otherwise default to desc.
|
||||
if (_eventsSortKey === key) {
|
||||
_eventsSortDir = _eventsSortDir === 'desc' ? 'asc' : 'desc';
|
||||
} else {
|
||||
_eventsSortKey = key;
|
||||
_eventsSortDir = 'desc';
|
||||
}
|
||||
renderEventsTable(_eventsCache, _eventsTotal, document.getElementById('events-container'));
|
||||
}
|
||||
|
||||
function _applySort(events) {
|
||||
const key = _eventsSortKey;
|
||||
const dir = _eventsSortDir === 'asc' ? 1 : -1;
|
||||
return [...events].sort((a, b) => {
|
||||
let av = a[key], bv = b[key];
|
||||
// Nulls always sort last regardless of dir.
|
||||
if (av == null && bv == null) return 0;
|
||||
if (av == null) return 1;
|
||||
if (bv == null) return -1;
|
||||
if (typeof av === 'number' && typeof bv === 'number') return (av - bv) * dir;
|
||||
return String(av).localeCompare(String(bv)) * dir;
|
||||
});
|
||||
}
|
||||
|
||||
function _sortIndicator(key) {
|
||||
if (_eventsSortKey !== key) return '<span class="text-gray-400 opacity-50 ml-1">↕</span>';
|
||||
return _eventsSortDir === 'desc'
|
||||
? '<span class="text-seismo-orange ml-1">↓</span>'
|
||||
: '<span class="text-seismo-orange ml-1">↑</span>';
|
||||
}
|
||||
|
||||
function _sortableTh(label, key) {
|
||||
return `<th onclick="sortEvents('${key}')"
|
||||
class="px-4 py-3 text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider cursor-pointer select-none hover:bg-gray-100 dark:hover:bg-slate-600 transition-colors">
|
||||
${label}${_sortIndicator(key)}
|
||||
</th>`;
|
||||
}
|
||||
|
||||
function renderEventsTable(events, total, container) {
|
||||
if (!events || events.length === 0) {
|
||||
container.innerHTML = '<div class="text-center py-12 text-gray-500 dark:text-gray-400"><p class="text-sm">No events found matching the current filters.</p></div>';
|
||||
return;
|
||||
}
|
||||
|
||||
const rows = events.map(ev => {
|
||||
const sorted = _applySort(events);
|
||||
const rows = sorted.map(ev => {
|
||||
const ts = ev.timestamp ? ev.timestamp.replace('T', ' ').slice(0, 19) : '—';
|
||||
const tran = fmtPPV(ev.tran_ppv);
|
||||
const vert = fmtPPV(ev.vert_ppv);
|
||||
@@ -288,15 +336,15 @@ function renderEventsTable(events, total, container) {
|
||||
<table class="w-full text-left">
|
||||
<thead class="bg-gray-50 dark:bg-slate-700 border-b border-gray-200 dark:border-gray-600">
|
||||
<tr>
|
||||
<th class="px-4 py-3 text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider">Timestamp</th>
|
||||
<th class="px-4 py-3 text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider">Serial</th>
|
||||
<th class="px-4 py-3 text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider">Project</th>
|
||||
<th class="px-4 py-3 text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider">Tran</th>
|
||||
<th class="px-4 py-3 text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider">Vert</th>
|
||||
<th class="px-4 py-3 text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider">Long</th>
|
||||
<th class="px-4 py-3 text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider">PVS</th>
|
||||
<th class="px-4 py-3 text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider">Mic</th>
|
||||
<th class="px-4 py-3 text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider">Flags</th>
|
||||
${_sortableTh('Timestamp', 'timestamp')}
|
||||
${_sortableTh('Serial', 'serial')}
|
||||
${_sortableTh('Project', 'project')}
|
||||
${_sortableTh('Tran', 'tran_ppv')}
|
||||
${_sortableTh('Vert', 'vert_ppv')}
|
||||
${_sortableTh('Long', 'long_ppv')}
|
||||
${_sortableTh('PVS', 'peak_vector_sum')}
|
||||
${_sortableTh('Mic', 'mic_ppv')}
|
||||
${_sortableTh('Flags', 'false_trigger')}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="divide-y divide-gray-200 dark:divide-gray-700">${rows}</tbody>
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
{% block title %}Sound Level Meters - Seismo Fleet Manager{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
{% include "partials/fleet_tab_strip.html" %}
|
||||
<div class="mb-8">
|
||||
<h1 class="text-3xl font-bold text-gray-900 dark:text-white flex items-center">
|
||||
<svg class="w-8 h-8 mr-3 text-seismo-orange" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Tools - Seismo Fleet Manager{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<!-- Header -->
|
||||
<div class="mb-8">
|
||||
<h1 class="text-3xl font-bold text-gray-900 dark:text-white">Tools</h1>
|
||||
<p class="text-gray-600 dark:text-gray-400 mt-1">
|
||||
Active operator workflows. Pair devices, clean up duplicates, generate reports.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Card grid -->
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
|
||||
<!-- Pair Devices -->
|
||||
<a href="/pair-devices"
|
||||
class="block bg-white dark:bg-slate-800 rounded-xl shadow-lg p-5 hover:shadow-xl transition-shadow border border-transparent hover:border-seismo-orange">
|
||||
<div class="flex items-start gap-3">
|
||||
<div class="w-10 h-10 rounded-lg bg-orange-100 dark:bg-orange-900/30 text-seismo-orange flex items-center justify-center shrink-0">
|
||||
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"/>
|
||||
</svg>
|
||||
</div>
|
||||
<div class="flex-1 min-w-0">
|
||||
<h3 class="font-semibold text-gray-900 dark:text-white">Pair Devices</h3>
|
||||
<p class="text-sm text-gray-600 dark:text-gray-400 mt-1">
|
||||
Bidirectionally link seismographs ↔ modems (or SLMs ↔ modems) so they ship out together as a deployed pair.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</a>
|
||||
|
||||
<!-- Project Tidy -->
|
||||
<a href="/settings/developer/project-tidy"
|
||||
class="block bg-white dark:bg-slate-800 rounded-xl shadow-lg p-5 hover:shadow-xl transition-shadow border border-transparent hover:border-seismo-orange">
|
||||
<div class="flex items-start gap-3">
|
||||
<div class="w-10 h-10 rounded-lg bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400 flex items-center justify-center shrink-0">
|
||||
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14-4H5m14 8H5m14 4H5"/>
|
||||
</svg>
|
||||
</div>
|
||||
<div class="flex-1 min-w-0">
|
||||
<h3 class="font-semibold text-gray-900 dark:text-white">Project Tidy</h3>
|
||||
<p class="text-sm text-gray-600 dark:text-gray-400 mt-1">
|
||||
Find duplicate-looking projects via fuzzy name match (typos, abbreviations) and bulk-merge them. Useful after a metadata backfill run.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</a>
|
||||
|
||||
<!-- Metadata Backfill -->
|
||||
<a href="/settings/developer/metadata-backfill"
|
||||
class="block bg-white dark:bg-slate-800 rounded-xl shadow-lg p-5 hover:shadow-xl transition-shadow border border-transparent hover:border-seismo-orange">
|
||||
<div class="flex items-start gap-3">
|
||||
<div class="w-10 h-10 rounded-lg bg-purple-100 dark:bg-purple-900/30 text-purple-600 dark:text-purple-400 flex items-center justify-center shrink-0">
|
||||
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4m0 5c0 2.21-3.582 4-8 4s-8-1.79-8-4"/>
|
||||
</svg>
|
||||
</div>
|
||||
<div class="flex-1 min-w-0">
|
||||
<h3 class="font-semibold text-gray-900 dark:text-white">Backfill from event metadata</h3>
|
||||
<p class="text-sm text-gray-600 dark:text-gray-400 mt-1">
|
||||
Auto-create projects, locations, and unit assignments from the operator-typed metadata baked into SFM events. Skip the manual entry.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</a>
|
||||
|
||||
<!-- Reports (per-project) -->
|
||||
<a href="/projects"
|
||||
class="block bg-white dark:bg-slate-800 rounded-xl shadow-lg p-5 hover:shadow-xl transition-shadow border border-transparent hover:border-seismo-orange">
|
||||
<div class="flex items-start gap-3">
|
||||
<div class="w-10 h-10 rounded-lg bg-emerald-100 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400 flex items-center justify-center shrink-0">
|
||||
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
|
||||
</svg>
|
||||
</div>
|
||||
<div class="flex-1 min-w-0">
|
||||
<h3 class="font-semibold text-gray-900 dark:text-white">Reports</h3>
|
||||
<p class="text-sm text-gray-600 dark:text-gray-400 mt-1">
|
||||
Excel report generation lives on each project's detail page. Open a project and use <em>Generate Combined Report</em> (for multi-location sound studies) or single-location export.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</a>
|
||||
|
||||
<!-- Swap Detection (Phase 5c — coming soon) -->
|
||||
<div class="bg-gray-50 dark:bg-slate-800/50 rounded-xl shadow p-5 border border-dashed border-gray-300 dark:border-gray-700 cursor-not-allowed">
|
||||
<div class="flex items-start gap-3">
|
||||
<div class="w-10 h-10 rounded-lg bg-gray-200 dark:bg-gray-700 text-gray-400 flex items-center justify-center shrink-0">
|
||||
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"/>
|
||||
</svg>
|
||||
</div>
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="flex items-center gap-2 mb-1">
|
||||
<h3 class="font-semibold text-gray-500 dark:text-gray-400">Swap Detection</h3>
|
||||
<span class="px-1.5 py-0.5 rounded text-xs bg-gray-200 dark:bg-gray-700 text-gray-500 dark:text-gray-400">soon</span>
|
||||
</div>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-500">
|
||||
Daily background job that auto-detects unit swaps in the field (BE12345 → BE67890 at the same project + location) from operator-typed metadata. Coming in Phase 5c.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
{% endblock %}
|
||||
+391
-18
@@ -287,6 +287,16 @@
|
||||
↻ Refresh
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Gantt chart — visual timeline of all deployments. Click
|
||||
a bar to jump to its row in the list below. -->
|
||||
<div id="deploymentGantt" class="mb-4 hidden">
|
||||
<div class="bg-gray-50 dark:bg-slate-900/40 rounded-lg p-3">
|
||||
<svg id="deploymentGanttSvg" class="w-full" style="height: 140px;" preserveAspectRatio="none"></svg>
|
||||
<div id="deploymentGanttLegend" class="flex flex-wrap items-center gap-x-4 gap-y-1 mt-2 text-xs text-gray-500 dark:text-gray-400"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="deploymentTimeline" class="space-y-3">
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400">Loading timeline…</p>
|
||||
</div>
|
||||
@@ -313,7 +323,7 @@
|
||||
<span class="text-xs text-gray-500 dark:text-gray-400 mt-1">outside any assignment window</span>
|
||||
</div>
|
||||
<div class="bg-gray-50 dark:bg-slate-900/50 rounded-lg p-3 flex flex-col">
|
||||
<span class="text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wider">Peak PVS</span>
|
||||
<span class="text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wider">Overall Peak</span>
|
||||
<span id="ue-stat-peak" class="text-2xl font-bold text-gray-900 dark:text-white mt-1">—</span>
|
||||
<span id="ue-stat-peak-when" class="text-xs text-gray-500 dark:text-gray-400 mt-1">—</span>
|
||||
</div>
|
||||
@@ -1986,6 +1996,10 @@ loadUnitData().then(() => {
|
||||
// Replaces the legacy loadDeploymentHistory() + loadUnitHistory() pair.
|
||||
// Derives entries from unit_assignments + unit_history + SFM event overlay.
|
||||
|
||||
// Cache the most recent timeline payload so the merge action can look up
|
||||
// which assignment_ids belong together in a mergeable group.
|
||||
let _dtCurrentTimeline = { entries: [], merge_groups: [] };
|
||||
|
||||
async function loadDeploymentTimeline() {
|
||||
const container = document.getElementById('deploymentTimeline');
|
||||
container.innerHTML = '<p class="text-sm text-gray-500 dark:text-gray-400">Loading timeline…</p>';
|
||||
@@ -1994,12 +2008,58 @@ async function loadDeploymentTimeline() {
|
||||
const r = await fetch(`/api/units/${currentUnit.id}/deployment_timeline`);
|
||||
if (!r.ok) throw new Error('HTTP ' + r.status);
|
||||
const d = await r.json();
|
||||
renderDeploymentTimeline(d.entries || [], container);
|
||||
_dtCurrentTimeline = {
|
||||
entries: d.entries || [],
|
||||
merge_groups: d.merge_groups || [],
|
||||
};
|
||||
renderDeploymentTimeline(_dtCurrentTimeline.entries, container, _dtCurrentTimeline.merge_groups);
|
||||
} catch (e) {
|
||||
container.innerHTML = `<p class="text-sm text-red-500">Failed to load timeline: ${e.message}</p>`;
|
||||
}
|
||||
}
|
||||
|
||||
// Returns the merge_group (list of assignment_ids) that this assignment is
|
||||
// part of, or null if it isn't in any mergeable group.
|
||||
function _dtFindMergeGroup(assignmentId) {
|
||||
for (const group of _dtCurrentTimeline.merge_groups || []) {
|
||||
if (group.includes(assignmentId)) return group;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function mergeAssignmentGroup(assignmentIds) {
|
||||
if (!Array.isArray(assignmentIds) || assignmentIds.length < 2) return;
|
||||
const msg = `Merge ${assignmentIds.length} consecutive assignment records into one?\n\n`
|
||||
+ `The earliest record is kept and its window extended to span all `
|
||||
+ `of them. The other ${assignmentIds.length - 1} record(s) are deleted.\n\n`
|
||||
+ `Original metadata (notes + ingest source) is preserved. This is `
|
||||
+ `logged to the unit's history as "assignment_merged".`;
|
||||
if (!confirm(msg)) return;
|
||||
|
||||
try {
|
||||
// All assignments share the same project_id (validated server-side).
|
||||
// Pick the first entry's project_id from the cache.
|
||||
const first = (_dtCurrentTimeline.entries || []).find(e =>
|
||||
e.kind === 'assignment' && assignmentIds.includes(e.assignment_id)
|
||||
);
|
||||
const projectId = first ? first.project_id : null;
|
||||
if (!projectId) throw new Error('Could not resolve project id for this group');
|
||||
|
||||
const r = await fetch(`/api/projects/${projectId}/assignments/merge`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ assignment_ids: assignmentIds }),
|
||||
});
|
||||
if (!r.ok) {
|
||||
const err = await r.json().catch(() => ({detail: 'HTTP ' + r.status}));
|
||||
throw new Error(err.detail || 'HTTP ' + r.status);
|
||||
}
|
||||
await loadDeploymentTimeline();
|
||||
} catch (e) {
|
||||
alert(e.message || 'Failed to merge assignments.');
|
||||
}
|
||||
}
|
||||
|
||||
function _dtFmtDate(iso) {
|
||||
if (!iso) return '—';
|
||||
return iso.slice(0, 10);
|
||||
@@ -2044,6 +2104,17 @@ function _dtRenderAssignment(e) {
|
||||
? '<span class="px-2 py-0.5 rounded text-xs bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300">active</span>'
|
||||
: '';
|
||||
|
||||
// If this assignment belongs to a mergeable group, show a small
|
||||
// indicator badge — the group-level "Merge" action lives in the
|
||||
// banner at the top of the section to avoid N redundant buttons.
|
||||
const mergeGroup = _dtFindMergeGroup(e.assignment_id);
|
||||
const mergeableBadge = mergeGroup
|
||||
? `<span class="px-2 py-0.5 rounded text-xs bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300"
|
||||
title="This row is part of a ${mergeGroup.length}-record consecutive group at the same location — see the Merge banner above to combine them.">
|
||||
mergeable
|
||||
</span>`
|
||||
: '';
|
||||
|
||||
const overlay = evCount > 0
|
||||
? `<div class="mt-2 flex items-center gap-4 text-xs text-gray-600 dark:text-gray-400">
|
||||
<span><strong class="text-gray-900 dark:text-white">${evCount.toLocaleString()}</strong> event${evCount === 1 ? '' : 's'}</span>
|
||||
@@ -2056,7 +2127,7 @@ function _dtRenderAssignment(e) {
|
||||
? `<div class="mt-2 text-xs text-gray-600 dark:text-gray-400 italic">${_dtEsc(e.notes)}</div>`
|
||||
: '';
|
||||
|
||||
return `<div class="flex gap-3">
|
||||
return `<div class="flex gap-3 transition-shadow rounded-lg" data-assignment-row="${_dtEsc(e.assignment_id)}">
|
||||
<div class="flex flex-col items-center pt-1">
|
||||
<span class="w-3 h-3 rounded-full ${e.is_active ? 'bg-green-500' : 'bg-seismo-orange'}"></span>
|
||||
</div>
|
||||
@@ -2065,7 +2136,10 @@ function _dtRenderAssignment(e) {
|
||||
<div class="text-sm text-gray-700 dark:text-gray-300">
|
||||
<strong>${start}</strong> → <strong>${end}</strong>${dur}
|
||||
</div>
|
||||
${activeBadge}
|
||||
<div class="flex items-center gap-2">
|
||||
${mergeableBadge}
|
||||
${activeBadge}
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-1">${locLink}</div>
|
||||
${projLine}
|
||||
@@ -2118,18 +2192,253 @@ function _dtRenderStateChange(e) {
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function renderDeploymentTimeline(entries, container) {
|
||||
if (!entries.length) {
|
||||
container.innerHTML = '<p class="text-sm text-gray-500 dark:text-gray-400">No deployment history yet. Assign this unit to a project location to start a deployment record.</p>';
|
||||
// ── Gantt chart ─────────────────────────────────────────────────────────────
|
||||
// Renders all assignment windows as colored horizontal bars on an SVG
|
||||
// timeline. Click a bar to scroll its detail row into view in the list
|
||||
// below. Color per location, opacity reduced for closed assignments.
|
||||
// "Mergeable" groups get a unifying outline overlay so they're visible at
|
||||
// a glance as one logical deployment.
|
||||
const _ganttColorPalette = [
|
||||
'#f48b1c', '#142a66', '#7d234d', '#0e7490', '#15803d', '#a16207',
|
||||
'#9333ea', '#dc2626', '#0d9488', '#1d4ed8', '#be185d', '#65a30d',
|
||||
];
|
||||
function _ganttColorFor(locId, locColorMap) {
|
||||
if (locColorMap[locId]) return locColorMap[locId];
|
||||
const idx = Object.keys(locColorMap).length % _ganttColorPalette.length;
|
||||
locColorMap[locId] = _ganttColorPalette[idx];
|
||||
return locColorMap[locId];
|
||||
}
|
||||
|
||||
function _ganttParseDate(iso) {
|
||||
if (!iso) return null;
|
||||
const d = new Date(iso.replace(' ', 'T'));
|
||||
return isNaN(d.getTime()) ? null : d;
|
||||
}
|
||||
|
||||
function _ganttFmtMonth(d) {
|
||||
return d.toLocaleDateString('en-US', { month: 'short', year: '2-digit' });
|
||||
}
|
||||
|
||||
function renderDeploymentGantt(entries, mergeGroups) {
|
||||
const wrapper = document.getElementById('deploymentGantt');
|
||||
const svg = document.getElementById('deploymentGanttSvg');
|
||||
const legend = document.getElementById('deploymentGanttLegend');
|
||||
if (!wrapper || !svg) return;
|
||||
|
||||
const assignments = (entries || []).filter(e => e.kind === 'assignment' && e.starts_at);
|
||||
if (assignments.length === 0) {
|
||||
wrapper.classList.add('hidden');
|
||||
return;
|
||||
}
|
||||
wrapper.classList.remove('hidden');
|
||||
|
||||
// Compute time domain. Pad the end by a few days when an active
|
||||
// assignment is present so the "active" bar doesn't reach the very
|
||||
// edge of the chart.
|
||||
const now = new Date();
|
||||
let minDate = null, maxDate = null;
|
||||
for (const a of assignments) {
|
||||
const start = _ganttParseDate(a.starts_at);
|
||||
const end = a.is_active ? now : (_ganttParseDate(a.ends_at) || now);
|
||||
if (start && (!minDate || start < minDate)) minDate = start;
|
||||
if (end && (!maxDate || end > maxDate)) maxDate = end;
|
||||
}
|
||||
if (!minDate || !maxDate) { wrapper.classList.add('hidden'); return; }
|
||||
// Tiny padding at both ends (3% of total span).
|
||||
const span = maxDate - minDate;
|
||||
const pad = Math.max(span * 0.03, 24 * 3600 * 1000); // at least 1 day
|
||||
minDate = new Date(minDate.getTime() - pad);
|
||||
maxDate = new Date(maxDate.getTime() + pad);
|
||||
|
||||
// Build a quick "which mergeGroup is this id in?" map.
|
||||
const idToGroup = {};
|
||||
(mergeGroups || []).forEach((g, idx) => g.forEach(id => { idToGroup[id] = idx; }));
|
||||
|
||||
// Compute SVG geometry.
|
||||
const width = Math.max(svg.clientWidth || svg.parentElement.clientWidth || 800, 400);
|
||||
const height = 140;
|
||||
const padLeft = 8;
|
||||
const padRight = 8;
|
||||
const padTop = 32; // room for month labels above the bars
|
||||
const padBottom = 18; // room for assignment-count axis below
|
||||
const usableW = width - padLeft - padRight;
|
||||
const usableH = height - padTop - padBottom;
|
||||
const totalRange = maxDate - minDate;
|
||||
const xFor = (d) => padLeft + (d - minDate) / totalRange * usableW;
|
||||
|
||||
// Choose one-row-per-bar OR stack overlapping bars. Since same-unit
|
||||
// assignments rarely overlap (only via the brief unassign/reassign
|
||||
// race), a single row is usually fine. But just in case, stack with
|
||||
// simple top-down packing.
|
||||
const lanes = []; // each lane = [{x1, x2, ...}, ...]
|
||||
function placeInLane(start, end) {
|
||||
for (let i = 0; i < lanes.length; i++) {
|
||||
const last = lanes[i][lanes[i].length - 1];
|
||||
if (last.x2 + 2 < start) {
|
||||
lanes[i].push({ x1: start, x2: end });
|
||||
return i;
|
||||
}
|
||||
}
|
||||
lanes.push([{ x1: start, x2: end }]);
|
||||
return lanes.length - 1;
|
||||
}
|
||||
const placed = assignments.map(a => {
|
||||
const start = _ganttParseDate(a.starts_at);
|
||||
const end = a.is_active ? now : (_ganttParseDate(a.ends_at) || now);
|
||||
const x1 = xFor(start);
|
||||
const x2 = xFor(end);
|
||||
const lane = placeInLane(x1, x2);
|
||||
return { a, x1, x2, lane };
|
||||
});
|
||||
const laneCount = Math.max(lanes.length, 1);
|
||||
const barH = Math.max(14, Math.min(28, Math.floor(usableH / laneCount) - 4));
|
||||
const laneSpacing = barH + 4;
|
||||
|
||||
// Month gridlines + labels. Tick on the 1st of each month inside the
|
||||
// domain. If span > 24mo, tick every 3 months instead.
|
||||
const months = [];
|
||||
let monthCursor = new Date(minDate.getFullYear(), minDate.getMonth(), 1);
|
||||
const tickEveryMonths = (totalRange > 24 * 30 * 86400 * 1000) ? 3 : 1;
|
||||
while (monthCursor <= maxDate) {
|
||||
if (monthCursor >= minDate) months.push(new Date(monthCursor));
|
||||
monthCursor.setMonth(monthCursor.getMonth() + tickEveryMonths);
|
||||
}
|
||||
|
||||
// Build the SVG string.
|
||||
const isDark = document.documentElement.classList.contains('dark');
|
||||
const gridColor = isDark ? '#374151' : '#e5e7eb';
|
||||
const labelColor = isDark ? '#9ca3af' : '#6b7280';
|
||||
const todayColor = '#f48b1c';
|
||||
|
||||
const locColorMap = {};
|
||||
const usedLocs = {};
|
||||
|
||||
let parts = [];
|
||||
// Month gridlines.
|
||||
months.forEach(m => {
|
||||
const x = xFor(m);
|
||||
parts.push(`<line x1="${x}" y1="${padTop}" x2="${x}" y2="${height - padBottom}" stroke="${gridColor}" stroke-width="1"/>`);
|
||||
parts.push(`<text x="${x + 2}" y="${padTop - 6}" font-size="10" fill="${labelColor}" font-family="system-ui,sans-serif">${_ganttFmtMonth(m)}</text>`);
|
||||
});
|
||||
// Today marker.
|
||||
if (now >= minDate && now <= maxDate) {
|
||||
const x = xFor(now);
|
||||
parts.push(`<line x1="${x}" y1="${padTop}" x2="${x}" y2="${height - padBottom}" stroke="${todayColor}" stroke-width="2" stroke-dasharray="3 2" opacity="0.8"/>`);
|
||||
parts.push(`<text x="${x + 3}" y="${height - padBottom + 12}" font-size="9" fill="${todayColor}" font-family="system-ui,sans-serif">today</text>`);
|
||||
}
|
||||
|
||||
// Bars.
|
||||
placed.forEach(p => {
|
||||
const a = p.a;
|
||||
const color = _ganttColorFor(a.location_id || '_', locColorMap);
|
||||
usedLocs[a.location_name || '(no location)'] = color;
|
||||
const y = padTop + p.lane * laneSpacing;
|
||||
const opacity = a.is_active ? 1.0 : 0.85;
|
||||
const stroke = (a.source === 'metadata_backfill') ? '#3b82f6' : 'none';
|
||||
const strokeWidth = (a.source === 'metadata_backfill') ? 2 : 0;
|
||||
|
||||
const barW = Math.max(p.x2 - p.x1, 3);
|
||||
const tipDates = `${(a.starts_at || '').slice(0,10)} → ${a.is_active ? 'active' : (a.ends_at || '').slice(0,10)}`;
|
||||
const tip = `${(a.location_name || '?').replace(/"/g, '"')} (${tipDates})${a.event_overlay && a.event_overlay.event_count ? ' • ' + a.event_overlay.event_count + ' events' : ''}`;
|
||||
|
||||
parts.push(`<g style="cursor: pointer;" onclick="_ganttScrollTo('${a.assignment_id}')">
|
||||
<title>${tip}</title>
|
||||
<rect x="${p.x1}" y="${y}" width="${barW}" height="${barH}" rx="3"
|
||||
fill="${color}" opacity="${opacity}" stroke="${stroke}" stroke-width="${strokeWidth}"/>
|
||||
${a.is_active ? `<circle cx="${p.x2 - 4}" cy="${y + barH / 2}" r="2.5" fill="#fff" opacity="0.9"/>` : ''}
|
||||
</g>`);
|
||||
|
||||
// Mergeable highlight — thin dashed underline below the bar.
|
||||
if (idToGroup[a.assignment_id] !== undefined) {
|
||||
const uy = y + barH + 1;
|
||||
parts.push(`<line x1="${p.x1}" y1="${uy}" x2="${p.x2}" y2="${uy}" stroke="#3b82f6" stroke-width="1.5" stroke-dasharray="2 2" opacity="0.7"/>`);
|
||||
}
|
||||
});
|
||||
|
||||
svg.innerHTML = parts.join('');
|
||||
svg.setAttribute('viewBox', `0 0 ${width} ${height}`);
|
||||
|
||||
// Build legend (one swatch per distinct location).
|
||||
const legendItems = Object.entries(usedLocs).map(([name, color]) =>
|
||||
`<span class="flex items-center gap-1.5"><span class="inline-block w-3 h-2 rounded" style="background:${color}"></span>${_dtEsc(name)}</span>`
|
||||
);
|
||||
if (mergeGroups && mergeGroups.length > 0) {
|
||||
legendItems.push(`<span class="flex items-center gap-1.5"><span class="inline-block w-3 border-b-2 border-dashed border-blue-500"></span>mergeable group</span>`);
|
||||
}
|
||||
if (placed.some(p => p.a.source === 'metadata_backfill')) {
|
||||
legendItems.push(`<span class="flex items-center gap-1.5"><span class="inline-block w-3 h-2 rounded border-2 border-blue-500"></span>auto-backfilled</span>`);
|
||||
}
|
||||
legend.innerHTML = legendItems.join('');
|
||||
}
|
||||
|
||||
// Click-on-bar handler. Just scroll the matching list row into view +
|
||||
// briefly flash it so the eye finds it.
|
||||
function _ganttScrollTo(assignmentId) {
|
||||
const target = document.querySelector(`[data-assignment-row="${assignmentId}"]`);
|
||||
if (!target) return;
|
||||
target.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
target.classList.add('ring-2', 'ring-seismo-orange');
|
||||
setTimeout(() => target.classList.remove('ring-2', 'ring-seismo-orange'), 1500);
|
||||
}
|
||||
|
||||
function renderDeploymentTimeline(entries, container, mergeGroups) {
|
||||
if (!entries.length) {
|
||||
container.innerHTML = '<p class="text-sm text-gray-500 dark:text-gray-400">No deployment history yet. Assign this unit to a project location to start a deployment record.</p>';
|
||||
// Hide the Gantt block too.
|
||||
const g = document.getElementById('deploymentGantt');
|
||||
if (g) g.classList.add('hidden');
|
||||
return;
|
||||
}
|
||||
|
||||
// Render the Gantt chart first (above the list).
|
||||
renderDeploymentGantt(entries, mergeGroups);
|
||||
|
||||
// Build the mergeable-groups banner. Each group offers one "Merge into
|
||||
// one" button. Skipped when no groups exist.
|
||||
let bannerHtml = '';
|
||||
if (mergeGroups && mergeGroups.length > 0) {
|
||||
const rows = mergeGroups.map(group => {
|
||||
// Look up the entries to describe what we're merging.
|
||||
const groupEntries = (entries || []).filter(e =>
|
||||
e.kind === 'assignment' && group.includes(e.assignment_id)
|
||||
);
|
||||
if (groupEntries.length === 0) return '';
|
||||
const locName = groupEntries[0].location_name || 'unnamed location';
|
||||
const earliest = groupEntries.map(e => e.starts_at).filter(Boolean).sort()[0] || '';
|
||||
const latest = groupEntries.map(e => e.ends_at).filter(Boolean).sort().reverse()[0] || 'present';
|
||||
const idsJson = JSON.stringify(group).replace(/"/g, '"');
|
||||
return `<div class="flex items-center justify-between gap-3 py-1.5">
|
||||
<div class="text-sm text-blue-900 dark:text-blue-200 min-w-0 flex-1">
|
||||
<strong>${group.length} consecutive records</strong> at <strong>${_dtEsc(locName)}</strong>
|
||||
<span class="text-xs text-blue-700 dark:text-blue-300 ml-2">${_dtFmtDate(earliest)} → ${_dtFmtDate(latest)}</span>
|
||||
</div>
|
||||
<button onclick='mergeAssignmentGroup(${JSON.stringify(group)})'
|
||||
class="px-3 py-1 text-xs rounded-full bg-blue-600 hover:bg-blue-700 text-white font-medium whitespace-nowrap">
|
||||
Merge into one
|
||||
</button>
|
||||
</div>`;
|
||||
}).join('');
|
||||
bannerHtml = `<div class="mb-4 p-3 rounded-lg bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800">
|
||||
<div class="flex items-start gap-2 mb-2">
|
||||
<svg class="w-4 h-4 text-blue-600 dark:text-blue-400 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
|
||||
</svg>
|
||||
<div class="text-xs text-blue-800 dark:text-blue-300">
|
||||
Consecutive deployments at the same location detected. Combine them into a single record to clean up the view (notes + ingest sources are preserved).
|
||||
</div>
|
||||
</div>
|
||||
${rows}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
const html = entries.map(e => {
|
||||
if (e.kind === 'assignment') return _dtRenderAssignment(e);
|
||||
if (e.kind === 'gap') return _dtRenderGap(e);
|
||||
if (e.kind === 'state_change') return _dtRenderStateChange(e);
|
||||
return '';
|
||||
}).join('');
|
||||
container.innerHTML = html;
|
||||
|
||||
container.innerHTML = bannerHtml + '<div class="space-y-3">' + html + '</div>';
|
||||
}
|
||||
|
||||
// ── SFM Events section ──────────────────────────────────────────────────────
|
||||
@@ -2142,6 +2451,15 @@ function clearUnitEventFilters() {
|
||||
loadUnitEvents();
|
||||
}
|
||||
|
||||
// Module-level state for the unit-events table sort. Cache lets us re-sort
|
||||
// without a refetch when the user clicks a column header.
|
||||
let _ueEventsCache = [];
|
||||
let _ueEventsTotal = 0;
|
||||
let _ueEventsBucket = 'all';
|
||||
let _ueAssignmentsTotal = 0;
|
||||
let _ueSortKey = 'timestamp';
|
||||
let _ueSortDir = 'desc';
|
||||
|
||||
async function loadUnitEvents() {
|
||||
if (!currentUnit || currentUnit.device_type !== 'seismograph') return;
|
||||
const container = document.getElementById('ue-events-container');
|
||||
@@ -2166,13 +2484,62 @@ async function loadUnitEvents() {
|
||||
throw new Error(err.detail || 'HTTP ' + r.status);
|
||||
}
|
||||
const d = await r.json();
|
||||
_ueEventsCache = d.events || [];
|
||||
_ueEventsTotal = d.count || 0;
|
||||
_ueEventsBucket = bucket;
|
||||
_ueAssignmentsTotal = d.assignments_total || 0;
|
||||
renderUnitEventStats(d.stats);
|
||||
renderUnitEventTable(d.events, d.count, container, bucket, d.assignments_total);
|
||||
renderUnitEventTable(_ueEventsCache, _ueEventsTotal, container, bucket, _ueAssignmentsTotal);
|
||||
} catch (e) {
|
||||
container.innerHTML = `<div class="text-center py-12 text-red-500 text-sm">Failed to load events: ${e.message}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
function sortUnitEvents(key) {
|
||||
if (_ueSortKey === key) {
|
||||
_ueSortDir = _ueSortDir === 'desc' ? 'asc' : 'desc';
|
||||
} else {
|
||||
_ueSortKey = key;
|
||||
_ueSortDir = 'desc';
|
||||
}
|
||||
renderUnitEventTable(_ueEventsCache, _ueEventsTotal,
|
||||
document.getElementById('ue-events-container'), _ueEventsBucket, _ueAssignmentsTotal);
|
||||
}
|
||||
|
||||
function _ueApplySort(events) {
|
||||
const key = _ueSortKey;
|
||||
const dir = _ueSortDir === 'asc' ? 1 : -1;
|
||||
return [...events].sort((a, b) => {
|
||||
let av, bv;
|
||||
if (key === 'attribution') {
|
||||
// Sort by location name so attributed rows group together.
|
||||
av = a.attribution ? (a.attribution.location_name || '') : '';
|
||||
bv = b.attribution ? (b.attribution.location_name || '') : '';
|
||||
} else {
|
||||
av = a[key]; bv = b[key];
|
||||
}
|
||||
if (av == null && bv == null) return 0;
|
||||
if (av == null) return 1;
|
||||
if (bv == null) return -1;
|
||||
if (typeof av === 'number' && typeof bv === 'number') return (av - bv) * dir;
|
||||
return String(av).localeCompare(String(bv)) * dir;
|
||||
});
|
||||
}
|
||||
|
||||
function _ueSortIndicator(key) {
|
||||
if (_ueSortKey !== key) return '<span class="text-gray-400 opacity-50 ml-1">↕</span>';
|
||||
return _ueSortDir === 'desc'
|
||||
? '<span class="text-seismo-orange ml-1">↓</span>'
|
||||
: '<span class="text-seismo-orange ml-1">↑</span>';
|
||||
}
|
||||
|
||||
function _ueSortableTh(label, key) {
|
||||
return `<th onclick="sortUnitEvents('${key}')"
|
||||
class="px-4 py-3 text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider cursor-pointer select-none hover:bg-gray-100 dark:hover:bg-slate-600 transition-colors">
|
||||
${label}${_ueSortIndicator(key)}
|
||||
</th>`;
|
||||
}
|
||||
|
||||
function renderUnitEventStats(stats) {
|
||||
const s = stats || {};
|
||||
document.getElementById('ue-stat-total').textContent = (s.event_count ?? 0).toLocaleString();
|
||||
@@ -2228,12 +2595,17 @@ function _ueAttrCell(ev) {
|
||||
if (a) {
|
||||
const projLabel = _ueEsc(a.project_name || '—');
|
||||
const locLabel = _ueEsc(a.location_name || '—');
|
||||
// If the attributed location has since been soft-removed, badge
|
||||
// it so operators see at a glance this is historical attribution.
|
||||
const removedBadge = a.location_removed_at
|
||||
? '<span class="ml-1 text-[10px] uppercase tracking-wider px-1 py-0.5 rounded bg-gray-200 dark:bg-gray-700 text-gray-600 dark:text-gray-300 font-semibold" title="Location no longer actively monitored">removed</span>'
|
||||
: '';
|
||||
return `<a href="/projects/${_ueEsc(a.project_id)}/nrl/${_ueEsc(a.location_id)}"
|
||||
onclick="event.stopPropagation()"
|
||||
class="text-seismo-orange hover:text-seismo-navy"
|
||||
title="${projLabel} → ${locLabel}">
|
||||
📍 ${locLabel}
|
||||
</a>
|
||||
</a>${removedBadge}
|
||||
<div class="text-xs text-gray-500 dark:text-gray-400">${projLabel}</div>`;
|
||||
}
|
||||
const n = ev.nearest_assignment;
|
||||
@@ -2269,7 +2641,8 @@ function renderUnitEventTable(events, total, container, bucket, assignmentsTotal
|
||||
return;
|
||||
}
|
||||
|
||||
const rows = events.map(ev => {
|
||||
const sorted = _ueApplySort(events);
|
||||
const rows = sorted.map(ev => {
|
||||
const ts = ev.timestamp ? ev.timestamp.replace('T', ' ').slice(0, 19) : '—';
|
||||
const tran = _ueFmtPPV(ev.tran_ppv);
|
||||
const vert = _ueFmtPPV(ev.vert_ppv);
|
||||
@@ -2295,13 +2668,13 @@ function renderUnitEventTable(events, total, container, bucket, assignmentsTotal
|
||||
<table class="w-full text-left">
|
||||
<thead class="bg-gray-50 dark:bg-slate-700 border-b border-gray-200 dark:border-gray-600">
|
||||
<tr>
|
||||
<th class="px-4 py-3 text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider">Timestamp</th>
|
||||
<th class="px-4 py-3 text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider">Tran</th>
|
||||
<th class="px-4 py-3 text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider">Vert</th>
|
||||
<th class="px-4 py-3 text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider">Long</th>
|
||||
<th class="px-4 py-3 text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider">PVS</th>
|
||||
<th class="px-4 py-3 text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider">Flags</th>
|
||||
<th class="px-4 py-3 text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider">Attribution</th>
|
||||
${_ueSortableTh('Timestamp', 'timestamp')}
|
||||
${_ueSortableTh('Tran', 'tran_ppv')}
|
||||
${_ueSortableTh('Vert', 'vert_ppv')}
|
||||
${_ueSortableTh('Long', 'long_ppv')}
|
||||
${_ueSortableTh('PVS', 'peak_vector_sum')}
|
||||
${_ueSortableTh('Flags', 'false_trigger')}
|
||||
${_ueSortableTh('Attribution', 'attribution')}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="divide-y divide-gray-200 dark:divide-gray-700">${rows}</tbody>
|
||||
|
||||
@@ -199,7 +199,7 @@
|
||||
<span id="ev-stat-count" class="text-3xl font-bold text-gray-900 dark:text-white mt-1">—</span>
|
||||
</div>
|
||||
<div class="bg-white dark:bg-slate-800 rounded-xl shadow-lg p-4 flex flex-col">
|
||||
<span class="text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wider">Peak PVS</span>
|
||||
<span class="text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wider">Overall Peak</span>
|
||||
<span id="ev-stat-peak" class="text-3xl font-bold text-gray-900 dark:text-white mt-1">—</span>
|
||||
<span id="ev-stat-peak-when" class="text-xs text-gray-500 dark:text-gray-400 mt-1">—</span>
|
||||
</div>
|
||||
@@ -583,6 +583,14 @@ function renderAssignmentsUsed(assignments) {
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
|
||||
</svg>
|
||||
</button>
|
||||
<button type="button"
|
||||
onclick="deleteAssignment('${esc(a.assignment_id)}', '${esc(a.unit_id)}', '${start} → ${end}')"
|
||||
title="Delete this assignment record (for mis-clicks / duplicates)"
|
||||
class="text-gray-400 hover:text-red-600 transition-colors p-1">
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6M1 7h22M9 7V4a1 1 0 011-1h4a1 1 0 011 1v3"/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<span class="text-sm text-gray-700 dark:text-gray-300 whitespace-nowrap">${(a.events_in_window || 0).toLocaleString()} event${a.events_in_window === 1 ? '' : 's'}</span>
|
||||
</div>`;
|
||||
@@ -608,6 +616,33 @@ function openAssignmentEditModal(encodedJson) {
|
||||
document.getElementById('assignment-edit-modal').classList.remove('hidden');
|
||||
}
|
||||
|
||||
async function deleteAssignment(assignmentId, unitId, windowLabel) {
|
||||
// For mis-clicks / accidental duplicate assignments. Backend refuses
|
||||
// if there's a real recording session inside the window — those should
|
||||
// go through Edit or Unassign instead.
|
||||
const msg = `Delete this assignment?\n\n`
|
||||
+ `Unit: ${unitId}\n`
|
||||
+ `Window: ${windowLabel}\n\n`
|
||||
+ `This is for assignments created in error. Events that fell `
|
||||
+ `in this window will become unattributed. The unit's deployment `
|
||||
+ `history will log the deletion for audit.\n\n`
|
||||
+ `If the unit actually was deployed here, use Edit or Unassign instead.`;
|
||||
if (!confirm(msg)) return;
|
||||
|
||||
try {
|
||||
const r = await fetch(`/api/projects/${projectId}/assignments/${assignmentId}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
if (!r.ok) {
|
||||
const err = await r.json().catch(() => ({detail: 'HTTP ' + r.status}));
|
||||
throw new Error(err.detail || 'HTTP ' + r.status);
|
||||
}
|
||||
await loadLocationEvents(); // Refresh stats + table without this assignment.
|
||||
} catch (err) {
|
||||
alert(err.message || 'Failed to delete assignment.');
|
||||
}
|
||||
}
|
||||
|
||||
function closeAssignmentEditModal() {
|
||||
document.getElementById('assignment-edit-modal').classList.add('hidden');
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user