# Haven Grazuri Investment Limited - Deployment Guide

## Quick Deployment

### Windows
```batch
deploy.bat
```

### Linux/Mac
```bash
python deploy.py
```

---

## What the Deployment Script Does

### Automatic Steps:
1. ✅ Checks Python version (requires 3.8+)
2. ✅ Checks MySQL installation and connection
3. ✅ Installs all Python requirements
4. ✅ **Drops and recreates database** (removes old data!)
5. ✅ Runs all Django migrations
6. ✅ Creates superuser account
7. ✅ Creates initial data (branches, loan products)
8. ✅ Imports Grazuri users (if available)
9. ✅ Collects static files
10. ✅ Runs system checks
11. ✅ Creates .env file
12. ✅ Starts development server

---

## Prerequisites

### Required:
- **Python 3.8+** installed and in PATH
- **MySQL 8.0+** installed and running
- **MySQL credentials:**
  - User: `root`
  - Password: `password`
  - Host: `localhost`
  - Port: `3306`

### Optional:
- Git (for version control)
- Virtual environment (recommended)

---

## Deployment Options

### Full Deployment (Default)
```bash
python deploy.py
```
- Resets database completely
- Creates fresh installation
- Starts server automatically

### Skip Database Reset
```bash
python deploy.py --skip-db
```
- Keeps existing database
- Only runs migrations
- Useful for updates

### No Server Start
```bash
python deploy.py --no-server
```
- Completes deployment
- Doesn't start server
- Useful for production

### Production Mode
```bash
python deploy.py --production --no-server
```
- Sets production settings
- No debug mode
- Doesn't start dev server

---

## Configuration

### Database Settings
Edit in `deploy.py`:
```python
DB_NAME = "acbptxvs_branch_system"
DB_USER = "root"
DB_PASSWORD = "password"
DB_HOST = "localhost"
DB_PORT = "3306"
```

### Superuser Credentials
Edit in `deploy.py`:
```python
SUPERUSER_USERNAME = "admin"
SUPERUSER_EMAIL = "admin@havengrazuri.co.ke"
SUPERUSER_PASSWORD = "Admin@2025"
```

---

## After Deployment

### 1. Access the System
- **URL:** http://127.0.0.1:8000/
- **Username:** admin
- **Password:** Admin@2025

### 2. Change Password
- Login as admin
- Go to profile settings
- Change password immediately

### 3. Configure Settings
- Update `.env` file with production values
- Set `DEBUG=False` for production
- Configure proper `SECRET_KEY`
- Set up HTTPS

### 4. Import Data (Optional)
If you have Grazuri data:
```bash
python import_grazuri_users.py
```

---

## Troubleshooting

### Python Not Found
**Error:** `Python is not installed or not in PATH`

**Solution:**
1. Install Python from python.org
2. Add Python to system PATH
3. Restart terminal

### MySQL Connection Failed
**Error:** `Cannot connect to MySQL`

**Solution:**
1. Check MySQL is running
2. Verify credentials in `deploy.py`
3. Test connection: `mysql -u root -p`

### Port Already in Use
**Error:** `Port 8000 is already in use`

**Solution:**
1. Stop existing server
2. Or use different port: `python manage.py runserver 8001`

### Migration Errors
**Error:** `Migration failed`

**Solution:**
1. Run with `--skip-db` flag
2. Or manually reset: `python deploy.py`

### Requirements Installation Failed
**Error:** `Could not install requirements`

**Solution:**
1. Upgrade pip: `python -m pip install --upgrade pip`
2. Install manually: `pip install -r requirements.txt`

---

## Manual Deployment Steps

If automatic deployment fails, follow these manual steps:

### 1. Install Requirements
```bash
pip install -r requirements.txt
```

### 2. Create Database
```sql
DROP DATABASE IF EXISTS acbptxvs_branch_system;
CREATE DATABASE acbptxvs_branch_system CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
```

### 3. Run Migrations
```bash
python manage.py makemigrations
python manage.py migrate
```

