Skip to content

13. Energy Cooperative — Financial Ledger, Member Wallet, Billing Engine, Governance, Work Orders & Knowledge Base

Repository: Flutter App (planovi-flutter-app) • Rule Prefix: BR-ECOOP-OPS • Documented Rules: 27 • Open [TEAM_WHY_NEEDED] Questions: 5

1. Business Purpose & Actors

Operational backbone of Polish Energy Cooperatives: (1) 5-minute energy balancing (billing-calculator) & monthly member invoicing (generate-monthly-invoices); (2) Financial Ledger (member_shares, manual/energy invoicing, partial payments, voiding, Polish Excel CSV export) & Member Wallet; (3) Governance Center (digital resolution voting, quorum, attendance, voting protocols); (4) Technician Queue / Helpdesk & Work Orders (helpdesk_tickets + work_orders + SLA); (5) Knowledge Base (company_documents, SHA-256 deduplication, Quill templates, document-linked voting, 1h signed URLs).

  • Actors & RBAC:
    • ledger: Staff (canView/canEdit/canManage/canCreate) vs Member (TenantRole.member, own shares/invoices read-only).
    • wallet: Members & staff (canView, canEdit to initiate 'processing' bank-transfer payment).
    • governance: Members (canView, canEdit to vote); Board/Admin (canCreate, canManage to edit/publish/close/attendance/protocol).
    • technician_queue: Member (canView own reported_by, canCreate); Technician/Admin (canEdit all coop tickets, start/complete/reassign/delete).
    • knowledge_base: Members (canView, canEdit to vote); Admin/Owner/Manager (canCreate/canManage/canDelete).

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

  • Billing Calculator (billing-calculator/index.ts): X-Cron-Secret auth. Loops active cooperatives, queries gateway_registry (limit 1, unfiltered by coop!), reads raw_telemetry since lastRecord + 5m (limit 50k), computes 5-min deltas (skip gaps >2h & deltas >1000 kWh), detects Scenario A (sumXi * 0.8 > sumUi) vs B, inserts aggregate billing_records in 500-row chunks (23505 duplicates skipped).
  • Monthly Invoice Generator (generate-monthly-invoices/index.ts): X-Cron-Secret auth. Computes prior month [start, end) from up to 500k raw_telemetry rows per logical_points.user_id, applies Scenario A/B member settlement formula (energy_price_pln default 1.20), clamps amount_due >= 0, formats FV/YYYY-MM/<8CHAR_USER_ID>, checks duplicate, inserts invoices (status: 'issued', due 14th of next month).
  • Client-Side Invoice PDF & Actions (invoice_pdf_service.dart, invoice_actions_menu.dart): Active PDF engine (pdf + printing + PdfGoogleFonts.roboto* + assets/brand/logo-black.png). Uses frozen seller_snapshot/buyer_snapshot (fallback live tables), renders status stamps (ANULOWANA/OPŁACONA/OPŁACONA CZĘŚCIOWO), payment history, bank details. Menu provides Preview, Download, Send Email (external send-invoice-email with base64 PDF), Payment History, Register Partial/Full Payment (0 < amt <= remaining + 0.005), Payment Reminder (notifications), and Void (issued/draft with amount_paid == 0, reason >= 5 chars). (Legacy generate-invoice-pdf/index.ts using pdf-lib Helvetica ASCII is UNUSED.)
  • Financial Ledger & Member Wallet (financial_ledger_screen.dart, member_wallet_screen.dart, financial_provider.dart, ledger_export_service.dart): 5 parallel queries + isolate KPI computation (compute(_calculateSummaryWorker)) + 4 Realtime channels (2s debounce, 3m stale watchdog). Staff manages Member Shares (share_value=500, registration_fee=0), issues manual invoices (requires seller name/address/email, auto-number via get_coop_id_from_company + next_invoice_number RPCs, NIP checksum), exports Polish Excel CSV (UTF-8 BOM, ;, , decimal). Member Wallet computes 6-state MembershipFinancialState, renders synthetic 24h sine-wave settlement at hardcoded 1.15 PLN/kWh, and allows recording 'processing' bank-transfer payments.
  • Governance Center (governance_center_screen.dart, governance_provider.dart, generate-resolution-document/index.ts): Realtime on resolutions + unfiltered resolution_votes (150ms debounce). 3 tabs (Active, Drafts, Archive). Create inserts directly as active; Vote checks lock/window/duplicate/membership/voter_group (irreversible); Board edits/publishes/manages resolution_attendance/closes (closeResolution ignores quorum!)/generates HTML protocol (generate-resolution-document → guaranteed 400 due to companyId vs coopId mismatch!).
  • Technician Queue & Work Orders (work_order_provider.dart, technician_queue_screen.dart, ticket_dialogs.dart): Paginated helpdesk_tickets + work_orders (50/page, 2 Realtime channels), sorted by priority.weight DESC, createdAt DESC, 4 KPIs, 8 filters, create/edit/delete/assign/start/complete workflows.
  • Knowledge Base (knowledge_base_provider.dart, knowledge_base_screen.dart): Keyset-paginated company_documents (25/page server, 8/page table), upload (pdf/doc/docx/xlsx/csv <= 50 MB, SHA-256 dedupe, ASCII path → governance_documents), links requiresVote uploads to new resolutions row, integrates DocumentEditorScreen & company_templates, caches 1h signed URLs for 55m (max 200 entries).

