Skip to content
📦 ARCHIVED SNAPSHOT (v1.0) You are viewing historical business logic and documentation for Microservices (PHP) v1.0 (frozen on 2026-11-23, commit 96144c89). Switch to Latest →

1. Public Appointment Scheduler & Google Calendar Sync

Repository: Microservices (planovi-microservices) • Rule Prefix: BR-SCH • Documented Rules: 14 • Open [TEAM_WHY_NEEDED] Questions: 4

1. Business Purpose & Actors

  • Problem Solved: Allows Planovi tenants (businesses/cooperatives) to publish white-labeled, embeddable (<iframe>) appointment booking calendars backed by dual availability checking (Google Calendar FreeBusy + Planovi Supabase scheduler_bookings) and automatic Google Meet link creation.
  • Actors:
    • Tenant Admin (via planovi-flutter-app): Creates/updates/deletes scheduler configurations and links a Google Calendar via OAuth.
    • External Visitor / Prospective Client: Opens scheduler/index.php?id={cal_id} (directly or inside a customer website <iframe>), selects a date and time slot (displayed in visitor’s local browser timezone), fills default + custom fields, and submits a booking.

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

  • Feature A: Publish / Update Scheduler Config (POST scheduler/backend/save_scheduler.php)
    • Trigger: Flutter app sends JSON payload with X-Secret-Key header.
    • Validation: Checks OPTIONS (200) → POST only (405) → root .env must exist (500) → X-Secret-Key === SCHEDULER_API_SECRET and non-empty (401) → non-empty valid JSON (400) → non-empty id sanitized to [a-zA-Z0-9_-] (400).
    • State Change: Injects saved_at (Y-m-d H:i:s) and server_timestamp (time()), writes scheduler/data/{id}.json with chmod 0644.
    • Response: HTTP 200 with data.url, data.iframe_code, data.file_size, data.saved_at.
    • Failure: Returns HTTP 500 on directory creation, JSON encode, or file write error.
  • Feature B: Delete Scheduler Config (POST scheduler/backend/delete_json.php)
    • Trigger: Caller sends POST {"id": "..."} (no authentication check).
    • Validation: Non-empty id (else HTTP 400), sanitized via preg_replace('/[^a-zA-Z0-9_\-]/', '', $id).
    • State Change: Logs request + payload to scheduler/backend/delete_log.txt, unlinks scheduler/data/{cleanId}.json if present.
    • Response: HTTP 200 {"status":"success","message":"Deleted successfully."} or "File already missing." (idempotent).
    • Failure: HTTP 400 on missing ID, missing data/ dir, or unlink() permission error.
  • Feature C: Google Calendar OAuth Binding (GET scheduler/backend/auth_start.php → GET scheduler/backend/auth_callback.php)
    • Trigger: Tenant clicks connect link ?client_id={id} on auth_start.php.
    • Validation: auth_start.php dies if client_id query param is absent. Sets Google OAuth state = $client_id (raw, unsigned) and redirects to Google consent screen (access_type=offline, prompt=select_account consent, scopes: CALENDAR, email).
    • State Change: auth_callback.php exchanges ?code for OAuth tokens, sanitizes $_GET['state'] to [a-zA-Z0-9_-] (fallback 'default'), merges existing scheduler/data/{client_id}.json onto a hardcoded default template, overwrites google_refresh_token (preserving old one if Google omits it), google_access_token, token_created, is_connected = true, and saves JSON.
    • Response: HTML confirmation page with link /?id={client_id}.
    • Failure: die() with plain text on token exchange exception or $token['error']; echoes "Brak kodu autoryzacyjnego." if ?code is missing.
  • Feature D: Render Booking Page & Public Config (GET scheduler/index.php?id={cal_id} + GET scheduler/backend/public_config.php?id={cal_id})
    • Trigger: Visitor opens scheduler page.
    • Validation: index.php sanitizes id (defaults to 'default'), reads scheduler/data/{cal_id}.json server-side for initial render (if missing, renders "Strona niedostępna" / "Ten harmonogram został usunięty lub nie istnieje."). Client JS then fetches backend/public_config.php?id={cal_id}&v={timestamp} twice (once from inline script in index.php:1111, once from script_v2.js:469).
    • State Change: public_config.php unwraps json_data/json wrappers, strips 5 private token keys (PRIVATE_KEYS), computes boolean is_connected, and returns sanitized JSON. Client applies custom colors, re-renders calendar blocking past dates, inactive weekdays, date_range exceptions, and blocked_dates.
    • Failure: If public_config.php returns 404/error, script_v2.js:535 replaces document.body.innerHTML with "Strona niedostępna".
  • Feature E: Fetch Available Slots (GET scheduler/backend/api.php?id={cal_id}&date=YYYY-MM-DD)
    • Trigger: Visitor clicks an unblocked calendar day.
    • Validation: Validates date against /^\d{4}-\d{2}-\d{2}$/ and strtotime($date). Loads scheduler/data/{id}.json, resolves timezone (default Europe/Warsaw).
    • Processing: If Google refresh token exists and syncGoogle is true, exchanges refresh token (persisting refreshed access/refresh tokens back to disk without file lock) and queries Google FreeBusy API for [00:00:00, 23:59:59] in host timezone. If syncPlanovi is true, queries Supabase scheduler_bookings (status=in.(pending,confirmed)). Generates slots from workStart to workEnd stepping by slot_duration * 60 seconds; excludes lunch break, time_block exceptions, any mathematical overlap (slotStart < busyEnd && slotEnd > busyStart) with Google/Supabase busy blocks, and slots <= time().
    • Response: HTTP 200 {"slots": ["09:00", ...], "API_DEBUG_TRACE": [...]}. Client JS (script_v2.js:275-315) applies a second client-side filter for lunch, time_block, and daily/weekly bounds, then converts host-timezone strings to browser local timezone for display while preserving dataset.originalTime for submission.
  • Feature F: Create Booking (POST scheduler/backend/api.php?id={cal_id})
    • Trigger: Visitor submits #booking-form.
    • Validation: Parses JSON body; requires date (/^\d{4}-\d{2}-\d{2}$/) and time (/^\d{2}:\d{2}(:\d{2})?$/); rejects past slots ($startTs <= time() with "Ten termin już minął. Wybierz inną godzinę.").
    • Race-Condition Guard (BUG-V42): Immediately re-queries Supabase supabaseSlotTaken() and Google googleSlotTaken(). If taken → returns {"success": false, "code": "slot_taken", "error": "Ten termin został właśnie zajęty. Wybierz inną godzinę."}.
    • State Change:
      1. If syncPlanovi: POST /rest/v1/scheduler_bookings with status: 'pending', Prefer: return=representation. If Postgres unique constraint returns HTTP 409 → slotTakenResponse() (no Google event created).
      2. If isGoogleConnected && $service: Creates Google Calendar event with hangoutsMeet conference (conferenceDataVersion=1, sendUpdates=all) and attendee if email passes FILTER_VALIDATE_EMAIL. Errors are silently swallowed (catch (Throwable $e) {}).
      3. If syncPlanovi && $bookingRowId && $googleEventId: PATCH /rest/v1/scheduler_bookings?id=eq.{rowId} to attach google_event_id and meeting_link.
    • Response: HTTP 200 {"success": true, "meet_link": "...", "API_DEBUG_TRACE": [...]}. UI hides form and reveals #success-message.
    • Failure: All exceptions and PHP fatal errors return HTTP 200 with {"success": false, "error": "...", "API_DEBUG_TRACE": [...]}; client displays alert("❌ Błąd: " + error.message) and re-enables submit button.

