# 📊 Call Analytics Dashboard - Complete System

A modern, full-stack call analytics platform with AI-powered insights, sentiment analysis, and comprehensive call management.

![React](https://img.shields.io/badge/React-18.3-blue) ![Flask](https://img.shields.io/badge/Flask-3.0-green) ![Python](https://img.shields.io/badge/Python-3.8+-yellow) ![MySQL](https://img.shields.io/badge/MySQL-8.0-orange)

## 🎯 Overview

This system provides a complete solution for post-call analysis, including:
- **React Dashboard** - Modern, responsive UI with dark mode
- **Flask REST API** - Scalable backend with comprehensive endpoints
- **AI Integration** - Sarvam AI transcription + AWS Bedrock analysis
- **Real-time Analytics** - Sentiment, intent, and performance metrics
- **Multi-tenant Support** - Business selector with isolated data

## 📁 Project Structure

```
/var/www/html/sara/
├── dashboard-frontend/          # React Dashboard
│   ├── src/
│   │   ├── components/         # React components
│   │   ├── pages/              # Page components
│   │   ├── services/           # API integration
│   │   └── App.jsx             # Main app
│   ├── package.json
│   └── README.md
│
├── dashboard-backend/           # Flask API
│   ├── app.py                  # Main application
│   ├── db_handler.py           # Database operations
│   ├── analytics.py            # Analytics service
│   ├── config.py               # Configuration
│   ├── requirements.txt
│   └── README.md
│
└── post call analysis/          # Existing processing system
    ├── app.py                  # Original Flask app (port 4567)
    ├── sarvam_processor.py     # Audio transcription
    └── audio_job_consumer.py   # RabbitMQ consumer
```

## 🚀 Quick Start - Full Stack

### 1. Backend Setup
```bash
cd dashboard-backend

# Create virtual environment
python3 -m venv venv
source venv/bin/activate

# Install dependencies
pip install -r requirements.txt

# Configure environment
cp .env.example .env
# Edit .env with your database credentials

# Start backend
python app.py
# Running at: http://localhost:5000
```

### 2. Frontend Setup
```bash
cd dashboard-frontend

# Install dependencies
npm install

# Start development server
npm run dev
# Running at: http://localhost:5173
```

### 3. Access Dashboard
Open browser: **http://localhost:5173**

Default view uses mock data - ready to explore immediately!

## 🔗 System Architecture

```
┌─────────────────┐
│  React Frontend │ :5173
│  (Vite + React) │
└────────┬────────┘
         │ HTTP/REST
         ▼
┌─────────────────┐
│  Flask API      │ :5000
│  (Dashboard)    │
└────────┬────────┘
         │ SQL
         ▼
┌─────────────────┐       ┌──────────────────┐
│  MySQL Database │◄──────┤ Flask Processor  │ :4567
│  voicebot_cluster│       │ (Existing System)│
└─────────────────┘       └────────┬─────────┘
                                   │
                          ┌────────┴──────────┐
                          │                   │
                     Sarvam AI          AWS Bedrock
                     (Transcribe)       (Analysis)
```

## 📊 Features Breakdown

### Frontend Dashboard
✅ **Dashboard Overview**
- Real-time KPI metrics (Total Calls, Processed, Pending, Messages)
- Interactive charts (Sentiment pie chart, Intent bar chart)
- Recent calls table with quick actions
- Success rate and average duration tracking

✅ **Calls Management**
- Advanced filtering (Status, Intent, Date Range)
- Search by Call ID, Customer, or Agent
- Export to CSV functionality
- Detailed call view with full transcript
- Keywords and emotions visualization

✅ **Analytics**
- Sentiment distribution (Positive/Neutral/Negative)
- Sales intent classification (High/Medium/Low)
- Trend analysis over time
- Agent performance metrics

✅ **Modern UI/UX**
- Dark mode with localStorage persistence
- Fully responsive (Mobile/Tablet/Desktop)
- Smooth animations and transitions
- Professional color scheme

### Backend API
✅ **20+ REST Endpoints**
- Business management
- Call CRUD operations
- Advanced search and filtering
- Analytics and statistics
- Data export (JSON/CSV)
- Webhook support

✅ **Database Integration**
- Dynamic table routing per business
- Efficient query optimization
- JSON field parsing
- Connection pooling

✅ **Analytics Engine**
- Aggregated statistics
- Sentiment analysis
- Intent distribution
- Trend calculations
- Agent performance tracking

## 🗄️ Database Schema

### Primary Tables (per business)

**`{bid}_calls`** - Main call records
```sql
id, bid, callid, fileUrl, status (0-3), agent_name, duration,
customer_name, call_date, call_time, call_status, keywords,
sentiments, emotions, summary, sales_intent, transcripts,
customer_details, remarks, created_at, updated_at
```

**`{bid}_sarvamresponse`** - Transcription data
```sql
id, callid, transcript, request_id, language, raw_response,
status, created_at, updated_at
```

**`{bid}_call_history`** - Conversation summaries
```sql
id, business_id, callid, transfer_reason, created_at, updated_at
```

### Status Flow
```
0 (Unprocessed) → 1 (Transcribed) → 2 (Analyzed) → 3 (Message Sent)
```

## 🔧 Configuration

### Backend (.env)
```env
# Database
DB_HOST=10.0.0.109
DB_USER=admin
DB_PASSWORD=your-password
DB_NAME=voicebot_cluster

# Server
FLASK_PORT=5000
FLASK_DEBUG=True

# CORS
CORS_ORIGINS=http://localhost:5173
```

### Frontend (api.js)
```javascript
const API_BASE_URL = 'http://localhost:5000';

// Switch from mock to real API
import { apiService } from '../services/api';
// instead of mockDataService
```

## 📡 API Examples

### Get Businesses
```bash
curl http://localhost:5000/list-businesses
```

### Get Calls with Filters
```bash
# By status
curl "http://localhost:5000/calls/6840?status=3"

# By date range
curl "http://localhost:5000/calls/6840?date_from=2024-11-01&date_to=2024-11-30"

# With pagination
curl "http://localhost:5000/calls/6840?limit=50&offset=0"
```

### Get Analytics
```bash
# Statistics
curl "http://localhost:5000/analytics/6840/stats"

# Sentiment
curl "http://localhost:5000/analytics/6840/sentiment"

# Intent distribution
curl "http://localhost:5000/analytics/6840/intent"

# Trends
curl "http://localhost:5000/analytics/6840/trends?days=7"
```

### Search Calls
```bash
curl -X POST http://localhost:5000/calls/search \
  -H "Content-Type: application/json" \
  -d '{"bid":"6840","query":"product","limit":50}'
```

## 🚀 Production Deployment

### Backend (with Gunicorn)
```bash
cd dashboard-backend
pip install gunicorn
gunicorn -w 4 -k gevent -b 0.0.0.0:5000 app:app
```

### Frontend (Build)
```bash
cd dashboard-frontend
npm run build
# Deploy dist/ folder to web server
```

### Nginx Configuration
```nginx
# Backend API
location /api {
    proxy_pass http://127.0.0.1:5000;
}

# Frontend
location / {
    root /var/www/html/sara/dashboard-frontend/dist;
    try_files $uri /index.html;
}
```

## 📊 Data Flow

```
1. Call Completed
   ↓
2. Update Call → /update-call (existing system)
   ↓
3. Queue for Processing → RabbitMQ
   ↓
4. Transcribe → Sarvam AI
   ↓
5. Analyze → AWS Bedrock
   ↓
6. Store Results → MySQL ({bid}_calls)
   ↓
7. Send Message → WhatsApp/Email
   ↓
8. Display in Dashboard → React Frontend
```

## 🔐 Security Considerations

- ✅ Environment variables for sensitive data
- ✅ Parameterized SQL queries (no injection)
- ✅ CORS configuration
- ✅ Error handling and logging
- ⚠️ Add authentication for production
- ⚠️ Enable rate limiting
- ⚠️ Use HTTPS in production

## 📈 Performance Tips

### Database
```sql
-- Add indexes for better performance
ALTER TABLE 6840_calls ADD INDEX idx_status (status);
ALTER TABLE 6840_calls ADD INDEX idx_call_date (call_date);
ALTER TABLE 6840_calls ADD INDEX idx_callid (callid);
```

### Backend
- Enable Redis caching
- Use connection pooling
- Implement pagination for large datasets

### Frontend
- Build for production: `npm run build`
- Enable gzip compression
- Use CDN for static assets

## 🧪 Testing

### Backend
```bash
# Health check
curl http://localhost:5000/health

# Load test
ab -n 1000 -c 10 http://localhost:5000/health
```

### Frontend
```bash
# Development server
npm run dev

# Production build
npm run build
npm run preview
```

## 📚 Documentation

- **Frontend**: [dashboard-frontend/README.md](dashboard-frontend/README.md)
- **Backend**: [dashboard-backend/README.md](dashboard-backend/README.md)
- **Quick Starts**:
  - [Frontend Quick Start](dashboard-frontend/QUICKSTART.md)
  - [Backend Quick Start](dashboard-backend/QUICKSTART.md)

## 🛠️ Technology Stack

### Frontend
- React 18.3
- Vite 6.0
- Tailwind CSS 3.4
- React Router 7.1
- Recharts 2.15
- Lucide Icons

### Backend
- Flask 3.0
- PyMySQL 1.1
- Python 3.8+
- Gunicorn (production)

### Database
- MySQL 8.0
- Dynamic table schema

### AI/ML
- Sarvam AI (transcription)
- AWS Bedrock (analysis)
- Nova Lite LLM

## 🔄 Integration Points

### Existing System
- Port 4567: Original Flask processor
- RabbitMQ: Audio job queue
- Azure Blob: Audio storage
- WhatsApp API: Message delivery
- AWS SES: Email delivery

### New Dashboard
- Port 5000: New REST API
- Port 5173: React dev server

## 📊 Metrics & Monitoring

**Available Metrics:**
- Total calls processed
- Average call duration
- Success rate percentage
- Sentiment distribution
- Sales intent classification
- Agent performance
- Message delivery rate

## 🐛 Troubleshooting

### Backend Issues
```bash
# Database connection
mysql -h 10.0.0.109 -u admin -p voicebot_cluster

# Port in use
lsof -ti:5000 | xargs kill -9

# Dependencies
pip install -r requirements.txt
```

### Frontend Issues
```bash
# Clear cache
rm -rf node_modules package-lock.json
npm install

# Port in use
lsof -ti:5173 | xargs kill -9
```

## 🎯 Future Enhancements

- [ ] Real-time WebSocket updates
- [ ] JWT authentication
- [ ] Advanced date range picker
- [ ] Call recording playback
- [ ] Email template viewer
- [ ] Custom report builder
- [ ] Excel export
- [ ] Push notifications
- [ ] Multi-language support
- [ ] Mobile app

## 📞 Support

For issues or questions:
1. Check documentation in README files
2. Review QUICKSTART guides
3. Contact development team

## 📄 License

Part of the Post Call Analysis System.

---

**Built with ❤️ using React + Flask + Python**

**Full Stack Dashboard - Ready to Deploy! 🚀**
