Backend (planovi-backend) β Business Logic & Modules
Code-Verified Blueprint: 9 modules β’ 79 documented
BR-*business rules β’ Zero-orphan file coverage.
Switch betweenLatestand frozen release snapshots using the Documentation Version dropdown at the top of the left sidebar.
Module Specifications Index
| # | Module Specification | Rule Prefix | Rules (BR-*) | Open [TEAM_WHY] |
|---|---|---|---|---|
| 1 | Core Runtime, Shared Libraries, Platform Infra & Brand Kit | BR-CORE | 6 | 2 |
| 2 | RBAC, Licensing, Quotas, Operator Panel & Team Access | BR-RBAC | 17 | 3 |
| 3 | SaaS Subscriptions, Stripe Billing & Hardware Orders | BR-SUB | 11 | 5 |
| 4 | IoT Telemetry Ingestion, Aggregation, Live State & Alerts | BR-IOT | 11 | 3 |
| 5 | Cooperative Energy Billing, Invoicing & AI Energy Balancing | BR-BILL | 7 | 3 |
| 6 | Declaration Templates, OCR, Form Builder & Member Onboarding | BR-DECL | 8 | 5 |
| 7 | Agreements, E-Signing, Resolutions & Offers | BR-SIGN | 7 | 3 |
| 8 | Schedulers, Automation, Energy News, Tenders & Event Notifications | BR-CRON | 5 | 4 |
| 9 | Jarvis AI Assistant | BR-JARVIS | 7 | 4 |
- Cross-Cutting Concerns & Shared Infrastructure β
- Open
[TEAM_WHY_NEEDED]Questions & Tech Debt Board β
Repository Snapshot & Runtime Metadata
- Repository:
PA-IDEAS/planovi-backend - Branch & HEAD Commit:
develop@f026e3b(Merge branch 'fix/edge-functions-syntax-and-fetch-timeouts' into develop)
Primary Stack & Pinned Versions
- Runtime: Self-hosted Supabase Edge Runtime (
edge-runtime v1.54.3, referenced insupabase/functions/main/index.ts:29), Deno TypeScript, PostgreSQL (withpg_cronandsupabase_realtimepublications). - No root
supabase/config.tomlor rootdeno.jsonexists in this repository. Onlysupabase/functions/jarvis/config.toml(verify_jwt = false) and 8 boilerplate per-functiondeno.jsonfiles (export-csv,generate-report,ingest-telemetry-old,jarvis,process-declaration-ocr,process-tauron-csv,tender-cron,upload-declaration) exist, each declaring"@supabase/functions-js": "jsr:@supabase/functions-js@^2". - Pinned Deno / ESM / NPM Imports (verified across
supabase/functions/):https://deno.land/std@0.177.0/http/server.ts(36 functions) andhttps://deno.land/std@0.168.0/http/server.ts(24 functions)https://esm.sh/@supabase/supabase-js@2(65 files) andhttps://esm.sh/@supabase/supabase-js@2.39.3(3 files:export-csv,generate-report,process-tauron-csv)https://esm.sh/pdf-lib@1.17.1(5 files) andhttps://esm.sh/@pdf-lib/fontkit@1.1.1(3 files)https://esm.sh/stripe@14(1 file:stripe-webhook,apiVersion: "2024-06-20")https://esm.sh/@google/generative-ai(unpinned, 2 files:process-declaration-ocr,submit-member-declaration)https://esm.sh/mammoth@1.6.0(docx-to-html),npm:mammoth(unpinned,submit-member-declaration)https://esm.sh/csv-parse@5.5.3/sync(process-tauron-csv)npm:fflate@0.8.2(process-declaration-ocr)npm:pizzip(unpinned, 3 files) andnpm:docxtemplater(unpinned, 2 files)
- Embedded Legacy Docs Site (
docs/package.json):astro@^4.16.1,@astrojs/starlight@^0.28.2,sharp@^0.33.5,typescript@^5.5.4.
What This Repo Owns (and What It Explicitly Does NOT Own)
- Owns:
- All 65 Supabase Edge Functions (plus
_shared/libraries and the self-hostedmaindynamic worker router) executing privileged server-side logic: Stripe SaaS billing/webhooks, RBAC/team/operator workflows, IoT telemetry ingestion/aggregation/alerts, cooperative energy billing & PDF/DOCX/CSV generation, declaration OCR/onboarding/review, CRM offers & eIDAS SES e-signing, schedulers/RSS/tenders, and Jarvis AI. - 41 incremental PostgreSQL migrations (
supabase/migrations/) covering maintenance registry, whitelisted iframe domains, RBAC (has_permission,company_has_module,full_scope, owner-only bypass, realtime), license/seat/storage/AI-token guards, operator panel & coupon grants, converter lifecycle/orders/main-vs-submeter separation, hourly/billing SQL aggregators,enforce_2fa, and private storage buckets (tauron_csvs,declaration-documents). - Synced Planovi brand assets (
assets/brand/),BRANDING_GUIDE.md, andscripts/sync-brand.sh.
- All 65 Supabase Edge Functions (plus
- Does NOT Own:
- Base PostgreSQL schema DDL: Core tables (
companies,company_members,user_profiles,company_licenses,license_tiers,inquiries,agreements,agreement_signatories,building_agreements,offers,offer_items,dealflow_entries,buildings,devices,converters,edge_converters,raw_telemetry,device_live_state,billing_records,invoices,jarvis_history,reminders,declaration_templates,declaration_fields,onboarding_sessions,onboarding_tokens,user_metadata,system_notifications,webhook_deliveries, etc.) are NOT created insupabase/migrations/β they pre-exist in the database or live outside this repo. - Frontend & Mobile UI: Owned by
planovi-flutter-app(panel/portal/mobile) andplanovi-converter/admin(IoT fleet admin panel). - Public PHP / Laravel Web Forms & Supabase GoTrue Auth Email Templates:
offer.php,api/form-writer.php,inquiry.php,payment-success.php,agreements/sign.php, and GoTrue HTML auth templates live inplanovi-microservices. - IoT Converter Control Plane & Firmware:
converters-api-dev:8000(FastAPI control plane) and RP2350 C/C++ firmware live inplanovi-converter. - Marketing Site & Hosted Brand Assets: Public PNG logos (
https://[dev-]webpage.planovi.app/assets/logo-white.png) live inplanovi-webpage; canonical brand-kit source lives inPA-IDEAS/planovi-docs. - Outbound CRM Webhook Delivery Worker & GDPR 30-Day Deletion Cron:
webhook_deliveriesrows are only enqueued here; no consumer exists in this repo. No cron job purges accounts afteruser_profiles.deletion_scheduled_at.
- Base PostgreSQL schema DDL: Core tables (
Directory Map
planovi-backend/βββ AGENTS.md # Agent guidelines & Zone 1 / Zone 2 branding rulesβββ CLAUDE.md -> AGENTS.md # Symlink to AGENTS.mdβββ BRANDING_GUIDE.md # Synced canonical Planovi ecosystem design tokens guideβββ README.md # Outdated overview (claims 35 functions; do not trust)βββ assets/brand/ # 18 official Planovi SVG/PNG/MP4 brand assetsβββ scripts/β βββ sync-brand.sh # Pulls BRANDING_GUIDE.md & assets from PA-IDEAS/planovi-docsβββ docs/ # Legacy Astro Starlight site (heavily drifted from source code)βββ supabase/ βββ functions/ β βββ _shared/ # 6 shared Deno TS modules (auth, email, form_link, docx, declaration_*) β βββ main/ # Self-hosted Edge Runtime dynamic worker router + metadata β βββ <64 domain functions>/ # 64 Edge Function directories (incl. legacy ingest-telemetry-old) βββ migrations/ # 41 SQL migration scripts (20240101..20261118)Local Development & Testing Commands
- Prerequisites: Deno, Supabase CLI, Docker Desktop, Node.js (for
docs/only),ghCLI (forscripts/sync-brand.sh). - Note on missing local scaffolding: There is no
supabase/config.toml, no.env.example, no.github/workflows/*CI/CD pipelines, and zero unit/integration test files (*_test.ts) anywhere in the repository. - Type-check an Edge Function with Deno:
Terminal window deno check supabase/functions/<function-name>/index.ts - Serve Edge Functions locally (requires a locally created env file containing the keys in the table below):
Terminal window supabase functions serve --env-file ./supabase/.env.local --no-verify-jwt - Sync canonical brand assets from
PA-IDEAS/planovi-docs:Terminal window ./scripts/sync-brand.sh - Run/build legacy embedded Astro docs portal (
docs/):Terminal window cd docs && npm install && npm run dev # http://localhost:4321cd docs && npm run build
Environment Variables & Config Keys (KEY NAMES ONLY)
Architectural Warning: Edge Functions inconsistently read either
ENERGY_SUPABASE_URL/ENERGY_SUPABASE_SERVICE_ROLE_KEY(38 functions +_shared/email.ts) ORSUPABASE_URL/SUPABASE_SERVICE_ROLE_KEY(21 functions +_shared/auth.ts::validateAuth).aggregate-hourlyfalls back between both;run-schedulerrequires both sets in the same invocation (validateAuthreadsSUPABASE_*, handler readsENERGY_SUPABASE_*).
| Key Name | Where Read (file) | Required? | Purpose |
|---|---|---|---|
SUPABASE_URL | _shared/auth.ts, aggregate-hourly, ai-energy-balancer, billing-calculator, export-csv, finalize-agreement, generate-agreement, generate-invoice-pdf, generate-monthly-invoices, generate-offer, generate-report, generate-resolution-document, ingest-telemetry, ingest-telemetry-old, jarvis, process-tauron-csv, reminder-scheduler, send-signature-request, signing-api, tender-cron | Yes (for listed functions) | Base Supabase project URL (internal Docker/Kong URL on self-hosted VPS) |
SUPABASE_SERVICE_ROLE_KEY | Same as SUPABASE_URL except export-csv & generate-report (still read via validateAuth in generate-report) | Yes (for listed functions) | Privileged PostgREST/Auth/Storage key bypassing RLS |
SUPABASE_ANON_KEY | export-csv/index.ts, generate-report/index.ts | Yes (for those 2) | User-scoped RLS Supabase client key |
ENERGY_SUPABASE_URL | _shared/email.ts, aggregate-daily, aggregate-hourly, approve-declaration-schema, cancel-account-deletion, change-declaration-template, change-plan, cleanup-telemetry, create-admin-edit-link, create-form-preview, create-portal-session, generate-prefilled-docx, get-billing-invoices, get-company-declaration-schema, get-member-declaration, grant-portal-access, handle-stripe-webhook, invite-team-member, member-onboarding-status, operator-coupons, preview-plan-change, process-alerts, process-declaration-ocr, refresh-live-state, review-member-declaration, run-scheduler, send-account-deletion-notice, send-account-updated-notice, send-agreement-email, send-correction-request-notice, send-event-invitation, send-invoice-email, send-onboarding-invitation, send-rejection-notice, send-subscription-cancelled, send-subscription-updated, set-auto-renew, start-checkout, stripe-webhook, submit-inquiry, submit-member-declaration, suggest-declaration-steps, unsubscribe, update-member-declaration, upload-declaration | Yes (for listed functions) | Supabase project URL for Energy/Planovi functions |
ENERGY_SUPABASE_SERVICE_ROLE_KEY | Same list as ENERGY_SUPABASE_URL (except _shared/email.ts) | Yes (for listed functions) | Service-role key for Energy/Planovi functions |
PUBLIC_SUPABASE_URL | finalize-agreement, generate-agreement, generate-offer, generate-prefilled-docx, signing-api | Recommended on self-hosted | Public HTTPS origin replacing internal Docker origin in Storage signed URLs |
PUBLIC_AUTH_URL | handle-stripe-webhook/index.ts | Optional (default https://api.planovi.app/auth/v1) | Public GoTrue /auth/v1 base URL for legacy invite links |
CRON_SECRET | _shared/auth.ts (validateAuth) | Optional (recommended) | Shared secret accepted via x-cron-secret header or Authorization: Bearer |
STRIPE_SECRET_KEY | change-plan, create-portal-session, get-billing-invoices, handle-stripe-webhook, operator-coupons, preview-plan-change, set-auto-renew, start-checkout, stripe-webhook, submit-inquiry | Yes (for billing/coupons) | Stripe REST API Bearer key |
STRIPE_INQUIRY_WEBHOOK_SECRET | handle-stripe-webhook/index.ts | Yes (for SaaS webhook) | HMAC-SHA256 signing secret for SaaS subscription & inquiry webhook |
STRIPE_WEBHOOK_SECRET | stripe-webhook/index.ts | Yes (for agreements webhook) | Stripe SDK signing secret for legacy agreements checkout webhook |
RESEND_API_KEY | _shared/email.ts, finalize-agreement, generate-agreement, generate-offer, grant-portal-access, handle-stripe-webhook, invite-team-member, send-account-deletion-notice, send-account-updated-notice, send-rejection-notice, send-signature-request, send-subscription-cancelled, send-subscription-updated, signing-api, stripe-webhook, submit-member-declaration | Yes (for transactional email) | Resend REST API Bearer key |
FROM_EMAIL | Same as RESEND_API_KEY | Optional (default noreply@planovi.app; typo noreply@planowi.app in send-subscription-updated) | Sender address formatted as Planovi <FROM_EMAIL> |
REPLY_TO_EMAIL | _shared/email.ts | Optional (default info@planovi.app) | Default reply_to for _shared/email.ts emails |
INTERNAL_NOTIFY_EMAIL | handle-stripe-webhook/index.ts | Optional (default info@planovi.app) | Internal Planovi sales alert recipient for Enterprise / deployment_help checkouts |
ADMIN_NOTIFICATION_EMAIL | submit-member-declaration/index.ts | Optional | Global admin notification address on member declaration submission |
PANEL_URL | create-portal-session, handle-stripe-webhook, invite-team-member, send-agreement-email, start-checkout | Optional (defaults vary: https://dev-panel.planovi.app or https://panel.planovi.app) | Panel app base URL for Stripe redirects, invite links, and agreement links |
PORTAL_URL | cancel-account-deletion, grant-portal-access, send-subscription-cancelled, send-subscription-updated, submit-inquiry | Optional (defaults vary: https://app.planovi.app or https://portal.planovi.app) | Portal/web app base URL for CTAs and checkout cancel URL |
INVITE_LINK_MODE | handle-stripe-webhook/index.ts | Optional (default legacy; supports token_hash) | Controls whether checkout invite link routes via GoTrue /verify or Flutter AuthLinkGate (?token_hash=) |
FORM_BASE_URL | _shared/form_link.ts (send-onboarding-invitation, send-correction-request-notice, create-form-preview, create-admin-edit-link) | Yes (throws HTTP 500 if missing) | Public URL of offer.php on external DealFlow form server |
FORM_WRITER_URL | _shared/form_link.ts | Yes (for form publishing) | Endpoint URL of api/form-writer.php accepting { token, data } |
HOSTINGER_WRITER_URL | _shared/form_link.ts | Optional (legacy fallback for FORM_WRITER_URL) | Legacy alias for FORM_WRITER_URL |
DEALFLOW_API_SECRET | _shared/form_link.ts | Yes (for form publishing) | Shared secret sent in X-Api-Secret header to form-writer.php |
UNSUBSCRIBE_BASE_URL | _shared/email.ts, grant-portal-access, send-account-updated-notice, send-rejection-notice | Optional (default ${ENERGY_SUPABASE_URL}/functions/v1/unsubscribe) | Base URL for email unsubscribe footer links |
CANCEL_DELETION_BASE_URL | send-account-deletion-notice/index.ts | Optional (default ${ENERGY_SUPABASE_URL}/functions/v1/cancel-account-deletion) | Base URL for 30-day account deletion cancellation link |
SIGNING_SECRET | send-signature-request/index.ts, signing-api/index.ts | Yes (for e-signing) | HMAC-SHA256 secret for stateless signatory tokens & audit hashes |
SIGNING_PAGE_URL | send-signature-request/index.ts, signing-api/index.ts | Yes (for e-signing) | Public URL of agreements/sign.php signing UI |
DEFAULT_WEBHOOK_URL | finalize-agreement, generate-agreement, generate-offer, send-signature-request, signing-api | Optional | Target URL populated into webhook_deliveries (consumer_type: "crm") |
GEMINI_API_KEY | jarvis, process-declaration-ocr, submit-member-declaration, suggest-declaration-steps, tender-cron | Yes (for AI features) | Google Gemini API key (gemini-2.5-flash) |
ELEVENLABS_API_KEY | jarvis/index.ts | Optional | ElevenLabs TTS API key (eleven_multilingual_v2) |
GOOGLE_CLIENT_ID | reminder-scheduler/index.ts | Yes (for Gmail token refresh) | Google OAuth client ID for refreshing user_google_tokens |
GOOGLE_CLIENT_SECRET | reminder-scheduler/index.ts | Yes (for Gmail token refresh) | Google OAuth client secret for refreshing user_google_tokens |
PLANOVI_INGEST_ORIGIN_URL | ingest-telemetry/index.ts | Optional (default http://converters-api-dev:8000/api/v1/telemetry/edge-record) | Upstream FastAPI converter control-plane dual-write URL |
PLANOVI_EDGE_SHARED_TOKEN | ingest-telemetry/index.ts | Optional (insecure hardcoded fallback DEFAULT_EDGE_TOKEN in source!) | Shared header X-Planovi-Edge-Token sent to converters-api-dev |
INCHARGE_EMAIL | ingest-telemetry-old/index.ts | Legacy only | InCharge cloud API login email |
INCHARGE_PASSWORD | ingest-telemetry-old/index.ts | Legacy only | InCharge cloud API login password |
Complete File Coverage Matrix (Zero-Orphan Inventory)
Every active and legacy file in PA-IDEAS/planovi-backend (66 supabase/functions/ directories, 41 supabase/migrations/ files, root configs, scripts/, assets/brand/, and docs/) belongs to exactly one module below.
| Module | Prefix | Assigned Files / Edge Functions / Migrations |
|---|---|---|
| 2.1 Core Runtime, Shared Libraries, Platform Infra & Brand Kit | BR-CORE | Router & Shared: supabase/functions/main/{index.ts,index.ts.metadata.json}, supabase/functions/_shared/{auth.ts,email.ts,form_link.ts,docx.ts,declaration_template_move.ts,declaration_values.ts}Migrations (4): 20240101000000_create_maintenance_table.sql, 20261022000000_create_whitelisted_domains_table.sql, 20261105100000_notification_triggers_definer.sql, 20261107120000_realtime_dealflow_entries.sqlRepo Tooling, Brand & Legacy Docs: AGENTS.md, CLAUDE.md, BRANDING_GUIDE.md, README.md, scripts/sync-brand.sh, assets/brand/* (18 files), docs/* (Astro Starlight site, 20 files) |
| 2.2 RBAC, Licensing, Quotas, Operator Panel & Team Access | BR-RBAC | Edge Functions (6): invite-team-member/index.ts, grant-portal-access/index.ts, cancel-account-deletion/index.ts, send-account-deletion-notice/index.ts, send-account-updated-notice/index.ts, operator-coupons/index.tsMigrations (22): 20261029120000_license_guard.sql, 20261102110000_license_tiers_usage_limits.sql, 20261102120000_usage_quotas_storage_tokens.sql, 20261102130000_usage_limits_license_tier_fallback.sql, 20261103100000_license_seats_guard.sql, 20261105120000_coop_member_data_rls.sql, 20261105130000_coop_finance_rls.sql, 20261110150000_operator_panel.sql, 20261110170000_license_grants.sql, 20261110190000_billing_managers.sql, 20261110210000_company_admin_contacts.sql, 20261111090000_license_grants_total_seats.sql, 20261116100000_rbac_team_declarations_pilot.sql, 20261116150000_rbac_owner_only_bypass.sql, 20261116160000_module_min_plan.sql, 20261117090000_rbac_all_tabs.sql, 20261117100000_rbac_realtime.sql, 20261117120000_rbac_full_scope.sql, 20261117130000_rbac_full_scope_telemetry.sql, 20261117140000_telemetry_scope_hardening.sql, 20261118100000_rbac_admin_screens_view.sql, 20261118180000_company_settings_enforce_2fa.sql |
| 2.3 SaaS Subscriptions, Stripe Billing & Hardware Orders | BR-SUB | Edge Functions (11): start-checkout/index.ts, change-plan/index.ts, preview-plan-change/index.ts, set-auto-renew/index.ts, create-portal-session/index.ts, get-billing-invoices/index.ts, handle-stripe-webhook/index.ts, stripe-webhook/index.ts, submit-inquiry/index.ts, send-subscription-updated/index.ts, send-subscription-cancelled/index.tsMigration (1): 20261118140000_converter_lifecycle_orders_billing.sql (also cross-referenced in 2.4 & 2.5) |
| 2.4 IoT Telemetry Ingestion, Aggregation, Live State & Alerts | BR-IOT | Edge Functions (9): ingest-telemetry/{index.ts,schema3_adapter.ts}, ingest-telemetry-old/{index.ts,deno.json,.npmrc}, aggregate-hourly/index.ts, aggregate-daily/index.ts, refresh-live-state/index.ts, cleanup-telemetry/index.ts, process-alerts/index.ts, process-tauron-csv/{index.ts,deno.json,.npmrc}, export-csv/{index.ts,deno.json,.npmrc}Migrations (9): 20260813173407_create_tauron_csvs_bucket.sql, 20261016171900_sync_edge_converters_to_converters.sql, 20261024231000_fix_telemetry_gateway_and_live_state.sql, 20261026153000_update_ingest_telemetry_devices_last_seen.sql, 20261030090000_hourly_summaries_fix.sql, 20261030091000_hourly_summaries_ignore_zero.sql, 20261030100000_hourly_summaries_read_policy.sql, 20261030120000_hourly_summaries_lag_delta.sql, 20261030131000_fix_telemetry_device_ts_and_replay.sql |
| 2.5 Cooperative Energy Billing, Invoicing & AI Energy Balancing | BR-BILL | Edge Functions (6): billing-calculator/index.ts, generate-monthly-invoices/index.ts, generate-invoice-pdf/index.ts, send-invoice-email/index.ts, ai-energy-balancer/index.ts, generate-report/{index.ts,deno.json,.npmrc}Migrations (2): 20261030110000_billing_records_calc.sql, 20261102140000_billing_records_device_ts.sql |
| 2.6 Declaration Templates, OCR, Form Builder & Member Onboarding | BR-DECL | Edge Functions (18): upload-declaration/{index.ts,deno.json,.npmrc}, process-declaration-ocr/{index.ts,deno.json,.npmrc}, approve-declaration-schema/index.ts, suggest-declaration-steps/index.ts, get-company-declaration-schema/index.ts, change-declaration-template/index.ts, create-form-preview/index.ts, create-admin-edit-link/index.ts, docx-to-html/index.ts, generate-prefilled-docx/{index.ts,fill_form.ts}, send-onboarding-invitation/index.ts, member-onboarding-status/index.ts, submit-member-declaration/index.ts, get-member-declaration/index.ts, update-member-declaration/index.ts, review-member-declaration/index.ts, send-correction-request-notice/index.ts, send-rejection-notice/index.tsMigrations (3): 20261030130000_declaration_steps.sql, 20261102100000_apply_declaration_steps.sql, 20261105140000_declaration_documents_bucket.sql |
| 2.7 Agreements, E-Signing, Resolutions & Offers | BR-SIGN | Edge Functions (7): generate-agreement/index.ts, send-agreement-email/index.ts, send-signature-request/index.ts, signing-api/index.ts, finalize-agreement/index.ts, generate-resolution-document/index.ts, generate-offer/index.ts |
| 2.8 Schedulers, Automation, Energy News, Tenders & Event Notifications | BR-CRON | Edge Functions (6): run-scheduler/index.ts, reminder-scheduler/index.ts, fetch-energy-news/index.ts, tender-cron/{index.ts,deno.json,.npmrc}, send-event-invitation/index.ts, unsubscribe/index.ts |
| 2.9 Jarvis AI Assistant | BR-JARVIS | Edge Function (1 dir, 13 files): jarvis/{index.ts,config.toml,deno.json,.npmrc}, plus 9 orphaned dead-code files: jarvis/prompts/jarvis_system.ts, jarvis/services/{database_service.ts,llm_service.ts,tts_service.ts}, jarvis/tools/{index.ts,client_manager.ts,document_gen.ts,gmail_sender.ts,google_calendar.ts} |
Totals Verified: 66 supabase/functions/* directories (100%), 41 supabase/migrations/*.sql files (100%), all tooling/brand/docs files (100%). Zero orphans.