Skip to content
📦 ARCHIVED SNAPSHOT (v1.0) You are viewing historical business logic and documentation for Flutter App v1.0 (frozen on 2026-11-23, commit 92290cf7). Switch to Latest →

1. Platform Shell, Config, Theme/Branding, i18n, Splash, Maintenance & Observability

Repository: Flutter App (planovi-flutter-app) • Rule Prefix: BR-CORE • Documented Rules: 20 • Open [TEAM_WHY_NEEDED] Questions: 2

1. Business Purpose & Actors

Provides application bootstrap, multi-platform shell navigation (MainLayout + SidePanelOverlay), Zone 1/Zone 2 design tokens (AppColors, AppTheme, PlanoviLogo, PlanoviLoader), Polish/English localization (LocalString / LanguageService), video-to-Hero splash handoff (web/index.html + SplashVideoGate), Cloudflare Turnstile anti-bot widget, SaaS seat-based LicenseGate, Realtime per-module maintenance blocking (MaintenanceProvider), shared Storage uploads (StorageService), and multi-sink error observability (AppErrorLogger, ErrorLogService, AppErrorHandler).

  • Actors: Unauthenticated visitors (Splash, Turnstile, language/theme toggles), Standard/Coop Members (subject to LicenseGate, RBAC, maintenance blocks), Technicians (technician role auto-granted tab 26), Company Admins (isAdmin bypasses RBAC, maintenance when bypass_for_admins = true, and seat requirement on active plans), Owners/Billing Managers (can_manage_billing = true gets "Przejdź do płatności" CTA in LicenseGate), Platform Operators (is_platform_operator() == true gets "Panel operatora" nav entry).

2. All Features & End-to-End Flows (Happy Path + Error Paths)

  • Bootstrap (lib/main.dart:78-136): WidgetsFlutterBinding.ensureInitialized() → Firebase.initializeApp (non-blocking try/catch; registers FlutterError.onError and PlatformDispatcher.instance.onError) → dotenv.load('assets/env') fallback .env → registerWebViewWithWeb() (no-op) → initializeDateFormatting('pl', null) → PendingAuthLink.captureFromUrl() → SupabaseService.initialize() → SessionEndNotice.init() → load persisted locale & theme → mount MultiProvider (18 providers) → GetMaterialApp route '/': SplashVideoGate -> AuthLinkGate -> AuthWrapper.
  • Navigation Shell (lib/core/layout/main_layout.dart, lib/main.dart:261-406):
    • Desktop (width >= 1024px): permanent collapsible sidebar (256px / 72px) + sliding right SidePanelOverlay (480px, 320ms). Mobile/Tablet (< 1024px): AppBar + Drawer + full-width SidePanelOverlay. (Note separate inner-screen ResponsiveLayout uses <850 / 850..1099 / >=1100.)
    • Indices 0..29 + 99: 0 = DashboardScreen (or 99 EnergyDashboardScreen in coop mode), 1 = JarvisVoiceScreen, 2 = ClientsListScreen, 3 = UnifiedCalendarScreen, 4 = 'Operacje Content (Placeholder)', 5 = 'Strategia Content (Placeholder)', 6 = SettingsScreen, 7 = KonfiguracjeBrandinguScreen, 8 = ListOfDealflowsScreen, 9 = DealflowEntriesScreen, 10 = ListOfSchedulersScreen, 11 = RbacUnifiedScreen, 12 = DocumentsListScreen, 13 = SchedulerBookingsScreen, 14 = OffersListScreen, 15 = AgreementsListScreen, 16 = OfferTemplatesListScreen, 17 = AgreementTemplatesListScreen, 18 = TemplatesCombinedScreen, 20 = MyDevicesScreen, 21 = EnergyBalanceScreen, 22 = KnowledgeBaseScreen, 23 = TeamDeclarationsScreen, 24 = GovernanceCenterScreen, 25 = MemberWalletScreen, 26 = TechnicianQueueScreen, 27 = FinancialLedgerScreen, 28 = CoopSettingsScreen, 29 = UsersLicensesScreen.
    • On tab click: fires background PermissionProvider.loadPermissions(), checks MaintenanceProvider.isModuleUnderMaintenance() (shows ModuleMaintenanceDialog and blocks switch if active), closes SidePanelController/Drawer, updates index. Live PlanoviAppHome.build() swaps active view to ModuleMaintenanceScreen if maintenance toggles on mid-session.
  • Splash Handoff (web/index.html, splash_bridge*.dart, splash_video_gate.dart):
    • Web: DOM #planovi-splash plays splash-dark.mp4 / splash-light.mp4 (from localStorage['flutter.theme_mode']) starting at 0.65s at 1.65x, holds frame at 5.05s. LoginScreen reports exact PlanoviLogo rect (data-target="login", planovi-splash-target); JS measures paused video wordmark via 192x108 canvas scan, fades backdrop (0.42s), flies crisp SVG #planovi-splash-hero-logo (0.72s cubic-bezier(0.22,1,0.36,1)), dispatches planovi-splash-landed, removes overlay after 2 rAFs. Hard safety timeout: 7.0s (JS) / 4.5s (SplashBridge).
    • Mobile: SplashVideoGate plays bundled MP4, flies detached PlanoviLogo (700ms), 6.5s hard timeout, fallback static logo (1200ms).
  • License Gate (lib/core/widgets/license_gate.dart): Prefetched in parallel by PermissionGate (single-use cache, TTL 20s), calls my_license_access(p_company_id). Blocks all users when !has_licenses || !has_active_license || subscription_status in {'canceled','unpaid','incomplete_expired'}; allows admins or has_seat == true on active plans; fail-closed (_Access.checkFailed) on RPC error. Calls my_billing_access(p_company_id) for "Przejdź do płatności" CTA; else displays companies.contact_email/email or company_admin_contacts(p_company_id).
  • Maintenance Sync (lib/core/providers/maintenance_provider.dart): Fetches app_modules_maintenance joined app_modules, subscribes to Realtime channel maintenance_sync_channel (PostgresChangeEvent.all), re-fetches on any DB change.
  • Turnstile (turnstile_widget.dart, turnstile_web_impl.dart, web/turnstile.html): Web renders 320x80 HtmlElementView iframe communicating via window.postMessage(..., "*") (turnstile_token / turnstile_error / reset). Mobile uses webview_flutter + JS channel TurnstileChannel (currently broken because TurnstileConfig.baseUrl returns 'io.supabase.planovi://').
  • Error Observability (app_error_logger.dart, error_log_service.dart, snackbar_helper.dart): Fatal UI/async crashes go to Crashlytics (mobile) + Google Chat webhook (all platforms, threaded by planovi_<screen>_<errorType>, 60s dedupe). "Raport" button on MySnackBar.errorSnackbar inserts into error_logs and forwards to AppErrorLogger.logNonFatal.

