# Queue Setup Guide - Fix EMS Question URLs

## 🎯 Tại sao dùng Queue?

**exec command:**
- ❌ Tắt terminal → Process die
- ❌ Tắt máy → Process die
- ❌ Không retry khi fail

**Queue Job:**
- ✅ Tắt terminal → Job vẫn chạy
- ✅ Tắt máy → Job tiếp tục khi máy bật lại (nếu queue worker running)
- ✅ Auto retry khi fail
- ✅ Monitor được (failed jobs, pending jobs)

---

## 🚀 Setup Queue (3 bước)

### **Step 1: Cấu hình Queue Driver**

**Option A: Database Queue (Đơn giản nhất)**

```bash
# .env
QUEUE_CONNECTION=database

# Tạo table jobs
php artisan queue:table
php artisan queue:failed-table
php artisan migrate
```

**Option B: Redis Queue (Performance tốt hơn)**

```bash
# .env
QUEUE_CONNECTION=redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

# Install Redis (nếu chưa có)
sudo apt-get install redis-server
```

---

### **Step 2: Start Queue Worker**

```bash
# Start worker (foreground - để test)
php artisan queue:work

# hoặc chạy persistent (background)
nohup php artisan queue:work --daemon >> storage/logs/queue.log 2>&1 &
```

**Lưu ý:** Worker này phải **LUÔN CHẠY** để process jobs!

---

### **Step 3: Test**

```bash
# Call API
curl -X POST http://localhost/api/lms/ems/fix-question-urls \
  -H "Content-Type: application/json" \
  -d '{"tenant_id": 7}'

# Response:
# {
#   "success": true,
#   "message": "Queued job to fix URLs for 150 questions",
#   "job_type": "queue"
# }

# Check queue worker log
tail -f storage/logs/queue.log

# hoặc check Laravel log
tail -f storage/logs/laravel.log | grep "Fix EMS question URLs"
```

---

## 🔧 Setup Supervisord (Production - Recommended)

### **Tạo config file:**

```bash
sudo nano /etc/supervisor/conf.d/lms-queue-worker.conf
```

**Nội dung:**

```ini
[program:lms-queue-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/html/lms_hocmai/artisan queue:work --sleep=3 --tries=3 --max-time=3600
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
user=www-data
numprocs=2
redirect_stderr=true
stdout_logfile=/var/www/html/lms_hocmai/storage/logs/queue-worker.log
stopwaitsecs=3600
```

**Start supervisor:**

```bash
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start lms-queue-worker:*

# Check status
sudo supervisorctl status
```

---

## 📊 Monitor Queue

### **Check pending jobs:**

```bash
# Database queue
SELECT * FROM jobs ORDER BY id DESC LIMIT 10;

# Redis queue
redis-cli
> LLEN queues:default
```

### **Check failed jobs:**

```bash
php artisan queue:failed

# Retry failed job
php artisan queue:retry {job-id}

# Retry all
php artisan queue:retry all
```

---

## 🎯 Benefits

| Feature | exec command | Queue Job |
|---------|--------------|-----------|
| **Tắt terminal** | ❌ Die | ✅ Continue |
| **Tắt máy** | ❌ Die | ✅ Continue (if worker auto-start) |
| **Retry on fail** | ❌ No | ✅ Yes |
| **Monitor** | ❌ Hard | ✅ Easy |
| **Logging** | File only | Database + File |

---

## 🧪 Testing

### **Test 1: Dispatch job**

```bash
curl -X POST http://localhost/api/lms/ems/fix-question-urls \
  -d '{"tenant_id": 7}'
```

### **Test 2: Check queue**

```bash
# Database queue
SELECT * FROM jobs;

# Should see 1 job queued
```

### **Test 3: Start worker**

```bash
php artisan queue:work

# Should see:
# [timestamp] Processing: App\Jobs\FixEmsQuestionUrlsJob
# [timestamp] Processed: App\Jobs\FixEmsQuestionUrlsJob
```

### **Test 4: Close terminal**

```bash
# Start worker in background
nohup php artisan queue:work >> storage/logs/queue.log 2>&1 &

# Dispatch job
curl -X POST http://localhost/api/lms/ems/fix-question-urls -d '{"tenant_id": 7}'

# Close terminal
exit

# → Job vẫn chạy! ✅

# SSH lại và check
tail -f storage/logs/laravel.log | grep "Fix EMS"
```

---

## ⚠️ Important

**Queue worker PHẢI chạy để jobs được process!**

```bash
# Check if worker is running
ps aux | grep "queue:work"

# If not running, start it
nohup php artisan queue:work >> storage/logs/queue.log 2>&1 &

# Better: Use supervisord (auto-restart)
```

---

## 📝 Quick Start

```bash
# 1. Setup database queue
php artisan queue:table
php artisan queue:failed-table
php artisan migrate

# 2. Update .env
QUEUE_CONNECTION=database

# 3. Start worker
nohup php artisan queue:work >> storage/logs/queue.log 2>&1 &

# 4. Test
curl -X POST http://localhost/api/lms/ems/fix-question-urls -d '{"tenant_id": 7}'

# 5. Monitor
tail -f storage/logs/laravel.log
```

---

**Giờ có thể tắt máy rồi (nếu queue worker auto-start)!** 🎉