3. Hard Business Rules, Validations, Calculations & Edge Cases

  • BR-SCH-01 (ID Sanitization & Default): id is sanitized to [a-zA-Z0-9_-] (scheduler/index.php:22, api.php:119, public_config.php:22, save_scheduler.php:147, delete_json.php:33, auth_callback.php:22). index.php and api.php default empty ID to 'default'; public_config.php rejects empty ID with HTTP 400.
  • BR-SCH-02 (JSON Envelope Unwrapping): Config files may store fields at root, under json_data (object or JSON-encoded string), or under json (object or JSON-encoded string). All readers (index.php:37-41, api.php:135-139, public_config.php:45-49, script_v2.js:480-484) unwrap in that exact precedence order.
  • BR-SCH-03 (Host Timezone Resolution): api.php:144-148 checks $config['timezone'] ?? $config['user_timezone'] ?? 'Europe/Warsaw'. Any non-string or value not in timezone_identifiers_list() falls back to 'Europe/Warsaw'. script_v2.js:261 applies the identical fallback chain.
  • BR-SCH-04 (Sync Flag Precedence): syncGoogle resolves $config['jarvis_sync_google'] ?? $config['save_to_google'] ?? true; syncPlanovi resolves $config['jarvis_sync_planovi'] ?? $config['save_to_planovi'] ?? true (api.php:154-155). Google connection is active only when !empty($config['google_refresh_token']) && $syncGoogle (api.php:157-158).
  • BR-SCH-05 (Google Calendar ID Guard): calendarId defaults to 'primary'. Any value that is neither 'primary' nor passes filter_var($calendarId, FILTER_VALIDATE_EMAIL) is forced to 'primary' (api.php:173-176).
  • BR-SCH-06 (Working Hours & Default Slot Duration): Default slot_duration is 30 minutes (api.php:354, 444). Default working window is 09:00–17:00 (api.php:294-295). In weekly mode, PHP date('N') (1=Mon .. 7=Sun) indexes $availability['weekly']; inactive days yield zero slots (api.php:313-323). If availability is absent, falls back to legacy work_hours.start/work_hours.end (api.php:338-340).
  • BR-SCH-07 (Slot Exclusion & Overlap Formula): A candidate slot [slotStart, slotEnd) is marked BUSY if:
    1. slotStart <= time() (past or current second, api.php:400), OR
    2. lunchActive && slotStart < lunchEndTs && slotEnd > lunchStartTs (default lunch 12:00–13:00 when active, api.php:332-333, 368), OR
    3. Overlaps any exceptions item with type === 'time_block' and date === $date (api.php:375-385), OR
    4. Overlaps any busy block from Google Calendar FreeBusy or Supabase scheduler_bookings (status IN ('pending','confirmed')) via strict interval overlap slotStart < busyEnd && slotEnd > busyStart (api.php:392, 71, 90).
    • Whole days are inactive if $date is in blocked_dates or falls within [start_date, end_date] inclusive of a date_range exception (api.php:301-309).
  • BR-SCH-08 (Double-Booking Prevention — BUG-V42): On POST, api.php performs: (1) pre-insert check against Supabase (supabaseSlotTaken(), throws if Supabase fails with >= 400, failing closed, api.php:62-64), (2) pre-insert check against Google FreeBusy (googleSlotTaken(), errors ignored — fails open, api.php:464-466), (3) INSERT into scheduler_bookings before calling Google Calendar events->insert, mapping DB HTTP 409 unique-index violation on (scheduler_id, booking_date, booking_time) to code: 'slot_taken' (api.php:486-527).
  • BR-SCH-09 (Token Redaction in Public Config): public_config.php:14-20 strips google_access_token, google_refresh_token, token_created, refresh_token, access_token from the unwrapped config before returning JSON, setting is_connected boolean instead.
  • BR-SCH-10 (Client Timezone Conversion & Day-Shift Display): script_v2.js:197-248 skips conversion when baseTz === userLocalTimeZone. Otherwise it extracts the host GMT±HH:MM offset via toLocaleString("en-US", {timeZone: baseTz, timeZoneName: "shortOffset"}), constructs an offset ISO string, formats using navigator.language, and appends ' (+1 dzień)' or ' (-1 dzień)' when local date differs from host date. Submissions always transmit the unmodified host originalTime (script_v2.js:396-401).
  • BR-SCH-11 (Iframe Embedding Policy): scheduler/.htaccess:1-4 unsets X-Frame-Options and sets Content-Security-Policy: frame-ancestors *.
  • BR-SCH-12 (Theme Fallback Derivation): index.php:53-65 resolves theme in order: branding.theme → theme → dark_theme (bool) → isDarkTheme (bool) → linear RGB luminance of brand_color_bg ((0.2126*R + 0.7152*G + 0.0722*B)/255 < 0.5 ? 'dark' : 'light').
  • BR-SCH-13 (Booking Defaults & Phone Mapping): Missing name defaults to 'Nieznany Klient'; customer_phone maps $customFields['telefon'] ?? $customFields['phone'] ?? null (api.php:436, 497).
  • BR-SCH-14 (Custom Field Types Supported): text, email, number, phone, textarea, date, time, url, checkbox, enum (select), file (rendered as <input type="file">, though FormData.get() into JSON.stringify() serializes File as {} — see Section 5), and fallback text (script_v2.js:591-731).

