# H&A Stay Hub A comprehensive property rental platform designed specifically for the African market, connecting property owners with travelers and tenants across the continent. ## 🌍 Overview H&A Stay Hub is a modern web application that revolutionizes property rentals in Africa by providing: - **Verified Property Listings**: Curated accommodations from vibrant cities to serene safaris - **Secure Escrow Payments**: Built-in payment protection with mobile money integration - **KYC/KYB Onboarding**: Comprehensive verification for property owners, tenants, and agents - **Multi-Currency Support**: Local currency transactions across African regions - **Mobile-First Design**: Optimized for African mobile networks with offline capabilities ## ⚠️ Current Status (July 2026) The project is **feature-complete** across marketplace, bookings, payments, KYC, admin, and PWA shell, and the full UI/UX reboot is complete. It is currently in **pre-launch hardening** following a comprehensive audit on 2026-07-23. Notable remaining work before production: - Apply the latest Supabase migrations to the linked project. - Remove remaining `console.*` statements from service files and replace them with structured logging/Sentry. - Resolve type-safety debt (`any`/implicit casts) and ESLint hook dependency warnings. - Harden offline booking UX and payment flows for production. - Refresh README, WIKI, and PROJECT_STATUS documentation. See `docs/comprehensive-audit-fix-roadmap-2026-07-23.md` for the prioritized fix list. ## πŸš€ Features ### For Property Owners - **Complete KYC Verification**: Role-based onboarding with progress tracking - **Property Management**: Full CRUD operations for listings - **Secure Payments**: Escrow-based payment system with PIN protection - **Real-time Notifications**: Instant booking and payment alerts - **Earnings Analytics**: Track revenue and commission - **Dashboard**: Comprehensive overview of properties and bookings ### For Tenants & Travelers - **Verified Properties**: Browse curated, verified accommodations - **Easy Booking**: Streamlined booking process with instant confirmation - **Mobile Money**: M-Pesa, MTN Mobile Money, and Paystack integration - **Secure Payments**: Escrow protection for all transactions - **User Dashboard**: Track bookings, favorites, and messages - **Demo Mode**: Try the platform without creating an account ### For Agents - **Professional Onboarding**: Dedicated KYC verification for agents - **Multi-property Management**: Manage properties for multiple clients - **Commission Tracking**: Automated commission calculation and reporting - **Client Dashboard**: Overview of all managed properties - **Performance Analytics**: Track bookings and earnings ### Platform Features - **Unified Authentication**: Single page for sign in/sign up with demo mode - **Smart Onboarding**: Role-based wizard with auto-save and skip functionality - **Accessibility**: WCAG 2.1 AA compliant with full keyboard navigation - **Performance**: 60fps animations, lazy loading, optimized images - **Responsive Design**: Mobile-first approach optimized for African networks - **Real-time Updates**: Live messaging and notification system - **Multi-currency**: Support for local currencies across Africa - **Webhook System**: Automated payment event handling ## πŸ›  Tech Stack ### Frontend - **React 18** with TypeScript - **Vite** for fast development and building - **Tailwind CSS** for styling - **shadcn/ui** component library - **React Router** for navigation - **React Hook Form** with Zod validation - **Recharts** for analytics charts - **VitePWA / Workbox** for offline support ### Backend & Database - **Supabase** for backend-as-a-service - **PostgreSQL** database with Row Level Security - **Descope** for authentication ### Monitoring & Observability - **Sentry** (`@sentry/react`) for error tracking and session replay - Set `VITE_SENTRY_DSN` to enable; graceful no-op without it ### Key Integrations - **Mobile Money APIs** (M-Pesa, MTN, Paystack) - **Escrow Payment System** - **Currency Exchange** (ExchangeRate API β€” set `VITE_EXCHANGE_RATE_API_KEY`; falls back to static rates) - **iCal / `.ics` export** for calendar sync (Google Calendar, Apple Calendar, Outlook) ## πŸ“ Project Structure ``` src/ β”œβ”€β”€ components/ # Reusable UI components β”‚ β”œβ”€β”€ ui/ # shadcn/ui components β”‚ β”œβ”€β”€ onboarding/ # KYC forms β”‚ └── ... # Feature components β”œβ”€β”€ pages/ # Route components β”œβ”€β”€ integrations/ # External service integrations β”œβ”€β”€ hooks/ # Custom React hooks β”œβ”€β”€ lib/ # Utilities and configurations └── assets/ # Images and static files supabase/ β”œβ”€β”€ migrations/ # Database schema and seed data └── config.toml # Supabase configuration ``` ## πŸ—„ Database Schema ### Core Tables - **users**: User profiles with auth integration - **properties**: Property listings with owner relationships - **escrows**: Payment escrow system - **payment_events**: Payment transaction logs - **roles**: User role management - **user_roles**: Role assignments ### Key Features - Row Level Security (RLS) policies - Audit trails for escrow transactions - Multi-tenant architecture support ## πŸš€ Getting Started ### Prerequisites - Node.js 18+ and npm - Supabase account and project - Descope account for authentication ### Installation 1. **Clone the repository** ```bash git clone cd hna-stay-hub ``` 2. **Install dependencies** ```bash npm install ``` 3. **Environment Setup** - Copy `.env.example` to `.env.local` - Configure Supabase and Descope credentials 4. **Start development server** ```bash npm run dev ``` 5. **Database Setup** ```bash # Apply migrations supabase db push # Seed test data supabase db reset ``` ## πŸ“œ Available Scripts ### Development - `npm run dev` - Start development server on port 8087 - `npm run build` - Build for production - `npm run build:dev` - Build for development - `npm run preview` - Preview production build - `npm run lint` - Run ESLint ### Testing - `npm test` - Run all Playwright E2E tests - `npm run test:ui` - Run tests with Playwright UI - `npm run test:headed` - Run tests in headed mode (watch browser) - `npm run test:debug` - Debug tests with Playwright inspector ### Database - `supabase db push` - Apply migrations to database - `supabase db reset` - Reset database and apply all migrations - `supabase gen types typescript` - Generate TypeScript types from database schema ### Documentation - Auto-generated on every commit via GitHub Actions - Manual generation: `node .github/scripts/generate-docs.js` ## πŸ” Authentication & Onboarding ### Authentication System The app uses **Descope** for authentication with JWT tokens: - **Email/Password**: Secure login with validation - **Demo Mode**: Try the platform without creating an account - **Session Management**: Secure JWT token-based sessions - **Smart Routing**: Automatic redirect based on onboarding status ### Unified Auth Page (`/auth`) - **Tabbed Interface**: Switch between sign in and sign up - **Form Validation**: Real-time validation with Zod - **Password Requirements**: 8+ characters, uppercase, lowercase, number - **Demo Login**: Select role and explore without account - **Responsive Design**: Optimized for mobile and desktop ### Onboarding Wizard (`/onboarding`) - **Role Selection**: Choose Tenant, Property Owner, or Agent - **Progress Tracking**: Visual indicator with percentage - **KYC Forms**: Role-specific verification forms - **Auto-save**: Progress saved automatically to database - **Skip Option**: Complete profile later with confirmation - **Resume Capability**: Continue from where you left off ### Dashboard Integration - **Onboarding Banner**: Shows completion status and progress - **One-click Navigation**: Jump to onboarding wizard - **Session Dismissal**: Hide banner temporarily - **Benefits Display**: See what you'll gain by completing profile ### Technical Implementation - **Database Tables**: `user_profiles`, `onboarding_sessions` - **RLS Policies**: Secure data access control - **Service Layer**: `onboarding-service.ts` for business logic - **Custom Hooks**: `use-auth-redirect`, `use-onboarding-status` - **Context**: `OnboardingFlowContext` for state management ## πŸ’° Payment System ### Escrow Flow 1. Tenant books property β†’ Funds held in escrow 2. Property owner confirms β†’ Funds released 3. Automatic audit trails and notifications ### Supported Payment Methods - M-Pesa (Kenya) - MTN Mobile Money (Various countries) - Paystack (Nigeria and others) - Bank transfers ## 🌍 Deployment ### Live Application 🌐 **Production URL**: [https://hna.africa](https://hna.africa) πŸ”§ **Dev/Staging URL**: [https://home-n-away.vercel.app](https://home-n-away.vercel.app) ### Using Lovable 1. Visit [Lovable Project](https://lovable.dev/projects/0321bc9d-740d-4a37-b9a3-7be454230b0e) 2. Click Share β†’ Publish ### Vercel Deployment The application is deployed on Vercel with automatic deployments from the main branch. **Production URL**: https://hna.africa **Dev/Staging URL**: https://home-n-away.vercel.app **Configuration**: - Build command: `npm run build` - Publish directory: `dist` - Environment variables configured in Netlify dashboard ### Custom Domain Configure custom domains through Lovable dashboard under Project Settings or Netlify domain settings. ## 🀝 Contributing 1. Fork the repository 2. Create a feature branch 3. Make your changes 4. Run tests and linting 5. Submit a pull request ## πŸ“„ License This project is private and proprietary to H&A Platform. ## 🎯 Recent Achievements ### Full UI/UX Reboot & Pre-Launch Hardening (July 2026) - βœ… Full UI/UX reboot completed across all major components and pages - βœ… Payment secrets moved from the browser bundle to Supabase Edge Functions - βœ… Build/preview smoke gate added to CI - βœ… Escrow PIN salt validation and partial unique index on `escrows.pin_hashed` added - βœ… Rate limiter in-memory guidance and offline `BookingStatusTracker` offline gating - βœ… CSP report-only policy added to `vercel.json` and `netlify.toml` - βœ… Disabled/rollback migrations moved to `supabase/migrations/disabled/` - βœ… `offline.html` fallback wired into the PWA shell - βœ… Agent commission dashboard route (`/agent/commission`) and UI added - βœ… Operational-roles E2E route-guard coverage expanded - πŸ”„ Ongoing: type-safety cleanup, console log removal, and documentation refresh ### Unified Authentication & Onboarding (January 2025) βœ… **Implemented** | E2E tests in place - Unified authentication page with tabbed interface - Demo mode for testing without account creation - Role-based onboarding wizard (Tenant, Owner, Agent) - Progress tracking with auto-save functionality - Dashboard integration with completion banner - Smart routing based on onboarding status - Comprehensive database schema with RLS policies ### UI/UX Enhancement Suite (November 2025) βœ… **100% Complete** | 112+ Tests Passing | WCAG 2.1 AA Compliant - Refined logo and navigation components - Scroll-based effects and mobile menu - Enhanced hero section with parallax scrolling - Loading states and skeleton loaders - Page transition system with smooth animations - Full accessibility compliance (keyboard nav, screen readers) - Performance optimizations (60fps, lazy loading) ### Testing Infrastructure βœ… **Automated Test Infrastructure** - Unit and E2E suites in place (Playwright + Vitest) - E2E coverage for auth/onboarding flows - UI/UX and accessibility visual regression tests - Cross-browser and cross-device coverage - Some suites (operational roles, `StatCard.property.test.tsx`) still need stabilization ### Documentation βœ… **15+ Comprehensive Guides** - User guides and technical references - Testing documentation (E2E, accessibility, visual regression) - Component-specific guides - Implementation summaries - Auto-generated documentation system ## πŸ“š Documentation ### Complete Documentation Hub - **[Documentation Index](./docs/DOCUMENTATION_INDEX.md)** - Complete guide to all 30+ documentation files ### Quick Access - [Wiki](./WIKI.md) - Quick reference and recent updates - [Project Status](./docs/PROJECT_STATUS.md) - Current status and metrics - [User Guide](./docs/USER_GUIDE_AUTH_ONBOARDING.md) - How to use the platform - [Technical Reference](./docs/TECHNICAL_REFERENCE.md) - Architecture and implementation - [Testing Guide](./docs/PHASE1_TESTING_GUIDE.md) - How to test ## πŸ§ͺ Testing ### End-to-end tests Configure seeded test accounts, then run Playwright: ```bash # .env.local (do not commit) TEST_CLEANER_EMAIL=cleaner@example.com TEST_CLEANER_PASSWORD=... TEST_SUPERVISOR_EMAIL=supervisor@example.com TEST_SUPERVISOR_PASSWORD=... TEST_ADMIN_EMAIL=admin@example.com TEST_ADMIN_PASSWORD=... npm run test ``` ### PWA screenshots Start the app (`npm run dev` or `npm run preview`), then regenerate real screenshots: ```bash npm run generate:pwa-screenshots ``` ## πŸ“ž Support For support and questions: - πŸ“š Browse the [Documentation Index](./docs/DOCUMENTATION_INDEX.md) - πŸ“– Check the [Wiki](./WIKI.md) - πŸ› Report bugs via GitHub Issues - πŸ“§ Email: support@hna.africa --- # H&A Stay Hub - Project Wiki **Last Updated:** 2026-07-24 ## Table of Contents - [Overview](#overview) - [Recent Changes](#recent-changes) - [Project Structure](#project-structure) - [Features](#features) - [Development Guide](#development-guide) - [Troubleshooting](#troubleshooting) --- ## Overview H&A Stay Hub is a property rental marketplace designed specifically for the African market, connecting property owners with travelers and tenants across the continent. ### Tech Stack - **Frontend:** React 18 + TypeScript + Vite - **UI:** Tailwind CSS + shadcn/ui + Fluent Design System - **Backend:** Supabase (PostgreSQL) - **Auth:** Descope - **Payments:** M-Pesa, Paystack, MTN Mobile Money --- ## Recent Changes ### πŸ›‘οΈ P2 Pre-launch Hardening (July 2026) **Status:** Completed - Escrow PIN salt validation (`VITE_ESCROW_PIN_SALT`) now rejects default/missing values in `env-validator.ts` and `EscrowService`. - Added partial unique index `idx_escrows_pin_hashed_unique` on `escrows.pin_hashed` for active PIN uniqueness. - Updated `vercel.json` and `netlify.toml` with `Content-Security-Policy-Report-Only` to audit `unsafe-eval` removal. - Added production note to `src/lib/rate-limiter.ts` about per-deploy reset limitation. - Improved offline UX in `BookingStatusTracker` using `pwaService.isOnline()` and disabled action buttons when offline. - Archived disabled/rollback migrations into `supabase/migrations/disabled/` with a README. - `offline.html` fallback is pre-cached via `vite-plugin-pwa` includeAssets. - New `/agent/commission` route and `AgentCommissionDashboard` UI for agents to view commission by property. - Expanded `tests/operational-roles.spec.ts` route-guard coverage. ### Latest Implementations (November 2025) #### ✨ Unified Authentication & Onboarding System (100% Complete) **Status:** βœ… Production Ready | **Tests:** 57 E2E tests passing **Authentication Features:** - Unified authentication page with tabbed sign in/sign up interface - Form validation with Zod (email format, password requirements) - Demo mode with role selection for testing without account creation - Smart post-authentication routing based on onboarding status - Legacy route redirects (`/login` β†’ `/auth?mode=signin`) - Beautiful gradient background with responsive design **Onboarding Features:** - Role-based onboarding wizard (Tenant, Property Owner, Agent) - Visual progress indicator with step tracking - Skippable KYC verification with confirmation dialog - Auto-save functionality for progress persistence - Resume capability from any point in the flow - Dashboard completion banner with progress percentage **Technical Implementation:** - 20+ new components and hooks created - Onboarding service layer for business logic - Database schema with onboarding tracking - RLS policies for secure data access - Comprehensive error handling and loading states #### 🎨 UI/UX Enhancements (100% Complete) **Status:** βœ… Production Ready | **Tests:** 112+ tests passing | **Compliance:** WCAG 2.1 AA **Visual Improvements:** - Refined logo component with 44x44px touch targets - Scroll-based navigation with backdrop blur (>100px threshold) - Mobile navigation menu with 300ms slide-out animation - Enhanced hero section with gradient text and parallax scrolling - Dashboard visual hierarchy with staggered fade-in animations - Consistent card elevation system (shadow-elevation-2/4/8) **Animation System:** - Centralized animation configuration (200-300ms timing) - Custom hooks: useScrollPosition, useIntersectionObserver, useReducedMotion, useViewport - GPU-accelerated transforms for 60fps performance - Smooth page transitions with fade-in effects - Modal scale animations (95% to 100%, 250ms) - Button press feedback (scale to 95%, 100ms) **Loading & Feedback:** - Skeleton loader components with shimmer animation (1500ms) - Button loading spinners - Logo pulse animation during load - Smooth fade-in transitions (300ms) - Progress indicators throughout **Accessibility Features:** - Full keyboard navigation support (Tab/Shift+Tab) - Visible focus indicators (2px outline) - ARIA labels on all interactive elements - Screen reader support with live regions - Skip to main content link - WCAG AA color contrast compliance - Minimum 44x44px touch targets **Performance Optimizations:** - Lazy loading components with Intersection Observer - Optimized images with blur-up placeholders - Code splitting for faster initial load - Will-change optimization for animations - CSS transforms for GPU acceleration #### πŸ—„οΈ Database & Backend Enhancements - Added onboarding tracking fields to user_profiles table - Created onboarding_sessions table for progress persistence - Implemented comprehensive RLS policies for data security - Phase 1 core marketplace migration (properties, bookings, escrow) - Webhook system for payment event handling #### πŸ“š Documentation System - Automated documentation generation from commits - GitHub Actions workflow for auto-updates - 9+ comprehensive user and technical guides - Testing documentation (E2E, accessibility, visual regression) - Performance optimization guides #### πŸ”§ Bug Fixes & Improvements - Fixed crypto module browser compatibility issue in escrow service - Resolved database migration syntax errors - Updated RLS policies for proper access control - Fixed test suite syntax errors - Improved TypeScript type definitions --- ## Project Structure ### Key Directories ``` src/ β”œβ”€β”€ components/ β”‚ β”œβ”€β”€ ui/ # Base UI components (shadcn/ui) β”‚ β”œβ”€β”€ auth/ # Authentication components β”‚ β”œβ”€β”€ onboarding/ # Onboarding flow components β”‚ β”œβ”€β”€ payment/ # Payment-related components β”‚ └── dashboard/ # Dashboard components β”œβ”€β”€ pages/ # Route-level components β”œβ”€β”€ hooks/ # Custom React hooks β”œβ”€β”€ services/ # Business logic & API calls β”œβ”€β”€ contexts/ # React Context providers β”œβ”€β”€ integrations/ # External service integrations └── types/ # TypeScript type definitions ``` ### Database ``` supabase/ β”œβ”€β”€ migrations/ # SQL migration files └── functions/ # Edge functions ``` --- ## Features ### Core Features - βœ… Property Management (CRUD operations) - βœ… Booking System with escrow payments - βœ… User Authentication (Descope with JWT) - βœ… Unified Auth & Onboarding Flow - βœ… KYC/KYB Verification (role-based) - βœ… Multi-currency support - βœ… Mobile money integration (M-Pesa, Paystack, MTN) - βœ… Real-time messaging - βœ… Admin dashboard - βœ… Webhook system for payment events - βœ… Earnings analytics and tracking ### Authentication & Onboarding **Unified Authentication:** - Single page for sign in and sign up with tab switching - Email/password validation with Zod - Password strength requirements (8+ chars, uppercase, lowercase, number) - Demo mode with role selection (no account needed) - Smart routing based on onboarding status - Legacy route redirects for backward compatibility **Onboarding Wizard:** - Role selection: Tenant, Property Owner, or Agent - Visual progress indicator with percentage tracking - Role-specific KYC forms - Skip functionality with confirmation dialog - Auto-save progress to database - Resume from any point in the flow - Dashboard banner for incomplete profiles **Technical Features:** - Session persistence in onboarding_sessions table - RLS policies for secure data access - Onboarding status tracking (not_started, in_progress, completed, skipped) - Completion percentage calculation - Smart navigation and routing ### Payment Features **Escrow System:** - PIN-based fund release (4-6 digit PIN) - Secure escrow creation and management - Automatic audit trails - Transaction event logging **Payment Gateways:** - M-Pesa (Kenya mobile money) - Paystack (Nigerian payment processor) - MTN Mobile Money (multi-country) - Bank transfer support **Payment Features:** - Multi-currency support with real-time exchange rates - Secure transaction handling - Payment method selection UI - Webhook integration for payment events - Earnings analytics and reporting ### UI/UX Features **Design System:** - Fluent 2 Design System implementation - Custom design tokens and theming - Consistent elevation system (shadow-elevation-2/4/8/16/64) - Typography scale (display, title, body, caption) - Motion system with standardized animations - Dark mode support (class-based theme switching) **Animations:** - Scroll-based navigation effects - Page transitions (300ms fade-in) - Modal animations (scale 95% to 100%) - Button press feedback (scale to 95%) - Parallax scrolling on hero section - Staggered fade-in for dashboard cards - Shimmer effect on skeleton loaders **Accessibility:** - WCAG 2.1 Level AA compliant - Full keyboard navigation - Screen reader support with ARIA labels - Visible focus indicators (2px outline) - Skip to main content link - Minimum 44x44px touch targets - Color contrast compliance (4.5:1 minimum) **Performance:** - Lazy loading with Intersection Observer - Optimized images with blur-up placeholders - Code splitting for faster load times - GPU-accelerated animations (60fps) - Reduced motion support - Will-change optimization --- ## Development Guide ### Getting Started ```bash # Install dependencies npm install # Start development server (port 8087) npm run dev # Build for production npm run build # Preview production build npm run preview # Run tests npm test ``` ### Environment Setup Create a `.env` file with: ```env VITE_SUPABASE_URL=your_supabase_url VITE_SUPABASE_PUBLISHABLE_KEY=your_supabase_anon_key VITE_DESCOPE_PROJECT_ID=your_descope_project_id VITE_ESCROW_PIN_SALT=your_pin_salt ``` See `.env.example` for full list. ### Database Migrations ```bash # Apply migrations using Supabase CLI supabase db push # Or use the migration scripts ./apply-migration.bat # Windows ./apply-migration.sh # Linux/Mac ``` ### Code Quality ```bash # Lint code npm run lint # Type check npx tsc --noEmit ``` --- ## Troubleshooting ### Common Issues #### Build Errors **Problem:** Module not found or import errors ```bash # Solution: Clear cache and reinstall rm -rf node_modules package-lock.json npm install ``` **Problem:** TypeScript errors after database changes ```bash # Solution: Regenerate Supabase types supabase gen types typescript --local > src/integrations/supabase/types.ts ``` #### Database Issues **Problem:** Migration fails - Check migration file syntax - Verify table/column names - Review RLS policies - Check for existing data conflicts **Problem:** RLS policy errors - Verify user authentication - Check policy conditions - Review table permissions #### Authentication Issues **Problem:** Login redirect not working - Check `use-auth-redirect` hook implementation - Verify onboarding status in database - Review routing configuration **Problem:** Demo login not persisting - Check localStorage for `demoUser` key - Verify OnboardingFlowContext initialization - Review session management ### Debug Tips 1. **Check Browser Console** - Look for error messages - Review network requests - Check localStorage/sessionStorage 2. **Database Queries** - Use Supabase dashboard to inspect data - Check RLS policies in SQL editor - Review query logs 3. **Authentication Flow** - Verify Descope configuration - Check session tokens - Review auth state in React DevTools --- ## Documentation ### User Guides - [User Guide: Auth & Onboarding](docs/USER_GUIDE_AUTH_ONBOARDING.md) - [Accessibility Guide](docs/ACCESSIBILITY_GUIDE.md) - [Environment Setup](docs/ENVIRONMENT_SETUP.md) ### Technical Documentation - [Technical Reference](docs/TECHNICAL_REFERENCE.md) - [Migration Guide](docs/PHASE1_MIGRATION_GUIDE.md) - [Quick Start Migration](docs/QUICK_START_MIGRATION.md) - [Migration Troubleshooting](docs/MIGRATION_TROUBLESHOOTING.md) - [Auto-Docs System](docs/AUTO_DOCS_README.md) ### Testing Guides - [Phase 1 Testing Guide](docs/PHASE1_TESTING_GUIDE.md) - [Accessibility Testing Guide](docs/ACCESSIBILITY_TESTING_GUIDE.md) - [Visual Regression Testing Guide](docs/VISUAL_REGRESSION_TESTING_GUIDE.md) - [Testing Commands](docs/TESTING_COMMANDS.md) ### Component Guides - [Loading States Guide](docs/LOADING_STATES_GUIDE.md) - [Page Transitions Guide](docs/PAGE_TRANSITIONS_GUIDE.md) - [Footer Component Guide](docs/FOOTER_COMPONENT_GUIDE.md) - [Performance Optimization Guide](docs/PERFORMANCE_OPTIMIZATION_GUIDE.md) ### Implementation Summaries - [Unified Auth Implementation Summary](docs/UNIFIED_AUTH_IMPLEMENTATION_SUMMARY.md) - [UI/UX Enhancement Complete](docs/UI_UX_ENHANCEMENT_COMPLETE.md) - [Implementation Complete](docs/IMPLEMENTATION_COMPLETE.md) - [Test Suite Complete](docs/TEST_SUITE_COMPLETE.md) - [Webhook Implementation Review](docs/WEBHOOK_IMPLEMENTATION_REVIEW.md) --- ## Quick Links ### πŸ“š Documentation Hub - **[Documentation Index](docs/DOCUMENTATION_INDEX.md)** - Complete guide to all documentation ### πŸ“Š Project Overview - [Project Status](docs/PROJECT_STATUS.md) - Comprehensive status and metrics - [Changelog](docs/CHANGELOG.md) - All notable changes - [README](README.md) - Project introduction ### πŸ“– User Documentation - [User Guide: Auth & Onboarding](docs/USER_GUIDE_AUTH_ONBOARDING.md) - [Accessibility Guide](docs/ACCESSIBILITY_GUIDE.md) - [Environment Setup](docs/ENVIRONMENT_SETUP.md) ### πŸ”§ Technical Documentation - [Technical Reference](docs/TECHNICAL_REFERENCE.md) - [Migration Guide](docs/PHASE1_MIGRATION_GUIDE.md) - [Quick Start Migration](docs/QUICK_START_MIGRATION.md) - [Migration Troubleshooting](docs/MIGRATION_TROUBLESHOOTING.md) ### πŸ§ͺ Testing Documentation - [Phase 1 Testing Guide](docs/PHASE1_TESTING_GUIDE.md) - [Accessibility Testing](docs/ACCESSIBILITY_TESTING_GUIDE.md) - [Visual Regression Testing](docs/VISUAL_REGRESSION_TESTING_GUIDE.md) - [Testing Commands](docs/TESTING_COMMANDS.md) ### 🎨 Component Guides - [Loading States Guide](docs/LOADING_STATES_GUIDE.md) - [Page Transitions Guide](docs/PAGE_TRANSITIONS_GUIDE.md) - [Footer Component Guide](docs/FOOTER_COMPONENT_GUIDE.md) - [Performance Optimization](docs/PERFORMANCE_OPTIMIZATION_GUIDE.md) ### πŸ“ Implementation Summaries - [Unified Auth Implementation](docs/UNIFIED_AUTH_IMPLEMENTATION_SUMMARY.md) - [UI/UX Enhancement Complete](docs/UI_UX_ENHANCEMENT_COMPLETE.md) - [Implementation Complete](docs/IMPLEMENTATION_COMPLETE.md) - [Test Suite Complete](docs/TEST_SUITE_COMPLETE.md) --- ## Statistics ### Project Metrics - **Total Tests:** 169+ automated tests - **Test Coverage:** Comprehensive (E2E, UI/UX, Accessibility) - **Documentation:** 15+ comprehensive guides - **Accessibility:** WCAG 2.1 AA compliant - **Performance:** 60fps animations, < 2s page load ### Code Statistics - **Components:** 100+ - **Custom Hooks:** 15+ - **Service Layers:** 10+ - **Pages:** 15+ - **Database Tables:** 10+ ### Feature Completion - βœ… Phase 1 Core Marketplace (100%) - βœ… Unified Auth & Onboarding (100%) - βœ… UI/UX Enhancement Suite (100%) - βœ… Testing Infrastructure (100%) - βœ… Documentation System (100%) --- **This wiki is automatically updated by GitHub Actions on every commit.** *For manual updates, run: `node .github/scripts/generate-docs.js`* --- # H&A Stay Hub - Documentation Index **Complete guide to all project documentation** Last Updated: November 16, 2025 --- ## Γ°ΕΈβ€œΕ‘ Documentation Overview This project includes comprehensive documentation covering all aspects of development, testing, deployment, and usage. This index helps you find the right documentation for your needs. --- ## Γ°ΕΈΕ½Β― Start Here ### New to the Project? 1. **[README.md](../README.md)** - Project introduction and overview 2. **[WIKI.md](../WIKI.md)** - Quick reference and recent updates 3. **[PROJECT_STATUS.md](./PROJECT_STATUS.md)** - Current status and metrics 4. **[ENVIRONMENT_SETUP.md](./ENVIRONMENT_SETUP.md)** - Get your dev environment ready ### Need to Understand a Feature? 1. **[User Guide: Auth & Onboarding](./USER_GUIDE_AUTH_ONBOARDING.md)** - How to use the system 2. **[Technical Reference](./TECHNICAL_REFERENCE.md)** - How it works under the hood 3. **Implementation Summaries** - Detailed feature documentation ### Want to Contribute? 1. **[Technical Reference](./TECHNICAL_REFERENCE.md)** - Architecture and patterns 2. **[Testing Guide](./PHASE1_TESTING_GUIDE.md)** - How to test your changes 3. **[Migration Guide](./PHASE1_MIGRATION_GUIDE.md)** - Database changes --- ## Γ°ΕΈβ€œβ€“ User Documentation ### Getting Started - **[Environment Setup](./ENVIRONMENT_SETUP.md)** - Prerequisites and installation - Environment variables - Database setup - Running the application - **[User Guide: Auth & Onboarding](./USER_GUIDE_AUTH_ONBOARDING.md)** - How to sign up and sign in - Using demo mode - Completing onboarding - Dashboard features ### Accessibility - **[Accessibility Guide](./ACCESSIBILITY_GUIDE.md)** - Keyboard navigation - Screen reader support - WCAG compliance - Accessibility features --- ## 🔧 Technical Documentation ### Architecture & Design - **[Technical Reference](./TECHNICAL_REFERENCE.md)** - System architecture - Component structure - Data flow - Security model - API integration - **[Project Status](./PROJECT_STATUS.md)** - Feature completion status - Metrics and statistics - Technology stack - Browser support - Timeline ### Database - **[Phase 1 Migration Guide](./PHASE1_MIGRATION_GUIDE.md)** - Database schema overview - Migration process - RLS policies - Data relationships - **[Quick Start Migration](./QUICK_START_MIGRATION.md)** - Fast migration setup - Common commands - Quick troubleshooting - **[Migration Troubleshooting](./MIGRATION_TROUBLESHOOTING.md)** - Common issues - Error messages - Solutions - Best practices - **[Apply Migration Dashboard](./APPLY_MIGRATION_DASHBOARD.md)** - Dashboard-specific migrations - Data updates - Verification steps ### Implementation Details - **[Unified Auth Implementation Summary](./UNIFIED_AUTH_IMPLEMENTATION_SUMMARY.md)** - Authentication system - Onboarding wizard - Database schema - Component architecture - 57 E2E tests - **[UI/UX Enhancement Complete](./UI_UX_ENHANCEMENT_COMPLETE.md)** - Visual improvements - Animation system - Accessibility features - Performance optimizations - 112+ tests - **[Implementation Complete](./IMPLEMENTATION_COMPLETE.md)** - Overall implementation status - All 14 tasks completed - File structure - Configuration - **[Webhook Implementation Review](./WEBHOOK_IMPLEMENTATION_REVIEW.md)** - Webhook system - Payment events - Integration details ### Automation - **[Auto-Documentation System](./AUTO_DOCS_README.md)** - GitHub Actions workflow - Documentation generation - Auto-update process - Manual generation --- ## Γ°ΕΈΒ§Βͺ Testing Documentation ### Test Guides - **[Phase 1 Testing Guide](./PHASE1_TESTING_GUIDE.md)** - Testing strategy - Test types - Running tests - Writing tests - **[Test Suite Complete](./TEST_SUITE_COMPLETE.md)** - 57 E2E tests - Test coverage - Running tests - Test files overview - **[Testing Commands](./TESTING_COMMANDS.md)** - All test commands - Command options - CI/CD integration ### Specialized Testing - **[Accessibility Testing Guide](./ACCESSIBILITY_TESTING_GUIDE.md)** - Accessibility test suite - axe-core integration - Keyboard navigation tests - Screen reader tests - 25+ accessibility tests - **[Visual Regression Testing Guide](./VISUAL_REGRESSION_TESTING_GUIDE.md)** - Visual regression tests - Screenshot comparison - Cross-browser testing - 55+ visual tests ### Test Documentation - **[tests/README.md](../tests/README.md)** - Test file organization - Test patterns - Best practices - Examples --- ## Γ°ΕΈΕ½Β¨ Component Documentation ### UI Components - **[Loading States Guide](./LOADING_STATES_GUIDE.md)** - Skeleton loaders - Loading spinners - Progress indicators - Shimmer effects - Usage examples - **[Page Transitions Guide](./PAGE_TRANSITIONS_GUIDE.md)** - Page transition system - Animation timing - Modal animations - Button feedback - Implementation - **[Footer Component Guide](./FOOTER_COMPONENT_GUIDE.md)** - Footer structure - Logo integration - Responsive design - Styling ### Performance - **[Performance Optimization Guide](./PERFORMANCE_OPTIMIZATION_GUIDE.md)** - Lazy loading - Image optimization - Code splitting - Animation performance - Best practices --- ## Γ°ΕΈβ€œΒ Project Management ### Planning & Specs - **[.kiro/specs/phase1-marketplace/](../.kiro/specs/phase1-marketplace/)** - Requirements document - Design document - Task list - **[.kiro/specs/unified-auth-onboarding/](../.kiro/specs/unified-auth-onboarding/)** - Requirements document - Design document - Task list - **[.kiro/specs/ui-ux-enhancement/](../.kiro/specs/ui-ux-enhancement/)** - Requirements document - Design document - Task list ### Progress Tracking - **[Phase 1 Progress Summary](./PHASE1_PROGRESS_SUMMARY.md)** - Feature completion - Milestone tracking - Next steps - **[Migration Summary](./MIGRATION_SUMMARY.md)** - Migration status - Applied migrations - Pending migrations ### Change Management - **[CHANGELOG.md](./CHANGELOG.md)** - All notable changes - Version history - Feature additions - Bug fixes ### Incident Reports - **[INCIDENT_PROD_TDZ_CRASH_2026-06-15.md](./INCIDENT_PROD_TDZ_CRASH_2026-06-15.md)** - P0: White blank page on all routes in production - Root cause: Rollup cross-chunk TDZ crash from `manualChunks` - Fix: Removed `manualChunks` from `vite.config.ts` - Lessons learned and prevention steps --- ## 🔍 Quick Reference ### By Role #### For Developers 1. [Technical Reference](./TECHNICAL_REFERENCE.md) 2. [Environment Setup](./ENVIRONMENT_SETUP.md) 3. [Testing Guide](./PHASE1_TESTING_GUIDE.md) 4. [Migration Guide](./PHASE1_MIGRATION_GUIDE.md) #### For QA Engineers 1. [Testing Commands](./TESTING_COMMANDS.md) 2. [Accessibility Testing](./ACCESSIBILITY_TESTING_GUIDE.md) 3. [Visual Regression Testing](./VISUAL_REGRESSION_TESTING_GUIDE.md) 4. [Test Suite Complete](./TEST_SUITE_COMPLETE.md) #### For Product Managers 1. [Project Status](./PROJECT_STATUS.md) 2. [User Guide](./USER_GUIDE_AUTH_ONBOARDING.md) 3. [Implementation Summaries](./IMPLEMENTATION_COMPLETE.md) 4. [Phase 1 Progress](./PHASE1_PROGRESS_SUMMARY.md) #### For Designers 1. [UI/UX Enhancement Complete](./UI_UX_ENHANCEMENT_COMPLETE.md) 2. [Accessibility Guide](./ACCESSIBILITY_GUIDE.md) 3. [Loading States Guide](./LOADING_STATES_GUIDE.md) 4. [Page Transitions Guide](./PAGE_TRANSITIONS_GUIDE.md) #### For End Users 1. [User Guide: Auth & Onboarding](./USER_GUIDE_AUTH_ONBOARDING.md) 2. [Accessibility Guide](./ACCESSIBILITY_GUIDE.md) 3. [README](../README.md) ### By Topic #### Authentication & Onboarding - [User Guide: Auth & Onboarding](./USER_GUIDE_AUTH_ONBOARDING.md) - [Unified Auth Implementation](./UNIFIED_AUTH_IMPLEMENTATION_SUMMARY.md) - [Technical Reference](./TECHNICAL_REFERENCE.md) #### Database & Migrations - [Phase 1 Migration Guide](./PHASE1_MIGRATION_GUIDE.md) - [Quick Start Migration](./QUICK_START_MIGRATION.md) - [Migration Troubleshooting](./MIGRATION_TROUBLESHOOTING.md) - [Migration Summary](./MIGRATION_SUMMARY.md) #### Testing - [Phase 1 Testing Guide](./PHASE1_TESTING_GUIDE.md) - [Accessibility Testing](./ACCESSIBILITY_TESTING_GUIDE.md) - [Visual Regression Testing](./VISUAL_REGRESSION_TESTING_GUIDE.md) - [Test Suite Complete](./TEST_SUITE_COMPLETE.md) - [Testing Commands](./TESTING_COMMANDS.md) #### UI/UX - [UI/UX Enhancement Complete](./UI_UX_ENHANCEMENT_COMPLETE.md) - [Loading States Guide](./LOADING_STATES_GUIDE.md) - [Page Transitions Guide](./PAGE_TRANSITIONS_GUIDE.md) - [Footer Component Guide](./FOOTER_COMPONENT_GUIDE.md) - [Accessibility Guide](./ACCESSIBILITY_GUIDE.md) #### Performance - [Performance Optimization Guide](./PERFORMANCE_OPTIMIZATION_GUIDE.md) - [Technical Reference](./TECHNICAL_REFERENCE.md) #### Payments - [Webhook Implementation Review](./WEBHOOK_IMPLEMENTATION_REVIEW.md) - [Technical Reference](./TECHNICAL_REFERENCE.md) --- ## Γ°ΕΈβ€œΕ  Documentation Statistics ### Total Documents: 31+ - User Guides: 4 - Technical Docs: 8 - Testing Docs: 6 - Component Guides: 4 - Implementation Summaries: 5 - Project Management: 3 - Incident Reports: 1 ### Documentation Coverage - Òœ… Getting Started: Complete - Òœ… User Documentation: Complete - Òœ… Technical Documentation: Complete - Òœ… Testing Documentation: Complete - Òœ… Component Documentation: Complete - Òœ… API Documentation: In Progress ### Auto-Generated Documentation - Òœ… WIKI.md (auto-updated on commit) - Òœ… CHANGELOG.md (auto-updated on commit) - Òœ… GitHub Actions workflow configured --- ## Γ°ΕΈβ€β€ž Documentation Maintenance ### Auto-Updates Documentation is automatically updated on every commit via GitHub Actions: - WIKI.md is regenerated - CHANGELOG.md is updated - Technical reference is refreshed ### Manual Updates For manual documentation updates: ```bash node .github/scripts/generate-docs.js ``` ### Contributing to Documentation 1. Follow the existing format and style 2. Use clear, concise language 3. Include code examples where appropriate 4. Update this index when adding new docs 5. Test all commands and examples --- ## Γ°ΕΈβ€œΕΎ Support ### Documentation Issues - Found a typo? Open a GitHub issue - Missing documentation? Request it via GitHub - Unclear instructions? Let us know ### Getting Help - Check the relevant documentation first - Search existing GitHub issues - Open a new issue with details - Contact the development team --- ## Γ°ΕΈΕ½Β― Documentation Goals ### Current Status - Òœ… Comprehensive coverage of all features - Òœ… User and technical documentation - Òœ… Testing documentation - Òœ… Component guides - Òœ… Auto-generation system ### Future Improvements - [ ] API documentation (Swagger/OpenAPI) - [ ] Video tutorials - [ ] Interactive examples - [ ] Internationalization (i18n) - [ ] More code examples --- **Last Updated:** June 15, 2026 **Maintained By:** H&A Stay Hub Development Team **Auto-Generated:** Yes (via GitHub Actions) --- # H&A Stay Hub - Project Status **Last Updated:** July 24, 2026 ## πŸ“Š Overall Status > **Project Phase:** Pre-launch hardening. The platform is feature-complete but not yet production-hardened. A comprehensive audit on 2026-07-23 identified launch blockers and gaps that are actively being addressed. - **Code Quality**: UI/UX reboot complete; type-safety and lint debt remain - **Test Coverage**: Unit and E2E infrastructure in place; some suites need expansion/stabilization - **Documentation**: Comprehensive (15+ guides); refresh in progress - **Accessibility**: WCAG 2.1 AA target; ongoing visual regression testing - **Performance**: 60fps target; build and PWA optimizations ongoing --- ## 🎯 Feature Completion Status ### βœ… Phase 1: Core Marketplace (100% Complete) **Status:** Production Ready | **Migration:** Applied #### Database Schema - βœ… User profiles with role management - βœ… Properties table with owner relationships - βœ… Bookings system with status tracking - βœ… Escrow payment system with PIN protection - βœ… Payment events logging - βœ… Onboarding tracking - βœ… RLS policies for all tables #### Property Management - βœ… Create, read, update, delete properties - βœ… Image upload and management - βœ… Pricing and availability settings - βœ… Property search and filtering - βœ… Property details page - βœ… Favorites system #### Booking System - βœ… Booking creation and management - βœ… Booking confirmation flow - βœ… Status tracking (pending, confirmed, completed, cancelled) - βœ… Booking history - βœ… Real-time availability checking #### Payment Integration - βœ… Escrow system with PIN-based release - βœ… M-Pesa integration - βœ… Paystack integration - βœ… MTN Mobile Money integration - βœ… Payment method selection UI - βœ… Transaction logging - βœ… Webhook system for payment events - βœ… Earnings analytics ### βœ… Unified Authentication & Onboarding (100% Complete) **Status:** Production Ready | **Tests:** 57 E2E tests passing #### Authentication Features - βœ… Unified auth page with tabbed interface - βœ… Sign in form with validation - βœ… Sign up form with password requirements - βœ… Demo mode with role selection - βœ… Smart post-auth routing - βœ… Legacy route redirects - βœ… Session management - βœ… Error handling and loading states #### Onboarding System - βœ… Role selection (Tenant, Property Owner, Agent) - βœ… Visual progress indicator - βœ… Role-specific KYC forms - βœ… Auto-save functionality - βœ… Skip with confirmation dialog - βœ… Resume capability - βœ… Dashboard completion banner - βœ… Progress percentage tracking #### Technical Implementation - βœ… Database schema (onboarding_sessions table) - βœ… RLS policies for secure access - βœ… Onboarding service layer - βœ… Custom hooks (use-auth-redirect, use-onboarding-status) - βœ… Context management (OnboardingFlowContext) - βœ… 20+ new components created ### βœ… UI/UX Enhancement Suite (100% Complete) **Status:** Production Ready | **Tests:** 112+ tests passing | **Compliance:** WCAG 2.1 AA #### Visual Enhancements - βœ… Refined logo component (44x44px touch targets) - βœ… Scroll-based navigation effects - βœ… Mobile navigation menu (300ms slide-out) - βœ… Enhanced hero section with parallax - βœ… Dashboard visual hierarchy - βœ… Consistent card elevation system - βœ… Loading states and skeleton loaders - βœ… Page transition system - βœ… Enhanced footer component #### Animation System - βœ… Centralized animation configuration - βœ… Custom hooks (useScrollPosition, useIntersectionObserver, useReducedMotion, useViewport) - βœ… GPU-accelerated transforms (60fps) - βœ… Smooth page transitions (300ms fade-in) - βœ… Modal animations (scale 95% to 100%) - βœ… Button press feedback (scale to 95%) - βœ… Shimmer effect on loaders (1500ms) - βœ… Staggered animations for lists #### Accessibility Features - βœ… Full keyboard navigation (Tab/Shift+Tab) - βœ… Visible focus indicators (2px outline) - βœ… ARIA labels on all interactive elements - βœ… Screen reader support with live regions - βœ… Skip to main content link - βœ… WCAG AA color contrast (4.5:1 minimum) - βœ… Minimum 44x44px touch targets - βœ… Reduced motion support #### Performance Optimizations - βœ… Lazy loading with Intersection Observer - βœ… Optimized images with blur-up placeholders - βœ… Code splitting for faster load - βœ… Will-change optimization - βœ… CSS transforms for GPU acceleration - βœ… 60fps animation performance ### βœ… Testing Infrastructure (100% Complete) **Status:** 169+ Automated Tests #### E2E Tests (57 tests) - βœ… Authentication flow tests (15 tests) - βœ… Onboarding wizard tests (15 tests) - βœ… Dashboard integration tests (13 tests) - βœ… End-to-end user journey tests (14 tests) #### UI/UX Tests (112+ tests) - βœ… Visual regression tests (55+ tests) - βœ… Accessibility tests (25+ tests) - βœ… Component tests (32+ tests) #### Test Coverage - βœ… Cross-browser testing (Chrome, Firefox, Safari, Edge) - βœ… Cross-device testing (Desktop, Mobile, Tablet) - βœ… Accessibility testing with axe-core - βœ… Performance benchmarking - βœ… Keyboard navigation testing - βœ… Screen reader compatibility testing ### βœ… Documentation System (100% Complete) **Status:** 15+ Comprehensive Guides #### User Documentation - βœ… User Guide: Auth & Onboarding - βœ… Accessibility Guide - βœ… Environment Setup Guide - βœ… Quick Start Guide #### Technical Documentation - βœ… Technical Reference - βœ… Migration Guide - βœ… Quick Start Migration - βœ… Migration Troubleshooting - βœ… Auto-Documentation System #### Testing Documentation - βœ… Phase 1 Testing Guide - βœ… Accessibility Testing Guide - βœ… Visual Regression Testing Guide - βœ… Testing Commands Reference #### Component Documentation - βœ… Loading States Guide - βœ… Page Transitions Guide - βœ… Footer Component Guide - βœ… Performance Optimization Guide #### Implementation Summaries - βœ… Unified Auth Implementation Summary - βœ… UI/UX Enhancement Complete - βœ… Implementation Complete - βœ… Test Suite Complete - βœ… Webhook Implementation Review #### Auto-Generated Documentation - βœ… GitHub Actions workflow - βœ… Automated WIKI updates - βœ… Automated CHANGELOG updates - βœ… Documentation generation script --- ## πŸ“ˆ Metrics & Statistics ### Code Statistics - **Total Components:** 100+ - **Custom Hooks:** 15+ - **Service Layers:** 10+ - **Pages:** 15+ - **Database Tables:** 10+ - **Migrations:** 70+ ### Test Statistics - **Total Tests:** 169+ - **E2E Tests:** 57 - **UI/UX Tests:** 112+ - **Test Files:** 5 - **Test Coverage:** Comprehensive ### Documentation Statistics - **Total Guides:** 15+ - **User Guides:** 4 - **Technical Docs:** 5 - **Testing Docs:** 4 - **Component Docs:** 4 - **Implementation Summaries:** 5 ### Performance Metrics - **First Contentful Paint (FCP):** < 1.5s βœ… - **Largest Contentful Paint (LCP):** < 2.5s βœ… - **Cumulative Layout Shift (CLS):** < 0.1 βœ… - **First Input Delay (FID):** < 100ms βœ… - **Animation Frame Rate:** 60fps βœ… ### Accessibility Metrics - **WCAG 2.1 Level A:** 100% compliant βœ… - **WCAG 2.1 Level AA:** 100% compliant βœ… - **Keyboard Accessible:** All features βœ… - **Screen Reader Compatible:** All content βœ… - **Touch Targets:** All meet 44x44px βœ… - **Color Contrast:** All meet 4.5:1 βœ… --- ## πŸš€ Technology Stack ### Frontend - **Framework:** React 18 with TypeScript - **Build Tool:** Vite 5 with SWC - **Styling:** Tailwind CSS with Fluent 2 Design System - **UI Components:** shadcn/ui (Radix UI primitives) - **Routing:** React Router v6 - **State Management:** TanStack Query + React Context - **Forms:** React Hook Form with Zod validation - **Icons:** Lucide React - **Maps:** Leaflet with React Leaflet ### Backend & Services - **Database:** Supabase (PostgreSQL) with RLS - **Authentication:** Descope with JWT tokens - **File Storage:** Supabase Storage - **Real-time:** Supabase Realtime ### Payment Integrations - **M-Pesa:** Kenya mobile money - **Paystack:** Nigerian payment processor - **MTN Mobile Money:** Multi-country support - **Escrow:** PIN-based fund release system ### Development Tools - **Linting:** ESLint with TypeScript ESLint - **Testing:** Playwright for E2E tests - **Package Manager:** npm - **Version Control:** Git - **CI/CD:** GitHub Actions --- ## 🎯 Current Focus Areas ### Production Readiness - βœ… All core features implemented - βœ… Comprehensive test coverage - βœ… Documentation complete - βœ… Accessibility compliant - βœ… Performance optimized ### Deployment Preparation - βœ… Database migrations ready - βœ… Environment configuration documented - βœ… Testing infrastructure in place - βœ… Documentation system automated ### P2 Pre-launch Hardening (July 2026) - βœ… Escrow PIN salt validation and partial unique index on `escrows.pin_hashed` - βœ… CSP report-only policy added to Vercel/Netlify headers for `unsafe-eval` audit - βœ… Rate limiter production guidance documented - βœ… Offline booking action gating in `BookingStatusTracker` and `offline.html` fallback - βœ… Disabled/rollback migrations archived in `supabase/migrations/disabled/` - βœ… Agent commission dashboard (`/agent/commission`) route and UI - βœ… Expanded `tests/operational-roles.spec.ts` route-guard coverage - πŸ”„ Remaining: type-safety debt, console log cleanup, full documentation refresh ### Next Steps 1. **Production Deployment** - Apply database migrations to production - Deploy application to production environment - Configure custom domain - Set up monitoring and analytics 2. **User Onboarding** - Conduct user testing sessions - Gather feedback on auth and onboarding flows - Monitor completion rates - Iterate based on user feedback 3. **Performance Monitoring** - Set up performance monitoring - Track Core Web Vitals - Monitor error rates - Optimize based on real-world data 4. **Feature Enhancements** - Social authentication (Google, Facebook) - Two-factor authentication - Advanced search filters - Property recommendations - In-app messaging enhancements --- ## πŸ”„ Development Workflow ### Version Control - **Main Branch:** Production-ready code - **Development Branch:** Active development - **Feature Branches:** Individual features - **Commit Convention:** Conventional Commits ### Testing Workflow 1. Write code 2. Run unit tests 3. Run E2E tests 4. Check accessibility 5. Review performance 6. Submit for review ### Documentation Workflow - Auto-generated on every commit - Manual updates for major changes - Review and approval process - Version control for docs ### Deployment Workflow 1. Merge to main branch 2. Run full test suite 3. Build production bundle 4. Apply database migrations 5. Deploy to production 6. Monitor for issues --- ## πŸ“Š Browser & Device Support ### Desktop Browsers - βœ… Chrome/Edge (last 2 versions) - βœ… Firefox (last 2 versions) - βœ… Safari (last 2 versions) ### Mobile Browsers - βœ… Mobile Safari (iOS 13+) - βœ… Chrome Mobile (Android 8+) - βœ… Samsung Internet ### Device Categories - βœ… Desktop (1920x1080 and above) - βœ… Laptop (1366x768 and above) - βœ… Tablet (768x1024) - βœ… Mobile (375x667 and above) --- ## πŸŽ“ Team Resources ### Getting Started 1. Read [Environment Setup](./ENVIRONMENT_SETUP.md) 2. Review [Technical Reference](./TECHNICAL_REFERENCE.md) 3. Check [User Guide](./USER_GUIDE_AUTH_ONBOARDING.md) 4. Run tests: `npm test` ### Development Resources - [Project Structure](../.kiro/steering/structure.md) - [Technology Stack](../.kiro/steering/tech.md) - [Product Overview](../.kiro/steering/product.md) - [Testing Guide](./PHASE1_TESTING_GUIDE.md) ### Support Channels - Technical Documentation: `docs/` - Test Documentation: `tests/README.md` - Spec Documents: `.kiro/specs/` - GitHub Issues: For bug reports and feature requests --- ## πŸ† Achievements ### Code Quality - βœ… TypeScript strict mode (where applicable) - βœ… ESLint configuration - βœ… Consistent code style - βœ… Component-based architecture - βœ… Service layer separation ### Testing Excellence - βœ… 169+ automated tests - βœ… Cross-browser coverage - βœ… Cross-device coverage - βœ… Accessibility testing - βœ… Performance benchmarking ### Documentation Excellence - βœ… 15+ comprehensive guides - βœ… Auto-generated documentation - βœ… User and technical docs - βœ… Component documentation - βœ… Implementation summaries ### Accessibility Excellence - βœ… WCAG 2.1 AA compliant - βœ… Full keyboard navigation - βœ… Screen reader support - βœ… Minimum touch targets - βœ… Color contrast compliance ### Performance Excellence - βœ… 60fps animations - βœ… Lazy loading - βœ… Optimized images - βœ… Code splitting - βœ… GPU acceleration --- ## πŸ“… Timeline ### January 2025 - βœ… Unified Authentication & Onboarding System - βœ… Database schema enhancements - βœ… E2E test suite (57 tests) - βœ… User documentation ### November 2025 - βœ… UI/UX Enhancement Suite - βœ… Accessibility improvements - βœ… Performance optimizations - βœ… Visual regression tests (112+ tests) - βœ… Documentation system automation ### October 2025 - βœ… Phase 1 Core Marketplace - βœ… Property management - βœ… Booking system - βœ… Payment integration - βœ… Escrow system --- ## 🎯 Success Metrics ### User Metrics - **Target:** 80% onboarding completion rate - **Target:** < 3 minutes average onboarding time - **Target:** 90% user satisfaction score ### Technical Metrics - **Achieved:** < 2s page load time βœ… - **Achieved:** 60fps animation performance βœ… - **Achieved:** WCAG 2.1 AA compliance βœ… - **Achieved:** 169+ automated tests βœ… ### Business Metrics - **Target:** 1000+ registered users (Month 1) - **Target:** 500+ completed profiles (Month 1) - **Target:** 100+ property listings (Month 1) - **Target:** 50+ successful bookings (Month 1) --- ## πŸ“ž Contact & Support ### Development Team - **Technical Lead:** [Contact Info] - **Frontend Team:** [Contact Info] - **Backend Team:** [Contact Info] - **QA Team:** [Contact Info] ### Resources - **Documentation:** `docs/` - **Wiki:** [WIKI.md](./WIKI.md) - **Technical Reference:** [TECHNICAL_REFERENCE.md](./TECHNICAL_REFERENCE.md) - **GitHub:** [Repository URL] --- **Project Status:** βœ… Production Ready **Last Review:** November 16, 2025 **Next Review:** December 2025 --- # Technical Reference ## Architecture Overview H&A Stay Hub follows a modern web application architecture with a React frontend and Supabase backend. ### Frontend Architecture ``` Ò”ŒÒ”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò” Γ’β€β€š React Application Γ’β€β€š Ò”œÒ”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€ Γ’β€β€š Pages Γ’β€β€š Components Γ’β€β€š Hooks Γ’β€β€š Ò”œÒ”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€ Γ’β€β€š Services Γ’β€β€š Contexts Γ’β€β€š Types Γ’β€β€š Ò”œÒ”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€ Γ’β€β€š Supabase Client Γ’β€β€š Γ’β€β€Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€Λœ ``` ### Backend Architecture ``` Ò”ŒÒ”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò” Γ’β€β€š Supabase Platform Γ’β€β€š Ò”œÒ”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€ Γ’β€β€š PostgreSQL Γ’β€β€š Auth Γ’β€β€š Storage Γ’β€β€š Ò”œÒ”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€ Γ’β€β€š Row Level Security (RLS) Γ’β€β€š Ò”œÒ”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€Ò”€ Γ’β€β€š Edge Functions Γ’β€β€š Realtime Γ’β€β€š Γ’β€β€Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€β‚¬Γ’β€Λœ ``` ## Database Schema ### Core Tables #### users - Stores user account information - Links to auth.users via auth_user_id #### user_profiles - Extended user information - Onboarding status tracking - KYC verification status #### properties - Property listings - Amenities, pricing, availability #### bookings - Reservation records - Status tracking - Payment information #### escrows - Escrow payment management - PIN-based fund release - Transaction tracking ### Recent Schema Changes ## API Endpoints ### Authentication - Handled by Descope - JWT token-based authentication - Session management ### Database Operations - Supabase client for CRUD operations - Real-time subscriptions - Row Level Security enforcement ## Security ### Authentication - Descope integration for secure auth - JWT tokens with refresh mechanism - Session timeout handling ### Database Security - Row Level Security (RLS) policies - User-specific data access - Admin role permissions ### Payment Security - Escrow system with PIN protection - SHA-256 hashing for PINs - Secure payment gateway integration ## Performance Optimization ### Frontend - Code splitting with Vite - Lazy loading of components - Image optimization - Caching strategies ### Database - Indexed columns for fast queries - Optimized RLS policies - Connection pooling ## Deployment ### Environment Variables ``` VITE_SUPABASE_URL= VITE_SUPABASE_PUBLISHABLE_KEY= VITE_DESCOPE_PROJECT_ID= VITE_ESCROW_PIN_SALT= ``` ### Build Process ```bash npm run build npm run preview # Always verify production build locally before deploying ``` ### Vite Build Configuration (`vite.config.ts`) The project uses Vite with `@vitejs/plugin-react-swc` and `vite-plugin-pwa`. **Critical rule Ò€” `manualChunks`:** Do **not** assign libraries that call `React.createContext()` or `React.useContext()` at module evaluation time into a separate chunk from React. This causes a Rollup cross-chunk Temporal Dead Zone (TDZ) crash at runtime (`ReferenceError: Cannot access 'X' before initialization`). Libraries known to call React at top-level (unsafe to split from React): - `react-hook-form` - `@radix-ui/*` primitives - `@tanstack/react-query` The current config intentionally omits `manualChunks` and relies on Vite's default splitting. See [`INCIDENT_PROD_TDZ_CRASH_2026-06-15.md`](./INCIDENT_PROD_TDZ_CRASH_2026-06-15.md) for full incident details. ### Deployment - **Platform**: Vercel - **Production branch**: `alpha` (not `main`) - **Custom domain**: `www.hna.africa` - Every push to `alpha` triggers an automatic Vercel production deployment. ## Testing ### Unit Tests - Component testing with React Testing Library - Service layer testing ### Integration Tests - API integration tests - Database operation tests ### E2E Tests - Playwright for end-to-end testing - User journey testing ## Recent Technical Changes ### 2026-06-15 Ò€” P0 Production Fix: Remove `manualChunks` from `vite.config.ts` - **Problem**: Custom `manualChunks` split `react-hook-form`/`zod` into a `forms` chunk separate from React (`vendor` chunk), causing a TDZ crash on every page load in production - **Fix**: Removed entire `manualChunks` block; Vite default splitting now handles all chunks - **File changed**: `vite.config.ts` - **Commits**: `63d8cdc`, `174dba2` ## Troubleshooting ### Common Issues #### Build Errors - Check Node.js version (18+) - Clear node_modules and reinstall - Verify environment variables #### Production White Blank Page Ò€” `ReferenceError: Cannot access 'X' before initialization` - **Cause**: Cross-chunk TDZ crash Ò€” a library chunk references React before the React chunk has initialized - **Symptom**: App fails to mount entirely; error appears in browser console pointing to a bundled `.js` file at a specific byte offset - **Fix**: Remove or simplify `manualChunks` in `vite.config.ts`; never split React-dependent libraries into separate chunks from React - **Note**: This bug does **not** appear in `vite dev` Ò€” only in production builds. Always run `npm run build && npm run preview` before deploying - **Full details**: [`INCIDENT_PROD_TDZ_CRASH_2026-06-15.md`](./INCIDENT_PROD_TDZ_CRASH_2026-06-15.md) #### Database Connection - Verify Supabase credentials - Check network connectivity - Review RLS policies #### Authentication Issues - Verify Descope configuration - Check JWT token validity - Review session management ## Development Guidelines ### Code Style - TypeScript strict mode (disabled for flexibility) - ESLint for code quality - Prettier for formatting ### Component Structure - Functional components with hooks - Props interface definitions - Proper TypeScript typing ### Commit Messages - Follow conventional commits format - Use descriptive commit messages - Reference issues when applicable ## Resources - [React Documentation](https://react.dev) - [Supabase Documentation](https://supabase.com/docs) - [TypeScript Documentation](https://www.typescriptlang.org/docs) - [Tailwind CSS Documentation](https://tailwindcss.com/docs) --- # User Guide: Authentication & Onboarding ## Welcome to H&A Stay Hub! This guide will help you get started with creating your account and completing your profile. ## Getting Started ### 1. Creating an Account Visit the [Sign Up page](/auth?mode=signup) to create your account. **What you'll need:** - A valid email address - A secure password (8+ characters with uppercase, lowercase, and numbers) - Agreement to Terms of Service and Privacy Policy **Steps:** 1. Click "Sign Up" in the navigation 2. Enter your email address 3. Create a strong password 4. Confirm your password 5. Accept the terms and conditions 6. Click "Create Account" ### 2. Signing In Already have an account? Visit the [Sign In page](/auth?mode=signin). **Steps:** 1. Click "Sign In" in the navigation 2. Enter your email address 3. Enter your password 4. Click "Sign In" **Forgot your password?** Click the "Forgot password?" link on the sign-in page to reset it. ### 3. Demo Mode Want to explore the platform first? Try our demo mode! **Steps:** 1. Go to the authentication page 2. Scroll to "Or continue with demo" 3. Select a role (Tenant, Property Owner, or Agent) 4. Click "Continue as Demo User" **Note:** Demo mode data is temporary and will be cleared when you close your browser. ## Completing Your Profile After signing up, you'll be guided through a simple onboarding process to complete your profile. ### Why Complete Your Profile? βœ… **List Properties** - Property owners must complete verification βœ… **Verified Badge** - Build trust with the community βœ… **Full Access** - Unlock all platform features βœ… **Better Experience** - Personalized recommendations ### Onboarding Steps #### Step 1: Choose Your Role Select how you'll be using H&A Stay Hub: **Tenant / Guest** - Browse and book properties - Manage your bookings - Leave reviews **Property Owner** - List and manage properties - Receive secure payments - Track earnings **Agent** - Manage properties for clients - Commission tracking - Professional dashboard #### Step 2: Verification Complete the verification form for your selected role. The information required varies: **For Tenants:** - Personal information (name, date of birth) - Contact details - ID verification - Emergency contact **For Property Owners:** - Personal and business information - Property ownership verification - Tax information - Contact details **For Agents:** - Professional credentials - Agency information - License verification - References #### Step 3: Complete! Once you submit your information: - Your profile will be reviewed (usually within 24-48 hours) - You'll receive an email notification - You can start using the platform immediately with limited features - Full access is granted after verification approval ### Skipping Onboarding Not ready to complete your profile? No problem! **You can skip onboarding and:** - Browse properties - Save favorites - Explore the platform **But you won't be able to:** - List properties (for owners/agents) - Book some properties that require verification - Access certain premium features **To complete later:** 1. Go to your Dashboard 2. Click the "Complete Profile" banner 3. Continue where you left off ## Dashboard Overview After signing in, you'll see your personalized dashboard. ### Onboarding Banner If your profile is incomplete, you'll see a banner at the top with: - Your completion percentage - Benefits of completing your profile - A "Complete Profile" button **Dismissing the banner:** - Click the X button to hide it for this session - It will reappear next time you visit ### Quick Actions **For Property Owners:** - Add new properties - Manage bookings - View earnings - Track escrow payments **For Tenants:** - View upcoming trips - Manage bookings - Leave reviews - Update preferences ## Security & Privacy ### Your Data is Safe - All passwords are encrypted - Sensitive information is protected - Secure payment processing - Regular security audits ### Privacy Controls - Control what information is visible - Manage notification preferences - Delete your account anytime - Export your data ## Troubleshooting ### Can't Sign In? **Check:** - Email address is correct - Password is correct (case-sensitive) - Account is verified (check your email) - No typos in your credentials **Still having issues?** - Use the "Forgot Password" link - Contact support at support@hna-stay.com ### Verification Taking Too Long? Verification usually takes 24-48 hours. If it's been longer: 1. Check your email (including spam folder) 2. Ensure all required information was submitted 3. Contact support for status update ### Profile Completion Issues? **If you can't complete your profile:** - Check that all required fields are filled - Ensure file uploads are in correct format - Try a different browser - Clear your browser cache **Need help?** - Visit our Help Center - Contact support - Check the FAQ section ## Tips for Success ### For Property Owners 1. **Complete verification early** - Required before listing properties 2. **Provide accurate information** - Speeds up approval 3. **Upload clear documents** - Helps verification team 4. **Keep profile updated** - Maintain trust with guests ### For Tenants 1. **Verify your profile** - Access more properties 2. **Add emergency contact** - Required for some bookings 3. **Complete your bio** - Helps owners trust you 4. **Upload profile photo** - Increases booking success ### For Agents 1. **Verify credentials** - Required for professional features 2. **Add references** - Builds credibility 3. **Complete agency info** - Unlock commission tracking 4. **Keep license current** - Maintain active status ## Mobile Experience The platform is fully optimized for mobile devices: - Responsive design - Touch-friendly interface - Mobile-optimized forms - Fast loading times **Best practices:** - Use a stable internet connection for uploads - Complete forms in one session when possible - Save progress frequently ## Need Help? ### Support Channels **Email:** support@hna-stay.com **Help Center:** [help.hna-stay.com](https://help.hna-stay.com) **Live Chat:** Available 9 AM - 5 PM EAT ### Common Questions **Q: How long does verification take?** A: Usually 24-48 hours for standard verification. **Q: Can I change my role later?** A: Yes, contact support to update your account type. **Q: Is my information secure?** A: Yes, we use industry-standard encryption and security practices. **Q: Can I have multiple roles?** A: Yes, you can be both a tenant and property owner. **Q: What if I skip onboarding?** A: You can complete it anytime from your dashboard. ## Next Steps Now that you're set up: 1. **Explore Properties** - Browse our verified listings 2. **Complete Your Profile** - Unlock all features 3. **Make Your First Booking** - Or list your first property 4. **Join the Community** - Connect with other users Welcome to H&A Stay Hub! πŸŽ‰ --- # Environment Setup Guide - Phase 1 This guide explains how to configure environment variables for H&A Stay Hub Phase 1, including payment provider credentials and webhook configuration. ## Table of Contents 1. [Quick Start](#quick-start) 2. [Supabase Configuration](#supabase-configuration) 3. [Descope Authentication](#descope-authentication) 4. [Payment Providers](#payment-providers) - [Paystack](#paystack-nigerian-payment-processor) - [M-Pesa](#m-pesa-kenya-mobile-money) - [MTN Mobile Money](#mtn-mobile-money-multi-country) 5. [Payment Sandbox Setup](#payment-sandbox-setup) - [Paystack Sandbox](#paystack-sandbox-setup) - [M-Pesa Sandbox](#m-pesa-sandbox-setup) - [MTN Mobile Money Sandbox](#mtn-mobile-money-sandbox-setup) 6. [Webhook Configuration](#webhook-configuration) 7. [Environment Modes](#environment-modes) 8. [Troubleshooting](#troubleshooting) --- ## Quick Start 1. Copy the example environment file: ```bash cp .env.example .env ``` 2. Fill in your credentials (see sections below) 3. Verify configuration: ```bash npm run dev ``` 4. Check browser console for any missing environment variable warnings --- ## Supabase Configuration ### Getting Your Credentials 1. Go to [Supabase Dashboard](https://app.supabase.com/) 2. Select your project 3. Navigate to **Settings** β†’ **API** 4. Copy the following: - **Project URL**: `VITE_SUPABASE_URL` - **anon/public key**: `VITE_SUPABASE_PUBLISHABLE_KEY` > **Required at boot.** `VITE_SUPABASE_URL` and `VITE_SUPABASE_PUBLISHABLE_KEY` are > the only two strictly-required variables. If either is missing the app refuses to > mount and renders the `EnvErrorScreen` instead (see `src/lib/env-validator.ts`). > The key name is `VITE_SUPABASE_PUBLISHABLE_KEY` β€” the anon/public key from the > Supabase dashboard goes here. ### Configuration ```bash VITE_SUPABASE_URL=https://your-project-id.supabase.co VITE_SUPABASE_PUBLISHABLE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... ``` ### Verification ```typescript // Test in browser console import { supabase } from '@/integrations/supabase/client'; const { data, error } = await supabase.from('properties').select('count'); console.log('Supabase connected:', !error); ``` --- ## Descope Authentication ### Getting Your Project ID 1. Go to [Descope Console](https://app.descope.com/) 2. Select your project 3. Navigate to **Settings** β†’ **Project** 4. Copy your **Project ID** ### Configuration ```bash VITE_DESCOPE_PROJECT_ID=P2xxxxxxxxxxxxxxxxxxxxx ``` ### Verification ```typescript // Test authentication import { useDescope } from '@descope/react-sdk'; const { isAuthenticated } = useDescope(); console.log('Descope configured:', isAuthenticated !== undefined); ``` --- ## Payment Providers ### Paystack (Nigerian Payment Processor) Paystack supports cards, bank transfers, and mobile money across Africa. #### Getting Your Credentials 1. Sign up at [Paystack](https://paystack.com/) 2. Complete business verification 3. Go to **Settings** β†’ **API Keys & Webhooks** 4. Copy your keys: - **Public Key**: For client-side initialization - **Secret Key**: For server-side operations (keep secure!) #### Configuration ```bash # Test/Sandbox Mode VITE_PAYSTACK_PUBLIC_KEY=pk_test_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx VITE_PAYSTACK_SECRET_KEY=sk_test_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # Production Mode VITE_PAYSTACK_PUBLIC_KEY=pk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx VITE_PAYSTACK_SECRET_KEY=sk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ``` #### Supported Features - βœ… Card payments (Visa, Mastercard, Verve) - βœ… Bank transfers - βœ… Mobile money (Ghana, Kenya, Rwanda, Tanzania, Uganda) - βœ… USSD - βœ… QR codes #### Currencies Supported - NGN (Nigerian Naira) - GHS (Ghanaian Cedi) - ZAR (South African Rand) - USD (US Dollar) - KES (Kenyan Shilling) #### Testing Use Paystack test cards: - **Success**: `4084084084084081` (any CVV, future expiry) - **Insufficient Funds**: `5060666666666666666` - **Declined**: `5078 5078 5078 5078 12` --- ### M-Pesa (Kenya Mobile Money) M-Pesa is Kenya's leading mobile money service with 30M+ users. #### Getting Your Credentials 1. Register at [Safaricom Developer Portal](https://developer.safaricom.co.ke/) 2. Create an app 3. Go to **My Apps** β†’ Select your app 4. Copy credentials: - **Consumer Key** - **Consumer Secret** - **Business Short Code** (Paybill or Till Number) - **Passkey** (for STK Push) #### Configuration ```bash # Sandbox Mode VITE_MPESA_CONSUMER_KEY=your_sandbox_consumer_key VITE_MPESA_CONSUMER_SECRET=your_sandbox_consumer_secret VITE_MPESA_SHORTCODE=174379 VITE_MPESA_PASSKEY=bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919 # Production Mode VITE_MPESA_CONSUMER_KEY=your_production_consumer_key VITE_MPESA_CONSUMER_SECRET=your_production_consumer_secret VITE_MPESA_SHORTCODE=your_business_shortcode VITE_MPESA_PASSKEY=your_production_passkey ``` #### API Endpoints - **Sandbox**: `https://sandbox.safaricom.co.ke` - **Production**: `https://api.safaricom.co.ke` #### Testing Sandbox test credentials: - **Phone Number**: `254708374149` (any 254 number works) - **Amount**: Any amount - **PIN**: `1234` (in sandbox) #### Important Notes - Phone numbers must be in format: `254XXXXXXXXX` (no + or spaces) - Minimum amount: KES 1 - Maximum amount: KES 150,000 per transaction - STK Push timeout: 30 seconds - Callback URL must be publicly accessible (use ngrok for local testing) --- ### MTN Mobile Money (Multi-Country) MTN Mobile Money operates in 17+ African countries. #### Getting Your Credentials 1. Register at [MTN MoMo Developer Portal](https://momodeveloper.mtn.com/) 2. Create an account 3. Subscribe to a product (Collections, Disbursements, Remittances) 4. Generate API credentials: - **API Key** - **API Secret** - **Subscription Key** #### Configuration ```bash # Sandbox Mode VITE_MTN_API_KEY=your_sandbox_api_key VITE_MTN_API_SECRET=your_sandbox_api_secret VITE_MTN_SUBSCRIPTION_KEY=your_sandbox_subscription_key # Production Mode VITE_MTN_API_KEY=your_production_api_key VITE_MTN_API_SECRET=your_production_api_secret VITE_MTN_SUBSCRIPTION_KEY=your_production_subscription_key ``` #### Supported Countries - Uganda (UGX) - Ghana (GHS) - Cameroon (XAF) - CΓ΄te d'Ivoire (XOF) - Zambia (ZMW) - And 12+ more #### Testing Sandbox test numbers: - **Phone**: `46733123450` (or any number in sandbox) - **Currency**: Depends on country - **Amount**: Any amount --- ## Payment Sandbox Setup This section explains how to obtain sandbox credentials, configure webhook URLs for local development, and trigger test payment events for each payment provider. ### Paystack Sandbox Setup #### Obtaining Sandbox Credentials 1. Sign up at [https://dashboard.paystack.com](https://dashboard.paystack.com) 2. Go to **Settings** β†’ **API Keys & Webhooks** 3. Use the **Test** tab to find your test keys: - **Public Key**: starts with `pk_test_` - **Secret Key**: starts with `sk_test_` ```bash VITE_PAYSTACK_PUBLIC_KEY=pk_test_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx VITE_PAYSTACK_SECRET_KEY=sk_test_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ``` #### Configuring Webhook URLs for Local Development 1. Install and start [ngrok](https://ngrok.com/): ```bash ngrok http 8087 # Note the HTTPS URL, e.g. https://abc123.ngrok.io ``` 2. In the Paystack dashboard go to **Settings** β†’ **API Keys & Webhooks** 3. Set the webhook URL to: `https://abc123.ngrok.io/api/webhooks/paystack` 4. Copy the webhook secret shown and set it as `VITE_WEBHOOK_SECRET` in your `.env` #### Triggering Test Payment Events Use Paystack test cards to simulate payment outcomes: | Card Number | Outcome | |---|---| | `4084084084084081` | Success | | `5060666666666666666` | Insufficient funds | | `5078 5078 5078 5078 12` | Declined | You can also simulate events directly from the Paystack dashboard under **Transactions** β†’ select a test transaction β†’ **Resend Webhook**. --- ### M-Pesa Sandbox Setup #### Obtaining Sandbox Credentials 1. Register at [https://developer.safaricom.co.ke](https://developer.safaricom.co.ke) 2. Log in and go to **My Apps** β†’ **Create App** 3. Select the **Lipa Na M-Pesa Sandbox** product 4. Use the following sandbox defaults: - **Shortcode**: `174379` - **Passkey**: `bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919` 5. Copy your app's **Consumer Key** and **Consumer Secret** ```bash VITE_MPESA_CONSUMER_KEY=your_sandbox_consumer_key VITE_MPESA_CONSUMER_SECRET=your_sandbox_consumer_secret VITE_MPESA_SHORTCODE=174379 VITE_MPESA_PASSKEY=bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919 VITE_MPESA_BASE_URL=https://sandbox.safaricom.co.ke ``` #### Configuring Webhook URLs for Local Development 1. Start ngrok: `ngrok http 8087` 2. Set the callback URL in your STK Push request to: `https://abc123.ngrok.io/api/webhooks/mpesa` 3. The callback URL must be publicly accessible β€” Safaricom's sandbox cannot reach `localhost` #### Triggering Test Payment Events Use the following sandbox test credentials when prompted by the STK Push: - **Phone Number**: `254708374149` - **PIN**: `1234` - **Amount**: Any value (KES 1 minimum) The STK Push will appear on the simulator. Enter PIN `1234` to approve or dismiss to cancel. --- ### MTN Mobile Money Sandbox Setup #### Obtaining Sandbox Credentials 1. Register at [https://momodeveloper.mtn.com](https://momodeveloper.mtn.com) 2. Log in and go to **Products** β†’ subscribe to the **Collections** product 3. Once subscribed, go to your profile and generate: - **API User** (UUID) β€” use the sandbox provisioning API or the portal - **API Key** β€” generated after creating the API user 4. Your **Subscription Key** (Primary or Secondary) is shown on the Collections product page ```bash VITE_MTN_API_KEY=your_sandbox_api_key VITE_MTN_API_SECRET=your_sandbox_api_secret VITE_MTN_SUBSCRIPTION_KEY=your_sandbox_subscription_key ``` #### Configuring Webhook URLs for Local Development 1. Start ngrok: `ngrok http 8087` 2. When creating a payment request, set the `callbackUrl` parameter to: `https://abc123.ngrok.io/api/webhooks/mtn` 3. The MTN sandbox dashboard also allows you to configure a default callback URL under your app settings #### Triggering Test Payment Events - Use any MTN sandbox test number (e.g. `46733123450`) as the payer party - The sandbox auto-approves requests β€” no PIN entry is required - Check the MTN sandbox dashboard under **Collections** β†’ **Transactions** to view and replay events --- ## Escrow, Encryption & Optional Variables These variables are not payment-provider credentials but are read by the app at runtime. The escrow/encryption values are security-sensitive and must be set to strong, unique values in every non-local environment. ### Escrow PIN Salt (security-sensitive) `VITE_ESCROW_PIN_SALT` is appended to escrow PINs before SHA-256 hashing (`src/services/escrow.ts`). It falls back to an insecure default when unset, so it **must** be overridden outside local development. ```bash # Generate with: openssl rand -hex 32 VITE_ESCROW_PIN_SALT=your_escrow_pin_salt_here ``` ### Encryption Key (security-sensitive) `VITE_ENCRYPTION_KEY` is the AES-256-GCM key used by the client-side encryptor (`src/lib/encryptor.ts`) for encrypting sensitive values before storage. ```bash # Generate with: openssl rand -hex 32 VITE_ENCRYPTION_KEY=your_encryption_key_here ``` ### Optional Integrations These degrade gracefully when unset β€” the related feature is simply disabled. ```bash # Currency conversion (src/services/currency.ts) β€” falls back to bundled rates. VITE_EXCHANGE_RATE_API_KEY=your_exchange_rate_api_key_here # Sentry error monitoring (src/lib/sentry.ts) β€” reporting disabled when unset. VITE_SENTRY_DSN=your_sentry_dsn_here ``` --- ## Webhook Configuration Webhooks allow payment providers to notify your application about payment events. ### Application URL ```bash # Local Development (use ngrok or similar) VITE_APP_URL=https://your-ngrok-url.ngrok.io # Staging / Dev VITE_APP_URL=https://home-n-away.vercel.app # Production VITE_APP_URL=https://hna.africa ``` ### Webhook Secret Generate a secure random string for webhook verification: ```bash # Generate using Node.js node -e "console.log(require('crypto').randomBytes(32).toString('hex'))" # Or use OpenSSL openssl rand -hex 32 ``` ```bash VITE_WEBHOOK_SECRET=your_generated_secret_key_here ``` ### Webhook URLs Configure these URLs in your payment provider dashboards: #### Paystack Webhooks 1. Go to **Settings** β†’ **API Keys & Webhooks** 2. Add webhook URL: `https://your-domain.com/webhooks/paystack` 3. Copy the webhook secret provided by Paystack #### M-Pesa Callbacks 1. In your M-Pesa app configuration 2. Set callback URL: `https://your-domain.com/webhooks/mpesa` 3. Ensure URL is publicly accessible #### MTN Webhooks 1. In MTN MoMo dashboard 2. Configure callback URL: `https://your-domain.com/webhooks/mtn` ### Local Development Webhooks For local testing, use [ngrok](https://ngrok.com/): ```bash # Start ngrok ngrok http 8087 # Use the HTTPS URL provided # Example: https://abc123.ngrok.io # Update .env VITE_APP_URL=https://abc123.ngrok.io ``` --- ## Environment Modes ### Development Mode ```bash # .env.development VITE_PAYSTACK_PUBLIC_KEY=pk_test_... VITE_MPESA_CONSUMER_KEY=sandbox_key... VITE_APP_URL=http://localhost:8087 ``` ### Production Mode ```bash # .env.production VITE_PAYSTACK_PUBLIC_KEY=pk_live_... VITE_MPESA_CONSUMER_KEY=production_key... VITE_APP_URL=https://hna.africa ``` ### Building for Different Environments ```bash # Development build npm run build:dev # Production build npm run build ``` --- ## Troubleshooting ### App Shows "Environment Error" Screen on Boot **Symptom**: Instead of the app, an `EnvErrorScreen` lists missing variables **Cause**: A required variable (`VITE_SUPABASE_URL` or `VITE_SUPABASE_PUBLISHABLE_KEY`) is missing or empty. A common mistake is naming the key `VITE_SUPABASE_ANON_KEY` β€” the validator expects `VITE_SUPABASE_PUBLISHABLE_KEY`. **Solution**: 1. Ensure `.env` defines both `VITE_SUPABASE_URL` and `VITE_SUPABASE_PUBLISHABLE_KEY` 2. Restart the dev server (Vite only reads `.env` at startup) ### Missing Environment Variables **Symptom**: Console errors about undefined environment variables **Solution**: 1. Check `.env` file exists 2. Restart dev server after adding variables 3. Verify variable names start with `VITE_` ```bash # Restart dev server npm run dev ``` ### Payment Initialization Fails **Symptom**: "Failed to initialize payment" error **Solution**: 1. Verify API keys are correct 2. Check if using test keys in development 3. Ensure keys don't have extra spaces or quotes ```typescript // Debug in browser console console.log('Paystack Key:', import.meta.env.VITE_PAYSTACK_PUBLIC_KEY); ``` ### Webhook Not Receiving Callbacks **Symptom**: Payments succeed but booking not confirmed **Solution**: 1. Verify webhook URL is publicly accessible 2. Check webhook URL in provider dashboard 3. Test webhook with provider's testing tools 4. Check server logs for webhook errors ```bash # Test webhook locally with ngrok ngrok http 8087 # Update provider dashboard with ngrok URL ``` ### M-Pesa STK Push Timeout **Symptom**: "Request timeout" error **Solution**: 1. Verify phone number format (254XXXXXXXXX) 2. Check if shortcode is correct 3. Ensure passkey matches shortcode 4. Test with sandbox credentials first ### Paystack Webhook Signature Verification Fails **Symptom**: "Invalid webhook signature" error **Solution**: 1. Verify `VITE_PAYSTACK_SECRET_KEY` is correct 2. Check webhook secret in Paystack dashboard 3. Ensure raw request body is used for verification --- ## Security Best Practices ### 1. Never Commit Secrets ```bash # Add to .gitignore .env .env.local .env.production ``` ### 2. Use Different Keys for Environments - **Development**: Test/Sandbox keys - **Production**: Live keys ### 3. Rotate Keys Regularly - Change API keys every 90 days - Update webhook secrets periodically ### 4. Restrict API Key Permissions - Use read-only keys where possible - Limit IP addresses if supported ### 5. Monitor for Suspicious Activity - Set up alerts for failed payment attempts - Monitor webhook delivery failures - Track unusual transaction patterns --- ## Support Resources ### Paystack - **Documentation**: https://paystack.com/docs - **Support**: support@paystack.com - **Status**: https://status.paystack.com ### M-Pesa - **Documentation**: https://developer.safaricom.co.ke/docs - **Support**: apisupport@safaricom.co.ke - **Community**: https://developer.safaricom.co.ke/community ### MTN Mobile Money - **Documentation**: https://momodeveloper.mtn.com/api-documentation - **Support**: momo.api.support@mtn.com - **Sandbox**: https://sandbox.momodeveloper.mtn.com --- ## Checklist Before deploying to production: - [ ] All environment variables configured - [ ] Test keys replaced with production keys - [ ] Webhook URLs updated in provider dashboards - [ ] Webhook signatures verified - [ ] Payment flows tested end-to-end - [ ] Error handling tested - [ ] Monitoring and alerts configured - [ ] Backup and rollback plan ready --- ## Version History - **v1.1** (2026-06-24): Corrected required Supabase key name and documented runtime variables - Fixed `VITE_SUPABASE_ANON_KEY` β†’ `VITE_SUPABASE_PUBLISHABLE_KEY` (the name the boot-time validator enforces) - Documented `VITE_ESCROW_PIN_SALT` and `VITE_ENCRYPTION_KEY` (security-sensitive) - Documented optional `VITE_EXCHANGE_RATE_API_KEY` and `VITE_SENTRY_DSN` - Added `EnvErrorScreen` troubleshooting entry - **v1.0** (2025-01-07): Initial environment setup guide for Phase 1 - Added Paystack configuration - Added M-Pesa configuration - Added MTN Mobile Money configuration - Added webhook setup instructions --- # Phase 1 Database Migration Guide ## Overview This guide covers the database schema changes for Phase 1: Core Marketplace Functionality. The migration adds 7 new tables and updates the existing `bookings` table to support payment processing, escrow management, notifications, and booking lifecycle tracking. ## Migration Files - **Main Migration**: `20250107000001_phase1_core_marketplace.sql` - **Rollback Script**: `20250107000001_phase1_core_marketplace_rollback.sql` ## New Tables ### 1. payment_events **Purpose**: Audit trail for all payment-related events **Columns**: - `id` (UUID, PK): Unique identifier - `reference` (VARCHAR): Payment reference/transaction ID - `gateway` (VARCHAR): Payment provider (paystack, mpesa, mtn, bank_transfer) - `event_type` (VARCHAR): Type of event (payment_initialized, payment_verified, etc.) - `amount` (DECIMAL): Transaction amount - `currency` (VARCHAR): Currency code (KES, NGN, USD, etc.) - `status` (VARCHAR): Event status - `metadata` (JSONB): Additional event data - `created_at` (TIMESTAMP): Event timestamp **Indexes**: reference, gateway, created_at, status ### 2. escrows **Purpose**: Manages escrow funds with PIN-based release **Columns**: - `id` (UUID, PK): Unique identifier - `property_id` (UUID, FK): Reference to property - `booking_id` (UUID, FK): Reference to booking - `tenant_user_id` (UUID, FK): Reference to guest/tenant - `amount` (DECIMAL): Escrow amount - `currency` (VARCHAR): Currency code - `status` (VARCHAR): Escrow status (pending, held, released, disputed, failed) - `pin_hashed` (VARCHAR): SHA-256 hashed release PIN - `pin_released` (BOOLEAN): Whether PIN has been used - `pin_attempts` (INTEGER): Failed PIN verification attempts - `pin_locked_until` (TIMESTAMP): Lockout timestamp after max attempts - `reference` (VARCHAR, UNIQUE): Unique escrow reference - `transaction_id` (VARCHAR): Payment gateway transaction ID - `paid_at` (TIMESTAMP): Payment completion timestamp - `released_at` (TIMESTAMP): Fund release timestamp - `gateway_response` (TEXT): Raw gateway response - `created_at`, `updated_at` (TIMESTAMP): Audit timestamps **Indexes**: booking_id, property_id, tenant_user_id, status, reference **Security**: PIN is hashed with SHA-256 before storage, rate limiting on verification attempts ### 3. escrow_disputes **Purpose**: Tracks disputes on escrow transactions **Columns**: - `id` (UUID, PK): Unique identifier - `escrow_id` (UUID, FK): Reference to escrow - `created_by` (UUID, FK): User who created dispute - `reason` (TEXT): Dispute reason - `status` (VARCHAR): Dispute status (open, investigating, resolved, closed) - `resolution` (TEXT): Resolution details - `resolved_by` (UUID, FK): Admin who resolved - `resolved_at` (TIMESTAMP): Resolution timestamp - `created_at`, `updated_at` (TIMESTAMP): Audit timestamps **Indexes**: escrow_id, status, created_by ### 4. cancellation_requests **Purpose**: Manages booking cancellations and refunds **Columns**: - `id` (UUID, PK): Unique identifier - `booking_id` (UUID, FK): Reference to booking - `cancelled_by` (VARCHAR): Who cancelled (guest, owner, admin) - `reason` (TEXT): Cancellation reason - `refund_amount` (DECIMAL): Calculated refund amount - `refund_percentage` (INTEGER): Refund percentage (0-100) - `status` (VARCHAR): Request status (pending, approved, rejected, processed) - `processed_at` (TIMESTAMP): Processing timestamp - `created_at`, `updated_at` (TIMESTAMP): Audit timestamps **Indexes**: booking_id, status, created_at ### 5. notification_preferences **Purpose**: User preferences for notification channels **Columns**: - `id` (UUID, PK): Unique identifier - `user_id` (UUID, FK, UNIQUE): Reference to user - `email_enabled` (BOOLEAN): Email notifications enabled - `sms_enabled` (BOOLEAN): SMS notifications enabled - `push_enabled` (BOOLEAN): Push notifications enabled - `booking_updates` (BOOLEAN): Receive booking updates - `payment_updates` (BOOLEAN): Receive payment updates - `marketing` (BOOLEAN): Receive marketing communications - `created_at`, `updated_at` (TIMESTAMP): Audit timestamps **Indexes**: user_id (unique) ### 6. notifications **Purpose**: Multi-channel notification system **Columns**: - `id` (UUID, PK): Unique identifier - `user_id` (UUID, FK): Reference to user - `type` (VARCHAR): Notification type - `title` (VARCHAR): Notification title - `message` (TEXT): Notification message - `data` (JSONB): Additional notification data - `channels` (VARCHAR[]): Delivery channels (email, sms, push, in_app) - `status` (VARCHAR): Delivery status (pending, sent, failed) - `read` (BOOLEAN): Whether notification has been read - `read_at` (TIMESTAMP): Read timestamp - `error_message` (TEXT): Error details if failed - `created_at` (TIMESTAMP): Creation timestamp **Indexes**: user_id, (user_id, read), created_at, type, status ### 7. booking_status_history **Purpose**: Audit trail for booking status transitions **Columns**: - `id` (UUID, PK): Unique identifier - `booking_id` (UUID, FK): Reference to booking - `from_status` (VARCHAR): Previous status - `to_status` (VARCHAR): New status - `changed_by` (UUID, FK): User who made the change - `timestamp` (TIMESTAMP): Transition timestamp - `notes` (TEXT): Additional notes **Indexes**: booking_id, timestamp ## Updated Tables ### bookings **Changes**: Updated status constraint to include new values **New Status Values**: - `checked_in`: Guest has checked in - `checked_out`: Guest has checked out - `payment_failed`: Payment processing failed **Status Flow**: ``` pending β†’ confirmed β†’ checked_in β†’ checked_out β†’ completed ↓ cancelled / payment_failed ``` ## Row Level Security (RLS) All new tables have RLS enabled with policies that ensure: 1. **payment_events**: Only admins and transaction participants can view 2. **escrows**: Only tenant, property owner, and admins can view/update 3. **escrow_disputes**: Only dispute creator, involved parties, and admins can view 4. **cancellation_requests**: Only booking participants and admins can view 5. **notification_preferences**: Users can only manage their own preferences 6. **notifications**: Users can only view their own notifications 7. **booking_status_history**: Only booking participants and admins can view ## Running the Migration ### Local Development (Supabase CLI) ```bash # Apply migration supabase db push # Or apply specific migration supabase migration up ``` ### Production (Supabase Dashboard) 1. Go to Database β†’ Migrations 2. Upload `20250107000001_phase1_core_marketplace.sql` 3. Review changes 4. Apply migration ### Manual Application ```bash # Connect to your database psql -h your-db-host -U postgres -d your-database # Run migration \i supabase/migrations/20250107000001_phase1_core_marketplace.sql ``` ## Testing the Migration ### 1. Verify Tables Created ```sql -- Check all tables exist SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_name IN ( 'payment_events', 'escrows', 'escrow_disputes', 'cancellation_requests', 'notification_preferences', 'notifications', 'booking_status_history' ); ``` ### 2. Verify Indexes ```sql -- Check indexes for payment_events SELECT indexname FROM pg_indexes WHERE tablename = 'payment_events'; ``` ### 3. Verify RLS Policies ```sql -- Check RLS is enabled SELECT tablename, rowsecurity FROM pg_tables WHERE schemaname = 'public' AND tablename IN ( 'payment_events', 'escrows', 'escrow_disputes', 'cancellation_requests', 'notification_preferences', 'notifications', 'booking_status_history' ); -- Check policies exist SELECT tablename, policyname FROM pg_policies WHERE schemaname = 'public'; ``` ### 4. Test Data Insertion ```sql -- Test payment_events INSERT INTO payment_events (reference, gateway, event_type, status) VALUES ('TEST-001', 'paystack', 'test_event', 'success'); -- Verify insertion SELECT * FROM payment_events WHERE reference = 'TEST-001'; -- Clean up DELETE FROM payment_events WHERE reference = 'TEST-001'; ``` ## Rollback Procedure If you need to rollback the migration: ```bash # Using Supabase CLI supabase db reset # Or manually psql -h your-db-host -U postgres -d your-database \ -f supabase/migrations/20250107000001_phase1_core_marketplace_rollback.sql ``` **⚠️ WARNING**: Rollback will permanently delete all data in the new tables. Ensure you have backups before proceeding. ## Post-Migration Steps 1. **Update Environment Variables** - Add payment provider credentials - Configure webhook URLs - Set encryption keys 2. **Test Payment Flows** - Test Paystack sandbox - Test M-Pesa sandbox - Verify webhook delivery 3. **Verify RLS Policies** - Test as different user roles - Ensure data isolation works correctly 4. **Monitor Performance** - Check query performance - Monitor index usage - Optimize if needed ## Troubleshooting ### Migration Fails **Issue**: Foreign key constraint errors **Solution**: Ensure the `properties`, `bookings`, and `users` tables exist before running migration ```sql -- Check required tables exist SELECT table_name FROM information_schema.tables WHERE table_name IN ('properties', 'bookings', 'users'); ``` ### RLS Policies Not Working **Issue**: Users can't access their own data **Solution**: Verify auth.uid() returns correct user ID ```sql -- Test as authenticated user SELECT auth.uid(); -- Check user mapping SELECT id, auth_user_id FROM users WHERE auth_user_id = auth.uid(); ``` ### Performance Issues **Issue**: Slow queries on new tables **Solution**: Verify indexes are created ```sql -- Check index usage SELECT schemaname, tablename, indexname, idx_scan FROM pg_stat_user_indexes WHERE tablename IN ('payment_events', 'escrows', 'notifications') ORDER BY idx_scan DESC; ``` ## Support For issues or questions: 1. Check Supabase logs in Dashboard β†’ Logs 2. Review migration file for syntax errors 3. Test in local development environment first 4. Contact team lead for production issues ## Version History - **v1.0** (2025-01-07): Initial Phase 1 migration - Added 7 new tables - Updated bookings table - Implemented RLS policies - Added indexes and triggers --- # Quick Start: Apply Database Migration Choose the method that works best for you: ## πŸš€ Method 1: NPX Commands (Easiest - 1 minute, No Installation!) ```bash # Step 1: Link to your project npx supabase link # Step 2: Apply migration npx supabase db push # Step 3: Generate types npx supabase gen types typescript --project-id YOUR_PROJECT_REF > src/integrations/supabase/types.ts # Step 4: Restart dev server npm run dev ``` βœ… **Done!** See `APPLY_MIGRATION_NPX.md` for detailed instructions. --- ## πŸ“± Method 2: Supabase Dashboard (2 minutes) 1. **Open Supabase Dashboard** - Go to https://app.supabase.com - Select your project - Click **SQL Editor** in sidebar 2. **Run Migration** - Click **New Query** - Open file: `supabase/migrations/20250107000001_phase1_core_marketplace.sql` - Copy all contents and paste into SQL Editor - Click **Run** (or Ctrl/Cmd + Enter) - Wait for "Success" message 3. **Verify** - Copy contents of `verify-migration.sql` - Paste and run in SQL Editor - Check that all 7 tables are created 4. **Update Types** - Go to Settings β†’ API β†’ TypeScript - Copy the generated types - Paste into `src/integrations/supabase/types.ts` βœ… **Done!** Restart your dev server: `npm run dev` --- ## πŸ’» Method 3: Using Scripts (Automated - 1 minute) ### Windows: ```cmd apply-migration.bat ``` ### Mac/Linux: ```bash chmod +x apply-migration.sh ./apply-migration.sh ``` βœ… **Done!** The script handles everything automatically. --- ## πŸ”§ Method 4: Manual CLI Commands ```bash # 1. Install Supabase CLI (if not installed) npm install -g supabase # 2. Login supabase login # 3. Link to your project supabase link --project-ref your-project-ref # 4. Apply migration supabase db push # 5. Generate types supabase gen types typescript --local > src/integrations/supabase/types.ts # 6. Restart dev server npm run dev ``` --- ## βœ… Verification Checklist After applying the migration, verify: - [ ] All 7 tables created (payment_events, escrows, escrow_disputes, cancellation_requests, notification_preferences, notifications, booking_status_history) - [ ] Indexes created (20+ indexes) - [ ] RLS policies enabled (15+ policies) - [ ] Triggers created (4 triggers) - [ ] TypeScript types updated - [ ] No errors in console --- ## πŸ†˜ Troubleshooting ### "Supabase CLI not found" ```bash npm install -g supabase ``` ### "Not linked to project" ```bash supabase link --project-ref your-project-ref ``` ### "Permission denied" on .sh file ```bash chmod +x apply-migration.sh ``` ### "Table already exists" This is normal! The migration uses `IF NOT EXISTS` to handle existing tables gracefully. --- ## πŸ“š Detailed Documentation For more details, see: - **Full Guide**: `APPLY_MIGRATION.md` - **Troubleshooting**: `docs/MIGRATION_TROUBLESHOOTING.md` - **Testing**: `docs/PHASE1_TESTING_GUIDE.md` --- ## 🎯 What's Next? After successful migration: 1. **Configure Environment Variables** - Copy `.env.example` to `.env` - Add your Supabase URL and keys - Add payment provider credentials (Paystack, M-Pesa) 2. **Test Payment Flow** - Create a test booking - Try payment with sandbox credentials - Verify escrow creation 3. **Test PIN Release** - Complete a booking - Use PIN to release escrow funds - Verify funds released --- **Need Help?** Check the full documentation in `APPLY_MIGRATION.md` --- # Webhook Implementation Review ## Overview This document provides a detailed review of the webhook implementation in `src/pages/Webhooks.tsx`, including architecture decisions, security considerations, and recommendations for improvement. ## Architecture ### Component Structure ``` Webhooks.tsx β”œβ”€β”€ Rate Limiting (in-memory Map) β”œβ”€β”€ Webhook Handlers β”‚ β”œβ”€β”€ handlePaystackWebhook() β”‚ β”œβ”€β”€ handleMpesaWebhook() β”‚ └── processWebhookCallback() β”œβ”€β”€ Database Operations β”‚ └── updateBookingAndEscrow() └── UI Display └── Webhook Events List ``` ### Data Flow ```mermaid sequenceDiagram participant PP as Payment Provider participant WH as Webhook Handler participant RL as Rate Limiter participant PS as Payment Service participant DB as Database participant UI as User Interface PP->>WH: Callback with payment data WH->>RL: Check rate limit RL-->>WH: Allow/Deny alt Rate limit OK WH->>PS: Verify payment PS-->>WH: Payment details WH->>DB: Update escrow WH->>DB: Update booking WH->>DB: Log payment event WH->>UI: Show success toast else Rate limit exceeded WH->>UI: Show rate limit error end ``` ## Implementation Details ### 1. Rate Limiting **Implementation**: ```typescript const webhookRateLimiter = new Map(); const RATE_LIMIT_WINDOW = 60000; // 1 minute const MAX_REQUESTS_PER_WINDOW = 10; const checkRateLimit = (gateway: string): boolean => { const now = Date.now(); const key = `webhook_${gateway}`; const limiter = webhookRateLimiter.get(key); if (!limiter || now > limiter.resetTime) { webhookRateLimiter.set(key, { count: 1, resetTime: now + RATE_LIMIT_WINDOW }); return true; } if (limiter.count >= MAX_REQUESTS_PER_WINDOW) { return false; } limiter.count++; return true; }; ``` **Pros**: - βœ… Simple implementation - βœ… No external dependencies - βœ… Fast performance - βœ… Per-gateway rate limiting **Cons**: - ⚠️ Resets on server restart - ⚠️ Not shared across multiple server instances - ⚠️ Memory-based (not persistent) **Recommendations**: 1. **For Production**: Implement Redis-based rate limiting ```typescript import Redis from 'ioredis'; const redis = new Redis(process.env.REDIS_URL); const checkRateLimit = async (gateway: string): Promise => { const key = `webhook_ratelimit:${gateway}`; const count = await redis.incr(key); if (count === 1) { await redis.expire(key, 60); // 60 seconds } return count <= MAX_REQUESTS_PER_WINDOW; }; ``` 2. **Alternative**: Use Supabase Edge Functions with Deno KV ```typescript const kv = await Deno.openKv(); const key = ["webhook_ratelimit", gateway]; const result = await kv.atomic() .sum(key, 1) .commit(); ``` ### 2. Paystack Webhook Handler **Implementation**: ```typescript const handlePaystackWebhook = async (reference: string) => { try { const paymentData = await paystackService.verifyPayment(reference); if (paymentData.status === 'success') { await updateBookingAndEscrow( reference, 'paystack', paymentData.amount / 100, // Convert from kobo paymentData.currency, paymentData.id.toString() ); } else { throw new Error(`Payment verification failed: ${paymentData.gateway_response}`); } } catch (error) { console.error('Paystack webhook error:', error); throw error; } }; ``` **Security Analysis**: βœ… **Strengths**: 1. Verifies payment with Paystack API (doesn't trust webhook alone) 2. Checks payment status before processing 3. Converts currency correctly (kobo to naira) 4. Comprehensive error handling ⚠️ **Potential Issues**: 1. No webhook signature verification in this function 2. Relies on paystackService for signature verification **Signature Verification** (in paystackService): ```typescript private verifyWebhookSignature(payload: string, signature: string): boolean { const crypto = require('crypto'); const hash = crypto .createHmac('sha512', this.secretKey) .update(payload, 'utf8') .digest('hex'); return hash === signature; } ``` βœ… **This is correct** - Uses HMAC SHA-512 as per Paystack documentation **Recommendations**: 1. Add signature verification to webhook handler: ```typescript const handlePaystackWebhook = async (reference: string, signature: string) => { // Verify signature first if (!paystackService.verifyWebhookSignature(payload, signature)) { throw new Error('Invalid webhook signature'); } // Then proceed with verification } ``` 2. Add replay attack prevention: ```typescript const processedWebhooks = new Set(); if (processedWebhooks.has(reference)) { throw new Error('Webhook already processed'); } processedWebhooks.add(reference); ``` ### 3. M-Pesa Webhook Handler **Implementation**: ```typescript const handleMpesaWebhook = async (checkoutRequestId: string) => { try { const response = await mpesaService.querySTKPush(checkoutRequestId); if (response.ResponseCode === '0') { const metadata = searchParams.get('metadata'); const amount = metadata ? JSON.parse(metadata).amount : 0; await updateBookingAndEscrow( checkoutRequestId, 'mpesa', amount, 'KES', response.CheckoutRequestID || checkoutRequestId ); } else { throw new Error(`M-Pesa verification failed: ${response.ResponseDescription}`); } } catch (error) { console.error('M-Pesa webhook error:', error); throw error; } }; ``` **Security Analysis**: βœ… **Strengths**: 1. Queries M-Pesa API for verification 2. Checks ResponseCode for success 3. Error handling with descriptive messages ⚠️ **Potential Issues**: 1. Amount extracted from URL parameter (could be manipulated) 2. No signature verification (M-Pesa doesn't provide webhook signatures) **Recommendations**: 1. Store amount in escrow record, don't rely on URL parameter: ```typescript // Get amount from escrow record instead const { data: escrow } = await supabase .from('escrows') .select('amount, currency') .eq('reference', checkoutRequestId) .single(); await updateBookingAndEscrow( checkoutRequestId, 'mpesa', escrow.amount, // Use stored amount escrow.currency, response.CheckoutRequestID ); ``` 2. Add IP whitelist for M-Pesa callbacks: ```typescript const MPESA_IPS = ['196.201.214.200', '196.201.214.206']; const verifyMpesaIP = (ip: string): boolean => { return MPESA_IPS.includes(ip); }; ``` ### 4. Database Update Logic **Implementation**: ```typescript const updateBookingAndEscrow = async ( reference: string, gateway: string, amount: number, currency: string, transactionId: string ): Promise => { try { // 1. Log payment event await supabase.from('payment_events').insert([{...}]); // 2. Find escrow const escrowClient: any = supabase; const escrowResult: any = await escrowClient .from('escrows') .select('*') .eq('reference', reference) .single(); // 3. Update escrow await escrowClient.from('escrows').update({ status: 'held', paid_at: new Date().toISOString(), transaction_id: transactionId, gateway_response: JSON.stringify({ gateway, amount, currency }) }).eq('id', escrow.id); // 4. Update booking await escrowClient.from('bookings').update({ status: 'confirmed' }).eq('id', bookingId); // 5. Create status history await escrowClient.from('booking_status_history').insert([{...}]); } catch (error) { console.error('Error updating booking and escrow:', error); throw error; } }; ``` **Transaction Safety**: ⚠️ **Issue**: No database transaction wrapping **Problem**: If step 3 succeeds but step 4 fails, escrow is updated but booking is not. **Recommendation**: Use Supabase RPC with PostgreSQL transaction: ```sql -- Create RPC function CREATE OR REPLACE FUNCTION update_booking_and_escrow( p_reference TEXT, p_transaction_id TEXT, p_gateway_response TEXT ) RETURNS void AS $$ BEGIN -- Update escrow UPDATE escrows SET status = 'held', paid_at = NOW(), transaction_id = p_transaction_id, gateway_response = p_gateway_response WHERE reference = p_reference; -- Update booking UPDATE bookings SET status = 'confirmed' WHERE id = (SELECT booking_id FROM escrows WHERE reference = p_reference); -- Insert status history INSERT INTO booking_status_history (booking_id, from_status, to_status, timestamp, notes) SELECT booking_id, 'pending', 'confirmed', NOW(), 'Payment confirmed via ' || (p_gateway_response::json->>'gateway') FROM escrows WHERE reference = p_reference; END; $$ LANGUAGE plpgsql; ``` Then call from TypeScript: ```typescript await supabase.rpc('update_booking_and_escrow', { p_reference: reference, p_transaction_id: transactionId, p_gateway_response: JSON.stringify({ gateway, amount, currency }) }); ``` ### 5. Error Handling **Current Implementation**: ```typescript try { // Process webhook } catch (error) { console.error('Webhook processing error:', error); toast({ title: "Webhook Error", description: error instanceof Error ? error.message : "Failed to process payment callback", variant: "destructive" }); } ``` **Pros**: - βœ… Catches all errors - βœ… User-friendly error messages - βœ… Logs to console for debugging **Cons**: - ⚠️ No error categorization - ⚠️ No retry mechanism - ⚠️ No alerting for critical errors **Recommendations**: 1. **Categorize Errors**: ```typescript class WebhookError extends Error { constructor( message: string, public code: string, public retryable: boolean = false ) { super(message); } } // Usage if (!escrow) { throw new WebhookError( 'Escrow not found', 'ESCROW_NOT_FOUND', false // Not retryable ); } ``` 2. **Implement Retry Logic**: ```typescript const processWithRetry = async (fn: () => Promise, maxRetries = 3) => { for (let i = 0; i < maxRetries; i++) { try { await fn(); return; } catch (error) { if (i === maxRetries - 1 || !(error as WebhookError).retryable) { throw error; } await sleep(1000 * Math.pow(2, i)); // Exponential backoff } } }; ``` 3. **Add Error Monitoring**: ```typescript import * as Sentry from '@sentry/react'; catch (error) { Sentry.captureException(error, { tags: { component: 'webhook', gateway: gateway }, extra: { reference: reference, amount: amount } }); } ``` ### 6. Type Safety **Current Approach**: ```typescript const escrowClient: any = supabase; const escrowResult: any = await escrowClient.from('escrows').select('*'); ``` **Issue**: Uses `any` types to bypass TypeScript errors **Why**: New tables not in generated Supabase types yet **Solution**: After migration, regenerate types: ```bash supabase gen types typescript --local > src/integrations/supabase/types.ts ``` Then update code: ```typescript import { Database } from '@/integrations/supabase/types'; const { data: escrow } = await supabase .from('escrows') .select('*') .eq('reference', reference) .single(); ``` ## Security Checklist - [x] Rate limiting implemented - [x] Payment verification with provider API - [ ] Webhook signature verification (Paystack only) - [ ] Replay attack prevention - [ ] IP whitelist (M-Pesa) - [ ] Amount validation from database - [ ] Database transactions for atomic updates - [ ] Error monitoring and alerting - [ ] Audit logging - [ ] Input sanitization ## Performance Considerations ### Current Performance **Estimated Response Time**: - Rate limit check: ~1ms - Payment verification API call: ~500-1000ms - Database updates (4 queries): ~100-200ms - **Total**: ~600-1200ms **Bottlenecks**: 1. Payment provider API calls (network latency) 2. Multiple database queries (not batched) ### Optimization Recommendations 1. **Batch Database Operations**: ```typescript // Instead of 4 separate queries, use RPC function await supabase.rpc('update_booking_and_escrow', {...}); // Reduces to 1 query ``` 2. **Cache Payment Verifications**: ```typescript const verificationCache = new Map(); const getCachedVerification = async (reference: string) => { if (verificationCache.has(reference)) { return verificationCache.get(reference); } const result = await paystackService.verifyPayment(reference); verificationCache.set(reference, result); return result; }; ``` 3. **Async Logging**: ```typescript // Don't await logging supabase.from('payment_events').insert([{...}]); // Fire and forget ``` ## Testing Recommendations ### Unit Tests ```typescript describe('Webhook Handler', () => { it('should check rate limit correctly', () => { expect(checkRateLimit('paystack')).toBe(true); // ... 10 more calls expect(checkRateLimit('paystack')).toBe(false); }); it('should handle Paystack webhook', async () => { const result = await handlePaystackWebhook('TEST-REF'); expect(result).toBeDefined(); }); }); ``` ### Integration Tests ```typescript describe('Webhook Integration', () => { it('should update booking and escrow on success', async () => { // Create test booking and escrow // Simulate webhook // Verify database updates }); }); ``` ### Load Tests ```bash # Test rate limiting under load ab -n 100 -c 10 http://localhost:8087/webhooks?gateway=paystack&reference=TEST ``` ## Deployment Checklist Before deploying to production: - [ ] Apply database migration - [ ] Regenerate Supabase types - [ ] Update environment variables - [ ] Configure webhook URLs in provider dashboards - [ ] Set up error monitoring (Sentry) - [ ] Implement Redis-based rate limiting - [ ] Add webhook signature verification - [ ] Add replay attack prevention - [ ] Set up alerting for failed webhooks - [ ] Test with sandbox credentials - [ ] Load test webhook endpoints - [ ] Document webhook URLs for ops team ## Conclusion The current webhook implementation provides a solid foundation with: - βœ… Basic rate limiting - βœ… Payment verification - βœ… Database updates - βœ… Error handling **Priority Improvements**: 1. **High**: Add database transactions for atomic updates 2. **High**: Implement proper signature verification 3. **Medium**: Add Redis-based rate limiting for production 4. **Medium**: Implement replay attack prevention 5. **Low**: Add error monitoring and alerting The implementation is production-ready for MVP with the high-priority improvements. --- # Escrow Milestone-Based Release System ## Overview This document describes the milestone-based escrow release system implemented for H&A Stay Hub to address the cash flow problem for property owners with long-term bookings. ## Problem Previously, property owners had to wait until the entire guest stay was completed (e.g., 30 days) to release their escrow funds. This created significant cash flow issues for hosts relying on regular income. ## Solution Implemented a milestone-based escrow release system that: - **Short stays (≀7 days)**: Uses the existing single-release model - **Long stays (>7 days)**: Automatically generates weekly milestones for fund release ## Implementation Details ### Database Schema **File**: `supabase/migrations/20260121000001_escrow_milestones.sql` Creates the `escrow_milestones` table with: - `id`: Primary key - `escrow_id`: Foreign key to escrows table - `milestone_number`: Sequential milestone number (1, 2, 3...) - `scheduled_date`: When milestone becomes eligible for release - `amount`: Portion of escrow allocated to this milestone - `currency`: Currency code - `status`: 'pending', 'ready', 'released', 'disputed' - `pin_hashed`: SHA-256 hashed PIN for this milestone - `pin_released`: Boolean flag - `released_at`: Timestamp when released - `released_by`: User who released the milestone ### Service Layer Updates #### EscrowService (`src/services/escrow.ts`) Added methods: - `generateMilestones()`: Creates milestones for long-term stays - `getMilestones()`: Fetches all milestones for an escrow - `updateMilestoneStatuses()`: Updates pending milestones to ready when scheduled date is reached - `verifyAndReleaseMilestone()`: Verifies PIN and releases a specific milestone - `getMilestoneSummary()`: Returns summary of released/pending/ready amounts #### BookingService (`src/services/booking.ts`) Updated `handleStatusTransition()` to: - Auto-generate milestones when booking status changes to "confirmed" - Only generate milestones for stays >7 days - Fall back gracefully if milestone generation fails ### UI Components #### EscrowMilestones (`src/components/EscrowMilestones.tsx`) New component displaying: - Progress bar showing released vs total amount - Summary cards (released/ready/pending counts) - Individual milestone cards with: - Scheduled date - Amount - Status badge - PIN entry for ready milestones - Release confirmation - Security notice about PIN usage #### EscrowPinManager (`src/components/EscrowPinManager.tsx`) Updated to: - Check if escrow has milestones - Show `EscrowMilestones` component for long-term stays - Fall back to original single-release UI for short stays ## Milestone Generation Logic For bookings longer than 7 days: - **7-13 days**: 2 milestones (50% each at day 7 and checkout) - **14-20 days**: 3 milestones (33% each at day 7, 14, and checkout) - **21+ days**: Weekly milestones (equal portions every 7 days, final at checkout) Each milestone: - Gets a unique 6-digit PIN generated using `crypto.getRandomValues()` - PIN is hashed with SHA-256 and salt before storage - PIN is sent to property owner via email/notification - Status starts as 'pending', changes to 'ready' on scheduled date - Owner enters PIN to release funds when ready ## Security Features - Cryptographically secure PIN generation (not Math.random) - SHA-256 hashing with server-side salt - Rate limiting on PIN attempts - Each milestone has unique PIN - PINs are single-use per milestone - Audit logging for all milestone operations ## Migration Instructions **IMPORTANT**: Never use `npx supabase db reset` - this will delete all production data. To apply the milestone migration: 1. **Via Supabase Dashboard**: - Go to https://supabase.com/dashboard - Navigate to your project - Go to SQL Editor - Copy and paste the contents of `supabase/migrations/20260121000001_escrow_milestones.sql` - Execute the SQL 2. **Via CLI** (if migration history is clean): ```bash npx supabase db push ``` If you encounter migration conflicts, use the SQL Editor method above. ## Testing Test scenarios: 1. Create a booking for 3 days β†’ should use single-release model 2. Create a booking for 10 days β†’ should generate 2 milestones 3. Create a booking for 30 days β†’ should generate 5 milestones (weekly) 4. Verify milestone status changes from pending to ready on scheduled date 5. Test PIN verification and milestone release 6. Verify escrow status changes to 'released' when all milestones are released ## Future Enhancements - Add milestone release notifications (email/in-app) - Implement automatic milestone status updates via cron job - Add milestone dispute handling - Create admin dashboard for milestone oversight - Add milestone release analytics ## Files Modified - `supabase/migrations/20260121000001_escrow_milestones.sql` (new) - `src/services/escrow.ts` (updated) - `src/services/booking.ts` (updated) - `src/components/EscrowMilestones.tsx` (new) - `src/components/EscrowPinManager.tsx` (updated) ## Notes - TypeScript errors will persist until migration is applied and types are regenerated - The system gracefully falls back to single-release if milestones table doesn't exist - Migration file is safe to apply - it only adds a new table, doesn't modify existing data --- # Performance Optimization Guide ## Overview This guide documents the performance optimizations implemented across the H&A Stay Hub platform to ensure fast load times, smooth animations, and efficient resource usage. ## Implemented Optimizations ### 1. Lazy Loading (Requirement 10.4) Components and images are loaded only when needed, reducing initial bundle size and improving load times. #### Lazy-Loaded Components **LazyLoad Wrapper**: ```tsx import { LazyLoad, lazy } from '@/components/LazyLoad'; // Lazy load a component const HeavyComponent = lazy(() => import('@/components/HeavyComponent')); // Use with Suspense boundary }> ``` **Location**: `src/components/LazyLoad.tsx` #### Lazy-Loaded Images **OptimizedImage Component**: ```tsx import { OptimizedImage } from '@/components/OptimizedImage'; ``` **Features**: - Intersection Observer for viewport detection - Blur-up placeholder support - Automatic lazy loading - Smooth fade-in transition - Fallback handling **Location**: `src/components/OptimizedImage.tsx` ### 2. Intersection Observer (Requirement 10.4) Scroll-triggered animations use Intersection Observer for better performance. **Hook Usage**: ```tsx import { useIntersectionObserver } from '@/hooks/use-intersection-observer'; const { ref, isVisible } = useIntersectionObserver({ threshold: 0.1, rootMargin: '50px', freezeOnceVisible: true, });
Content
``` **Configuration**: - `threshold`: 0.1 (10% of element must be visible) - `rootMargin`: '50px' (trigger 50px before entering viewport) - `freezeOnceVisible`: true (stop observing after first visibility) **Location**: `src/hooks/use-intersection-observer.tsx` ### 3. CSS Transform Animations (Requirement 10.2) All animations use CSS transforms for GPU acceleration and 60fps performance. **Optimized Properties**: - Γ’Ε“β€œ `transform` (translate, scale, rotate) - Γ’Ε“β€œ `opacity` - Γ’Ε“β€” Avoid: `top`, `left`, `width`, `height`, `margin`, `padding` **Examples**: ```css /* Good - GPU accelerated */ .element { transform: translateY(20px); opacity: 0; transition: transform 300ms, opacity 300ms; } /* Bad - causes layout recalculation */ .element { top: 20px; opacity: 0; transition: top 300ms, opacity 300ms; } ``` ### 4. Reduced Motion Support (Requirement 10.5) Respects user's motion preferences for accessibility and performance. **Implementation**: ```css @media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation-duration: 0.01ms !important; animation-iteration-count: 1 !important; transition-duration: 0.01ms !important; scroll-behavior: auto !important; } } ``` **Hook**: ```tsx import { useReducedMotion } from '@/hooks/use-reduced-motion'; const prefersReducedMotion = useReducedMotion(); // Conditionally apply animations
Content
``` **Location**: `src/hooks/use-reduced-motion.tsx`, `src/index.css` ### 5. Will-Change Optimization (Requirement 10.5) The `will-change` property is applied only during active animations to avoid performance issues. **Utility Function**: ```tsx import { optimizeWillChange } from '@/lib/performance'; // Apply will-change before animation const element = document.querySelector('.animated'); optimizeWillChange(element, ['transform', 'opacity'], 300); ``` **Automatic Application**: ```tsx // In Logo component className={cn( interactive && "hover:will-change-transform" )} ``` **Best Practices**: - Only use during animations - Remove after animation completes - Limit to 2-3 properties max - Don't apply to many elements simultaneously ### 6. Image Optimization (Requirement 10.3) Images are optimized with blur-up placeholders and lazy loading. **Blur-Up Technique**: 1. Show tiny blurred placeholder (< 1KB) 2. Load full image in background 3. Fade in full image when loaded **Implementation**: ```tsx ``` **Recommended Formats**: - WebP with JPEG fallback - AVIF for modern browsers - SVG for icons and logos ### 7. Code Splitting Large components are split into separate chunks for faster initial load. **Route-Based Splitting**: ```tsx // Already implemented in React Router const Dashboard = lazy(() => import('@/pages/Dashboard')); const PropertyDetail = lazy(() => import('@/pages/PropertyDetail')); ``` **Component-Based Splitting**: ```tsx // Heavy components loaded on demand const EarningsAnalytics = lazy(() => import('@/components/EarningsAnalytics')); const BookingStatusManager = lazy(() => import('@/components/BookingStatusManager')); ``` > Òő ï¸ **Critical: Do not use `manualChunks` to split React-dependent libraries** > > The project previously used `manualChunks` in `vite.config.ts` to split `react-hook-form`, `zod`, and Radix UI into separate chunks. This caused a **P0 production outage** Ò€” a Rollup cross-chunk Temporal Dead Zone (TDZ) crash where `react-hook-form` called `React.createContext()` before the React chunk had initialized, crashing every page with a white blank screen. > > **The current configuration intentionally omits `manualChunks`** and relies on Vite's built-in splitting. If you need to re-introduce manual chunking, ensure React and all libraries that call React APIs at module-evaluation time are in the same chunk. See [`INCIDENT_PROD_TDZ_CRASH_2026-06-15.md`](./INCIDENT_PROD_TDZ_CRASH_2026-06-15.md) for full details. ### 8. Performance Utilities **Location**: `src/lib/performance.ts` #### Debounce Limits function execution rate for expensive operations. ```tsx import { debounce } from '@/lib/performance'; const handleSearch = debounce((query: string) => { // Expensive search operation searchProperties(query); }, 300); ``` #### Throttle Ensures function executes at most once per time period. ```tsx import { throttle } from '@/lib/performance'; const handleScroll = throttle(() => { // Scroll handler updateScrollPosition(); }, 100); ``` #### Request Idle Callback Executes non-critical work during browser idle time. ```tsx import { requestIdleCallback } from '@/lib/performance'; requestIdleCallback(() => { // Non-critical analytics trackPageView(); }, { timeout: 2000 }); ``` #### Batch DOM Operations Prevents layout thrashing by batching reads and writes. ```tsx import { batchDOMOperations } from '@/lib/performance'; const elements = document.querySelectorAll('.card'); batchDOMOperations( // Reads [ () => elements.forEach(el => el.getBoundingClientRect()), ], // Writes [ () => elements.forEach(el => el.style.transform = 'translateY(0)'), ] ); ``` #### Optimized Scroll Handler Uses passive event listener and requestAnimationFrame. ```tsx import { createOptimizedScrollHandler } from '@/lib/performance'; const cleanup = createOptimizedScrollHandler((scrollY) => { // Handle scroll updateNavigation(scrollY); }); // Cleanup on unmount return cleanup; ``` ## Performance Metrics ### Target Metrics (Requirements 10.1, 10.2) - **First Contentful Paint (FCP)**: < 1.5s - **Largest Contentful Paint (LCP)**: < 2.5s - **Time to Interactive (TTI)**: < 3.5s - **Cumulative Layout Shift (CLS)**: < 0.1 - **First Input Delay (FID)**: < 100ms - **Frame Rate**: 60fps for all animations ### Measuring Performance **Get Performance Metrics**: ```tsx import { getPerformanceMetrics } from '@/lib/performance'; const metrics = getPerformanceMetrics(); console.log('TTFB:', metrics.ttfb); console.log('FCP:', metrics.fcp); console.log('Total Load Time:', metrics.totalLoadTime); ``` **Measure Function Performance**: ```tsx import { measurePerformance } from '@/lib/performance'; const result = await measurePerformance('fetchProperties', async () => { return await fetchProperties(); }); // Check performance entries const measures = performance.getEntriesByName('fetchProperties'); console.log('Duration:', measures[0].duration); ``` ## Best Practices ### 1. Component Optimization **Use React.memo for expensive components**: ```tsx export const ExpensiveComponent = React.memo(({ data }) => { // Component logic }, (prevProps, nextProps) => { // Custom comparison return prevProps.data.id === nextProps.data.id; }); ``` **Use useMemo for expensive calculations**: ```tsx const sortedData = useMemo(() => { return data.sort((a, b) => a.price - b.price); }, [data]); ``` **Use useCallback for event handlers**: ```tsx const handleClick = useCallback(() => { // Handler logic }, [dependencies]); ``` ### 2. Image Optimization **Always specify dimensions**: ```tsx ``` **Use appropriate formats**: - Photos: WebP/JPEG - Graphics: WebP/PNG - Icons: SVG - Animations: CSS/SVG (avoid GIF) **Implement responsive images**: ```tsx Description ``` ### 3. Animation Optimization **Use CSS animations over JavaScript**: ```css /* Preferred */ .element { animation: fadeIn 300ms ease-out; } @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } ``` **Limit concurrent animations**: - Maximum 3-4 elements animating simultaneously - Stagger animations for better performance - Use `animation-delay` for sequencing **Optimize animation properties**: ```tsx // Good - GPU accelerated transform: translateX(100px) scale(1.1); opacity: 0.5; // Bad - causes reflow left: 100px; width: 200px; ``` ### 4. Bundle Optimization **Analyze bundle size**: ```bash npm run build # Check dist/ folder sizes ``` **Code splitting strategies**: - Route-based splitting (automatic with React Router) - Component-based splitting (lazy load heavy components) - Vendor splitting (separate chunk for node_modules) **Tree shaking**: - Use ES6 imports (not CommonJS) - Import only what you need - Avoid barrel exports for large libraries ### 5. Network Optimization **Preload critical resources**: ```tsx import { preloadResources } from '@/lib/performance'; // Preload hero image preloadResources(['/images/hero.jpg'], 'image'); // Preload fonts preloadResources(['/fonts/inter.woff2'], 'font'); ``` **Use CDN for static assets**: - Images - Fonts - Third-party libraries **Implement caching strategies**: ```tsx // React Query with caching const { data } = useQuery('properties', fetchProperties, { staleTime: 5 * 60 * 1000, // 5 minutes cacheTime: 10 * 60 * 1000, // 10 minutes }); ``` ## Testing Performance ### Browser DevTools **Chrome DevTools**: 1. Open DevTools (F12) 2. Go to Performance tab 3. Click Record 4. Interact with page 5. Stop recording 6. Analyze flame chart **Lighthouse Audit**: 1. Open DevTools (F12) 2. Go to Lighthouse tab 3. Select categories (Performance, Accessibility, Best Practices) 4. Click "Generate report" 5. Review scores and recommendations ### Performance Monitoring **Web Vitals**: ```tsx import { getCLS, getFID, getFCP, getLCP, getTTFB } from 'web-vitals'; getCLS(console.log); getFID(console.log); getFCP(console.log); getLCP(console.log); getTTFB(console.log); ``` **Custom Metrics**: ```tsx // Mark important events performance.mark('hero-loaded'); performance.mark('dashboard-rendered'); // Measure between marks performance.measure('hero-to-dashboard', 'hero-loaded', 'dashboard-rendered'); // Get measurements const measures = performance.getEntriesByType('measure'); ``` ## Troubleshooting ### Issue: Slow initial load **Solutions**: - Implement code splitting - Lazy load below-the-fold content - Optimize images (compress, use WebP) - Minimize JavaScript bundle - Use CDN for static assets ### Issue: Janky animations **Solutions**: - Use CSS transforms instead of position properties - Limit concurrent animations - Apply will-change only during animations - Check for layout thrashing - Use requestAnimationFrame for JS animations ### Issue: High memory usage **Solutions**: - Remove will-change after animations - Unsubscribe from event listeners - Clear intervals and timeouts - Implement virtual scrolling for long lists - Use React.memo to prevent unnecessary re-renders ### Issue: Slow scroll performance **Solutions**: - Use passive event listeners - Throttle scroll handlers - Use Intersection Observer instead of scroll events - Avoid expensive calculations in scroll handlers - Implement virtual scrolling ## Requirements Coverage This implementation satisfies: - **10.1**: Logo renders within 100ms Γ’Ε“β€œ - **10.2**: CSS transforms used for 60fps performance Γ’Ε“β€œ - **10.3**: Images use blur-up placeholders Γ’Ε“β€œ - **10.4**: Dashboard components lazy loaded below fold Γ’Ε“β€œ - **10.5**: Will-change optimized, reduced motion supported Γ’Ε“β€œ ## Resources ### Tools - [Chrome DevTools](https://developers.google.com/web/tools/chrome-devtools) - [Lighthouse](https://developers.google.com/web/tools/lighthouse) - [WebPageTest](https://www.webpagetest.org/) - [Bundle Analyzer](https://www.npmjs.com/package/webpack-bundle-analyzer) ### Libraries - [web-vitals](https://github.com/GoogleChrome/web-vitals) - [React.lazy](https://react.dev/reference/react/lazy) - [Intersection Observer API](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API) ### Articles - [Web Performance Optimization](https://web.dev/fast/) - [Rendering Performance](https://web.dev/rendering-performance/) - [Image Optimization](https://web.dev/fast/#optimize-your-images) - [Code Splitting](https://web.dev/reduce-javascript-payloads-with-code-splitting/) ## Future Enhancements 1. **Service Worker**: Offline support and caching 2. **HTTP/2 Server Push**: Push critical resources 3. **Brotli Compression**: Better compression than gzip 4. **Resource Hints**: dns-prefetch, preconnect, prefetch 5. **Virtual Scrolling**: For long property lists 6. **Progressive Web App**: Install as native app 7. **Edge Caching**: Cache at CDN edge locations 8. **Image CDN**: Automatic image optimization and delivery --- # Accessibility Guide ## Overview This guide documents the accessibility features implemented across the H&A Stay Hub platform to ensure an inclusive experience for all users, including those using assistive technologies. ## Implemented Features ### 1. Visible Focus Indicators (Requirement 9.2) All interactive elements have visible focus indicators with a 2px outline. **Implementation**: ```css *:focus-visible { outline: 2px solid hsl(var(--primary)); outline-offset: 2px; border-radius: 4px; } ``` **Affected Elements**: - Links - Buttons - Form inputs - Interactive icons - Navigation items **Testing**: Press Tab to navigate through the page and verify all interactive elements show a clear blue outline. ### 2. Keyboard Navigation (Requirement 9.5) Full keyboard navigation support with logical tab order. **Key Features**: - Tab: Move forward through interactive elements - Shift+Tab: Move backward through interactive elements - Enter: Activate buttons and links - Space: Activate buttons - Escape: Close modals and menus **Skip to Main Content**: A "Skip to main content" link appears when focused, allowing keyboard users to bypass navigation. **Location**: `src/components/accessibility/SkipToMain.tsx` **Usage**: ```tsx import { SkipToMain } from '@/components/accessibility'; // In App.tsx ``` ### 3. Logo Accessibility (Requirements 9.1, 9.3, 9.4) The Logo component includes comprehensive accessibility features. **Features**: - **ARIA Label**: "H&A Stay Hub logo, navigate to home page" - **Keyboard Accessible**: Enter key triggers navigation - **Screen Reader Support**: Announces purpose and destination - **Minimum Touch Target**: 44x44px on mobile **Implementation**: ```tsx ``` **Location**: `src/components/ui/logo.tsx` ### 4. Screen Reader Support (Requirement 9.4) Comprehensive screen reader support throughout the application. **Components**: #### ScreenReaderOnly Renders content visible only to screen readers. ```tsx import { ScreenReaderOnly } from '@/components/accessibility'; Additional context for screen readers ``` #### LiveRegion Announces dynamic content changes to screen readers. ```tsx import { LiveRegion } from '@/components/accessibility'; ``` **Location**: `src/components/accessibility/` ### 5. ARIA Labels and Roles All interactive elements have appropriate ARIA labels and roles. **Examples**: **Navigation**: ```tsx ``` **Social Media Links**: ```tsx ``` **Form Inputs**: ```tsx ``` ### 6. Color Contrast (Requirement 9.5) All text meets WCAG AA standards for color contrast. **Contrast Ratios**: - Normal text: Minimum 4.5:1 - Large text (18px+): Minimum 3:1 - Interactive elements: Minimum 3:1 **Testing**: Use browser DevTools or online contrast checkers to verify ratios. ### 7. Touch Targets (Requirement 7.1) All interactive elements meet minimum touch target size of 44x44px on mobile. **Implementation**: ```tsx ``` **Affected Components**: - Buttons - Links - Icons - Form controls - Navigation items ### 8. Semantic HTML Proper use of semantic HTML elements for better accessibility. **Structure**: ```html
``` ### 9. Form Accessibility All forms include proper labels, error messages, and validation feedback. **Best Practices**: ```tsx
{hasError && ( Please enter a valid email address )}
``` ### 10. Modal Accessibility Modals trap focus and can be closed with Escape key. **Features**: - Focus trap: Tab cycles through modal elements only - Escape key: Closes modal - Focus restoration: Returns focus to trigger element - ARIA attributes: role="dialog", aria-modal="true" **Implementation**: Already handled by Radix UI Dialog component. ## Accessibility Components ### SkipToMain **Purpose**: Allows keyboard users to skip navigation and jump to main content. **Location**: `src/components/accessibility/SkipToMain.tsx` **Usage**: ```tsx import { SkipToMain } from '@/components/accessibility'; ``` **Behavior**: - Hidden by default - Visible when focused (Tab key) - Jumps to element with id="main-content" ### ScreenReaderOnly **Purpose**: Provides content visible only to screen readers. **Location**: `src/components/accessibility/ScreenReaderOnly.tsx` **Usage**: ```tsx import { ScreenReaderOnly } from '@/components/accessibility'; ``` ### LiveRegion **Purpose**: Announces dynamic content changes to screen readers. **Location**: `src/components/accessibility/LiveRegion.tsx` **Usage**: ```tsx import { LiveRegion } from '@/components/accessibility'; const [message, setMessage] = useState(''); // When something happens setMessage('Item added to cart'); ``` **Props**: - `message`: The message to announce - `politeness`: 'polite' | 'assertive' | 'off' - `clearAfter`: Auto-clear after milliseconds (optional) ## Testing Checklist ### Keyboard Navigation - [ ] All interactive elements are keyboard accessible - [ ] Tab order is logical and intuitive - [ ] Focus indicators are clearly visible - [ ] Skip to main content link works - [ ] Modals trap focus correctly - [ ] Escape key closes modals and menus ### Screen Reader Testing - [ ] Logo announces correctly - [ ] All images have alt text - [ ] Form labels are associated with inputs - [ ] Error messages are announced - [ ] Dynamic content changes are announced - [ ] Navigation structure is clear ### Visual Testing - [ ] Focus indicators have 2px outline - [ ] Color contrast meets WCAG AA - [ ] Text is readable at 200% zoom - [ ] Touch targets are minimum 44x44px - [ ] No content is hidden by focus indicators ### Assistive Technology Testing **Screen Readers**: - NVDA (Windows) - JAWS (Windows) - VoiceOver (macOS/iOS) - TalkBack (Android) **Browser Extensions**: - axe DevTools - WAVE - Lighthouse Accessibility Audit ## Common Patterns ### Accessible Button with Icon ```tsx ``` ### Accessible Link ```tsx View Details ``` ### Accessible Form Field ```tsx
{hasError && ( Property name is required )}
``` ### Accessible Navigation ```tsx ``` ## WCAG 2.1 Compliance ### Level A (Must Have) - βœ“ Keyboard accessible - βœ“ Text alternatives for images - βœ“ Meaningful sequence - βœ“ Sensory characteristics - βœ“ Use of color - βœ“ Audio control - βœ“ Keyboard trap avoidance - βœ“ Timing adjustable - βœ“ Pause, stop, hide - βœ“ Three flashes or below - βœ“ Bypass blocks (skip links) - βœ“ Page titled - βœ“ Focus order - βœ“ Link purpose - βœ“ Language of page ### Level AA (Should Have) - βœ“ Captions (prerecorded) - βœ“ Audio description - βœ“ Contrast (minimum 4.5:1) - βœ“ Resize text (200%) - βœ“ Images of text - βœ“ Multiple ways to navigate - βœ“ Headings and labels - βœ“ Focus visible - βœ“ Language of parts - βœ“ On focus - βœ“ On input - βœ“ Error identification - βœ“ Labels or instructions - βœ“ Error suggestion - βœ“ Error prevention ## Browser Support All accessibility features are supported in: - Chrome/Edge: Last 2 versions - Firefox: Last 2 versions - Safari: Last 2 versions - Mobile Safari: iOS 13+ - Chrome Mobile: Android 8+ ## Resources ### Tools - [axe DevTools](https://www.deque.com/axe/devtools/) - [WAVE Browser Extension](https://wave.webaim.org/extension/) - [Lighthouse](https://developers.google.com/web/tools/lighthouse) - [Color Contrast Analyzer](https://www.tpgi.com/color-contrast-checker/) ### Guidelines - [WCAG 2.1](https://www.w3.org/WAI/WCAG21/quickref/) - [ARIA Authoring Practices](https://www.w3.org/WAI/ARIA/apg/) - [WebAIM](https://webaim.org/) ### Testing - [Screen Reader Testing](https://webaim.org/articles/screenreader_testing/) - [Keyboard Testing](https://webaim.org/articles/keyboard/) - [Color Contrast Testing](https://webaim.org/articles/contrast/) ## Requirements Coverage This implementation satisfies: - **9.1**: Logo includes appropriate alt text/aria-label βœ“ - **9.2**: Visible focus indicators with 2px outline βœ“ - **9.3**: Logo is keyboard accessible with Enter key support βœ“ - **9.4**: Screen reader announces logo purpose and destination βœ“ - **9.5**: Full keyboard navigation with Tab/Shift+Tab support βœ“ ## Future Enhancements 1. **High Contrast Mode**: Support for Windows High Contrast Mode 2. **Voice Control**: Optimize for voice navigation 3. **Dyslexia Support**: Optional dyslexia-friendly font 4. **Reading Mode**: Simplified layout for better readability 5. **Keyboard Shortcuts**: Custom keyboard shortcuts for power users 6. **Focus Management**: Advanced focus management for SPAs ## Troubleshooting ### Issue: Focus indicators not visible **Solution**: Check if custom CSS is overriding the focus-visible styles. Ensure outline is not set to none. ### Issue: Screen reader not announcing changes **Solution**: Verify LiveRegion component is used and aria-live attribute is set correctly. ### Issue: Keyboard navigation not working **Solution**: Check if elements have proper tabindex and event handlers. Ensure no JavaScript errors are blocking events. ### Issue: Skip link not appearing **Solution**: Verify SkipToMain component is rendered and main content has id="main-content". ## Contact For accessibility issues or questions, please contact the development team or file an issue in the project repository. --- # Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] ### Fixed #### P0 Production Outage Ò€” White Blank Page / TDZ Crash (2026-06-15) - **Bug**: All pages on `hna.africa` rendered as a white blank page with `Uncaught ReferenceError: Cannot access 'C' before initialization` at `forms-B3HCCH5z.js:1:1806` - **Type**: Rollup cross-chunk Temporal Dead Zone (TDZ) initialization error - **Root cause**: `vite.config.ts` `manualChunks` config assigned `react-hook-form` to a `forms` chunk while React itself landed in `vendor`. Because `react-hook-form` calls `React.createContext()` at module evaluation time, the `forms` chunk crashed when it ran before `vendor` had initialized React. - **Fix**: Removed `manualChunks` entirely from `vite.config.ts` Ò€” Vite's default code-splitting correctly handles cross-chunk initialization order. - **Commits**: `63d8cdc` (intermediate), `174dba2` (final fix) - **Incident doc**: [`docs/INCIDENT_PROD_TDZ_CRASH_2026-06-15.md`](./INCIDENT_PROD_TDZ_CRASH_2026-06-15.md) ### Added #### Unified Authentication & Onboarding System (January 2025) - Unified authentication page with tabbed sign in/sign up interface - Demo mode with role selection for testing without account creation - Role-based onboarding wizard (Tenant, Property Owner, Agent) - Progress tracking and auto-save functionality - Skippable KYC verification with confirmation dialog - Dashboard onboarding completion banner with progress indicator - Smart post-authentication routing based on onboarding status - Onboarding session persistence in database - 57 comprehensive E2E tests with Playwright #### UI/UX Enhancements (November 2025) - Refined logo component with improved accessibility - Scroll-based navigation effects with backdrop blur - Mobile navigation menu with slide-out animation - Enhanced hero section with gradient text and parallax scrolling - Improved dashboard visual hierarchy with staggered animations - Loading states and skeleton loaders with shimmer effects - Page transition system with smooth fade-in animations - Enhanced footer component with consistent branding - Comprehensive accessibility improvements (WCAG 2.1 AA compliant) - Performance optimizations with lazy loading and intersection observers - 112+ automated tests for visual regression and accessibility #### Documentation System - Automated documentation generation from commits - GitHub Actions workflow for documentation updates - Comprehensive user guides and technical references - Auto-updating WIKI and CHANGELOG - Testing guides for E2E, accessibility, and visual regression #### Database & Backend - Onboarding tracking fields in user_profiles table - Onboarding_sessions table for progress persistence - Row Level Security (RLS) policies for data protection - Phase 1 core marketplace migration - Webhook implementation for payment events ### Changed - Updated navigation component with scroll detection - Enhanced dashboard with user name and role display - Improved button components with loading states and press feedback - Updated dialog and alert-dialog components with scale animations - Refactored authentication flow to use unified auth page - Modernized routing with legacy route redirects ### Fixed - Crypto module browser compatibility issue in escrow service - Database migration syntax errors - RLS policy access control issues - Test suite syntax errors with string literals - TypeScript type definitions for database schema ### Security - Implemented comprehensive RLS policies - Secure session management for onboarding progress - PIN-based escrow fund release system - JWT token-based authentication with Descope - Validated `VITE_ESCROW_PIN_SALT` in `env-validator.ts` and made `EscrowService` reject default/missing salts - Added `Content-Security-Policy-Report-Only` headers to `vercel.json` and `netlify.toml` to audit `unsafe-eval` removal ### Added - Partial unique index `idx_escrows_pin_hashed_unique` on `escrows.pin_hashed` (migration) - Agent commission dashboard at `/agent/commission` with KPI cards and property-level commission breakdown - Production guidance note to `src/lib/rate-limiter.ts` about per-deploy reset limitation - Offline status gating in `BookingStatusTracker` using `pwaService.isOnline()` - `public/offline.html` fallback pre-cached via `vite-plugin-pwa` includeAssets - `supabase/migrations/disabled/` archive with README for rollback/disabled migrations - Expanded `tests/operational-roles.spec.ts` route-guard coverage --- # Footer Component Guide ## Overview The Footer component provides a comprehensive, responsive footer with consistent branding, navigation links, social media icons, and language/currency settings. It follows the UI/UX Enhancement spec requirements for brand consistency and proper spacing. ## Features Implemented ### 1. Logo Integration (Requirement 1.5, 5.4) - **Size**: "sm" variant for compact footer display - **Variant**: "gradient" for visual consistency with navigation - **Spacing**: 24px (gap-6) from surrounding elements - **Interactive**: Hover effects enabled for better UX ### 2. Consistent Layout - **Max Width**: 1400px centered for optimal readability - **Padding**: py-12 (48px vertical) and px-4 (16px horizontal) - **Background**: bg-muted with border-t for subtle separation - **Responsive**: Adapts from mobile (stacked) to desktop (horizontal) ### 3. Smooth Transitions - **Duration**: 150ms for color transitions - **Button Feedback**: active:scale-95 with 100ms duration - **Hover States**: Smooth color changes on all interactive elements ### 4. Language and Currency Settings - **Language Selector**: Globe icon with current language display - **Currency Selector**: Dollar sign icon with current currency - **Interactive**: Hover and active states for better feedback ### 5. Social Media Integration - **Icons**: Facebook, Instagram, Twitter, LinkedIn - **Accessibility**: Proper aria-labels for screen readers - **Transitions**: Smooth hover and active states ## Component Structure ``` Footer β”œβ”€β”€ Main Container (max-w-[1400px]) β”‚ β”œβ”€β”€ Links Grid (4 columns on desktop, 2 on mobile) β”‚ β”‚ β”œβ”€β”€ Company β”‚ β”‚ β”œβ”€β”€ Support β”‚ β”‚ β”œβ”€β”€ Hosting β”‚ β”‚ └── Discover β”‚ └── Bottom Section β”‚ β”œβ”€β”€ Logo & Copyright β”‚ β”œβ”€β”€ Social Media Icons β”‚ β”œβ”€β”€ Language/Currency Settings β”‚ └── Legal Links ``` ## Usage ### Basic Implementation ```tsx import Footer from '@/components/Footer'; const MyPage = () => { return (
{/* Page content */}
); }; ``` ### Current Integration The Footer is currently used in: - `src/pages/Index.tsx` - Landing page - `src/pages/Favorites.tsx` - Favorites page - `src/pages/Messages.tsx` - Messages page ## Styling Details ### Colors - **Background**: `bg-muted` - Subtle background color - **Border**: `border-t border-border` - Top border for separation - **Text**: `text-muted-foreground` - Secondary text color - **Hover**: `hover:text-primary` - Primary color on hover ### Spacing - **Container Padding**: `py-12 px-4` (48px vertical, 16px horizontal) - **Logo Spacing**: `gap-6` (24px) from surrounding elements - **Section Spacing**: `mb-12` (48px) between main sections - **Link Spacing**: `space-y-3` (12px) between links ### Typography - **Category Headers**: Uppercase, tracking-wide, font-semibold - **Links**: text-sm (14px) - **Copyright**: text-sm (14px) ### Responsive Behavior #### Mobile (< 768px) - Links grid: 2 columns - Logo and copyright: Stacked vertically, centered - Social icons: Centered below logo - Language/Currency: Centered, wrapped - Legal links: Centered, wrapped #### Desktop (β‰₯ 768px) - Links grid: 4 columns - Logo and copyright: Horizontal, left-aligned - Social icons: Right-aligned - Language/Currency: Right-aligned - Legal links: Centered ## Accessibility Features ### ARIA Labels All social media links have descriptive aria-labels: ```tsx ``` ### Keyboard Navigation - All links and buttons are keyboard accessible - Focus indicators visible (inherited from global styles) - Logical tab order maintained ### Screen Reader Support - Semantic HTML structure with `