# 🚀 Start Call Analytics Dashboard - Quick Guide

## Complete System Startup in 2 Terminals

---

## Terminal 1: Backend API

```bash
# Navigate to backend
cd /var/www/html/sara/dashboard-backend

# Activate virtual environment
source venv/bin/activate

# Start the Flask API
python app.py
```

**Expected Output:**
```
=========================================
Call Analytics Dashboard API
=========================================
✓ Checking database connection...
✓ Database connection successful

Starting Flask Application...
 * Running on http://0.0.0.0:5000
 * Debug mode: on
```

**Backend Ready:** http://localhost:5000

---

## Terminal 2: Frontend Dashboard

```bash
# Navigate to frontend
cd /var/www/html/sara/dashboard-frontend

# Start React development server
npm run dev
```

**Expected Output:**
```
VITE v7.2.4  ready in 823 ms

➜  Local:   http://localhost:5173/
➜  Network: http://192.168.x.x:5173/
➜  press h + enter to show help
```

**Frontend Ready:** http://localhost:5173

---

## ✅ Verify Everything Works

### 1. Test Backend Health
```bash
curl http://localhost:5000/health
```

**Expected Response:**
```json
{
  "status": "healthy",
  "timestamp": "2024-11-25T...",
  "service": "Call Analytics Dashboard API"
}
```

### 2. Test Businesses Endpoint
```bash
curl http://localhost:5000/list-businesses
```

**Expected Response:**
```json
[
  {
    "bid": "6840",
    "name": "Business 6840",
    "totalCalls": 125,
    "callsTable": "6840_calls"
  }
]
```

### 3. Open Dashboard
Open browser: **http://localhost:5173**

You should see:
- ✅ Business selector with real businesses
- ✅ Dashboard with real metrics
- ✅ Charts with actual data
- ✅ Recent calls from database

---

## 🎯 Full System Architecture

```
┌─────────────────────────────────┐
│   React Frontend Dashboard      │
│   http://localhost:5173          │
│   - Modern UI with Tailwind      │
│   - Dark mode support            │
│   - Real-time analytics          │
└───────────┬─────────────────────┘
            │
            │ HTTP/REST API
            │
┌───────────▼─────────────────────┐
│   Flask Backend API              │
│   http://localhost:5000          │
│   - 20+ REST endpoints           │
│   - Analytics engine             │
│   - CORS enabled                 │
└───────────┬─────────────────────┘
            │
            │ SQL Queries
            │
┌───────────▼─────────────────────┐
│   MySQL Database                 │
│   10.0.0.109:3306                │
│   voicebot_cluster               │
│   - {bid}_calls                  │
│   - {bid}_sarvamresponse         │
│   - {bid}_call_history           │
└─────────────────────────────────┘
```

---

## 📊 What You'll See

### Dashboard Overview
- **Total Calls** - Count from database
- **Processed Calls** - Status 2-3
- **Pending Calls** - Status 0-1
- **Messages Sent** - Status 3
- **Average Duration** - Calculated from all calls
- **Success Rate** - ANSWER vs total attempts
- **High Intent Calls** - Sales intent = High
- **Sentiment Chart** - Aggregated positive/neutral/negative
- **Intent Chart** - Distribution from sand_logic_response

### Calls List
- All calls for selected business
- Filter by status (Unprocessed/Transcribed/Analyzed/Message Sent)
- Filter by sales intent (High/Medium/Low)
- Date range filtering
- Search by call ID, customer, agent
- Export to CSV

### Call Detail
- Full call metadata
- Complete transcript (from sarvamresponse)
- Customer contact information
- Sentiment breakdown
- Keywords and emotions
- Sales intent classification
- Download transcript

---

## 🛠️ Troubleshooting

### Backend Won't Start

**Issue:** `Address already in use`
```bash
# Kill process on port 5000
lsof -ti:5000 | xargs kill -9

# Then restart
python app.py
```

**Issue:** `Database connection failed`
```bash
# Test MySQL connection
mysql -h 10.0.0.109 -u admin -p voicebot_cluster

# Check .env file
cat .env | grep DB_
```

### Frontend Won't Start

**Issue:** `Port 5173 already in use`
```bash
# Kill process
lsof -ti:5173 | xargs kill -9

# Then restart
npm run dev
```

**Issue:** `Module not found`
```bash
# Reinstall dependencies
rm -rf node_modules package-lock.json
npm install
```

### No Data Showing

**Check Backend:**
```bash
# Test API
curl http://localhost:5000/list-businesses
curl "http://localhost:5000/calls/6840?limit=5"
```

**Check Database:**
```sql
-- Connect to MySQL
mysql -h 10.0.0.109 -u admin -p voicebot_cluster

-- Check tables
SHOW TABLES LIKE '%_calls';

-- Check data
SELECT COUNT(*) FROM 6840_calls;
SELECT * FROM 6840_calls LIMIT 5;
```

**Check Browser:**
- Open DevTools (F12)
- Go to Console tab
- Look for errors
- Check Network tab for failed requests

---

## 🔄 Stop the System

### Stop Backend (Terminal 1)
Press `CTRL + C`

### Stop Frontend (Terminal 2)
Press `CTRL + C`

---

## 📦 Alternative: Using Startup Scripts

### Backend with Script
```bash
cd /var/www/html/sara/dashboard-backend
./run.sh
```

### Production Mode (Gunicorn)
```bash
cd /var/www/html/sara/dashboard-backend
source venv/bin/activate
gunicorn -w 4 -k gevent -b 0.0.0.0:5000 app:app
```

---

## 🎨 Features to Test

- [ ] Business selector works
- [ ] Dashboard loads with real metrics
- [ ] Sentiment chart displays
- [ ] Intent chart displays
- [ ] Recent calls table shows data
- [ ] Navigate to Calls page
- [ ] Filter calls by status
- [ ] Filter calls by intent
- [ ] Search for calls
- [ ] Click on a call to view details
- [ ] View full transcript
- [ ] See customer details
- [ ] Dark mode toggle works
- [ ] Export CSV works
- [ ] No console errors

---

## 📈 Performance Tips

### Database Optimization
```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);
ALTER TABLE 6840_calls ADD INDEX idx_sales_intent (sales_intent);
```

### Backend Optimization
- Use Gunicorn with multiple workers
- Enable Redis caching (optional)
- Monitor slow queries

### Frontend Optimization
- Build for production: `npm run build`
- Use production build with Nginx
- Enable gzip compression

---

## 📚 Documentation

- **Backend API:** [dashboard-backend/README.md](dashboard-backend/README.md)
- **Frontend:** [dashboard-frontend/README.md](dashboard-frontend/README.md)
- **API Integration:** [dashboard-frontend/API_INTEGRATION_COMPLETE.md](dashboard-frontend/API_INTEGRATION_COMPLETE.md)
- **Master Docs:** [CALL_ANALYTICS_README.md](CALL_ANALYTICS_README.md)

---

## 🎉 Success!

When both servers are running and you can see the dashboard with real data, you're all set!

**Backend:** ✅ http://localhost:5000
**Frontend:** ✅ http://localhost:5173
**Database:** ✅ Connected to voicebot_cluster

**Happy Analyzing! 📊**
