Skip to content

9. Scheduler, Unified Calendar, Bookings & Meeting Invitations

Repository: Flutter App (planovi-flutter-app) • Rule Prefix: BR-SCHED • Documented Rules: 19 • Open [TEAM_WHY_NEEDED] Questions: 4

1. Business Purpose & Actors

Combines four scheduling/governance capabilities: (1) Public Booking Page / Scheduler builder (KonfiguracjeBrandinguScreen, NoweZadanieScreen, ListOfSchedulersScreen) writing JSON configs to an external PHP backend (SCHEDULER_BASE_URL) and Supabase schedulers; (2) 3-column Inbound Bookings pipeline (SchedulerBookingsScreen, BookingDetailsPanel) with notes, attachments, and 1-click Dealflow conversion; (3) Internal Team UnifiedCalendarScreen merging multi-assignee calendar_events with active scheduler_bookings and calendar_delegations; (4) Energy Cooperative Governance Meetings (“Zebranie”) with A4 PDF invitations (MeetingInvitationPdfService), per-member RSVP tracking (event_invitations), and transactional emails (send-event-invitation).

  • Actors:
    • Company Admin: Full calendar/team switcher, AdminCalendarDelegationsDialog, edit/delete any team event (PermissionProvider.isAdmin).
    • Cooperative Organizer (owner/admin in company_members): Creates/edits/cancels "Zebranie" governance meetings and resends failed invitation emails (MeetingInvitationService.isOrganizer).
    • Regular Employee / CRM User: Gated by calendar:VIEW, team_calendars:VIEW, schedules:CREATE|UPDATE|DELETE, schedules_list:VIEW|CREATE|UPDATE|DELETE, config:VIEW|CREATE|UPDATE, scheduler_bookings:VIEW|UPDATE, dealflow_entries:CREATE; self-delegates via CalendarSettingsDialog.
    • Calendar Delegate: Edit access to another user’s events via calendar_delegations.
    • Cooperative Member: Views upcoming invitations & submits RSVP (accepted/declined) on EnergyDashboardScreen (MeetingInvitationsCard).
    • External Customer: Books appointment on public {SCHEDULER_FRONTEND_URL}/?id=<id>, inserting into scheduler_bookings.

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

  • Fullscreen Branding & Configurator (konfiguracjebranding_screen.dart): Desktop 38%/62% split (Zone 1 editor / Zone 2 live preview with desktop/375px mobile & Scheduler/Dealflow toggles); Mobile 5-step wizard. Validates names & active companyId, uploads logo (<= 2.0 MB, 1024×1024, bucket logos), saves Dealflow and/or Scheduler to PHP FIRST (strictly requiring status == 'success' before writing Supabase dealflows/schedulers), constructs iframe (height="600"), displays copyable URLs/iframes.
  • Side-Panel Quick Scheduler Form (nowe_zadanie_screen.dart): Opened from ListOfSchedulersScreen FAB/Edit (despite filename meaning “New Task”). Generates 'sched_<epochMs>' ID (vs Uuid().v4() in KonfiguracjeBrandinguScreen), sets 'timezone': 'Europe/Warsaw', calls saveSchedulerConfig (BUG: does NOT check status == 'success' before saving to Supabase!), writes iframe (height="800"). Restores SharedPreferences draft scheduler_form_draft_backup on init (though _saveFormStateLocally has 0 callers).
  • Scheduler List & Iframe Domain Gate (list_of_schedulers_screen.dart): Queries schedulers by company_id (sorts in-memory by created_at DESC), checks DomainVerificationService().fetchDomains(companyId). Direct URL is always shown; iframe_code is unlocked when domains.isNotEmpty (BUG: does not require isVerified!) else auto-prompts inline _showAddDomainDialog. Delete removes Supabase row then best-effort calls PHP delete_json.php.
  • Bookings Pipeline (scheduler_bookings_screen.dart, booking_details_panel.dart): 3 columns (Upcoming = pending|confirmed, Completed, Cancelled; drag-and-drop on desktop >900px, tabs on mobile). Optimistic status updates (revert on error). Expandable cards launch meeting_link and convert to dealflow_entries (deal_value: 0, new_lead). BookingDetailsPanel manages scheduler_booking_notes + image uploads (imageQuality: 80 → bucket booking_attachments).
  • Unified Calendar & Delegations (unified_calendar_screen.dart, calendar_service.dart, calendar_settings_dialog.dart, admin_calendar_delegations_dialog.dart): Day/Week/Month views (60px/hr 24h grid, live 1-min clock indicator, overlap column clustering, right Agenda sidebar on >=600px). Merges calendar_events (deduplicated by group_id) with active scheduler_bookings (pending|confirmed, synthetic 'booking_<id>' orange read-only blocks). Note: Does NOT call Google Calendar API directly (Google Calendar API is only invoked by Jarvis Edge Function and external PHP Scheduler). Delegations managed in SettingsScreen via self-service or admin bulk-insert dialogs.
  • New/Edit Event & Governance Meetings (new_event_form.dart, meeting_invitation_service.dart, meeting_invitation_pdf_service.dart, meeting_invitation_widgets.dart):
    • Standard event converts local times to UTC, assigns group_id = Uuid().v4(), fans out 1 calendar_events row per assignee, logs calendar_event_history, and computes assignee add/remove set deltas on edit.
    • Governance Meeting (_isMeeting = true, organizer-only): requires city, address, org name, ≥1 invitee. Inserts event_meetings, tags calendar_events.event_type = 'governance', builds Polish A4 PDF (Roboto fonts + assets/brand/logo-black.png footer watermark) → uploads governance_documents/<companyId>/meetings/<groupId>.pdf, inserts event_invitations, invokes external send-event-invitation (mode: 'invite').
    • Meeting Edit: notifies removed invitees (mode: 'uninvite') BEFORE deleting their rows, inserts new invitees, regenerates PDF, notifies existing (mode: 'update', reset_responses: timeChanged || placeChanged) and new (mode: 'invite').
    • Meeting Cancel (from NewEventForm only): optionally sends mode: 'cancel', removes PDF, deletes event_meetings (cascading event_invitations), then deletes calendar_events.
    • Organizer tracks delivery/RSVP pills + 1h signed PDF + Resend Failed in MeetingStatusSection; members RSVP on EnergyDashboardScreen via MeetingInvitationsCard.