4. State Machines & Data Lifecycle

Booking Slot & Reservation Lifecycle:

stateDiagram-v2
    [*] --> CandidateSlot: GET api.php (workStart..workEnd)
    CandidateSlot --> Excluded: Past / Lunch / Exception / Busy Overlap
    CandidateSlot --> Free: No conflicts
    Free --> ReservedDB: POST api.php -> INSERT scheduler_bookings (status=pending)
    Free --> SlotTaken: Pre-check conflict OR DB HTTP 409
    ReservedDB --> SyncedWithGoogle: Google events.insert OK -> PATCH google_event_id & meeting_link
    ReservedDB --> ReservedNoGoogle: Google disconnected or insert error swallowed
    SyncedWithGoogle --> [*]
    ReservedNoGoogle --> [*]
    SlotTaken --> [*]
  • Booking Statuses Handled by This Repo: Reads pending and confirmed as blocking busy states (api.php:53, 262); always inserts new rows with status: 'pending' (api.php:501). Subsequent transitions (confirmed, cancelled, completed) are managed outside this repo in planovi-flutter-app / planovi-backend.

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

  • Endpoints Exposed:
    • GET /scheduler/index.php?id={cal_id} → HTML booking widget.
    • GET /scheduler/backend/public_config.php?id={cal_id} → Sanitized JSON config (200/400/404/500).
    • GET /scheduler/backend/api.php?id={cal_id}&date=YYYY-MM-DD → JSON {slots[], API_DEBUG_TRACE[]} (always HTTP 200).
    • POST /scheduler/backend/api.php?id={cal_id} → Body {id, date, time, name, email, custom_fields} → JSON {success, meet_link?, code?, error?, API_DEBUG_TRACE[]} (always HTTP 200).
    • POST /scheduler/backend/save_scheduler.php → Header X-Secret-Key, Body {id, ...} → Writes scheduler/data/{id}.json (200/400/401/405/500).
    • POST /scheduler/backend/delete_json.php → Body {id} → Deletes scheduler/data/{id}.json, appends scheduler/backend/delete_log.txt (200/400).
    • GET /scheduler/backend/auth_start.php?client_id={id} → 302 redirect to Google OAuth2.
    • GET /scheduler/backend/auth_callback.php?code={code}&state={id} → Exchanges tokens, writes scheduler/data/{id}.json, returns HTML.
  • Database Tables Touched: scheduler_bookings (GET, POST, PATCH via PostgREST).
  • Local Files Touched: scheduler/data/{id}.json (read/write/unlink), scheduler/backend/delete_log.txt (append).
  • External APIs: Google OAuth2 token endpoint, Google Calendar API v3 (freebusy.query, events.insert with hangoutsMeet + sendUpdates=all which triggers Google Calendar invite emails).

