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 managingapp_modules_maintenanceandwhitelisted_domains, technicians/applicants triggeringsystem_notificationsviawork_ordersandcoop_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", returns200 { 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 proxiesworker.fetch(req). - Failure: Catches worker errors, attaches CORS headers, returns
503("Function stopped (time/CPU limit exceeded)") if error name/message indicatesWorkerRequestCancelled/"cancelled", otherwise404("Function not found or failed to load").
- Shared Libraries (
supabase/functions/_shared/):auth.ts: ProvidesrequireUser,activeRole,hasRbacPermission,requireStaff,jsonResponse,errorResponse,httpError,UUID_RE,corsHeaders, andvalidateAuth(handlesOPTIONS,x-cron-secret,Bearer <service_role>,Bearer <CRON_SECRET>, or GoTrueauth.getUser).email.ts: ProvidesescapeHtml,escapeMultiline,unsubscribeUrlFor,ctaButton, Zone 1emailShell, andsendEmail(Resend APIPOST https://api.resend.com/emailswithAbortSignal.timeout(15_000)).form_link.ts: ProvidesformBaseUrl,writeFormJson(15s timeout toFORM_WRITER_URLwithX-Api-Secret),cleanPreviewUrl,sanitizeLabelHtml,loadMemberForm,loadMemberFields,loadMemberValues, andissueFormLink(72h TTL, reuse/revoke logic).docx.ts: ProvidesgenerateDeclarationDocx(PizZip+Docxtemplaterplaceholder rendering) and chunkedtoBase64(CHUNK = 0x8000).declaration_template_move.ts: ProvidescarryAnswersToTemplate(field_keymatching,number -> textconversion) andmissingRequiredFields.declaration_values.ts: ProvidesconvertValue(7 data types),normalizeDate,toBool,isEmptyValue, andvalidationResponse(HTTP 422 batch errors).
- Platform Maintenance Registry (
20240101000000_create_maintenance_table.sql):- Creates
public.app_modules(19 initial modules) and 1:1public.app_modules_maintenance(is_under_maintenance,maintenance_message,bypass_for_admins,start_time,end_time). Publicly readable (USING (true)), writable by any user who isadmin/ownerin any company.
- Creates
- Iframe Domain Whitelist (
20261022000000_create_whitelisted_domains_table.sql):- Creates
public.whitelisted_domains(company_id,domain,txt_verification_token,statusin'pending'|'verified'|'revoked',verified_at,ga4_measurement_id, unique(company_id, domain)). Readable by company members; writable by companyadmin/ownerandservice_role.
- Creates
- Definer Notification Triggers (
20261105100000_notification_triggers_definer.sql):- Rewrites
notify_work_order_events()andnotify_application_events()asSECURITY DEFINER(search_path = public, pg_temp, revoked frompublic) so app users changing ticket/application statuses can trigger inserts intosystem_notificationswithout needing an INSERT RLS policy onsystem_notifications.
- Rewrites
- Kanban Realtime (
20261107120000_realtime_dealflow_entries.sql):- Idempotently adds
public.dealflow_entriestosupabase_realtimepublication (RLS-scoped viatenant_isolation_dealflow_entries).
- Idempotently adds
- Brand Kit Sync (
scripts/sync-brand.sh):- Shallow-clones
PA-IDEAS/planovi-docsviagh repo cloneinto temp dir and overwrites./BRANDING_GUIDE.mdand./assets/brand/.
- Shallow-clones
3. Hard Business Rules, Validations, Calculations & Edge Cases (BR-CORE)
BR-CORE-01(Worker Resource Limits): Every Edge Function executed viamain/index.ts:27-32is bounded bymemoryLimitMb: 150,workerTimeoutMs: 300_000(5 min),cpuTimeSoftLimitMs: 10_000,cpuTimeHardLimitMs: 20_000. Exceeding CPU/time limits returns HTTP503with CORS headers.BR-CORE-02(validateAuthPrecedence):_shared/auth.ts:113-176evaluates: (1)OPTIONS->200 "ok"; (2)x-cron-secret === CRON_SECRET; (3)Bearer===SUPABASE_SERVICE_ROLE_KEY; (4)Bearer===CRON_SECRET; (5)Bearervalidated as any Supabase user JWT viaauth.getUser. Defaultoptionsenables all three (allowUser: true).BR-CORE-03(requireStaffRBAC Rule):_shared/auth.ts:64-73validatesUUID_RE(400), checks activecompany_members(403), bypasses forrole IN ('admin', 'owner'), and falls back tohasRbacPermission(companyId, userId, 'team_declarations', action)whereuser_overridesrevoke (is_granted = false) beats grant (is_granted = true), which beats baseuser_roles -> role_permissions. (Note: Drifts from DB20261116150000owner-only bypass.)BR-CORE-04(Resend Email Transport Timeout & Defaults):_shared/email.ts:81-114enforcesAbortSignal.timeout(15_000), defaultsFROM_EMAILto"noreply@planovi.app"andREPLY_TO_EMAILto"info@planovi.app", formats sender asPlanovi <${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_ordersINSERT with non-nulltechnician_id-> notifies technician (type: 'work_order',"Nowe zgłoszenie").work_ordersUPDATEstatus -> 'completed'(IS DISTINCT FROM) -> notifies all activeowner/adminofcompany_id(type: 'system_alert',"Zgłoszenie zakończone").coop_applicationsUPDATE('draft'|'awaiting_correction') -> 'submitted'-> notifies activeowner/admin("Nowa Deklaracja").coop_applicationsUPDATE'submitted' -> 'awaiting_correction'-> notifiesnew.user_id("Deklaracja wymaga poprawek").coop_applicationsUPDATE-> 'approved'(IS DISTINCT FROM) -> notifiesnew.user_id("Witaj w Spółdzielni!").
BR-CORE-06(Whitelisted Domain Uniqueness):whitelisted_domainsenforcesUNIQUE (company_id, domain)and defaultsstatus = 'pending'.
4. State Machines & Data Lifecycle
whitelisted_domains.status:'pending'->'verified'(setsverified_at) |'revoked'. (No DB CHECK constraint; enforced by convention.)app_modules_maintenance.is_under_maintenance:false(default) <->true(optionalstart_time/end_time,bypass_for_adminsdefaulttrue).
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 onwork_orders&coop_applicationswritingsystem_notifications; publicationsupabase_realtimeextended withdealflow_entries. - External APIs:
https://api.resend.com/emails(_shared/email.ts),FORM_WRITER_URL(_shared/form_link.ts),PA-IDEAS/planovi-docsviagh(scripts/sync-brand.sh).
6. Cross-Repository Dependencies
| Caller -> Callee | Protocol & Auth | Exact Endpoint / Contract |
|---|---|---|
Nginx / Kong -> main/index.ts | Internal HTTP, passes all env vars | /functions/v1/<service_name> -> EdgeRuntime.userWorkers.create |
planovi-flutter-app -> app_modules_maintenance | PostgREST / Anon or User JWT | SELECT public; ALL for any company admin/owner |
planovi-flutter-app -> dealflow_entries | Supabase Realtime (WebSocket + User JWT) | supabase_realtime publication filtered by tenant_isolation_dealflow_entries |
planovi-microservices / DNS worker -> whitelisted_domains | PostgREST / service_role | Reads/verifies txt_verification_token, sets status = 'verified' |
scripts/sync-brand.sh -> PA-IDEAS/planovi-docs | GitHub CLI (gh) | Copies brand-kit/BRANDING_GUIDE.md & brand-kit/assets/ |
7. Why It Works This Way
main/index.tsexplicit CPU budget (10ssoft /20shard) & CORS on errors: Comments (lines 3-4, 29-30) document thatedge-runtime v1.54.3defaults killedprocess-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_eventsasSECURITY DEFINER: Documented in20261105100000:4-15:system_notificationsdeliberately has noINSERTRLS policy, so non-definer triggers caused42501rollback 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 Message | Root Cause in Code | How to Verify / Exact Query or Log | Fix |
|---|---|---|---|
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>: + WorkerRequestCancelled | Optimize 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 locally | Fix 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 DEFINER | SELECT 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 refresh | dealflow_entries missing from supabase_realtime publication | SELECT tablename FROM pg_publication_tables WHERE pubname='supabase_realtime' AND tablename='dealflow_entries'; | Apply 20261107120000_realtime_dealflow_entries.sql |