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 β†’

Backend (planovi-backend) β€” Business Logic & Modules

Code-Verified Blueprint: 9 modules β€’ 79 documented BR-* business rules β€’ Zero-orphan file coverage.
Switch between Latest and frozen release snapshots using the Documentation Version dropdown at the top of the left sidebar.

Module Specifications Index

#Module SpecificationRule PrefixRules (BR-*)Open [TEAM_WHY]
1Core Runtime, Shared Libraries, Platform Infra & Brand KitBR-CORE62
2RBAC, Licensing, Quotas, Operator Panel & Team AccessBR-RBAC173
3SaaS Subscriptions, Stripe Billing & Hardware OrdersBR-SUB115
4IoT Telemetry Ingestion, Aggregation, Live State & AlertsBR-IOT113
5Cooperative Energy Billing, Invoicing & AI Energy BalancingBR-BILL73
6Declaration Templates, OCR, Form Builder & Member OnboardingBR-DECL85
7Agreements, E-Signing, Resolutions & OffersBR-SIGN73
8Schedulers, Automation, Energy News, Tenders & Event NotificationsBR-CRON54
9Jarvis AI AssistantBR-JARVIS74

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 in supabase/functions/main/index.ts:29), Deno TypeScript, PostgreSQL (with pg_cron and supabase_realtime publications).
  • No root supabase/config.toml or root deno.json exists in this repository. Only supabase/functions/jarvis/config.toml (verify_jwt = false) and 8 boilerplate per-function deno.json files (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) and https://deno.land/std@0.168.0/http/server.ts (24 functions)
    • https://esm.sh/@supabase/supabase-js@2 (65 files) and https://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) and https://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) and npm: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-hosted main dynamic 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, and scripts/sync-brand.sh.
  • 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 in supabase/migrations/ β€” they pre-exist in the database or live outside this repo.
    • Frontend & Mobile UI: Owned by planovi-flutter-app (panel/portal/mobile) and planovi-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 in planovi-microservices.
    • IoT Converter Control Plane & Firmware: converters-api-dev:8000 (FastAPI control plane) and RP2350 C/C++ firmware live in planovi-converter.
    • Marketing Site & Hosted Brand Assets: Public PNG logos (https://[dev-]webpage.planovi.app/assets/logo-white.png) live in planovi-webpage; canonical brand-kit source lives in PA-IDEAS/planovi-docs.
    • Outbound CRM Webhook Delivery Worker & GDPR 30-Day Deletion Cron: webhook_deliveries rows are only enqueued here; no consumer exists in this repo. No cron job purges accounts after user_profiles.deletion_scheduled_at.

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), gh CLI (for scripts/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:4321
    cd 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) OR SUPABASE_URL / SUPABASE_SERVICE_ROLE_KEY (21 functions + _shared/auth.ts::validateAuth). aggregate-hourly falls back between both; run-scheduler requires both sets in the same invocation (validateAuth reads SUPABASE_*, handler reads ENERGY_SUPABASE_*).