6. Cross-Repository Dependencies

CallerCalleeProtocol & AuthExact Endpoint / Contract
planovi-flutter-appplanovi-microservices (scheduler)HTTPS POST + X-Secret-Key (SCHEDULER_API_SECRET)POST /backend/save_scheduler.php
planovi-flutter-appplanovi-microservices (scheduler)HTTPS POST (No Auth)POST /backend/delete_json.php
planovi-flutter-appplanovi-microservices (scheduler)Browser redirect (No Auth)GET /backend/auth_start.php?client_id={id}
scheduler/backend/api.phpplanovi-backend (Supabase PostgREST)HTTPS + apikey & Bearer (SCHEDULER_SUPABASE_SERVICE_KEY)GET/POST/PATCH /rest/v1/scheduler_bookings
scheduler/backend/api.php, auth_*.phpGoogle OAuth2 & Calendar API v3HTTPS OAuth2 (GOOGLE_CLIENT_ID/SECRET + per-tenant refresh token)freebusy->query(), events->insert()

7. Why It Works This Way (Decisions, Trade-offs & Workarounds)

  • DB-First Booking Reservation (df6c0ae5, BUG-V42): Booking is inserted into scheduler_bookings before creating the Google Calendar event so Postgres’s unique index on (scheduler_id, booking_date, booking_time) atomically prevents double-booking and orphaned Google Calendar events on concurrent requests.
  • Timezone Default Fixed to Europe/Warsaw (be0e8ee0): Previously defaulted to Asia/Kolkata, causing 13 of 15 dev schedulers without a saved timezone to offer Indian time slots.
  • public_config.php Proxy (54152854, 15281491): Introduced to stop the browser from fetching data/{id}.json directly and exposing google_access_token / google_refresh_token.
  • Workaround / Fragility: scheduler/backend/api.php includes includes/security.php (bf68edcf), yet does not enforce CSRF or Turnstile on booking POSTs.
  • [TEAM_WHY_NEEDED: Why does scheduler/backend/api.php return HTTP 200 with full API_DEBUG_TRACE on every request including errors and fatal crashes, instead of proper 4xx/5xx codes and server-side logging?]
  • [TEAM_WHY_NEEDED: Why are Google Calendar event creation failures silently swallowed (api.php:571-573) after reserving the DB row, leaving a booking with no Meet link and no user/host warning?]
  • [TEAM_WHY_NEEDED: Why does scheduler/backend/delete_json.php require no authentication header unlike save_scheduler.php?]
  • [TEAM_WHY_NEEDED: Why is scheduler/data/.htaccess missing from git even though public_config.php:6 states "The data/ folder itself is now blocked by data/.htaccess"?]

