# WhatsApp Marketing Module - Testing Guide

## ✅ What's Been Implemented

### Core Functionality
- ✅ **WhatsApp Web Integration** - Node.js service with whatsapp-web.js
- ✅ **QR Code Generation** - Real-time via Socket.IO
- ✅ **Account Management** - Connect, disconnect, health monitoring
- ✅ **Campaign System** - Create, launch, pause, resume campaigns
- ✅ **Contact Management** - Import/export, tagging, bulk actions
- ✅ **Message Queue System** - Laravel jobs with retry logic
- ✅ **Rate Limiting** - Warming schedule enforcement
- ✅ **Counter Management** - Daily/hourly resets with scheduler
- ✅ **Ban Score System** - Automatic risk tracking

### Jobs & Automation
- ✅ **SendWhatsAppMessage** - Individual message sending with retry
- ✅ **ProcessWhatsAppCampaign** - Batch processing with rate limits
- ✅ **ResetWhatsAppDailyCounters** - Daily reset + warming advancement
- ✅ **ResetWhatsAppHourlyCounters** - Hourly limit reset

## 🚀 Step-by-Step Testing Guide

### Prerequisites

**1. Start Required Services**
```bash
# Terminal 1: Laravel
php artisan serve

# Terminal 2: Queue Worker
php artisan queue:work --tries=3

# Terminal 3: WhatsApp Service
cd whatsapp-service
npm run dev
```

**2. Verify Services Running**
```bash
# Check Laravel
curl http://neosolvix.test

# Check WhatsApp Service
curl http://localhost:3001/health
```

### Test 1: Connect WhatsApp Account

**Steps:**
1. Navigate to: `http://neosolvix.test/websites/{website_id}/marketing/whatsapp-unofficial/accounts/create`
2. Fill in form:
   - Phone: `+60123456789` (your test number)
   - Display Name: `Test Account`
   - Warming Schedule: `Conservative (21 Days)`
3. Click "Generate QR Code & Connect"
4. **Expected**: QR code appears within 10-15 seconds
5. Open WhatsApp on phone → Settings → Linked Devices → Link a Device
6. Scan QR code
7. **Expected**: Page shows "Connected Successfully!" and redirects

**What to Check:**
- [ ] QR code appears
- [ ] Socket.IO connection established (check browser console)
- [ ] Account status becomes "connected" in database
- [ ] Session saved in `whatsapp-service/sessions/`
- [ ] Node.js logs show "WhatsApp client ready"

**Troubleshooting:**
- QR not appearing? Check Node.js service logs
- Socket.IO errors? Verify CORS settings in `.env`
- Connection fails? Delete session folder and retry

---

### Test 2: Create Contacts

**Method A: Manual Add**
1. Go to Contacts → Add Contact
2. Add test contact with your phone number
3. Add tag: `VIP`

**Method B: CSV Import**
1. Download template
2. Add 3-5 test contacts
3. Import CSV

**What to Check:**
- [ ] Contacts appear in list
- [ ] Tags work correctly
- [ ] Contact count updates in dashboard

---

### Test 3: Create Campaign

**Steps:**
1. Go to Campaigns → Create Campaign
2. Fill in:
   - Name: `Test Campaign 1`
   - Type: `Blast`
   - WhatsApp Account: Select your connected account
   - Message: `Hello {name}, this is a test message!`
   - Select contacts with tag `VIP`
   - Schedule: `Immediate`
3. Click "Create Campaign"
4. **Expected**: Campaign created with messages queued

**What to Check:**
- [ ] Campaign shows in list
- [ ] Message preview shows variable replaced
- [ ] Contact count matches selected
- [ ] Messages created in database (status: pending)

---

### Test 4: Launch Campaign & Send Messages

**Steps:**
1. Go to campaign detail page
2. Click "Launch Campaign"
3. **Expected**: Status changes to "Running"
4. Watch queue worker terminal for activity

**What Happens:**
1. `ProcessWhatsAppCampaign` job dispatched
2. Job dispatches `SendWhatsAppMessage` jobs with delays
3. Each message sent via Node.js service
4. Status updated: pending → sent → delivered → read

**What to Check:**
- [ ] Campaign status: running
- [ ] Queue worker processes jobs
- [ ] Node.js logs show messages being sent
- [ ] WhatsApp receives messages on phone
- [ ] Message status updates in database
- [ ] Account counters increment
- [ ] Campaign stats update in real-time

**Monitor Progress:**
```bash
# Watch queue jobs
php artisan queue:work -vvv

# Check Node.js logs
# (in whatsapp-service terminal)

# Check Laravel logs
tail -f storage/logs/laravel.log
```

---

### Test 5: Rate Limiting

**Steps:**
1. Check account daily limit: `SELECT total_sent_today, warming_day FROM whatsapp_unofficial_accounts;`
2. Note current warming day limit (Day 1 = 20 messages for Conservative)
3. Create campaign with MORE than daily limit (e.g., 25 messages)
4. Launch campaign
5. **Expected**: Only sends up to daily limit, rest rescheduled

**What to Check:**
- [ ] Stops at daily limit
- [ ] Remaining jobs rescheduled for next day
- [ ] Ban score doesn't increase
- [ ] Account status remains "connected"

---

### Test 6: Hourly/Daily Reset