Key NameWhere 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-cronYes (for listed functions)Base Supabase project URL (internal Docker/Kong URL on self-hosted VPS)
SUPABASE_SERVICE_ROLE_KEYSame 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_KEYexport-csv/index.ts, generate-report/index.tsYes (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-declarationYes (for listed functions)Supabase project URL for Energy/Planovi functions
ENERGY_SUPABASE_SERVICE_ROLE_KEYSame list as ENERGY_SUPABASE_URL (except _shared/email.ts)Yes (for listed functions)Service-role key for Energy/Planovi functions
PUBLIC_SUPABASE_URLfinalize-agreement, generate-agreement, generate-offer, generate-prefilled-docx, signing-apiRecommended on self-hostedPublic HTTPS origin replacing internal Docker origin in Storage signed URLs
PUBLIC_AUTH_URLhandle-stripe-webhook/index.tsOptional (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_KEYchange-plan, create-portal-session, get-billing-invoices, handle-stripe-webhook, operator-coupons, preview-plan-change, set-auto-renew, start-checkout, stripe-webhook, submit-inquiryYes (for billing/coupons)Stripe REST API Bearer key
STRIPE_INQUIRY_WEBHOOK_SECREThandle-stripe-webhook/index.tsYes (for SaaS webhook)HMAC-SHA256 signing secret for SaaS subscription & inquiry webhook
STRIPE_WEBHOOK_SECRETstripe-webhook/index.tsYes (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-declarationYes (for transactional email)Resend REST API Bearer key
FROM_EMAILSame as RESEND_API_KEYOptional (default noreply@planovi.app; typo noreply@planowi.app in send-subscription-updated)Sender address formatted as Planovi <FROM_EMAIL>
REPLY_TO_EMAIL_shared/email.tsOptional (default info@planovi.app)Default reply_to for _shared/email.ts emails
INTERNAL_NOTIFY_EMAILhandle-stripe-webhook/index.tsOptional (default info@planovi.app)Internal Planovi sales alert recipient for Enterprise / deployment_help checkouts
ADMIN_NOTIFICATION_EMAILsubmit-member-declaration/index.tsOptionalGlobal admin notification address on member declaration submission
PANEL_URLcreate-portal-session, handle-stripe-webhook, invite-team-member, send-agreement-email, start-checkoutOptional (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_URLcancel-account-deletion, grant-portal-access, send-subscription-cancelled, send-subscription-updated, submit-inquiryOptional (defaults vary: https://app.planovi.app or https://portal.planovi.app)Portal/web app base URL for CTAs and checkout cancel URL
INVITE_LINK_MODEhandle-stripe-webhook/index.tsOptional (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.tsYes (for form publishing)Endpoint URL of api/form-writer.php accepting { token, data }
HOSTINGER_WRITER_URL_shared/form_link.tsOptional (legacy fallback for FORM_WRITER_URL)Legacy alias for FORM_WRITER_URL
DEALFLOW_API_SECRET_shared/form_link.tsYes (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-noticeOptional (default ${ENERGY_SUPABASE_URL}/functions/v1/unsubscribe)Base URL for email unsubscribe footer links
CANCEL_DELETION_BASE_URLsend-account-deletion-notice/index.tsOptional (default ${ENERGY_SUPABASE_URL}/functions/v1/cancel-account-deletion)Base URL for 30-day account deletion cancellation link
SIGNING_SECRETsend-signature-request/index.ts, signing-api/index.tsYes (for e-signing)HMAC-SHA256 secret for stateless signatory tokens & audit hashes
SIGNING_PAGE_URLsend-signature-request/index.ts, signing-api/index.tsYes (for e-signing)Public URL of agreements/sign.php signing UI
DEFAULT_WEBHOOK_URLfinalize-agreement, generate-agreement, generate-offer, send-signature-request, signing-apiOptionalTarget URL populated into webhook_deliveries (consumer_type: "crm")
GEMINI_API_KEYjarvis, process-declaration-ocr, submit-member-declaration, suggest-declaration-steps, tender-cronYes (for AI features)Google Gemini API key (gemini-2.5-flash)
ELEVENLABS_API_KEYjarvis/index.tsOptionalElevenLabs TTS API key (eleven_multilingual_v2)
GOOGLE_CLIENT_IDreminder-scheduler/index.tsYes (for Gmail token refresh)Google OAuth client ID for refreshing user_google_tokens
GOOGLE_CLIENT_SECRETreminder-scheduler/index.tsYes (for Gmail token refresh)Google OAuth client secret for refreshing user_google_tokens
PLANOVI_INGEST_ORIGIN_URLingest-telemetry/index.tsOptional (default http://converters-api-dev:8000/api/v1/telemetry/edge-record)Upstream FastAPI converter control-plane dual-write URL
PLANOVI_EDGE_SHARED_TOKENingest-telemetry/index.tsOptional (insecure hardcoded fallback DEFAULT_EDGE_TOKEN in source!)Shared header X-Planovi-Edge-Token sent to converters-api-dev
INCHARGE_EMAILingest-telemetry-old/index.tsLegacy onlyInCharge cloud API login email
INCHARGE_PASSWORDingest-telemetry-old/index.tsLegacy onlyInCharge 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.

ModulePrefixAssigned Files / Edge Functions / Migrations
2.1 Core Runtime, Shared Libraries, Platform Infra & Brand KitBR-CORERouter & 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.sql
Repo 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 AccessBR-RBACEdge 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.ts
Migrations (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 OrdersBR-SUBEdge 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.ts
Migration (1): 20261118140000_converter_lifecycle_orders_billing.sql (also cross-referenced in 2.4 & 2.5)
2.4 IoT Telemetry Ingestion, Aggregation, Live State & AlertsBR-IOTEdge 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 BalancingBR-BILLEdge 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 OnboardingBR-DECLEdge 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.ts
Migrations (3): 20261030130000_declaration_steps.sql, 20261102100000_apply_declaration_steps.sql, 20261105140000_declaration_documents_bucket.sql
2.7 Agreements, E-Signing, Resolutions & OffersBR-SIGNEdge 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 NotificationsBR-CRONEdge 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 AssistantBR-JARVISEdge 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.