3. Hard Business Rules (BR-ECOOP-OPS-01..27)

  • BR-ECOOP-OPS-01 (Coefficients & Tariff): α = 0.8, β = 0.6; server default 1.20 PLN/kWh, Wallet estimator hardcoded 1.15 PLN/kWh (billing-calculator:33, generate-monthly-invoices:37-39,156, member_wallet_screen.dart:443).
  • BR-ECOOP-OPS-02 (Scenario A vs B): Server strict ΣXi * 0.8 > ΣUi; Wallet >= (billing-calculator:241, member_wallet_screen.dart:467).
  • BR-ECOOP-OPS-03 (5-Min Delta Guards): INTERVAL_MINUTES = 5, skip gaps > 2h, discard deltas > 1000 kWh, clamp negative to 0 (billing-calculator:34,182-199).
  • BR-ECOOP-OPS-04 (Coop Aggregate Balance): Esp = 0, Etau = ΣXi - ΣUi (4 decimals, 500-row chunks) (billing-calculator:246-263).
  • BR-ECOOP-OPS-05 (Member Monthly Cost — No VAT): adjXi = Xi*0.8, ratio = (ΣXi*0.8)/ΣUi; Scenario A min(adjXi, Ui)*0.8*P - max(adjXi-Ui, 0)*0.6*P; Scenario B adjXi*0.8*P + max(Ui-adjXi, 0)*P; amount_due = max(round(Cost, 2), 0); zero VAT logic (generate-monthly-invoices:270-305).
  • BR-ECOOP-OPS-06 (Client Hourly Billing): Same α=0.8/β=0.6 hourly math in financial_provider.dart:1063-1104.
  • BR-ECOOP-OPS-07 (Invoice Numbering & Due Dates): Auto FV/YYYY-MM/<8CHAR_UID> due 14th next month; Manual RPC next_invoice_number (fallback FV/YYYY/0001), default +14d (generate-monthly-invoices:75,276, financial_ledger_screen.dart:623-636,787).
  • BR-ECOOP-OPS-08 (Voiding Rules): Voided excluded from KPIs; only issued/draft with amount_paid == 0 voidable; reason >= 5 chars (financial_provider.dart:86-88,541-558, invoice_actions_menu.dart:55-59).
  • BR-ECOOP-OPS-09 (Payment Tolerance): Methods {bank_transfer, przelewy24, stripe, cash_adjustment}; 0 < amount <= remaining + 0.005; marks 'paid' when remaining <= 0.005 (0.01 in recordPayment) (financial_provider.dart:493-494,791,811,862).
  • BR-ECOOP-OPS-10 (Seller Completeness & Frozen Snapshots): Manual invoice requires name, address, email; seller_snapshot/buyer_snapshot frozen at issue time (financial_provider.dart:636-705, invoice_pdf_service.dart:68-71).
  • BR-ECOOP-OPS-11 (Buyer NIP Checksum): 10 digits with mod-11 weights [6,5,7,2,3,4,5,6,7]; address >= 5 chars (financial_provider.dart:654-664).
  • BR-ECOOP-OPS-12 (Staff vs Member View Routing): {owner, admin, technician, auditor} → energy_balance_dashboard_view; members/building filter → energy_balance_dashboard_view_by_building (financial_provider.dart:161-162,447-471).
  • BR-ECOOP-OPS-13 (Share Defaults): share_value = 500.00, registration_fee = 0.00, upsert conflict (company_id, user_id) (financial_provider.dart:904).
  • BR-ECOOP-OPS-14 (Polish Excel CSV): UTF-8 BOM, ; delimiter, , decimal, CRLF (ledger_export_service.dart:10-11,111-128).
  • BR-ECOOP-OPS-15 (Wallet State Precedence): rejectedMember > paymentFailed > processing > activeMember > pendingVerification > awaitingPayment (member_wallet_screen.dart:368-418).
  • BR-ECOOP-OPS-16 (Voting Thresholds): Quorum 25–75% (default 50%); passing 50–75% (default 50.01%); approval = yesVotes / totalVotes * 100 (abstains in denominator) (governance_provider.dart:115-116,243-253).
  • BR-ECOOP-OPS-17 (Voting Eligibility & Immutability): Active resolution within [start, end], immutable single vote, active company_members, matching voter_group ∈ {all, owner, admin, member, technician, auditor, viewer} (admin/owner bypass) (governance_provider.dart:509-532).
  • BR-ECOOP-OPS-18 (Quorum Discrepancy): Client closeResolution checks yesPercent >= passingThreshold ONLY (ignores quorum); generate-resolution-document checks quorumReached && approval >= passingThreshold (governance_provider.dart:684-687 vs generate-resolution-document:67-68).
  • BR-ECOOP-OPS-19 (Ending-Soon Threshold): 0 <= remaining <= 24h (governance_provider.dart:831-834).
  • BR-ECOOP-OPS-20 (Work Order Priority): critical(4) > high(3) > medium(2) > low(1); work order status/priority overrides parent ticket (work_order_provider.dart:76-83,157-162,343-347).
  • BR-ECOOP-OPS-21 (Work Order SLA & Validation): Overdue when now > slaDueAt and non-terminal; title >= 3, description >= 10 chars; page size 50 (work_order_provider.dart:191-202,291, ticket_dialogs.dart:120-136).
  • BR-ECOOP-OPS-22 (KB File Limits & Dedupe): pdf/doc/docx/xlsx/csv, <= 50 MB, SHA-256 duplicate block per company_id (knowledge_base_provider.dart:572-596).
  • BR-ECOOP-OPS-23 (KB Category & Path): uchwały↔resolution, regulaminy↔regulation, formularze↔form; uploads start as draft at governance_documents/$companyId/$cat/$year/$month/${ms}_$safeName (knowledge_base_provider.dart:81-88,599-632).
  • BR-ECOOP-OPS-24 (KB URL Cache & Expiry): 1h signed URLs cached 55m (evicted at 200); expiring soon <= 14d (knowledge_base_provider.dart:1089-1139,1237-1243).
  • BR-ECOOP-OPS-25 (KB Sorting & Pagination): Priority ack(0) > vote(1) > expiry(2) > other(3), then createdAt DESC; 25/page server, 8/page UI (knowledge_base_screen.dart:75,1197-1214).
  • BR-ECOOP-OPS-26 (Edge Function Status Codes): 401 (cron secret), 400 (missing params), 404 (invoice not found), 200 (OK/skipped), 500 (including JWT auth errors in generate-invoice-pdf & generate-resolution-document!).
  • BR-ECOOP-OPS-27 (RLS Silent-Block Guard): .select('id') empty-result checks in voidInvoice, saveMemberBilling, archiveDocument, updateTicket, deleteTicket.

