Skip to content
📦 ARCHIVED SNAPSHOT (v1.0) You are viewing historical business logic and documentation for Flutter App v1.0 (frozen on 2026-11-23, commit 92290cf7). Switch to Latest →

11. Energy Cooperative — Live Dashboard, Telemetry Pipelines, Device Control, AI Balancing, Reports & Tauron CSV

Repository: Flutter App (planovi-flutter-app) • Rule Prefix: BR-ECOOP-TEL • Documented Rules: 20 • Open [TEAM_WHY_NEEDED] Questions: 4

1. Business Purpose & Actors

Powers real-time energy monitoring, settlement analytics, building/converter/device infrastructure management, automated telemetry ingestion/aggregation/retention/alerting pipelines, AI surplus load balancing, Tauron DSO CSV reconciliation, and cooperative PDF/CSV reporting.

  • Actors:
    • Cooperative Admin / Owner (owner, admin): Full energy_devices & energy_balance RBAC; manages buildings, IoT converters (gateway_registry + converters), devices, polling/AI thresholds (system_settings), cross-member filters, and elevated reports (executive, financial, monthly, members).
    • Technician (technician / canEdit('energy_devices')): Edits/controls devices, uploads building photos, assigns devices to buildings, toggles allow_coop_control/allow_ai_control.
    • Auditor (auditor): Read-only access + elevated report permissions (['owner', 'admin', 'auditor']).
    • Cooperative Member (member): Scoped to own buildings (b.clientId == uid || b.companyId == wid), personal share, non-elevated reports (kpi, energy_balance, devices, voting, helpdesk), and contact_requests approval/decline.
    • Machine Actors: Cron (X-Cron-Secret) invoking run-scheduler, ingest-telemetry, aggregate-hourly, aggregate-daily, refresh-live-state, cleanup-telemetry, process-alerts, ai-energy-balancer; Aslandi RP2350 IoT Converters via Nginx mTLS proxy (X-Device-Serial, X-Request-Id) pushing to ingest-telemetry-new; Supabase Storage webhook (X-Webhook-Secret) invoking process-tauron-csv.

