Skip to content
📦 ARCHIVED SNAPSHOT (v1.0) You are viewing historical business logic and documentation for Backend (Edge Functions) v1.0 (frozen on 2026-11-23, commit f026e3b). Switch to Latest →

5. Cooperative Energy Billing, Invoicing & AI Energy Balancing

Repository: Backend (planovi-backend) • Rule Prefix: BR-BILL • Documented Rules: 7 • Open [TEAM_WHY_NEEDED] Questions: 3

1. Business Purpose & Actors

Computes 5-minute cooperative energy balances (Zasady Bilansowania Scenario A vs B) in billing_records, delivers client-generated invoice PDFs via Resend (send-invoice-email), and houses 5 legacy/pre-company_id-migration functions (billing-calculator, generate-monthly-invoices, generate-invoice-pdf, ai-energy-balancer, generate-report).

  • Actors: pg_cron (fn_calculate_billing_records every 5 min as system UUID 00000000-0000-0000-0000-000000000001), Cooperative owner/admin (sending invoice emails via Księga Finansowa), Cooperative members (receiving invoices, generating generate-report), and external services (Resend, QuickChart.io, stubbed Incharge Control API).

2. All Features & End-to-End Flows

  1. Active 5-Minute SQL Billing Ledger (fn_calculate_billing_records in 20261030110000, 20261102140000, 20261118140000):
    • Scheduled every 5 min via pg_cron job 'calculate-billing-records' ('*/5 * * * *'), default [now() - 2h, now()).
    • Floors p_from to 5-min boundary -> deletes existing building_id IS NULL rows in window for active-gateway companies -> computes per-point LAG deltas on raw_telemetry (2h lookback, ordered by COALESCE(device_ts, ts), source_sequence NULLS LAST, excluding invalid, (0,0), SUBMETER, and is_billing_enabled = false buildings; skipping gaps > 2h & jumps > 1000 kWh) -> groups into 5-min buckets and inserts billing_records.
  2. Invoice Email Delivery (send-invoice-email/index.ts — ACTIVE):
    • POST -> requireUser + activeRole ∈ {'admin','owner'} -> validates company_id, invoice_id, pdf_base64 (valid base64, <= 5 MB -> 413, magic header "%PDF" -> 400), optional message (<= 2000 chars).
    • Loads invoices scoped to (id, company_id) (404); requires user_id (422). Resolves recipient strictly from DB (buyer_snapshot.email fallback user_profiles.email, 422 if missing; ignores email_opt_out).
    • Sends Zone 1 Planovi HTML email (emailShell, no unsubscribe link) via Resend with Faktura_${safeNumber}.pdf attachment (502 on mail failure). Best-effort updates invoices.{emailed_at, emailed_to, emailed_by} (non-fatal warning if columns absent).
  3. Deprecated / Broken Legacy Edge Functions (Schema Drift to coop_id/cooperatives):
    • billing-calculator/index.ts: Replaced by fn_calculate_billing_records() after failing since 2026-07-16 (billing_records.coop_id removed).
    • generate-monthly-invoices/index.ts: Queries legacy cooperatives, user_cooperatives, system_settings.coop_id, invoices.coop_id; computes flawed member settlement math; inserts FV/YYYY-MM/<USER_8>.
    • generate-invoice-pdf/index.ts: validateAuth (no tenant check!) -> queries legacy cooperatives & 1 random 5-min billing_records row -> renders legacy navy/teal pdf-lib PDF -> uploads to invoices bucket.
    • ai-energy-balancer/index.ts: Rule-based (NO LLM) surplus dispatcher reading raw_telemetry (last 60m), prioritizing energy_storage -> ev_charger -> heat_pump -> heater, with stubbed hardware control and broken auto-off loop.
    • generate-report/index.ts: User JWT + company_members -> renders 8 report types (executive, financial, kpi, members, devices, voting, helpdesk, energy_balance) with QuickChart.io PNGs (4500ms timeout) -> uploads to coop_reports -> returns 60s signed URL (400 on all errors). Mixes company_id with legacy coop_id/telemetry_logs.

