Skip to content

Billing & Invoicing Engine

The Billing & Invoicing Engine manages the financial settlement of renewable energy sharing within Planovi cooperatives, generating legally binding Polish VAT invoices (Faktura VAT) and accounting exports.


Functions Matrix

Function NameInbound TriggerCore ResponsibilityOutput Artifact
billing-calculatorAPI Request / Monthly BatchCalculates energy settlement ledgers & tariffsJSON calculation breakdown
generate-invoice-pdfAPI Request / Batch WorkerRenders vector PDF invoice with QR payment codePDF stored in invoices bucket
generate-monthly-invoicesCron (1st of month 00:00)Orchestrates bulk billing for all cooperative membersInvoices batch run & member notices
export-csvUser Export RequestGenerates accounting CSV for ERP importsCSV download stream
generate-reportUser Request / PeriodicCompiles annual/quarterly energy balance reportsPDF/XLSX summary document

1. Energy Billing Formula & Calculation Engine

Under Polish Renewable Energy Sources (OZE) legislation, energy cooperatives settle power flows based on 1-hour interval balancing between collective generation and individual member consumption:

$$\text{Net Settled Volume} = \sum_{t=1}^{T} \max\left(0, E_{\text{consumed}, t} - \alpha \cdot E_{\text{generated}, t}\right)$$

Where $\alpha$ represents the member’s proportional cooperative share factor.

billing-calculator Logic

flowchart TD
    Start[Invoke billing-calculator] --> FetchTariff[Fetch Cooperative Tariff Matrix]
    FetchTariff --> FetchAgg[Query telemetry_daily for Billing Window]
    FetchAgg --> ApplyBalancing[Apply Hourly Net Balancing Formula]
    ApplyBalancing --> CalculateCharges[Compute Energy Cost + Grid Distribution Fee]
    CalculateCharges --> ApplyDiscounts[Apply Cooperative Self-Consumption Rebate]
    ApplyDiscounts --> CalculateVAT[Compute 23% VAT Rate]
    CalculateVAT --> ReturnPayload[Return Structured Financial Ledger]

Response Schema

{
"member_id": "9f8e7d6c-5b4a-3f2e-1d0c-9a8b7c6d5e4f",
"billing_period": {
"start": "2026-08-01T00:00:00Z",
"end": "2026-08-31T23:59:59Z"
},
"metrics": {
"total_consumed_kwh": 340.5,
"coop_covered_kwh": 260.0,
"grid_billed_kwh": 80.5
},
"financials": {
"net_amount_pln": 185.40,
"vat_rate_pct": 23,
"vat_amount_pln": 42.64,
"gross_amount_pln": 228.04,
"coop_savings_pln": 143.20
}
}

2. generate-invoice-pdf

Renders an enterprise-grade Polish tax invoice compliant with Polish Ministry of Finance regulations (Ustawa o podatku od towarów i usług).

Technical Pipeline

  1. Font Loading: Injects Latin-Extended fonts (Roboto / Inter) into the Deno PDF rendering engine to ensure flawless rendering of Polish diacritics (ą, ć, ę, ł, ń, ó, ś, ź, ż).
  2. Dynamic QR Code Generation: Generates an EPC-standard QR code / Polish BLIK transfer string embedding:
    • Beneficiary Account Number (IBAN).
    • Cooperative Recipient Name.
    • Invoice Number (FV/YYYY/MM/{sequential_id}).
    • Exact Gross Amount in PLN.
  3. Storage Persistence: Uploads binary PDF into Supabase Storage bucket invoices/{coop_id}/{year}/{invoice_id}.pdf.
  4. Signed URL Dispatch: Returns a signed, time-limited URL for secure previewing in the mobile app.

3. generate-monthly-invoices

End-of-Month Batch Processing Workflow

sequenceDiagram
    autonumber
    participant Cron as "Supabase Cron (1st of month)"
    participant Batch as generate-monthly-invoices
    participant Calc as billing-calculator
    participant PDF as generate-invoice-pdf
    participant Mail as send-notification

    Cron->>Batch: Trigger Batch Job (target_month = "YYYY-MM")
    Batch->>Batch: Lock cooperative billing ledger to prevent duplicate runs
    loop For Every Active Member in Cooperative
        Batch->>Calc: Compute member balance
        Calc-->>Batch: Calculation results
        Batch->>PDF: Generate invoice document
        PDF-->>Batch: Invoice PDF URL & Storage Reference
        Batch->>Batch: Insert record into `invoices` table
        Batch->>Mail: Queue email with attached PDF
    end
    Batch->>Batch: Release ledger lock & update status to "COMPLETED"

4. export-csv & generate-report

Accounting System Compatibility

export-csv generates delimited exports configured for Polish accounting software:

  • Comarch ERP Optima / InsERT Subiekt GT / nexo / Symfonia.
  • Standard character encoding: UTF-8 with BOM or Windows-1250.
  • Format fields: Invoice Date, Sale Date, Member NIP/PESEL, Net Value, VAT Rate, VAT Amount, Gross Total, Split Payment indicator (Mechanizm Podzielonej Płatności - MPP).