# Production Deployment Guide - Branch & Portfolio Filtering

## ⚠️ IMPORTANT - Read Before Deploying

This guide will help you safely deploy the branch and portfolio filtering system to your production environment.

---

## 📋 Pre-Deployment Checklist

### 1. Backup Your System
- [ ] **Database backup** (CRITICAL!)
  ```bash
  # For MySQL/MariaDB
  mysqldump -u username -p database_name > backup_$(date +%Y%m%d_%H%M%S).sql
  ```
- [ ] **Code backup** (files will be backed up automatically by script)
- [ ] **Test on staging environment first** (if available)

### 2. Verify Current System
- [ ] System is running without errors
- [ ] All users can currently access the system
- [ ] No pending migrations
- [ ] No ongoing critical operations

### 3. Prepare for Downtime
- [ ] Schedule deployment during low-traffic period
- [ ] Notify users of potential brief downtime
- [ ] Have rollback plan ready

---

## 🚀 Deployment Steps

### Step 1: Upload Files to Production

Upload these files to your production server:

**Required Files:**
```
utils/filtering.py                              # Core filtering module
apply_comprehensive_filtering.py                # Update script
verify_filtering_implementation.py              # Verification script
deploy_filtering_to_production.py               # Production deployment script
```

**Documentation Files (optional but recommended):**
```
COMPREHENSIVE_FILTERING_IMPLEMENTATION.md
STAFF_FILTERING_GUIDE.md
FILTERING_IMPLEMENTATION_SUMMARY.md
FILTERING_QUICK_REFERENCE.md
PRODUCTION_DEPLOYMENT_FILTERING.md
```

### Step 2: Connect to Production Server

```bash
# SSH into your production server
ssh user@your-production-server.com

# Navigate to your application directory
cd /path/to/branch-system
```

### Step 3: Run the Deployment Script

```bash
# Make sure you're in the application directory
python deploy_filtering_to_production.py
```

The script will:
1. ✓ Verify all prerequisites
2. ✓ Create automatic backup of files
3. ✓ Check Django setup
4. ✓ Verify filtering module
5. ✓ Test with real data
6. ✓ Apply updates to view files
7. ✓ Run verification tests
8. ✓ Provide restart instructions

### Step 4: Restart Application

**For cPanel:**
```
1. Login to cPanel
2. Go to "Setup Python App"
3. Find your application
4. Click "Restart" button
```

**For systemd:**
```bash
sudo systemctl restart branch-system
```

**For Apache with mod_wsgi:**
```bash
sudo systemctl restart apache2
# or
sudo service apache2 restart
```

**For touch reload (Passenger):**
```bash
touch tmp/restart.txt
```

### Step 5: Verify Deployment

#### Test with Different User Roles:

1. **Test as Admin:**
   - Login as admin user
   - Check dashboard shows all data
   - Try branch selector - should filter data
   - Verify all reports work

2. **Test as Loan Officer:**
   - Login as loan officer
   - Check dashboard shows only their portfolio
   - Verify cannot see other officers' clients
   - Check all reports show only portfolio data

3. **Test as Secretary/Auditor:**
   - Login as secretary or auditor
   - Check dashboard shows only their branch
   - Verify cannot see other branches
   - Check all reports show only branch data

#### Run Verification Script:
```bash
python verify_filtering_implementation.py
```

Expected output: All checks should pass ✓

---

## 🔄 Rollback Procedure (If Needed)

If something goes wrong, you can rollback:

### Option 1: Automatic Rollback
```bash
# The deployment script creates a backup directory
# Use the backup directory name from the deployment output
python deploy_filtering_to_production.py --rollback backup_before_filtering_YYYYMMDD_HHMMSS
```

### Option 2: Manual Rollback
```bash
# Restore from the backup directory
cp backup_before_filtering_*/reports/views.py reports/views.py
cp backup_before_filtering_*/loans/views.py loans/views.py
cp backup_before_filtering_*/utils/views.py utils/views.py
cp backup_before_filtering_*/users/views.py users/views.py

# Restart application
sudo systemctl restart branch-system
```

### Option 3: Database Restore (if needed)
```bash
# Only if database was affected (it shouldn't be)
mysql -u username -p database_name < backup_YYYYMMDD_HHMMSS.sql
```

---

## 🧪 Post-Deployment Testing

### Critical Tests:

1. **Login Test**
   - [ ] Admin can login
   - [ ] Loan officer can login
   - [ ] Secretary can login
   - [ ] Borrowers can login

2. **Dashboard Test**
   - [ ] Admin sees all data
   - [ ] Loan officer sees only portfolio
   - [ ] Secretary sees only branch
   - [ ] All metrics display correctly