2. All Features & End-to-End Flows (Happy Path + Error Paths)

  • Live Energy Dashboard (energy_dashboard_screen.dart): AutomaticKeepAliveClientMixin; clears tenant-scoped caches on activeWorkspaceId switch; runs parallel fetches (DeviceControlProvider, TelemetryProvider, FinancialProvider, TeamCoopProvider, KnowledgeBaseProvider, user_profiles, pending contact_requests, MeetingInvitationsCard, fetch-energy-news). Pull-to-refresh throttled to 15 seconds. Displays Contact Request banners, Grid Flow KPIs, System Health Strip, Savings & Eco Impact (CO₂/trees), Local AI Insights, Share Donut, Stacked Energy Chart (1h/4h/12h/24h/7d), and Enterprise Reports Center (generate-report / export-csv).
  • Energy Balance & Analytics (energy_balance_screen.dart, telemetry_provider.dart):
    • Resolves converter hardware_ids → gateway_registry UUIDs (sentinel _noGateway = 00000000-0000-0000-0000-000000000000 on missing link to prevent coop-wide leak).
    • Hybrid stitching by rangeHours: <= 4h → RPC get_15min_energy; 4–24h → hourly_telemetry_summaries (< startOfToday UTC) + RPC get_hourly_energy (>= startOfToday); > 24h → hourly_telemetry_summaries grouped daily + RPC get_daily_energy overriding today. Realtime INSERT on raw_telemetry (2s debounce, ignored on historical windows < now - 1h).
    • Blocks interactive queries > 90 days with email report dialog. Supports cascading filters (Member → 16 Polish voivodeships → County → Municipality → Building → Status), interactive rate simulator (0.50–3.00 PLN/kWh, 50 steps), Scenario A/B cards, server CSV export, client RepaintBoundary A4 landscape PDF (pixelRatio: 2.0), and paginated (100/page) hourly reconciliation table.
  • Device Monitoring & Infrastructure (my_devices_screen.dart, device_control_provider.dart, infrastructure_provider.dart): 30s periodic silent refresh + Realtime (buildings, converters, devices, 150ms debounce).
    • Buildings CRUD + photo upload (buildings bucket, <= 5 MB) + soft-delete cascade (soft-deletes devices, unassigns converters, soft-deletes building) + embedded BuildingAgreementsSection.
    • Converters: assign (upserts gateway_registry + converters), activate/deactivate (inactive ↔ disabled), soft-delete (gateway_status = 'revoked'). Live _pollConverters calls ingest-telemetry without X-Cron-Secret (broken — 401!).
    • Devices CRUD (0 < max_power_kw <= 1000, 230V/400V), remote On/Off toggle (2s per-device cooldown, DB-only, optimistic with rollback), allow_coop_control/allow_ai_control toggles, paginated device_events_app (15/page) with device_event_acks upsert, and _PollSettingsSheet (system_settings upsert).
  • Backend Pipelines (Edge Functions):
    • ingest-telemetry (legacy InCharge poller, X-Cron-Secret): caches InCharge JWT in Deno KV (5m refresh buffer, 23h TTL), reads global system_settings, polls https://incharge.insolve.pl/sensors/get_readings?module_id=... for all active gateways, maps readings + SHA-256 payload_hash → raw_telemetry; fatal errors write to telemetry_quarantine.
    • ingest-telemetry-new (Aslandi RP2350 mTLS push, X-Device-Serial): POST-only (405), <= 65,536 B (413), forwards to authoritative RPC ingest_telemetry_batch(p_hardware_id, p_payload, p_request_id). Returns 200 on PROCESSED/DUPLICATE/QUARANTINED (firmware clears SD card), 403 on REJECTED (firmware stops retry), 500 on DB error (firmware retries).
    • aggregate-hourly / aggregate-daily (ENERGY_SUPABASE_URL): Rolling 1h raw_telemetry → telemetry_hourly; unbounded telemetry_hourly → telemetry_daily.
    • refresh-live-state (ENERGY_SUPABASE_URL): Unbounded raw_telemetry DESC → latest per logical_point_id → device_live_state (online <= 15m, stale 16–60m, offline > 60m).
    • cleanup-telemetry (ENERGY_SUPABASE_URL): Hard-deletes raw_telemetry > 60d, telemetry_hourly > 180d, telemetry_daily > 730d.
    • process-alerts (ENERGY_SUPABASE_URL): Evaluates device_live_state → inserts system_alerts (offline, stale, voltage_anomaly, power_spike) with zero deduplication.
    • run-scheduler: Reads system_settings & due system_jobs from ENERGY_SUPABASE_URL, dispatches POST ${SUPABASE_URL}/functions/v1/${job.function_name} with X-Cron-Secret and retry/backoff logging to job_execution_logs & job_failures.
    • ai-energy-balancer: Computes 60m surplus per active cooperative (effectiveSurplusKw = prod * surplusFactor - cons), triggers DB-only turn_on (stub hardware call) by priority energy_storage > ev_charger > heat_pump > heater (allow_ai_control first, then max_power_kw DESC), logs surplus_events & device_commands, and runs checkAutoOff after min_device_runtime_minutes.
    • process-tauron-csv (X-Webhook-Secret): Downloads {coop_id}/{import_id}.csv from tauron_csvs, reconciles against legacy device_telemetry, inserts tauron_reconciliation_logs, updates tauron_imports.status (completed/anomalies_detected).
    • generate-report & export-csv: Verify Bearer JWT + company_members existence (no role check!), query cooperative tables (telemetry_logs for energy balance!), call quickchart.io (4.5s timeout) for PDF charts, upload to coop_reports, return 60s signed URL.

