Data Flow
Relevant source files
The following files were used as context for generating this wiki page:The data flow in BMSview is designed around a local-first architecture, where the browser's IndexedDB is the primary data store for the user to ensure offline functionality and a responsive UI. The server, powered by Netlify Functions, acts as the authoritative source and handles complex processing tasks like AI analysis, data aggregation, and integrity checks. Data is synchronized periodically between the client and server.
This document outlines the primary data pathways within the application, including BMS screenshot analysis, historical data retrieval for charting, AI-driven insights generation, and administrative data reconciliation. The system leverages a combination of synchronous API calls for immediate feedback and asynchronous background jobs for more intensive operations.
Sources: GEMINI.md
BMS Screenshot Analysis Flow
This flow describes the process from a user uploading a BMS screenshot to receiving an analysis. The application primarily uses a synchronous flow for single-file uploads to provide a fast user experience.
Sources: GEMINI.md
The diagram below illustrates the sequence of events for a synchronous analysis request.
This sequence shows the synchronous analysis flow for a single screenshot upload.
Sources: GEMINI.md, STATE_MANAGEMENT_GUIDE.md, SANITY_CHECK_REPORT.md
Key Steps:
- Upload: The user uploads a screenshot. The
clientServicedispatches aPREPARE_ANALYSISaction to update the UI state. - API Call: A synchronous request is made to the
/.netlify/functions/analyzeendpoint. - Deduplication: The backend calculates a SHA-256 hash of the image content to check if an analysis already exists in the
analysis-resultscollection. - AI Analysis: If no record is found, the image is sent to the Google Gemini API for OCR and analysis.
- Data Validation: The extracted data is passed through a data integrity validation layer (
validateAnalysisData) which performs physics and consistency checks (e.g., SOC range, voltage sum). - Storage: The new analysis result, along with any validation warnings and a
needsReviewflag, is stored in theanalysis-resultscollection in MongoDB. - Response: The complete
AnalysisRecordis returned to the client. - UI Update: The
clientServicedispatches aSYNC_ANALYSIS_COMPLETEaction, which updates theappStateand displays the results to the user.
Sources: GEMINI.md, SANITY_CHECK_REPORT.md, 12-2-todo.md
Historical & Analytics Data Flow
The Historical Analysis feature provides administrators with advanced charting and analytics. This system can operate in two modes: displaying only BMS screenshot data or displaying a merged timeline of BMS data and hourly cloud/weather data.
Sources: ADMIN_HISTORICAL_ANALYSIS_OVERHAUL.md, HOURLY_CLOUD_SOLAR_INTEGRATION.md
The following flowchart shows the data retrieval logic for the historical chart.
This diagram illustrates the two data paths for populating the historical analysis chart.
Sources: HISTORICAL_ANALYSIS_IMPLEMENTATION_COMPLETE.md, ADMIN_HISTORICAL_ANALYSIS_OVERHAUL.md
Data Retrieval Modes
1. BMS-Only Mode
- The
HistoricalChart.tsxcomponent, via theuseAnalyticsData.tshook, fetches data from the standard/.netlify/functions/historyendpoint. - This endpoint returns an array of
AnalysisRecordobjects directly from thehistorycollection in MongoDB for the selected system and date range.
Sources: HISTORICAL_ANALYSIS_IMPLEMENTATION_COMPLETE.md
2. Merged Data Mode
- When the "Hourly Weather" toggle is enabled, the frontend calls the
getMergedTimelineDatafunction. - This function hits the
/.netlify/functions/historyendpoint with themerged=truequery parameter. - The backend then executes the
mergeBmsAndCloudDatautility fromdata-merge.cjs. This utility:- Fetches BMS records from the
historycollection. - Fetches hourly weather data (cloud cover, irradiance) from the
hourly-weathercollection. - Performs linear interpolation to estimate BMS metric values at hourly intervals where no screenshot exists.
- Merges the two datasets, prioritizing real BMS data where available.
- Tags each data point with its
source: 'bms', 'cloud', or 'estimated'. - Downsamples the final dataset to a maximum of 2000 points for performance if necessary.
- Fetches BMS records from the
- The
HistoricalChart.tsxcomponent uses thesourcefield to apply different visual styles (e.g., solid lines for 'bms', dashed for 'estimated').
Sources: ADMIN_HISTORICAL_ANALYSIS_OVERHAUL.md, HOURLY_CLOUD_SOLAR_INTEGRATION.md
AI Insights Generation (ReAct Loop)
For generating deep insights, the system uses a ReAct (Reasoning and Acting) loop with the Gemini AI. This allows the AI to use a set of predefined "tools" to gather more data on-demand to answer complex user queries.
The diagram below shows the ReAct loop, including the mechanism for handling timeouts and resuming jobs.
This sequence illustrates the AI insights generation process, including tool use and the timeout/resume mechanism.
Sources: SESSION_COMPLETE.md, COMPLETION_SUMMARY.md, FINAL_REPORT_TASK_COMPLETION.md
Key Aspects:
- Full Historical Context: Before starting the loop,
insights-guru.cjsqueries the database for the actual available data range and can load a 90-day daily rollup with hourly averages to give Gemini comprehensive context. - Tool Calling: Gemini is instructed to use tools like
request_bms_datato query the database for specific date ranges if the initial context is insufficient. It is explicitly forbidden from merely recommending tool use to the user. - Timeout and Resume: For long-running analyses, the synchronous request may time out. The API returns a
408 Timeoutstatus with ajobId. TheclientServiceautomatically retries the request, passing thejobIdto resume the conversation from its last checkpoint. - Format Validation: The final response from Gemini is automatically validated. If a user requested a specific format (like CSV or a Markdown table) and the response is malformed, the system sends a correction prompt back to Gemini to fix the formatting before returning it to the user.
Sources: IMPLEMENTATION_COMPLETE.md, INSIGHTS_TOOL_EXECUTION_ENHANCEMENT.md, FINAL_REPORT_TASK_COMPLETION.md
Admin Data Reconciliation
This flow allows administrators to audit data integrity, specifically to find analysis records associated with a Data Logger ID (DL-#) that are not linked to a registered BMS system.
This diagram shows the process for auditing and reconciling orphaned data logger records.
Sources: DATA_RECONCILIATION_PR_SUMMARY.md
Reconciliation Steps:
- The
ReconciliationDashboard.tsxcomponent calls the/.netlify/functions/admin-data-integrityendpoint. - This function executes a MongoDB aggregation pipeline on the
analysis-resultscollection. - The pipeline groups all records by
dlNumberand checks if a corresponding system exists in thesystemscollection. - It returns a list of all
dlNumbersources, categorized asMATCHED(linked to a system) orORPHAN(not linked). - The frontend displays orphaned sources in a dedicated table, from which an admin can "adopt" the data by creating a new BMS system for it.
Sources: DATA_RECONCILIATION_PR_SUMMARY.md
Summary
BMSview's data architecture is a robust system that balances client-side responsiveness with powerful serverless backend processing. Data flows through distinct, well-defined pathways depending on the task: rapid synchronous analysis for user uploads, flexible historical data aggregation for charting, a sophisticated ReAct loop for AI-powered insights, and an efficient pipeline for administrative data audits. The use of Netlify Functions, MongoDB, and a local-first approach provides a scalable and maintainable foundation for the application's features.