# Expenses Management System - Deployment Guide

## Quick Deployment

### Option 1: Python Deployment Script (Recommended)
```bash
python deploy_expenses_system.py
```

**Options:**
- `--skip-sample-data` - Skip creating sample expenses
- `--production` - Run in production mode (collects static files)

**Example:**
```bash
# Development deployment with sample data
python deploy_expenses_system.py

# Production deployment without sample data
python deploy_expenses_system.py --production --skip-sample-data
```

### Option 2: Shell Script (Linux/Mac)
```bash
chmod +x deploy_expenses.sh
./deploy_expenses.sh
```

**Options:**
- `--production` - Collect static files
- `--skip-sample-data` - Skip sample data creation

### Option 3: Batch Script (Windows)
```cmd
deploy_expenses.bat
```

**Options:**
- `--production` - Collect static files
- `--skip-sample-data` - Skip sample data creation

---

## Manual Deployment Steps

If you prefer to deploy manually, follow these steps:

### 1. Database Migrations

```bash
# Create migrations for expenses app
python manage.py makemigrations expenses

# Apply all migrations
python manage.py migrate
```

### 2. Collect Static Files (Production Only)

```bash
python manage.py collectstatic --noinput
```

### 3. Create Sample Data (Optional)

```bash
python create_sample_expenses.py
```

This creates 15 realistic sample expenses for testing.

### 4. Verify Installation

```bash
python verify_expenses.py
```

This checks:
- Database table exists
- Sample data is present
- URLs are configured
- Templates are in place

### 5. Run System Check

```bash
python manage.py check
```

### 6. Clear Cache (Optional)

```bash
python clear_django_cache.py
```

---

## Post-Deployment

### 1. Start the Server

**Development:**
```bash
python manage.py runserver
```

**Production:**
Configure your web server (Apache, Nginx, etc.) to serve the application.

### 2. Access the System

Navigate to:
- **Expenses List**: http://localhost:8000/expenses/
- **Add Expense**: http://localhost:8000/expenses/add/
- **Pending Approvals**: http://localhost:8000/expenses/approvals/pending/
- **Analytics**: http://localhost:8000/expenses/analytics/

### 3. Test Features

1. Login with your credentials
2. Navigate to "Expenses" in the sidebar
3. Test creating a new expense
4. Test filtering and search
5. Test approval workflow (if manager/admin)
6. Test analytics dashboard
7. Test export functionality

---

## Verification Checklist

After deployment, verify:

- [ ] Database migrations applied successfully
- [ ] Expenses table exists in database
- [ ] Expenses menu appears in sidebar
- [ ] Can access /expenses/ URL
- [ ] Can create new expense
- [ ] Can view expense list
- [ ] Can filter expenses
- [ ] Can approve/reject (if manager)
- [ ] Can view analytics
- [ ] Can export to Excel
- [ ] Sample data is present (if created)

---

## Troubleshooting

### Issue: Migration Fails

**Solution:**
```bash
# Check migration status
python manage.py showmigrations expenses

# If needed, fake the migration
python manage.py migrate expenses --fake-initial
```

### Issue: Static Files Not Loading

**Solution:**
```bash
# Collect static files again
python manage.py collectstatic --noinput --clear

# Check STATIC_ROOT in settings.py
```

### Issue: Expenses Menu Not Showing

**Solution:**
1. Check user role (must be staff, manager, or admin)
2. Clear browser cache
3. Restart Django server
4. Check templates/base.html for sidebar code

### Issue: Permission Denied

**Solution:**
1. Check user role in database
2. Ensure user is staff: `user.is_staff = True`
3. Check role: `user.role in ['admin', 'team_leader', 'loan_officer', 'secretary']`

### Issue: Sample Data Creation Fails

**Solution:**
```bash
# Check if branches exist
python manage.py shell
>>> from users.models import Branch
>>> Branch.objects.all()

# Check if staff users exist
>>> from users.models import CustomUser
>>> CustomUser.objects.filter(role__in=['admin', 'team_leader']).count()
```

---

## Production Deployment

### Additional Steps for Production

1. **Set DEBUG = False** in settings.py
2. **Configure ALLOWED_HOSTS** in settings.py
3. **Set up proper database** (MySQL/PostgreSQL)
4. **Configure static files serving** (Apache/Nginx)
5. **Set up media files serving**
6. **Configure HTTPS**
7. **Set up backup system**
8. **Configure logging**

### Example Production Settings

```python
# settings.py (production)
DEBUG = False
ALLOWED_HOSTS = ['yourdomain.com', 'www.yourdomain.com']

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'branch_business_advance',
        'USER': 'your_db_user',
        'PASSWORD': 'your_db_password',
        'HOST': 'localhost',
        'PORT': '3306',
    }
}

STATIC_ROOT = '/var/www/static/'
MEDIA_ROOT = '/var/www/media/'
```

### Web Server Configuration

**Apache (.htaccess):**
```apache
# Serve media files
Alias /media/ /var/www/media/
<Directory /var/www/media/>
    Require all granted
</Directory>

# Serve static files
Alias /static/ /var/www/static/
<Directory /var/www/static/>
    Require all granted
</Directory>
```

**Nginx:**
```nginx
location /media/ {
    alias /var/www/media/;
}

location /static/ {
    alias /var/www/static/;
}
```

---

## Rollback Procedure

If you need to rollback the deployment:

### 1. Rollback Migrations

```bash
# List migrations
python manage.py showmigrations expenses

# Rollback to previous migration
python manage.py migrate expenses zero
```

### 2. Remove Expenses App

```python
# settings.py
INSTALLED_APPS = [
    # ... other apps ...
    # 'expenses',  # Comment out or remove
]
```

### 3. Remove URLs

```python
# branch_system/urls.py
urlpatterns = [
    # ... other patterns ...
    # path('expenses/', include('expenses.urls')),  # Comment out
]
```

### 4. Restart Server

```bash
# Development
python manage.py runserver

# Production
sudo systemctl restart apache2  # or nginx
```

---

## Monitoring & Maintenance

### Regular Tasks

1. **Monitor expense creation rate**
2. **Check pending approvals daily**
3. **Review expense analytics weekly**
4. **Export data for accounting monthly**
5. **Backup database regularly**

### Performance Monitoring

```bash
# Check database size
python manage.py dbshell
> SELECT COUNT(*) FROM expenses;
> SELECT SUM(amount) FROM expenses WHERE status='approved';

# Check slow queries
# Enable Django Debug Toolbar in development
```

---

## Support

For issues or questions:

1. Check [EXPENSES_USER_GUIDE.md](EXPENSES_USER_GUIDE.md)
2. Review [EXPENSES_FEATURE_DOCUMENTATION.md](EXPENSES_FEATURE_DOCUMENTATION.md)
3. Run verification: `python verify_expenses.py`
4. Check logs: `logs/` directory
5. Contact system administrator

---

## Deployment Checklist

### Pre-Deployment
- [ ] Backup database
- [ ] Review code changes
- [ ] Test in development environment
- [ ] Update documentation
- [ ] Notify users of deployment

### During Deployment
- [ ] Put site in maintenance mode (production)
- [ ] Run deployment script
- [ ] Verify migrations
- [ ] Test critical features
- [ ] Check logs for errors

### Post-Deployment
- [ ] Remove maintenance mode
- [ ] Verify all features working
- [ ] Monitor for errors
- [ ] Notify users deployment is complete
- [ ] Update deployment log

---

**Deployment Script Version**: 1.0  
**Last Updated**: November 29, 2024  
**Tested On**: Django 4.x, Python 3.8+
