kamau1's picture
chore: migrate to useast organize the docs, delete redundant migrations
c4f7e3e

SwiftOps Backend - Quick Start Guide

Get the backend running in 5 minutes.


πŸš€ Prerequisites

  • Python 3.11+
  • Docker & Docker Compose
  • Git

⚑ Quick Setup (Docker)

1. Clone and Setup

# Clone repository
git clone <repo-url>
cd backend

# Copy environment file
cp .env.example .env

2. Configure Environment

Edit .env and add your Supabase credentials:

# Minimum required configuration
DATABASE_URL=postgresql://postgres:password@db.your-project.supabase.co:5432/postgres
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_ANON_KEY=your-anon-key
SUPABASE_SERVICE_KEY=your-service-key
SECRET_KEY=your-secret-key-change-this

3. Start Everything

# Start all services (API, Celery, Redis, PostgreSQL)
docker-compose up -d

# View logs
docker-compose logs -f api

# Check status
docker-compose ps

4. Run Migrations

# Run database migrations
docker-compose exec api alembic upgrade head

# Seed test data (optional)
docker-compose exec api python scripts/seed_data.py

5. Test the API

Open your browser:


πŸ› οΈ Manual Setup (Without Docker)

1. Create Virtual Environment

# Create venv
python -m venv venv

# Activate (Linux/Mac)
source venv/bin/activate

# Activate (Windows)
venv\Scripts\activate

2. Install Dependencies

pip install -r requirements.txt

3. Setup Environment

cp .env.example .env
# Edit .env with your configuration

4. Start Redis (Required for Celery)

# Using Docker
docker run -d -p 6379:6379 redis:alpine

# Or install Redis locally
# Mac: brew install redis && redis-server
# Ubuntu: sudo apt install redis-server && redis-server

5. Run Migrations

alembic upgrade head

6. Start Services

Terminal 1 - API Server:

uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

Terminal 2 - Celery Worker:

celery -A app.tasks.celery_app worker --loglevel=info

Terminal 3 - Celery Beat (Scheduler):

celery -A app.tasks.celery_app beat --loglevel=info

πŸ§ͺ Verify Installation

1. Health Check

curl http://localhost:8000/health

Expected response:

{
  "status": "healthy",
  "database": "connected",
  "redis": "connected",
  "version": "1.0.0"
}

2. Run Tests

# Run all tests
pytest

# Run with coverage
pytest --cov=app --cov-report=html

# Open coverage report
open htmlcov/index.html

3. Test API Endpoint

# Create a test user (if seed data not loaded)
curl -X POST http://localhost:8000/api/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "test@example.com",
    "password": "testpassword123",
    "name": "Test User"
  }'

# Login
curl -X POST http://localhost:8000/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "test@example.com",
    "password": "testpassword123"
  }'

πŸ“ Project Structure Overview

backend/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ api/              # API endpoints
β”‚   β”œβ”€β”€ services/         # Business logic
β”‚   β”œβ”€β”€ repositories/     # Data access
β”‚   β”œβ”€β”€ models/           # Database models
β”‚   β”œβ”€β”€ schemas/          # Request/response schemas
β”‚   └── tasks/            # Background tasks
β”œβ”€β”€ tests/                # Test suite
β”œβ”€β”€ scripts/              # Utility scripts
└── .env                  # Configuration

πŸ”‘ Key Endpoints

Authentication

  • POST /api/v1/auth/login - User login
  • POST /api/v1/auth/register - User registration
  • POST /api/v1/auth/refresh - Refresh token

Tickets

  • GET /api/v1/tickets - List tickets
  • POST /api/v1/tickets - Create ticket
  • POST /api/v1/tickets/{id}/assign - Assign ticket
  • PATCH /api/v1/tickets/{id}/status - Update status

Payroll

  • GET /api/v1/payroll - List payroll records
  • POST /api/v1/payroll/generate - Generate payroll
  • PATCH /api/v1/payroll/{id}/mark-paid - Mark as paid

Inventory

  • GET /api/v1/inventory - List inventory
  • POST /api/v1/inventory/assign - Assign to agent
  • POST /api/v1/inventory/return - Return equipment

Analytics

  • GET /api/v1/analytics/dashboard - Dashboard metrics
  • GET /api/v1/analytics/agent-performance - Agent stats
  • GET /api/v1/analytics/sla-compliance - SLA reports

