Skip to content

Open Questions [TEAM_WHY_NEEDED] & Tech Debt

Use this board during engineering/product reviews to record the historical “Why?” behind non-obvious rules and track cleanup priorities.

A. Consolidated [TEAM_WHY_NEEDED] Questions for the Team

  1. [Core / Entrypoint] Are web/turnstile.html mobile loading (io.supabase.planovi:///turnstile.html) and MaintenanceProvider’s omitted tabs 14–18 intentional or oversights?
  2. [Core / Error Logging] Why is a hardcoded Google Chat webhook URL (with embedded key & token) present as a fallback in lib/core/services/app_error_logger.dart:20-21?
  3. [Auth / Account Deletion] Why does cancel-account-deletion/index.ts accept raw user_profile_id UUID as ?token= instead of a cryptographically signed or single-use cancellation token?
  4. [Admin / Dashboard] Is DashboardScreen (hardcoded '—' KPIs, static charts, 3 "In Development" no-ops) planned for real CRM metrics or deprecated in favor of EnergyDashboardScreen?
  5. [Admin / Team Management] Both RbacUnifiedScreen (Tab 1, route 11) and UsersLicensesScreen (route 29) perform invites, role edits, and member removals with diverging DB logic — which screen is authoritative?
  6. [Billing / External Repo] Where are the v3 Stripe billing/operator Edge Functions (start-checkout, preview-plan-change, change-plan, set-auto-renew, create-portal-session, get-billing-invoices, operator-coupons, handle-stripe-webhook) and their SQL RPCs version-controlled, and are in-repo stripe-webhook, send-subscription-updated, and send-subscription-cancelled still deployed?
  7. [Billing / Dual Supabase] Why do 27 Edge Functions read ENERGY_SUPABASE_URL / ENERGY_SUPABASE_SERVICE_ROLE_KEY while 16 read standard SUPABASE_URL / SUPABASE_SERVICE_ROLE_KEY (and run-scheduler mixes both)? Are these two separate Supabase projects or a legacy secret-naming convention?
  8. [Settings / Domains] Why is DNS TXT verification executed client-side with direct client UPDATE on whitelisted_domains instead of a server-side Edge Function?
  9. [Settings / Tenders] Is Grant/Tender matching (tender_profiles + tender-cron mock data + unread tender_matches) paused or consumed by an external app?
  10. [Settings / Google Calendar] Why does SettingsScreen render two separate Google Calendar connect widgets side-by-side (line 704 and GoogleCalendarConnectButton at line 763)?
  11. [CRM / Clients] Why does ClientProfileDetailScreen match agreements in-memory by client_email (capped at last 50 company agreements) instead of querying client_id, and why is ClientService.deleteAttachment not exposed in UI?
  12. [CRM / Soft vs Hard Delete] Why does active ClientService.deleteClient hard-delete while unused ClientRepository.delete soft-deletes (deleted_at + is_active = false)?
  13. [Dealflow / Dual Flows] Why do parallel Offer/Agreement creation UX flows coexist (embedded OfferGeneratorPanel/AgreementGeneratorPanel on Kanban cards vs full-screen CreateOfferScreen/CreateAgreementScreen triggered by DealflowStageService)?
  14. [Dealflow / Tenant Source] Why does CreateDealflowScreen read companyId from TenantSessionProvider.activeWorkspaceId while all other Dealflow screens read CompanyProvider.currentCompany?.id?
  15. [Docs / PDF Engine] Why do generate-offer and generate-agreement still render hardcoded pdf-lib layouts with dummy provider address/NIP instead of rendering the HTML/Canvas templates saved in public.templates?
  16. [Docs / DOCX & e-Sign] Why is docx-to-html in supabase/functions/ with zero callers, where is send-signature-request hosted, what external webhook triggers dual_dispatch: true, and why does _bridgeToKnowledgeBase write lowercase status: 'draft' into company_documents?
  17. [Scheduler / Dual Editors & Invitations] Why do NoweZadanieScreen and KonfiguracjeBrandinguScreen coexist with different ID formats (sched_<ms> vs UUID), iframe heights (800 vs 600), and error handling? Where does send-event-invitation live? Why do scheduler editors ignore user_google_tokens? Why is CalendarCoopProvider unused?
  18. [Jarvis / Audio, TTS, Cron & Currency] Where and how often is reminder-scheduler triggered in production? Why does llm_service.ts:70 hardcode mime_type: 'audio/wav' against .m4a/.webm recordings? Is auto-TTS on text-only replies intentional? Why do OfferPdfService/CreateOfferCard hardcode USD ($) inside Polish offer templates?
  19. [Energy Coop / Telemetry Pipelines] Which aggregation pipeline is authoritative (hourly_telemetry_summaries read by Flutter vs telemetry_hourly/telemetry_daily written by aggregate-*)? Has ingest-telemetry-new replaced ingest-telemetry? What service uploads to tauron_csvs and writes legacy device_telemetry?
  20. [Energy Coop / Onboarding Drift & Fake Settings] Why do 3 notice/access EFs pass user_profile_id to unsubscribe (which only accepts onboarding_tokens.token)? Where are the 5 missing onboarding/agreement EFs and v2 upgrades hosted? Why do CoopSettingsScreen AI Policy and Telemetry controls run Future.delayed(600ms) with no persistence?
  21. [Energy Coop / Finance & Governance] Should share_capital/entry_fee invoices be titled "Wezwanie do zapłaty" (invoice_pdf_service.dart:29-30)? Are billing-calculator and generate-monthly-invoices still live after the coop_id → company_id migration? Why does MemberWalletScreen synthesize a 24h sine-wave from kWh cooperativeSavings at 1.15 PLN/kWh? Why is VAT absent from all cooperative billing/PDF math? Is online payment planned for Wallet "Zapłać"? Should KnowledgeBaseProvider.acknowledgeDocument() persist to DB?

B. Critical & High Security Findings Checklist

  • Hardcoded Google Chat Webhook Secret in Client Bundle: lib/core/services/app_error_logger.dart:20-21 ships fallback webhook URL containing key & token in compiled Web JS / mobile binaries. Rotate key immediately and move error forwarding server-side.
  • Client-Side GEMINI_API_KEY Exposure: lib/features/templates/services/gemini_placeholder_service.dart:16-18 (used by gemini_template_service.dart:125 and create_template_screen.dart:2550) bundles GEMINI_API_KEY into client builds and sends ?key=... directly from browsers. Proxy through an authenticated Edge Function.
  • MFA (2FA) Complete Bypass at AAL1: lib/core/widgets/auth_wrapper.dart never inspects getAuthenticatorAssuranceLevel(). Page refresh, session resume, or Google OAuth bypasses MfaVerifyScreen.
  • Cross-Tenant & OAuth Token Dump in Jarvis QUERY_DB: supabase/functions/jarvis/services/database_service.ts:311-319 runs queryDatabaseDynamically via service_role with NO company_id filter and NO table blocklist (prompt injection can exfiltrate user_google_tokens across all tenants). Also add user_id/company_id guards to updateReminderAlarm, updateHistoryWidget, and deleteHistoryMessage (lines 142-159,275-278).
  • Client-Side DNS Verification Bypass on whitelisted_domains: domain_verification_service.dart:145-150 + 20261013120000_create_whitelisted_domains_table.sql:29-73 allow any company member (even is_active = false, non-admin) to directly UPDATE whitelisted_domains SET status = 'verified' via PostgREST. Move verification server-side and restrict RLS to active admins.
  • Unauthenticated Service-Role Edge Functions (Zero Auth): generate-offer, generate-agreement, and docx-to-html perform zero JWT/tenant checks and are absent from supabase/config.toml; ingest-telemetry-new relies solely on Nginx mTLS stripping/injecting X-Device-Serial (also absent from config.toml).
  • Cross-Tenant IDOR in 11 Service-Role Edge Functions: generate-invoice-pdf, generate-resolution-document, upload-declaration, process-declaration-ocr, approve-declaration-schema, get-company-declaration-schema, get-member-declaration, update-member-declaration, review-member-declaration, member-onboarding-status, and generate-prefilled-docx verify JWT validity ONLY — zero company_members tenant check.
  • Role Privilege Escalation in 6 Member-Checked Edge Functions: send-onboarding-invitation, send-correction-request-notice, send-rejection-notice, grant-portal-access, generate-report, and export-csv check membership existence without verifying role IN ('admin', 'owner') (or 'auditor' for reports).
  • Cross-Tenant Data Corruption in 3 Energy Cron Functions: ai-energy-balancer/index.ts:125 (const gateways = allGateways unfiltered) and billing-calculator/index.ts:106-112 & generate-monthly-invoices/index.ts:136-143 (gateway_registry.limit(1) unfiltered) mix all tenants’ telemetry/billing.
  • Stored XSS / HTML Injection & Client-Trusted Vote Tallies: generate-resolution-document/index.ts interpolates unescaped inputs into served HTML and trusts client-supplied yesVotes/quorumReached. 8 transactional email Edge Functions (stripe-webhook, send-subscription-*, send-onboarding-invitation, submit-member-declaration, send-correction-request-notice, send-rejection-notice, grant-portal-access) also interpolate raw DB/user strings into HTML.
  • Predictable Public Cancellation Token: cancel-account-deletion/index.ts accepts raw user_profile_id UUID as ?token=.
  • Sensitive PII / Confidential Files in Public Storage & Third-Party Cloud: document_editor_screen.dart:3724-3735 passes public .docx URLs to view.officeapps.live.com; generate-invoice-pdf uploads invoices to public invoices bucket; generate-prefilled-docx (v1) uploads member declarations to public declaration-templates; StorageService.uploadSignature uploads signatures to public company-media.

C. Missing External & Drifted Edge Functions Checklist

  • 19 External/Missing Edge Functions Referenced by Flutter (17 actively invoked + 1 webhook referenced + 1 feature-flagged OFF) — ABSENT from supabase/functions/:
    • Billing / Operator (8): start-checkout, preview-plan-change, change-plan, set-auto-renew, create-portal-session, get-billing-invoices, operator-coupons, handle-stripe-webhook (referenced).
    • Team Invites (2): invite-team-member, invite_user.
    • Commercial / Calendar / Finance Emails (4): send-signature-request, send-event-invitation, send-invoice-email, send-agreement-email.
    • Onboarding v2 (4): create-admin-edit-link, create-form-preview, suggest-declaration-steps, change-declaration-template.
    • Feature-flagged OFF (1): provision-energy-coop (kProvisionEnergyCoopEnabled = false).
  • 6 In-Repo Onboarding Edge Functions Stale at v1 (Behind Flutter v2 Contract): update-member-declaration, generate-prefilled-docx, send-onboarding-invitation, send-correction-request-notice, get-member-declaration, grant-portal-access (plus Flutter comments reference absent _shared/declaration_values.ts).
  • supabase/config.toml Misconfigurations: verify_jwt = true conflicts with X-Cron-Secret / X-Webhook-Secret on tender-cron and process-tauron-csv; stripe-webhook, ingest-telemetry-new, ai-energy-balancer, generate-offer, generate-agreement, docx-to-html, reminder-scheduler, fetch-energy-news are missing from config.toml; jarvis has conflicting verify_jwt between root supabase/config.toml (true) and supabase/functions/jarvis/config.toml (false).

D. Verified Functional Bugs & Data Integrity Defects Checklist

  • CompanyModel.toJson() key mismatch (company_model.dart:68 vs 32): Writes 'license_tiers' while fromJson() reads 'license_tier', resetting licenseTiers to [1].
  • generate-resolution-document guaranteed 400: Backend requires coopId; GovernanceProvider sends companyId (governance_provider.dart:741). Also inserts into legacy coop_documents.
  • Governance quorum bypass (governance_provider.dart:683-687): closeResolution() ignores quorumReached; _calculateMetrics ignores voterGroup and votingPower; _EditResolutionSheet cannot clear _votingEndsAt to null.
  • generate-offer VAT & discount corruption (generate-offer/index.ts:280-287,565-568): parseFloat(vat_rate) || 23 turns 0% VAT into 23%; ignores discount_percent/discount_amount; never sets sent_at; both generate-offer & generate-agreement hardcode dummy Warsaw address/NIP, misroute webhook_deliveries.target_url to company_settings.website, and sort locale DESC so 'pl-PL' always beats 'en-GB'/'de-DE'.
  • Invalid Gemini model (gemini_placeholder_service.dart:20): Hardcodes 'gemini-3.6-flash' (HTTP 404).
  • Broken Unsubscribe links (always 404): send-account-updated-notice, send-correction-request-notice, send-rejection-notice, grant-portal-access pass user_profile_id as ?token= while unsubscribe/index.ts:58 queries onboarding_tokens.token.
  • Storage warning vanishes at >= 95% (company_usage_overview_widget.dart:154): Checks isNearCapacity ([80%, 95%)) and omits isOverCapacity (>= 95%).
  • Trialing/past-due licenses hidden (billing_screen.dart:232): Hard-filters .eq('status', 'active').
  • Company owner rejected by send-subscription-updated/cancelled: Checks role !== "admin".
  • fetch-energy-news WAF short-circuit (fetch-energy-news/index.ts:178-215): HTTP 200 Cloudflare HTML from primary skips Secondary/Tertiary RSS feeds.
  • Users & Licenses bugs: UsersLicensesService.removeMember deletes only 1st assignmentId; updateMemberRoleAndDetails never syncs user_roles; EditMemberRoleDialog coerces custom roles to 'member'.
  • CRM / Dealflow bugs: ClientForm._checkForDuplicates breaks PostgREST .or() on commas/dots; ClientProfileDetailScreen matches agreements by empty client_email; CreateDealflowScreen checks sales:* RBAC while list checks dealflow:*; ListOfDealflowsScreen delete posts to hardcoded dev-dealflow.planovi.app/backend/delete_json.php; OfferEditPanel imports package:web unconditionally (breaks native builds); dealflow_entry_details_panel.dart:838 omits withData: true (breaks native uploads) and fails question mapping; DealflowStageService._handleApproved matches agreements by email ignoring deal_id; AgreementGeneratorPanel package picker doesn’t update _monthlyFeeCtrl.
  • Docs / Quill bugs: CreateAgreementScreen double-save duplicates/OCC-fails; InteractiveTableWidget._scheduleSync double-wraps custom_table; DocumentReaderScreen lacks _TableEmbedBuilder and renders HTML as raw text on Web; _bridgeToKnowledgeBase writes lowercase 'draft' leaking into Published tab; _cleanupOrphanedImages breaks document_versions; create_template_screen.dart:4772 bakes sample values instead of {{placeholders}}.
  • Scheduler / Calendar bugs: Deleting governance meeting from UnifiedCalendarScreen skips cancelMeeting (orphans records/PDFs); UnifiedCalendarScreen DragTarget ignores drops by Admins/Creators; NoweZadanieScreen ignores PHP errors, initializes legacy hex controllers, and drops defaultValue; ListOfSchedulersScreen unlocks iframe on pending domains; NewEventForm.didUpdateWidget doesn’t reload _editMeeting.
  • Jarvis bugs: reminder_alert Snooze/Done are DB no-ops; create_offer saves pdf_url: null (widgetData['doc_url'] vs data.doc_url); expired [SYSTEM_CONFIRM] sends literal "[SYSTEM_CONFIRM]" to Gemini; reminder-scheduler omits updating expires_at after token refresh; jarvis_voice_screen.dart:139 doesn’t call stopAlarm() on dispose; llm_service.ts hardcodes audio/wav.
  • Energy Coop Telemetry / Ops bugs: MyDevicesScreen._fetchConverterPreview fails 401 against ingest-telemetry; refresh-live-state & aggregate-daily truncate at PostgREST max_rows = 1000; process-alerts floods duplicate alerts; ai-energy-balancer.checkAutoOff loops infinitely; aggregate-hourly writes unaligned millisecond bucket_start; EnergyDashboardScreen 7-day chart renders blank; generate-report/export-csv ignore Flutter’s startDate/endDate/reportType; KnowledgeBaseProvider._canUserSeeDocument exposes restricted archived docs and mismatches roles.name vs enum role; WorkOrderProvider.deleteTicket deletes child work_orders before verifying parent RLS; summary.cooperativeSavings (kWh) displays as "PLN"; NotificationCenterProvider serializes 'workOrders' vs 'work_orders'.
  • Core / Auth / i18n bugs: CreateCompanyScreen imports dart:io File (Web crash); TenantSessionProvider.isSessionHealthy & Coop realtime watchdogs false-alarm after 3–5m idle; Mobile Turnstile loads io.supabase.planovi:///turnstile.html; MaintenanceProvider omits tabs 14–18; LocalString has 157 PL / 106 EN duplicate keys + 8 value collisions.

E. Dead / Legacy / Orphaned Code Inventory

  • Unused Dart Feature Layers & Models (0 active callers):
    • lib/features/products/models/category.dart, product.dart; lib/features/sets/models/set_model.dart
    • lib/features/clients/providers/client_provider.dart, repositories/client_repository.dart, ClientService.deleteAttachment
    • lib/features/offers/providers/offer_provider.dart, services/offer_service.dart, repositories/offer_repository.dart
    • lib/features/agreements/providers/agreement_provider.dart, repositories/agreement_repository.dart
    • lib/features/templates/models/template.dart, services/variable_extractor_service.dart, screens/variable_filler_screen.dart, screens/template_html_preview_screen.dart
    • lib/features/dealflow/models/dealflow_offer_model.dart, services/canvas_pdf_service.dart, services/offer_generator_service.dart, ViewOfferButton/ViewAgreementButton
    • lib/features/energy_coop/providers/calendar_coop_provider.dart
    • lib/features/jarvis/screens/jarvis_screen.dart
    • lib/features/admin/widgets/change_license_dialog.dart
    • lib/core/services/api_client.dart, secure_storage_service.dart; lib/core/widgets/app_sidebar.dart, gradient_button.dart
    • UsageService.canUpload(), DomainStatus.revoked, SharedPreferences 'global_crm_sync', TelemetryProvider.processTauronCSV & processModbusTelemetry, WorkOrder.isEscalated UI, KnowledgeBaseProvider 12 debug* methods, CoopSettingsScreen mock AI/Telemetry handlers.
  • Unused / Orphaned Edge Functions & Modules (0 callers in repo):
    • docx-to-html, generate-invoice-pdf, send-account-updated-notice, send-subscription-updated, send-subscription-cancelled, upload-declaration, approve-declaration-schema, review-member-declaration, member-onboarding-status, supabase/functions/jarvis/tools/index.ts (TOOLS).
  • Non-Runtime / Legacy Repo Artifacts: test/widget_test.dart (stale Flutter counter test referencing nonexistent MyApp), docs/, stitch_planovi_setup_wizard/, payload.json, payload.json.save.