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/adminincompany_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 viaCalendarSettingsDialog. - Calendar Delegate: Edit access to another user’s events via
calendar_delegations. - Cooperative Member: Views upcoming invitations & submits RSVP (
accepted/declined) onEnergyDashboardScreen(MeetingInvitationsCard). - External Customer: Books appointment on public
{SCHEDULER_FRONTEND_URL}/?id=<id>, inserting intoscheduler_bookings.
- Company Admin: Full calendar/team switcher,
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 & activecompanyId, uploads logo (<= 2.0 MB,1024×1024, bucketlogos), saves Dealflow and/or Scheduler to PHP FIRST (strictly requiringstatus == 'success'before writing Supabasedealflows/schedulers), constructs iframe (height="600"), displays copyable URLs/iframes. - Side-Panel Quick Scheduler Form (
nowe_zadanie_screen.dart): Opened fromListOfSchedulersScreenFAB/Edit (despite filename meaning “New Task”). Generates'sched_<epochMs>'ID (vsUuid().v4()inKonfiguracjeBrandinguScreen), sets'timezone': 'Europe/Warsaw', callssaveSchedulerConfig(BUG: does NOT checkstatus == 'success'before saving to Supabase!), writes iframe (height="800"). RestoresSharedPreferencesdraftscheduler_form_draft_backupon init (though_saveFormStateLocallyhas 0 callers). - Scheduler List & Iframe Domain Gate (
list_of_schedulers_screen.dart): Queriesschedulersbycompany_id(sorts in-memory bycreated_at DESC), checksDomainVerificationService().fetchDomains(companyId). Direct URL is always shown;iframe_codeis unlocked whendomains.isNotEmpty(BUG: does not requireisVerified!) else auto-prompts inline_showAddDomainDialog. Delete removes Supabase row then best-effort calls PHPdelete_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 launchmeeting_linkand convert todealflow_entries(deal_value: 0,new_lead).BookingDetailsPanelmanagesscheduler_booking_notes+ image uploads (imageQuality: 80→ bucketbooking_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/hr24h grid, live 1-min clock indicator, overlap column clustering, right Agenda sidebar on>=600px). Mergescalendar_events(deduplicated bygroup_id) with activescheduler_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 inSettingsScreenvia 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 1calendar_eventsrow per assignee, logscalendar_event_history, and computes assignee add/remove set deltas on edit. - Governance Meeting (
_isMeeting = true, organizer-only): requirescity,address, org name, ≥1 invitee. Insertsevent_meetings, tagscalendar_events.event_type = 'governance', builds Polish A4 PDF (Robotofonts +assets/brand/logo-black.pngfooter watermark) → uploadsgovernance_documents/<companyId>/meetings/<groupId>.pdf, insertsevent_invitations, invokes externalsend-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
NewEventFormonly): optionally sendsmode: 'cancel', removes PDF, deletesevent_meetings(cascadingevent_invitations), then deletescalendar_events. - Organizer tracks delivery/RSVP pills + 1h signed PDF + Resend Failed in
MeetingStatusSection; members RSVP onEnergyDashboardScreenviaMeetingInvitationsCard.
- Standard event converts local times to UTC, assigns
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 basehttps://dev-scheduler.planovi.app/backend; frontend fallbackhttps://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):
KonfiguracjeBrandinguScreenaborts Supabase write unlesssave_scheduler.phpreturnsstatus == 'success'(konfiguracjebranding_screen.dart:1350-1357; violated byNoweZadanieScreen). - BR-SCHED-03 (Active Company Required):
KonfiguracjeBrandinguScreenblocks save without activeCompanyProvider.currentCompany?.id(konfiguracjebranding_screen.dart:1029-1038). - BR-SCHED-04 (Single Default Scheduler):
is_default == trueclears previous defaults for thatcompany_id(supabase_service.dart:96-102). - BR-SCHED-05 (Slot Durations & Timezone): Allowed
slot_duration ∈ [15, 30, 45, 60]min (default30); 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–Fri09:00–17:00), optionallunch_break(12:00–13:00),exceptions(date_range/time_block); auto-migrates legacyblocked_dates(nowe_zadanie_screen.dart:73-124,241-287). - BR-SCHED-07 (Logo Upload Limits): Max
1024×1024px,<= 2.0 MB, bucketlogos(nowe_zadanie_screen.dart:524-555,konfiguracjebranding_screen.dart:580-612). - BR-SCHED-08 (Iframe Embed Gate):
ListOfSchedulersScreenunlocksiframe_codewhenfetchDomains(companyId).isNotEmpty(list_of_schedulers_screen.dart:218-254,1035-1058). - BR-SCHED-09 (Zone 2 Preview Contrast): Previews bind to tenant
_primaryColor/_accentColor/_bgColorand compute button foreground viaAppColors.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._parseSupabaseTimestampappends'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 bygroup_id; updates/deletes target all rows matching(group_id, company_id)strippingid/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 requireschedules: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_historywrite 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/adminincompany_members; requires ≥1 invitee, org name,city, andaddress; setsevent_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 receivemode: 'invite'; existing receivemode: 'update'withreset_responses: timeChanged || placeChangedwhennotify && 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):
myUpcomingInvitationsfiltersstarts_at >= now() - 12h(limit 20); valid responses'accepted' | 'declined' | 'pending';responded_atnulled 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_bookingswithstatus IN ('pending', 'confirmed')AND non-nulluser_idappear inUnifiedCalendarScreen(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 topendingon 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 -> Callee | Protocol & Auth | Exact Endpoint / Contract |
|---|---|---|
SchedulerApiService / KonfiguracjeBrandinguScreen -> Hostinger PHP Scheduler Backend | HTTPS / 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 Backend | HTTPS / X-Secret-Key (DEALFLOW_API_SECRET) | POST {DEALFLOW_BASE_URL}/save_dealflow.php |
External Customer -> Public Scheduler Frontend -> Supabase scheduler_bookings | HTTPS 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 Supabasetimestamp without time zoneand PHP slots. - Retaining previous
google_access_token/google_refresh_tokenon edit prevents ephemeral Supabase sessions from wiping PHP calendar sync (nowe_zadanie_screen.dart:40-42). - Defensive multi-column lookup on
companieshandles 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
UnifiedCalendarScreenorphans meeting records: Drag-to-trash / agenda delete callsCalendarService.deleteEventdirectly withoutMeetingInvitationService.cancelMeeting, leaving orphanevent_meetings,event_invitations, and storage PDFs with no cancellation email. - Drag-and-drop silently ignored for Admins/Creators:
DraggableallowsisAdmin || isCreator(unified_calendar_screen.dart:1465-1470), butDragTarget.onAcceptWithDetails(line 1634-1638) only acceptsisAssignee || isDelegated! NoweZadanieScreensilently writes broken schedulers when PHP fails: UnlikeKonfiguracjeBrandinguScreen, 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 dropsdefaultValuedue to camelCase vs snake_case mismatch.- RBAC mismatch across Scheduler screens: List checks
schedules_list:*, side-panel checksschedules:*, fullscreen configurator checksconfig:*. - Cross-company delegation query leak:
CalendarSettingsDialog._fetchDelegates(line 39-42) andUnifiedCalendarScreen._fetchTeamMembers(line 133-136) omit.eq('company_id', companyId)oncalendar_delegations. NewEventForm.didUpdateWidgetstale 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':KonfiguracjeBrandinguScreendropdown"Co 2 tygodnie"serializes as'mode': 'weekly'. - Dead code:
CalendarCoopProvider(also writes camelCase'workOrder'vs'work_order'), 4SchedulerApiServicemethods,_saveFormStateLocally(), and placeholder buttons inBookingDetailsPanel. - Log grep:
MEETING,Warning: Failed to save event history,--- SUPABASE BULK INSERT ERROR ---,❌ [DRAFT ERROR].