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 →

1. Core Runtime, Shared Libraries, Platform Infra & Brand Kit

Repository: Backend (planovi-backend) • Rule Prefix: BR-CORE • Documented Rules: 6 • Open [TEAM_WHY_NEEDED] Questions: 2

1. Business Purpose & Actors

Provides the self-hosted Supabase Edge Runtime HTTP worker router (main/index.ts), reusable TypeScript helpers (_shared/), platform-level database infrastructure (module maintenance registry, iframe domain whitelisting, SECURITY DEFINER system notification triggers, Kanban realtime publication), and canonical Planovi brand asset synchronization (scripts/sync-brand.sh).

  • Actors: Every HTTP caller to /functions/v1/<service>, Supabase Edge Runtime supervisor, cooperative admins/owners managing app_modules_maintenance and whitelisted_domains, technicians/applicants triggering system_notifications via work_orders and coop_applications, and developers syncing brand assets.

2. All Features & End-to-End Flows

  • Dynamic Edge Worker Router (supabase/functions/main/index.ts):
    • Trigger: Every request routed through self-hosted Supabase Edge Runtime.
    • Extracts last non-empty path segment as service_name. If empty or "main", returns 200 { message: "Supabase Edge Runtime Active (Router)" }.
    • Spawns isolated worker via EdgeRuntime.userWorkers.create({ servicePath: "/home/deno/functions/<service_name>", memoryLimitMb: 150, workerTimeoutMs: 300_000, cpuTimeSoftLimitMs: 10_000, cpuTimeHardLimitMs: 20_000, noModuleCache: false, envVars: Object.entries(Deno.env.toObject()) }) and proxies worker.fetch(req).
    • Failure: Catches worker errors, attaches CORS headers, returns 503 ("Function stopped (time/CPU limit exceeded)") if error name/message indicates WorkerRequestCancelled / "cancelled", otherwise 404 ("Function not found or failed to load").
  • Shared Libraries (supabase/functions/_shared/):
    • auth.ts: Provides requireUser, activeRole, hasRbacPermission, requireStaff, jsonResponse, errorResponse, httpError, UUID_RE, corsHeaders, and validateAuth (handles OPTIONS, x-cron-secret, Bearer <service_role>, Bearer <CRON_SECRET>, or GoTrue auth.getUser).
    • email.ts: Provides escapeHtml, escapeMultiline, unsubscribeUrlFor, ctaButton, Zone 1 emailShell, and sendEmail (Resend API POST https://api.resend.com/emails with AbortSignal.timeout(15_000)).
    • form_link.ts: Provides formBaseUrl, writeFormJson (15s timeout to FORM_WRITER_URL with X-Api-Secret), cleanPreviewUrl, sanitizeLabelHtml, loadMemberForm, loadMemberFields, loadMemberValues, and issueFormLink (72h TTL, reuse/revoke logic).
    • docx.ts: Provides generateDeclarationDocx (PizZip + Docxtemplater placeholder rendering) and chunked toBase64 (CHUNK = 0x8000).
    • declaration_template_move.ts: Provides carryAnswersToTemplate (field_key matching, number -> text conversion) and missingRequiredFields.
    • declaration_values.ts: Provides convertValue (7 data types), normalizeDate, toBool, isEmptyValue, and validationResponse (HTTP 422 batch errors).
  • Platform Maintenance Registry (20240101000000_create_maintenance_table.sql):
    • Creates public.app_modules (19 initial modules) and 1:1 public.app_modules_maintenance (is_under_maintenance, maintenance_message, bypass_for_admins, start_time, end_time). Publicly readable (USING (true)), writable by any user who is admin/owner in any company.
  • Iframe Domain Whitelist (20261022000000_create_whitelisted_domains_table.sql):
    • Creates public.whitelisted_domains (company_id, domain, txt_verification_token, status in 'pending'|'verified'|'revoked', verified_at, ga4_measurement_id, unique (company_id, domain)). Readable by company members; writable by company admin/owner and service_role.
  • Definer Notification Triggers (20261105100000_notification_triggers_definer.sql):
    • Rewrites notify_work_order_events() and notify_application_events() as SECURITY DEFINER (search_path = public, pg_temp, revoked from public) so app users changing ticket/application statuses can trigger inserts into system_notifications without needing an INSERT RLS policy on system_notifications.
  • Kanban Realtime (20261107120000_realtime_dealflow_entries.sql):
    • Idempotently adds public.dealflow_entries to supabase_realtime publication (RLS-scoped via tenant_isolation_dealflow_entries).
  • Brand Kit Sync (scripts/sync-brand.sh):
    • Shallow-clones PA-IDEAS/planovi-docs via gh repo clone into temp dir and overwrites ./BRANDING_GUIDE.md and ./assets/brand/.

3. Hard Business Rules, Validations, Calculations & Edge Cases (BR-CORE)

  • BR-CORE-01 (Worker Resource Limits): Every Edge Function executed via main/index.ts:27-32 is bounded by memoryLimitMb: 150, workerTimeoutMs: 300_000 (5 min), cpuTimeSoftLimitMs: 10_000, cpuTimeHardLimitMs: 20_000. Exceeding CPU/time limits returns HTTP 503 with CORS headers.
  • BR-CORE-02 (validateAuth Precedence): _shared/auth.ts:113-176 evaluates: (1) OPTIONS -> 200 "ok"; (2) x-cron-secret === CRON_SECRET; (3) Bearer === SUPABASE_SERVICE_ROLE_KEY; (4) Bearer === CRON_SECRET; (5) Bearer validated as any Supabase user JWT via auth.getUser. Default options enables all three (allowUser: true).
  • BR-CORE-03 (requireStaff RBAC Rule): _shared/auth.ts:64-73 validates UUID_RE (400), checks active company_members (403), bypasses for role IN ('admin', 'owner'), and falls back to hasRbacPermission(companyId, userId, 'team_declarations', action) where user_overrides revoke (is_granted = false) beats grant (is_granted = true), which beats base user_roles -> role_permissions. (Note: Drifts from DB 20261116150000 owner-only bypass.)
  • BR-CORE-04 (Resend Email Transport Timeout & Defaults): _shared/email.ts:81-114 enforces AbortSignal.timeout(15_000), defaults FROM_EMAIL to "noreply@planovi.app" and REPLY_TO_EMAIL to "info@planovi.app", formats sender as Planovi <${from}>, and fails cleanly with { ok: false, error: "RESEND_API_KEY not configured" } if key is empty.
  • BR-CORE-05 (Work Order & Application System Notifications): 20261105100000:
    • work_orders INSERT with non-null technician_id -> notifies technician (type: 'work_order', "Nowe zgłoszenie").
    • work_orders UPDATE status -> 'completed' (IS DISTINCT FROM) -> notifies all active owner/admin of company_id (type: 'system_alert', "Zgłoszenie zakończone").
    • coop_applications UPDATE ('draft'|'awaiting_correction') -> 'submitted' -> notifies active owner/admin ("Nowa Deklaracja").
    • coop_applications UPDATE 'submitted' -> 'awaiting_correction' -> notifies new.user_id ("Deklaracja wymaga poprawek").
    • coop_applications UPDATE -> 'approved' (IS DISTINCT FROM) -> notifies new.user_id ("Witaj w Spółdzielni!").
  • BR-CORE-06 (Whitelisted Domain Uniqueness): whitelisted_domains enforces UNIQUE (company_id, domain) and defaults status = 'pending'.

4. State Machines & Data Lifecycle

  • whitelisted_domains.status: 'pending' -> 'verified' (sets verified_at) | 'revoked'. (No DB CHECK constraint; enforced by convention.)
  • app_modules_maintenance.is_under_maintenance: false (default) <-> true (optional start_time/end_time, bypass_for_admins default true).

5. Technical Contract

  • Router Endpoint: ANY /functions/v1/<service_name> (main/index.ts).
  • Tables Created/Altered: app_modules, app_modules_maintenance, whitelisted_domains; triggers updated on work_orders & coop_applications writing system_notifications; publication supabase_realtime extended with dealflow_entries.
  • External APIs: https://api.resend.com/emails (_shared/email.ts), FORM_WRITER_URL (_shared/form_link.ts), PA-IDEAS/planovi-docs via gh (scripts/sync-brand.sh).

6. Cross-Repository Dependencies

Caller -> CalleeProtocol & AuthExact Endpoint / Contract
Nginx / Kong -> main/index.tsInternal HTTP, passes all env vars/functions/v1/<service_name> -> EdgeRuntime.userWorkers.create
planovi-flutter-app -> app_modules_maintenancePostgREST / Anon or User JWTSELECT public; ALL for any company admin/owner
planovi-flutter-app -> dealflow_entriesSupabase Realtime (WebSocket + User JWT)supabase_realtime publication filtered by tenant_isolation_dealflow_entries
planovi-microservices / DNS worker -> whitelisted_domainsPostgREST / service_roleReads/verifies txt_verification_token, sets status = 'verified'
scripts/sync-brand.sh -> PA-IDEAS/planovi-docsGitHub CLI (gh)Copies brand-kit/BRANDING_GUIDE.md & brand-kit/assets/

7. Why It Works This Way

  • main/index.ts explicit CPU budget (10s soft / 20s hard) & CORS on errors: Comments (lines 3-4, 29-30) document that edge-runtime v1.54.3 defaults killed process-declaration-ocr (cold start + Gemini) mid-request, and missing CORS on router errors caused browsers to show opaque "Failed to fetch".
  • notify_work_order_events / notify_application_events as SECURITY DEFINER: Documented in 20261105100000:4-15: system_notifications deliberately has no INSERT RLS policy, so non-definer triggers caused 42501 rollback when technicians changed work-order status in Kolejka serwisowa.
  • [TEAM_WHY_NEEDED: In 20240101000000_create_maintenance_table.sql:45-67, why can ANY tenant's company admin/owner modify global app_modules and app_modules_maintenance for the entire multi-tenant platform instead of restricting writes to platform_operators?]
  • [TEAM_WHY_NEEDED: Where is the DNS TXT verification worker for whitelisted_domains implemented (none exists in planovi-backend)?]

8. Debugging, Logs & Common Failure Modes

Symptom / Error MessageRoot Cause in CodeHow to Verify / Exact Query or LogFix
HTTP 503 "Function stopped (time/CPU limit exceeded)"Worker exceeded cpuTimeHardLimitMs: 20_000 or workerTimeoutMs: 300_000 (main/index.ts:28-32, 40-52)Check Edge Runtime logs for [router] <service_name>: + WorkerRequestCancelledOptimize CPU-heavy parsing (e.g., avoid mammoth/large PDF merges in worker) or increase router budget
HTTP 404 "Function not found or failed to load"Syntax/import error or missing folder under /home/deno/functions/<service_name> (main/index.ts:38-52)Inspect [router] <service_name>: details field; run deno check locallyFix TypeScript syntax/imports and redeploy
new row violates row-level security policy for table system_notifications (42501)Notification trigger running as SECURITY INVOKER instead of DEFINERSELECT p.proname, p.prosecdef FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace WHERE n.nspname='public' AND p.proname IN ('notify_work_order_events','notify_application_events','notify_contact_request_events');Apply 20261105100000_notification_triggers_definer.sql
Kanban board does not show new leads until manual refreshdealflow_entries missing from supabase_realtime publicationSELECT tablename FROM pg_publication_tables WHERE pubname='supabase_realtime' AND tablename='dealflow_entries';Apply 20261107120000_realtime_dealflow_entries.sql