3. Hard Business Rules (BR-ECOOP-TEL-01..20)

  • BR-ECOOP-TEL-01 (Coop Billing Formula): α = 0.8, β = 0.6, default price 1.20 PLN/kWh (simulator 0.50–3.00). Per hour: adjXi = Xi * 0.8; if adjXi >= Ui: coopCost += Ui*P*0.8 - (adjXi - Ui)*P*0.6; else coopCost += adjXi*P*0.8 + (Ui - adjXi)*P. Baseline Tauron: Xi >= Ui ? -(Xi-Ui)*P*0.6 : |Xi-Ui|*P. net_savings = tauronCost - coopCost (financial_provider.dart:1063-1104).
  • BR-ECOOP-TEL-02 (Self-Consumption Ratio): clamp(totalConsumption / totalProduction, 0.0, 1.0) (0.0 if totalProduction <= 0) (telemetry_provider.dart:36-41,189-190).
  • BR-ECOOP-TEL-03 (CO₂ & Trees Impact): co2Saved = (dailyProdKwh * 0.4) * (lifetime ? 365 : 1); trees = round(co2Saved / 20) (energy_dashboard_screen.dart:1515-1519).
  • BR-ECOOP-TEL-04 (Telemetry Sanitization): Rejects timestamps > now + 5m; zeroes deltas < 0 or > 2000 kWh; skips gaps > 2h in worker (telemetry_provider.dart:22-34,98-105).
  • BR-ECOOP-TEL-05 (Granularity & 90-Day Cap): <= 4h 15min RPC; 4–24h hourly hybrid; > 24h daily hybrid; interactive max 90 days (telemetry_provider.dart:374-383, energy_balance_screen.dart:50,262-266).
  • BR-ECOOP-TEL-06 (Health Freshness Bands): TelemetryProvider: <=30m healthy, <=4h delayed, >4h offline (per-converter <=60m); refresh-live-state: <=15m online, 16–60m stale, >60m offline; MyDevicesScreen device/converter stale >15m (telemetry_provider.dart:754-822, refresh-live-state/index.ts:97-115, my_devices_screen.dart:83-85,635-636).
  • BR-ECOOP-TEL-07 (Local AI Insights & Battery Bands): High consumption avgCons > avgProd * 1.3; prod drop last4 < prev4 * 0.7; low battery < 20%; battery UI bands >60% green, 26–60% warning, <=25% red (energy_dashboard_screen.dart:1244-1323, my_devices_screen.dart:3449-3453).
  • BR-ECOOP-TEL-08 (Trend Split Rule): Halves chart array; < 2 points, firstHalf == 0, or |diff| < 1.0% → 'stabilny' (energy_dashboard_screen.dart:1204-1242).
  • BR-ECOOP-TEL-09 (Device & Photo Limits): 0 < max_power_kw <= 1000, mains_voltage ∈ {230, 400}, I = (kW * 1000) / V, 2s toggle cooldown, building photo <= 5 MB (my_devices_screen.dart:828-834,2504-2506,3053-3057,4517-4577).
  • BR-ECOOP-TEL-10 (Gateway Status Mapping): gateway_registry.gateway_status ∈ {active, disabled, maintenance, revoked}; app 'inactive' → 'disabled', soft-delete → 'revoked' (infrastructure_provider.dart:23-31,419-433).
  • BR-ECOOP-TEL-11 (Polling Clamp): Disabled → 24h; seconds ∈ [10, 3600], minutes ∈ [1, 60], hours ∈ [1, 24], default 5 min (infrastructure_provider.dart:61-72).
  • BR-ECOOP-TEL-12 (InCharge Normalization): voltage_v = round2(avg(3 phases)), active_power_kw = round4(sum(3 phases W) / 1000), device_ts = "${upload_date}Z", payload_hash = sha256(json) (ingest-telemetry/index.ts:125-162).
  • BR-ECOOP-TEL-13 (RP2350 Push Contract): POST only (405), X-Device-Serial required (400), body <= 65,536 B (413), schema_version = 1, 1..50 meters, numeric address, ISO timestamp; invalid JSON/shape returns 200 QUARANTINED, unknown/disabled 403 REJECTED, DB error 500 (ingest-telemetry-new/index.ts:19-81,89-225).
  • BR-ECOOP-TEL-14 (Retention Windows): raw_telemetry = 60d, telemetry_hourly = 180d, telemetry_daily = 730d (cleanup-telemetry/index.ts:30-113).
  • BR-ECOOP-TEL-15 (Alert Thresholds): offline (critical), stale (medium), voltage_v > 260 || < 180 (voltage_anomaly/high), active_power_kw > 1000 (power_spike/high) (process-alerts/index.ts:48-133).
  • BR-ECOOP-TEL-16 (AI Balancer Rules): 60m valid non-suspect window; <0 kW = prod, >=0 = cons; effectiveSurplus = prod * 0.8 - cons; priority energy_storage(1) > ev_charger(2) > heat_pump(3) > heater(4), allow_ai_control first, max_power_kw DESC; auto-off after 15 min (ai-energy-balancer/index.ts:112-265,373-413).
  • BR-ECOOP-TEL-17 (Tauron CSV Formats): Edge Function expects {coop_id}/{import_id}.csv (; or ,, cols device_id, kwh_produced, date, bucket tauron_csvs <= 50 MB); unused Flutter worker expects ; with >=27 cols (CP/CO + 24 hours) (process-tauron-csv/index.ts:25-63, telemetry_provider.dart:44-64).
  • BR-ECOOP-TEL-18 (Auth & Signed Report TTL): Cron X-Cron-Secret (401), Storage webhook X-Webhook-Secret (401), Reports JWT + company_members (400 on errors, 60s signed URLs; UI restricts elevated reports to owner/admin/auditor).
  • BR-ECOOP-TEL-19 (Helpdesk SLA Report Rules): High-priority avg > 48h → [CRITICAL]; resolved < 24h → % [PERFORMANCE] (generate-report/index.ts:524-536).
  • BR-ECOOP-TEL-20 (UI Health Priority Order): !isActive → offline, lastSeen > 15m → staleTelemetry, open WorkOrder → maintenanceRequired, unack critical → critical, unack warning → warning, else healthy (my_devices_screen.dart).