### 4. Create Superuser
```bash
python manage.py createsuperuser
```

### 5. Collect Static Files
```bash
python manage.py collectstatic --noinput
```

### 6. Start Server
```bash
python manage.py runserver
```

---

## Production Deployment

### 1. Update Settings
Edit `.env`:
```env
DEBUG=False
SECRET_KEY=your-secret-key-here
ALLOWED_HOSTS=yourdomain.com,www.yourdomain.com
SECURE_SSL_REDIRECT=True
SESSION_COOKIE_SECURE=True
CSRF_COOKIE_SECURE=True
```

### 2. Use Production Server
Don't use `runserver` in production. Use:
- **Gunicorn** (recommended)
- **uWSGI**
- **Daphne**

Example with Gunicorn:
```bash
pip install gunicorn
gunicorn branch_system.wsgi:application --bind 0.0.0.0:8000
```

### 3. Set Up Nginx (Recommended)
```nginx
server {
    listen 80;
    server_name yourdomain.com;
    
    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
    
    location /static/ {
        alias /path/to/staticfiles/;
    }
}
```

### 4. Set Up SSL
```bash
# Using Let's Encrypt
sudo certbot --nginx -d yourdomain.com
```

### 5. Set Up Systemd Service
Create `/etc/systemd/system/havengrazuri.service`:
```ini
[Unit]
Description=Haven Grazuri Investment Limited
After=network.target

[Service]
User=www-data
Group=www-data
WorkingDirectory=/path/to/branchsystem
ExecStart=/path/to/venv/bin/gunicorn branch_system.wsgi:application --bind 127.0.0.1:8000

[Install]
WantedBy=multi-user.target
```

Enable and start:
```bash
sudo systemctl enable havengrazuri
sudo systemctl start havengrazuri
```

---

## Backup & Restore

### Backup Database
```bash
mysqldump -u root -p acbptxvs_branch_system > backup_$(date +%Y%m%d).sql
```

### Restore Database
```bash
mysql -u root -p acbptxvs_branch_system < backup_20260508.sql
```

### Backup Files
```bash
tar -czf backup_files_$(date +%Y%m%d).tar.gz media/ staticfiles/
```

---

## Monitoring

### Check Server Status
```bash
# Development
ps aux | grep "manage.py runserver"

# Production (Gunicorn)
sudo systemctl status havengrazuri
```

### View Logs
```bash
# Django logs
tail -f logs/django.log

# Gunicorn logs
sudo journalctl -u havengrazuri -f
```

### Database Status
```bash
mysql -u root -p -e "SHOW PROCESSLIST"
```

---

## Updates & Maintenance

### Update Code
```bash
git pull origin main
python deploy.py --skip-db
```

### Update Dependencies
```bash
pip install -r requirements.txt --upgrade
```

### Run Migrations
```bash
python manage.py migrate
```

### Clear Cache
```bash
python manage.py clear_cache
```

---

## Security Checklist

### Before Production:
- [ ] Change DEBUG to False
- [ ] Set strong SECRET_KEY
- [ ] Configure ALLOWED_HOSTS
- [ ] Enable HTTPS
- [ ] Set secure cookies
- [ ] Change default passwords
- [ ] Set up firewall
- [ ] Configure backup system
- [ ] Set up monitoring
- [ ] Review user permissions

---

## Support

**Haven Grazuri Investment Limited**
- Email: havenin2023@gmail.com
- Phone: +254112941830
- WhatsApp: +254112941830

---

## Quick Reference

### Start Server
```bash
python manage.py runserver
```

### Stop Server
Press `Ctrl+C`

### Access Admin
http://127.0.0.1:8000/admin/

### Access System
http://127.0.0.1:8000/

### Run Tests
```bash
python manage.py test
```

### Create Backup
```bash
mysqldump -u root -p acbptxvs_branch_system > backup.sql
```

---

**Deployment Script Version:** 1.0  
**Last Updated:** May 8, 2026  
**System:** Haven Grazuri Investment Limited
