# Production Code Deployment
## Merge Code Changes (Templates, CSS, JS, Settings)

⚠️ **Điều Kiện**: Production server đã có PostgreSQL, SSL, Gunicorn, Apache setup sẵn

---

## ⚡ Quick Deployment (5 bước)

### 1️⃣ Test Locally
```bash
# Trên máy dev - chạy server để xem trước
python manage.py runserver

# Kiểm tra:
# - Homepage load đúng
# - CSS, JS load bình thường  
# - Admin panel OK
# - Chatbot API hoạt động
```

### 2️⃣ Commit & Push Code
```bash
# Commit changes
git add .
git commit -m "fix: improve topbar styling - fix language toggle icons

- Fix Facebook icon visibility with btn-light styling
- Prevent language toggle icons from being cut off
- Improve contrast and visual hierarchy"

# Push to production branch
git push origin main
```

### 3️⃣ SSH to Production & Pull Code
```bash
ssh user@production-server.com

cd /var/www/bmc

# Pull latest code
git pull origin main

# Kiểm tra code được pull
git log --oneline -3
```

### 4️⃣ Collectstatic (nếu có file CSS/JS mới)
```bash
# Chỉ cần nếu sửa static files
python manage.py collectstatic --noinput --clear

# Verify
ls -la staticfiles/css/  # Kiểm tra file mới
```

### 5️⃣ Restart Web Server
```bash
# Nếu dùng Gunicorn
sudo systemctl restart bmc-gunicorn

# Nếu dùng Apache
sudo systemctl restart apache2

# Verify it's running
sudo systemctl status bmc-gunicorn
# hoặc
sudo systemctl status apache2

# Tail logs để kiểm tra error
tail -f /var/log/django/bmc.log
```

---

## 📋 Chi Tiết Từng Bước

### Step 1️⃣ - Test Trên Dev

```bash
# Trên máy dev
cd /path/to/project
python manage.py runserver

# Browser: http://localhost:8000
# Kiểm tra:
✓ Homepage displays correctly
✓ CSS loads (colors, layout OK)
✓ JavaScript works (interactivity OK)
✓ Images load
✓ Navigation works
✓ Admin panel accessible
✓ Chatbot responds
✓ Responsive design (open DevTools, test mobile)
```

### Step 2️⃣ - Commit Changes

```bash
# Xem những file đã sửa
git status

# Add toàn bộ changes
git add .

# Commit với message rõ ràng
git commit -m "fix: improve UI styling and fix bugs

Changed files:
- BmcBase/templates/base.html (topbar styling)
- BmcBase/static/css/style.css (color improvements)
- BmcBase/static/js/chatbot.js (chatbot fixes)
- BMC/settings.py (minor config updates)

What was fixed:
- Fixed language toggle icon cutoff
- Improved Facebook button visibility
- Better color contrast for accessibility"

# Verify commit
git log --oneline -1

# Push to main branch
git push origin main
```

### Step 3️⃣ - Pull on Production

```bash
# SSH vào production server
ssh user@your-production-ip

# Go to project folder
cd /var/www/bmc  # ← Path tùy theo setup của bạn

# Kích hoạt virtual environment
source venv/bin/activate

# Pull latest code
git pull origin main

# Verify code pulled
git log --oneline -1
git diff HEAD~1  # Xem changes được pull

# Kiểm tra không có merge conflict
git status  # Phải là "nothing to commit"
```

### Step 4️⃣ - Collectstatic (nếu cần)

```bash
# Chỉ chạy nếu sửa CSS/JS/images
python manage.py collectstatic --noinput --clear

# Xem output, phải thành công
# Should show: X static files copied, Y post-processed

# Verify files copied to staticfiles/
ls -la staticfiles/
ls -la staticfiles/css/
ls -la staticfiles/js/
```

### Step 5️⃣ - Restart Server

**Nếu sử dụng Gunicorn:**
```bash
# Reload Gunicorn (graceful restart, không drop connections)
sudo systemctl restart bmc-gunicorn

# Verify
sudo systemctl status bmc-gunicorn
sudo systemctl is-active bmc-gunicorn  # Phải return "active"

# Check logs
sudo journalctl -u bmc-gunicorn -n 20 -f
```

**Nếu sử dụng Apache:**
```bash
# Reload Apache (graceful restart)
sudo systemctl reload apache2

# Verify
sudo systemctl status apache2
sudo systemctl is-active apache2

# Check Apache error log
sudo tail -f /var/log/apache2/error.log
```

**Nếu sử dụng cả hai (Gunicorn + Apache proxy):**
```bash
# Restart Gunicorn trước
sudo systemctl restart bmc-gunicorn

# Reload Apache (proxy)
sudo systemctl reload apache2

# Verify both
sudo systemctl status bmc-gunicorn
sudo systemctl status apache2
```

---

## ✅ Post-Deployment Verification

### Kiểm Tra Sau Deploy