4. State Machines & Data Lifecycle

stateDiagram-v2
    [*] --> draft
    draft --> issued: Issue invoice
    draft --> voided: Void (amount_paid == 0)
    issued --> voided: Void (amount_paid == 0)
    issued --> partially_paid: Partial payment
    issued --> paid: Full payment / markPaid
    partially_paid --> paid: Remaining balance paid
  • Resolutions (resolutions.status): draft | review | scheduled → active → passed | rejected (terminal/locked; also completed, archived).
  • Work Orders (helpdesk_tickets/work_orders): new → assigned ↔ in_progress → completed | cancelled (no cancel UI).
  • Knowledge Base (company_documents): draft → approved ↔ archived → soft-deleted (deleted_at).

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

  • Tables & Views: invoices, payments, member_shares, member_wallet_transactions, companies, system_settings, company_members, user_profiles, notifications, billing_records, raw_telemetry, cooperatives, gateway_registry, user_cooperatives, logical_points, resolutions, resolution_votes, resolution_attendance, helpdesk_tickets, work_orders, devices, company_documents, coop_documents (legacy), document_votes, company_templates, document_categories, roles, user_roles; views energy_balance_dashboard_view, energy_balance_dashboard_view_by_building, resolution_results_view.
  • RPCs: get_coop_id_from_company(p_company_id), next_invoice_number(p_coop_id).
  • Storage Buckets: governance_documents (private, 1h signed URLs), invoices (public, legacy generate-invoice-pdf).
  • In-Repo Edge Functions (4): billing-calculator, generate-monthly-invoices (X-Cron-Secret), generate-invoice-pdf (unused), generate-resolution-document (JWT).

