Skip to content
📦 ARCHIVED SNAPSHOT (v1.0) You are viewing historical business logic and documentation for Backend (Edge Functions) v1.0 (frozen on 2026-11-23, commit f026e3b). Switch to Latest →

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 (29 Actionable Team Decisions)

  1. Env Var Split (SUPABASE_* vs ENERGY_SUPABASE_*): Why do 38 Edge Functions read ENERGY_SUPABASE_URL/ENERGY_SUPABASE_SERVICE_ROLE_KEY while 21 functions + _shared/auth.ts::validateAuth read SUPABASE_URL/SUPABASE_SERVICE_ROLE_KEY (and run-scheduler requires both)? Are they aliases to one project or a split project topology?
  2. Global Maintenance Table Write Policy (20240101000000:45-67): Why can any tenant company’s admin/owner modify global app_modules and app_modules_maintenance for all tenants instead of restricting to platform_operators?
  3. DNS Verification Worker (20261022000000): Where is the DNS TXT verification worker for whitelisted_domains implemented?
  4. Global user_overrides Scoping (20261116100000, 20261116150000): user_overrides has no company_id column, leaking overrides across companies for multi-company users. Is a migration adding company_id planned?
  5. Non-Decrementing AI Token Add-On (20261102120000): Why does user_token_quotas.purchased_token_addon persist across every monthly reset instead of decrementing as a one-time top-up?
  6. Missing 30-Day GDPR Purge Cron (send-account-deletion-notice): Where is the cron job that encrypts/permanently deletes accounts 30 days after deletion_scheduled_at?
  7. Legacy Agreements Stripe Webhook (stripe-webhook/index.ts): Is stripe-webhook (agreements.stripe_payment_status) still active in DealFlow/production or dead code?
  8. submit-inquiry Dev Redirect & Cardless Flag (submit-inquiry/index.ts:183): Why does submit-inquiry hardcode dev-dealflow.planovi.app/payment-success.php and omit payment_method_collection=if_required?
  9. Client-Triggered Subscription Emails (send-subscription-updated / cancelled): Why are these separate admin-only client-invoked endpoints instead of being sent server-side from change-plan/set-auto-renew/handle-stripe-webhook?
  10. Cancelled License Floor (recomputeLicenseTier): Why does companies.license_tier floor at [1] (Starter) even when a company has 0 active licenses?
  11. 14-Day Grace Period Enforcement (payment_failed_at): Where is the 14-day past_due cutoff actually enforced (Flutter UI, RLS, or external cron)?
  12. Parallel Telemetry Aggregation Pipelines: Why do telemetry_hourly/telemetry_daily (Edge Functions) AND hourly_telemetry_summaries (pg_cron SQL) coexist, and which is authoritative in PROD?
  13. Unauthenticated Converter Preview (ingest-telemetry/index.ts:81-135): Why does Flutter call unauthenticated POST ingest-telemetry instead of querying device_live_state via RLS?
  14. Pre-2026-10-18 Swapped Hourly Rows (20261030090000:13): Should historical pre-Oct-18 rows in hourly_telemetry_summaries stay immutable or be swapped?
  15. Legacy Pre-company_id Billing/AI Functions: Are billing-calculator, generate-monthly-invoices, generate-invoice-pdf, ai-energy-balancer, and generate-report abandoned and ready for removal, or slated for company_id migration?
  16. Monthly Invoice Math & VAT (generate-monthly-invoices): Why does the code double-apply 0.8, charge pure consumers 0 PLN in Scenario A, clamp export credits to 0 PLN, and omit VAT/OSD fees despite "FAKTURA VAT"?
  17. Invoice Email RBAC & Reply-To (send-invoice-email): Should it gate on RBAC ledger.invoices|UPDATE instead of hardcoded admin/owner, and pass the already-queried companies.contact_email as replyTo?
  18. Orphaned OCR Approval Pipeline (approve-declaration-schema): Is approve-declaration-schema (and ocr_extraction_sessions/ocr_extracted_fields) dead code now that process-declaration-ocr writes directly to declaration_fields?
  19. get-company-declaration-schema Usage: Why does it return all active fields across all templates (including admin fields) without template filtering or steps? Is any client still calling it?
  20. Hardcoded Planovi Theme in Form Links (_shared/form_link.ts): Why do create-form-preview, create-admin-edit-link, and issueFormLink hardcode #32CA42/#09090B instead of loading cooperative Zone 2 custom colors?
  21. docx-to-html Production Status: Is docx-to-html (unscoped validateAuth, mammoth@1.6.0, mojibake headings) still used?
  22. Step-Apply RBAC Gap (apply_declaration_steps): Why do declaration_steps RLS and apply_declaration_steps require planovi_is_admin while suggest-declaration-steps permits team_declarations|OTHERS?
  23. Gemini XML-Patching vs Docxtemplater (submit-member-declaration): Why does submit-member-declaration still use mammoth + gemini-2.5-flash + raw XML regex instead of generate-prefilled-docx / _shared/docx.ts?
  24. Premature is_energy_coop_member = true & Global ADMIN_NOTIFICATION_EMAIL (submit-member-declaration): Why is is_energy_coop_member set before board approval (unlike submit_on_behalf), and why is admin notification a single global env var instead of per-company admins?
  25. Client-Orchestrated Review/Rejection Split: Why are review-member-declaration, send-rejection-notice, and onboarding_sessions transitions split across separate client calls instead of one atomic endpoint?
  26. CRM webhook_deliveries Consumer: What service polls and delivers webhook_deliveries (consumer_type = "crm")?
  27. Hardcoded Placeholder Seller & Non-Expiring Signing Tokens (generate-agreement, generate-offer, signing-api): Why are "Planowi sp. z o.o. / NIP: 000-000-00-00" hardcoded, and should signing tokens carry an expiration/enforce signing_deadline?
  28. Cron Wiring & Prototype Status (run-scheduler, reminder-scheduler, tender-cron, send-event-invitation): Is run-scheduler superseded by pg_cron? Where are reminder-scheduler/tender-cron scheduled? Is tender-cron (expired May–June 2026 mock data) an abandoned prototype? Why does send-event-invitation gate on team_declarations|OTHERS and omit an unsubscribe footer?
  29. Jarvis Architecture (jarvis/index.ts): Why does TTS upload to public client_files/jarvis_audio/ (untracked by storage quotas, no company prefix, hardcoded Rachel voice), why inject the full OpenAPI schema when only 4 tables are writable, and how should multi-company users pick their active company?

