Project Overview
KnowMyHotel is a comprehensive LLM-powered revenue management platform for hotels. It provides conversational AI insights, automated rate recommendations, comprehensive reporting, competitor analysis, and team collaboration features.
Key Features
- AI Revenue Manager: Conversational interface for revenue insights
- Dynamic Pricing: Automated rate optimization with multiple rule types
- Comprehensive Reports: Pace, Pickup, Revenue Deck, Month-End, Parity, Segment/Source, Year-End, Weekly Performance
- Competitor Analysis: Real-time compset tracking and market intelligence
- Team Collaboration: Multi-user access with role-based permissions
- Data Upload: Channel manager integration and data ingestion
- Performance Goals: KPI tracking and goal management
- Notifications: Real-time alerts and system notifications
Architecture
Application Structure
The application follows a modern React architecture with:
- Frontend: React 18 with TypeScript, Vite build tool
- State Management: React Context API (AuthContext, PropertyContext, PricingContext)
- Routing: React Router v7 with protected routes
- Styling: TailwindCSS with custom components
- API Communication: Axios-based API client with authentication
- Real-time: Socket.io for live updates
Data Flow
User Action → Component → Service → API Client → Backend API
↓
Response → Service → Context → Component → UI Update
Setup & Installation
Prerequisites
- Node.js 18+ and npm/yarn
- Git
- Code editor (VS Code recommended)
Installation Steps
- Clone the repository:
git clone [repository-url] cd knowmyhotel - Install dependencies:
npm install - Environment Variables:
Create a
.envfile in the root directory:VITE_API_BASE_URL=http://localhost:5001/api - Run development server:
npm run dev - Build for production:
npm run build
Tech Stack
Core Technologies
- React 18.2.0: UI library
- TypeScript 5.5.3: Type safety
- Vite 5.4.2: Build tool and dev server
- React Router 7.6.0: Routing
- TailwindCSS 3.3.3: Styling
Key Libraries
- Framer Motion 11.18.2: Animations
- Axios 1.10.0: HTTP client
- Socket.io Client 4.8.1: Real-time communication
- React ApexCharts 1.7.0: Charts and graphs
- Date-fns 2.30.0: Date manipulation
- XLSX 0.18.5: Excel file generation
- jsPDF 3.0.1: PDF generation
- Lucide React 0.511.0: Icons
UI Component Libraries
- Radix UI: Accessible component primitives (Dialog, Popover, Select, Toggle, Tooltip)
- Shadcn UI: Custom component library built on Radix
Folder Structure
knowmyhotel/
├── src/
│ ├── api/
│ │ ├── services/ # API service layer
│ │ └── utils/ # API utilities (apiClient)
│ ├── components/ # React components
│ │ ├── ai-insights/ # AI insights components
│ │ ├── chat/ # Chat interface components
│ │ ├── dashboard/ # Dashboard-specific components
│ │ ├── magicui/ # Magic UI components
│ │ ├── onboarding/ # Onboarding flow components
│ │ ├── pricing/ # Pricing rule components
│ │ ├── reports/ # Report components
│ │ └── ui/ # Reusable UI components
│ ├── contexts/ # React contexts
│ ├── lib/ # Utility libraries
│ ├── pages/ # Page components
│ │ ├── dashboard/ # Dashboard pages
│ │ ├── marketing/ # Marketing pages
│ │ ├── pricing/ # Pricing pages
│ │ └── reports/ # Report pages
│ ├── types/ # TypeScript type definitions
│ ├── utils/ # Utility functions
│ ├── main.tsx # Application entry point
│ ├── router.tsx # Route configuration
│ └── style.css # Global styles
├── public/ # Static assets
├── package.json # Dependencies
├── tsconfig.json # TypeScript config
├── vite.config.ts # Vite configuration
└── tailwind.config.js # Tailwind configuration
File Organization
Naming Conventions
- Components: PascalCase (e.g., `Dashboard.tsx`, `MetricsGrid.tsx`)
- Services: camelCase with Service suffix (e.g., `authService.ts`, `propertyService.ts`)
- Types: camelCase (e.g., `chat.ts`, `pricing.ts`)
- Utils: camelCase (e.g., `excelGenerator.ts`, `notifications.mock.ts`)
- Contexts: PascalCase with Context suffix (e.g., `AuthContext.tsx`)
Component Structure
Each component typically follows this structure:
// Imports
import React from 'react';
import { ... } from '@/components/...';
// Types/Interfaces
interface ComponentProps {
// props
}
// Component
export const Component: React.FC = ({ ... }) => {
// State, hooks, handlers
return (
// JSX
);
};
export default Component;
Pages Overview
Pages are the top-level route components that represent different views in the application. They are organized by feature area.
Page Categories
- Authentication: Login, SignUp
- Dashboard: Main dashboard, Chat interface
- Reports: Various analytical reports
- Pricing: Pricing dashboard, rule builder, calendar, AI pricing
- Marketing: Public-facing pages (About, Features, Pricing, Contact, etc.)
- Settings: User settings, team access, notifications, performance goals
Authentication Pages
Login.tsx
Location: src/pages/Login.tsx
Route: /login
Description: User login page with email and password authentication.
Features:
- Email/password login form
- Error handling and validation
- Redirects to dashboard on success
- Uses AuthService for authentication
SignUp.tsx
Location: src/pages/SignUp.tsx
Route: /signup
Description: New user registration page.
Features:
- User registration form (name, email, phone, password)
- Form validation
- Redirects to onboarding after signup
Dashboard Pages
Dashboard.tsx
Location: src/pages/Dashboard.tsx
Route: /dashboard
Description: Main dashboard page showing overview metrics, AI action plan, revenue performance, and compset data.
Components Used:
- Sidebar - Navigation menu
- StickyHeader - Top header with property selector
- MetricsGrid - Today's overview metrics
- AIActionPlan - AI-generated action items
- RevenuePerformance - Revenue charts
- PickupTrendCalendar - Booking trends
- CompsetOverview - Competitor overview
- CompsetHotels - Competitor hotel list
- AnimatedAIChat - Quick AI chat interface
- AlertBar - System alerts
ChatPage ([chatID].tsx)
Location: src/pages/dashboard/chat/[chatID].tsx
Route: /dashboard/chat/:chatID or /dashboard/chat/new
Description: Full-screen AI chat interface for conversational revenue management.
Features:
- Real-time message exchange with AI
- Chat history with pagination
- Message suggestions parsing
- Socket.io integration for live updates
- Chat sidebar for conversation list
Report Pages
All report pages are located in src/pages/reports/ and follow similar patterns with date selection, data fetching, and export capabilities.
PickupReport.tsx
Route: /reports/pickup or /reports/pickup/:hotelId/:selectedDate (public)
Description: Daily pickup report showing booking trends, channel performance, and revenue analysis.
Features:
- Date picker for report date
- Pickup summary cards (Today's pickup, revenue, ADR, month totals)
- Channel performance table
- Actual vs BOB data breakdown
- Revenue analysis charts
- Next month forecast
- PDF and Excel export
- Public sharing mode (no auth required)
PaceReport.tsx
Route: /reports/pace
Description: Pace report comparing current booking pace against historical data.
RevenueDeck.tsx
Route: /reports/revenue
Description: Comprehensive revenue analysis deck with multiple metrics and visualizations.
MonthEndSummary.tsx
Route: /reports/month-end
Description: Monthly performance summary report.
ParityReport.tsx
Route: /reports/parity
Description: Rate parity analysis across different channels.
SegmentSourceReports.tsx
Route: /reports/segments
Description: Segment and source-based performance analysis.
YearEndReport.tsx
Route: /reports/year-end
Description: Annual performance summary and analysis.
WeeklyPerformanceReport.tsx
Route: /reports/weekly-performance
Description: Weekly performance metrics and trends.
AIInsights.tsx
Route: /insights
Description: AI-powered insights and recommendations page.
Components:
- AIInsightsHero - Hero section
- InteractiveMetricsDashboard - Metrics visualization
- InteractiveActionPlan - Actionable recommendations
CompsetMarket.tsx
Route: /compset-market
Description: Competitor set and market analysis page.
Pricing Pages
PricingDashboard.tsx
Location: src/pages/pricing/PricingDashboard.tsx
Route: /pricing
Description: Main pricing dashboard showing all pricing rules, statistics, and quick actions.
Features:
- Rules overview with statistics (total, active, inactive)
- Rules list with status indicators
- Create new rule button
- Edit and delete rule actions
- Rule type filtering
RuleTypeSelection.tsx
Route: /pricing/rules/create
Description: Rule type selection page before creating a new pricing rule.
Rule Types:
- Occupancy-Based
- Time-Based (Day of Week)
- Demand-Based
- Length of Stay
- Competitive
- Seasonal
RuleBuilder.tsx
Route: /pricing/rules/builder?type=...
Description: Multi-step form for creating or editing pricing rules.
Steps:
- Basic Information (name, description, priority, status)
- Rate Range (min, base, max rates)
- Rule-Specific Conditions (varies by rule type)
- Review and Save
Components Used:
- OccupancyBasedConfig
- TimeBasedConfig
- LengthOfStayConfig
- DemandBasedConfig
- CompetitiveConfig
- SeasonalConfig
PricingCalendar.tsx
Route: /pricing/calendar
Description: Calendar view for managing pricing rules across dates.
AIPricing.tsx
Route: /pricing/ai
Description: AI-powered pricing suggestions and recommendations.
Features:
- Date range selection
- AI rate suggestions with confidence scores
- Rate adjustment interface
- Excel export functionality
Marketing Pages
All marketing pages are located in src/pages/marketing/ and are public-facing (no authentication required).
Home.tsx
Route: /
Components:
- LandingHeader
- HeroSection
- NextHeroSection
- FeatureSection
- TestimonialsSection
- PricingPreviewSection
- FAQSection
- Footer
Other Marketing Pages
- About.tsx -
/about- Company information - Features.tsx -
/features- Feature showcase - Pricing.tsx -
/pricing-page- Pricing plans - CompsetAnalysis.tsx -
/compset-analysis- Competitor analysis feature - Contact.tsx -
/contact- Contact information - Help.tsx -
/help- Help and support - Docs.tsx -
/docs- Documentation - Status.tsx -
/status- System status - TermsConditions.tsx -
/terms-conditions- Terms and conditions - Privacy.tsx -
/privacy- Privacy policy - CancellationRefunds.tsx -
/cancellation-refunds- Cancellation policy
Other Pages
Onboarding.tsx
Route: /onboarding
Description: Multi-step onboarding flow for new users to set up their hotel property.
Steps:
- HotelProfileStep - Basic hotel information
- HotelAddressStep - Address and location
- DataSourceStep - Channel manager selection
- TeamAccessStep - Team member invitation
- CompsetSetupStep - Competitor set configuration
- InsightPreferencesStep - AI insight preferences
- PerformanceGoalsStep - Performance targets
- SetupCompleteStep - Completion confirmation
Settings.tsx
Route: /settings
Description: Comprehensive settings page for property configuration.
Sections:
- Hotel Profile - Name, type, rooms, star rating, use cases
- Hotel Address - Full address with map integration
- Platform Links - OTA and social media links
- Business Goals - Revenue targets and KPIs
TeamAccess.tsx
Route: /team
Description: Team member management page.
Features:
- Add team members with roles
- View team member list
- Search and filter by role
- Role-based permissions (Owner, Revenue Manager, Sales, Front Office)
DataUpload.tsx
Route: /data-upload
Description: Data upload interface for channel manager data.
Features:
- Channel manager selection
- Template download
- File upload (drag & drop)
- Data mapping and validation
- Upload progress tracking
PerformanceGoals.tsx
Route: /performance-goals
Description: Performance goals tracking and KPI monitoring.
Features:
- Date range selection
- Performance metrics by category (Revenue, Occupancy, Operations)
- AI-generated insights and recommendations
- Progress tracking with visual indicators
Notifications.tsx
Route: /notifications
Description: Notification center for system alerts and updates.
Features:
- Notification list with categories
- Search and filter functionality
- Mark as read/unread
- Notification statistics
ErrorPage.tsx
Route: Error boundary fallback
Description: Error page displayed when route errors occur.
Components Overview
Components are reusable React components organized by feature area. They follow a consistent structure and use TypeScript for type safety.
Component Organization:
ui/- Reusable UI primitives (buttons, cards, inputs, etc.)dashboard/- Dashboard-specific componentschat/- Chat interface componentsonboarding/- Onboarding flow componentspricing/- Pricing rule configuration componentsai-insights/- AI insights visualization componentsmagicui/- Advanced UI components (animations, effects)reports/- Report-specific components
UI Components
Located in src/components/ui/. These are base components built on Radix UI primitives and styled with TailwindCSS.
Core UI Components
- button.tsx - Button component with variants (default, outline, ghost, destructive)
- card.tsx - Card container component
- input.tsx - Text input component
- textarea.tsx - Textarea component
- select.tsx - Select dropdown component (Radix UI)
- dialog.tsx - Modal dialog component (Radix UI)
- popover.tsx - Popover component (Radix UI)
- tooltip.tsx - Tooltip component (Radix UI)
- badge.tsx - Badge/tag component
- calendar.tsx - Calendar date picker
- progress.tsx - Progress bar component
- toast.tsx - Toast notification system
- toggle.tsx - Toggle switch component
- toggle-group.tsx - Toggle group component
- sparkles.tsx - Sparkle animation effect
- cover.tsx - Cover/overlay component
Usage Example
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
<Card>
<CardHeader>
<CardTitle>Title</CardTitle>
</CardHeader>
<CardContent>
<Button variant="default">Click Me</Button>
</CardContent>
</Card>
Dashboard Components
Located in src/components/dashboard/. Components specific to the dashboard view.
Key Components
- Sidebar.tsx - Main navigation sidebar with expandable menus
- StickyHeader.tsx - Fixed top header with property selector
- MetricsGrid.tsx - Grid of today's overview metrics (Revenue, Occupancy, ADR, RevPAR, Room Nights, Cancellations)
- AIActionPlan.tsx - AI-generated action plan with priority cards
- RevenuePerformance.tsx - Revenue performance charts
- PickupTrendCalendar.tsx - Booking trend calendar visualization
- CompsetOverview.tsx - Competitor set overview
- CompsetHotels.tsx - List of competitor hotels
- AnimatedAIChat.tsx - Quick AI chat interface for dashboard
- AlertBar.tsx - System alerts and notifications bar
- PropertyDropdown.tsx - Property selector dropdown
- Calendar.tsx - Calendar component for date selection
- AIInsightFeed.tsx - Feed of AI insights
- LiveRateShop.tsx - Live rate shopping interface
Chat Components
Located in src/components/chat/. Components for the AI chat interface.
Components
- ChatHeader.tsx - Chat header with title and actions
- ChatSidebar.tsx - Sidebar showing conversation list
- ChatInput.tsx - Message input component with send button
- MessageBubble.tsx - Individual message bubble component
- TypingIndicator.tsx - Loading/typing indicator for AI responses
Onboarding Components
Located in src/components/onboarding/. Step components for the onboarding flow.
Step Components
- HotelProfileStep.tsx - Step 1: Hotel name, type, rooms, star rating, use cases
- HotelAddressStep.tsx - Step 2: Address and location
- DataSourceStep.tsx - Step 3: Channel manager selection
- TeamAccessStep.tsx - Step 4: Team member invitation
- CompsetSetupStep.tsx - Step 5: Competitor set configuration
- InsightPreferencesStep.tsx - Step 6: AI insight preferences
- PerformanceGoalsStep.tsx - Step 7: Performance targets
- SetupCompleteStep.tsx - Step 8: Completion confirmation
Pricing Components
Located in src/components/pricing/. Configuration components for different pricing rule types.
Rule Configuration Components
- OccupancyBasedConfig.tsx - Occupancy-based rule configuration with bands
- TimeBasedConfig.tsx - Day-of-week/time-based rule configuration
- LengthOfStayConfig.tsx - Length of stay rule configuration
- DemandBasedConfig.tsx - Demand-based rule configuration
- CompetitiveConfig.tsx - Competitive pricing rule configuration
- SeasonalConfig.tsx - Seasonal rule configuration
AI Insights Components
Located in src/components/ai-insights/. Components for AI-powered insights visualization.
Components
- AIInsightsHero.tsx - Hero section for insights page
- AIInsightsShimmer.tsx - Loading shimmer effect
- InteractiveActionPlan.tsx - Interactive action plan with expandable items
- InteractiveMetricsDashboard.tsx - Interactive metrics dashboard with charts
MagicUI Components
Located in src/components/magicui/. Advanced UI components with animations and effects.
Components
- animated-beam.tsx - Animated beam/line effect
- animated-list.tsx - Animated list component
- bento-grid.tsx - Bento grid layout component
- box-reveal.tsx - Box reveal animation component
- calendar.tsx - Enhanced calendar component
- globe.tsx - 3D globe component
- hero-video-dialog.tsx - Video dialog for hero sections
- marquee.tsx - Marquee/scrolling text component
- sign-in-flow.tsx - Sign-in flow component
- sign-up-flow.tsx - Sign-up flow component
Other Components
Additional utility and feature components located in src/components/.
Components
- ProtectedRoute.tsx - Route protection wrapper component
- ErrorBoundary.tsx - Error boundary for catching React errors
- TokenExpirationHandler.tsx - Handles token expiration and redirects
- LoginRedirectIfAuthenticated.tsx - Redirects authenticated users away from login
- AnimatedLogo.tsx - Animated logo component
- LandingHeader.tsx - Header for landing/marketing pages
- HeroSection.tsx - Hero section for landing page
- FeatureSection.tsx - Feature showcase section
- Footer.tsx - Footer component
- ComingSoon.tsx - Coming soon placeholder component
- ROICalculator.tsx - ROI calculator component
- CalendlyWidget.tsx - Calendly integration widget
- EarlyAccessForm.tsx - Early access signup form
- PublicReportFooter.tsx - Footer for public report sharing
API Services Overview
All API services are located in src/api/services/. They handle communication with the backend API and provide typed interfaces for data operations.
Service Pattern:
- All services use the
ApiClientutility for HTTP requests - Services return typed responses with
success,code,message, anddatafields - Error handling is consistent across all services
- Authentication is handled automatically via
AuthService.authenticatedFetch
Auth Service
Location: src/api/services/authService.ts
Methods:
login(credentials)- User login with email/passwordsignUp(userData)- New user registrationstoreUserData(userData)- Store user data in localStoragegetUserData()- Retrieve stored user dataclearUserData()- Clear stored user datavalidateToken()- Validate authentication tokenisTokenExpired()- Check if token is expiredhandleTokenExpiration()- Handle token expiration (redirect to login)authenticatedFetch(url, options)- Fetch with authentication headers
Property Service
Location: src/api/services/propertyService.ts
Methods:
getPropertyList()- Get list of user's propertiesgetPropertyDetails(hId)- Get detailed property informationaddProperty(propertyData)- Add new propertyupdateProperty(hId, propertyData)- Update property detailsupdatePropertyAddress(hId, addressData)- Update property addressupdatePlatformLinks(hId, linksData)- Update OTA/social media linksupdateBusinessGoals(hId, goalsData)- Update business goals
Dashboard Service
Location: src/api/services/dashboardService.ts
Methods:
getTodaysOverview(hId)- Get today's performance metricsgetPerformanceGoals(hId, startDate, endDate)- Get performance goals data
Report Service
Location: src/api/services/reportService.ts
Methods:
getPickupReport(hId, date)- Get pickup report (authenticated)getPickupReportPublic(hotelId, date)- Get pickup report (public, no auth)getPaceReport(hId, startDate, endDate)- Get pace reportgetRevenueDeck(hId, startDate, endDate)- Get revenue deckgetMonthEndSummary(hId, startDate, endDate)- Get month-end summarygetParityReport(hId, startDate, endDate)- Get parity reportgetSegmentSourceReports(hId, startDate, endDate)- Get segment/source reportsgetYearEndReport(hId, startDate, endDate)- Get year-end reportgetWeeklyPerformanceReport(hId)- Get weekly performance report
Chat Service
Location: src/api/services/chatService.ts
Methods:
sendMessage(hId, conversationId, message)- Send chat messagegetChatMessages(hId, conversationId, limit, skip)- Get chat messages with paginationcreateConversation(hId, initialMessage)- Create new conversationgetConversations(hId)- Get list of conversations
Pricing Services
Rule Service
Location: src/api/services/ruleService.ts
Methods:
getRulesOverview(hId)- Get rules statisticsgetRules(hId)- Get all pricing rulesgetRuleById(hId, ruleId)- Get specific rulecreateRule(hId, ruleData)- Create new pricing ruleupdateRule(hId, ruleId, ruleType, ruleData)- Update existing ruledeleteRule(hId, ruleId, ruleType)- Delete pricing rule
AI Pricing Service
Location: src/api/services/aiPricingService.ts
Methods:
getRateSuggestions(hId, startDate, endDate)- Get AI rate suggestions
Other Services
AI Insights Service
Location: src/api/services/aiInsightsService.ts
Methods:
getInsights(hId)- Get AI insightsparseInsights(data)- Parse insights response
Team Service
Location: src/api/services/teamService.ts
Methods:
getTeam()- Get team membersaddMembers(members)- Add team members
Upload Service
Location: src/api/services/uploadService.ts
Methods:
uploadReservations(hId, cmId, file)- Upload reservation data file
CM Service
Location: src/api/services/cmService.ts
Methods:
getCMList()- Get list of channel managers
Compset Service
Location: src/api/services/compsetService.ts
Methods:
getCompsetList(hId)- Get competitor set listaddCompset(hId, compsetData)- Add competitor set
User Preferences Service
Location: src/api/services/userPreferencesService.ts
Methods:
getUserPreferences()- Get user preferencesupdateUserPreferences(preferences)- Update user preferences
API Client
Location: src/api/utils/apiClient.ts
Description: Centralized HTTP client for API requests. All services use this client.
Methods:
get<T>(endpoint)- GET requestpost<T>(endpoint, data)- POST requestput<T>(endpoint, data)- PUT requestdelete<T>(endpoint)- DELETE request
Features:
- Automatic authentication header injection
- Token expiration handling
- Consistent error handling
- TypeScript generics for type safety
Contexts Overview
React Contexts provide global state management for the application. Located in src/contexts/.
Context Pattern:
- Each context has a Provider component that wraps the app
- Custom hooks (e.g.,
useAuth,useProperty) provide easy access - Contexts are initialized in
main.tsx
Auth Context
Location: src/contexts/AuthContext.tsx
Provider: AuthProvider
Hook: useAuth()
State:
isAuthenticated- Boolean indicating auth statususer- User data objectloading- Loading state
Methods:
login(data)- Set user data after loginsignUp(data)- Set user data after signuplogout()- Clear user datacheckTokenExpiration()- Check and handle token expiration
Features:
- Automatic token validation on mount
- Periodic token expiration checks (every 5 minutes)
- Token refresh on tab visibility change
- Persistent user data in localStorage
Property Context
Location: src/contexts/PropertyContext.tsx
Provider: PropertyProvider
Hook: useProperty()
State:
selectedProperty- Currently selected property object
Methods:
setSelectedProperty(property)- Set selected propertyclearSelectedProperty()- Clear selected property
Features:
- Automatic property selection from localStorage
- Auto-selects first property if none selected
- Persistent selection across sessions
Pricing Context
Location: src/contexts/PricingContext.tsx
Provider: PricingProvider
Hook: usePricing()
Description: Manages pricing-related state and operations.
Routing Overview
Location: src/router.tsx
The application uses React Router v7 with createBrowserRouter for route configuration.
Route Categories:
- Public Routes: Home, Login, SignUp, Marketing pages
- Protected Routes: Dashboard, Reports, Pricing, Settings (wrapped in ProtectedRoute)
- Public Report Routes: Shared report links (no auth required)
Route Configuration
Route Structure:
{
path: '/route-path',
element: <Component />,
errorElement: <ErrorPage />
}
Key Routes:
/- Home page/login- Login page/signup- Signup page/onboarding- Onboarding flow/dashboard- Main dashboard/dashboard/chat/:chatID- Chat interface/reports/*- Report pages/pricing/*- Pricing pages/settings- Settings page/team- Team access page/insights- AI insights page
Protected Routes
Component: ProtectedRoute.tsx
Usage:
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
Features:
- Checks authentication status via AuthContext
- Shows loading state while checking auth
- Redirects to
/loginif not authenticated - Validates token expiration
- Handles token expiration redirects
Types Overview
TypeScript type definitions are located in src/types/. They provide type safety across the application.
Chat Types
Location: src/types/chat.ts
export interface Message {
id: string;
text: string;
sender: 'user' | 'ai';
timestamp: Date;
}
export interface ChatCommand {
icon: JSX.Element;
label: string;
description: string;
prefix: string;
}
Pricing Types
Location: src/types/pricing.ts
Key Types:
PricingRule- Complete pricing rule objectPricingRuleType- Union type of rule typesPricingRuleStatus- Rule status ('active' | 'inactive' | 'draft')PricingRateRange- Rate range configurationPricingRuleImpact- Estimated impact of a rulePricingDashboardStats- Dashboard statistics
Socket Types
Location: src/types/socketResponses.ts
Description: Type definitions for Socket.io real-time communication responses.
Utilities Overview
Utility functions and helpers are located in src/utils/ and src/lib/.
Excel Generator
Location: src/utils/excelGenerator.ts
Class: ExcelGenerator
Methods:
generateAIPricingExcel(rateSuggestions, adjustedRates, hotelName)- Generate Excel file for AI pricing data
Features:
- Creates multiple sheets (Summary, Data, Analysis)
- Formatted with colors and styling
- Includes KPIs and insights
- Uses XLSX library
Notifications
Location: src/utils/notifications.mock.ts and src/utils/notifications.conditions.ts
Description: Notification system with mock data and condition checking.
Files:
notifications.mock.ts- Mock notification data and utilitiesnotifications.conditions.ts- Notification condition logicNOTIFICATIONS_DOCUMENTATION.md- Notification system documentation
Lib Utils
Location: src/lib/utils.ts
Function:
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
Description: Utility function for merging TailwindCSS classes using clsx and tailwind-merge.
Usage:
import { cn } from '@/lib/utils';
<div className={cn("base-class", condition && "conditional-class")} />
Styling Overview
The application uses TailwindCSS for styling with custom configuration and global styles.
Styling Approach:
- TailwindCSS: Utility-first CSS framework
- Global Styles:
src/style.cssfor base styles - Component Styles: Inline Tailwind classes
- Dark Theme: Black/dark gray color scheme
Tailwind Configuration
Location: tailwind.config.js
Features:
- Custom color palette
- Path alias support (
@/*) - Animation utilities
- Custom spacing and typography
CSS Structure
Global Styles: src/style.css
Includes:
- TailwindCSS directives (@tailwind base, components, utilities)
- Custom CSS variables
- Base element styles
- Animation definitions
Coding Standards
Naming Conventions
- Components: PascalCase (e.g.,
Dashboard.tsx) - Functions/Variables: camelCase (e.g.,
handleClick) - Constants: UPPER_SNAKE_CASE (e.g.,
API_BASE_URL) - Types/Interfaces: PascalCase (e.g.,
UserData)
File Organization
- One component per file
- Co-locate related files (component + types + styles)
- Use index files for clean imports
Code Style
- Use TypeScript for type safety
- Use functional components with hooks
- Use early returns for cleaner code
- Extract reusable logic into custom hooks
- Use descriptive variable and function names
Component Patterns
Component Structure
// 1. Imports
import React from 'react';
import { ... } from '@/components/...';
// 2. Types/Interfaces
interface ComponentProps {
// props
}
// 3. Component
export const Component: React.FC<ComponentProps> = ({ ... }) => {
// 4. State & Hooks
const [state, setState] = useState();
// 5. Handlers
const handleClick = () => { ... };
// 6. Effects
useEffect(() => { ... }, []);
// 7. Render
return (
// JSX
);
};
export default Component;
Best Practices
- Keep components focused and single-purpose
- Extract complex logic into custom hooks
- Use TypeScript interfaces for props
- Memoize expensive computations
- Use React.memo for expensive components
- Handle loading and error states
Error Handling
Error Boundary
Use ErrorBoundary component to catch React errors:
<ErrorBoundary>
<App />
</ErrorBoundary>
API Error Handling
- All services return consistent error responses
- Handle 401 (unauthorized) with token expiration logic
- Handle 404 (not found) with user-friendly messages
- Handle network errors with retry mechanisms
- Display errors using Toast notifications
Form Validation
- Validate inputs on submit
- Show inline error messages
- Disable submit button during validation
- Use TypeScript for type validation
Performance
Optimization Techniques
- Code Splitting: Use React.lazy() for route-based splitting
- Memoization: Use useMemo() and useCallback() for expensive operations
- Virtual Scrolling: For long lists (chat messages, reports)
- Image Optimization: Lazy load images, use appropriate formats
- Bundle Size: Tree-shake unused code, use dynamic imports
Loading States
- Show loading indicators for async operations
- Use skeleton screens for better UX
- Implement pagination for large datasets
- Cache API responses when appropriate
Monitoring
- Monitor bundle size with build tools
- Use React DevTools Profiler
- Monitor API response times
- Track error rates and user feedback