# 🔧 Troubleshooting QR Code - Status INACTIVE

## ❌ Masalah: Status Tetap "INACTIVE"

Jika status di test_qr.html tetap **"INACTIVE"** dan tidak berubah, ini artinya `createSession()` **gagal atau tidak pernah dipanggil**.

---

## 🔍 Langkah Debugging

### Step 1: Cek Server Console (PENTING!)

Setelah klik **"Generate QR Code"**, **LANGSUNG cek console server** tempat kamu jalankan `npm start`.

**Yang HARUS muncul:**
```
🔵 Creating session: device_001
📡 Fetching latest Baileys version...
✅ Baileys version: 2.xxxx
📁 Created session directory: d:\home\...\sessions\device_001
🔑 Loading auth state from: d:\home\...\sessions\device_001
🔌 Creating WhatsApp socket...
✅ Session stored in memory
🟡 Connecting to WhatsApp...
```

**Jika TIDAK ADA log ini** → `createSession()` tidak dipanggil sama sekali!

---

### Step 2: Error yang Mungkin Muncul

#### Error 1: `Cannot find module 'baileys'`
```
❌ CRITICAL ERROR creating session device_001:
   Error: Cannot find module 'baileys'
```

**Solusi:**
```bash
npm install
```

#### Error 2: `useSingleFileAuthState is not a function`
```
Error: useSingleFileAuthState is not a function
```

**Solusi:** Sudah di-fix! Sekarang pakai `useMultiFileAuthState`.

#### Error 3: `Database connection error`
```
Error updating status: Database connection error
```

**Solusi:**
1. Cek apakah MySQL running
2. Cek `.env` settings
3. Restart server

#### Error 4: `ECONNREFUSED` atau `ETIMEDOUT`
```
Connection closed: device_001
   Status code: 428
   Should reconnect: true
```

**Solusi:**
1. Cek internet connection
2. Firewall mungkin blocking
3. WhatsApp server mungkin down (rare)

---

### Step 3: Cek Database

```sql
-- Cek status instance
SELECT uniqueId, title, status, number, LENGTH(qr) as qr_length 
FROM instance 
WHERE uniqueId = 'device_001';

-- Jika status masih "GENERATING" atau "INACTIVE" lebih dari 30 detik
-- Hapus dan coba lagi
DELETE FROM instance WHERE uniqueId = 'device_001';
```

---

### Step 4: Hapus Session yang Error

Jika ada session yang error atau stuck:

```sql
-- Hapus dari database
DELETE FROM instance WHERE uniqueId = 'device_001';
```

Kemudian **hapus folder session**:
```bash
# Windows
rmdir /s /q d:\home\CRM\Whatscrm\dev_main\sessions\device_001

# Atau manual: hapus folder device_001 di folder sessions/
```

---

## ✅ Flow yang Benar

```
1. Klik "Generate QR Code"
   ↓
2. POST /api/qr/gen_qr
   ↓
3. INSERT INTO instance (status='GENERATING')
   ↓
4. createSession() dipanggil
   ↓
5. Console: "🔵 Creating session: device_001"
   ↓
6. Console: "📡 Fetching latest Baileys version..."
   ↓
7. Console: "🔌 Creating WhatsApp socket..."
   ↓
8. Console: "🟡 Connecting to WhatsApp..."
   ↓
9. Console: "🟢 QR Code received for: device_001"
   ↓
10. Database: UPDATE instance SET qr='base64...', status='QR_READY'
   ↓
11. Frontend: QR code muncul! 🎉
```

---

## 🚨 Jika Masih Tidak Berfungsi

### Option A: Test dengan Baileys Sederhana

Buat file `test_baileys.js` di root project:

```javascript
const { makeWASocket, useMultiFileAuthState, fetchLatestBaileysVersion } = require('baileys');
const fs = require('fs');
const path = require('path');

async function test() {
  console.log('Testing Baileys...');
  
  const sessionDir = path.join(__dirname, 'test_session');
  if (!fs.existsSync(sessionDir)) {
    fs.mkdirSync(sessionDir, { recursive: true });
  }
  
  const { state, saveCreds } = await useMultiFileAuthState(sessionDir);
  const { version } = await fetchLatestBaileysVersion();
  
  console.log('Baileys version:', version.join('.'));
  
  const sock = makeWASocket({
    version,
    auth: state,
    printQRInTerminal: true,
  });
  
  sock.ev.on('connection.update', (update) => {
    const { connection, qr } = update;
    
    if (qr) {
      console.log('\n✅ QR CODE RECEIVED!');
      console.log('QR length:', qr.length);
      process.exit(0);
    }
    
    if (connection === 'open') {
      console.log('\n✅ CONNECTED!');
      process.exit(0);
    }
  });
}

test().catch(console.error);
```

Jalankan:
```bash
node test_baileys.js
```

**Jika berhasil:** QR code akan muncul di console dalam 5-10 detik.
**Jika gagal:** Akan muncul error detail.

---

### Option B: Cek Baileys Version

```bash
npm list baileys
```

Harus show: `baileys@7.0.0-rc.9`

Jika tidak match, reinstall:
```bash
npm uninstall baileys
npm install baileys@7.0.0-rc.9
```

---

## 📋 Checklist Troubleshooting

- [ ] Server running (`npm start`)
- [ ] Console show "QR Addon initialized successfully"
- [ ] MySQL running dan connected
- [ ] Internet connection aktif
- [ ] Folder `sessions/` writable
- [ ] Baileys terinstall (`npm list baileys`)
- [ ] Tidak ada error di console saat generate QR
- [ ] Instance belum ada di database (uniqueId unik)
- [ ] JWT token valid dan belum expired

---

## 💡 Tips

1. **Selalu cek console** setelah klik "Generate QR Code"
2. **Screenshot console log** jika error untuk troubleshooting
3. **Hapus instance lama** sebelum generate baru
4. **Jangan gunakan uniqueId yang sama** untuk multiple sessions
5. **Restart server** jika ada perubahan di `index.js`

---

**Last Updated:** April 9, 2026
