RideFlow Documentation

RideFlow is a full-featured ride booking platform built with React, TypeScript, and Supabase. This guide walks you through installation, configuration, deployment, and day-to-day operation — in that order.

📖 How to Use This Documentation

Follow the sections in order for a fresh installation. Each part builds on the previous one:

  1. Getting Started — Install, run, and deploy the app
  2. Configuration — Environment variables, secrets, integrations
  3. Rider Experience — Features your customers see
  4. Driver Portal — Features drivers use daily
  5. Admin Panel — Back-office management
  6. Technical Reference — Architecture, database, APIs
  7. Self-Hosting Guide — Advanced deployment on your own infrastructure

Key Capabilities

🚗 3-Step Booking

Location → Vehicle → Payment with guest support

📍 Live Tracking

Real-time driver GPS via WebSockets + Leaflet maps

👨‍✈️ Driver Portal

Onboarding, shifts, earnings, commission tracking

⚙️ Admin Dashboard

Bookings, pricing, zones, routes, revenue analytics

💳 3 Payment Gateways

Stripe, PayPal, Bank Transfer with webhooks

🤖 AI Chatbot

Natural language booking assistant

🌍 18 Languages

EN, ES, FR, DE, AR, HI, IT, JA, KO, NL, PL, PT, RU, SV, TH, TR, ZH + more

🎨 White-Label

Dynamic branding, colors, logos from admin panel

⭐ Loyalty System

Rider points (Bronze→Platinum) + Driver bonuses

📱 PWA

Installable app with offline capabilities

🔔 4 Notification Channels

In-app, email, SMS, browser push

🔒 Role-Based Access

Admin, moderator, user, driver with RLS

Application Routes

