# Deploy Reports Fix to Production

## Quick Summary
The processing fees and interest income reports were showing zeros because they were calculating values instead of using actual database fields.

## What Was Fixed

### 1. Processing Fees Report
- **Before:** Calculated as 2% of total_amount (incorrect)
- **After:** Uses actual `loan.processing_fee` field from database
- **Impact:** Now shows real processing fee revenue

### 2. Interest Income Report  
- **Before:** Calculated as 15% annual rate (incorrect)
- **After:** Uses actual `loan.interest_amount` field from database
- **Impact:** Now shows real interest income

### 3. Report Filtering
- **Before:** Only showed active loans from current month
- **After:** Shows all loans with fees/interest, defaults to all-time view
- **Impact:** Historical data now visible

## Files to Upload

Upload these 2 files to production:

1. **reports/simple_reports_service.py**
   - Fixed `get_processing_fees_report()` method
   - Fixed `get_interest_income_report()` method

2. **reports/views.py**
   - Fixed `enhanced_processing_fees_report()` function
   - Better date filtering and error handling

## Deployment Steps

### Option A: Via cPanel File Manager (Recommended)

1. **Login to cPanel**
   - Go to: https://branchbusinessadvance.co.ke:2083
   - Login with your credentials

2. **Navigate to File Manager**
   - Click "File Manager" icon
   - Navigate to: `/home/branchbu/public_html/reports/`

3. **Backup Current Files**
   ```
   Right-click on simple_reports_service.py → Copy
   Rename copy to: simple_reports_service.py.backup
   
   Right-click on views.py → Copy
   Rename copy to: views.py.backup
   ```

4. **Upload New Files**
   - Click "Upload" button
   - Select `reports/simple_reports_service.py` from your local machine
   - Select `reports/views.py` from your local machine
   - Confirm overwrite when prompted

5. **Restart Application**
   - Navigate to: `/home/branchbu/public_html/`
   - Create/touch file: `tmp/restart.txt`
   - Or edit `passenger_wsgi.py` (add a space and save)

### Option B: Via FTP

1. **Connect via FTP**
   - Host: branchbusinessadvance.co.ke
   - Username: Your FTP username
   - Password: Your FTP password
   - Port: 21

2. **Navigate to reports folder**
   ```
   cd /home/branchbu/public_html/reports/
   ```

3. **Backup and Upload**
   ```
   # Backup current files
   cp simple_reports_service.py simple_reports_service.py.backup
   cp views.py views.py.backup
   
   # Upload new files (overwrite existing)
   put simple_reports_service.py
   put views.py
   ```

4. **Restart Application**
   ```
   cd /home/branchbu/public_html/
   touch tmp/restart.txt
   ```

### Option C: Via SSH (If Available)

```bash
# Connect to server
ssh username@branchbusinessadvance.co.ke

# Navigate to project directory
cd /home/branchbu/public_html

# Backup current files
cp reports/simple_reports_service.py reports/simple_reports_service.py.backup
cp reports/views.py reports/views.py.backup

# Upload new files (use scp or git pull)
# Then restart
touch tmp/restart.txt
```

## Verification Steps

### 1. Check Processing Fees Report
Visit: https://branchbusinessadvance.co.ke/reports/processing-fees/

**Expected Results:**
- Should show actual processing fees from loans
- "Fees Collected" should show total processing fee revenue
- "Total Loans Processed" should show count of loans with fees
- Charts should display data (not empty)

**If Still Showing Zeros:**
- Check if production database has loans with processing_fee > 0
- Try logging in as admin user (to see all branches)
- Select "All Time" period filter

### 2. Check Interest Income Report
Visit: https://branchbusinessadvance.co.ke/reports/interest-income/

**Expected Results:**
- Should show actual interest income from loans
- "Total Interest Income" should show sum of interest amounts
- Monthly breakdown should show data

### 3. Check Application Logs
```bash
# Via SSH or cPanel Terminal
tail -f /home/branchbu/public_html/logs/error.log
```

Look for any errors related to reports.

## Troubleshooting

### Issue: Still Showing Zeros After Deployment

**Possible Causes:**