3. Hard Business Rules, Validations, Calculations & Edge Cases (BR-BILL)

  • BR-BILL-01 (5-Min Epoch Alignment & Replay Order): fn_calculate_billing_records aligns buckets to date_bin('5 minutes', eff_ts, '2000-01-01 00:00:00+00') where eff_ts = COALESCE(device_ts, ts), ordered by eff_ts, source_sequence NULLS LAST.
  • BR-BILL-02 (Cooperative Balancing Ratios & Scenarios):
    • Internal ratio $\alpha = 0.8$; external OSD/TAURON ratio $\beta = 0.6$ (in generate-monthly-invoices).
    • Scenario 'A' (Surplus): $\sum X_i \times 0.8 > \sum U_i$; else Scenario 'B' (Deficit).
    • In billing_records: raw_production_kw = round(sum(x), 4) (kWh), raw_consumption_kw = round(sum(u), 4) (kWh), e_sp_internal_balance = 0, e_tau_external_settlement = round(sum(x) - sum(u), 4), building_id = NULL.
  • BR-BILL-03 (Idempotent DELETE + INSERT Window): Because PostgreSQL unique indexes treat NULL building_id as distinct, fn_calculate_billing_records deletes [v_from, p_to) before re-inserting instead of ON CONFLICT (20261030110000:51-52).
  • BR-BILL-04 (Invoice Email Guardrails): send-invoice-email: admin/owner only (403); PDF <= 5 MB (413) + %PDF header (400); recipient DB-only (buyer_snapshot.email -> user_profiles.email, ignores email_opt_out); message <= 2000 chars HTML-escaped; remaining = max(0, amount_due - amount_paid).
  • BR-BILL-05 (AI Balancer Heuristics): ai-energy-balancer: default settings { ai_balancer_enabled: true, surplus_factor: 0.8, min_device_runtime_minutes: 15, surplus_threshold_kw: null }; active_power_kw < 0 = production; effectiveSurplusKw = totalProductionKw * surplusFactor - totalConsumptionKw; priority allow_ai_control first, then energy_storage (1) -> ev_charger (2) -> heat_pump (3) -> heater (4), then max_power_kw DESC.
  • BR-BILL-06 (No VAT / No Distribution Fee Math): Neither VAT (23%) nor OSD fee exemptions are implemented in generate-monthly-invoices or generate-invoice-pdf (despite "FAKTURA VAT" title).
  • BR-BILL-07 (Zone 2 PDF Branding Non-Compliance): generate-invoice-pdf and generate-report violate BRANDING_GUIDE.md §5.4 (use WinAnsi Helvetica, legacy navy/teal dark headers, no tenant logo/color auto-darkening). send-invoice-email is Zone 1 compliant.

4. State Machines & Data Lifecycle

  • invoices.status: 'issued' -> 'partially_paid' -> 'paid' | 'voided'. Email audit overwrites emailed_at, emailed_to, emailed_by.
  • billing_records (building_id IS NULL): Recomputed every 5 min within trailing 2h; immutable thereafter unless manually backfilled. Scenario: 'A' | 'B'.
  • surplus_events.status: Inserted as 'active' and never transitioned to closed. device_commands.status: 'sent' (auto-control stub / auto-off) | 'skipped' (manual notify only).

