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_recordsevery 5 min as system UUID00000000-0000-0000-0000-000000000001), Cooperativeowner/admin(sending invoice emails via Księga Finansowa), Cooperative members (receiving invoices, generatinggenerate-report), and external services (Resend, QuickChart.io, stubbed Incharge Control API).
2. All Features & End-to-End Flows
- Active 5-Minute SQL Billing Ledger (
fn_calculate_billing_recordsin20261030110000,20261102140000,20261118140000):- Scheduled every 5 min via
pg_cronjob'calculate-billing-records'('*/5 * * * *'), default[now() - 2h, now()). - Floors
p_fromto 5-min boundary -> deletes existingbuilding_id IS NULLrows in window for active-gateway companies -> computes per-point LAG deltas onraw_telemetry(2h lookback, ordered byCOALESCE(device_ts, ts), source_sequence NULLS LAST, excluding invalid,(0,0),SUBMETER, andis_billing_enabled = falsebuildings; skipping gaps> 2h& jumps> 1000 kWh) -> groups into 5-min buckets and insertsbilling_records.
- Scheduled every 5 min via
- Invoice Email Delivery (
send-invoice-email/index.ts— ACTIVE):POST->requireUser+activeRole ∈ {'admin','owner'}-> validatescompany_id,invoice_id,pdf_base64(valid base64,<= 5 MB->413, magic header"%PDF"->400), optionalmessage(<= 2000 chars).- Loads
invoicesscoped to(id, company_id)(404); requiresuser_id(422). Resolves recipient strictly from DB (buyer_snapshot.emailfallbackuser_profiles.email,422if missing; ignoresemail_opt_out). - Sends Zone 1 Planovi HTML email (
emailShell, no unsubscribe link) via Resend withFaktura_${safeNumber}.pdfattachment (502on mail failure). Best-effort updatesinvoices.{emailed_at, emailed_to, emailed_by}(non-fatal warning if columns absent).
- Deprecated / Broken Legacy Edge Functions (Schema Drift to
coop_id/cooperatives):billing-calculator/index.ts: Replaced byfn_calculate_billing_records()after failing since2026-07-16(billing_records.coop_idremoved).generate-monthly-invoices/index.ts: Queries legacycooperatives,user_cooperatives,system_settings.coop_id,invoices.coop_id; computes flawed member settlement math; insertsFV/YYYY-MM/<USER_8>.generate-invoice-pdf/index.ts:validateAuth(no tenant check!) -> queries legacycooperatives& 1 random 5-minbilling_recordsrow -> renders legacy navy/tealpdf-libPDF -> uploads toinvoicesbucket.ai-energy-balancer/index.ts: Rule-based (NO LLM) surplus dispatcher readingraw_telemetry(last 60m), prioritizingenergy_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 (4500mstimeout) -> uploads tocoop_reports-> returns 60s signed URL (400on all errors). Mixescompany_idwith legacycoop_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_recordsaligns buckets todate_bin('5 minutes', eff_ts, '2000-01-01 00:00:00+00')whereeff_ts = COALESCE(device_ts, ts), ordered byeff_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.
- Internal ratio $\alpha = 0.8$; external OSD/TAURON ratio $\beta = 0.6$ (in
BR-BILL-03(IdempotentDELETE + INSERTWindow): Because PostgreSQL unique indexes treatNULLbuilding_idas distinct,fn_calculate_billing_recordsdeletes[v_from, p_to)before re-inserting instead ofON CONFLICT(20261030110000:51-52).BR-BILL-04(Invoice Email Guardrails):send-invoice-email:admin/owneronly (403); PDF<= 5 MB(413) +%PDFheader (400); recipient DB-only (buyer_snapshot.email->user_profiles.email, ignoresemail_opt_out);message <= 2000chars 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; priorityallow_ai_controlfirst, thenenergy_storage (1) -> ev_charger (2) -> heat_pump (3) -> heater (4), thenmax_power_kw DESC.BR-BILL-06(No VAT / No Distribution Fee Math): Neither VAT (23%) nor OSD fee exemptions are implemented ingenerate-monthly-invoicesorgenerate-invoice-pdf(despite"FAKTURA VAT"title).BR-BILL-07(Zone 2 PDF Branding Non-Compliance):generate-invoice-pdfandgenerate-reportviolateBRANDING_GUIDE.md§5.4 (use WinAnsi Helvetica, legacy navy/teal dark headers, no tenant logo/color auto-darkening).send-invoice-emailis Zone 1 compliant.
4. State Machines & Data Lifecycle
invoices.status:'issued'->'partially_paid'->'paid'|'voided'. Email audit overwritesemailed_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 legacybilling-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_cronjob'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,4500mstimeout ingenerate-report), stubbedhttps://incharge.insolve.pl/YOUR_CONTROL_ENDPOINT(ai-energy-balancer).
6. Cross-Repository Dependencies
| Caller -> Callee | Protocol & Auth | Exact Endpoint / Contract |
|---|---|---|
planovi-flutter-app (Księga Finansowa) -> send-invoice-email | HTTPS 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-report | HTTPS POST / User JWT | Polish 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_snapshotpreference: Preserves legal immutability of details frozen at invoice issue time (send-invoice-email/index.ts:92-93).- SQL
fn_calculate_billing_recordsreplacingbilling-calculator: Fixedcoop_idschema break (0 rows written since 2026-07-16) and unifieddevice_tsordering withhourly_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 Message | Root Cause in Code | How to Verify / Exact Query or Log | Fix |
|---|---|---|---|
generate-invoice-pdf or generate-report crashes (500/400) on Polish names; 'ten miesiąc' ignored | Double-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 files | Rewrite files in clean UTF-8 or embed Roboto TTF via @pdf-lib/fontkit |
| Any logged-in user can overwrite/read another company’s invoice PDF | IDOR in generate-invoice-pdf/index.ts: uses validateAuth (any user JWT) + service_role with zero tenant check | Call generate-invoice-pdf with foreign invoice_id | Enforce requireStaff + company_id check or retire legacy function |
billing-calculator, generate-monthly-invoices, ai-energy-balancer leak cross-tenant data or fail | All 3 query gateway_registry/raw_telemetry without tenant filter AND query deleted cooperatives/coop_id columns | Check logs for column "...coop_id" does not exist | Retire 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" suffix | Generate type: "financial" report | Fix unit label to kWh or multiply by tariff |
Replies to emailed invoices go to info@planovi.app instead of the cooperative | send-invoice-email:110 fetches companies.contact_email, email but never passes replyTo to sendEmail() | Inspect send-invoice-email/index.ts:110,145 | Pass `replyTo: company?.contact_email |