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

  1. Clone the repository:
    git clone [repository-url]
    cd knowmyhotel
  2. Install dependencies:
    npm install
  3. Environment Variables:

    Create a .env file in the root directory:

    VITE_API_BASE_URL=http://localhost:5001/api
  4. Run development server:
    npm run dev
  5. 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:

  1. Basic Information (name, description, priority, status)
  2. Rate Range (min, base, max rates)
  3. Rule-Specific Conditions (varies by rule type)
  4. 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:

  1. HotelProfileStep - Basic hotel information
  2. HotelAddressStep - Address and location
  3. DataSourceStep - Channel manager selection
  4. TeamAccessStep - Team member invitation
  5. CompsetSetupStep - Competitor set configuration
  6. InsightPreferencesStep - AI insight preferences
  7. PerformanceGoalsStep - Performance targets
  8. 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 components
  • chat/ - Chat interface components
  • onboarding/ - Onboarding flow components
  • pricing/ - Pricing rule configuration components
  • ai-insights/ - AI insights visualization components
  • magicui/ - 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 ApiClient utility for HTTP requests
  • Services return typed responses with success, code, message, and data fields
  • 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/password
  • signUp(userData) - New user registration
  • storeUserData(userData) - Store user data in localStorage
  • getUserData() - Retrieve stored user data
  • clearUserData() - Clear stored user data
  • validateToken() - Validate authentication token
  • isTokenExpired() - Check if token is expired
  • handleTokenExpiration() - 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 properties
  • getPropertyDetails(hId) - Get detailed property information
  • addProperty(propertyData) - Add new property
  • updateProperty(hId, propertyData) - Update property details
  • updatePropertyAddress(hId, addressData) - Update property address
  • updatePlatformLinks(hId, linksData) - Update OTA/social media links
  • updateBusinessGoals(hId, goalsData) - Update business goals

Dashboard Service

Location: src/api/services/dashboardService.ts