B. Critical Security & Data-Integrity Bugs (Fix First)

  • Unauthenticated Telemetry Injection & Preview Leak (ingest-telemetry/index.ts:81-141): Preview mode runs with service_role and ZERO auth; ingestion only rejects bad x-ssl-client-verify when the header is present (direct hits without header bypass mTLS). Also contains hardcoded DEFAULT_EDGE_TOKEN at line 19.
  • Cross-Tenant IDOR in generate-invoice-pdf & generate-resolution-document: Both accept any user JWT via validateAuth(req) and read/write arbitrary invoice_id or coopId using service_role with zero tenant checks. generate-resolution-document also trusts client vote tallies and has Stored XSS.
  • RLS Bypass Regression on get_15min_energy (20261118140000:1185): Overwrote 20261117140000’s SECURITY INVOKER back to SECURITY DEFINER, re-opening cross-tenant telemetry reads.
  • Broken AI Token Quota Enforcement (jarvis/index.ts:725): get_user_token_status returns a PostgREST array [{ allowed: false }]; checking tokenStatus.allowed === false always evaluates undefined, so HTTP 429 never fires. Also jarvis/index.ts ignores app_modules.min_plan = 2 and RBAC, and trusts client-supplied pending_action JSON on [SYSTEM_CONFIRM] (lines 210-212).
  • Over-Permissive validateAuth on Global Cron/Admin Functions: run-scheduler, reminder-scheduler, tender-cron, cleanup-telemetry, process-alerts, process-tauron-csv, aggregate-hourly, aggregate-daily, billing-calculator, generate-monthly-invoices, ai-energy-balancer all accept any regular user JWT (allowUser: true default); refresh-live-state and ingest-telemetry-old have zero auth.
  • Member Can Write/Read Board-Only Fields (submit-member-declaration, get-member-declaration, get-company-declaration-schema): submit-member-declaration does not block field_visibility === 'admin', calculated, or is_active === false fields; get-* endpoints leak admin fields to plain members.
  • Unauthenticated Raw UUID Cancellation/Unsubscribe Tokens: cancel-account-deletion (?token=<user_profile_id>) has no HMAC/expiry; grant-portal-access, send-rejection-notice, and send-account-updated-notice pass ?token=<user_profile_id> to unsubscribe, which always 404s.
  • Stored HTML / MIME Header Injection in Emails: Unescaped user/DB strings in submit-member-declaration, send-rejection-notice, grant-portal-access, send-account-deletion-notice, send-account-updated-notice, handle-stripe-webhook, reminder-scheduler, and jarvis (raw Subject:/To: without CRLF stripping or RFC 2047).
  • Global Maintenance Table Writable by Any Tenant Admin (20240101000000:45-67): Any company’s admin/owner can put platform modules into maintenance for all tenants.
  • RBAC Drift Between DB and Edge Functions: _shared/auth.ts (+ 5 inline copies), invite-team-member, and grant-portal-access still bypass RBAC for admin (vs DB owner-only bypass 20261116150000) and check legacy team_declarations instead of the 7 granular tab modules. DB has_permission() (20261116160000) omits al.granular_action IS NULL.