8. Debugging, Logs & Common Failure Modes

Symptom / Error MessageRoot Cause in CodeHow to Verify / Exact Log or QueryFix
"Błąd konfiguracji: Twoje SUPABASE_URL w api.php musi zaczynać się od 'https://'."SCHEDULER_SUPABASE_URL missing or empty in root .env (api.php:109, 115).Inspect API_DEBUG_TRACE in network response; check root .env key presence.Set SCHEDULER_SUPABASE_URL and SCHEDULER_SUPABASE_SERVICE_KEY in server root .env.
"Ten termin został właśnie zajęty. Wybierz inną godzinę."Slot overlaps existing pending/confirmed row, Google busy block, or hit Postgres 409 unique index (api.php:35-45, 454-467, 524-527).Check API_DEBUG_TRACE step 5a or 5b; query SELECT * FROM scheduler_bookings WHERE scheduler_id = '...' AND booking_date = '...'.Expected race protection; visitor chooses another slot.
"Strona niedostępna" on scheduler loadscheduler/data/{id}.json missing on disk (index.php:30, public_config.php:30).Check ls scheduler/data/{id}.json and tail scheduler/backend/delete_log.txt.Re-save scheduler from Flutter app (save_scheduler.php).
Google Calendar events not blocked / not createdgoogle_refresh_token revoked/expired (api.php:183-186) or config_google.php redirect URI mismatches production domain (dev-scheduler.planovi.app hardcoded at config_google.php:7).Inspect API_DEBUG_TRACE step 3b. Google Auth Warning.Move Google OAuth credentials/redirect URI to .env and re-authorize via auth_start.php?client_id={id}.
Booking fails silently with file custom fieldscript_v2.js:410 puts FormData.get() File object into JSON body; JSON.stringify serializes it as {}.Inspect POST payload to backend/api.php in browser DevTools.Implement multipart/Storage upload or disallow file custom field type.