4. State Machines & Data Lifecycle

stateDiagram-v2
    [*] --> active: Assign converter / register device
    active --> disabled: Pause converter (app: inactive)
    disabled --> active: Reactivate converter
    active --> maintenance: Maintenance mode
    maintenance --> active: Clear maintenance
    active --> revoked: Soft-delete converter (preserves telemetry)
    revoked --> active: Re-assign converter (clears deleted_at)
  • Job Execution (run-scheduler): running → (retrying →)* success | failed (final_failure: true).
  • Live State (device_live_state): online (<= 15m) → stale (16–60m) → offline (> 60m).
  • Tauron Import (tauron_imports): processing → completed | anomalies_detected (failed not implemented on exception!).

5. Technical Contract (Inputs → Processing → Side Effects)

  • Tables & Views: buildings, converters, gateway_registry, devices, companies, cooperatives, company_members, user_profiles, contact_requests, system_settings, logical_points, raw_telemetry, hourly_telemetry_summaries, telemetry_hourly, telemetry_daily, telemetry_logs (legacy), device_telemetry (legacy), telemetry_quarantine, device_live_state, device_health_status (view), device_events, device_events_app (view), device_event_acks, system_alerts, system_jobs, job_execution_logs, job_failures, surplus_events, device_commands, tauron_imports, tauron_reconciliation_logs, billing_records, document_votes, coop_documents, helpdesk_tickets, energy_balance_dashboard_view, energy_balance_dashboard_view_by_building.
  • RPCs: get_15min_energy, get_hourly_energy, get_daily_energy, ingest_telemetry_batch.
  • Storage Buckets: tauron_csvs (private, 50MB, service_role only), coop_reports (60s signed URLs), buildings (public, 5MB), governance_documents.
  • Realtime: buildings-$id, converters-$id, devices:company_id=eq.$id, raw_telemetry_$id.

6. Cross-Repository Dependencies

Caller -> CalleeProtocol & AuthExact Endpoint / Contract
Aslandi RP2350 Firmware -> Nginx mTLS Proxy -> ingest-telemetry-newHTTPS mTLS -> X-Device-Serial, X-Request-IdPOST /functions/v1/ingest-telemetry-new (schema_version: 1, meters[1..50], <=64KB)
ingest-telemetry -> InCharge Cloud APIHTTPS / Bearer JWT (Deno KV cached)POST https://incharge.insolve.pl/sign_in, GET /sensors/get_readings?module_id=...
generate-report -> QuickChart APIHTTPS Public (4.5s timeout)POST https://quickchart.io/chart -> PNG
External Cron / Storage Webhook -> Energy Pipeline EFsHTTPS / X-Cron-Secret or X-Webhook-Secretrun-scheduler, ingest-telemetry, aggregate-*, refresh-live-state, cleanup-telemetry, process-alerts, ai-energy-balancer, process-tauron-csv
External DB Migrations Repo -> SQL RPCs/ViewsSQLDefines ingest_telemetry_batch, get_*_energy, hourly_telemetry_summaries populator, device_events_app, energy_balance_dashboard_view*