6. Cross-Repository Dependencies

Caller -> CalleeProtocol & AuthExact Endpoint / Contract
InvoiceActionsMenu -> External Edge Function send-invoice-email (absent from repo!)HTTPS / User JWT (functions.invoke){company_id, invoice_id, pdf_base64, message?} -> {success: true, sent_to}
External Cron -> billing-calculator (5m) & generate-monthly-invoices (1st 00:05)HTTPS / X-Cron-SecretPOST /functions/v1/billing-calculator, POST /functions/v1/generate-monthly-invoices
External DB Migrations Repo -> Views/RPCs/RLSSQLplanovi_coop_staff_company_ids() (migrations 20261105120000/130000), energy_balance_dashboard_view*, resolution_results_view, resolutions_voter_group_check

7. Why It Works This Way

  • Client-side InvoicePdfService (Roboto Google Fonts) replaced server generate-invoice-pdf (Helvetica WinAnsi) to render Polish diacritics cleanly and keep Ledger & Wallet PDFs identical.
  • Frozen seller_snapshot/buyer_snapshot JSONB columns prevent company/member profile edits from mutating historical invoices.
  • Hardcoded _kVoterGroups works around DB check constraint resolutions_voter_group_check rejecting custom Polish role names like "Zarząd".
  • [TEAM_WHY_NEEDED: Should share_capital and entry_fee invoices be titled "Wezwanie do zapłaty" instead of "Faktura" (invoice_pdf_service.dart:29-30)?]
  • [TEAM_WHY_NEEDED: Are billing-calculator and generate-monthly-invoices still live after the cooperatives/coop_id -> companies/company_id migration, or replaced by another backend repo?]
  • [TEAM_WHY_NEEDED: Why does MemberWalletScreen synthesize a 24h sine-wave energy curve from summary.cooperativeSavings (kWh sum!) at hardcoded 1.15 PLN/kWh instead of reading billing_records/system_settings?]
  • [TEAM_WHY_NEEDED: Why is VAT completely absent from all billing formulas and InvoicePdfService despite legacy generate-invoice-pdf printing "FAKTURA VAT"?]
  • [TEAM_WHY_NEEDED: Is online payment (Przelewy24/Stripe) planned for MemberWalletScreen "Zapłać", and should KnowledgeBaseProvider.acknowledgeDocument() persist to a DB table instead of an in-memory Set?]

8. Debugging, Logs & Common Failure Modes

  • CRITICAL — generate-resolution-document broken contract + Stored XSS + Forgery + IDOR: Expects coopId while Flutter sends companyId (guaranteed 400); inserts into legacy coop_documents instead of company_documents; interpolates unescaped HTML (Stored XSS); trusts client-supplied vote tallies (yesVotes, quorumReached) instead of querying DB; never checks tenant membership/board role.
  • CRITICAL — Cross-tenant billing corruption in billing-calculator & generate-monthly-invoices: Both query gateway_registry.limit(1) without filtering by coop.id — every cooperative is billed against the first active gateway in the entire DB!
  • HIGH — IDOR & public PII exposure in generate-invoice-pdf: Never verifies caller belongs to the invoice’s tenant; uploads invoices to public bucket invoices (getPublicUrl).
  • HIGH — Governance quorum bypass & voter-group miscalculation: GovernanceProvider.closeResolution() ignores quorumReached (marks resolution 'passed' without quorum); _calculateMetrics ignores voterGroup and vote.votingPower; Realtime on resolution_votes has no company_id filter.
  • HIGH — Knowledge Base visibility bypass: _canUserSeeDocument returns true for doc.isArchived before checking visibilityLevel (exposing restricted docs once archived), and compares roles.name against session.currentUserRole enum code (locking custom-role members out).
  • MEDIUM bugs: summary.cooperativeSavings sums coop_export (kWh) yet renders with " PLN" suffix; _EditResolutionSheet cannot clear _votingEndsAt back to null; deleteTicket deletes work_orders before verifying RLS on helpdesk_tickets; WorkOrder.isEscalated hardcoded false (dead Escalated KPI/filter UI); acknowledgeDocument is in-memory only; non-atomic invoice/payment writes; 7 dialog controllers leaked.
  • Log grep: [FIN], [INVOICE_PDF], 🏛️ GOV, 🔒 GOV [CLOSE_VOTE], [TICKET_FORM], 🔗 KB_FETCH, ==== BILLING CALCULATOR START ====.