# 🔧 Cara Menjalankan QR Addon di Local

## ✅ Masalah yang Sudah Diperbaiki

1. ✅ **Middleware plan check** → Dihilangkan untuk local development
2. ✅ **QR code tidak langsung muncul** → Sekarang ada polling endpoint
3. ✅ **Tidak ada feedback** → Ditambahkan logging dan status tracking
4. ✅ **Auto-reconnect** → Session otomatis reconnect jika putus

---

## 🚀 Cara Menjalankan (3 Steps)

### Step 1: Restart Server

```bash
# Stop server jika sedang berjalan (Ctrl+C)
npm start
```

Pastikan di console muncul:
```
WaCrm server is running on port 8001
QR Addon initialized successfully
```

---

### Step 2: Generate QR Code

#### Option A: Via Test Page (MUDAH!)

1. Buka file ini di browser:
   ```
   d:\home\CRM\Whatscrm\dev_main\helper\addon\qr\test_qr.html
   ```

2. **Login dulu** ke `http://localhost:8001`

3. **Ambil JWT Token**:
   - Buka browser DevTools (F12)
   - Application > Local Storage
   - Copy value dari key `token`

4. **Paste token** di field "JWT Token"

5. Klik **"Generate QR Code"**

6. **Tunggu 5-10 detik** → QR code akan muncul otomatis

7. **Scan dengan WhatsApp**:
   - WhatsApp → Settings → Linked Devices → Link a Device
   - Arahkan kamera ke QR code

#### Option B: Via API (Advanced)

**Generate QR:**
```bash
curl -X POST http://localhost:8001/api/qr/gen_qr \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -d '{"title":"My WhatsApp","uniqueId":"device_001"}'
```

**Response:**
```json
{
  "success": true,
  "msg": "QR code is generating. Please wait 5-10 seconds.",
  "uniqueId": "device_001"
}
```

---

### Step 3: Poll QR Code (PENTING!)

QR code **TIDAK LANGSUNG MUNCUL**! Harus di-polling dulu.

**Endpoint:**
```
GET http://localhost:8001/api/qr/get_qr?uniqueId=device_001
```

**Contoh Response:**

**Status: GENERATING** (belum siap)
```json
{
  "success": true,
  "status": "GENERATING",
  "qr": null,
  "number": null,
  "title": "My WhatsApp"
}
```

**Status: QR_READY** (siap scan!)
```json
{
  "success": true,
  "status": "QR_READY",
  "qr": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...",
  "number": null,
  "title": "My WhatsApp"
}
```

**Status: ACTIVE** (sudah terhubung!)
```json
{
  "success": true,
  "status": "ACTIVE",
  "qr": "",
  "number": "6281234567890",
  "title": "My WhatsApp"
}
```

---

## 📊 Status Flow

```
GENERATING → QR_READY → ACTIVE
    ↓            ↓         ↓
  Membuat   QR Code    WhatsApp
  Session   Siap Scan  Terhubung
```

**Keterangan:**
- `GENERATING` → Session Baileys dibuat, menunggu QR dari WhatsApp server (3-10 detik)
- `QR_READY` → QR code sudah digenerate, siap di-scan (berlaku ~30 detik)
- `ACTIVE` → WhatsApp sudah terhubung, bisa kirim/terima pesan

---

## 🐛 Troubleshooting

### ❌ QR Code Tidak Muncul

**Cek server logs di console:**
```
QR code generated for session: device_001
```

**Jika tidak ada log ini**, berarti:
1. Session tidak terbuat dengan benar
2. Cek koneksi database MySQL
3. Restart server

**Cek database:**
```sql
SELECT * FROM instance WHERE uniqueId = 'device_001';
```

Kolom `qr` harus berisi base64 image (panjang, diawali `data:image/png;base64,`)

---

### ❌ Status Tetap "GENERATING" Lebih dari 30 Detik

**Kemungkinan penyebab:**
1. Baileys tidak bisa connect ke WhatsApp server
2. Firewall/network blocking
3. Versi Baileys tidak kompatibel

**Solusi:**
```sql
-- Hapus instance yang stuck
DELETE FROM instance WHERE uniqueId = 'device_001';
```

Kemudian:
1. Restart server
2. Coba generate ulang

---

### ❌ Error: "Instance with this uniqueId already exists"

Instance sudah ada di database.

**Solusi:**
```sql
-- Hapus instance lama
DELETE FROM instance WHERE uniqueId = 'YOUR_UNIQUE_ID';
```

Atau gunakan `uniqueId` yang berbeda.

---

### ❌ "Your plan does not allow you this feature"

Middleware plan check masih aktif.

**Solusi:** Sudah di-fix! Endpoint `/gen_qr` sekarang bypass plan check.

Jika masih error, pastikan file `routes/qr.js` sudah terupdate (lihat bagian `/gen_qr` - tidak ada `checkPlan` dan `checkQrScan`).

---

### ❌ QR Code Expired Sebelum Sempat Scan

QR code WhatsApp memang expired setelah ~30 detik.

**Solusi:**
1. Siapkan WhatsApp di HP SEBELUM generate QR
2. Buka WhatsApp → Settings → Linked Devices
3. Klik "Link a Device" (jangan tutup)
4. Generate QR di web
5. Tunggu status `QR_READY`
6. Langsung scan!

Atau hapus instance dan generate ulang:
```sql
DELETE FROM instance WHERE uniqueId = 'device_001';
```

---

## 🔍 Debug Mode

### 1. Enable Logging

Tambahkan di `.env`:
```env
NODE_ENV=development
```

### 2. Cek Server Console

Harus muncul log seperti:
```
{ title: 'My WhatsApp', uniqueId: 'device_001', uid: 'xxx' }
QR code generated for session: device_001
WhatsApp connected: 6281234567890
```

### 3. Cek Database

```sql
-- Lihat semua instance
SELECT uniqueId, title, status, number, LENGTH(qr) as qr_size 
FROM instance 
ORDER BY createdAt DESC;

-- Hapus instance yang error
DELETE FROM instance WHERE status = 'GENERATING' AND createdAt < NOW() - INTERVAL 5 MINUTE;
```

---

## 📁 File Structure

```
helper/addon/qr/
├── index.js              ✅ Real Baileys implementation
├── index_stub.js.bak     ⚠️ Backup stub (non-aktif)
├── test_qr.html          🧪 Test page untuk generate QR
├── LOCAL_SETUP.md        📖 Dokumentasi lengkap
├── ACTIVATION.md         📝 Info activation
└── README.md             ← File ini
```

---

## 🎯 Quick Checklist

- [ ] Server running (`npm start`)
- [ ] Database connected (cek console: "Database has been connected")
- [ ] QR Addon initialized (cek console: "QR Addon initialized successfully")
- [ ] User logged in dan punya JWT token
- [ ] `uniqueId` belum ada di database
- [ ] WhatsApp siap di HP untuk scan QR

---

## 💡 Tips

1. **Gunakan `uniqueId` yang konsisten** - misal `device_001`, `device_002`, dst
2. **Jangan tutup browser saat polling** - QR code akan muncul otomatis
3. **Siapkan WhatsApp sebelum generate** - QR expired cepat
4. **Cek server logs** - banyak info berguna di console
5. **Gunakan test_qr.html** - lebih mudah daripada Postman

---

**Created:** April 9, 2026  
**WhatsApp CRM Version:** 5.9  
**Baileys Version:** 7.0.0-rc.9
