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,canEditto initiate'processing'bank-transfer payment).governance: Members (canView,canEditto vote); Board/Admin (canCreate,canManageto edit/publish/close/attendance/protocol).technician_queue: Member (canViewownreported_by,canCreate); Technician/Admin (canEditall coop tickets, start/complete/reassign/delete).knowledge_base: Members (canView,canEditto 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-Secretauth. Loops activecooperatives, queriesgateway_registry(limit 1, unfiltered by coop!), readsraw_telemetrysincelastRecord + 5m(limit 50k), computes 5-min deltas (skip gaps>2h& deltas>1000 kWh), detects Scenario A (sumXi * 0.8 > sumUi) vs B, inserts aggregatebilling_recordsin 500-row chunks (23505duplicates skipped). - Monthly Invoice Generator (
generate-monthly-invoices/index.ts):X-Cron-Secretauth. Computes prior month[start, end)from up to 500kraw_telemetryrows perlogical_points.user_id, applies Scenario A/B member settlement formula (energy_price_plndefault1.20), clampsamount_due >= 0, formatsFV/YYYY-MM/<8CHAR_USER_ID>, checks duplicate, insertsinvoices(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 frozenseller_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 (externalsend-invoice-emailwith base64 PDF), Payment History, Register Partial/Full Payment (0 < amt <= remaining + 0.005), Payment Reminder (notifications), and Void (issued/draftwithamount_paid == 0, reason>= 5chars). (Legacygenerate-invoice-pdf/index.tsusingpdf-libHelvetica 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 sellername/address/email, auto-number viaget_coop_id_from_company+next_invoice_numberRPCs, NIP checksum), exports Polish Excel CSV (UTF-8 BOM,;,,decimal). Member Wallet computes 6-stateMembershipFinancialState, renders synthetic 24h sine-wave settlement at hardcoded1.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 onresolutions+ unfilteredresolution_votes(150ms debounce). 3 tabs (Active, Drafts, Archive). Create inserts directly asactive; Vote checks lock/window/duplicate/membership/voter_group(irreversible); Board edits/publishes/managesresolution_attendance/closes (closeResolutionignores quorum!)/generates HTML protocol (generate-resolution-document→ guaranteed 400 due tocompanyIdvscoopIdmismatch!). - Technician Queue & Work Orders (
work_order_provider.dart,technician_queue_screen.dart,ticket_dialogs.dart): Paginatedhelpdesk_tickets+work_orders(50/page, 2 Realtime channels), sorted bypriority.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-paginatedcompany_documents(25/page server, 8/page table), upload (pdf/doc/docx/xlsx/csv <= 50 MB, SHA-256 dedupe, ASCII path →governance_documents), linksrequiresVoteuploads to newresolutionsrow, integratesDocumentEditorScreen&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 default1.20 PLN/kWh, Wallet estimator hardcoded1.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 to0(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 Amin(adjXi, Ui)*0.8*P - max(adjXi-Ui, 0)*0.6*P; Scenario BadjXi*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.6hourly math infinancial_provider.dart:1063-1104. - BR-ECOOP-OPS-07 (Invoice Numbering & Due Dates): Auto
FV/YYYY-MM/<8CHAR_UID>due 14th next month; Manual RPCnext_invoice_number(fallbackFV/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/draftwithamount_paid == 0voidable; reason>= 5chars (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'whenremaining <= 0.005(0.01inrecordPayment) (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_snapshotfrozen 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>= 5chars (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%(default50%); passing50–75%(default50.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, activecompany_members, matchingvoter_group ∈ {all, owner, admin, member, technician, auditor, viewer}(admin/owner bypass) (governance_provider.dart:509-532). - BR-ECOOP-OPS-18 (Quorum Discrepancy): Client
closeResolutionchecksyesPercent >= passingThresholdONLY (ignores quorum);generate-resolution-documentchecksquorumReached && approval >= passingThreshold(governance_provider.dart:684-687vsgenerate-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 > slaDueAtand non-terminal; title>= 3, description>= 10chars; page size50(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 percompany_id(knowledge_base_provider.dart:572-596). - BR-ECOOP-OPS-23 (KB Category & Path):
uchwały↔resolution,regulaminy↔regulation,formularze↔form; uploads start asdraftatgovernance_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), thencreatedAt 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 ingenerate-invoice-pdf&generate-resolution-document!). - BR-ECOOP-OPS-27 (RLS Silent-Block Guard):
.select('id')empty-result checks invoidInvoice,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; alsocompleted,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; viewsenergy_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, legacygenerate-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 -> Callee | Protocol & Auth | Exact 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-Secret | POST /functions/v1/billing-calculator, POST /functions/v1/generate-monthly-invoices |
| External DB Migrations Repo -> Views/RPCs/RLS | SQL | planovi_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(RobotoGoogle Fonts) replaced servergenerate-invoice-pdf(HelveticaWinAnsi) to render Polish diacritics cleanly and keep Ledger & Wallet PDFs identical. - Frozen
seller_snapshot/buyer_snapshotJSONB columns prevent company/member profile edits from mutating historical invoices. - Hardcoded
_kVoterGroupsworks around DB check constraintresolutions_voter_group_checkrejecting 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-documentbroken contract + Stored XSS + Forgery + IDOR: ExpectscoopIdwhile Flutter sendscompanyId(guaranteed 400); inserts into legacycoop_documentsinstead ofcompany_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 querygateway_registry.limit(1)without filtering bycoop.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 bucketinvoices(getPublicUrl). - HIGH — Governance quorum bypass & voter-group miscalculation:
GovernanceProvider.closeResolution()ignoresquorumReached(marks resolution'passed'without quorum);_calculateMetricsignoresvoterGroupandvote.votingPower; Realtime onresolution_voteshas nocompany_idfilter. - HIGH — Knowledge Base visibility bypass:
_canUserSeeDocumentreturnstruefordoc.isArchivedbefore checkingvisibilityLevel(exposing restricted docs once archived), and comparesroles.nameagainstsession.currentUserRoleenum code (locking custom-role members out). - MEDIUM bugs:
summary.cooperativeSavingssumscoop_export(kWh) yet renders with" PLN"suffix;_EditResolutionSheetcannot clear_votingEndsAtback tonull;deleteTicketdeleteswork_ordersbefore verifying RLS onhelpdesk_tickets;WorkOrder.isEscalatedhardcodedfalse(dead Escalated KPI/filter UI);acknowledgeDocumentis 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 ====.