```bash
# 1. Kiểm tra website load đúng
curl -I https://bmc.com.vn/
# Status phải là 200

# 2. Kiểm tra CSS load
curl -I https://bmc.com.vn/static/css/style.css
# Status phải là 200

# 3. Kiểm tra admin panel
curl -I https://bmc.com.vn/admin/
# Status phải là 301 hoặc 302 (redirect login)

# 4. Kiểm tra homepage content
curl -s https://bmc.com.vn/ | grep -o "<title>.*</title>"

# 5. Kiểm tra logs không có error
tail -f /var/log/django/bmc.log
# Kiểm tra không có "ERROR", "Exception"

# 6. Browser: Access website và test features
# - Homepage loads
# - Click menu items
# - Try chatbot
# - Check images display
# - Test responsive design (F12)
```

---

## 🔧 Common Changes & Commands

### Chỉ sửa Templates (HTML)
```bash
# Không cần collectstatic
git pull origin main
sudo systemctl restart bmc-gunicorn
# Done! (HTML được serve dynamically)
```

### Sửa CSS/JS Files
```bash
# Cần collectstatic
git pull origin main
python manage.py collectstatic --noinput --clear
sudo systemctl restart bmc-gunicorn
```

### Sửa settings.py
```bash
# Cần restart server
git pull origin main
sudo systemctl restart bmc-gunicorn
# Verify: tail -f /var/log/django/bmc.log
```

### Sửa Templates + CSS + Settings
```bash
# Chạy toàn bộ
git pull origin main
python manage.py collectstatic --noinput --clear
sudo systemctl restart bmc-gunicorn
```

---

## 🆘 Troubleshooting

### Issue: "500 Error" sau deploy
```bash
# 1. Check logs
tail -f /var/log/django/bmc.log
tail -f /var/log/apache2/error.log

# 2. Verify code pulled correctly
git log --oneline -1

# 3. Restart again
sudo systemctl restart bmc-gunicorn

# 4. Check syntax errors in Python files
python -m py_compile BmcBase/views.py  # Check syntax
```

### Issue: "CSS/JS không load"
```bash
# 1. Check static files collected
ls -la staticfiles/css/

# 2. Re-collect
python manage.py collectstatic --noinput --clear

# 3. Reload Apache
sudo systemctl reload apache2

# 4. Browser: Hard refresh (Ctrl+Shift+Delete)
```

### Issue: "Template error"
```bash
# 1. Check log
tail -f /var/log/django/bmc.log

# 2. Check template syntax
python manage.py check

# 3. Verify template file exists
ls BmcBase/templates/BmcBase/

# 4. Restart
sudo systemctl restart bmc-gunicorn
```

### Issue: "Gunicorn won't restart"
```bash
# Check what's blocking
sudo lsof -i :8000  # If using port 8000
sudo lsof -i :8001

# Kill process if stuck
sudo kill -9 <PID>

# Restart
sudo systemctl restart bmc-gunicorn

# Check status
sudo systemctl status bmc-gunicorn
```

---

## 📋 Pre-Deployment Checklist

- [ ] All changes committed locally
- [ ] Tested on dev machine
- [ ] No console errors in DevTools
- [ ] CSS/styling looks correct
- [ ] JavaScript functionality works
- [ ] Responsive design tested
- [ ] Admin panel accessible
- [ ] Ready to push

## 📋 Deployment Checklist

- [ ] SSH to production server
- [ ] `git pull origin main` successful
- [ ] `git status` shows "nothing to commit"
- [ ] `python manage.py collectstatic` (if needed)
- [ ] Web server restarted
- [ ] Logs show no errors
- [ ] Website loads in browser
- [ ] CSS/JS loaded properly
- [ ] Admin panel works
- [ ] Features tested

---

## ⏱️ Typical Deployment Time

```
Test locally:          5-10 min
Commit & push:         2 min
SSH & pull:            1 min
Collectstatic:         30 sec - 2 min (depending on file count)
Restart server:        5-10 sec (Gunicorn graceful reload)
Verify:                2-5 min
─────────────────────────────
Total:                 15-30 min
```

---

## 🔗 Reference Commands

```bash
# Quick commands reference
git pull origin main                              # Pull latest code
python manage.py collectstatic --noinput --clear  # Rebuild static files
python manage.py check                            # Check for errors
python manage.py runserver                        # Test locally

# Server commands
sudo systemctl restart bmc-gunicorn              # Restart Gunicorn
sudo systemctl reload apache2                     # Reload Apache
sudo systemctl status bmc-gunicorn               # Check status
sudo journalctl -u bmc-gunicorn -n 50 -f         # View logs
tail -f /var/log/django/bmc.log                  # Django logs
tail -f /var/log/apache2/error.log               # Apache errors
```

---

## 📝 Git Workflow

```
Local Dev:
  1. Sửa files (templates, CSS, JS, settings)
  2. Test: python manage.py runserver
  3. Commit: git commit
  4. Push: git push origin main

Production Server:
  1. SSH vào server
  2. git pull origin main
  3. python manage.py collectstatic (nếu cần)
  4. sudo systemctl restart bmc-gunicorn
  5. Verify: curl & browser test
```

---

**💡 Pro Tips:**
- Always test locally before deploying
- Use meaningful commit messages
- Keep deployment simple & focused
- Check logs after deployment
- Restart is fast (few seconds)
- Collectstatic can be slow if many files (use --clear to optimize)

**🚀 You're ready to deploy!**
