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
- [Core / Entrypoint] Are
web/turnstile.htmlmobile loading (io.supabase.planovi:///turnstile.html) andMaintenanceProvider’s omitted tabs14–18intentional or oversights? - [Core / Error Logging] Why is a hardcoded Google Chat webhook URL (with embedded
key&token) present as a fallback inlib/core/services/app_error_logger.dart:20-21? - [Auth / Account Deletion] Why does
cancel-account-deletion/index.tsaccept rawuser_profile_idUUID as?token=instead of a cryptographically signed or single-use cancellation token? - [Admin / Dashboard] Is
DashboardScreen(hardcoded'—'KPIs, static charts, 3"In Development"no-ops) planned for real CRM metrics or deprecated in favor ofEnergyDashboardScreen? - [Admin / Team Management] Both
RbacUnifiedScreen(Tab 1, route 11) andUsersLicensesScreen(route 29) perform invites, role edits, and member removals with diverging DB logic — which screen is authoritative? - [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-repostripe-webhook,send-subscription-updated, andsend-subscription-cancelledstill deployed? - [Billing / Dual Supabase] Why do 27 Edge Functions read
ENERGY_SUPABASE_URL/ENERGY_SUPABASE_SERVICE_ROLE_KEYwhile 16 read standardSUPABASE_URL/SUPABASE_SERVICE_ROLE_KEY(andrun-schedulermixes both)? Are these two separate Supabase projects or a legacy secret-naming convention? - [Settings / Domains] Why is DNS TXT verification executed client-side with direct client
UPDATEonwhitelisted_domainsinstead of a server-side Edge Function? - [Settings / Tenders] Is Grant/Tender matching (
tender_profiles+tender-cronmock data + unreadtender_matches) paused or consumed by an external app? - [Settings / Google Calendar] Why does
SettingsScreenrender two separate Google Calendar connect widgets side-by-side (line 704andGoogleCalendarConnectButtonatline 763)? - [CRM / Clients] Why does
ClientProfileDetailScreenmatch agreements in-memory byclient_email(capped at last 50 company agreements) instead of queryingclient_id, and why isClientService.deleteAttachmentnot exposed in UI? - [CRM / Soft vs Hard Delete] Why does active
ClientService.deleteClienthard-delete while unusedClientRepository.deletesoft-deletes (deleted_at+is_active = false)? - [Dealflow / Dual Flows] Why do parallel Offer/Agreement creation UX flows coexist (embedded
OfferGeneratorPanel/AgreementGeneratorPanelon Kanban cards vs full-screenCreateOfferScreen/CreateAgreementScreentriggered byDealflowStageService)? - [Dealflow / Tenant Source] Why does
CreateDealflowScreenreadcompanyIdfromTenantSessionProvider.activeWorkspaceIdwhile all other Dealflow screens readCompanyProvider.currentCompany?.id? - [Docs / PDF Engine] Why do
generate-offerandgenerate-agreementstill render hardcodedpdf-liblayouts with dummy provider address/NIP instead of rendering the HTML/Canvas templates saved inpublic.templates? - [Docs / DOCX & e-Sign] Why is
docx-to-htmlinsupabase/functions/with zero callers, where issend-signature-requesthosted, what external webhook triggersdual_dispatch: true, and why does_bridgeToKnowledgeBasewrite lowercasestatus: 'draft'intocompany_documents? - [Scheduler / Dual Editors & Invitations] Why do
NoweZadanieScreenandKonfiguracjeBrandinguScreencoexist with different ID formats (sched_<ms>vs UUID), iframe heights (800vs600), and error handling? Where doessend-event-invitationlive? Why do scheduler editors ignoreuser_google_tokens? Why isCalendarCoopProviderunused? - [Jarvis / Audio, TTS, Cron & Currency] Where and how often is
reminder-schedulertriggered in production? Why doesllm_service.ts:70hardcodemime_type: 'audio/wav'against.m4a/.webmrecordings? Is auto-TTS on text-only replies intentional? Why doOfferPdfService/CreateOfferCardhardcode USD ($) inside Polish offer templates? - [Energy Coop / Telemetry Pipelines] Which aggregation pipeline is authoritative (
hourly_telemetry_summariesread by Flutter vstelemetry_hourly/telemetry_dailywritten byaggregate-*)? Hasingest-telemetry-newreplacedingest-telemetry? What service uploads totauron_csvsand writes legacydevice_telemetry? - [Energy Coop / Onboarding Drift & Fake Settings] Why do 3 notice/access EFs pass
user_profile_idtounsubscribe(which only acceptsonboarding_tokens.token)? Where are the 5 missing onboarding/agreement EFs and v2 upgrades hosted? Why doCoopSettingsScreenAI Policy and Telemetry controls runFuture.delayed(600ms)with no persistence? - [Energy Coop / Finance & Governance] Should
share_capital/entry_feeinvoices be titled"Wezwanie do zapłaty"(invoice_pdf_service.dart:29-30)? Arebilling-calculatorandgenerate-monthly-invoicesstill live after thecoop_id→company_idmigration? Why doesMemberWalletScreensynthesize a 24h sine-wave from kWhcooperativeSavingsat1.15 PLN/kWh? Why is VAT absent from all cooperative billing/PDF math? Is online payment planned for Wallet"Zapłać"? ShouldKnowledgeBaseProvider.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-21ships fallback webhook URL containingkey&tokenin compiled Web JS / mobile binaries. Rotate key immediately and move error forwarding server-side. - Client-Side
GEMINI_API_KEYExposure:lib/features/templates/services/gemini_placeholder_service.dart:16-18(used bygemini_template_service.dart:125andcreate_template_screen.dart:2550) bundlesGEMINI_API_KEYinto 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.dartnever inspectsgetAuthenticatorAssuranceLevel(). Page refresh, session resume, or Google OAuth bypassesMfaVerifyScreen. - Cross-Tenant & OAuth Token Dump in Jarvis
QUERY_DB:supabase/functions/jarvis/services/database_service.ts:311-319runsqueryDatabaseDynamicallyviaservice_rolewith NOcompany_idfilter and NO table blocklist (prompt injection can exfiltrateuser_google_tokensacross all tenants). Also adduser_id/company_idguards toupdateReminderAlarm,updateHistoryWidget, anddeleteHistoryMessage(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-73allow any company member (evenis_active = false, non-admin) to directlyUPDATE 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, anddocx-to-htmlperform zero JWT/tenant checks and are absent fromsupabase/config.toml;ingest-telemetry-newrelies solely on Nginx mTLS stripping/injectingX-Device-Serial(also absent fromconfig.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, andgenerate-prefilled-docxverify JWT validity ONLY — zerocompany_memberstenant 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, andexport-csvcheck membership existence without verifyingrole IN ('admin', 'owner')(or'auditor'for reports). - Cross-Tenant Data Corruption in 3 Energy Cron Functions:
ai-energy-balancer/index.ts:125(const gateways = allGatewaysunfiltered) andbilling-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.tsinterpolates unescaped inputs into served HTML and trusts client-suppliedyesVotes/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.tsaccepts rawuser_profile_idUUID as?token=. - Sensitive PII / Confidential Files in Public Storage & Third-Party Cloud:
document_editor_screen.dart:3724-3735passes public.docxURLs toview.officeapps.live.com;generate-invoice-pdfuploads invoices to publicinvoicesbucket;generate-prefilled-docx(v1) uploads member declarations to publicdeclaration-templates;StorageService.uploadSignatureuploads signatures to publiccompany-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).
- Billing / Operator (8):
- 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.tomlMisconfigurations:verify_jwt = trueconflicts withX-Cron-Secret/X-Webhook-Secretontender-cronandprocess-tauron-csv;stripe-webhook,ingest-telemetry-new,ai-energy-balancer,generate-offer,generate-agreement,docx-to-html,reminder-scheduler,fetch-energy-newsare missing fromconfig.toml;jarvishas conflictingverify_jwtbetween rootsupabase/config.toml(true) andsupabase/functions/jarvis/config.toml(false).
D. Verified Functional Bugs & Data Integrity Defects Checklist
-
CompanyModel.toJson()key mismatch (company_model.dart:68vs32): Writes'license_tiers'whilefromJson()reads'license_tier', resettinglicenseTiersto[1]. -
generate-resolution-documentguaranteed 400: Backend requirescoopId;GovernanceProvidersendscompanyId(governance_provider.dart:741). Also inserts into legacycoop_documents. - Governance quorum bypass (
governance_provider.dart:683-687):closeResolution()ignoresquorumReached;_calculateMetricsignoresvoterGroupandvotingPower;_EditResolutionSheetcannot clear_votingEndsAttonull. -
generate-offerVAT & discount corruption (generate-offer/index.ts:280-287,565-568):parseFloat(vat_rate) || 23turns0%VAT into23%; ignoresdiscount_percent/discount_amount; never setssent_at; bothgenerate-offer&generate-agreementhardcode dummy Warsaw address/NIP, misroutewebhook_deliveries.target_urltocompany_settings.website, and sortlocale DESCso'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-accesspassuser_profile_idas?token=whileunsubscribe/index.ts:58queriesonboarding_tokens.token. - Storage warning vanishes at
>= 95%(company_usage_overview_widget.dart:154): ChecksisNearCapacity([80%, 95%)) and omitsisOverCapacity(>= 95%). - Trialing/past-due licenses hidden (
billing_screen.dart:232): Hard-filters.eq('status', 'active'). - Company
ownerrejected bysend-subscription-updated/cancelled: Checksrole !== "admin". -
fetch-energy-newsWAF short-circuit (fetch-energy-news/index.ts:178-215): HTTP 200 Cloudflare HTML from primary skips Secondary/Tertiary RSS feeds. - Users & Licenses bugs:
UsersLicensesService.removeMemberdeletes only 1stassignmentId;updateMemberRoleAndDetailsnever syncsuser_roles;EditMemberRoleDialogcoerces custom roles to'member'. - CRM / Dealflow bugs:
ClientForm._checkForDuplicatesbreaks PostgREST.or()on commas/dots;ClientProfileDetailScreenmatches agreements by emptyclient_email;CreateDealflowScreencheckssales:*RBAC while list checksdealflow:*;ListOfDealflowsScreendelete posts to hardcodeddev-dealflow.planovi.app/backend/delete_json.php;OfferEditPanelimportspackage:webunconditionally (breaks native builds);dealflow_entry_details_panel.dart:838omitswithData: true(breaks native uploads) and fails question mapping;DealflowStageService._handleApprovedmatches agreements by email ignoringdeal_id;AgreementGeneratorPanelpackage picker doesn’t update_monthlyFeeCtrl. - Docs / Quill bugs:
CreateAgreementScreendouble-save duplicates/OCC-fails;InteractiveTableWidget._scheduleSyncdouble-wrapscustom_table;DocumentReaderScreenlacks_TableEmbedBuilderand renders HTML as raw text on Web;_bridgeToKnowledgeBasewrites lowercase'draft'leaking into Published tab;_cleanupOrphanedImagesbreaksdocument_versions;create_template_screen.dart:4772bakes sample values instead of{{placeholders}}. - Scheduler / Calendar bugs: Deleting governance meeting from
UnifiedCalendarScreenskipscancelMeeting(orphans records/PDFs);UnifiedCalendarScreenDragTargetignores drops by Admins/Creators;NoweZadanieScreenignores PHP errors, initializes legacy hex controllers, and dropsdefaultValue;ListOfSchedulersScreenunlocks iframe onpendingdomains;NewEventForm.didUpdateWidgetdoesn’t reload_editMeeting. - Jarvis bugs:
reminder_alertSnooze/Done are DB no-ops;create_offersavespdf_url: null(widgetData['doc_url']vsdata.doc_url); expired[SYSTEM_CONFIRM]sends literal"[SYSTEM_CONFIRM]"to Gemini;reminder-scheduleromits updatingexpires_atafter token refresh;jarvis_voice_screen.dart:139doesn’t callstopAlarm()on dispose;llm_service.tshardcodesaudio/wav. - Energy Coop Telemetry / Ops bugs:
MyDevicesScreen._fetchConverterPreviewfails 401 againstingest-telemetry;refresh-live-state&aggregate-dailytruncate at PostgRESTmax_rows = 1000;process-alertsfloods duplicate alerts;ai-energy-balancer.checkAutoOffloops infinitely;aggregate-hourlywrites unaligned millisecondbucket_start;EnergyDashboardScreen7-day chart renders blank;generate-report/export-csvignore Flutter’sstartDate/endDate/reportType;KnowledgeBaseProvider._canUserSeeDocumentexposes restricted archived docs and mismatchesroles.namevs enum role;WorkOrderProvider.deleteTicketdeletes childwork_ordersbefore verifying parent RLS;summary.cooperativeSavings(kWh) displays as"PLN";NotificationCenterProviderserializes'workOrders'vs'work_orders'. - Core / Auth / i18n bugs:
CreateCompanyScreenimportsdart:ioFile(Web crash);TenantSessionProvider.isSessionHealthy& Coop realtime watchdogs false-alarm after 3–5m idle; Mobile Turnstile loadsio.supabase.planovi:///turnstile.html;MaintenanceProvideromits tabs14–18;LocalStringhas 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.dartlib/features/clients/providers/client_provider.dart,repositories/client_repository.dart,ClientService.deleteAttachmentlib/features/offers/providers/offer_provider.dart,services/offer_service.dart,repositories/offer_repository.dartlib/features/agreements/providers/agreement_provider.dart,repositories/agreement_repository.dartlib/features/templates/models/template.dart,services/variable_extractor_service.dart,screens/variable_filler_screen.dart,screens/template_html_preview_screen.dartlib/features/dealflow/models/dealflow_offer_model.dart,services/canvas_pdf_service.dart,services/offer_generator_service.dart,ViewOfferButton/ViewAgreementButtonlib/features/energy_coop/providers/calendar_coop_provider.dartlib/features/jarvis/screens/jarvis_screen.dartlib/features/admin/widgets/change_license_dialog.dartlib/core/services/api_client.dart,secure_storage_service.dart;lib/core/widgets/app_sidebar.dart,gradient_button.dartUsageService.canUpload(),DomainStatus.revoked,SharedPreferences'global_crm_sync',TelemetryProvider.processTauronCSV&processModbusTelemetry,WorkOrder.isEscalatedUI,KnowledgeBaseProvider12debug*methods,CoopSettingsScreenmock 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 nonexistentMyApp),docs/,stitch_planovi_setup_wizard/,payload.json,payload.json.save.