3. Hard Business Rules (BR-SCHED-01..19)

  • BR-SCHED-01 (PHP Auth & Fallbacks): All PHP calls send X-Secret-Key: SCHEDULER_API_SECRET; default base https://dev-scheduler.planovi.app/backend; frontend fallback https://scheduler.planovi.app (release) / https://dev-scheduler.planovi.app (debug) (scheduler_api_service.dart:10-17,27-136, app_config.dart:34-42).
  • BR-SCHED-02 (PHP-First Atomic Sync): KonfiguracjeBrandinguScreen aborts Supabase write unless save_scheduler.php returns status == 'success' (konfiguracjebranding_screen.dart:1350-1357; violated by NoweZadanieScreen).
  • BR-SCHED-03 (Active Company Required): KonfiguracjeBrandinguScreen blocks save without active CompanyProvider.currentCompany?.id (konfiguracjebranding_screen.dart:1029-1038).
  • BR-SCHED-04 (Single Default Scheduler): is_default == true clears previous defaults for that company_id (supabase_service.dart:96-102).
  • BR-SCHED-05 (Slot Durations & Timezone): Allowed slot_duration ∈ [15, 30, 45, 60] min (default 30); no buffer time; timezone hardcoded to 'Europe/Warsaw' (scheduler_config.dart:54,61, nowe_zadanie_screen.dart:70,1354-1355).
  • BR-SCHED-06 (Availability & Legacy Migration): Modes 'daily' (09:00–17:00) or 'weekly' ('1'..'7', Mon–Fri 09:00–17:00), optional lunch_break (12:00–13:00), exceptions (date_range / time_block); auto-migrates legacy blocked_dates (nowe_zadanie_screen.dart:73-124,241-287).
  • BR-SCHED-07 (Logo Upload Limits): Max 1024×1024 px, <= 2.0 MB, bucket logos (nowe_zadanie_screen.dart:524-555, konfiguracjebranding_screen.dart:580-612).
  • BR-SCHED-08 (Iframe Embed Gate): ListOfSchedulersScreen unlocks iframe_code when fetchDomains(companyId).isNotEmpty (list_of_schedulers_screen.dart:218-254,1035-1058).
  • BR-SCHED-09 (Zone 2 Preview Contrast): Previews bind to tenant _primaryColor/_accentColor/_bgColor and compute button foreground via AppColors.contrastOn(_primaryColor) (luminance > 0.42 ? #09090B : white) (konfiguracjebranding_screen.dart:143-149,2766-2782, app_colors.dart:97-98).
  • BR-SCHED-10 (Strict UTC Persistence): CalendarEventModel._parseSupabaseTimestamp appends 'Z' if timezone suffix absent; toJson() emits .toUtc().toIso8601String(); UI converts .toLocal() (calendar_event_model.dart:82-92,107-108,126-127).
  • BR-SCHED-11 (Group Event Fan-Out & Deduplication): 1 row per assignee sharing group_id = Uuid().v4(); UI deduplicates by group_id; updates/deletes target all rows matching (group_id, company_id) stripping id/user_id (calendar_service.dart:69-87,112-120, unified_calendar_screen.dart:473-481).
  • BR-SCHED-12 (Calendar Authorization & Delegations): Team switcher requires isAdmin || team_calendars:VIEW; create/delete require schedules:CREATE/DELETE; edit requires (isAssignee || isCreator || isDelegated || isAdmin) && !isExternalBooking; self-delegation & duplicate (owner_id, delegate_id) blocked (unified_calendar_screen.dart:861-864,948-949,1458-1470).
  • BR-SCHED-13 (Non-Blocking Event Audit Log): calendar_event_history write errors are caught and logged without failing the event write (calendar_service.dart:51-54,99-103,134-148).
  • BR-SCHED-14 (Governance Meeting Eligibility & Validation): Organizer must be active owner/admin in company_members; requires ≥1 invitee, org name, city, and address; sets event_type = 'governance' (meeting_invitation_service.dart:65-82,174-182, new_event_form.dart:424-437).
  • BR-SCHED-15 (Meeting Update Notification & RSVP Reset): Removed invitees receive mode: 'uninvite' BEFORE row deletion; added invitees always receive mode: 'invite'; existing receive mode: 'update' with reset_responses: timeChanged || placeChanged when notify && detailsChanged (meeting_invitation_service.dart:304-314,337-409).
  • BR-SCHED-16 (Meeting PDF Storage & Signed URL TTL): Stored at governance_documents/<companyId>/meetings/<groupId>.pdf (upsert: true); PDF failure is non-fatal; signed download URL TTL = 3600s (1h) (meeting_invitation_service.dart:57,184-210,517-525).
  • BR-SCHED-17 (Upcoming Invitation Window & RSVP): myUpcomingInvitations filters starts_at >= now() - 12h (limit 20); valid responses 'accepted' | 'declined' | 'pending'; responded_at nulled on 'pending' (meeting_invitation_service.dart:491-515).
  • BR-SCHED-18 (Booking-to-Dealflow Transfer): Requires dealflow_entries:CREATE; inserts {deal_value: 0, current_stage: 'new_lead', custom_field_data} (scheduler_bookings_screen.dart:160,514-535).
  • BR-SCHED-19 (Calendar Booking Filter): Only scheduler_bookings with status IN ('pending', 'confirmed') AND non-null user_id appear in UnifiedCalendarScreen (unified_calendar_screen.dart:185-195).

4. State Machines & Data Lifecycle

stateDiagram-v2
    [*] --> pending: External booking / invitation created
    pending --> completed: Booking marked done (removed from Calendar)
    pending --> cancelled: Booking cancelled (removed from Calendar)
    completed --> pending: Drag back to Upcoming
    cancelled --> pending: Drag back to Upcoming
    cancelled --> completed: Drag to Completed
  • Meeting RSVP (event_invitations.response): pending → accepted ↔ declined → reset to pending on date/place edit (reset_responses: true) → hard-deleted on uninvite/cancel.
  • Meeting Email Delivery (event_invitations.email_status): queued → sent | failed (retryable) | no_email (app-only).

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

  • Tables: schedulers, dealflows, scheduler_bookings, scheduler_booking_notes, dealflow_entries, calendar_events, calendar_event_history, calendar_delegations, event_meetings, event_invitations, companies, company_members, user_profiles, user_roles, roles, whitelisted_domains, user_google_tokens.
  • Storage Buckets: logos (public), booking_attachments (public), governance_documents (private, 1h signed URLs).
  • RPCs: None directly in Module 9.

6. Cross-Repository Dependencies

Caller -> CalleeProtocol & AuthExact Endpoint / Contract
SchedulerApiService / KonfiguracjeBrandinguScreen -> Hostinger PHP Scheduler BackendHTTPS / X-Secret-Key (SCHEDULER_API_SECRET)POST {SCHEDULER_BASE_URL}/save_scheduler.php, POST /delete_json.php (unused: PUT save_scheduler.php, GET get_schedulers.php, POST save_dealflow.php)
KonfiguracjeBrandinguScreen -> Hostinger PHP Dealflow BackendHTTPS / X-Secret-Key (DEALFLOW_API_SECRET)POST {DEALFLOW_BASE_URL}/save_dealflow.php
External Customer -> Public Scheduler Frontend -> Supabase scheduler_bookingsHTTPS Public -> DB Insert{SCHEDULER_FRONTEND_URL}/?id=<schedulerId> writes bookings to scheduler_bookings
MeetingInvitationService -> External Edge Function send-event-invitation (absent from repo!)HTTPS / User JWT (functions.invoke)`{event_group_id, panel_url, mode: ‘invite’

7. Why It Works This Way

  • Forced UTC 'Z' parsing (calendar_event_model.dart:81-92) and hardcoded 'Europe/Warsaw' (nowe_zadanie_screen.dart:1354) fix timestamp shift bugs between Supabase timestamp without time zone and PHP slots.
  • Retaining previous google_access_token/google_refresh_token on edit prevents ephemeral Supabase sessions from wiping PHP calendar sync (nowe_zadanie_screen.dart:40-42).
  • Defensive multi-column lookup on companies handles dev/prod schema differences (meeting_invitation_service.dart:84-101).
  • [TEAM_WHY_NEEDED: Why do parallel editors NoweZadanieScreen and KonfiguracjeBrandinguScreen coexist with different ID formats (sched_<ms> vs UUID), iframe heights (800 vs 600), and error handling?]
  • [TEAM_WHY_NEEDED: Where is the send-event-invitation Edge Function source code hosted?]
  • [TEAM_WHY_NEEDED: Why do scheduler editors read Google tokens from ephemeral session/userMetadata instead of user_google_tokens?]
  • [TEAM_WHY_NEEDED: Why was CalendarCoopProvider written with soft-delete + Realtime + coop_id but never registered in main.dart or used by any screen?]

8. Debugging, Logs & Common Failure Modes

  • Deleting governance meeting from UnifiedCalendarScreen orphans meeting records: Drag-to-trash / agenda delete calls CalendarService.deleteEvent directly without MeetingInvitationService.cancelMeeting, leaving orphan event_meetings, event_invitations, and storage PDFs with no cancellation email.
  • Drag-and-drop silently ignored for Admins/Creators: Draggable allows isAdmin || isCreator (unified_calendar_screen.dart:1465-1470), but DragTarget.onAcceptWithDetails (line 1634-1638) only accepts isAssignee || isDelegated!
  • NoweZadanieScreen silently writes broken schedulers when PHP fails: Unlike KonfiguracjeBrandinguScreen, ignores PHP error responses (nowe_zadanie_screen.dart:1398-1407); also initializes hex text controllers to legacy teal/navy ('2DD4BF'/'14B8A6'/'0F172A') while color swatches start at Planovi green/graphite, and drops defaultValue due to camelCase vs snake_case mismatch.
  • RBAC mismatch across Scheduler screens: List checks schedules_list:*, side-panel checks schedules:*, fullscreen configurator checks config:*.
  • Cross-company delegation query leak: CalendarSettingsDialog._fetchDelegates (line 39-42) and UnifiedCalendarScreen._fetchTeamMembers (line 133-136) omit .eq('company_id', companyId) on calendar_delegations.
  • NewEventForm.didUpdateWidget stale meeting state: Switching events in an open side panel does not re-call _loadEditMeeting() (new_event_form.dart:172-179).
  • Bi-weekly schedule silently stored as 'weekly': KonfiguracjeBrandinguScreen dropdown "Co 2 tygodnie" serializes as 'mode': 'weekly'.
  • Dead code: CalendarCoopProvider (also writes camelCase 'workOrder' vs 'work_order'), 4 SchedulerApiService methods, _saveFormStateLocally(), and placeholder buttons in BookingDetailsPanel.
  • Log grep: MEETING , Warning: Failed to save event history, --- SUPABASE BULK INSERT ERROR ---, ❌ [DRAFT ERROR].