Spaces:
Sleeping
Sleeping
File size: 20,358 Bytes
1e89ad0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 |
# SwiftOps Backend Architecture
## ποΈ Architectural Principles
### **1. Clean Architecture**
The application follows clean architecture principles with clear separation of concerns:
```
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Presentation Layer β
β (FastAPI Routes, WebSockets) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Service Layer β
β (Business Logic, Orchestration) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Repository Layer β
β (Data Access, Queries) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Database Layer β
β (PostgreSQL via Supabase) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
**Benefits**:
- **Testability**: Each layer can be tested independently
- **Maintainability**: Changes in one layer don't affect others
- **Scalability**: Easy to add new features without breaking existing code
- **Flexibility**: Can swap implementations (e.g., change database, payment gateway)
---
## π¦ Layer Responsibilities
### **Presentation Layer** (`app/api/`)
**Responsibility**: Handle HTTP requests/responses, input validation, authentication
**What it does**:
- Parse request data
- Validate input using Pydantic schemas
- Call service layer methods
- Format responses
- Handle errors and return appropriate HTTP status codes
**What it DOESN'T do**:
- Business logic
- Direct database access
- Complex calculations
**Example**:
```python
# app/api/v1/tickets.py
@router.post("/tickets/{ticket_id}/assign")
async def assign_ticket(
ticket_id: UUID,
assignment: TicketAssignmentCreate,
current_user: User = Depends(get_current_user),
ticket_service: TicketService = Depends(get_ticket_service)
):
"""Assign a ticket to a field agent."""
try:
result = await ticket_service.assign_ticket(
ticket_id=ticket_id,
user_id=assignment.user_id,
assigned_by=current_user.id
)
return {"success": True, "data": result}
except BusinessRuleViolation as e:
raise HTTPException(status_code=400, detail=str(e))
```
---
### **Service Layer** (`app/services/`)
**Responsibility**: Implement business logic, orchestrate operations, enforce business rules
**What it does**:
- Validate business rules
- Coordinate multiple repository calls
- Handle transactions
- Trigger side effects (notifications, webhooks)
- Calculate derived values (payroll, SLA deadlines)
**What it DOESN'T do**:
- Direct SQL queries
- HTTP request handling
- Data formatting for API responses
**Example**:
```python
# app/services/ticket_service.py
class TicketService:
def __init__(
self,
ticket_repo: TicketRepository,
assignment_repo: AssignmentRepository,
notification_service: NotificationService,
sla_service: SLAService
):
self.ticket_repo = ticket_repo
self.assignment_repo = assignment_repo
self.notification_service = notification_service
self.sla_service = sla_service
async def assign_ticket(self, ticket_id: UUID, user_id: UUID, assigned_by: UUID):
"""Assign ticket to user with business rule validation."""
# 1. Get ticket and validate
ticket = await self.ticket_repo.get_by_id(ticket_id)
if not ticket:
raise TicketNotFoundError(ticket_id)
if ticket.status != 'open':
raise BusinessRuleViolation("Can only assign open tickets")
# 2. Validate user can be assigned
active_assignments = await self.assignment_repo.count_active_assignments(user_id)
if active_assignments >= 3:
raise BusinessRuleViolation("User already has 3 active assignments")
# 3. Check user is in project team
if not await self._user_in_project_team(user_id, ticket.project_id):
raise BusinessRuleViolation("User not in project team")
# 4. Create assignment
assignment = await self.assignment_repo.create(
ticket_id=ticket_id,
user_id=user_id,
action='assigned',
assigned_at=datetime.utcnow()
)
# 5. Update ticket status
await self.ticket_repo.update_status(ticket_id, 'assigned')
# 6. Calculate SLA deadline
sla_deadline = await self.sla_service.calculate_deadline(ticket)
await self.ticket_repo.update_sla(ticket_id, sla_deadline)
# 7. Send notification
await self.notification_service.send_assignment_notification(user_id, ticket)
return assignment
```
---
### **Repository Layer** (`app/repositories/`)
**Responsibility**: Data access, database queries, ORM operations
**What it does**:
- CRUD operations
- Complex queries
- Filtering and pagination
- Soft delete handling
- Optimistic locking
**What it DOESN'T do**:
- Business logic
- Validation (beyond data integrity)
- Side effects (notifications, webhooks)
**Example**:
```python
# app/repositories/ticket_repository.py
class TicketRepository:
def __init__(self, db: Session):
self.db = db
async def get_by_id(self, ticket_id: UUID) -> Optional[Ticket]:
"""Get ticket by ID, excluding soft-deleted."""
return self.db.query(Ticket).filter(
Ticket.id == ticket_id,
Ticket.deleted_at.is_(None)
).first()
async def get_open_tickets(
self,
project_id: UUID,
limit: int = 50,
offset: int = 0
) -> List[Ticket]:
"""Get open tickets for a project with pagination."""
return self.db.query(Ticket).filter(
Ticket.project_id == project_id,
Ticket.status == 'open',
Ticket.deleted_at.is_(None)
).order_by(Ticket.created_at.desc()).limit(limit).offset(offset).all()
async def update_status(self, ticket_id: UUID, status: str) -> Ticket:
"""Update ticket status."""
ticket = await self.get_by_id(ticket_id)
ticket.status = status
ticket.updated_at = datetime.utcnow()
self.db.commit()
self.db.refresh(ticket)
return ticket
```
---
## π Data Flow Examples
### **Example 1: Ticket Assignment Flow**
```
1. Frontend sends POST /api/v1/tickets/{id}/assign
β
2. API Route (tickets.py)
- Validates JWT token
- Parses request body
- Calls TicketService.assign_ticket()
β
3. TicketService
- Validates business rules (max 3 assignments)
- Calls TicketRepository.get_by_id()
- Calls AssignmentRepository.count_active_assignments()
- Calls AssignmentRepository.create()
- Calls TicketRepository.update_status()
- Calls SLAService.calculate_deadline()
- Calls NotificationService.send_notification()
β
4. Repositories
- Execute SQL queries via SQLAlchemy
- Return data to service
β
5. Service returns result to API route
β
6. API route formats response and returns to frontend
```
---
### **Example 2: Payroll Generation Flow (Background Task)**
```
1. Celery Beat triggers weekly payroll task (Friday 6 PM)
β
2. PayrollTask (tasks/payroll_tasks.py)
- Calls PayrollService.generate_weekly_payroll()
β
3. PayrollService
- Gets all active projects
- For each project:
- Gets project team members
- For each member:
- Calls PayrollRepository.get_tickets_closed()
- Calls TimesheetRepository.get_hours_worked()
- Calculates earnings based on compensation type
- Calls PayrollRepository.create()
- Calls FinanceService.create_transaction()
β
4. Repositories
- Execute queries and insert payroll records
β
5. Service sends notifications to users
β
6. Task completes and logs result
```
---
## π Security Architecture
### **1. Authentication Flow**
```
1. User logs in via Supabase Auth
β
2. Supabase returns JWT token
β
3. Frontend includes token in Authorization header
β
4. FastAPI middleware validates token
β
5. Extracts user_id from token
β
6. Loads User from database
β
7. Checks user role and permissions
β
8. Allows/denies request
```
### **2. Row-Level Security (RLS)**
**Database Level** (Supabase RLS Policies):
```sql
-- Example: Users can only see tickets from their projects
CREATE POLICY "Users see own project tickets"
ON Tickets FOR SELECT
USING (
project_id IN (
SELECT project_id FROM ProjectTeam WHERE user_id = auth.uid()
)
);
```
**Application Level** (Service Layer):
```python
# Always filter by user's accessible projects
async def get_tickets(self, user: User):
project_ids = await self._get_user_project_ids(user.id)
return await self.ticket_repo.get_by_projects(project_ids)
```
### **3. Multi-Tenancy Isolation**
**Client Isolation**:
```python
# Every query scoped to user's client
async def get_customers(self, user: User):
if user.client_id:
return await self.customer_repo.get_by_client(user.client_id)
elif user.contractor_id:
# Contractor sees customers from their projects
project_ids = await self._get_contractor_projects(user.contractor_id)
return await self.customer_repo.get_by_projects(project_ids)
```
---
## π Caching Strategy
### **What to Cache**
1. **User Sessions** (Redis, TTL: 30 minutes)
- User profile
- User permissions
- User's active projects
2. **Dashboard Metrics** (Redis, TTL: 5 minutes)
- Ticket counts by status
- SLA compliance rates
- Agent workload
3. **Configuration** (Redis, TTL: 1 hour)
- System settings
- Feature flags
- SLA thresholds
4. **Location Data** (Redis, TTL: 1 minute)
- Agent current locations
- Real-time tracking data
### **Cache Invalidation**
```python
# Example: Invalidate cache on ticket status change
async def update_ticket_status(self, ticket_id: UUID, status: str):
ticket = await self.ticket_repo.update_status(ticket_id, status)
# Invalidate related caches
await cache.delete(f"ticket:{ticket_id}")
await cache.delete(f"project:{ticket.project_id}:tickets")
await cache.delete(f"dashboard:metrics:{ticket.project_id}")
return ticket
```
---
## π Background Tasks Architecture
### **Celery Task Types**
1. **Scheduled Tasks** (Celery Beat)
- Weekly payroll generation (Friday 6 PM)
- Daily SLA monitoring (every hour)
- Daily metrics computation (midnight)
- Invoice generation (end of month)
2. **Async Tasks** (Triggered by API)
- Send email notifications
- Send SMS notifications
- Process payment gateway callbacks
- Generate reports
3. **Retry Tasks** (Failed payment retries)
- Retry failed M-Pesa payments
- Retry failed SMS deliveries
### **Task Configuration**
```python
# app/tasks/celery_app.py
from celery import Celery
from celery.schedules import crontab
celery_app = Celery('swiftops')
celery_app.conf.beat_schedule = {
'generate-weekly-payroll': {
'task': 'app.tasks.payroll_tasks.generate_weekly_payroll',
'schedule': crontab(day_of_week=5, hour=18, minute=0), # Friday 6 PM
},
'monitor-sla-violations': {
'task': 'app.tasks.sla_tasks.monitor_sla_violations',
'schedule': crontab(minute=0), # Every hour
},
'compute-daily-metrics': {
'task': 'app.tasks.analytics_tasks.compute_daily_metrics',
'schedule': crontab(hour=0, minute=0), # Midnight
},
}
```
---
## π Scalability Patterns
### **1. Horizontal Scaling**
**Stateless API Design**:
- No session state stored in API servers
- All state in database or Redis
- Can run multiple API instances behind load balancer
**Load Balancing**:
```
βββββββββββββββ
βLoad Balancerβ
βββββββββββββββ
β
ββββββββββββββββββββΌβββββββββββββββββββ
β β β
βββββββββββ βββββββββββ βββββββββββ
β API #1 β β API #2 β β API #3 β
βββββββββββ βββββββββββ βββββββββββ
β β β
ββββββββββββββββββββΌβββββββββββββββββββ
β
βββββββββββββββ
β Database β
βββββββββββββββ
```
### **2. Database Optimization**
**Read Replicas**:
- Use read replicas for reporting queries
- Master for writes, replicas for reads
**Connection Pooling**:
```python
# app/db/session.py
engine = create_engine(
DATABASE_URL,
pool_size=20, # Max connections in pool
max_overflow=10, # Additional connections if pool full
pool_pre_ping=True, # Verify connections before use
pool_recycle=3600 # Recycle connections after 1 hour
)
```
**Query Optimization**:
- Use indexes effectively (already in schema)
- Avoid N+1 queries (use eager loading)
- Paginate large result sets
- Use database views for complex queries
### **3. Caching Strategy**
**Multi-Level Caching**:
```
Request β API β L1 Cache (In-Memory) β L2 Cache (Redis) β Database
```
**Cache-Aside Pattern**:
```python
async def get_ticket(self, ticket_id: UUID):
# Try cache first
cached = await cache.get(f"ticket:{ticket_id}")
if cached:
return cached
# Cache miss, query database
ticket = await self.ticket_repo.get_by_id(ticket_id)
# Store in cache
await cache.set(f"ticket:{ticket_id}", ticket, ttl=300)
return ticket
```
---
## π§ͺ Testing Strategy
### **Test Pyramid**
```
βββββββββββ
β E2E β (Few, slow, expensive)
βββββββββββ
βββββββββββββββββ
β Integration β (Some, medium speed)
βββββββββββββββββ
βββββββββββββββββββββββββ
β Unit Tests β (Many, fast, cheap)
βββββββββββββββββββββββββ
```
### **Unit Tests** (70% of tests)
- Test individual functions
- Mock external dependencies
- Fast execution (< 1 second per test)
```python
# tests/unit/test_services/test_payroll_service.py
def test_calculate_flat_rate_payroll():
# Arrange
role = Mock(compensation_type='flat_rate', flat_rate_amount=5000)
# Act
earnings = payroll_service._calculate_earnings(role, tickets=[], hours=0)
# Assert
assert earnings == 5000
```
### **Integration Tests** (25% of tests)
- Test multiple components together
- Use test database
- Medium speed (1-5 seconds per test)
```python
# tests/integration/test_api/test_tickets.py
def test_assign_ticket_endpoint(client, test_db):
# Create test data
ticket = create_test_ticket(test_db)
user = create_test_user(test_db)
# Call API
response = client.post(
f"/api/v1/tickets/{ticket.id}/assign",
json={"user_id": str(user.id)}
)
# Assert
assert response.status_code == 200
assert test_db.query(TicketAssignment).count() == 1
```
### **E2E Tests** (5% of tests)
- Test complete user workflows
- Use real database (or close replica)
- Slow (10+ seconds per test)
```python
# tests/e2e/test_ticket_workflow.py
def test_complete_ticket_workflow(client, test_db):
# 1. Create sales order
# 2. Generate ticket from sales order
# 3. Assign ticket to agent
# 4. Agent accepts assignment
# 5. Agent arrives at site
# 6. Agent completes work
# 7. Subscription activated
# 8. Verify all state changes
```
---
## π Monitoring & Observability
### **Logging Strategy**
**Log Levels**:
- **DEBUG**: Detailed information for debugging
- **INFO**: General informational messages
- **WARNING**: Warning messages (non-critical issues)
- **ERROR**: Error messages (handled exceptions)
- **CRITICAL**: Critical errors (system failures)
**Structured Logging**:
```python
import structlog
logger = structlog.get_logger()
logger.info(
"ticket_assigned",
ticket_id=str(ticket_id),
user_id=str(user_id),
project_id=str(project_id),
assigned_by=str(assigned_by)
)
```
### **Metrics to Track**
1. **API Metrics**
- Request rate (requests/second)
- Response time (p50, p95, p99)
- Error rate (4xx, 5xx)
2. **Business Metrics**
- Tickets created/assigned/completed per day
- Average ticket completion time
- SLA compliance rate
- Payroll processing time
3. **System Metrics**
- Database connection pool usage
- Cache hit rate
- Celery queue length
- Memory/CPU usage
### **Error Tracking**
Use Sentry for error tracking:
```python
import sentry_sdk
sentry_sdk.init(
dsn=SENTRY_DSN,
environment=ENVIRONMENT,
traces_sample_rate=0.1
)
```
---
## π§ Development Workflow
### **Local Development**
1. Start services:
```bash
docker-compose up -d postgres redis
```
2. Run migrations:
```bash
alembic upgrade head
```
3. Start API:
```bash
uvicorn app.main:app --reload
```
4. Start Celery:
```bash
celery -A app.tasks.celery_app worker --loglevel=info
```
### **Code Quality**
**Pre-commit Hooks**:
- Black (code formatting)
- isort (import sorting)
- flake8 (linting)
- mypy (type checking)
**CI/CD Pipeline**:
1. Run tests
2. Check code coverage (> 80%)
3. Run linters
4. Build Docker image
5. Deploy to staging
6. Run E2E tests
7. Deploy to production
---
## π Additional Resources
- [FastAPI Documentation](https://fastapi.tiangolo.com/)
- [SQLAlchemy Documentation](https://docs.sqlalchemy.org/)
- [Celery Documentation](https://docs.celeryproject.org/)
- [Supabase Documentation](https://supabase.com/docs)
- [Clean Architecture](https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html)
|