7. Why It Works This Way

  • Hybrid stitching (hourly_telemetry_summaries + live RPCs) avoids full-table scans of raw_telemetry for multi-day views without double-counting today.
  • Sentinel _noGateway UUID prevents unlinked converters from dropping the gateway filter and displaying the whole cooperative’s energy.
  • generate-report transliterates Polish characters via sanitize() because pdf-lib Helvetica uses WinAnsiEncoding.
  • [TEAM_WHY_NEEDED: Why do 6 pipeline functions use ENERGY_SUPABASE_URL while ingest-telemetry, ingest-telemetry-new, ai-energy-balancer, process-tauron-csv, and run-scheduler's HTTP dispatch use SUPABASE_URL?]
  • [TEAM_WHY_NEEDED: Why does Flutter TelemetryProvider read hourly_telemetry_summaries while aggregate-hourly/aggregate-daily write telemetry_hourly/telemetry_daily? Which aggregation pipeline is live?]
  • [TEAM_WHY_NEEDED: Has ingest-telemetry-new replaced ingest-telemetry in production, or do InCharge polling and RP2350 push run concurrently?]
  • [TEAM_WHY_NEEDED: What external service uploads to service_role-only bucket tauron_csvs and populates legacy device_telemetry?]

8. Debugging, Logs & Common Failure Modes

  • CRITICAL SECURITY — ingest-telemetry-new unauthenticated spoofing risk: Trusts X-Device-Serial with zero auth (and is absent from supabase/config.toml). Must sit strictly behind Nginx mTLS stripping client headers.
  • CRITICAL — Cross-tenant leak in ai-energy-balancer: ai-energy-balancer/index.ts:125 assigns const gateways = allGateways without filtering by coop — every cooperative computes surplus across ALL tenants’ gateways!
  • CRITICAL — run-scheduler cross-project split: Queries system_jobs on ENERGY_SUPABASE_URL but dispatches HTTP to SUPABASE_URL (run-scheduler/index.ts:194).
  • Triple-divergent system_settings schema & coop_id vs company_id mismatch: Flutter saves company_id + ai_balancing_enabled; ai-energy-balancer reads coop_id + ai_balancer_enabled; run-scheduler reads EAV setting_key/setting_value.
  • Silent 401s on Converter Live Cards: MyDevicesScreen._fetchConverterPreview calls ingest-telemetry without X-Cron-Secret and expects a preview JSON contract neither ingestion function implements.
  • Silent truncation at 1,000 rows (max_rows): refresh-live-state and aggregate-daily execute unbounded SELECT * queries without date filters/pagination, silently dropping devices once rows exceed 1,000.
  • Infinite alert flood & infinite auto-off loop: process-alerts never deduplicates system_alerts; ai-energy-balancer.checkAutoOff never updates turn_on command status so it re-fires turn_off forever; aggregate-hourly uses unaligned millisecond bucket_start.
  • Report RBAC bypass & ignored date filters: generate-report/export-csv never check owner/admin/auditor role server-side; Flutter sends startDate/endDate/reportType while backend reads dateRange/period/type (always exporting default 24h from legacy telemetry_logs).
  • Dashboard 7-day blank chart & static KPIs: Selecting '7 dni' zeroes _hourlyProduction/_hourlyConsumption while _DashboardChartWidget reads them; KPI production/consumption sum rated max_power_kw; _PollSettingsSheet never initializes AI settings from systemSettings and never saves _thresholdPct.
  • Log grep: [InfraProvider], [DeviceProvider], [TEL], ==== TELEMETRY INGESTION START ====, ==== AI ENERGY BALANCER START ====, STARTING SCHEDULER ENGINE.