# Deployment Guide for payments.taifaguard.co.ke

This guide explains how to deploy the Django backend to production on `https://payments.taifaguard.co.ke` using nginx and gunicorn.

## Prerequisites

- Ubuntu/Debian server with root/sudo access
- Python 3.8+ installed
- PostgreSQL server installed
- Nginx installed
- SSL certificate for payments.taifaguard.co.ke
- Domain DNS pointing to your server IP

## Step 1: Prepare the Server

### 1.1 Create necessary directories

```bash
sudo mkdir -p /var/www/html/internet/buy/backend
sudo mkdir -p /var/log/gunicorn
sudo mkdir -p /var/run/gunicorn
sudo chown -R www-data:www-data /var/www/html/internet
sudo chown -R www-data:www-data /var/log/gunicorn
sudo chown -R www-data:www-data /var/run/gunicorn
```

### 1.2 Upload project files

Upload your project files to `/var/www/html/internet/buy/backend/` or clone from your repository:

```bash
cd /var/www/html/internet/buy/backend
# Upload files here or git clone
```

## Step 2: Install PostgreSQL and Create Database

### 2.1 Install PostgreSQL Server

```bash
sudo apt update
sudo apt install postgresql postgresql-contrib
sudo systemctl start postgresql
sudo systemctl enable postgresql
```

### 2.2 Create Database and User

```bash
sudo -u postgres psql
```

In the PostgreSQL prompt, run:

```sql
CREATE DATABASE internet_payments;
CREATE USER django_user WITH PASSWORD 'your_secure_password_here';
ALTER ROLE django_user SET client_encoding TO 'utf8';
ALTER ROLE django_user SET default_transaction_isolation TO 'read committed';
ALTER ROLE django_user SET timezone TO 'UTC';
GRANT ALL PRIVILEGES ON DATABASE internet_payments TO django_user;
\q
```

### 2.3 Install PostgreSQL Development Libraries

For `psycopg2` to work, you may need PostgreSQL development libraries:

```bash
sudo apt install libpq-dev build-essential
```

## Step 3: Set Up Python Virtual Environment

```bash
cd /var/www/html/internet/buy/backend
python3 -m venv venv
source venv/bin/activate
pip install --upgrade pip
pip install -r requirements.txt
```

**Note:** If `psycopg2-binary` installation fails, you can try installing `psycopg2` instead (requires PostgreSQL development libraries):
```bash
sudo apt install libpq-dev
pip install psycopg2
```

## Step 4: Configure Django Settings

Update `backend/settings.py` for production:

1. Set `DEBUG = False`
2. Update `ALLOWED_HOSTS`:
   ```python
   ALLOWED_HOSTS = ['payments.taifaguard.co.ke', 'www.payments.taifaguard.co.ke']
   ```
3. Set `STATIC_ROOT`:
   ```python
   STATIC_ROOT = BASE_DIR / 'staticfiles'
   ```
4. Update `CORS_ALLOWED_ORIGINS` to include your frontend domain(s)

5. **Create `.env` file** (Recommended):
   ```bash
   cd /var/www/html/internet/buy/backend
   cp .env.example .env
   nano .env
   ```
   
   **Generate a SECRET_KEY:**
   
   You can generate a Django secret key using one of these methods:
   
   **Method 1: Using Django's built-in utility (Recommended)**
   ```bash
   python manage.py shell -c "from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())"
   ```
   
   **Method 2: Using Python one-liner**
   ```bash
   python -c "from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())"
   ```
   
   **Method 3: Using Python script**
   ```python
   from django.core.management.utils import get_random_secret_key
   print(get_random_secret_key())
   ```
   
   Copy the generated secret key and add it to your `.env` file:
   ```env
   SECRET_KEY=django-insecure-abc123xyz789...your-generated-key-here
   DEBUG=False
   ALLOWED_HOSTS=payments.taifaguard.co.ke,www.payments.taifaguard.co.ke
   DB_NAME=internet_payments
   DB_USER=django_user
   DB_PASSWORD=your_secure_password_here
   DB_HOST=localhost
   DB_PORT=5432
   ```
   
   **Note:** The `.env` file is automatically loaded by `python-decouple`. Make sure it's not committed to git (it's already in `.gitignore`).
   
   **Alternative:** You can also set environment variables in your systemd service file (see Step 8) or export them in your shell.

## Step 5: Collect Static Files

```bash
cd /var/www/html/internet/buy/backend
source venv/bin/activate
python manage.py collectstatic --noinput
```

## Step 6: Set Up SSL Certificate

### Option A: Using Let's Encrypt (Recommended)

```bash
sudo apt update
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d payments.taifaguard.co.ke
```

This will automatically configure nginx with SSL certificates.

### Option B: Using Your Own Certificates

Place your SSL certificate and key in:
- Certificate: `/etc/ssl/certs/payments.taifaguard.co.ke.crt`
- Key: `/etc/ssl/private/payments.taifaguard.co.ke.key`

## Step 7: Configure Nginx

1. Copy the nginx configuration:
   ```bash
   sudo cp /var/www/html/internet/buy/backend/nginx.conf /etc/nginx/sites-available/payments.taifaguard.co.ke
   ```

2. If using Let's Encrypt, update the SSL certificate paths in the nginx config:
   ```bash
   sudo nano /etc/nginx/sites-available/payments.taifaguard.co.ke
   ```
   Update these lines:
   ```
   ssl_certificate /etc/letsencrypt/live/payments.taifaguard.co.ke/fullchain.pem;
   ssl_certificate_key /etc/letsencrypt/live/payments.taifaguard.co.ke/privkey.pem;
   ```