πŸ› Troubleshooting

Issue: Database connection failed

Solution:

# Check DATABASE_URL in .env
# Verify Supabase project is running
# Test connection:
psql $DATABASE_URL

Issue: Redis connection failed

Solution:

# Check if Redis is running
docker ps | grep redis

# Or test connection
redis-cli ping
# Should return: PONG

Issue: Celery tasks not running

Solution:

# Check Celery worker is running
celery -A app.tasks.celery_app inspect active

# Check Celery beat is running
celery -A app.tasks.celery_app inspect scheduled

# View Celery logs
docker-compose logs -f celery-worker

Issue: Import errors

Solution:

# Ensure virtual environment is activated
which python
# Should show: /path/to/venv/bin/python

# Reinstall dependencies
pip install -r requirements.txt --force-reinstall

Issue: Alembic migration failed

Solution:

# Check current migration version
alembic current

# Downgrade one version
alembic downgrade -1

# Upgrade again
alembic upgrade head

# If stuck, reset migrations (CAUTION: drops all data)
alembic downgrade base
alembic upgrade head

πŸ“ Common Development Tasks

Create a New Migration

# Auto-generate migration from model changes
alembic revision --autogenerate -m "Add new column to tickets"

# Create empty migration
alembic revision -m "Custom migration"

# Apply migration
alembic upgrade head

Add a New API Endpoint

  1. Create schema in app/schemas/:
# app/schemas/ticket.py
class TicketCreate(BaseModel):
    title: str
    description: str
    priority: str
  1. Add service method in app/services/:
# app/services/ticket_service.py
async def create_ticket(self, data: TicketCreate):
    # Business logic here
    pass
  1. Add API route in app/api/v1/:
# app/api/v1/tickets.py
@router.post("/tickets")
async def create_ticket(
    data: TicketCreate,
    service: TicketService = Depends(get_ticket_service)
):
    return await service.create_ticket(data)

Add a Background Task

# app/tasks/custom_tasks.py
from app.tasks.celery_app import celery_app

@celery_app.task
def my_background_task(param1, param2):
    # Task logic here
    pass

# Trigger from API
my_background_task.delay(param1, param2)

Run Specific Tests

# Run single test file
pytest tests/unit/test_services/test_ticket_service.py

# Run single test function
pytest tests/unit/test_services/test_ticket_service.py::test_assign_ticket

# Run tests matching pattern
pytest -k "test_ticket"

# Run with verbose output
pytest -v

# Run with print statements
pytest -s

πŸ”§ Development Tools

Database Management

# Connect to database
psql $DATABASE_URL

# View tables
\dt

# Describe table
\d tickets

# Run query
SELECT * FROM tickets LIMIT 10;

Redis Management

# Connect to Redis
redis-cli

# View all keys
KEYS *

# Get value
GET ticket:123

# Delete key
DEL ticket:123

# Clear all data (CAUTION)
FLUSHALL

API Testing with HTTPie

# Install HTTPie
pip install httpie

# Test endpoint
http GET http://localhost:8000/api/v1/tickets \
  Authorization:"Bearer YOUR_TOKEN"

# POST request
http POST http://localhost:8000/api/v1/tickets \
  Authorization:"Bearer YOUR_TOKEN" \
  title="Test Ticket" \
  description="Test description"

πŸ“š Next Steps

  1. Read the Architecture Guide: ARCHITECTURE.md
  2. Explore API Documentation: http://localhost:8000/docs
  3. Review Code Examples: Check app/services/ for business logic patterns
  4. Write Tests: Add tests for new features in tests/
  5. Check Background Tasks: Review app/tasks/ for scheduled jobs

πŸ†˜ Getting Help

  • Documentation: See README.md and ARCHITECTURE.md
  • API Docs: http://localhost:8000/docs
  • Issues: Create an issue on GitHub
  • Team Chat: [Your team communication channel]

βœ… Checklist for New Developers

  • Clone repository
  • Setup environment variables
  • Start services (Docker or manual)
  • Run migrations
  • Run tests (all passing)
  • Access API docs at http://localhost:8000/docs
  • Create a test ticket via API
  • Review architecture documentation
  • Understand folder structure
  • Ready to code! πŸš€