3. **Reports Test**
   - [ ] Processing fees report works
   - [ ] Interest income report works
   - [ ] Loans due report works
   - [ ] All other reports work

4. **Branch Selector Test**
   - [ ] Admin can switch branches
   - [ ] Data updates when branch changes
   - [ ] Loan officer can filter portfolio by branch

5. **Data Isolation Test**
   - [ ] Loan officer A cannot see Loan officer B's clients
   - [ ] Secretary A cannot see Branch B's data
   - [ ] All filtering rules enforced

---

## 📊 Monitoring After Deployment

### First 24 Hours:

1. **Monitor Error Logs**
   ```bash
   # Check application logs
   tail -f /path/to/logs/error.log
   
   # Check Apache/Nginx logs
   tail -f /var/log/apache2/error.log
   ```

2. **Monitor User Activity**
   - Check if users can access their data
   - Monitor for permission errors
   - Check for any unusual behavior

3. **Database Monitoring**
   - Monitor query performance
   - Check for any slow queries
   - Verify data integrity

### What to Look For:

- ✓ No 500 errors
- ✓ No permission denied errors
- ✓ Users can see their data
- ✓ Reports generate successfully
- ✓ Dashboard loads quickly

---

## 🐛 Troubleshooting

### Issue: Users See No Data

**Possible Causes:**
1. User has no branch assigned (secretaries/auditors)
2. User has no clients in portfolio (loan officers)
3. Filtering too restrictive

**Solution:**
```bash
# Check user assignments
python manage.py shell
>>> from users.models import CustomUser
>>> user = CustomUser.objects.get(email='user@example.com')
>>> print(f"Role: {user.role}")
>>> print(f"Branch: {user.branch}")
>>> print(f"Portfolio clients: {user.portfolio_clients.count()}")
```

### Issue: Users See Too Much Data

**Possible Causes:**
1. User is admin/superuser
2. Filtering not applied correctly

**Solution:**
```bash
# Verify filtering is working
python verify_filtering_implementation.py

# Check user role
python manage.py shell
>>> from users.models import CustomUser
>>> user = CustomUser.objects.get(email='user@example.com')
>>> print(f"Role: {user.role}, Is Superuser: {user.is_superuser}")
```

### Issue: Branch Filter Not Working

**Possible Causes:**
1. Session not storing branch ID
2. Branch ID not being passed to views

**Solution:**
- Clear browser cache and cookies
- Check session configuration in settings
- Verify branch selector is working

### Issue: Import Errors

**Error:** `ImportError: cannot import name 'get_filtered_loans'`

**Solution:**
```bash
# Verify filtering.py exists
ls -la utils/filtering.py

# Restart application
sudo systemctl restart branch-system
```

---

## 📞 Support & Help

### If Deployment Fails:

1. **Don't Panic** - You have backups
2. **Check Error Messages** - Read the error output carefully
3. **Rollback if Needed** - Use the rollback procedure
4. **Review Logs** - Check application and server logs
5. **Test Locally** - Try deployment on local/staging first

### Getting Help:

1. Check documentation files
2. Run verification script
3. Review error logs
4. Check user assignments
5. Contact system administrator

---

## ✅ Success Criteria

Deployment is successful when:

- [x] All users can login
- [x] Dashboard displays correctly for all roles
- [x] Reports work for all users
- [x] Branch filtering works
- [x] Portfolio filtering works
- [x] No errors in logs
- [x] Data isolation enforced
- [x] Performance is acceptable

---

## 📝 Deployment Log Template

Keep a record of your deployment:

```
Deployment Date: _______________
Deployed By: _______________
Production Server: _______________

Pre-Deployment:
[ ] Database backup created: _______________
[ ] Code backup created: _______________
[ ] Users notified: Yes/No

Deployment:
[ ] Files uploaded: _______________
[ ] Script executed: _______________
[ ] Application restarted: _______________

Post-Deployment:
[ ] Admin login tested: Pass/Fail
[ ] Loan officer login tested: Pass/Fail
[ ] Secretary login tested: Pass/Fail
[ ] Dashboard tested: Pass/Fail
[ ] Reports tested: Pass/Fail
[ ] Branch filtering tested: Pass/Fail

Issues Encountered:
_______________________________________________
_______________________________________________

Resolution:
_______________________________________________
_______________________________________________

Status: Success / Rolled Back / Partial
```

---

## 🎯 Final Notes

- **No database migrations required** - This is a code-only update
- **No data loss** - Filtering only affects what users see, not data storage
- **Reversible** - Can be rolled back if needed
- **Safe** - Automatic backups created before changes
- **Tested** - Verification scripts ensure everything works

**Good luck with your deployment! 🚀**