3. Enable the site:
   ```bash
   sudo ln -s /etc/nginx/sites-available/payments.taifaguard.co.ke /etc/nginx/sites-enabled/
   ```

4. Test nginx configuration:
   ```bash
   sudo nginx -t
   ```

5. Reload nginx:
   ```bash
   sudo systemctl reload nginx
   ```

## Step 8: Configure Gunicorn Systemd Service

**Important:** Update the systemd service file to include database environment variables:

```bash
sudo nano /etc/systemd/system/payments-backend.service
```

Add the environment variables in the `[Service]` section:

```ini
[Service]
...
Environment="DB_NAME=internet_payments"
Environment="DB_USER=django_user"
Environment="DB_PASSWORD=your_secure_password_here"
Environment="DB_HOST=localhost"
Environment="DB_PORT=5432"
Environment="DJANGO_SECRET_KEY=your-secret-key-here"
...
```

1. Copy the systemd service file:
   ```bash
   sudo cp /var/www/html/internet/buy/backend/payments-backend.service /etc/systemd/system/
   ```

2. Update the service file if your virtual environment path is different:
   ```bash
   sudo nano /etc/systemd/system/payments-backend.service
   ```

3. Reload systemd and start the service:
   ```bash
   sudo systemctl daemon-reload
   sudo systemctl enable payments-backend
   sudo systemctl start payments-backend
   ```

4. Check service status:
   ```bash
   sudo systemctl status payments-backend
   ```

5. View logs if there are issues:
   ```bash
   sudo journalctl -u payments-backend -f
   ```

## Step 9: Run Database Migrations

```bash
cd /var/www/html/internet/buy/backend
source venv/bin/activate
python manage.py migrate
```

## Step 10: Create Superuser (Optional)

```bash
cd /var/www/html/internet/buy/backend
source venv/bin/activate
python manage.py createsuperuser
```

## Step 11: Verify Deployment

1. Check nginx is running:
   ```bash
   sudo systemctl status nginx
   ```

2. Check gunicorn service is running:
   ```bash
   sudo systemctl status payments-backend
   ```

3. Test the site:
   - Visit `https://payments.taifaguard.co.ke` in your browser
   - Check that SSL certificate is valid
   - Test your API endpoints

## Useful Commands

### Restart Services

```bash
# Restart Django backend
sudo systemctl restart payments-backend

# Restart nginx
sudo systemctl restart nginx

# Restart both
sudo systemctl restart payments-backend nginx
```

### View Logs

```bash
# Gunicorn logs
sudo tail -f /var/log/gunicorn/payments_backend_error.log
sudo tail -f /var/log/gunicorn/payments_backend_access.log

# Nginx logs
sudo tail -f /var/log/nginx/payments.taifaguard.co.ke.error.log
sudo tail -f /var/log/nginx/payments.taifaguard.co.ke.access.log

# Systemd service logs
sudo journalctl -u payments-backend -f
```

### Update Code

```bash
cd /var/www/html/internet/buy/backend
source venv/bin/activate
# Pull latest code or upload new files
pip install -r requirements.txt  # If dependencies changed
python manage.py collectstatic --noinput  # If static files changed
python manage.py migrate  # If database schema changed
sudo systemctl restart payments-backend
```

## Security Considerations

1. **Firewall**: Ensure only ports 80 and 443 are open:
   ```bash
   sudo ufw allow 80/tcp
   sudo ufw allow 443/tcp
   sudo ufw enable
   ```

2. **SECRET_KEY**: Generate a strong secret key and store it in `.env` file:
   ```bash
   # Generate secret key
   python manage.py shell -c "from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())"
   ```
   Then add it to your `.env` file:
   ```env
   SECRET_KEY=your-generated-secret-key-here
   ```
   Never commit the secret key to version control. It's already in `.gitignore`.

3. **Database**: PostgreSQL is configured. Ensure database credentials are stored securely using environment variables, not hardcoded in settings.py

4. **File Permissions**: Ensure proper file ownership:
   ```bash
   sudo chown -R www-data:www-data /var/www/html/internet/buy/backend
   sudo chmod -R 755 /var/www/html/internet/buy/backend
   ```

## Troubleshooting

### 502 Bad Gateway
- Check if gunicorn is running: `sudo systemctl status payments-backend`
- Check gunicorn logs: `sudo tail -f /var/log/gunicorn/payments_backend_error.log`
- Verify the port in gunicorn_config.py matches nginx upstream

### Static files not loading
- Run `python manage.py collectstatic --noinput`
- Check nginx static file path matches STATIC_ROOT
- Verify file permissions

### SSL certificate issues
- Verify certificate paths in nginx config
- Check certificate expiration: `sudo certbot certificates`
- Renew if needed: `sudo certbot renew`

### Permission denied errors
- Check file ownership: `ls -la /var/www/html/internet/buy/backend`
- Fix ownership: `sudo chown -R www-data:www-data /var/www/html/internet/buy/backend`

### PostgreSQL connection errors
- Verify PostgreSQL is running: `sudo systemctl status postgresql`
- Test database connection: `psql -U django_user -d internet_payments -h localhost`
- Check environment variables are set correctly in systemd service
- Verify database user has correct permissions: `sudo -u postgres psql -c "\du"`
- Check PostgreSQL authentication in `/etc/postgresql/*/main/pg_hba.conf` (should allow local connections)
- Verify PostgreSQL is listening on the correct address: `sudo netstat -plnt | grep 5432`

