# Heat User - Multi-Tenant Migration Summary

## ✅ HOÀN TẤT

### **1. Helper Methods** (✅ Done)

**File:** `app/Helpers/HelperTenant.php`

Đã thêm 2 methods mới:
```php
public static function getActiveTenantCodes(): array
public static function getActiveTenantConnections(): array
```

**⚠️ TODO:** Cập nhật list tenant codes trong `getActiveTenantCodes()`:
```php
return [
    'hocmai',
    'icc',
    // Thêm các tenant codes khác ở đây
];
```

---

### **2. Cron Command** (✅ Done)

**File:** `app/Console/Commands/AutoEndInactiveSessions.php`

Đã update để loop qua tất cả tenants:
- ✅ Get all tenant connections
- ✅ Loop và xử lý từng tenant
- ✅ Error handling per tenant
- ✅ Logging per tenant
- ✅ Summary report

**Test:**
```bash
php artisan sessions:auto-end

# Expected output:
# Found 2 active tenants
# 
# 📌 Processing tenant: hocmai (connection: lms_tenant_hocmai)
#   Active sessions: 5
#   ✓ Ended 3 sessions in 125.50ms
# 
# 📌 Processing tenant: icc (connection: lms_tenant_icc)
#   Active sessions: 2
#   ✓ Ended 1 sessions in 45.20ms
# 
# ═══════════════════════════════════════
# 📊 SUMMARY
# ═══════════════════════════════════════
# Total tenants processed: 2
# Total sessions ended: 4
# Total execution time: 250.30ms
```

---

### **3. Service Example** (✅ Done)

**File:** `app/Services/HeatUser/StudySessionService_MULTI_TENANT_EXAMPLE.php`

Đã tạo file example với 7 methods đã update:
1. ✅ `startSession()`
2. ✅ `heartbeat()`
3. ✅ `autoEndInactiveSessions()`
4. ✅ `endSessionWithTime()`
5. ✅ `updateDailyStudyTime()`
6. ✅ `updateHistoryStudyTime()`
7. ✅ `checkExistingSession()`

**Pattern chung:**
```php
// Get tenant connection
$tenantConnection = HelperTenant::getCurrentTenantConnection();

// Use ->on($tenantConnection) for all queries
Model::on($tenantConnection)->where(...)->first()
```

---

## 🔧 CẦN LÀM (Manual Update)

### **Update Service File**

**File:** `app/Services/HeatUser/StudySessionService.php`

Bạn cần apply pattern từ example file vào tất cả methods:

#### **Checklist:**

**Public Methods:**
- [ ] `startSession()` - See example ✅
- [ ] `continueSession()` - Apply same pattern
- [ ] `heartbeat()` - See example ✅
- [ ] `submitSession()` - Apply same pattern
- [ ] `stopSession()` - Apply same pattern
- [ ] `autoEndInactiveSessions()` - See example ✅
- [ ] `getStudentStatistics()` - Apply same pattern
- [ ] `getActiveSession()` - Apply same pattern
- [ ] `checkExistingSession()` - See example ✅

**Private Methods:**
- [ ] `endSessionWithTime()` - See example ✅
- [ ] `distributeDailyTime()` - Add `$tenantConnection` param
- [ ] `updateDailyStudyTime()` - See example ✅
- [ ] `updateHistoryStudyTime()` - See example ✅
- [ ] `updateContestStudyTime()` - Apply same pattern

#### **Steps:**

1. **Mở file example:** `StudySessionService_MULTI_TENANT_EXAMPLE.php`
2. **Copy pattern** từ example methods
3. **Apply vào actual file:** `StudySessionService.php`
4. **Test từng method** sau khi update

#### **Key Changes:**