C. High-Impact Functional & Logic Bugs

  • Double-Counting Demoted Building Counters (20261118140000:1584-1606): set_building_main_counter demotes counters.role = 'SUBMETER' but fails to update logical_points.meter_role = 'SUBMETER'.
  • Converter Maintenance Mode Not Synced (20261118140000:573-585,618-621): fn_sync_edge_converter_to_converters omits status = EXCLUDED.status on ON CONFLICT (hardware_id) DO UPDATE, so MAINTENANCE converters keep ingesting telemetry.
  • Broken run-scheduler (run-scheduler/index.ts:188-195): Hardcodes http://host.docker.internal:54321, sends headers: {} (401s against validateAuth), lacks row locking, and expects key-value system_settings schema conflicting with coop_id-based system_settings.
  • Broken Completion Tracking (member-onboarding-status:154-175,248-279): Counts cleared/null answers as completed (answerMap.has instead of .get === true) and aggregates fields across ALL templates (including archived & admin-only).
  • 9 Files with Double-Encoded UTF-8 Mojibake: Crashes pdf-lib WinAnsi in generate-invoice-pdf & generate-report, breaks case 'ten miesiÄ…c': in generate-report:599, breaks Polish Word heading mapping (Nagłówek 1) in docx-to-html:41-43, and writes corrupted Polish text in generate-resolution-document, ai-energy-balancer, reminder-scheduler, tender-cron.
  • Broken refresh-live-state, aggregate-hourly, process-alerts: refresh-live-state hits PostgREST 1000-row cap (offline devices stay 'online'); aggregate-hourly collapses 24h into 1 bucket with no onConflict; process-alerts floods duplicate alerts and misses 0V outages & negative export spikes.
  • Broken signing-api Order/Deadline/Finalize Checks (signing-api:308-398): Does not enforce signing_order, signing_deadline, agreements.status, or sig.status === 'pending'; triggers finalize-agreement on nobodyPending instead of allSigned.
  • Jarvis Operational Bugs (jarvis/index.ts): Expired >30m confirm/reject falls through to Gemini; missing googleToken writes literal "PENDING_DOC_URL" or silently drops Google-only events; solo calendar events fail pre-flight validator (prompt omits attendees); reminder_alert unhandled; allEvents queried & discarded; user_id forced on all non-calendar inserts.
  • Subscription Email Bugs: send-subscription-updated:139 has "noreply@planowi.app" typo; both send-subscription-* block role === 'owner' (HTTP 500) and render #F1F5F9 white text on #FFFFFF.
  • reminder-scheduler OAuth Refresh Leak (lines 64-67): Saves new access_token without updating expires_at, forcing a Google OAuth refresh on every run.
  • fetch-energy-news Waterfall Bug (lines 178-225): HTTP 200 WAF HTML or 0 parsed items from WysokieNapiecie short-circuits to static fallback instead of trying CIRE.pl & Google News.
  • Storage Quota Blindspots: Offer/agreement PDFs (documents/offers/..., documents/agreements/...) and Jarvis TTS MP3s (client_files/jarvis_audio/...) are excluded from company_storage_quotas.
  • Hardcoded DEV Data in SQL Migrations: 20261016171900, 20261024231000, 20261030110000, and 20261102140000 embed DEV company UUID d116b78e-5974-473b-a803-ccb199da744f, serial 'ASL-EC-12332453574787', and interactive Studio SELECT queries.

D. Dead, Legacy, Orphaned & Duplicated Code

  • 9 Orphaned Jarvis Files (ZERO imports, missing security hardening): supabase/functions/jarvis/{prompts/jarvis_system.ts, services/database_service.ts, services/llm_service.ts, services/tts_service.ts, tools/index.ts, tools/client_manager.ts, tools/document_gen.ts, tools/gmail_sender.ts, tools/google_calendar.ts}.
  • Legacy / Superseded Edge Functions: ingest-telemetry-old, billing-calculator (replaced by SQL fn_calculate_billing_records), approve-declaration-schema (bypassed by process-declaration-ocr), generate-monthly-invoices, generate-invoice-pdf, ai-energy-balancer, generate-report, process-tauron-csv, export-csv (all broken by coop_id/cooperatives/telemetry_logs/device_telemetry schema drift), stripe-webhook (unreferenced agreements webhook), tender-cron (hardcoded expired 2026 mock data).
  • Dead Copy-Pasted Helpers: Unused toIso/recomputeLicenseTier/syncLicensesFromSubscription in preview-plan-change/index.ts:160-216; unreachable OPTIONS handlers after validateAuth in docx-to-html, generate-resolution-document, reminder-scheduler; unused allEvents query in jarvis/index.ts:582-586.
  • Severe Auth/Stripe/Email Code Duplication: requireUser/requireStaff/hasRbacPermission duplicated inline in 5 functions instead of _shared/auth.ts; canManageBilling/buildPlan/syncLicensesFromSubscription/stripe() duplicated across 6 billing functions.
  • Hardcoded dev- URLs Across Production Code: https://dev-webpage.planovi.app/assets/logo-white.png in all email templates, https://dev-dealflow.planovi.app/payment-success.php in submit-inquiry, https://dev-panel.planovi.app default in 4 functions.
  • Severe Documentation Drift (README.md & docs/): Embedded Astro Starlight docs (docs/) and README.md are severely outdated (claim 35 functions instead of 65, describe non-existent job_queue/coop_news_feed/QR-code VAT invoices/LLM news cron/30-day retention/253V alert threshold/non-existent .env.example & deno test suite). Treat this blueprint—not docs/ or README.md—as the verified source of truth.