# 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** ```bash # Clone repository git clone cd backend # Copy environment file cp .env.example .env ``` ### **2. Configure Environment** Edit `.env` and add your Supabase credentials: ```bash # 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** ```bash # 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** ```bash # 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: - **API Docs**: http://localhost:8000/docs - **Health Check**: http://localhost:8000/health --- ## ๐Ÿ› ๏ธ Manual Setup (Without Docker) ### **1. Create Virtual Environment** ```bash # Create venv python -m venv venv # Activate (Linux/Mac) source venv/bin/activate # Activate (Windows) venv\Scripts\activate ``` ### **2. Install Dependencies** ```bash pip install -r requirements.txt ``` ### **3. Setup Environment** ```bash cp .env.example .env # Edit .env with your configuration ``` ### **4. Start Redis** (Required for Celery) ```bash # 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** ```bash alembic upgrade head ``` ### **6. Start Services** **Terminal 1 - API Server**: ```bash uvicorn app.main:app --reload --host 0.0.0.0 --port 8000 ``` **Terminal 2 - Celery Worker**: ```bash celery -A app.tasks.celery_app worker --loglevel=info ``` **Terminal 3 - Celery Beat** (Scheduler): ```bash celery -A app.tasks.celery_app beat --loglevel=info ``` --- ## ๐Ÿงช Verify Installation ### **1. Health Check** ```bash curl http://localhost:8000/health ``` Expected response: ```json { "status": "healthy", "database": "connected", "redis": "connected", "version": "1.0.0" } ``` ### **2. Run Tests** ```bash # Run all tests pytest # Run with coverage pytest --cov=app --cov-report=html # Open coverage report open htmlcov/index.html ``` ### **3. Test API Endpoint** ```bash # 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**: ```bash # Check DATABASE_URL in .env # Verify Supabase project is running # Test connection: psql $DATABASE_URL ``` ### **Issue: Redis connection failed** **Solution**: ```bash # Check if Redis is running docker ps | grep redis # Or test connection redis-cli ping # Should return: PONG ``` ### **Issue: Celery tasks not running** **Solution**: ```bash # 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**: ```bash # 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**: ```bash # 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** ```bash # 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/`: ```python # app/schemas/ticket.py class TicketCreate(BaseModel): title: str description: str priority: str ``` 2. Add service method in `app/services/`: ```python # app/services/ticket_service.py async def create_ticket(self, data: TicketCreate): # Business logic here pass ``` 3. Add API route in `app/api/v1/`: ```python # 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** ```python # 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** ```bash # 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** ```bash # Connect to database psql $DATABASE_URL # View tables \dt # Describe table \d tickets # Run query SELECT * FROM tickets LIMIT 10; ``` ### **Redis Management** ```bash # 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** ```bash # 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! ๐Ÿš€