Skip to content
📦 ARCHIVED SNAPSHOT (v1.0) You are viewing historical business logic and documentation for Flutter App v1.0 (frozen on 2026-11-23, commit 92290cf7). Switch to Latest →

12. Energy Cooperative — Member Onboarding, Declarations OCR, Building Agreements & Portal Access

Repository: Flutter App (planovi-flutter-app) • Rule Prefix: BR-ECOOP-ONB • Documented Rules: 28 • Open [TEAM_WHY_NEEDED] Questions: 3

1. Business Purpose & Actors

Orchestrates new member onboarding into Polish Energy Cooperatives: declaration template upload & Gemini OCR extraction, multi-step dynamic form/field schema authoring (with rich HTML labels and calculated fee fields), 72-hour tokenized Hostinger PHP web declaration delivery, public declaration submission & Gemini-patched DOCX confirmation, board review/correction/rejection & portal provisioning (company_members), TAURON OSD Annex 1 (Odbiorca) / 1a (Wytwórca OZE) agreements with handwritten SignaturePad + PDF/DOCX export, 1-year retention member removal/restoration, cooperative settings, and real-time in-app notifications.

  • Actors:
    • Cooperative Admin / Board / Owner: team_declarations:MANAGE or isAdminOrOwner; CoopSettingsScreen requires config:VIEW || settings:MANAGE (blocked for TenantRole.member).
    • Board Signatories (up to 2): Configured in companies.board_signatories (default role 'Członek Zarządu'), cosign TAURON agreements via SignaturePad.
    • Prospective Member (Public/Unauthenticated): Receives 72h tokenized link (FORM_BASE_URL?token=<token>), submits answers on Hostinger offer.php → submit-member-declaration, or unsubscribes via unsubscribe?token=....
    • Active Cooperative Member: Provisioned via grant-portal-access; signs own building’s TAURON applications (sign_building_agreement RPC), views notifications, subject to GDPR peer contact masking (•••••••••) unless contact_requests.status == 'approved'.

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

  • Flow 1 — Template Upload & Gemini OCR (team_declarations_screen.dart, process-declaration-ocr/index.ts): Admin uploads .docx/.pdf (<= 10.0 MB) directly to declaration-templates/{companyId}/{ts}.{ext} (ASCII-only), inserts active row in declaration_templates (without deactivating other active templates), invokes process-declaration-ocr. Backend downloads file, sends PDF bytes as multimodal inlineData (chunked 8192B base64) or DOCX via mammoth.extractRawText (>= 10 chars) to gemini-2.5-flash with strict reading-order prompt, deletes prior created_from_ocr = true fields, inserts ordered declaration_fields. OCR failure leaves template active with 0 fields for manual editing.
  • Flow 2 — Schema, Steps & Rich HTML Labels (team_declarations_screen.dart, declaration_rich_label_editor.dart, declaration_label_html.dart): CRUD on declaration_steps (≥1 step required; AI grouping via external suggest-declaration-steps + RPC apply_declaration_steps), field types (text, textarea, number, date, boolean, signature, declaration, calculated, info), Quill rich-label editor (allowlist p, br, b, i, u, a[href], ul, ol, li; https:///mailto: only; plain label <= 500 chars), HTTPS-only preview_url (<= 2048 chars), drag-and-drop & multi-select step moves, form preview via external create-form-preview.
  • Flow 3 — Member Invitation & Hostinger Sync (send-onboarding-invitation/index.ts): Validates JWT + active company_members, checks email regex, blocks users already filled or email_opt_out, creates Auth user + user_profiles (rolls back Auth user if profile upsert fails), reuses/creates onboarding_sessions (started) & 72h onboarding_tokens, POSTs {token, data: formJson} to HOSTINGER_WRITER_URL (X-Api-Secret: DEALFLOW_API_SECRET, non-fatal warning on failure), sends Resend invitation email.
  • Flow 4 — Public Declaration Submission & AI-Patched DOCX (submit-member-declaration/index.ts): IP rate limit 10 req / 15 min (Deno KV → 429), validates token (401 missing, 409 ALREADY_SUBMITTED if used_at set, sets expired if past expires_at), enforces field.company_id === companyId & required fields, replaces user_metadata, sets user_profiles.onboarding_status = 'filled' + is_energy_coop_member = true, onboarding_sessions = 'review_pending', marks used_at. Non-fatal handleEmails: prompts gemini-2.5-flash for {find, replace} pairs, patches word/document.xml via PizZip, emails member (+ DOCX attachment) and ADMIN_NOTIFICATION_EMAIL.
  • Flow 5 — Board Editing & Template Migration: Primary web edit via external create-admin-edit-link; fallback in-panel dialog uploads signatures to company-media/{companyId}/signatures/... and invokes update-member-declaration (local repo EF is stale v1!). Template switch invokes external change-declaration-template + optional correction request.
  • Flow 6 — Review, Notices & Portal Access: Flutter directly inserts member_declaration_reviews and updates onboarding_sessions (completed/rejected), then invokes grant-portal-access (idempotent company_members insert on 23505, sets onboarding_status = 'approved', emails PORTAL_URL — errors swallowed in UI!), send-correction-request-notice, or send-rejection-notice (errors swallowed in UI!).
  • Flow 7 — Prefilled DOCX Generation (generate-prefilled-docx/index.ts): Local v1 uses PizZip + Docxtemplater (YES/NO booleans) and uploads to public declaration-templates/{companyId}/generated/{uuid}.docx; Flutter expects v2 with session_id and action: 'sign' for 1h signed URLs.
  • Flow 8 — TAURON Annex 1 (Odbiorca) & 1a (Wytwórca OZE) Agreements (building_agreement_*.dart, signature_pad.dart): Collects coop/member/building/device data (RES Act classification <=50 kW mikro, <=1000 kW mala, >1000 kW koncesja; strips *@deleted.local emails), renders bundled DOCX (assets/agreements/zalacznik_1*.docx) or Roboto PDF (BuildingAgreementPdf), supports draft → sent (external send-agreement-email) → member signs (SignaturePad 960×360 PNG → RPC sign_building_agreement) → up to 2 board signatures (completed) OR paper scan upload (<= 15 MB to governance_documents, 1h signed URL → uploaded).
  • Flow 9 — Member Removal Cascade (coop_member_removal_service.dart): Ordinary members only (admins/owners blocked); reason >= 3 chars → RPC remove_coop_member writes 1-year snapshot in coop_member_removals; restorable via restore_coop_member; purged by pg_cron purge_expired_coop_members.
  • Flow 10 — Coop Settings & Notification Center (coop_settings_screen.dart, notification_center_provider.dart): Edits companies (NIP mod-11 checksum, 10-digit KRS, board_signatories, RLS 0-row check), system_settings (share_value=500, registration_fee=0), document_categories; AI/Telemetry toggles are unpersisted UI stubs (Future.delayed(600ms)). NotificationCenterProvider loads top 100 company-scoped notifications with Realtime (120ms debounce) and optimistic read/read-all.

3. Hard Business Rules (BR-ECOOP-ONB-01..28)

  • BR-ECOOP-ONB-01 (Template Upload): .docx/.pdf only, <= 10.0 MB, ASCII key "{companyId}/{ts}.{ext}" (team_declarations_screen.dart:3108-3153).
  • BR-ECOOP-ONB-02 (Multiple Concurrent Active Templates): Uploading/activating a template MUST NOT deactivate other active templates (team_declarations_screen.dart:3181-3183).
  • BR-ECOOP-ONB-03 (OCR Model & Reading Order): gemini-2.5-flash; PDF sent as chunked-8192B inlineData; DOCX requires >= 10 extracted chars; re-runs replace created_from_ocr = true only (process-declaration-ocr/index.ts:47-65,177-231).
  • BR-ECOOP-ONB-04 (Rich Label & Preview URL Security): HTML allowlist p, br, b, i, u, a[href], ul, ol, li; https:///mailto: only; plain label <= 500 chars; preview_url strict HTTPS domain <= 2048 chars, no IP/localhost/userinfo (declaration_label_html.dart:8-33).
  • BR-ECOOP-ONB-05 (Info & Calculated Fields): info never required, always user visibility, excluded from completion; calculated multiplies source_field by share_value/registration_fee (team_declarations_screen.dart:420-444).
  • BR-ECOOP-ONB-06 (Step Invariants): >= 1 step required; title <= 200, description <= 2000 chars (team_declarations_screen.dart:3526,3534,3783-3785).
  • BR-ECOOP-ONB-07 (Invitation Guards): Rejects already filled or email_opt_out profiles; invited_by derived from JWT user.id (send-onboarding-invitation/index.ts:88-158).
  • BR-ECOOP-ONB-08 (Auth User Rollback): Deletes newly created Auth user if user_profiles upsert fails (send-onboarding-invitation/index.ts:192-198).
  • BR-ECOOP-ONB-09 (72h Token TTL & Single-Use): 72h expiry; reuses unused unexpired token for same session; used_at != null → HTTP 409 already_submitted: true; expired sets onboarding_status = 'expired' (send-onboarding-invitation:238, submit-member-declaration).
  • BR-ECOOP-ONB-10 (Submission Rate Limit): 10 req / 15 min / IP via Deno KV → HTTP 429 (submit-member-declaration/index.ts:17-39,53-60).
  • BR-ECOOP-ONB-11 (Submission Company Isolation): body.token mandatory (401); rejects fields where field.company_id !== companyId or missing is_required (submit-member-declaration/index.ts:70-76,142-145).
  • BR-ECOOP-ONB-12 (Client Value Validation): Validates number, date (YYYY-MM-DD/DD.MM.YYYY), email, phone (>=7 digits); no PESEL/NIP/PPE checksum in declaration fields (team_declarations_screen.dart:2200-2245).
  • BR-ECOOP-ONB-13 (Resubmission Override): review_pending with onboarding_completed_at > lastDecisionAt resets isDecided = false (team_coop_provider.dart:648-655).
  • BR-ECOOP-ONB-14 (Portal Access Idempotency): grant-portal-access treats Postgres 23505 on company_members insert as success (grant-portal-access/index.ts:98-113).
  • BR-ECOOP-ONB-15 (Email Opt-Out): All 4 onboarding notice EFs skip Resend when email_opt_out === true; unsubscribe queries onboarding_tokens.token (400/404/200).
  • BR-ECOOP-ONB-16 (GDPR Contact Masking): Masks non-admin peer email/phone as "•••••••••" unless contact_requests.status = 'approved' (team_declarations_screen.dart:162,7283-7315).
  • BR-ECOOP-ONB-17 (TAURON RES Thresholds): pv_installation + biogas_plant: <= 50 kW → 'mikro', <= 1000 kW → 'mala', > 1000 kW → 'koncesja' (building_agreement_service.dart:273-304).
  • BR-ECOOP-ONB-18 (Building Agreement Signatories): Requires building.clientId; max 2 board signatures (FIFO eviction, same-name replace); member sign via sign_building_agreement RPC (building_agreement_service.dart:414).
  • BR-ECOOP-ONB-19 (Paper Scan Limits): pdf/jpg/jpeg/png, <= 15 MB, governance_documents bucket, 3600s signed URL (building_agreements_section.dart:380-390).
  • BR-ECOOP-ONB-20 (Cancel vs Delete): draft hard-deleted; all other statuses soft-cancelled (status = 'cancelled') (building_agreement_service.dart:467-476).
  • BR-ECOOP-ONB-21 (Removal Retention): Non-admin/non-owner only; reason >= 3 chars; 1-year retention in coop_member_removals (team_declarations_screen.dart:2601,5061).
  • BR-ECOOP-ONB-22 (Company Data Validations): NIP mod-11 ([6,5,7,2,3,4,5,6,7]), 10-digit KRS, address >= 5 chars, email regex, .select('id') RLS guard (coop_settings_screen.dart:218-220,293-295,352-405).
  • BR-ECOOP-ONB-23 (Financial Defaults): share_value = 500.0 PLN, registration_fee = 0.0 PLN (team_coop_provider.dart:107-108).
  • BR-ECOOP-ONB-24 (SignaturePad): 480×180 logical (960×360 PNG at 2×), ≥1 stroke with ≥2 points (signature_pad.dart:35-57).
  • BR-ECOOP-ONB-25 (Anonymized Email Suppression): Suppresses *@deleted.local on TAURON forms (building_agreement_service.dart:236).
  • BR-ECOOP-ONB-26 (Notification Scoping): Top 100 scoped to (company_id, recipient_user_id); Realtime filters _currentCompanyId (notification_center_provider.dart:259-266,428).
  • BR-ECOOP-ONB-27 (Pagination & Debounce): company_members 50/page, Realtime 600ms, search 280ms, notifications 120ms (team_coop_provider.dart:524,1684).
  • BR-ECOOP-ONB-28 (Legacy EF Error Status): Most onboarding EFs return HTTP 500 for auth/validation errors except submit-member-declaration (401/409/429/500) and unsubscribe (400/404/500).

4. State Machines & Data Lifecycle

stateDiagram-v2
    [*] --> started: send-onboarding-invitation (72h token)
    started --> review_pending: submit-member-declaration (token used_at set)
    review_pending --> completed: Admin approves -> grant-portal-access
    review_pending --> rejected: Admin rejects -> send-rejection-notice
    review_pending --> review_pending: correction_required / resubmission overrides isDecided
    started --> archived: Admin archives (deletes tokens)
    archived --> started: Admin restores
  • Building Agreements (building_agreements.status): draft → (delete = hard delete | sendForSignature → sent → memberSign → member_signed → coopSign → completed | uploadScan → uploaded | cancel → cancelled).

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

  • Tables: declaration_templates, declaration_steps, declaration_fields, ocr_extraction_sessions, ocr_extracted_fields, onboarding_sessions, onboarding_tokens, user_metadata, member_declaration_reviews, user_profiles, company_members, companies, system_settings, contact_requests, building_agreements, coop_member_removals, document_categories, notifications.
  • RPCs: apply_declaration_steps, get_coop_id_from_company, sign_building_agreement, remove_coop_member, restore_coop_member (+ pg_cron purge_expired_coop_members).
  • Storage & Assets: declaration-templates, declaration-documents (v2), governance_documents, company-media (signatures); assets/agreements/zalacznik_1_odbiorca.docx, zalacznik_1a_wytworca.docx, assets/brand/logo-black.png.
  • In-Repo Edge Functions (15): upload-declaration, process-declaration-ocr, approve-declaration-schema, get-company-declaration-schema, get-member-declaration, submit-member-declaration, update-member-declaration, review-member-declaration, member-onboarding-status, send-onboarding-invitation, send-correction-request-notice, send-rejection-notice, grant-portal-access, generate-prefilled-docx, unsubscribe (all use ENERGY_SUPABASE_URL + ENERGY_SUPABASE_SERVICE_ROLE_KEY).

6. Cross-Repository Dependencies

Caller -> CalleeProtocol & AuthExact Endpoint / Contract
send-onboarding-invitation -> Hostinger PHP (form-writer.php)HTTPS / X-Api-Secret: DEALFLOW_API_SECRETPOST ${HOSTINGER_WRITER_URL} {token, data: formJson}
Hostinger PHP (offer.php) -> submit-member-declarationHTTPS Public (body.token)POST /functions/v1/submit-member-declaration
TeamDeclarationsScreen / BuildingAgreementService -> 5 External Edge Functions (absent from repo!)HTTPS / User JWTcreate-admin-edit-link, create-form-preview, suggest-declaration-steps, change-declaration-template, send-agreement-email
process-declaration-ocr / submit-member-declaration -> Google Gemini APIHTTPS / GEMINI_API_KEYgemini-2.5-flash (OCR extraction & XML find/replace)
Onboarding EFs -> Resend APIHTTPS / RESEND_API_KEYPOST https://api.resend.com/emails

7. Why It Works This Way

  • Chunked 8192B base64 encoding prevents JS call-stack overflow on large PDFs/DOCXs (process-declaration-ocr:35-45).
  • Gemini XML find/replace fills arbitrary user-uploaded blanks (___, ☐), whereas generate-prefilled-docx uses Docxtemplater ({field_key}) and BuildingAgreementService uses archive ZIP {{key}} replacement.
  • Web Blob URL openers (url_opener_web.dart / web_blob_opener_web.dart) bypass browser data: URI blocks and Storage Content-Disposition: attachment.
  • [TEAM_WHY_NEEDED: Why do send-correction-request-notice, send-rejection-notice, and grant-portal-access pass user_profile_id as unsubscribe ?token= when unsubscribe/index.ts only queries onboarding_tokens.token?]
  • [TEAM_WHY_NEEDED: Why are 5 Edge Functions called by Flutter missing from this repo and 6 others stuck at v1? Is there a separate backend repo deployed directly to ENERGY_SUPABASE_URL?]
  • [TEAM_WHY_NEEDED: Why does CoopSettingsScreen ship interactive AI Policy and Telemetry controls backed only by Future.delayed(600ms) with no DB persistence?]

8. Debugging, Logs & Common Failure Modes

  • CRITICAL SECURITY — Cross-tenant IDOR in 9 Service-Role Edge Functions: upload-declaration, process-declaration-ocr, approve-declaration-schema, get-company-declaration-schema, get-member-declaration, update-member-declaration, review-member-declaration, member-onboarding-status, generate-prefilled-docx check JWT validity ONLY — zero company_members tenant check! Any user can read/edit/approve another cooperative’s declarations.
  • CRITICAL SECURITY — Privilege escalation in 4 Notice/Access EFs: send-onboarding-invitation, send-correction-request-notice, send-rejection-notice, grant-portal-access check is_active = true and ignore role — any ordinary member can invite, reject, or grant portal access!
  • CRITICAL SECURITY — Unescaped HTML injection in 5 email EFs + PII in public buckets: Raw names/reasons/answers interpolated into HTML; generate-prefilled-docx (v1) uploads PII declarations to public declaration-templates and StorageService.uploadSignature uploads signatures to public company-media.
  • Broken Unsubscribe links (always 404): 3 notice/access EFs pass user_profile_id instead of onboarding_tokens.token.
  • Missing CORS headers in 8 local EFs: upload-declaration, approve-declaration-schema, get-company-declaration-schema, get-member-declaration, update-member-declaration, review-member-declaration, member-onboarding-status, generate-prefilled-docx lack OPTIONS / CORS headers (blocked on Flutter Web).
  • Functional bugs: submit-member-declaration prematurely sets is_energy_coop_member = true before approval; local send-correction-request-notice/send-rejection-notice reject targets not yet in company_members; _confirmAction silently swallows errors from grant-portal-access & send-rejection-notice; NotificationCenterProvider writes 'workOrders' while parser matches 'work_orders'; TAURON Annex 1a checkboxes biogaz/bil_ryczalt/bil_rzecz are unreachable; archiveOnboardingSession omits company_id filter; 5 dialogs leak undisposed controllers.
  • Log grep: [TeamCoopProvider], [DECL LIFECYCLE], [DECL UPLOAD], [REMOVED MEMBERS], [AGREEMENTS], STARTING OCR EXTRACTION, SUBMIT MEMBER DECLARATION.