A NestJS-based WhatsApp chatbot for restaurant order processing with conversational commerce capabilities.
The application follows a modular architecture with clean separation of concerns:
src/
βββ modules/
β βββ conversations/ # Conversation flow and state management
β βββ whatsapp/ # WhatsApp API integration
β βββ orders/ # Order management
β βββ products/ # Product catalog
β βββ customers/ # Customer management
β βββ payments/ # Payment processing
βββ database/ # Database schema and migrations
βββ common/ # Shared utilities and types
βββ scripts/ # Database seeding and migration scripts
The bot uses a state machine with the following states:
- GREETING - Initial welcome with Leo introduction + menu display
- COLLECTING_NAME - Collects customer name for new users
- MAIN_MENU - Shows main menu options (currently unused)
- BROWSING_PRODUCTS - Displays product catalog
- ADDING_TO_CART - Handles product selection and cart operations
- COLLECTING_QUANTITY - Asks for product quantity
- REVIEWING_ORDER - Order review and confirmation
- AWAITING_PAYMENT - Payment processing
- PAYMENT_CONFIRMATION - Payment verification
- ORDER_COMPLETE - Order completion
User: "hello"
Bot: Leo introduction + Full menu display
State: ADDING_TO_CART
User: "1" (selects product)
Bot: Product details + "How many would you like?"
State: COLLECTING_QUANTITY
User: "2" (quantity)
Bot: "Added to cart! Do you want anything else?"
State: ADDING_TO_CART
Location: src/modules/conversations/
Core conversation management with state machine implementation.
conversation-flow.service.ts- Main conversation logic and state handlersconversation.service.ts- High-level conversation orchestrationorder-flow.service.ts- Cart and order management within conversationsinput-parser.service.ts- User input parsing and validationconversation-session.service.ts- Redis-based session management
conversation.types.ts- Core conversation interfaces and enumsstate-machine.types.ts- State machine configuration and context keys
Location: src/modules/whatsapp/
WhatsApp Business API integration using Twilio.
whatsapp-webhook.controller.ts- Webhook endpoint for incoming messageswhatsapp-message.service.ts- Outgoing message sending (with dev mode)message-processing.service.ts- Message parsing and routing
- Development Mode: Set
WHATSAPP_DEV_MODE=trueto log messages instead of sending - Rate Limit Handling: Automatically switches to dev mode when Twilio limits are hit
- Message Validation: Input validation and error handling
Location: src/modules/orders/
Order management and processing.
orders.service.ts- Order CRUD operations and business logicorders.repository.ts- Database operations for orders
Location: src/modules/products/
Product catalog management.
products.service.ts- Product business logicproducts.repository.ts- Database operations for products
findAvailableProducts()- Gets all available productssearchProducts()- Product search functionalityisProductAvailable()- Stock availability check
Location: src/modules/customers/
Customer management and recognition.
- Customer Recognition: Remembers returning customers by phone number
- Name Collection: Collects and stores customer names
- Personalized Greetings: Time-based personalized messages
Using Drizzle ORM with PostgreSQL.
- customers - Customer information and phone numbers
- products - Product catalog with pricing and availability
- orders - Order records and status
- order_items - Individual items within orders
- payments - Payment records and verification
scripts/seed-database.ts- Seeds sample productsscripts/migrate.ts- Runs database migrations
# Environment
NODE_ENV=development
PORT=4000
# Database (Supabase)
DATABASE_URL=postgresql://postgres:password@db.project.supabase.co:5432/postgres
# Redis
REDIS_HOST=localhost
REDIS_PORT=6379
# WhatsApp (Twilio)
TWILIO_ACCOUNT_SID=your_account_sid
TWILIO_AUTH_TOKEN=your_auth_token
TWILIO_WHATSAPP_NUMBER=whatsapp:+14155238886
WHATSAPP_WEBHOOK_VERIFY_TOKEN=your_verify_token
# Development Mode
WHATSAPP_DEV_MODE=true # Set to true for development
# Business Settings
BUSINESS_NAME=Chicken Republic Restaurant
TAX_RATE=0.08
PAYMENT_TIMEOUT_MINUTES=30- Node.js 18+
- PostgreSQL database (or Supabase)
- Redis server
- Twilio WhatsApp Business account
# Install dependencies
npm install
# Set up environment
cp .env.example .env
# Edit .env with your credentials
# Run database migrations
npm run db:migrate
# Seed sample products
npm run db:seed
# Start development server
npm run start:devFor development without hitting Twilio rate limits:
# Enable dev mode in .env
WHATSAPP_DEV_MODE=true
# Messages will be logged to console instead of sent- Leo Bot Introduction: Friendly greeting with restaurant branding
- Product Menu Display: Categorized product listing with prices
- Product Selection: Both number (1,2,3) and name selection
- Quantity Collection: Asks for quantity before adding to cart
- Cart Management: Add, view, and manage cart items
- Customer Recognition: Remembers returning customers
- Browsing Mode: "Just browsing" option for window shoppers
- Development Mode: Console logging for development
- Rate Limit Handling: Graceful handling of Twilio limits
- Restart Capability: "hello/hi" restarts conversation anytime
- Order Review State: Complete order review functionality
- Payment Processing: Payment instruction generation
- Payment Verification: Payment confirmation handling
- Receipt Generation: Digital receipt creation
- Order Completion: Final order completion flow
- Sessions stored in Redis with phone number as key
- Context preserved across conversation states
- Automatic session cleanup and expiration
- Graceful fallbacks for service failures
- User-friendly error messages
- Comprehensive logging for debugging
- Unit tests for core services
- Integration tests for order flow
- Mock services for external dependencies
- Redis caching for session data
- Database connection pooling
- Efficient product queries
- Complete Order Review State - Implement
handleReviewingOrderState() - Payment Flow Integration - Connect with payment service
- Receipt Generation - Implement digital receipt creation
- Error Recovery - Enhanced error handling and recovery
- Admin Dashboard - Product and order management
- Analytics - Conversation and sales analytics
- Multi-language Support - Localization capabilities
- Advanced Cart Features - Modify quantities, remove items
- Delivery Integration - Delivery tracking and notifications
- Database Connection: Check DATABASE_URL and network connectivity
- Twilio Rate Limits: Enable WHATSAPP_DEV_MODE for development
- Redis Connection: Ensure Redis server is running
- Product Not Found: Check if products are seeded in database
# Enable detailed logging
NODE_ENV=development
# Check application logs for detailed error informationBuilt with β€οΈ for Chicken Republic Restaurant