1. **No loans in production database**
   ```python
   # Check via Django shell
   python manage.py shell
   >>> from loans.models import Loan
   >>> Loan.objects.count()
   ```

2. **Loans don't have processing fees set**
   ```python
   >>> from django.db.models import Sum
   >>> Loan.objects.aggregate(Sum('processing_fee'))
   ```

3. **Branch filtering too restrictive**
   - Log in as admin user
   - Clear branch filter (select "All Branches")

4. **Files not uploaded correctly**
   - Check file timestamps in cPanel
   - Verify file sizes match local files
   - Re-upload if needed

5. **Application not restarted**
   - Touch `tmp/restart.txt` again
   - Or edit `passenger_wsgi.py` to force restart

### Issue: Error 500 After Deployment

**Solution:**
1. Check error logs: `tail -f logs/error.log`
2. Restore backup files:
   ```bash
   cp reports/simple_reports_service.py.backup reports/simple_reports_service.py
   cp reports/views.py.backup reports/views.py
   touch tmp/restart.txt
   ```
3. Contact support with error details

### Issue: Import Errors

**Solution:**
Ensure all imports are available:
```python
# These should already be installed
from django.db.models import Sum, Count, Q, Avg, F
from decimal import Decimal
from datetime import datetime, timedelta
```

## Testing Commands

Run these in production Django shell to verify data:

```python
# Access Django shell
python manage.py shell

# Check processing fees
from loans.models import Loan
from django.db.models import Sum
total_fees = Loan.objects.aggregate(Sum('processing_fee'))['processing_fee__sum']
print(f"Total processing fees: KSh {total_fees or 0:,.2f}")

# Check interest income
total_interest = Loan.objects.aggregate(Sum('interest_amount'))['interest_amount__sum']
print(f"Total interest: KSh {total_interest or 0:,.2f}")

# Check loan count
print(f"Total loans: {Loan.objects.count()}")
print(f"Loans with fees: {Loan.objects.filter(processing_fee__gt=0).count()}")

# Test report service
from reports.simple_reports_service import SimpleReportsService
service = SimpleReportsService()
report = service.get_processing_fees_report(period='month')
print(f"Report total: KSh {report['summary']['total_processing_fees']:,.2f}")
```

## Rollback Plan

If something goes wrong:

1. **Restore backup files:**
   ```bash
   cd /home/branchbu/public_html/reports/
   cp simple_reports_service.py.backup simple_reports_service.py
   cp views.py.backup views.py
   ```

2. **Restart application:**
   ```bash
   cd /home/branchbu/public_html/
   touch tmp/restart.txt
   ```

3. **Verify site is working:**
   - Visit: https://branchbusinessadvance.co.ke
   - Check that other pages load correctly

## Success Criteria

✅ Processing fees report shows actual data (not zeros)
✅ Interest income report shows actual data (not zeros)
✅ No error 500 pages
✅ All other reports still working
✅ Dashboard loads correctly
✅ No errors in application logs

## Support

If you encounter issues:

1. **Check the logs first:**
   - `/home/branchbu/public_html/logs/error.log`
   - `/home/branchbu/public_html/logs/access.log`

2. **Verify file permissions:**
   ```bash
   chmod 644 reports/simple_reports_service.py
   chmod 644 reports/views.py
   ```

3. **Test in Django shell:**
   - Run the testing commands above
   - Verify data exists in database

4. **Contact developer:**
   - Provide error logs
   - Describe what you see vs. what you expect
   - Include screenshots if helpful

## Post-Deployment Checklist

- [ ] Files uploaded successfully
- [ ] Application restarted
- [ ] Processing fees report showing data
- [ ] Interest income report showing data
- [ ] No errors in logs
- [ ] Dashboard still working
- [ ] Other reports still working
- [ ] Backup files saved

## Notes

- **Deployment Time:** ~5 minutes
- **Downtime:** None (hot reload)
- **Database Changes:** None required
- **Risk Level:** Low (only report calculations changed)
- **Reversible:** Yes (backup files available)

---

**Last Updated:** November 28, 2025
**Version:** 1.0
**Status:** Ready for Production