5. Technical Contract

  • Endpoints: send-invoice-email (active), plus legacy billing-calculator, generate-monthly-invoices, generate-invoice-pdf, ai-energy-balancer, generate-report.
  • SQL Objects: public.fn_calculate_billing_records(p_from, p_to) (SECURITY DEFINER, service-role/cron only), pg_cron job 'calculate-billing-records' ('*/5 * * * *'), public.backup_billing_records_2026_10_30.
  • Storage Buckets: invoices (generate-invoice-pdf, tracked in storage quota), coop_reports (generate-report, 60s signed URL, tracked in storage quota).
  • External APIs: Resend (send-invoice-email), QuickChart.io (POST https://quickchart.io/chart, 4500ms timeout in generate-report), stubbed https://incharge.insolve.pl/YOUR_CONTROL_ENDPOINT (ai-energy-balancer).

6. Cross-Repository Dependencies

Caller -> CalleeProtocol & AuthExact Endpoint / Contract
planovi-flutter-app (Księga Finansowa) -> send-invoice-emailHTTPS POST / User JWT (admin/owner)Sends client-generated pdf_base64 (<=5 MB)
planovi-flutter-app (Raport Godzinowy / Bilans) -> energy_balance_dashboard_view[_by_building]PostgREST / User JWT (SECURITY INVOKER)Reads billing_records populated by fn_calculate_billing_records
planovi-flutter-app -> generate-reportHTTPS POST / User JWTPolish dateRange ('24 godziny', 'ten miesiąc') + granularity -> 60s signed PDF URL

7. Why It Works This Way

  • Client-generated PDF passed to send-invoice-email: Guarantees the emailed invoice is byte-for-byte identical to Flutter Podgląd / Pobierz PDF (send-invoice-email/index.ts:4-5).
  • buyer_snapshot/seller_snapshot preference: Preserves legal immutability of details frozen at invoice issue time (send-invoice-email/index.ts:92-93).
  • SQL fn_calculate_billing_records replacing billing-calculator: Fixed coop_id schema break (0 rows written since 2026-07-16) and unified device_ts ordering with hourly_telemetry_summaries.
  • [TEAM_WHY_NEEDED: Are billing-calculator, generate-monthly-invoices, generate-invoice-pdf, ai-energy-balancer, and generate-report abandoned pre-company_id code awaiting deletion or still invoked anywhere?]
  • [TEAM_WHY_NEEDED: Why does generate-monthly-invoices double-apply ALPHA (0.8), charge pure consumers 0 PLN in Scenario A, clamp credits to 0 PLN, and omit VAT?]
  • [TEAM_WHY_NEEDED: Should send-invoice-email check RBAC ledger.invoices|UPDATE instead of hardcoded admin/owner, and pass companies.contact_email as replyTo (which it already SELECTs at line 110)?]

8. Debugging, Logs & Common Failure Modes

Symptom / Error MessageRoot Cause in CodeHow to Verify / Exact Query or LogFix
generate-invoice-pdf or generate-report crashes (500/400) on Polish names; 'ten miesiąc' ignoredDouble-encoded UTF-8 mojibake (Ä„ instead of Ą) breaks pl()/sanitize() WinAnsi strippers and case 'ten miesiÄ…c': (generate-invoice-pdf:17-28, generate-report:18-30,599)Inspect raw bytes with xxd on those filesRewrite files in clean UTF-8 or embed Roboto TTF via @pdf-lib/fontkit
Any logged-in user can overwrite/read another company’s invoice PDFIDOR in generate-invoice-pdf/index.ts: uses validateAuth (any user JWT) + service_role with zero tenant checkCall generate-invoice-pdf with foreign invoice_idEnforce requireStaff + company_id check or retire legacy function
billing-calculator, generate-monthly-invoices, ai-energy-balancer leak cross-tenant data or failAll 3 query gateway_registry/raw_telemetry without tenant filter AND query deleted cooperatives/coop_id columnsCheck logs for column "...coop_id" does not existRetire billing-calculator (replaced by SQL); refactor or delete remaining 4 legacy functions
ai-energy-balancer spams endless turn_off rows & fails empty .update({})checkAutoOff (ai-energy-balancer:368-408) never marks prior turn_on rows closed; lines 303-306 call .update({})SELECT command, status, count(*) FROM device_commands GROUP BY 1,2;Track closed state on turn_on / check current device state before emitting turn_off
generate-report prints kWh labeled as "PLN"generate-report:200-202 prints e_tau_external_settlement (kWh) under "KOSZT/ZYSK TAURON" with "PLN" suffixGenerate type: "financial" reportFix unit label to kWh or multiply by tariff
Replies to emailed invoices go to info@planovi.app instead of the cooperativesend-invoice-email:110 fetches companies.contact_email, email but never passes replyTo to sendEmail()Inspect send-invoice-email/index.ts:110,145Pass `replyTo: company?.contact_email