Methods:

  • getTodaysOverview(hId) - Get today's performance metrics
  • getPerformanceGoals(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 report
  • getRevenueDeck(hId, startDate, endDate) - Get revenue deck
  • getMonthEndSummary(hId, startDate, endDate) - Get month-end summary
  • getParityReport(hId, startDate, endDate) - Get parity report
  • getSegmentSourceReports(hId, startDate, endDate) - Get segment/source reports
  • getYearEndReport(hId, startDate, endDate) - Get year-end report
  • getWeeklyPerformanceReport(hId) - Get weekly performance report

Chat Service

Location: src/api/services/chatService.ts

Methods:

  • sendMessage(hId, conversationId, message) - Send chat message
  • getChatMessages(hId, conversationId, limit, skip) - Get chat messages with pagination
  • createConversation(hId, initialMessage) - Create new conversation
  • getConversations(hId) - Get list of conversations

Pricing Services

Rule Service

Location: src/api/services/ruleService.ts

Methods:

  • getRulesOverview(hId) - Get rules statistics
  • getRules(hId) - Get all pricing rules
  • getRuleById(hId, ruleId) - Get specific rule
  • createRule(hId, ruleData) - Create new pricing rule
  • updateRule(hId, ruleId, ruleType, ruleData) - Update existing rule
  • deleteRule(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 insights
  • parseInsights(data) - Parse insights response

Team Service

Location: src/api/services/teamService.ts

Methods:

  • getTeam() - Get team members
  • addMembers(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 list
  • addCompset(hId, compsetData) - Add competitor set

User Preferences Service

Location: src/api/services/userPreferencesService.ts

Methods:

  • getUserPreferences() - Get user preferences
  • updateUserPreferences(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 request
  • post<T>(endpoint, data) - POST request
  • put<T>(endpoint, data) - PUT request
  • delete<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 status
  • user - User data object
  • loading - Loading state

Methods:

  • login(data) - Set user data after login
  • signUp(data) - Set user data after signup
  • logout() - Clear user data
  • checkTokenExpiration() - 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 property
  • clearSelectedProperty() - 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 /login if 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 object
  • PricingRuleType - Union type of rule types
  • PricingRuleStatus - Rule status ('active' | 'inactive' | 'draft')
  • PricingRateRange - Rate range configuration
  • PricingRuleImpact - Estimated impact of a rule
  • PricingDashboardStats - 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 utilities
  • notifications.conditions.ts - Notification condition logic
  • NOTIFICATIONS_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.css for 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

Backend Overview

The KnowMyHotel Backend is a Node.js/Express.js REST API server that powers the entire platform. It handles authentication, data management, AI agent interactions, report generation, and real-time communication via WebSockets.

Key Backend Features

  • RESTful API: Express.js-based API with organized route structure
  • Authentication: JWT-based authentication with encrypted payloads
  • Database: MongoDB with Mongoose ODM
  • Real-time: Socket.io for live chat and notifications
  • AI Integration: LangChain for conversational AI
  • Scheduled Tasks: Node-cron for automated report generation
  • File Processing: Excel/CSV upload and processing
  • Email Service: SendGrid integration for notifications

Backend Architecture

Application Structure

The backend follows a layered architecture pattern:

  • Routes Layer: Express routes that define API endpoints
  • Controllers Layer: Business logic and request handling
  • Models Layer: Mongoose schemas for data structure
  • Middleware Layer: Authentication, validation, and custom middleware
  • Helpers/Utils: Reusable utility functions

Request Flow

Client Request → Express Middleware → Route → Controller → Model → Database
                ↓
            Response ← Controller ← Model ← Database

Server Components

  • HTTP Server: Express.js application
  • WebSocket Server: Socket.io for real-time communication
  • Database: MongoDB connection via Mongoose
  • Cron Jobs: Scheduled tasks for automated operations

Backend Setup & Installation

Prerequisites

  • Node.js 18+ and npm
  • MongoDB database (local or cloud)
  • Git
  • Code editor (VS Code recommended)

Installation Steps

  1. Clone the repository:
    git clone [repository-url]
    cd know-my-hotel-BE
  2. Install dependencies:
    npm install
  3. Environment Variables:

    Create a .env file in the root directory:

    PORT=3000
    MONGODB_URI=mongodb://localhost:27017/knowmyhotel
    ACCESS_TOKEN_SECRET=your-secret-key
    ACCESS_TOKEN_TIMEOUT_DURATION=24h
    ENCRYPTION_KEY=your-encryption-key
    ENCRYPTION_SALT=your-salt-hex
    ALGORITHM=aes-256-cbc
    SENDGRID_API_KEY=your-sendgrid-key
  4. Run development server:
    npm run dev
  5. Run production server:
    npm start

Backend Tech Stack

Core Technologies

  • Node.js: JavaScript runtime
  • Express.js 5.1.0: Web framework
  • MongoDB: NoSQL database
  • Mongoose 8.15.0: MongoDB ODM

Key Libraries

  • Socket.io 4.8.1: Real-time WebSocket communication
  • jsonwebtoken 9.0.2: JWT authentication
  • bcrypt 6.0.0: Password hashing
  • LangChain 0.3.30: LLM framework
  • @langchain/langgraph 0.4.0: AI agent orchestration
  • @langchain/google-genai 0.2.16: Google AI integration
  • node-cron 4.2.1: Scheduled task execution
  • multer 2.0.1: File upload handling
  • exceljs 4.4.0: Excel file generation
  • xlsx 0.18.5: Excel file parsing
  • @sendgrid/mail 8.1.5: Email service
  • axios 1.9.0: HTTP client
  • cheerio 1.1.0: HTML parsing
  • aws-sdk 2.1692.0: AWS services integration
  • zod 3.25.76: Schema validation

Development Tools

  • nodemon 3.1.10: Development server with auto-reload
  • morgan 1.10.0: HTTP request logger
  • cors 2.8.5: Cross-origin resource sharing
  • dotenv 16.5.0: Environment variable management

Backend Folder Structure

know-my-hotel-BE/
├── config/
│   └── db.js                   # MongoDB connection configuration
├── controllers/                # Business logic controllers
│   ├── agent/                  # AI agent controllers
│   │   ├── chats/              # Chat-related controllers
│   │   ├── tools/              # Agent tools (functions)
│   │   └── graph/              # LangGraph configuration
│   ├── compset/                # Competitor set controllers
│   ├── dashboard/              # Dashboard data controllers
│   ├── dynamicRates/           # Dynamic pricing controllers
│   │   └── dynamicRateRule/    # Pricing rule CRUD operations
│   ├── internal/               # Internal/admin controllers
│   ├── onboarding/             # User onboarding controllers
│   │   └── team/               # Team management
│   ├── performanceGoals/       # Performance goals controllers
│   ├── property/               # Property management controllers
│   ├── rateshop/               # Rate shopping controllers
│   ├── reports/                # Report generation controllers
│   │   ├── admin/              # Admin report operations
│   │   ├── publicReport/       # Public report endpoints
│   │   └── reportExcelFormat/  # Excel report formatters
│   ├── scheduler/              # Cron job controllers
│   └── settings/               # Settings controllers
├── helper/                     # Helper functions
│   ├── helperFunc.js           # General helper functions
│   └── occupancy.js            # Occupancy calculation helpers
├── middleware/                 # Express middleware
│   ├── authFunc.js             # Authentication middleware
│   └── custom.js               # Custom middleware
├── models/                     # Mongoose models
│   ├── dynamicRates/           # Dynamic rate models
│   └── ota/                    # OTA-related models
├── routes/                     # Express route definitions
├── utils/                      # Utility functions
│   ├── imageUpload.js          # Image upload utilities
│   ├── templates.js            # Email/template utilities
│   ├── timePeriodFuncs.js      # Date/time utilities
│   └── whatsAppFunc.js         # WhatsApp integration
├── server.js                   # Application entry point
├── package.json                # Dependencies
└── .env                        # Environment variables

Backend File Organization

Naming Conventions

  • Routes: camelCase with "Routes" suffix (e.g., `userRoutes.js`, `propertyRoutes.js`)
  • Controllers: camelCase (e.g., `login.js`, `addProperty.js`)
  • Models: camelCase with "Model" suffix (e.g., `userModel.js`, `propertiesModel.js`)
  • Middleware: camelCase (e.g., `authFunc.js`, `custom.js`)
  • Helpers/Utils: camelCase (e.g., `helperFunc.js`, `timePeriodFuncs.js`)

Controller Structure

Each controller typically follows this structure:

// Imports
import { responseFun } from "../../helper/helperFunc.js";
import { verifyJwt } from "../../middleware/authFunc.js";
import Model from "../../models/model.js";

// Controller function
const controllerName = async (req, res) => {
    try {
        // Extract data from request
        const { data } = req.body;
        const { id } = req.params;
        const authData = req.authData; // From verifyJwt middleware
        
        // Business logic
        // Database operations
        
        // Return response
        return responseFun(res, true, 200, 'Success message', data);
    } catch (error) {
        console.log('error: ', error);
        return responseFun(res, false, 500, error.message);
    }
};

export default controllerName;

Route Structure

import e from "express";
const route = e.Router();
import { verifyJwt } from "../middleware/authFunc.js";
import controller from "../controllers/controller.js";

// Define routes
route.get('/endpoint', verifyJwt, controller);
route.post('/endpoint', verifyJwt, controller);
route.patch('/endpoint/:id', verifyJwt, controller);
route.delete('/endpoint/:id', verifyJwt, controller);

export default route;

Backend Routes Overview

All API routes are organized by feature area and mounted under the /api prefix in server.js.

Route Organization:

  • /api/user - User authentication and management
  • /api/property - Property management and operations
  • /api/dashboard - Dashboard data endpoints
  • /api/report - Report generation endpoints
  • /api/agent - AI agent chat endpoints
  • /api/dynamicRate - Dynamic pricing rule endpoints
  • /api/compset - Competitor set endpoints
  • /api/setting - Settings endpoints
  • /api/internal - Internal/admin endpoints

User Routes

Location: routes/userRoutes.js

Base Path: /api/user

Endpoints

  • POST /api/user/signUp - User registration
  • POST /api/user/login - User login
  • POST /api/user/earlyAccess - Early access signup
  • GET /api/user/earlyAccess - Get early access list
  • PATCH /api/user/updateUser - Update user details (protected)
  • POST /api/user/addMember - Add team member (protected)
  • GET /api/user/getTeam - Get team members (protected)
  • GET /api/user/getUser - Get user details (protected)

Property Routes

Location: routes/propertyRoutes.js

Base Path: /api/property

Endpoints

  • POST /api/property/addProperty - Add new property (protected)
  • PATCH /api/property/updateProperty - Update property (protected)
  • PATCH /api/property/addOta - Add OTA links (protected)
  • GET /api/property/cmList - Get channel manager list (protected)
  • GET /api/property/fetchOtaLinks/:hId - Fetch OTA links (protected)
  • GET /api/property/getOtaLinks/:hId - Get verified OTA links (protected)
  • POST /api/property/uploadReservationsData - Upload reservation data (protected)
  • GET /api/property/compsetOverview/:hId - Get compset overview (protected)
  • GET /api/property/propertyList - Get property list (protected)
  • GET /api/property/property/:hId - Get property details (protected)
  • POST /api/property/getHotelDetails/:hId - Get hotel details via link (protected)
  • GET /api/property/rs/liveRateShop/:hId - Live rate shop (protected)
  • POST /api/property/rs/requestRateShop/:hId - Request rate shop (protected)
  • GET /api/property/getInsights/:hId - Get AI insights (protected)
  • POST /api/property/updateStage/:hId - Update property stage

Nested Routes

  • /api/property/compset/* - Compset routes (see compset routes section)

Dashboard Routes

Location: routes/dashboardRoutes.js

Base Path: /api/dashboard

Endpoints

  • GET /api/dashboard/todaysOverview - Get today's overview metrics (protected)
  • GET /api/dashboard/revenueOverview - Get revenue performance (protected)
  • GET /api/dashboard/pickupTrend - Get pickup trends (protected)
  • GET /api/dashboard/performanceGoal - Get performance goals (protected)
  • GET /api/dashboard/propertyInfo/:hId - Get property info (protected)
  • GET /api/dashboard/rateSuggestion/:hId - Get rate suggestions (protected)

Report Routes

Location: routes/reportRoutes.js

Base Path: /api/report

Authenticated Endpoints

  • GET /api/report/paceReport - Get pace report (protected)
  • GET /api/report/monthEndReport - Get month-end report (protected)
  • GET /api/report/pickupReport - Get pickup report (protected)
  • GET /api/report/parityReport - Get parity report (protected)
  • GET /api/report/sourceReport - Get source report (protected)
  • GET /api/report/yearEndReport - Get year-end report (protected)
  • GET /api/report/revenueDeck/:hId - Get revenue deck (protected)
  • GET /api/report/weeklyReport - Get weekly report (protected)

Admin Endpoints

  • GET /api/report/sendingAllMonthEndReports - Send all month-end reports (protected)
  • GET /api/report/sendingAllPickUpReports - Send all pickup reports (protected)
  • GET /api/report/sendingAllWeeklyReports - Send all weekly reports (protected)

Public Endpoints

These endpoints don't require authentication and are used for sharing reports:

  • GET /api/report/monthEndReport/:hId - Public month-end report
  • GET /api/report/pickupReport/:hId - Public pickup report
  • GET /api/report/paceReport/:hId - Public pace report
  • GET /api/report/parityReport/:hId - Public parity report
  • GET /api/report/sourceReport/:hId - Public source report
  • GET /api/report/yearEndReport/:hId - Public year-end report
  • GET /api/report/weeklyReport/:hId - Public weekly report

Agent Routes

Location: routes/agentRoute.js

Base Path: /api/agent

Endpoints

  • POST /api/agent/chat/:hId - Create new chat conversation (protected)
  • POST /api/agent/chat/:hId/:conversationId - Continue existing conversation (protected)

Note: Real-time chat communication is handled via Socket.io, not HTTP endpoints.

Dynamic Rate Routes

Location: routes/dynamicRateRoutes.js

Base Path: /api/dynamicRate

Endpoints

  • POST /api/dynamicRate/addRule - Add dynamic rate rule (protected)
  • GET /api/dynamicRate/getRule/:hId - Get all rules for property (protected)
  • PATCH /api/dynamicRate/updateRule/:hId/:id - Update rule (protected)
  • DELETE /api/dynamicRate/deleteRule/:hId/:id - Delete rule (protected)
  • GET /api/dynamicRate/rulesOverview/:hId - Get rules dashboard overview (protected)
  • GET /api/dynamicRate/pricingCalender/:hId - Get pricing calendar (protected)

Compset Routes

Location: routes/compsetRoutes.js

Base Path: /api/property/compset (nested under property routes)

Endpoints

  • GET /api/property/compset/getCompset/:hId - Get compset list (protected)
  • POST /api/property/compset/addCompset/:hId - Add compset (protected)
  • PATCH /api/property/compset/updateCompset/:hId - Update compset (protected)
  • GET /api/property/compset/getAllCompsetRates/:hId - Get all compset rates (protected)
  • GET /api/property/compset/compsetSuggestions/:hId - Get compset suggestions (protected)
  • GET /api/property/compset/marketAlertNPerformance/:hId - Get market alerts (protected)

Setting Routes

Location: routes/settingRoutes.js

Base Path: /api/setting

Endpoints

  • PATCH /api/setting/updateProperty/:hId - Update property settings (protected)

Internal Routes

Location: routes/internal.js

Base Path: /api/internal

Endpoints

Internal routes are used for admin operations and system integrations:

  • POST /api/internal/addSuggestedRates - Add suggested rates (internal)
  • POST /api/internal/updateInventory - Update inventory (internal)

Backend Controllers Overview

Controllers contain the business logic for handling requests. They are organized by feature area in the controllers/ directory.

Controller Pattern:

  • Controllers are async functions that receive req and res objects
  • They extract data from request body, params, or query
  • They perform business logic and database operations
  • They return responses using the responseFun helper
  • All errors are caught and handled in try-catch blocks

Onboarding Controllers

Location: controllers/onboarding/

Key Controllers

  • signUp.js - User registration
  • login.js - User authentication
  • updateUser.js - Update user profile
  • getUserDetails.js - Get user information
  • earlyAccess.js - Early access signup
  • getEarlyAccess.js - Get early access list
  • uploadReservationsData.js - Upload reservation data file
  • team/addMember.js - Add team member
  • team/getTeam.js - Get team members list

Property Controllers

Location: controllers/property/

Key Controllers

  • addProperty.js - Create new property
  • updateProperty.js - Update property details
  • getProperty.js - Get property information
  • propertyList.js - Get user's property list
  • addOta.js - Add OTA links
  • cmList.js - Get channel manager list
  • fetchLinks.js - Fetch OTA links from URLs
  • getLinks.js - Get verified OTA links
  • getHotelDetailsViaLink.js - Scrape hotel details from OTA
  • updatePropertyStage.js - Update onboarding stage

Dashboard Controllers

Location: controllers/dashboard/

Key Controllers

  • todaysOverview.js - Today's performance metrics
  • revenuePerformance.js - Revenue performance data
  • pickupTrend.js - Booking pickup trends
  • propertyInfo.js - Property information
  • rateSuggestion.js - AI rate suggestions
  • compsetOverview.js - Competitor set overview

Report Controllers

Location: controllers/reports/

Report Types

  • pickupReport.js - Daily pickup report
  • paceReport.js - Booking pace analysis
  • monthEndReport.js - Monthly summary
  • yearEndReport.js - Annual summary
  • parityReport.js - Rate parity analysis
  • sourceReport.js - Segment/source analysis
  • revenueDeckReport.js - Revenue deck
  • weeklyReport.js - Weekly performance

Public Report Controllers

Location: controllers/reports/publicReport/

Public versions of reports that don't require authentication for sharing.

Admin Report Controllers

Location: controllers/reports/admin/

  • sendingAllMonthEndReport.js - Send all month-end reports
  • sendingAllPickUpReports.js - Send all pickup reports
  • sendingAllWeeklyReports.js - Send all weekly reports

Excel Format Controllers

Location: controllers/reports/reportExcelFormat/

Controllers for generating Excel-formatted reports.

Agent Controllers

Location: controllers/agent/

Key Controllers

  • index.js - Main agent chat controller
  • run.js - Agent execution logic
  • agent.js - Agent configuration
  • insightsGenerator.js - AI insights generation
  • validator.js - Input validation
  • formatters.js - Response formatting
  • embedBatch.js - Batch embedding operations

Chat Controllers

Location: controllers/agent/chats/

  • getChat.js - Socket.io chat handlers
  • getConversation.js - Conversation retrieval

Agent Tools

Location: controllers/agent/tools/

Functions that the AI agent can call:

  • getPropertyInfo.js - Get property information
  • getRates.js - Get current rates
  • getReservation.js - Get reservation data
  • getCheckIn.js - Get check-in data
  • getCheckOut.js - Get check-out data
  • occupancyTool.js - Occupancy calculations
  • monthEndReportTool.js - Month-end report generation
  • vectorSearch.js - Vector database search
  • userInfo.js - User information

Graph Configuration

Location: controllers/agent/graph/

  • buildGraph.js - LangGraph graph builder
  • nodes.js - Graph node definitions

Dynamic Rate Controllers

Location: controllers/dynamicRates/

Key Controllers

  • dashboardOverview.js - Rules dashboard overview
  • pricingCalendar.js - Pricing calendar data

Rule Controllers

Location: controllers/dynamicRates/dynamicRateRule/

  • addDynamicRateRule.js - Create new pricing rule
  • getDynamicRateRule.js - Get all rules
  • updateDynamicRateRule.js - Update existing rule
  • deleteDynamicRateRule.js - Delete rule
  • generateRule.js - Generate rule from template

Compset Controllers

Location: controllers/compset/

Key Controllers

  • getCompset.js - Get compset list
  • updateCompset.js - Update compset
  • getAllCompsetRates.js - Get all compset rates
  • compsetSuggestions.js - Get compset suggestions
  • marketAlertNPerformance.js - Market alerts and performance

Scheduler Controllers

Location: controllers/scheduler/

These controllers are executed by cron jobs for automated tasks.

Key Controllers

  • cronJob.js - Main cron job scheduler
  • pickUp.js - Daily pickup report generation
  • weeklyReport.js - Weekly report generation
  • dynamicRates.js - Dynamic rate rule execution

Backend Models Overview

Models define the database schema using Mongoose. They are located in the models/ directory.

Model Pattern:

  • Models use Mongoose Schema to define structure
  • Each model exports a Mongoose model instance
  • Models include validation, defaults, and indexes
  • Timestamps are enabled by default

User Model

Location: models/userModel.js

Collection: users

Key Fields

  • userId - Unique user identifier
  • name - User name
  • email - Email address (unique, required)
  • password - Hashed password
  • phoneNumber - Phone number
  • userType - User type (Trial, Subscriber, etc.)
  • role - User role
  • teamId - Team identifier
  • onboarding - Onboarding status object
  • preferences - User preferences

Property Model

Location: models/propertiesModel.js

Collection: properties

Key Fields

  • hId - Hotel identifier (unique, required)
  • users - Array of user IDs with access
  • name - Property name
  • type - Property type
  • address - Address object (latitude, longitude, city, state, country, fullAddress)
  • totalRooms - Total number of rooms
  • starRating - Star rating
  • activeOta - Array of active OTA links
  • compsets - Array of competitor set IDs
  • socialMedia - Social media links object
  • bussinessGoals - Business goals object
  • propertyStage - Onboarding stage object
  • currencyCode - Currency code (default: INR)

Reservation Model

Location: models/reservations.js

Description: Stores reservation/booking data from channel managers.

Dynamic Rate Models

Location: models/dynamicRates/

Models

  • dynamicRateRulesModel.js - Pricing rule definitions
  • dynamicRates.js - Applied rate data

OTA Models

Location: models/ota/

Models

  • ota.js - OTA platform information
  • otaLinks.js - OTA property links
  • otaRates.js - OTA rate data
  • otaReviews.js - OTA review data
  • otaReputation.js - OTA reputation scores
  • liveInventory.js - Live inventory data

Other Models

Additional models in the system:

  • conversation.js - AI chat conversations
  • messagesModel.js - Chat messages
  • embeddingModel.js - Vector embeddings for search
  • insightsModel.js - AI-generated insights
  • reportsInsight.js - Report insights
  • suggestedRates.js - AI-suggested rates
  • suggestedCompset.js - Suggested competitor sets
  • rateShopModel.js - Rate shopping data
  • channelManager.js - Channel manager information
  • cmDetail.js - Channel manager details
  • propertyInventory.js - Property inventory data
  • hotelLastModified.js - Last modification tracking
  • currency.js - Currency information
  • earlyAccessUser.js - Early access users
  • verifiedProperty.js - Verified properties
  • verifiedUserModel.js - Verified users

Backend Middleware Overview

Middleware functions are executed before route handlers. They are located in the middleware/ directory.

Middleware Types:

  • Authentication: Verify JWT tokens
  • Validation: Validate request data
  • Error Handling: Catch and format errors
  • Custom: Application-specific middleware

Authentication Middleware

Location: middleware/authFunc.js

Key Functions

  • signJwt(payloadData) - Generate JWT token with encrypted payload
  • verifyJwt(req, res, next) - Express middleware for JWT verification
  • validateToken(token) - Validate and decode JWT token
  • invalidateToken(token) - Add token to blacklist
  • socketAuthWithValidate() - Socket.io authentication middleware

Authentication Flow

  1. User logs in with email/password
  2. Server validates credentials
  3. Server encrypts user data and signs JWT
  4. JWT token returned to client
  5. Client includes token in Authorization header
  6. Middleware decrypts and validates token
  7. Request proceeds with authenticated user data

Token Encryption

User data in JWT tokens is encrypted using AES-256-CBC before signing. This provides an additional layer of security.

Custom Middleware

Location: middleware/custom.js

Application-specific middleware functions.

Backend Helpers & Utils Overview

Helper functions and utilities are located in helper/ and utils/ directories.

Helper Functions

Location: helper/

Files

  • helperFunc.js - General helper functions
    • responseFun(res, success, code, message, data) - Standardized API response
  • occupancy.js - Occupancy calculation helpers

Utils Functions

Location: utils/

Files

  • imageUpload.js - Image upload utilities (AWS S3 integration)
  • templates.js - Email template utilities
  • timePeriodFuncs.js - Date and time period calculation functions
  • whatsAppFunc.js - WhatsApp integration utilities

Backend Database Overview

The backend uses MongoDB as the primary database with Mongoose as the ODM (Object Document Mapper).

Database Features

  • NoSQL: Document-based database
  • Schema Validation: Mongoose schemas enforce data structure
  • Indexes: Optimized queries with indexes
  • Relationships: References and embedded documents
  • Aggregations: Complex data processing with aggregation pipeline

Database Configuration

Location: config/db.js

The database connection is configured using environment variables:

MONGODB_URI=mongodb://localhost:27017/knowmyhotel
// or for cloud:
MONGODB_URI=mongodb+srv://user:password@cluster.mongodb.net/knowmyhotel

Database Connection

The database connection is established in server.js using the connectDB() function from config/db.js.

Connection Features:

  • Automatic connection on server start
  • Error handling with process exit on failure
  • Connection logging for debugging
  • Mongoose connection options for compatibility