# WhatsApp CRM Web Dashboard - Setup Guide

## Overview

Your WhatsApp CRM system now includes a **professional web dashboard** with:

✅ **Authentication System** - Secure login with default credentials
✅ **QR Code Scanner** - Scan to connect WhatsApp account
✅ **Real-time Status** - Check WhatsApp connection status
✅ **Webhook Management** - Create and manage webhooks for events
✅ **Responsive Design** - Works on desktop, tablet, and mobile
✅ **Auto-refresh** - Status updates automatically every 10 seconds

## Features

### 1. **Login Screen**
- Default credentials: `admin` / `admin`
- Generates unique Session ID and Webhook ID
- Initializes WhatsApp session automatically

### 2. **QR Code Section**
- Displays QR code for scanning with WhatsApp
- Shows Session ID (copy with one click)
- Shows Webhook ID (copy with one click)
- Real-time connection status

### 3. **Account Status**
- Connection Status (Connected/Disconnected)
- Account Information (Phone number when connected)
- Session Information (Start date)
- Webhook Status

### 4. **Webhook Configuration**
- Create webhooks for real-time events:
  - Message Received
  - Message Sent
  - Contact Added
  - Contact Updated
- View all active webhooks
- Test webhooks
- Delete webhooks

## File Structure

```
public/
├── index.html          # Main dashboard HTML
├── styles.css          # Complete styling
└── dashboard.js        # Frontend JavaScript logic
```

## How to Run

### 1. Install Dependencies (if not already done)
```bash
npm install
```

### 2. Start the Server
```bash
npm start
```

Or for development with auto-reload:
```bash
npm run dev
```

### 3. Open in Browser
```
http://localhost:3000
```

## Login Instructions

1. **Default Credentials:**
   - Username: `admin`
   - Password: `admin`

2. **Click Login** - System initializes a WhatsApp session

3. **Scan QR Code:**
   - Open WhatsApp on your phone
   - Go to Settings > Linked Devices
   - Click "Link a Device"
   - Point your phone at the QR code on screen
   - Wait for connection

4. **View Status:**
   - Status will show "Connected" when phone is linked
   - Phone number will display when authenticated

## API Endpoints Used

### Authentication
```javascript
POST /api/auth/init
// Initialize new session

GET /api/auth/{sessionId}/qr
// Get QR code as data URL

GET /api/auth/{sessionId}/status
// Check authentication status
```

### Webhooks
```javascript
POST /api/webhooks/{sessionId}
// Create new webhook

GET /api/webhooks/{sessionId}
// Get all webhooks

DELETE /api/webhooks/{sessionId}/{webhookId}
// Delete webhook

POST /api/webhooks/{sessionId}/{webhookId}/test
// Test webhook
```

## Data Storage

### LocalStorage
- **whatsapp_crm_session**: Stores session ID, webhook ID, username
- **whatsapp_crm_webhook**: Stores webhook configuration

### Backend Database
- Sessions stored in SQLite
- Webhooks stored in database
- All data persists between sessions

## Security Features

- ✅ Login authentication required
- ✅ Session-based access control
- ✅ CORS enabled for API calls
- ✅ Data stored securely in localStorage (client-side)
- ✅ Server-side session validation

## Customization

### Change Default Credentials

Edit [dashboard.js](public/dashboard.js) line ~95:

```javascript
if (username === 'admin' && password === 'admin') {
    // Change these values to your desired credentials
}
```

### Change API Base URL

Edit [dashboard.js](public/dashboard.js) line ~4:

```javascript
const API_BASE_URL = 'http://localhost:3000/api';
```

### Modify Styling

All styles are in [styles.css](public/styles.css). Key variables:

```css
:root {
    --primary: #25D366;      /* WhatsApp Green */
    --secondary: #075E54;    /* Dark Green */
    --danger: #E53935;       /* Red */
    --success: #66BB6A;      /* Light Green */
}
```

## Troubleshooting

### QR Code Not Showing
1. Check browser console for errors (F12)
2. Ensure server is running on correct port
3. Clear browser cache and reload

### Cannot Login
1. Verify username and password (default: admin/admin)
2. Check browser console for errors
3. Ensure API is responding with `/health` endpoint

### WhatsApp Not Connecting
1. Make sure phone has internet connection
2. QR code expires after 30 seconds - refresh page if needed
3. Try scanning again
4. Check WhatsApp version is up to date

### Webhook Issues
1. Ensure webhook URL is valid and accessible
2. Check webhook logs in system
3. Test webhook first before using in production

## Production Deployment

### 1. Update Configuration
Edit `.env` file:
```
PORT=3000
SESSION_PATH=./sessions
DATABASE_PATH=./data
LOG_PATH=./logs
```

### 2. Change Default Credentials
Modify authentication in `dashboard.js` and `auth.js`

### 3. Use HTTPS
Deploy behind reverse proxy (Nginx, Apache) with SSL

### 4. Database Backup
Regularly backup SQLite database file

### 5. Environment Variables
Set up proper environment variables for:
- Database location
- Session storage
- Log paths

## API Response Examples

### Successful Login
```json
{
  "sessionId": "abc-123",
  "webhookId": "xyz-789",
  "message": "Session initialized"
}
```

### Connection Status
```json
{
  "authenticated": true,
  "phoneNumber": "+1234567890",
  "timestamp": "2024-01-30T10:00:00Z"
}
```

### Create Webhook
```json
{
  "id": "webhook-123",
  "url": "https://example.com/webhook",
  "events": ["message.received", "message.sent"],
  "createdAt": "2024-01-30T10:00:00Z"
}
```

## Browser Support

- ✅ Chrome/Edge (Latest)
- ✅ Firefox (Latest)
- ✅ Safari (Latest)
- ✅ Mobile browsers

## Need Help?

- Check [README.md](../README.md) for general setup
- Review [WEBHOOKS.md](../WEBHOOKS.md) for webhook details
- See [API_EXAMPLES.md](../INTEGRATION_EXAMPLES.md) for code examples

## Next Steps

1. **Start the server**: `npm start`
2. **Open dashboard**: `http://localhost:3000`
3. **Login**: admin / admin
4. **Scan QR code** with WhatsApp
5. **Create webhooks** for real-time events
6. **Test integration** with your services

---

Last Updated: January 30, 2026
