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 Supabasescheduler_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.
- Tenant Admin (via
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-Keyheader. - Validation: Checks
OPTIONS(200) →POSTonly (405) → root.envmust exist (500) →X-Secret-Key === SCHEDULER_API_SECRETand non-empty (401) → non-empty valid JSON (400) → non-emptyidsanitized to[a-zA-Z0-9_-](400). - State Change: Injects
saved_at(Y-m-d H:i:s) andserver_timestamp(time()), writesscheduler/data/{id}.jsonwithchmod 0644. - Response: HTTP
200withdata.url,data.iframe_code,data.file_size,data.saved_at. - Failure: Returns HTTP
500on directory creation, JSON encode, or file write error.
- Trigger: Flutter app sends JSON payload with
- Feature B: Delete Scheduler Config (
POST scheduler/backend/delete_json.php)- Trigger: Caller sends
POST {"id": "..."}(no authentication check). - Validation: Non-empty
id(else HTTP400), sanitized viapreg_replace('/[^a-zA-Z0-9_\-]/', '', $id). - State Change: Logs request + payload to
scheduler/backend/delete_log.txt, unlinksscheduler/data/{cleanId}.jsonif present. - Response: HTTP
200{"status":"success","message":"Deleted successfully."}or"File already missing."(idempotent). - Failure: HTTP
400on missing ID, missingdata/dir, orunlink()permission error.
- Trigger: Caller sends
- 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}onauth_start.php. - Validation:
auth_start.phpdies ifclient_idquery param is absent. Sets Google OAuthstate = $client_id(raw, unsigned) and redirects to Google consent screen (access_type=offline,prompt=select_account consent, scopes:CALENDAR,email). - State Change:
auth_callback.phpexchanges?codefor OAuth tokens, sanitizes$_GET['state']to[a-zA-Z0-9_-](fallback'default'), merges existingscheduler/data/{client_id}.jsononto a hardcoded default template, overwritesgoogle_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?codeis missing.
- Trigger: Tenant clicks connect link
- 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.phpsanitizesid(defaults to'default'), readsscheduler/data/{cal_id}.jsonserver-side for initial render (if missing, renders"Strona niedostępna"/"Ten harmonogram został usunięty lub nie istnieje."). Client JS then fetchesbackend/public_config.php?id={cal_id}&v={timestamp}twice (once from inline script inindex.php:1111, once fromscript_v2.js:469). - State Change:
public_config.phpunwrapsjson_data/jsonwrappers, strips 5 private token keys (PRIVATE_KEYS), computes booleanis_connected, and returns sanitized JSON. Client applies custom colors, re-renders calendar blocking past dates, inactive weekdays,date_rangeexceptions, andblocked_dates. - Failure: If
public_config.phpreturns 404/error,script_v2.js:535replacesdocument.body.innerHTMLwith"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
dateagainst/^\d{4}-\d{2}-\d{2}$/andstrtotime($date). Loadsscheduler/data/{id}.json, resolves timezone (defaultEurope/Warsaw). - Processing: If Google refresh token exists and
syncGoogleis 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. IfsyncPlanoviis true, queries Supabasescheduler_bookings(status=in.(pending,confirmed)). Generates slots fromworkStarttoworkEndstepping byslot_duration * 60seconds; excludes lunch break,time_blockexceptions, 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 preservingdataset.originalTimefor 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}$/) andtime(/^\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 GooglegoogleSlotTaken(). If taken → returns{"success": false, "code": "slot_taken", "error": "Ten termin został właśnie zajęty. Wybierz inną godzinę."}. - State Change:
- If
syncPlanovi:POST /rest/v1/scheduler_bookingswithstatus: 'pending',Prefer: return=representation. If Postgres unique constraint returns HTTP409→slotTakenResponse()(no Google event created). - If
isGoogleConnected && $service: Creates Google Calendar event withhangoutsMeetconference (conferenceDataVersion=1,sendUpdates=all) and attendee if email passesFILTER_VALIDATE_EMAIL. Errors are silently swallowed (catch (Throwable $e) {}). - If
syncPlanovi && $bookingRowId && $googleEventId:PATCH /rest/v1/scheduler_bookings?id=eq.{rowId}to attachgoogle_event_idandmeeting_link.
- If
- 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
200with{"success": false, "error": "...", "API_DEBUG_TRACE": [...]}; client displaysalert("❌ Błąd: " + error.message)and re-enables submit button.
- Trigger: Visitor submits
3. Hard Business Rules, Validations, Calculations & Edge Cases
BR-SCH-01(ID Sanitization & Default):idis 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.phpandapi.phpdefault empty ID to'default';public_config.phprejects empty ID with HTTP400.BR-SCH-02(JSON Envelope Unwrapping): Config files may store fields at root, underjson_data(object or JSON-encoded string), or underjson(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-148checks$config['timezone'] ?? $config['user_timezone'] ?? 'Europe/Warsaw'. Any non-string or value not intimezone_identifiers_list()falls back to'Europe/Warsaw'.script_v2.js:261applies the identical fallback chain.BR-SCH-04(Sync Flag Precedence):syncGoogleresolves$config['jarvis_sync_google'] ?? $config['save_to_google'] ?? true;syncPlanoviresolves$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):calendarIddefaults to'primary'. Any value that is neither'primary'nor passesfilter_var($calendarId, FILTER_VALIDATE_EMAIL)is forced to'primary'(api.php:173-176).BR-SCH-06(Working Hours & Default Slot Duration): Defaultslot_durationis30minutes (api.php:354,444). Default working window is09:00–17:00(api.php:294-295). Inweeklymode, PHPdate('N')(1=Mon ..7=Sun) indexes$availability['weekly']; inactive days yield zero slots (api.php:313-323). Ifavailabilityis absent, falls back to legacywork_hours.start/work_hours.end(api.php:338-340).BR-SCH-07(Slot Exclusion & Overlap Formula): A candidate slot[slotStart, slotEnd)is markedBUSYif:slotStart <= time()(past or current second,api.php:400), ORlunchActive && slotStart < lunchEndTs && slotEnd > lunchStartTs(default lunch12:00–13:00when active,api.php:332-333,368), OR- Overlaps any
exceptionsitem withtype === 'time_block'anddate === $date(api.php:375-385), OR - Overlaps any busy block from Google Calendar FreeBusy or Supabase
scheduler_bookings(status IN ('pending','confirmed')) via strict interval overlapslotStart < busyEnd && slotEnd > busyStart(api.php:392,71,90).
- Whole days are inactive if
$dateis inblocked_datesor falls within[start_date, end_date]inclusive of adate_rangeexception (api.php:301-309).
BR-SCH-08(Double-Booking Prevention — BUG-V42): OnPOST,api.phpperforms: (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)INSERTintoscheduler_bookingsbefore calling Google Calendarevents->insert, mapping DB HTTP409unique-index violation on(scheduler_id, booking_date, booking_time)tocode: 'slot_taken'(api.php:486-527).BR-SCH-09(Token Redaction in Public Config):public_config.php:14-20stripsgoogle_access_token,google_refresh_token,token_created,refresh_token,access_tokenfrom the unwrapped config before returning JSON, settingis_connectedboolean instead.BR-SCH-10(Client Timezone Conversion & Day-Shift Display):script_v2.js:197-248skips conversion whenbaseTz === userLocalTimeZone. Otherwise it extracts the hostGMT±HH:MMoffset viatoLocaleString("en-US", {timeZone: baseTz, timeZoneName: "shortOffset"}), constructs an offset ISO string, formats usingnavigator.language, and appends' (+1 dzień)'or' (-1 dzień)'when local date differs from host date. Submissions always transmit the unmodified hostoriginalTime(script_v2.js:396-401).BR-SCH-11(Iframe Embedding Policy):scheduler/.htaccess:1-4unsetsX-Frame-Optionsand setsContent-Security-Policy: frame-ancestors *.BR-SCH-12(Theme Fallback Derivation):index.php:53-65resolves theme in order:branding.theme→theme→dark_theme(bool) →isDarkTheme(bool) → linear RGB luminance ofbrand_color_bg((0.2126*R + 0.7152*G + 0.0722*B)/255 < 0.5 ? 'dark' : 'light').BR-SCH-13(Booking Defaults & Phone Mapping): Missingnamedefaults to'Nieznany Klient';customer_phonemaps$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">, thoughFormData.get()intoJSON.stringify()serializesFileas{}— see Section 5), and fallbacktext(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
pendingandconfirmedas blocking busy states (api.php:53,262); always inserts new rows withstatus: 'pending'(api.php:501). Subsequent transitions (confirmed,cancelled,completed) are managed outside this repo inplanovi-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 HTTP200).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 HTTP200).POST /scheduler/backend/save_scheduler.php→ HeaderX-Secret-Key, Body{id, ...}→ Writesscheduler/data/{id}.json(200/400/401/405/500).POST /scheduler/backend/delete_json.php→ Body{id}→ Deletesscheduler/data/{id}.json, appendsscheduler/backend/delete_log.txt(200/400).GET /scheduler/backend/auth_start.php?client_id={id}→302redirect to Google OAuth2.GET /scheduler/backend/auth_callback.php?code={code}&state={id}→ Exchanges tokens, writesscheduler/data/{id}.json, returns HTML.
- Database Tables Touched:
scheduler_bookings(GET,POST,PATCHvia 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.insertwithhangoutsMeet+sendUpdates=allwhich triggers Google Calendar invite emails).
6. Cross-Repository Dependencies
| Caller | Callee | Protocol & Auth | Exact Endpoint / Contract |
|---|---|---|---|
planovi-flutter-app | planovi-microservices (scheduler) | HTTPS POST + X-Secret-Key (SCHEDULER_API_SECRET) | POST /backend/save_scheduler.php |
planovi-flutter-app | planovi-microservices (scheduler) | HTTPS POST (No Auth) | POST /backend/delete_json.php |
planovi-flutter-app | planovi-microservices (scheduler) | Browser redirect (No Auth) | GET /backend/auth_start.php?client_id={id} |
scheduler/backend/api.php | planovi-backend (Supabase PostgREST) | HTTPS + apikey & Bearer (SCHEDULER_SUPABASE_SERVICE_KEY) | GET/POST/PATCH /rest/v1/scheduler_bookings |
scheduler/backend/api.php, auth_*.php | Google OAuth2 & Calendar API v3 | HTTPS 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 intoscheduler_bookingsbefore 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 toAsia/Kolkata, causing 13 of 15 dev schedulers without a saved timezone to offer Indian time slots. public_config.phpProxy (54152854,15281491): Introduced to stop the browser from fetchingdata/{id}.jsondirectly and exposinggoogle_access_token/google_refresh_token.- Workaround / Fragility:
scheduler/backend/api.phpincludesincludes/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 Message | Root Cause in Code | How to Verify / Exact Log or Query | Fix |
|---|---|---|---|
"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 load | scheduler/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 created | google_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 field | script_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. |