Skip to content

Latest commit

 

History

History
207 lines (157 loc) · 7.45 KB

File metadata and controls

207 lines (157 loc) · 7.45 KB

WhatsApp Admin Dashboard - Implementation Documentation

Project Overview

The WhatsApp Admin Dashboard is a Streamlit-based web application that provides administrators with a centralized interface to monitor and manage WhatsApp conversations through an Order Management System (OMS). It serves as a bridge between administrators and customers, allowing manual intervention in automated WhatsApp business communications.

Project Structure

OMS-AdminDashboard/
├── app.py              # Main Streamlit application
├── config.py           # Configuration settings and styling
├── utils.py            # API utility functions
├── requirements.txt    # Python dependencies
├── Dockerfile         # Container deployment configuration
├── .dockerignore      # Docker ignore patterns
└── .gitignore         # Git ignore patterns

File-by-File Implementation Details

1. app.py - Main Application Entry Point

Purpose: Core Streamlit application that orchestrates the entire user interface and user interactions.

Key Components:

  • Session State Management: Tracks selected user across page refreshes
  • Connection Status: Real-time server connectivity monitoring
  • Sidebar Interface: User list with search and auto-refresh functionality
  • Chat Interface: Message display and sending functionality
  • Welcome Screen: Landing page when no user is selected

Flow:

  1. Initialize Streamlit page configuration and CSS
  2. Check server connection status
  3. Display sidebar with active users list
  4. Handle user selection and chat interface
  5. Process message sending and refresh cycles

2. config.py - Configuration Management

Purpose: Centralized configuration for API endpoints, UI settings, and styling.

Key Elements:

  • API Configuration: Base URL and vendor ID for OMS server
  • UI Settings: Streamlit page configuration and timezone settings
  • Custom CSS: Dark theme styling for chat interface and overall application

Important Values:

  • API_BASE: Points to Railway-hosted OMS server
  • VENDOR_ID: Specific to "Andhra Ghuma Ghumalu" business
  • CUSTOM_CSS: Comprehensive dark theme with chat bubble styling

3. utils.py - API Integration Layer

Purpose: Handles all communication with the OMS server and data processing.

Core Functions:

get_active_users()

  • Endpoint: GET /admin/users/{VENDOR_ID}
  • Returns: List of users with recent WhatsApp activity
  • Data Structure: [{userId, userName, lastMessage, lastMessageTime, direction}]

get_messages(user_id)

  • Endpoint: GET /admin/messages/{VENDOR_ID}/{user_id}
  • Returns: Complete conversation history for specific user
  • Data Structure: [{message, timestamp, direction}]

send_message(user_id, message)

  • Endpoint: POST /admin/send-message
  • Payload: {vendorId, userId, message}
  • Returns: Boolean success status

test_connection()

  • Endpoint: GET /admin/test-redis
  • Purpose: Health check for server availability

format_timestamp(timestamp_str)

  • Purpose: Converts ISO timestamps to IST HH:MM format
  • Handles: Timezone conversion and error fallback

get_display_name(user_name, user_id)

  • Purpose: Provides fallback display names for users
  • Logic: Uses userName if available, otherwise "User {last4digits}"

4. requirements.txt - Dependencies

Core Dependencies:

  • streamlit: Web application framework
  • requests: HTTP client for API communication
  • pytz: Timezone handling for IST conversion
  • streamlit-autorefresh: Auto-refresh functionality

Application Flow

1. Initialization Flow

app.py starts → Load config.py → Set page config → Apply custom CSS → Initialize session state

2. Main Application Loop

Check connection → Display sidebar → Fetch active users → Handle user selection → Display chat/welcome

3. User Interaction Flow

User clicks contact → Store in session_state → Fetch messages → Display chat → Enable message sending

4. Message Display Flow

get_messages(user_id) → Format timestamps → Build HTML → Escape content → Render with custom CSS

5. Message Sending Flow

User types message → Form submission → send_message() → Success feedback → Refresh interface

API Integration Details

Server Communication

  • Base URL: https://ordermanagementsystem-production-dd4b.up.railway.app
  • Authentication: Vendor ID-based (no tokens required)
  • Timeout: 5 seconds for reads, 15 seconds for message sending
  • Error Handling: Graceful degradation with user feedback

Data Flow

  1. Active Users: Fetched every 10 seconds (if auto-refresh enabled)
  2. Messages: Fetched when user is selected and after sending messages
  3. Connection Test: Performed on app startup and refresh

UI/UX Implementation

Layout Structure

  • Sidebar: Fixed width, scrollable user list with search
  • Main Area: Dynamic content (welcome screen or chat interface)
  • Chat Container: Fixed height with scroll, custom message bubbles

Message Display Logic

# Messages are rendered as HTML with custom CSS classes
if msg['direction'] == 'in':
    # User message (left-aligned, gray background)
    HTML: <div class="message-left"><div class="user-message">...</div></div>
else:
    # Bot message (right-aligned, gray background)
    HTML: <div class="message-right"><div class="bot-message">...</div></div>

State Management

  • selected_user: Maintains current conversation context
  • Auto-refresh: Toggle state for periodic updates
  • Search query: Filters user list in real-time

Deployment Configuration

Docker Setup

  • Base Image: Python 3.9-slim
  • Port: 8501 (Streamlit default)
  • Health Check: Built-in Streamlit health endpoint
  • Environment: Configured for Railway deployment

Production Considerations

  • CORS: Disabled for deployment environment
  • XSRF Protection: Disabled for API integration
  • Headless Mode: Enabled for server deployment

Security & Performance

Security Measures

  • Input Sanitization: HTML escaping for all user messages
  • XSS Prevention: Safe HTML rendering with Streamlit
  • API Timeout: Prevents hanging requests

Performance Optimizations

  • Efficient Rendering: Single HTML block for all messages
  • Minimal API Calls: Strategic refresh timing
  • CSS Optimization: Inline styles for better performance

Error Handling Strategy

Connection Errors

  • Server Unavailable: Clear error message, app stops gracefully
  • Timeout: User-friendly timeout messages
  • API Errors: Generic error handling with fallback empty states

User Experience

  • Loading States: Spinner during message sending
  • Success Feedback: Confirmation messages for actions
  • Graceful Degradation: App continues functioning with limited data

Customization Points

Business Logic

  • Vendor ID: Easily configurable for different businesses
  • Timezone: Configurable for different regions
  • Message Formatting: Customizable timestamp and display formats

UI Theming

  • Color Scheme: Fully customizable through CSS variables
  • Layout: Responsive design with configurable dimensions
  • Branding: Easy to modify titles, icons, and styling

This implementation provides a robust, scalable foundation for WhatsApp business communication management with clear separation of concerns and maintainable architecture.