3. Hard Business Rules (BR-CORE-01..20)

  • BR-CORE-01: SupabaseService._pick (lib/core/services/supabase_service.dart:19-35) resolves SUPABASE_URL/SUPABASE_ANON_KEY strictly in order: --dart-define > dotenv (assets/env fallback .env) > hardcoded prod fallback (https://api.planovi.app).
  • BR-CORE-02: AppConfig (lib/core/config/app_config.dart:4-42) resolves dealflowFrontendUrl (DEALFLOW_FRONTEND_URL > release https://dealflow.planovi.app / debug https://dev-dealflow.planovi.app) and schedulerFrontendUrl (SCHEDULER_FRONTEND_URL > release https://scheduler.planovi.app / debug https://dev-scheduler.planovi.app).
  • BR-CORE-03: LicenseGate._performCheck (license_gate.dart:100-128) blocks ALL users (including admins/owners) when !has_licenses || !has_active_license || subscription_status in {'canceled', 'unpaid', 'incomplete_expired'}.
  • BR-CORE-04: On an active subscription, admins/owners (is_admin || PermissionProvider.isAdmin) bypass seat assignment (license_gate.dart:124); non-admins require has_seat == true.
  • BR-CORE-05: LicenseGate is fail-closed: RPC error or non-Map payload sets _Access.checkFailed (license_gate.dart:149-162). Prefetch cache is single-use, user-matched, and valid < 20s (license_gate.dart:224-230).
  • BR-CORE-06: "Przejdź do płatności" in LicenseGate requires my_billing_access.can_manage_billing == true (fallback to isAdmin on RPC failure) (license_gate.dart:197-208,321). Blocked contact resolution prefers companies.contact_email/email (containing '@') over company_admin_contacts (license_gate.dart:165-195).
  • BR-CORE-07: PlanoviAppHome airlock (lib/main.dart:505-529) blocks missing workspace ('Nie masz przypisanego aktywnego workspace...') unless session is expired/null (triggers _recoverExpiredSession() refresh + revalidateSession(), signing out with SessionEndNotice.expired on permanent auth failure), and blocks suspended workspaces ('To środowisko zostało zawieszone...').
  • BR-CORE-08: MaintenanceProvider.isModuleUnderMaintenance (maintenance_provider.dart:113-124) blocks access when is_under_maintenance == true unless bypass_for_admins == true && isAdmin == true. Time bounds (start_time/end_time) are display-only and NOT evaluated for blocking.
  • BR-CORE-09: PlanoviAppHome._canAccessScreen (main.dart:368-372) returns true optimistically while permissions.isLoading && currentUserRole == null, and always returns true for permissions.isAdmin.
  • BR-CORE-10: In coop mode (isCoopModeActive), tab index 0 aliases to _cachedScreens[99] (EnergyDashboardScreen) (main.dart:362-364). Switching workspace ID or coop/standard mode resets _currentIndex = 0 (main.dart:310-314, main_layout.dart:190-195).
  • BR-CORE-11: "Panel operatora" nav entry appears only when RPC is_platform_operator() returns true (main_layout.dart:68-76,958-975).
  • BR-CORE-12: ThemeProvider (theme_provider.dart:5-20) defaults to ThemeMode.dark (#09090B) unless SharedPreferences['theme_mode'] == 'light'.
  • BR-CORE-13: Zone 2 dynamic button foreground contrast (app_colors.dart:97-98): background.computeLuminance() > 0.42 ? Color(0xFF09090B) : Colors.white.
  • BR-CORE-14: PlanoviLogo (planovi_logo.dart:48-49) clamps wordmark height to >= 20.0px with fixed 1284 / 375 aspect ratio.
  • BR-CORE-15: Splash hard safety timeouts: Web 7.0s (web/index.html:359), Web SplashBridge 4.5s (splash_bridge_web.dart:38), Mobile 6.5s (splash_video_gate.dart:52); min playback 2.65s (fallback 1.2s/1.4s), wordmark hold 5.05s at 1.65x from 0.65s.
  • BR-CORE-16: FlutterError.onError (main.dart:89-97) ignores silent, 'is invisible', 'A RenderFlex overflowed', and 'pointer'. AppErrorLogger (app_error_logger.dart:135-172) deduplicates identical alerts for 60s (GC at 120s) and caps stack traces at 4 lines.
  • BR-CORE-17: invokeEdgeFunction (edge_functions.dart:18-37) requires HTTP 2xx AND JSON data['success'] == true; otherwise throws EdgeFunctionException.
  • BR-CORE-18: StorageService.safeKey (storage_service.dart:208-219) transliterates Polish diacritics to ASCII and replaces non-[a-zA-Z0-9._-] with _ (avoids Supabase 400 InvalidKey). deleteClientFiles verifies removal via storage.list(search:) and throws 'Nie udało się usunąć X z Y plików z serwera.' if objects remain (storage_service.dart:175-201).
  • BR-CORE-19: SupabaseService.saveConfiguration (supabase_service.dart:96-121) clears is_default = false on existing company rows in dealflows/schedulers before inserting is_default: true.
  • BR-CORE-20: LanguageService (language_service.dart) defaults to Locale('pl', 'PL') with en_US fallback; MyText.selectable defaults to false (my_text.dart:28-55). strings.dart declares 3,612 constants; local_string.dart maps 3,598 unique keys per locale (with 157 PL / 106 EN duplicate entries and 8 Polish string collisions).

4. State Machines & Data Lifecycle

stateDiagram-v2
    [*] --> Loading: LicenseGate mounts
    Loading --> Allowed: active plan & (isAdmin || has_seat)
    Loading --> NoSeat: active plan & !isAdmin & !has_seat
    Loading --> InactiveAdmin: no active plan / dead status & isAdmin
    Loading --> InactiveMember: no active plan / dead status & !isAdmin
    Loading --> CheckFailed: my_license_access RPC error
    InactiveAdmin --> Loading: return from BillingScreen / Retry
    NoSeat --> Loading: Retry
    InactiveMember --> Loading: Retry
    CheckFailed --> Loading: Retry
  • Splash: Boot → (appReady && targetReady && minTimePassed) || safetyTimeout → HeroFlight (login) / BackdropFade (authenticated) → Landed → Removed.
  • Maintenance: Empty → Loaded + Realtime maintenance_sync_channel → per-module Active <-> Blocked (admin bypassed if bypass_for_admins).
  • Persistence Keys: SharedPreferences: theme_mode, locale_lang_code, locale_country_code, reopen_scheduler_form; FlutterSecureStorage: auth_token (unused ApiClient).

5. Technical Contract (Inputs → Processing → Side Effects)

  • Tables: app_modules_maintenance (R + Realtime), app_modules (R), error_logs (W), companies (R), company_members (R), dealflows/schedulers (CRUD).
  • RPCs: is_platform_operator(), my_license_access(p_company_id), my_billing_access(p_company_id), company_admin_contacts(p_company_id).
  • Storage Bucket: company-media ({companyId}/logos|avatars|signatures|clients|recordings/...).
  • Browser Events & PostMessage: Window events flutter-first-frame, planovi-splash-target, planovi-splash-landed; Turnstile postMessage JSON {type: 'turnstile_token'|'turnstile_error'} / {action: 'reset'}.

6. Cross-Repository Dependencies

Caller -> CalleeProtocol & AuthExact Endpoint / Contract
Flutter -> planovi-backend (Supabase)HTTPS / Supabase Anon + User JWT${SUPABASE_URL}/rest/v1/*, /rpc/*, /storage/v1/object/company-media/*, /functions/v1/*
Flutter -> planovi-microservices (Dealflow/Scheduler)HTTPS Public Links / Embeds${DEALFLOW_FRONTEND_URL}/offer.php?id=..., ${SCHEDULER_FRONTEND_URL}/?id=...
scripts/sync-brand.sh -> PA-IDEAS/planovi-docsgh repo clone (GitHub CLI auth)Copies brand-kit/BRANDING_GUIDE.md & brand-kit/assets/
AppErrorLogger -> Google Chat WebhookHTTPS POST (Webhook query key/token)${GOOGLE_CHAT_WEBHOOK_URL}&messageReplyOption=REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD
web/turnstile.html -> Cloudflare TurnstileHTTPS JS SDK (Public Sitekey)https://challenges.cloudflare.com/turnstile/v0/api.js
Flutter Mobile -> Firebase CrashlyticsFirebase SDK (google-services.json / firebase_options.dart)Project planovi-484112 (web, android, ios)

7. Why It Works This Way

  • SupabaseService._pick prioritizes --dart-define then assets/env (dev.public.env/prod.public.env injected by CI) to stop dev-panel builds from hitting production (supabase_service.dart:14-18).
  • PlanoviLoader synchronizes animation phase to DateTime.now().millisecondsSinceEpoch % 2200 (planovi_loader.dart:29-32) so sequential bootstrap gates (AuthWrapper -> CompanyGate -> PermissionGate -> LicenseGate) transition without resetting the spinner.
  • StorageService.deleteClientFiles re-lists Storage after .remove() because Supabase Storage returns HTTP 200 silently when RLS blocks deletion (storage_service.dart:171-201).
  • [TEAM_WHY_NEEDED: Tabs 4 (Operacje) and 5 (Strategia) in lib/main.dart:266-267 are still placeholder Text widgets despite having sidebar items and RBAC keys — are they planned modules or slated for removal?]
  • [TEAM_WHY_NEEDED: Why does Tab 18 (TemplatesCombinedScreen under Administracja) duplicate Tabs 16/17 (Offer/Agreement Templates under Sprzedaż)?]

8. Debugging, Logs & Common Failure Modes

  • Wrong Supabase env at startup -> assets/env missing or overridden -> check console 'Supabase API: <url>' (supabase_service.dart:38) -> verify CI env file or --dart-define.
  • LicenseGate stuck on "Nie udało się sprawdzić licencji" -> my_license_access RPC error / expired JWT -> grep 'LicenseGate: check failed' (license_gate.dart:150) -> retry or re-login.
  • Tabs 14–18 ignore maintenance mode -> MaintenanceProvider.getModuleNameForIndex() (maintenance_provider.dart:133-186) omits indices 14–18 (returns 'unknown') -> add explicit mappings.
  • Mobile Turnstile fails to load -> TurnstileConfig.baseUrl returns 'io.supabase.planovi://' on mobile (turnstile_widget.dart:92-93) -> load HTTPS panel origin or inline HTML.
  • Missing Google Chat crash alerts -> suppressed by FlutterError.onError filter or 60s dedupe cache -> check '[ChatSpace Webhook Dispatch Error]'.
  • SnackBar titles remain Polish in English UI -> snackbar_helper.dart:27,73 passes '${AppString.lblError} :' to MyText (unmapped key) -> translate key before appending ' :'.