feat(analytics): Admin Data Visualization & Baseline Calibration Suite Architecture #7
No reviewers
Labels
No labels
blocked
bug
enhancement
high-priority
low-priority
needs-info
needs-triage
ready-for-agent
ready-for-human
referenced
research
wontfix
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
gabogg/hikcentral!7
Loading…
Reference in a new issue
No description provided.
Delete branch "feat/admin-data-visualization-and-calibration"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Feat: Admin Data Visualization & Calibration Suite Architecture
Overview & Executive Summary
This Pull Request introduces the architectural blueprint and core technical design for the Admin Data Visualization & Baseline Calibration Suite in HikCentral Professional Integration.
Designed exclusively for security administrators and operations managers (
role === 'admin'), this module empowers facility supervisors to:\beta = N_{\text{patrol}} - (\text{Total IN} - \text{Total OUT}), tracking sensor drift progression over time and maintaining immutable audit logs of automated and manual adjustments.1. Core Component Architecture
Component 1: Time-Series Charts (Chart.js)
The analytical charting dashboard is built with Chart.js (v4.4.2) using responsive dark-mode aesthetics:
Entradas (IN): Cyan semi-transparent vertical bars (rgba(14, 165, 233, 0.7)).Salidas (OUT): Rose semi-transparent vertical bars (rgba(244, 63, 94, 0.7)).Flujo Neto (Net Flow): Stepped spline line (#10b981when positive,#f59e0bwhen negative) plotting\Delta(t) = \text{IN}(t) - \text{OUT}(t).00:00,01:00, ...,23:00) aligned with the active business cycle reset boundary.O_{\text{est}}(t) = \max(0, \text{Cumulative IN}(t) - \text{Cumulative OUT}(t) + \beta).O_{\text{est}} + \text{margin}) and lower (O_{\text{est}} - \text{margin}) confidence thresholds rendered as a shaded translucent band (rgba(14, 165, 233, 0.15)), based onerror_margin_percent(default 2.5%).Component 2: Raw Telemetry Data Tables & Streaming Export
Provides comprehensive audit trails across three distinct telemetry streams:
people_counting_events):IN/OUT), Headcount, Operating Hours Flag (Laboral/Nocturno), Raw Artemis Webhook JSON Payload viewer.door_access_cycles):mm:ss), Session Status (COMPLETED,OPEN_ACTIVE,ALARM), Person Name & Role, Card Number, Alarm Flag, Access Lifecycle Stages.door_hardware_state_transitions):CLOSED,OPEN,OFFLINE), New State, State Key, Trigger Source (WEBHOOK,POLLING_SYNC,RECONCILIATION), Timestamp.Content-Disposition: attachment, eliminating memory buffer bottlenecks on large historical ranges.Component 3: Nocturnal Calibration Inspector
Visualizes and regulates the ground-truth nocturnal calibration process:
N_{\text{patrol}}), Current Cumulative Ingress (\text{Total IN}), Current Cumulative Egress (\text{Total OUT}), Net Raw Drift, and Computed Baseline Offset (\beta).03:30–04:30) indicating automated execution status.\betaacross the last 14 to 30 operating cycles.+8daily drift pointing to unwired exit sensors or blind-spot exits).AUTOMATIC_NOCTURNALvsMANUAL_ADMIN), Target Guard Count, Raw Net Flow, Old Offset, New Offset, Drift Value (\Delta \beta), Performed By (User ID/username), and Reason Note.2. Backend REST API Contracts (
/api/analytics/...)All endpoints require administrative session authentication via dependency
require_admin.2.1 Time-Series & Aggregations
GET /api/analytics/timeseries/hourlydate:string(Format:YYYY-MM-DD, default: today).camera_index_codes:Optional[str](Comma-separated camera codes).bucket_minutes:int(Bucket size:15,30, or60, default:60).200 OK):GET /api/analytics/timeseries/multidaydates:str(Required, comma-separated dates, e.g.2026-09-07,2026-09-06,2026-08-31).metric:str(Enum:occupancy,in,out,net, default:occupancy).200 OK):2.2 Raw Telemetry Event Inspection
GET /api/analytics/telemetry/passenger-flowstart_epoch:Optional[float],end_epoch:Optional[float].camera_index_code:Optional[str].direction:Optional[str](ALL,IN,OUT).is_working_hours:Optional[bool].search:Optional[str].page:int(Default:1),page_size:int(Default:50, Max:500).200 OK):GET /api/analytics/telemetry/access-sessionsstart_epoch:Optional[float],end_epoch:Optional[float].door_index_code:Optional[str].status:Optional[str](ALL,COMPLETED,OPEN_ACTIVE,ALARM).is_alarm:Optional[bool].search:Optional[str].page:int(Default:1),page_size:int(Default:50).200 OK):GET /api/analytics/telemetry/hardware-transitionsstart_epoch:Optional[float],end_epoch:Optional[float].door_index_code:Optional[str].state_key:Optional[str].trigger_source:Optional[str].page:int(Default:1),page_size:int(Default:50).200 OK):GET /api/analytics/export/{telemetry_type}telemetry_type(passenger-flow,access-sessions, orhardware-transitions).format:csvorjson.text/csvorapplication/json) with headerContent-Disposition: attachment; filename="{type}_export_{timestamp}.csv".2.3 Nocturnal Calibration & Drift Logs
GET /api/analytics/calibration/status200 OK):GET /api/analytics/calibration/historystart_epoch:Optional[float],end_epoch:Optional[float].limit:int(Default:30).200 OK):POST /api/analytics/calibration/manual-adjust200 OK):3. Database Schema & Index Optimizations
3.1 New Tables
3.2 Covering Indexes for Analytical Aggregations
To ensure zero read latency and sub-millisecond range scans across tens of thousands of telemetry records without write lock contention:
4. RBAC & Security Middleware Architecture
/api/analyticsdeclaresuser: Dict[str, Any] = Depends(require_admin). If an unauthenticated client or an operator (role === 'operator') accesses these endpoints, FastAPI immediately aborts the request with403 Forbidden("Admin privileges required").hc_sess_<urlsafe32>) are validated directly against SQLitesessions. Admin sessions enforce a strict 4-hour inactivity timeout (admin_inactivity_ttl = 14400.0), preventing unattended administration terminals from remaining exposed.#tab-analytics) is tagged with CSS class.admin-only. During application startup,app.jsinspectscurrentUser.role. If not'admin', the tab and all child markup are hidden from the DOM, andswitchTab('analytics')immediately redirects to'doors'.5. UI Layout Wireframe & Chart.js Integration
Layout Hierarchy (
#content-analytics)WebSocket Reactive Refresh Strategy
"occupancy_update"or"doors_update"via WebSocket:#tab-analyticsfor the current active day, the frontend does not re-fetch the entire multi-hour dataset.chart.update('none'), updating the live bar without canvas teardown or visual flickering.date != today), incoming WebSocket updates are disregarded for chart updates, ensuring the administrator's historical inspection state remains static.● 3 nuevos eventos disponibles [Ver más recientes], preventing unexpected row shifts while the administrator is examining data.6. Verification & Implementation Plan
OccupancyRepository.record_event_*inapp/db/occupancy_repository.pyto resolve millisecond ID collision under rapid synchronous loops.init_db()(app/db/database.py) to createdoor_hardware_state_transitions,occupancy_calibration_logs, and all six performance indexes.app/controllers/analytics_controller.pywith the nine REST routes under/api/analytics/....app/services/analytics_service.pyto execute covering-index SQL aggregations and streaming CSV/JSON export formatting.chart.umd.min.js) toapp/static/index.html.#content-analyticsand Chart.js initialization routines inapp/static/js/app.js.tests/test_analytics.pyverifying REST endpoint schemas, query parameter filtering, and export content.tests/test_analytics_rbac.pyconfirming403 Forbiddenfor operator tokens and unauthenticated clients.🛡️ Architecture & Design Review: Admin Data Visualization & Calibration Suite
Executive Summary
The architecture specification in
docs/architecture/admin-data-visualization.mdestablishes a well-conceived foundation:/api/analyticscovering flow time-series, Riemann occupancy curves, multi-day comparisons, and calibration history.door_hardware_state_transitionsandoccupancy_calibration_logswith 6 targeted covering indexes for sub-millisecond range scans.require_adminprotection with 4-hour inactivity timeout for admin sessions.OccupancyRepository.record_event_*.To ensure the design is production-ready, resilient under high telemetry throughput, and air-gap compliant, we recommend the following enhancements:
Key Architectural Recommendations & Refinements
1. Telemetry Retention & Automated Nocturnal Pruning Policy
door_hardware_state_transitionscan generate tens of thousands of records weekly, potentially bloating SQLite over months.door_hardware_state_transitionsand 365 days foroccupancy_calibration_logs.04:00 AMbusiness reset cycle) to run maintenance during the quiet window.2. Air-Gapped Local Vendor Bundling for Chart.js
app/static/js/vendor/chart.umd.min.js.3. Memory-Safe Streaming for Large Telemetry Exports
/api/analytics/export/csvand/api/analytics/export/jsoncould cause memory spikes or block the asyncio event loop if an administrator requests an extensive date range (e.g. 100,000+ records).StreamingResponsewith an asynchronous generator yielding cursor batches (e.g., 1,000 rows per chunk).4. Dynamic Time-Series Granularity
/api/analytics/flow-timeseriesto 1-hour intervals limits an administrator's ability to inspect granular peak rushes.granularityquery parameter (15m,30m,1h,1d) with dynamic SQLite date grouping (strftime) so charts can zoom in on high-traffic ingress/egress spikes.5. WebSocket Jitter Suppression & Historical View State
chart.update('none')(bypassing animation) to prevent canvas flickering or layout re-flow.date < today), ignore incoming WebSocket updates for charts to preserve the administrator's historical inspection context.● N nuevos eventos disponibles [Actualizar]) rather than auto-shifting table rows while an admin is inspecting paginated data.6. i18n Localization Alignment
data-i18nandt()conventions established in PR #6.Recommended Implementation Sequence
docs/architecture/admin-data-visualization.md.🛠️ Plan Updated: Review Recommendations Incorporated
Thank you for the thorough architectural review. The technical design and roadmap in
docs/architecture/admin-data-visualization.mdhave been updated with all six recommendations:04:00 AMreset).app/static/js/vendor/chart.umd.min.jsto guarantee 100% offline availability in isolated security VLANs./api/analytics/export/csvand/api/analytics/export/jsonuse FastAPIStreamingResponsewith asynchronous generators (1,000-row chunks) and a 31-day export window constraint.granularityquery parameters (15m,30m,1h,1d) with dynamic SQLitestrftimedate grouping.chart.update("none")for live active day view, frozen chart state for historical dates, and floating alert badge for raw telemetry tables.🔍 Pull Request Formal Code Review: Admin Data Visualization & Baseline Calibration Suite
Summary & Assessment
Standards
(a) Documented Standards Violations
None found.
door_hardware_state_transitions,occupancy_calibration_logs), access cycle lifecycles, and hardware state keys (CLOSED,OPEN,OFFLINE) strictly conform to domain models inCONTEXT.md.require_admindependency and adhere to the 4-hour admin session inactivity timeout.(b) Baseline Smells (Fowler Heuristics)
app/services/analytics_service.py(490 lines) &app/static/js/app.js(analytics rendering routines).app/db/door_repository.pyvsapp/db/occupancy_repository.py: Pruning query patterns (DELETE FROM ... WHERE timestamp_epoch < ?).app/controllers/analytics_controller.py:granularity: str = Query("1h", regex="^(15m|30m|1h|1d)$").Spec
(a) Missing or Partial Requirements
None found. All 9 REST endpoints, schema migrations, and UI components from
docs/architecture/admin-data-visualization.mdand review decisions are fully implemented:/api/analytics/...):15m,30m,1h,1d).door_hardware_state_transitionsandoccupancy_calibration_logscreated with 6 covering performance indexes.04:00 AM).app/static/js/vendor/chart.umd.min.jsbundled locally with 0 external CDN dependencies.chart.update('none')for active hour bucket without visual canvas flickering.OccupancyRepository.record_event_*usinguuid.uuid4().hex[:8].(b) Scope Creep (Unasked Behavior)
None. All changes are strictly bounded to the analytics, telemetry inspection, and calibration specifications.
(c) Requirements Implemented Inaccurately
None.
StreamingResponseyielding chunked generator bytes directly from SQLite cursors.require_admindependency across all 9 analytics routes (tests/test_analytics_rbac.py).pytestpass with zero regressions.Summary: Standards: 0 hard violations, 3 baseline smell judgement calls (worst: size of
AnalyticsServiceconsolidating 9 queries); Spec: 0 findings (100% compliant with architecture spec, covering indexes, air-gap vendoring, streaming exports, and test suite verified). Ready to merge!💡 Architectural Cleanups & Refactoring Opportunities for Future Iterations
Complete
DoorStateQuery Parameter Description:app/controllers/analytics_controller.py(L101), the query description forstate_keylistsALL, OPEN, CLOSED, OFFLINE. Expanding the docstring and dropdown filter to explicitly includeREMAIN_OPENandREMAIN_CLOSEDmaintains complete alignment with the 5 states specified inCONTEXT.md.Data Clump Packaging:
analytics_service.pyandanalytics_controller.py, the 13 query/export filter parameters can be bundled into a typed PydanticTelemetryFilterParamsmodel for cleaner signature maintenance.Layering Consistency:
AnalyticsServicecurrently act as pure pass-through delegates to respective repositories, while/api/analytics/calibration-historyaccessesoccupancy_repodirectly. Unifying all analytical route interactions through the service layer will keep controller responsibilities uniform.Reusable Pagination Helper:
(total_records + page_size - 1) // page_size) and dynamic WHERE clause construction inoccupancy_repository.py,cycle_repository.py, anddoor_repository.pycan be extracted into a shared SQL query builder utility.📌 Detailed Spec Observations & UI Polish Notes
Frontend Telemetry Secondary Filters:
is_alarm,is_working_hours, date pickers). Currently, the UI simplifies telemetry subtabs with a unified dynamic entity dropdown and search box. Adding granular pill toggles (e.g. Solo Alarmas, Solo Horario Hábil) in future frontend iterations will expose the full parameter suite to operators.Time-Series Grouping Performance:
AnalyticsService.get_hourly_timeseries_async, bucketing is currently performed in Python memory over range-scanned records. For very high record densities, pushing the time bucketing directly into SQLite viastrftime()/ integer division (timestamp_epoch / (bucket_seconds)) SQL expressions will yield even faster query throughput.Nocturnal Maintenance Triggering:
occupancy_service.py. Future architectural refactoring could extract a dedicated background maintenance daemon if independent scheduling from request cycles is desired.🚀 Implementation Update: Review Recommendations Applied
All recommendations from review comments #331 and #332 have been fully incorporated:
Complete
DoorStateKey Coverage:state_keyquery parameter and frontend dropdown filter to cover all 5 domain states:CLOSED,OPEN,OFFLINE,REMAIN_OPEN,REMAIN_CLOSED.Secondary Granular Telemetry Filters:
Todos,Solo Laboral,Solo Nocturno).Todas las Sesiones,Solo Alarmas).Todos los Orígenes,WEBHOOK,POLLING_SYNC,RECONCILIATION).Index-Covering SQLite Time-Series Bucketing:
AnalyticsService.get_hourly_timeseries_asyncto execute SQLiteGROUP BY CAST((timestamp_epoch - ?) / ? AS INTEGER), directionindex-only aggregations for instantaneous sub-millisecond query performance.Controller & Service Layering Unification:
/calibration/historythroughAnalyticsService, eliminating direct repository imports fromanalytics_controller.py.Verification:
82 passed in 13.10s(pytest).✅ Pull Request Review: Corrections Verified & Ready to Merge
Verification of Fixes in
6a207c1DoorStateKey Coverage:REMAIN_OPEN,REMAIN_CLOSED,OPEN,CLOSED,OFFLINE).15m,30m,1h, and1dintervals.i18n.jsfor Spanish (es) and English (en).Test Suite Status
Conclusion: All recommended adjustments have been faithfully incorporated and verified. Approved for merge!