RouteDescriptionAccess
/Main booking page (3-step flow)Public
/authLogin / RegisterPublic
/setupSetup wizard (first-time only)Public
/featuresPrintable feature summary pagePublic
/my-bookingsUser's booking historyAuthenticated
/accountUser profile & settingsAuthenticated
/trackLive ride tracking with mapPublic (with reference)
/booking-confirmation/:idBooking confirmation detailsPublic
/share/:tokenAccept ride share invitationPublic
/privacy-policyPrivacy policy (CMS-backed)Public
/terms-of-serviceTerms of service (CMS-backed)Public
/installPWA installation instructionsPublic
/driver/loginDriver authenticationPublic
/driverDriver dashboardDriver role
/admin/*Admin panel (16 pages)Admin role

Prerequisites

Before you begin, make sure you have the following installed on your system.

RequirementMinimumRecommended
Node.js18+20 LTS
Package Managernpm (bundled)Bun (faster)
Supabase ProjectCloud accountCloud or self-hosted
GitAny recent versionLatest

💡 No Supabase Account Yet?

Create a free account at supabase.com. You'll need the project URL and anon key from your dashboard. Alternatively, see Self-Hosting: Supabase Setup for running Supabase locally.

Install & Run

Get RideFlow running locally in under 5 minutes.

Step 1: Clone & Install

Terminal
# Clone the repository
git clone <YOUR_GIT_URL>
cd <YOUR_PROJECT_NAME>

# Install dependencies
npm install

Step 2: Configure Environment

Create a .env file in the project root with your Supabase credentials:

.env (minimum required)
# Required — Supabase connection
VITE_SUPABASE_URL=https://your-project.supabase.co
VITE_SUPABASE_PUBLISHABLE_KEY=your-anon-key
VITE_SUPABASE_PROJECT_ID=your-project-id

See Environment Variables for the full list including demo mode toggles.

Step 3: Start the Dev Server

Terminal
npm run dev

# App is now running at http://localhost:5173

Step 4: Run the Setup Wizard

On first launch, RideFlow automatically redirects to /setup. Complete the 7-step wizard to create your admin account and configure the platform. See Setup Wizard for details.

⚠️ Database Must Be Ready

Before the app can start, your Supabase project must have the migrations applied. If you cloned the repo, run npx supabase db push after linking your project. See Database Migration.

Project Structure

src/
├── components/
│   ├── admin/          # Admin panel components
│   │   ├── drivers/    # Driver management sub-components
│   │   └── settings/   # Settings tabs (8 tabs)
│   ├── booking/        # Booking flow components (40+ files)
│   ├── driver/         # Driver portal components
│   │   └── onboarding/ # Driver onboarding wizard
│   ├── setup/          # Setup wizard guard
│   ├── auth/           # Authentication components
│   ├── account/        # User account components (loyalty, payments)
│   └── ui/             # Shared UI components (shadcn/ui)
├── contexts/           # React contexts (Auth, Language, SystemSettings)
├── hooks/              # Custom React hooks (30+ hooks)
├── i18n/               # Internationalization (en, es, fr, de)
├── integrations/       # Supabase client & auto-generated types
├── pages/              # Page components
│   └── admin/          # 16 admin pages
├── types/              # TypeScript type definitions
└── utils/              # Utility functions (demo, calendar, receipt, nav)

supabase/
├── functions/          # 25+ Edge functions
├── migrations/         # Database migration files
└── config.toml         # Supabase configuration

docs/                   # This documentation

Setup Wizard

On first launch, RideFlow redirects all routes to a 7-step setup wizard at /setup. This ensures every installation is properly configured before going live.

How It Works

  1. The SetupGuard component wraps all routes in App.tsx
  2. The useSetupCheck hook queries the setup_completed flag from system_settings
  3. If setup is NOT complete, all routes redirect to /setup
  4. Once complete, /setup redirects to /auth

Setup Steps

#StepRequiredWhat It Does
1Environment CheckRequiredValidates database, auth, storage, and system settings connectivity
2Super AdminRequiredCreates the primary admin account via signup + make_user_admin RPC
3App IdentityOptionalCompany name, support email, website URL, tagline
4System SettingsOptionalDefault currency, timezone, language, booking advance hours
5Email ConfigOptionalSender name/email, toggle booking confirmations and ride updates
6SecurityOptionalEmail verification toggle, session timeout, max login attempts
7LaunchRequiredReviews all steps, blocks if required steps incomplete, sets setup_completed = true

💡 RLS Onboarding Exception

The system_settings table has special RLS policies that allow authenticated users to INSERT/UPDATE when no admin exists yet. Once an admin is created, these policies automatically become inactive.

Re-Running Setup

SQL: Reset Setup Status
DELETE FROM system_settings WHERE key = 'setup_completed';
-- Optionally remove all admin roles to re-trigger wizard
DELETE FROM user_roles WHERE role = 'admin';

Build & Deploy

Create a production build and deploy it to your hosting provider.

Step 1: Build for Production

Terminal
# Build the app (output goes to /dist)
npm run build

# Preview the production build locally
npm run preview

The dist/ folder contains static files that can be served from any hosting provider.

Step 2: Choose a Hosting Provider

Vercel

Zero-config. Connect your Git repo and deploy.

Netlify

Drag-and-drop the dist folder or connect Git.

Docker

Use nginx to serve static files. See Deploy Options.

AWS S3 + CloudFront

Upload to S3, serve via CDN.

Step 3: Set Environment Variables

Configure the same VITE_* variables from your .env in your hosting provider's dashboard. These are baked into the build at compile time.

Step 4: Deploy Backend

If self-hosting, deploy the database migrations and edge functions:

Terminal
# Link to your Supabase project
npx supabase login
npx supabase link --project-ref YOUR_PROJECT_REF

# Apply database schema
npx supabase db push

# Deploy all edge functions
supabase functions deploy

See Self-Hosting Guide for detailed infrastructure setup.

⚠️ Production Checklist

  • Set VITE_DEMO_MODE=false (or remove the variable entirely)
  • Delete demo user accounts from the database
  • Complete the Setup Wizard to create a real Super Admin
  • Configure all required backend secrets (see Backend Secrets)
  • Review all RLS policies (see Security Hardening)

Environment Variables

All frontend configuration is done via .env variables prefixed with VITE_. These are embedded at build time.

Required Variables

.env — Required
VITE_SUPABASE_URL=https://your-project.supabase.co
VITE_SUPABASE_PUBLISHABLE_KEY=your-anon-key
VITE_SUPABASE_PROJECT_ID=your-project-id

Demo Mode Variables (All Optional)

.env — Demo Controls
VITE_DEMO_MODE=false          # Master toggle (must be true for any demo feature)
VITE_DEMO_BANNER=true         # Show "Demo Mode Active" banner
VITE_DEMO_SEED_DATA=true      # Auto-seed demo accounts on quick login
VITE_DEMO_WATERMARK=false     # Overlay translucent "DEMO" text
VITE_DEMO_QUICK_LOGIN=true    # Show quick-access demo login buttons
VITE_DEMO_MOCK_PAYMENTS=false # Simulate payments without real gateways
VITE_DEMO_MOCK_MAPS=false     # Use mock map data (no API key needed)
VITE_DEMO_NOTIFICATIONS=false # Show demo notification toasts
VITE_DEMO_AI_CHATBOT=true     # Enable AI chatbot in demo mode
VITE_DEMO_ANALYTICS=false     # Populate admin dashboard with sample data

See Demo / Test Mode for detailed descriptions and recommended configurations.

Backend Secrets

Edge functions require API keys stored securely as Supabase secrets. These are never exposed to the browser.

SecretRequired ForHow to Get It
GOOGLE_MAPS_API_KEYMaps, directions, geocoding, ETAGoogle Cloud Console
RESEND_API_KEYTransactional emailsResend.com
VAPID_PUBLIC_KEYBrowser push notificationsGenerate with web-push generate-vapid-keys
VAPID_PRIVATE_KEYBrowser push notifications(Same as above)
VAPID_SUBJECTBrowser push notificationsmailto:your@email.com
ELEVENLABS_API_KEYVoice announcements (drivers)ElevenLabs.io

Setting Secrets

Terminal — Supabase CLI
supabase secrets set GOOGLE_MAPS_API_KEY=your-key
supabase secrets set RESEND_API_KEY=your-key
supabase secrets set VAPID_PUBLIC_KEY=your-key
supabase secrets set VAPID_PRIVATE_KEY=your-key
supabase secrets set VAPID_SUBJECT=mailto:your@email.com

⚠️ Security

Never expose the service_role key in frontend code. Only the anon (publishable) key should be used in the browser. Payment gateway keys (Stripe, PayPal) are stored in system_settings and managed via Admin → Settings → Integrations.

Integrations

RideFlow integrates with several third-party services. All are optional — the app functions in demo mode without any API keys.

Maps: Google Maps

Required APIs: Maps JavaScript, Places, Directions, Geocoding, Distance Matrix. API key stored as a secret, loaded via get-maps-config edge function. Usage tracked in map_api_usage table with quota alerts.

When VITE_DEMO_MOCK_MAPS=true, mock route data is used instead — no API key needed.

Maps: Mapbox

Alternative/fallback to Google Maps. Used for driver dashboard map and route visualization. Required scopes: Styles, Geocoding, Directions, Fonts, Tilesets.

Email: Resend

Store RESEND_API_KEY as a backend secret. HTML email templates include responsive design, brand colors (from system_settings), dynamic company name, and CTAs. Used by: booking emails, reminders, document notifications, driver application alerts.

Voice: ElevenLabs

Voice announcements for driver notifications. Store ELEVENLABS_API_KEY as a backend secret. Used via useVoiceAnnouncements hook.

Payments: Stripe

  1. Configure in Admin → Settings → Integrations (test/live mode toggle)
  2. Add webhook endpoint: /functions/v1/stripe-webhook
  3. Events: payment_intent.succeeded, payment_intent.payment_failed, charge.refunded

Payments: PayPal

  1. Configure in Admin → Settings → Integrations
  2. Set IPN URL: /functions/v1/paypal-webhook
  3. Handles: Completed, Pending, Failed/Denied, Refunded/Reversed

Demo / Test Mode

RideFlow supports a comprehensive demo/test mode controlled by 10 environment variables. The master toggle VITE_DEMO_MODE must be true for any demo feature to activate.

What Each Toggle Controls

FeatureDemo ONDemo OFFVariable
Quick Demo Access buttonsVisibleHiddenQUICK_LOGIN
"Demo Mode Active" bannerVisibleHiddenBANNER
DEMO watermark overlayOpt-inHiddenWATERMARK
Auto-seed demo dataActiveNot triggeredSEED_DATA
Mock payment processingOpt-inReal gatewaysMOCK_PAYMENTS
Mock map/route dataOpt-inReal APIsMOCK_MAPS
Demo notification toastsOpt-inReal triggersNOTIFICATIONS
AI chatbot widgetVisibleHiddenAI_CHATBOT
Sample analytics dataOpt-inReal dataANALYTICS

Recommended Configurations

Full Demo (trade shows, client demos)

.env — Full Demo
VITE_DEMO_MODE=true
VITE_DEMO_BANNER=true
VITE_DEMO_WATERMARK=true
VITE_DEMO_QUICK_LOGIN=true
VITE_DEMO_SEED_DATA=true
VITE_DEMO_MOCK_PAYMENTS=true
VITE_DEMO_MOCK_MAPS=true
VITE_DEMO_NOTIFICATIONS=true
VITE_DEMO_AI_CHATBOT=true
VITE_DEMO_ANALYTICS=true

Testing Mode (developer testing with real APIs)

.env — Testing
VITE_DEMO_MODE=true
VITE_DEMO_BANNER=true
VITE_DEMO_QUICK_LOGIN=true
VITE_DEMO_SEED_DATA=true
VITE_DEMO_MOCK_PAYMENTS=false
VITE_DEMO_MOCK_MAPS=false

Production

.env — Production
VITE_DEMO_MODE=false
# All other demo vars are ignored when master toggle is off

Demo Accounts

Available when VITE_DEMO_MODE=true:

RoleEmailPassword
Useruser@demo.comUser123!
Adminadmin@demo.comAdmin123!
Driverdriver@demo.comDriver123!

Demo Data Seeding

The setup-demo-users edge function is idempotent and creates: 3 user accounts with profiles, admin role assignment, a driver record with 4.8★ rating, 5 shifts, 3 demo bookings, 4 earnings records, and 1 zone.

Booking Flow

A streamlined 3-step process optimized for conversion. Each step has a loading skeleton for perceived performance.

Step 1: Location & Service

Component: Step1Location.tsx

  • Pickup & Dropoff: Address autocomplete via Google Maps Places API, with additional stops (up to 3)
  • Saved Locations: Quick-select dropdown for logged-in users
  • Service Type: Hourly or Flat-rate
  • Transfer Type: One-way, Return, or Return (New Ride)
  • Date & Time: Smart time picker with surge pricing indicators and business hours enforcement
  • Passengers / Luggage / Child Seats / Flight Number / Notes
  • Map Preview: Route visualization with distance and duration
  • Traffic Alerts: Real-time traffic condition banners

Step 2: Vehicle Selection

Component: Step2Vehicle.tsx

  • Dynamic Pricing: Base price + per-km rate with pricing rules applied
  • Categories: Sedan, SUV, Van, Luxury (configurable)
  • Capacity Filtering: Only vehicles that fit passengers/luggage
  • Favorites, Comparison Drawer, Smart Fare Suggestions, Surge Alerts

Step 3: Payment & Confirmation

Component: Step3Payment.tsx

  • Payment Methods: Card (Stripe), PayPal, Bank Transfer
  • Promo Codes, Billing Details, Price Breakdown, Order Summary
  • Deposit Requirement: Configurable percentage (default 30%)
  • Guest Email: Required for non-authenticated bookings

Post-Booking

  • Confirmation Page: Booking reference, calendar export (ICS/Google/Outlook), receipt download
  • Email Notification: Branded email via send-booking-email edge function
  • Real-time Status: Timeline visualization + live tracking
  • Loyalty Points: Automatically earned on completed rides

Guest Bookings

Users can book rides without creating an account. Email is required in Step 3 for confirmation. The booking is created with user_id = NULL. The booking reference allows tracking without login at /track.

⚠️ Limitation

Guest bookings cannot be modified after creation. Users are encouraged to create an account for full booking management.

Vehicle Selection

Vehicle Schema

ColumnTypeDescription
nameTEXTDisplay name
categoryTEXTsedan, suv, van, luxury
passengers / luggageINTEGERCapacity limits
base_price / price_per_kmNUMERICPricing
featuresTEXT[]Leather seats, WiFi, etc.
imageTEXTFrom vehicle-images bucket
is_active / sort_orderBOOLEAN / INTVisibility & ordering

Pricing Hooks

  • useVehiclePricing — Total price from distance + rules + surge
  • useDynamicPricing — Time/distance/zone/vehicle pricing rules
  • useSurgePricing — Real-time demand-based surge multipliers

Payment Methods

💳 Stripe

Credit/debit card with webhook integration

🅿️ PayPal

PayPal payments with IPN webhook

🏦 Bank Transfer

Wire transfer with manual verification

All gateways are configured in Admin → Settings → Integrations with test/live mode toggles. Users can save and verify payment methods in their account. Demo mock payments available via VITE_DEMO_MOCK_PAYMENTS=true.

Fees & Surcharges

All fees are transparent and shown in the price breakdown before booking confirmation.

FeeColumnDescription
Booking Feebooking_feePlatform service charge (configurable in Admin → Settings)
Toll Chargestoll_chargesToll plaza fees along the route
Airport Chargesairport_chargesAirport pickup/dropoff surcharge
Cancellation Feecancellation_feeLate cancellation charge (within configured window)

Price Breakdown Example

Base Fare                    $45.00
Distance (12.3 km × $1.50)   $18.45
Booking Fee                   $5.00
Toll Charges                  $3.50
Airport Charges               $8.00
───────────────────────────────────
Subtotal                     $79.95
Promo Code (SAVE10 -10%)     -$7.99
Tax (VAT 20%)                $14.39
───────────────────────────────────
Total                        $86.35

Promo Codes

Percentage-based discounts validated via validate_promo_code database function. Features: date range validity, global + per-user usage limits, minimum booking amount. Usage tracked via promo_code_uses table.

Recurring Bookings

Users set up automatic recurring rides with frequency options: Daily, Weekly, Weekdays, Custom (specific days). The generate-recurring-bookings edge function runs daily to create upcoming bookings from templates.

Ride Sharing

Users can split ride costs with other passengers via email invitation.

  1. Booking owner enters recipient email and cost split percentage
  2. Email sent with unique share token
  3. Recipient accepts/declines at /share/:token
  4. Counter-proposals supported

Real-time Tracking

Live Driver Location

When a driver is assigned, users track the driver's location at /track:

  • Position updates every 10 seconds via Supabase Realtime
  • Interactive Leaflet map centered on pickup, with "Waiting for driver location…" overlay until GPS data arrives
  • Estimated arrival time via calculate-eta edge function
  • Booking status timeline, contact buttons (call/message driver), traffic alerts, AI live chat widget

Booking Statuses

StatusDescriptionActions
pendingAwaiting confirmationCancel, Modify
confirmedConfirmed, awaiting driverCancel, Track
completedRide finishedRate Driver, Receipt
cancelledBooking cancelledView Details

Notifications

Channels

  • In-App: Bell icon with unread badge counter
  • Email: Via Resend with branded HTML templates
  • SMS: Configurable phone notifications
  • Push: Browser push (VAPID-based)
  • Voice: ElevenLabs announcements for drivers

Automatic triggers fire on: booking status changes, driver assignment, driver arrival (ETA ≤5 min), ride start/completion. User preferences stored in notification_preferences table.

User Account

👤 Profile

Name, email, phone, avatar, preferred vehicle, theme, language

🔔 Notifications

Channel preferences (email, SMS, push)

💳 Payments

Saved methods with micro-transaction verification

⚙️ Settings

Theme, language, billing details (8 fields)

Loyalty & Rewards

Rider Loyalty Points

TierLifetime PointsBenefits
Bronze0+Base earning rate, standard support
Silver500+1.5x earning rate, priority booking
Gold2,000+2x earning rate, free upgrades
Platinum5,000+3x earning rate, VIP support, exclusive offers

Points are earned from ride completions, referrals, and promotions. Balance and history shown via LoyaltyPointsSection in the Account page.

AI Booking Chatbot

Floating AI assistant on the booking page for natural language booking guidance. Context-aware (receives current booking state), renders Markdown responses, powered by built-in AI models (no API key required). Controllable via VITE_DEMO_AI_CHATBOT.

A separate LiveChatWidget is available on the tracking page, contextually aware of the current booking.

Driver Onboarding

Application Process

The BecomeDriverDialog opens a 3-step wizard:

  1. Personal Information: Name, email, phone
  2. License Details: License number, expiry date
  3. Agreement: Terms of service + background check consent

Onboarding Statuses

StatusDescription
pendingApplication submitted, awaiting review
documents_requiredAdditional documents needed
verificationBackground check in progress
approvedApplication approved, driver active
rejectedApplication rejected (re-application available)

Driver Dashboard

Mobile-optimized dashboard at /driver with pull-to-refresh.

  • Availability Toggle: Switch Available/Offline status
  • Map View: All pickup locations with Mapbox
  • List View: Pickups sorted by ETA urgency (red ≤5min, amber ≤10min, green >10min)
  • Active Ride Card: Live timer, route details
  • Urgent Pickup FAB: Floating button for imminent pickups
  • Today's Earnings: Real-time summary with commission breakdown
  • Geofence Indicator: Zone entry/exit alerts

Shift Management

Shifts link drivers to zones with date/time ranges. Statuses: scheduled → active (checked in) → completed (checked out) or missed. Admin creates shifts in /admin/scheduling. Drivers see their shifts with check-in/out capability.

Earnings & Commission

Fully automated commission system that deducts a configurable percentage from every completed ride.

How Commission Works

  1. Admin sets rate: Commission % in Admin → Settings → Booking Policies (e.g., 15%)
  2. Ride completes: The auto_record_driver_earning_on_completion trigger fires
  3. Earnings calculated: Calls record_driver_earning_with_commission()
  4. Record created: gross_amount, commission_rate, commission_amount, net amount
  5. Summary updated: Driver's total/monthly earnings auto-updated

Earnings Breakdown

Rider Paid (Gross Fare):    $50.00
Commission Rate:             15%
Service Fee (Deduction):    -$7.50
─────────────────────────────────
Driver Net Pay:              $42.50

The DriverEarningsTracker component shows the visual "Rider Paid → Service Fee → You Earned" flow with per-ride detail and earning types (ride, tip, bonus, adjustment).

Driver Bonuses

Bonus types: milestone, performance, referral, and seasonal. Each has amount, rides_required, progress tracking, and validity dates. Stored in driver_bonuses table.

Document Management

Drivers upload license, insurance, and vehicle registration documents via DriverDocumentPortal. Documents go through a verification workflow (pending → verified/rejected). Expiring documents trigger alerts via check-expiring-documents edge function.

Location Tracking

Driver GPS coordinates are updated in real-time via DriverLocationTracker. Updates broadcast to riders through Supabase Realtime. The DriverRouteMap component shows the route from current location to pickup/dropoff.

Navigation Integration

Deep links to Google Maps, Waze, and Apple Maps for turn-by-turn navigation. The navigation button opens the user's preferred mapping app with the destination pre-filled.

Admin Dashboard

The dashboard at /admin shows real-time KPIs: today's bookings, active rides, revenue, pending tasks. Includes stat cards, traffic heatmap, driver deployment widget, pending documents, and API quota alerts.

Bookings Management

Full CRUD at /admin/bookings with search, filter (status, date range, vehicle), server-side pagination. Actions: assign driver, update status, modify details, process refund, view payment status.

Driver Management

Manage drivers at /admin/drivers. View applications at /admin/driver-applications. Review documents at /admin/document-review. Features: add/edit driver, performance cards, smart assignment, document verification, expiring document alerts.

Vehicle Management

CRUD for vehicles at /admin/vehicles. Configure: name, category, capacity, pricing (base + per-km + hourly), features, images, display order, active/inactive status.

Pricing Rules

Rule types: time-based (peak hours), distance-based (tiers), zone-based (surcharges), vehicle-specific. Each rule has multiplier, flat fee, priority, day/time constraints. Test with the Price Calculator at /admin/calculator.

Commission Settings

Configure the platform's revenue share from each completed ride.

Navigate to Admin → Settings → Booking Policies:

  • Commission Rate (%): 0–100%, step: 0.5%. Default: 15%.
  • Booking Fee: Fixed platform fee per booking
  • Cancellation Fee: Charged for late cancellations

Rate changes take effect immediately for new completions. Already-completed rides retain their original rate. All changes logged in the Audit Log.

Zones & Routes

Zone Management

Zones at /admin/zones: geographic areas with name, description, multiplier, active status. Used for zone-based pricing rules and driver shift assignments.

Route Management

Routes at /admin/routes: predefined origin-destination pairs with base price, estimated distance/duration, origin/destination zone links, display order.

Revenue & Analytics

Revenue dashboard at /admin/revenue with charts, booking volume trends, driver performance, payment method breakdown, and commission revenue tracking.

  • Total Revenue — Sum of completed booking fares
  • Commission Revenue — Platform's share from all rides
  • Driver Payouts — Net amounts paid to drivers
  • Booking Fees — Total platform booking fees

Admin Settings (8 Tabs)

All settings stored in system_settings table with audit logging.

#TabWhat It Controls
1GeneralBusiness info (name, email, phone, address), social links, business hours, timezone
2BookingDeposit %, cancellation hours, advance booking limits, currency, tax settings, commission rate, booking fee, distance unit (km/miles)
3NotificationsEmail sender name/address, confirmation/reminder toggles, SMS provider
4SecurityEmail verification, session timeout, max login attempts, 2FA, IP whitelist
5AppearancePrimary/accent colors, logo upload (light/dark), favicon, dark mode default. Colors applied as CSS custom properties for white-labeling.
6IntegrationsMaps provider, Stripe (test/live), PayPal, Bank Transfer. API key update forms.
7Audit LogAll settings changes with user, timestamp, old/new values. Filterable.

Architecture

┌─────────────────────────────────────────────────────────────────┐
│                        Frontend (React + Vite)                   │
├─────────────────────────────────────────────────────────────────┤
│  Booking Flow │ Driver Portal │ Admin Panel │ User Account       │
│  AI Chatbot   │ Setup Wizard  │ PWA Support │ i18n (18 languages)│
│  Loyalty      │ Features Page │ Demo Mode   │ Commission System  │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                     Backend (Supabase)                            │
├─────────────────────────────────────────────────────────────────┤
│  Auth (GoTrue) │ Database (PostgreSQL) │ Edge Functions (Deno)   │
│  Storage       │ Realtime (WebSockets) │ Secrets (API Keys)      │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                     External Integrations                        │
├─────────────────────────────────────────────────────────────────┤
│  Google Maps │ Mapbox │ Resend (Email) │ ElevenLabs (Voice)     │
│  Stripe      │ PayPal │ Bank Transfer                           │
└─────────────────────────────────────────────────────────────────┘
          

Data Flow

  1. User Action: User interacts with the React frontend
  2. API Call: Supabase client sends request to database or edge function
  3. RLS Check: Row Level Security verifies access permissions
  4. Database Operation: Data is read/written to PostgreSQL
  5. Triggers: Database triggers fire (notifications, earnings, commission, ratings)
  6. Realtime: Changes broadcast to subscribed clients via WebSockets
  7. UI Update: React components re-render via TanStack Query

Key Design Patterns

  • SECURITY DEFINER functions: has_role(), get_user_roles() bypass RLS to prevent recursive policy checks
  • Enum-based access: Roles stored in separate user_roles table
  • Upsert patterns: Settings and demo data use ON CONFLICT for idempotency
  • Edge Functions: All sensitive operations (payments, emails, API keys) are server-side
  • Commission triggers: Automatic calculation on ride completion
  • Dynamic branding: CSS custom properties applied from database at runtime

Tech Stack

Frontend

React 18

Modern hooks, concurrent features

TypeScript

Full type safety, strict mode

Vite

Fast dev server and build tool

Tailwind CSS

Utility-first with HSL tokens

shadcn/ui

Accessible Radix components

TanStack Query

Data fetching & caching

React Router 6

Client-side routing

Framer Motion

Production animations

Leaflet + Mapbox

Interactive maps

Recharts

Admin data visualization

Backend

PostgreSQL 15+

RLS, triggers, functions

Edge Functions

25+ serverless Deno functions

Realtime

WebSocket subscriptions

Auth (GoTrue)

Email/password + Google OAuth

Storage

S3-compatible (4 buckets)

Row Level Security

Fine-grained access control

Database Schema

20+ tables with RLS. Key tables summarized below.

Core Tables

TableKey ColumnsPurpose
bookingsbooking_reference, user_id, status, driver_id, total_price, feesAll ride bookings with pricing and status lifecycle
drivers30+ cols: name, license, location, ratings, earnings, onboarding statusDriver profiles and verification
vehiclesname, category, capacity, pricing, features, imageVehicle fleet configuration
profilesfull_name, phone, avatar, theme, language, billing_* (8 fields)Extended user information
user_rolesuser_id, role (admin/moderator/user)Role-based access control

Financial Tables

TablePurpose
driver_earningsPer-ride earnings with gross, commission_rate, commission_amount, net
driver_payoutsPayout records with period, amount, status
driver_bonusesMilestone/performance/referral bonuses with progress
payment_methodsSaved cards/bank/PayPal with verification
promo_codes / promo_code_usesDiscount codes and redemption tracking
loyalty_points / loyalty_balancesRider loyalty system with tiers

Supporting Tables

TablePurpose
driver_documentsLicense, insurance uploads with verification workflow
driver_shiftsZone-linked shift scheduling with check-in/out
driver_ratingsPer-ride ratings and comments
notifications / notification_preferencesMulti-channel notification system
zones / routes / pricing_rulesGeographic and pricing configuration
system_settings / settings_audit_logKey-value config with change history
page_contentCMS-backed pages (privacy policy, terms)
recurring_bookings / ride_sharesRecurring rides and cost sharing
languagesSupported languages with activation toggles and completeness
translation_overridesPer-language translation key overrides
email_logsEmail delivery history with status and error tracking
map_api_usageAPI call tracking per provider and type
favorite_vehiclesUser vehicle favorites for quick selection

Edge Functions

30+ serverless functions running on the Deno runtime. Deployed via supabase functions deploy.

Communication

FunctionPurposeSecret Required
send-booking-emailTransactional emails with brandingRESEND_API_KEY
send-booking-remindersUpcoming ride remindersRESEND_API_KEY
send-push-notificationBrowser push via Web PushVAPID keys
send-smsSMS notificationsProvider key
send-whatsapp-messageWhatsApp messagesProvider key
send-document-notificationDocument status emailsRESEND_API_KEY
send-verification-emailEmail verificationRESEND_API_KEY
notify-* (4 functions)Shift/ride/driver notifications

AI & Intelligence

FunctionPurposeSecret Required
ai-booking-chatAI booking assistantBuilt-in AI
smart-fare-suggestionsAI fare optimizationBuilt-in AI
predict-driver-deploymentAI driver placementBuilt-in AI
analyze-surge-pricingDemand-based pricing
predict-trafficTraffic predictionGOOGLE_MAPS_API_KEY
auto-dispatchAutomatic driver assignment

Maps & Location

FunctionPurposeSecret Required
get-traffic-dataReal-time traffic conditionsGOOGLE_MAPS_API_KEY
calculate-etaDriver ETA via Distance MatrixGOOGLE_MAPS_API_KEY
location-proxyAddress geocoding & reverse geocoding via OpenStreetMap Nominatim— (free, no key)

Payments & Webhooks

FunctionPurposeSecret Required
process-paymentUnified payment processingVia system_settings
process-refundAdmin refund processingVia system_settings
stripe-webhookStripe payment eventsVia system_settings
paypal-webhookPayPal IPN eventsVia system_settings

Administration

FunctionPurpose
setup-demo-usersSeed demo accounts & data
update-payment-secret / update-sms-secret / update-ai-secretUpdate API keys from admin panel
check-expiring-documents / check-expiring-verificationsDocument/verification expiry alerts
check-api-usage-alertsAPI quota monitoring
generate-recurring-bookingsCreate bookings from recurring templates
translate-batchBulk AI translation for i18n keys
update-email-providerUpdate email provider config from admin
ai-booking-featuresAI route suggestions, vehicle recommendations, booking summaries

RPC Functions

FunctionParametersReturnsDescription
has_role_user_id, _roleBOOLEANCheck if user has a specific role
get_user_roles_user_idSETOF app_roleGet all roles for a user
make_user_adminuser_emailVOIDAssign admin role by email
validate_promo_codep_code, p_booking_amount, p_user_idTABLEValidate and return promo code details
use_promo_codep_promo_code_id, p_user_id, p_booking_idVOIDRecord promo code usage
increment_map_api_usagep_provider, p_api_type, p_countVOIDTrack API call counts
record_driver_earning_with_commissionp_driver_id, p_booking_id, p_gross_amount, p_commission_rate, p_descriptionUUIDRecord earning with commission calc

Realtime Channels

Supabase Realtime is used for: booking status/driver location updates, driver availability changes, notification delivery, system settings changes (brand colors, currency).

Subscribe to Booking Updates
const channel = supabase
  .channel(`booking-${bookingId}`)
  .on('postgres_changes', {
    event: 'UPDATE',
    schema: 'public',
    table: 'bookings',
    filter: `id=eq.${bookingId}`,
  }, (payload) => {
    updateDriverMarker(payload.new.driver_location_lat, payload.new.driver_location_lng);
    updateBookingStatus(payload.new.status);
  })
  .subscribe();

Authentication

Supported Methods

  • Email/Password: Standard registration and login with Zod validation
  • Google OAuth: Cloud-managed or self-hosted Supabase OAuth (auto-detected)
  • Apple OAuth: Cloud-managed or self-hosted Supabase OAuth (auto-detected)
  • X (Twitter) OAuth: Direct Supabase OAuth only
  • Facebook OAuth: Direct Supabase OAuth only
  • Password Reset: ForgotPasswordDialog with email link flow

Auth Context

AuthContext provides: user, session, loading, isCloud, signIn, signUp, signInWithSocialProvider (Google/Apple/Twitter/Facebook), signOut. Profile auto-creation via handle_new_user trigger. The isCloud flag auto-detects the hosting environment for OAuth routing.

Role-Based Access

RolePermissions
userBook rides, manage own data, rate drivers, earn loyalty points
moderatorView reports, moderate content
adminFull system access — all data, settings, users, commission, bonuses

Frontend hook: useUserRoles() returns roles, isAdmin, isModerator, hasRole(), loading.

RLS & Security

All 20+ tables use Row Level Security. Common patterns:

  • User-owned: auth.uid() = user_id
  • Admin ALL: has_role(auth.uid(), 'admin')
  • Public read: is_active = true or USING (true)
  • Driver-owned: Subquery matching drivers.user_id = auth.uid()
  • Setup exception: NOT EXISTS (SELECT 1 FROM user_roles WHERE role = 'admin')

PWA Support

  • Service worker (public/sw.js) for offline caching
  • Web app manifest with icons (192x192, 512x512)
  • InstallPromptBanner for install promotion
  • Dedicated /install page with platform-specific instructions
  • vite-plugin-pwa for build-time manifest generation

Multi-language

18 languages via LanguageContext: English, Spanish, French, German, Arabic (RTL), Hindi, Italian, Japanese, Korean, Dutch, Polish, Portuguese, Russian, Swedish, Thai, Turkish, and Chinese. User preference stored in profiles.language_preference. Languages are managed from the languages database table with activation toggles and translation completeness tracking.

Translation Overrides: Admins can override any translation key per-language via the translation_overrides table. The Bulk Translation Manager in Admin Settings allows batch translation using the translate-batch edge function.

Theming & Branding

Theme management uses next-themes. HSL-based design tokens in index.css. User preference stored in profiles.theme_preference (light/dark/system).

Dynamic Branding: The SystemSettingsContext reads brand colors from the database and applies them as CSS custom properties at runtime. Primary color, accent color, logos, and favicon are all configurable from Admin → Settings → Appearance without code changes.

Self-Hosting Overview

RideFlow can be self-hosted on your own infrastructure for full data sovereignty, customization, cost control, and regulatory compliance.

┌─────────────────────────────────────────────────────────────────┐
│                     Your Infrastructure                          │
├─────────────────────────────────────────────────────────────────┤
│  ┌──────────────────┐     ┌──────────────────────────────────┐   │
│  │   Frontend App   │     │         Supabase Instance        │   │
│  │  (Static Files)  │────▶│  (Self-hosted or Supabase.com)   │   │
│  │  Vercel/Netlify/  │     │  PostgreSQL + Auth + Edge Funcs  │   │
│  │  Docker/S3+CF    │     │  + Realtime + Storage            │   │
│  └──────────────────┘     └──────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────────┘
          

System Requirements

ComponentMinimumRecommended
Node.js / BunNode.js 18+Node.js 20 LTS
PostgreSQL14+15+
RAM (Frontend)512 MB1 GB+
RAM (Database)1 GB4 GB+
Storage10 GB50 GB+

Authentication & OAuth

RideFlow supports two OAuth environments. The app auto-detects which path to use at runtime — no code changes required.

How It Works

EnvironmentDetectionOAuth Method
Cloud Hosted Cloud-hosted domain detection (e.g., *.yourplatform.app) Managed OAuth via built-in cloud auth SDK — zero configuration needed
Self-Hosted Any other hostname Standard supabase.auth.signInWithOAuth() — you configure providers in Supabase Dashboard

Self-Hosted OAuth Setup

  1. Open your Supabase Dashboard → Authentication → Providers
  2. Enable Google and/or Apple
  3. Enter your Client ID and Client Secret (from Google Cloud Console / Apple Developer Portal)
  4. Set the Redirect URL to https://<your-supabase-url>/auth/v1/callback
  5. In RideFlow Admin Settings → Integrations, toggle on the providers you configured

💡 Build Compatibility

The cloud auth SDK is loaded via dynamic import() and is not required at build time. Self-hosted builds will succeed without the package installed — the import silently falls back to Supabase OAuth at runtime.

⚠️ Provider Visibility

Social login buttons only appear on the Auth page if the corresponding provider is enabled in Admin Settings → Integrations. Make sure to toggle them on after configuring credentials.

Supabase Setup

Option 1: Supabase Cloud (Recommended)

  1. Create account at supabase.com
  2. Create project, note URL and anon key
  3. Run database migrations (see below)
  4. Configure auth, create storage buckets

Option 2: Self-Hosted Supabase (Docker)

Terminal
git clone --depth 1 https://github.com/supabase/supabase
cd supabase/docker
cp .env.example .env
# Edit .env with your settings
docker compose up -d

Deploy Options

Static File Hosting

After npm run build, deploy the dist/ folder to any static hosting provider: Vercel, Netlify, AWS S3+CloudFront, or Docker with nginx.

Docker Example

Dockerfile
FROM node:20-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build

FROM nginx:alpine
COPY --from=build /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80

💡 SPA Routing

Configure your web server to serve index.html for all routes. The public/.htaccess file handles this for Apache. For nginx, add try_files $uri $uri/ /index.html;.

Database Migration

Terminal
# Login and link to your project
npx supabase login
npx supabase link --project-ref YOUR_PROJECT_REF

# Push all migrations
npx supabase db push

⚠️ Common Error: pgcrypto

If you see ERROR: function gen_random_bytes(integer) does not exist, run this SQL first:

CREATE EXTENSION IF NOT EXISTS pgcrypto WITH SCHEMA extensions;

Then edit migration files: gen_random_bytesextensions.gen_random_bytes

Edge Functions Deployment

Terminal
# Deploy all functions at once
supabase functions deploy

# Deploy a specific function
supabase functions deploy send-booking-email

See Edge Functions for the full list with required secrets.

Storage Setup

Create 4 storage buckets:

BucketPublicPurpose
vehicle-imagesYesVehicle photos
avatarsYesUser profile pictures
driver-documentsNoLicense, insurance docs (private)
branding-assetsYesLogos, favicons

Security Hardening

🔒 Production Checklist

  • ✅ Enable RLS on all tables and review all policies
  • ✅ Use service_role key only server-side
  • ✅ Enable email verification
  • ✅ Configure rate limiting and CORS restrictions
  • ✅ Set up SSL/TLS
  • ✅ Disable demo mode (VITE_DEMO_MODE=false)
  • ✅ Remove demo accounts and data
  • ✅ Restrict Google Maps API key referrers
  • ✅ Set API usage quotas
  • ✅ Regular security audits

Troubleshooting

CORS Errors

Verify edge function CORS headers include your domain. Check API allowed origins.

Auth Not Working

Verify SUPABASE_URL and key. Check email confirmation settings. Verify redirect URLs.

RLS Permission Denied

Ensure user is authenticated. Test policies with role impersonation. Check has_role() function.

Edge Functions 500 Errors

Check logs: supabase functions logs [name]. Verify all secrets are set.

Maps Not Loading

Verify GOOGLE_MAPS_API_KEY secret. Enable required APIs in Google Cloud. Check referrer restrictions. Or enable VITE_DEMO_MOCK_MAPS=true for testing.

Commission Not Applied

Verify the auto_record_driver_earning_on_completion trigger exists. Check booking_policies.commissionPercentage in system_settings. Ensure booking has driver_id and total_price.

Upgrade Guide

Follow these steps to update RideFlow to any newer version. The same procedure applies regardless of your current version.

⚠️ Before You Begin

  • Back up your database — run pg_dump or use your hosting provider's snapshot feature
  • Back up your .env file and any custom branding assets
  • Read the Changelog for every version between your current and target version to understand new features and changes

Step 1 — Download the New Version

Replace your project files with the target release. Keep your .env file separate — do not overwrite it.

Terminal
# If using Git
git fetch origin
git checkout vX.X.X

# Or download the release archive and extract over your project directory

Step 2 — Install Dependencies

Terminal
npm install
# or: bun install

Step 3 — Update Environment Variables

Compare your existing .env with the new .env.example and add any new variables. Check the Changelog for details on what was added in each version.

Step 4 — Install the Supabase CLI

If you don't already have the Supabase CLI installed locally:

Terminal
npm i supabase

Step 5 — Log In to Supabase

Terminal
npx supabase login

This opens a browser window to authenticate with your Supabase account. You only need to do this once per machine.

Step 6 — Link Your Project

Terminal
npx supabase link --project-ref YOUR_SUPABASE_PROJECT_ID

ℹ️ Finding Your Project ID

Your project ID is visible in your Supabase Dashboard URL: https://supabase.com/dashboard/project/YOUR_PROJECT_ID. If already linked from a previous upgrade, you can skip this step.

Step 7 — Apply Database Migrations

This pushes all pending migration files to your database. New tables, columns, functions, triggers, and RLS policies will be applied automatically.

Terminal
npx supabase db push

⚠️ Important

Migration files are cumulative — the CLI tracks which ones have already been applied. Only new migrations since your last version will run. Never modify or delete existing migration files.

Step 8 — Deploy Edge Functions

This deploys all edge functions (new and updated) to your Supabase project:

Terminal
npx supabase functions deploy

ℹ️ Note

This command deploys all functions in the supabase/functions/ directory. It's safe to run even if some functions haven't changed — unchanged functions are simply redeployed with the same code.

Step 9 — Build & Deploy the Frontend

Terminal
# Build the production bundle
npm run build

# Test locally before deploying to production
npm run dev

# Deploy to your hosting provider — examples:

# Vercel
npx vercel --prod

# Netlify
npx netlify deploy --prod --dir=dist

# Firebase Hosting
npx firebase deploy --only hosting

# Any static host / VPS — upload the dist/ folder
scp -r dist/* user@your-server:/var/www/rideflow/

The npm run build command generates a dist/ folder with static files. Deploy this folder to your hosting provider (Vercel, Netlify, Firebase, VPS, etc.).

Step 10 — Verify

After upgrading, check the following:

  • ✅ Application loads without console errors
  • ✅ Booking flow works end-to-end (create → confirm → track)
  • ✅ Admin dashboard loads with all sections accessible
  • ✅ Driver login and dashboard function correctly
  • ✅ Existing data (bookings, drivers, users) is intact
  • ✅ Footer version matches the target release

Quick Reference — Full Command Sequence

Copy and run this complete sequence for a typical upgrade:

Terminal — Complete Upgrade
# 1. Get the new version
git fetch origin && git checkout vX.X.X

# 2. Install dependencies
npm install

# 3. Install Supabase CLI (if not already installed)
npm i supabase

# 4. Log in (one-time per machine)
npx supabase login

# 5. Link project (skip if already linked)
npx supabase link --project-ref YOUR_SUPABASE_PROJECT_ID

# 6. Apply database migrations
npx supabase db push

# 7. Deploy edge functions
npx supabase functions deploy

# 8. Build frontend
npm run build

# 9. Deploy frontend (pick your host)
npx vercel --prod          # Vercel
# npx netlify deploy --prod --dir=dist   # Netlify
# npx firebase deploy --only hosting     # Firebase

Changelog

Track all version updates, new features, and improvements to RideFlow.

v2.2.3 AI Provider Verification & Multi-Provider Routing

March 2026

🚀 New Features

  • Preferred Provider Routing: The translate-batch edge function now accepts a preferredProvider parameter, allowing callers to force a specific AI backend (openai or google_gemini) regardless of the default priority chain
  • AI Provider Verification: Both Google Gemini and OpenAI APIs have been independently tested and confirmed operational for bulk translation workloads

🔧 Improvements

  • AI Settings UI Copy: Updated admin AI Services panel to clarify that built-in AI is active by default and custom API keys are optional — new translation keys builtInAiActive and customKeyOptional
  • Provider Resolution Logic: Refactored resolveAiProvider to cleanly support an optional override parameter while preserving the existing Gemini → OpenAI → Lovable fallback chain

📖 Documentation

  • Changelog: Added v2.2.3 release notes

v2.2.2 18-Language i18n, AI Features, Dual OAuth & UI Refinements

March 2026

🚀 New Features

  • 18 Languages: Expanded i18n from 4 to 18 languages — Arabic (RTL), Hindi, Italian, Japanese, Korean, Dutch, Polish, Portuguese, Russian, Swedish, Thai, Turkish, and Chinese added alongside English, Spanish, French, and German
  • Bulk Translation Manager: Admin settings tab for batch-translating all keys into any supported language via the translate-batch edge function
  • Translation Overrides: Per-language key overrides stored in translation_overrides table, applied at runtime via useLanguagesFromDB hook
  • AI Booking Features: New ai-booking-features edge function providing smart route suggestions, vehicle recommendations, and natural-language booking summaries — supports admin-configured Google Gemini or OpenAI keys
  • Location Proxy: New location-proxy edge function using OpenStreetMap Nominatim for free address geocoding and reverse geocoding (no API key required)
  • Email Provider Config: Admin can configure email delivery provider and view email delivery logs from the Notifications settings tab
  • X (Twitter) OAuth: Users can sign in with their X/Twitter account via Supabase OAuth
  • Facebook OAuth: Users can sign in with their Facebook account via Supabase OAuth
  • Self-Hosted Supabase OAuth: Social login (Google/Apple) auto-detects the hosting environment — uses managed OAuth on cloud-hosted deployments and supabase.auth.signInWithOAuth() on self-hosted deployments
  • Admin Provider Toggles: All 4 social login providers (Google, Apple, X/Twitter, Facebook) can be independently enabled/disabled from Admin Settings → Integrations
  • Self-Hosting Guidance: Admin settings include instructions for self-hosted users to configure OAuth providers in their Supabase Dashboard

🔧 Improvements

  • Address Input Redesign: Clean minimal inputs with colored accent borders (green for pickup/stops, red for drop-off), integrated locate-me and saved-locations buttons
  • Translation Coverage: All hardcoded UI strings converted to use useLanguage() translation keys throughout booking flow components
  • Languages Table: Database-managed language registry with activation toggles and translation completeness percentages
  • Auth Context Refactor: signInWithSocialProvider handles four providers with automatic routing — cloud-managed for Google/Apple, direct Supabase for Twitter/Facebook. Exposes isCloud flag for environment-aware behavior
  • Auth Page UI: Social login buttons conditionally rendered based on system_settings flags
  • Removed Legacy OAuth Edge Functions: Deleted social-auth-redirect, social-auth-callback, and update-auth-provider in favor of native SDK methods
  • Edge Functions: Added translate-batch, update-email-provider, and ai-booking-features; cleaned obsolete entries from supabase/config.toml
  • Edge Function Migration: Replaced deprecated import { serve } from "https://deno.land/std/http/server.ts" with native Deno.serve() across all 36 edge functions to resolve bundling failures caused by unreachable deno.land hosts. Pinned @supabase/supabase-js to @2.49.1 for all functions

🐛 Bug Fixes

  • Self-Hosted Build Fix: Converted the static cloud auth SDK import to a dynamic import() so Rollup/Vite no longer fails during self-hosted builds where the SDK is unavailable

📚 Documentation

  • i18n Section: Updated from 4 to 18 languages with translation override and bulk translation details
  • Edge Functions: Added 3 new functions to the reference table
  • Authentication: Updated to reflect all 4 social OAuth providers
  • Changelog: Merged all v2.2.2 entries into a single consolidated release

v2.1.2 Live Tracking Map, Driver UX & Contact Visibility Fixes

February 2026

🚀 New Features

  • Live Tracking Map: Replaced static placeholder with a real Leaflet map on the booking tracking page, centered on the pickup location while waiting for driver GPS data
  • Driver Waiting Indicator: Floating status overlay with animated car icon and "Waiting for driver location…" message on the tracking map
  • Privacy Policy & Terms of Service: New /privacy-policy and /terms-of-service pages with CMS-backed content and sensible defaults

🐛 Bug Fixes

  • Call Driver Button: Fixed text visibility by switching from bg-accent to bg-primary text-primary-foreground for proper contrast in all themes
  • Complete Ride Button: Removed customer-facing "Complete Ride" action from the tracking page — this is now driver-only, preventing accidental ride completion

🔧 Improvements

  • Assistance Section: Wrapped "Need assistance?" contact buttons in a styled card with bg-secondary/30 for better visual hierarchy
  • Live Chat UX: Added toast notification guiding users to the floating chat widget when clicking the Live Chat button
  • Access Control: Tightened tracking page to only show customer-appropriate actions

📚 Documentation

  • Complete Restructure: Reorganized all documentation into a clear linear flow: Getting Started → Configuration → Features → Technical Reference → Self-Hosting
  • Standardized Setup: Consolidated Install, Build, Deploy into a single sequential path with numbered steps

v1.4.0 Commission System, Loyalty, Enhanced Demo Mode & Comprehensive Docs

February 2026

🚀 New Features

  • Commission System: Configurable % auto-deducted from every completed ride with full driver earnings breakdown
  • Driver Earnings UI: Visual "Rider Paid → Service Fee → You Earned" flow with progress bar and per-ride detail
  • Booking Fees & Surcharges: Toll charges, airport fees, booking fee, cancellation fee — all rider-paid and visible in price breakdown
  • Loyalty Points System: Rider points with Bronze→Platinum tiers, balance tracking, and transaction history
  • Driver Bonuses: Milestone, performance, referral, and seasonal bonus types with progress tracking
  • Features Page: Public /features route with categorized feature summary and print/PDF export
  • Distance Unit Settings: Configurable km/miles with automatic conversion across the app
  • Enhanced Demo Mode: 10 granular environment variables for fine-grained demo control
  • Dynamic Branding: SystemSettingsContext applies brand colors as CSS custom properties

🔧 Improvements

  • Separated showDemoQuickLogin() from master isDemoMode() for granular control
  • Commission rate stored per-earning record for historical accuracy
  • Database trigger auto_record_driver_earning_on_completion for automatic commission

v1.3.0 Setup Wizard, Demo Mode & Documentation

February 2026

🚀 New Features

  • Setup Wizard: 7-step onboarding at /setup for self-hosted installations
  • Setup Guard: Automatic redirect when no Super Admin exists
  • Multi-variable Demo Mode: Master toggle + granular controls via env vars
  • Demo Banner & Watermark: Visual indicators for demo environments

v1.2.0 Payment Webhooks & Multi-Gateway Support

February 2026

🚀 New Features

  • Stripe, PayPal IPN, Coinbase Commerce webhook edge functions
  • Unified process-payment and process-refund functions
  • Payment status tracker with real-time lifecycle visualization

v1.1.0 Driver Portal & Admin Enhancements

January 2026

🚀 New Features

  • Complete driver onboarding flow with document upload
  • Driver dashboard with map/list views and pull-to-refresh
  • Shift management and earnings tracking
  • Admin scheduling, revenue analytics, document review

v1.0.0 Initial Release

January 2026

🚀 Features

  • 3-step booking flow with guest support
  • Vehicle management and dynamic pricing
  • Real-time tracking and notifications
  • Admin dashboard with full CRUD
  • Multi-language and theming support
  • PWA with offline capabilities