**Test Hourly Reset:**
```bash
php artisan whatsapp:reset-hourly-counters
```
**Expected:**
- `total_sent_this_hour` reset to 0
- Logs confirm reset count

**Test Daily Reset:**
```bash
php artisan whatsapp:reset-daily-counters
```
**Expected:**
- `total_sent_today` reset to 0
- `warming_day` increments
- Ban score decreases by 5
- Logs show warming advancement

---

### Test 7: Error Handling

**Test A: Disconnected Account**
1. Logout WhatsApp on phone (unlink device)
2. Try to send message
3. **Expected**: Job fails, message marked as failed, ban score increases

**Test B: Invalid Number**
1. Add contact with invalid phone: `+1234567890`
2. Send message to this contact
3. **Expected**: Message fails after 3 retries, marked as failed

**Test C: Rate Limit Hit**
1. Send messages rapidly
2. **Expected**: Jobs delayed/rescheduled automatically

---

### Test 8: Campaign Pause/Resume

**Steps:**
1. Launch campaign with 20+ messages
2. After a few sent, click "Pause Campaign"
3. **Expected**: Status becomes "paused", no more messages sent
4. Click "Resume Campaign"
5. **Expected**: Processing continues from where it left off

---

### Test 9: Multiple Accounts

**Steps:**
1. Connect second WhatsApp account
2. Create campaign using Account 2
3. **Expected**: Both accounts can send independently
4. Check rate limits apply per-account

---

### Test 10: Ban Score System

**Simulate High Ban Score:**
```sql
UPDATE whatsapp_unofficial_accounts SET ban_score = 65 WHERE id = 1;
```

**Try to Send:**
- **Expected**: `canSendMessage()` returns false
- Messages fail immediately
- Account shows "High Risk" in dashboard

**Reduce Ban Score:**
```bash
php artisan whatsapp:reset-daily-counters
# Ban score reduces by 5 each day
```

---

## 🔍 Verification Checklist

### Database Checks
```sql
-- Check accounts
SELECT id, phone_number, status, ban_score, warming_day, total_sent_today FROM whatsapp_unofficial_accounts;

-- Check campaigns
SELECT id, name, status, messages_sent, messages_failed FROM whatsapp_unofficial_campaigns;

-- Check messages
SELECT id, status, recipient_phone, sent_at, failed_at FROM whatsapp_unofficial_messages WHERE campaign_id = X;

-- Check pending jobs
SELECT * FROM jobs;
```

### Log Checks
```bash
# Laravel logs
tail -f storage/logs/laravel.log

# Queue worker output
php artisan queue:work -vvv

# Node.js service
# Check terminal running npm run dev
```

### Dashboard Checks
- [ ] Dashboard stats update correctly
- [ ] Account health shows accurate data
- [ ] Campaign progress updates
- [ ] Recent messages display
- [ ] Ban score indicators work

---

## 📊 Performance Testing

### Load Test: 100 Messages
1. Import 100 contacts
2. Create campaign targeting all
3. Launch and monitor

**Expected Results:**
- All messages queued successfully
- Sent at rate of ~5/minute (per warming schedule)
- No failures due to rate limiting
- Memory usage stable
- Queue processes without errors

### Multi-Campaign Test
1. Create 3 campaigns simultaneously
2. Launch all three
3. Monitor queue and service

**Expected Results:**
- Jobs process in order
- Rate limits respected per account
- No race conditions
- Stats update correctly for each campaign

---

## 🐛 Common Issues & Solutions

### Issue: QR Code Not Appearing
**Causes:**
- WhatsApp service not running
- Socket.IO connection failed
- CORS issues

**Solutions:**
```bash
# Check service
curl http://localhost:3001/health

# Check browser console for errors
# Verify .env settings match
```

### Issue: Messages Not Sending
**Causes:**
- Queue worker not running
- Account disconnected
- Rate limit exceeded

**Solutions:**
```bash
# Start queue worker
php artisan queue:work

# Check account status
php artisan tinker
>>> App\Models\WhatsAppUnofficialAccount::find(1)->canSendMessage()

# Check failed jobs
SELECT * FROM failed_jobs;
```

### Issue: Ban Score Too High
**Solutions:**
```sql
-- Manual reset (use cautiously)
UPDATE whatsapp_unofficial_accounts SET ban_score = 0 WHERE id = 1;

-- Or wait for daily reset
php artisan whatsapp:reset-daily-counters
```

---

## 🎯 Production Readiness Checklist

Before deploying to production:

### Configuration
- [ ] Environment variables set correctly
- [ ] Queue worker running as service
- [ ] Scheduler (cron) configured
- [ ] WhatsApp service running as PM2 process
- [ ] SSL/HTTPS enabled for Socket.IO
- [ ] Backup strategy for sessions

### Monitoring
- [ ] Error logging configured
- [ ] Queue monitoring enabled
- [ ] WhatsApp service health checks
- [ ] Alert system for failures

### Documentation
- [ ] Team trained on system
- [ ] Emergency procedures documented
- [ ] Backup/restore procedures tested

---

## 🚧 Next Steps: Production Deployment

Once all tests pass, you're ready for:
1. Production server setup
2. PM2 configuration
3. Nginx reverse proxy
4. SSL certificate setup
5. Monitoring & logging setup
6. Backup automation

**Would you like the production deployment guide next?**