```php
// Step 1: Add at start of method
$tenantConnection = HelperTenant::getCurrentTenantConnection();

// Step 2: Replace all queries
// BEFORE:
$session = StudentStudySession::where(...)->first();

// AFTER:
$session = StudentStudySession::on($tenantConnection)->where(...)->first();

// Step 3: For private methods, add parameter
// BEFORE:
private function updateDailyStudyTime($studentId, $date, $minutes)

// AFTER:
private function updateDailyStudyTime($studentId, $date, $minutes, $tenantConnection = null)
{
    if (!$tenantConnection) {
        $tenantConnection = HelperTenant::getCurrentTenantConnection();
    }
    // ... use $tenantConnection
}

// Step 4: For transactions
DB::connection($tenantConnection)->beginTransaction()

// Step 5: Add tenant to logs
Log::info('...', ['tenant' => $tenantConnection, ...])
```

---

## 📚 Documentation

Đã tạo 3 files document:

1. **HEAT_USER_MULTI_TENANT_UPDATE.md**
   - Chi tiết về multi-tenant architecture
   - Pattern và best practices
   - Testing guide

2. **StudySessionService_MULTI_TENANT_EXAMPLE.php**
   - Example code với 7 methods đã update
   - Pattern summary ở cuối file
   - Copy-paste friendly

3. **HEAT_USER_MULTI_TENANT_SUMMARY.md** (This file)
   - Tổng hợp những gì đã làm
   - Checklist cần làm tiếp
   - Quick reference

---

## 🧪 Testing Plan

### **Test 1: Single Tenant (Web Request)**

```bash
# Test với tenant 'hocmai'
curl -X POST /api/heat-user/study-session/start \
  -H "Cookie: laravel_session=..." \
  -d '{
    "id_history_contest": 100,
    "id_history": 200,
    "id_bai_kiem_tra": 456
  }'

# Check logs - phải thấy:
# [tenant] => lms_tenant_hocmai
```

### **Test 2: Multi-Tenant (Cron)**

```bash
php artisan sessions:auto-end

# Should process all tenants
# Check logs for each tenant
```

### **Test 3: Verify Database**

```sql
-- Check session được tạo đúng database
-- Tenant 'hocmai' → database 'lms_tenant_hocmai'
SELECT * FROM lms_tenant_hocmai.student_study_sessions 
ORDER BY created_at DESC LIMIT 5;

-- Tenant 'icc' → database 'lms_tenant_icc'
SELECT * FROM lms_tenant_icc.student_study_sessions 
ORDER BY created_at DESC LIMIT 5;
```

---

## ⚠️ Important Notes

1. **Session Context**
   - Web requests: `tenant_connection` đã có trong session (middleware set)
   - Cron jobs: Command phải SET `tenant_connection` cho từng tenant

2. **Lock Keys**
   - Phải unique per tenant: `auto_end_sessions_{$tenantConnection}`
   - Tránh conflict giữa các tenants

3. **Logging**
   - Luôn include `tenant` trong logs để dễ debug
   - Format: `['tenant' => $tenantConnection, ...]`

4. **Transactions**
   - Dùng: `DB::connection($tenantConnection)->beginTransaction()`
   - Không dùng: `DB::beginTransaction()` (sẽ dùng default connection)

5. **Models**
   - Existing models: `$model->setConnection($tenantConnection)`
   - New queries: `Model::on($tenantConnection)`

---

## 🚀 Deployment Checklist

- [ ] Backup database tất cả tenants
- [ ] Update `getActiveTenantCodes()` với danh sách đúng
- [ ] Update tất cả methods trong Service (theo checklist trên)
- [ ] Test trên local/staging environment
- [ ] Test web requests (single tenant)
- [ ] Test cron job (multi-tenant)
- [ ] Verify logs có tenant info
- [ ] Monitor first few cron runs on production
- [ ] Check metrics per tenant

---

## 📞 Support

**Documents:**
- `docs/HEAT_USER_MULTI_TENANT_UPDATE.md` - Full guide
- `app/Services/HeatUser/StudySessionService_MULTI_TENANT_EXAMPLE.php` - Code examples

**Pattern Quick Reference:**
```php
$tenantConnection = HelperTenant::getCurrentTenantConnection();
Model::on($tenantConnection)->...
```

---

**Status:** ⚠️ Partial - Service file cần update manual (theo example file)

**Next Step:** Apply pattern từ example file vào actual Service file (13 methods)

