# Notification & Alert Microservice - Detailed Development Plan

This plan breaks down the multi-tenant B2B implementation into tiny, manageable components.

## Phase 1: Project Foundation & Setup

### 1.1 Project Initialization
- Initialize NestJS project with `nest new`
- Configure TypeScript with strict mode
- Set up project structure (src/, modules/, common/, config/, database/)
- Configure package.json with all required dependencies
- Set up .env.example with all configuration variables
- Create .gitignore with appropriate exclusions
- Set up ESLint and Prettier configuration

### 1.2 Configuration Module
- Install and configure `@nestjs/config`
- Create config schema with validation
- Set up environment variable definitions (DB, Redis, JWT, Pusher, FCM, APNs, S3)
- Create config service with typed getters
- Add configuration for different environments (dev, staging, prod)

### 1.3 Database Setup
- Install TypeORM and MySQL driver
- Configure TypeORM module with connection options
- Set up database connection pooling
- Create database configuration in config module
- Add migration configuration
- Create initial migration setup script

### 1.4 Redis Setup
- Install Redis client library
- Configure Redis connection module
- Set up Redis connection with retry logic
- Create Redis service wrapper
- Configure Redis Streams connection (project-scoped streams)
- Add Redis health check

### 1.5 Logging Setup
- Install and configure Winston logger
- Create custom logger service
- Set up log levels and formatting
- Configure structured logging with correlation IDs and project context
- Add request logging interceptor
- Set up log rotation and retention

### 1.6 Health Check
- Create health check module
- Implement basic health endpoint (`GET /health`)
- Add database health check
- Add Redis health check
- Add detailed status endpoint (`GET /api/v1/status`)
- Include Pusher, MySQL, Redis, queue health in status

---

## Phase 2: Database Models & Migrations (Multi-Tenant)

### 2.1 Base Entity
- Create base entity class with common fields (id, createdAt, updatedAt)
- Add UUID generation utility
- Set up soft delete support if needed

### 2.2 Project Entity
- Create Project entity with all fields (id, name, slug, description, apiKey, apiKeyHash, webhookUrl, status, settings)
- Add unique constraints on name, slug, apiKeyHash
- Configure JSON column for settings (Pusher config, rate limits, etc.)
- Add indexes on slug, apiKeyHash, status
- Create Project repository
- Add methods: findBySlug, findByApiKeyHash, findActiveProjects

### 2.3 User Entity (Project-Scoped)
- Create User entity with projectId foreign key
- Add unique constraints on (projectId, email) and (projectId, phone)
- Configure JSON columns for roles, pushTokens, pusherChannels
- Add indexes on projectId, email, phone, status
- Create User repository with project-scoped queries
- Add composite unique constraints

### 2.4 Role Entity (Project-Scoped)
- Create Role entity with projectId foreign key
- Add unique constraint on (projectId, name)
- Configure JSON column for permissions
- Add indexes on projectId, name
- Create Role repository with project-scoped queries

### 2.5 Rule Entity (Project-Scoped)
- Create Rule entity with projectId foreign key
- Add foreign key relationship to User (createdBy) and Project
- Configure JSON column for targetRoles
- Add indexes on projectId, active, priority, createdBy
- Create Rule repository with project-scoped queries

### 2.6 Event Entity (Project-Scoped)
- Create Event entity with projectId foreign key
- Add indexes on projectId, type, receivedAt
- Configure JSON column for payload
- Create Event repository with project-scoped queries

### 2.7 Notification Entity (Project-Scoped)
- Create Notification entity with projectId foreign key
- Add foreign key relationships to Rule, Event, and Project
- Configure JSON columns for recipients, action, acknowledgedBy
- Add indexes on projectId, ruleId, eventId, delivered, createdAt
- Create Notification repository with project-scoped queries

### 2.8 AuditLog Entity (Project-Scoped)
- Create AuditLog entity with projectId (nullable for system logs)
- Add indexes on projectId, userId, resourceType, timestamp
- Configure JSON column for metadata
- Create AuditLog repository with project-scoped queries

### 2.9 TransferBucket Entity (Project-Scoped)
- Create TransferBucket entity with projectId foreign key
- Add indexes on projectId, name
- Create TransferBucket repository with project-scoped queries

### 2.10 Database Migrations
- Create migration for Project table
- Create migration for User table (with projectId)
- Create migration for Role table (with projectId)
- Create migration for Rule table (with projectId)
- Create migration for Event table (with projectId)
- Create migration for Notification table (with projectId)
- Create migration for AuditLog table (with projectId)
- Create migration for TransferBucket table (with projectId)
- Create seed migration for default super admin user
- Add foreign key constraints and indexes

---

## Phase 3: Projects Module (Multi-Tenant Foundation)

### 3.1 Projects Module Setup
- Create ProjectsModule
- Import necessary dependencies (TypeORM)
- Set up module providers and exports

### 3.2 Projects DTOs
- Create CreateProjectDto (name, slug, description, webhookUrl, settings)
- Create UpdateProjectDto
- Create ProjectResponseDto
- Create RegenerateApiKeyDto
- Create ProjectStatsDto
- Add validation decorators (slug format, name uniqueness)

### 3.3 Projects Service
- Implement create method (generate API key, hash it, create project)
- Implement findAll method (with pagination and filters)
- Implement findById method
- Implement findBySlug method
- Implement findByApiKeyHash method (for authentication)
- Implement update method
- Implement delete method (soft delete)
- Implement regenerateApiKey method (invalidate old, generate new)
- Implement getStats method (user count, rule count, notification count)
- Add API key generation utility (cryptographically secure)
- Add API key hashing utility (bcrypt or similar)

### 3.4 Projects Controller
- Create POST /api/v1/projects endpoint (Super Admin only)
- Create GET /api/v1/projects endpoint (Super Admin only, with pagination)
- Create GET /api/v1/projects/:id endpoint
- Create PUT /api/v1/projects/:id endpoint (Super Admin only)
- Create DELETE /api/v1/projects/:id endpoint (Super Admin only)
- Create POST /api/v1/projects/:id/regenerate-api-key endpoint (Super Admin only)
- Create GET /api/v1/projects/:id/stats endpoint
- Add proper guards and validation

---

## Phase 4: Project Context & Multi-Tenant Infrastructure

### 4.1 Project Context Service
- Create ProjectContextService
- Implement setProject method (store in request context)
- Implement getProject method (retrieve from request context)
- Implement clearProject method
- Use AsyncLocalStorage or request-scoped service for context management

### 4.2 API Key Guard
- Create ApiKeyGuard
- Extract API key from `X-API-Key` header
- Hash the API key
- Look up project by apiKeyHash
- Validate project status (must be active)
- Set project context in ProjectContextService
- Handle invalid/missing API key errors

### 4.3 Project Guard
- Create ProjectGuard
- Extract project from JWT token (for user authentication)
- Or extract from API key (for external applications)
- Validate project exists and is active
- Set project context in ProjectContextService

### 4.4 Project Context Interceptor
- Create ProjectContextInterceptor
- Automatically inject project context into all requests
- Ensure project context is available in all services
- Add project context to logs

### 4.5 Project-Scoped Decorator
- Create @ProjectScoped() decorator
- Automatically apply project filtering to queries
- Use with TypeORM repositories

### 4.6 Current Project Decorator
- Create @CurrentProject() decorator
- Extract current project from request context
- Use in controllers to get current project

### 4.7 Base Repository with Project Scoping
- Create BaseRepository class
- Add automatic project filtering to all queries
- Override find, findOne, create, update, delete methods
- Ensure all queries include projectId filter

---

## Phase 5: Authentication & Authorization (Multi-Tenant)

### 5.1 Auth Module Setup
- Create AuthModule
- Install JWT and Passport packages
- Configure JWT module with secret and expiration
- Set up Passport JWT strategy (project-aware)
- Configure refresh token strategy
- Integrate with ProjectContextService

### 5.2 Password Utilities
- Create password hashing service using bcrypt
- Implement password comparison utility
- Add password strength validation
- Create password reset token generation

### 5.3 Auth DTOs
- Create RegisterDto with validation (email, phone, password, fullName, projectId or projectSlug)
- Create LoginDto with validation (email, password, projectId or projectSlug)
- Create RefreshTokenDto
- Create ChangePasswordDto
- Add validation decorators and custom validators

### 5.4 Auth Service (Project-Scoped)
- Implement register method (hash password, create user with 'pending' status, associate with project)
- Implement login method (validate credentials, validate project, generate JWT tokens with project context)
- Implement refresh token method (validate project context)
- Implement logout method (invalidate token)
- Add user status validation (only active users can login)
- Ensure all operations are project-scoped

### 5.5 Auth Controller
- Create POST /api/v1/auth/register endpoint (requires project context)
- Create POST /api/v1/auth/login endpoint (requires project context)
- Create POST /api/v1/auth/refresh endpoint
- Create POST /api/v1/auth/logout endpoint
- Add proper error handling and responses

### 5.6 JWT Guards (Project-Aware)
- Create JwtAuthGuard extending AuthGuard('jwt')
- Implement token validation
- Extract user and project from token payload
- Validate project context matches token
- Handle token expiration errors

### 5.7 Role Guards (Project-Aware)
- Create RolesGuard for role-based access control
- Implement @Roles() decorator
- Check user roles against required roles (within project)
- Handle unauthorized access errors

### 5.8 Custom Decorators
- Create @CurrentUser() decorator to extract user from request (project-scoped)
- Create @Public() decorator to bypass auth on specific routes
- Create @Roles() decorator for role requirements
- Create @CurrentProject() decorator

### 5.9 Auth Interceptors
- Create user transformation interceptor
- Remove sensitive fields (password) from responses
- Add user and project context to request

---

## Phase 6: Users Module (Project-Scoped)

### 6.1 Users Module Setup
- Create UsersModule
- Import necessary dependencies (TypeORM, AuthModule, ProjectsModule)
- Set up module providers and exports

### 6.2 Users DTOs
- Create CreateUserDto
- Create UpdateUserDto
- Create ApproveUserDto (roles assignment)
- Create UpdatePushTokensDto
- Create UserResponseDto
- Add validation decorators

### 6.3 Users Service (Project-Scoped)
- Implement findById method (with project filter)
- Implement findByEmail method (with project filter)
- Implement findByPhone method (with project filter)
- Implement findPendingUsers method (project-scoped)
- Implement approveUser method (update status, assign roles, project-scoped)
- Implement updateProfile method (project-scoped)
- Implement updatePushTokens method (project-scoped)
- Implement getUserPusherChannels method (project-scoped)
- Add transaction support for critical operations
- Ensure all queries include projectId filter

### 6.4 Users Controller
- Create GET /api/v1/users/pending endpoint (Admin only, project-scoped)
- Create POST /api/v1/users/:id/approve endpoint (Admin only, project-scoped)
- Create GET /api/v1/users/me endpoint (project-scoped)
- Create PUT /api/v1/users/me endpoint (project-scoped)
- Create PUT /api/v1/users/me/push-tokens endpoint (project-scoped)
- Add proper guards and validation

### 6.5 Pusher Auth Endpoint (Project-Scoped)
- Create POST /api/v1/users/me/pusher-auth endpoint
- Implement Pusher channel authentication using project's Pusher credentials
- Generate HMAC signature for private channels
- Validate JWT and user permissions
- Use project-specific Pusher secret from project settings
- Return auth signature

---

## Phase 7: Roles Module (Project-Scoped)

### 7.1 Roles Module Setup
- Create RolesModule
- Set up module structure

### 7.2 Roles DTOs
- Create CreateRoleDto (name, permissions, description)
- Create UpdateRoleDto
- Create RoleResponseDto
- Add validation decorators

### 7.3 Roles Service (Project-Scoped)
- Implement findAll method (project-scoped)
- Implement findById method (project-scoped)
- Implement findByName method (project-scoped)
- Implement create method (project-scoped, validate name uniqueness within project)
- Implement update method (project-scoped)
- Implement delete method (project-scoped)
- Add permission validation

### 7.4 Roles Controller
- Create GET /api/v1/roles endpoint (project-scoped)
- Create POST /api/v1/roles endpoint (Admin only, project-scoped)
- Create PUT /api/v1/roles/:id endpoint (Admin only, project-scoped)
- Create DELETE /api/v1/roles/:id endpoint (Admin only, project-scoped)
- Add proper guards and validation

---

## Phase 8: Rules Module (Project-Scoped)

### 8.1 Rules Module Setup
- Create RulesModule
- Import necessary dependencies

### 8.2 Rules DTOs
- Create CreateRuleDto (name, description, condition, targetRoles, sound, priority, active)
- Create UpdateRuleDto
- Create RuleResponseDto
- Create RuleListQueryDto (pagination, filters)
- Add validation decorators and custom validators for condition DSL

### 8.3 Rule Engine Service
- Install expr-eval or similar DSL parser
- Create RuleEngineService
- Implement condition parser
- Implement condition evaluator with event context
- Add support for operators: ==, !=, >, <, >=, <=, &&, ||
- Add support for event property access (event.type, event.amount, event.payload.status)
- Add safety checks to prevent code injection
- Add error handling for invalid conditions

### 8.4 Rules Service (Project-Scoped)
- Implement create method (validate condition, validate roles exist within project, project-scoped)
- Implement findAll method (with pagination and filters, project-scoped)
- Implement findById method (project-scoped)
- Implement findActiveRules method (project-scoped)
- Implement update method (project-scoped)
- Implement delete method (soft delete, project-scoped)
- Add transaction support
- Ensure all queries include projectId filter

### 8.5 Rules Controller
- Create POST /api/v1/rules endpoint (Admin/RuleManager only, project-scoped)
- Create GET /api/v1/rules endpoint (with pagination and filters, project-scoped)
- Create GET /api/v1/rules/:id endpoint (project-scoped)
- Create PUT /api/v1/rules/:id endpoint (Admin/RuleManager only, project-scoped)
- Create DELETE /api/v1/rules/:id endpoint (Admin/RuleManager only, project-scoped)
- Add proper guards and validation

---

## Phase 9: Events Module (Project-Scoped with API Key Auth)

### 9.1 Events Module Setup
- Create EventsModule
- Set up Redis Streams integration (project-scoped streams)
- Configure BullMQ for event processing queue

### 9.2 Events DTOs
- Create CreateEventDto (type, payload, source)
- Create EventResponseDto
- Add validation decorators

### 9.3 Event Consumer Service (Project-Scoped)
- Create EventConsumerService
- Implement Redis Streams consumer with project-scoped stream names
- Set up consumer group for at-least-once delivery
- Implement event ingestion from stream (with project context)
- Add error handling and retry logic
- Mark events as processed after handling

### 9.4 Event Processor Service (Project-Scoped)
- Create EventProcessorService
- Implement processEvent method (project-scoped)
- Fetch all active rules for the project
- Evaluate event against each rule using RuleEngineService
- For matched rules, determine recipients by role (within project)
- Create notifications for matched rules (with projectId)
- Queue notification delivery
- Update event processedAt timestamp
- Add transaction support

### 9.5 Events Controller (API Key Auth)
- Create POST /api/v1/events endpoint (authenticated via API key)
- Validate API key using ApiKeyGuard
- Extract project from API key
- Store event in database with projectId
- Queue event for processing
- Return event ID
- Add rate limiting per project

### 9.6 Event Processing Queue (Project-Scoped)
- Create BullMQ queue: event-processing-queue
- Create queue processor
- Include project context in job data
- Implement retry logic with exponential backoff
- Handle failed events
- Add job progress tracking

---

## Phase 10: Notifications Module (Project-Scoped)

### 10.1 Notifications Module Setup
- Create NotificationsModule
- Import Pusher module
- Set up BullMQ queues for notification delivery

### 10.2 Notifications DTOs
- Create NotificationResponseDto
- Create NotificationListQueryDto (pagination, status filters)
- Create AcknowledgeNotificationDto
- Create WebviewActionDto
- Add validation decorators

### 10.3 Notification Service (Project-Scoped)
- Implement create method (create notification record with projectId)
- Implement findAllForUser method (with pagination, project-scoped)
- Implement findById method (project-scoped)
- Implement acknowledge method (add user to acknowledgedBy, project-scoped)
- Implement logWebviewAction method (project-scoped)
- Implement getUnreadCount method (project-scoped)
- Implement markAsDelivered method (project-scoped)
- Add recipient validation (within project)

### 10.4 Pusher Service (Project-Specific Credentials)
- Install Pusher SDK
- Create PusherService
- Implement getPusherClient method (retrieve project's Pusher config from project settings)
- Implement triggerNotification method (use project's Pusher credentials)
- Implement batch trigger for multiple users (project-scoped)
- Add error handling and retry logic
- Cache Pusher clients per project

### 10.5 Notification Delivery Service (Project-Scoped)
- Create NotificationDeliveryService
- Implement deliverNotification method (project-scoped)
- Check user Pusher channel subscription (query Redis, project-scoped)
- If subscribed: trigger via Pusher using project's Pusher credentials
- If offline: queue for push notification (BullMQ queue)
- Update notification delivered status
- Use project-specific Pusher app configuration

### 10.6 Notifications Controller
- Create GET /api/v1/notifications endpoint (user's notifications, project-scoped)
- Create GET /api/v1/notifications/:id endpoint (project-scoped)
- Create PUT /api/v1/notifications/:id/acknowledge endpoint (project-scoped)
- Create POST /api/v1/notifications/:id/webview-action endpoint (project-scoped)
- Create GET /api/v1/notifications/unread-count endpoint (project-scoped)
- Create DELETE /api/v1/notifications/:id endpoint (soft delete, project-scoped)
- Add proper guards and validation

### 10.7 Notification Delivery Queue (Project-Scoped)
- Create BullMQ queue: notification-delivery-queue
- Create queue processor
- Include project context in job data
- Implement retry logic with exponential backoff
- Handle delivery failures
- Update notification status

---

## Phase 11: Push Notifications (Fallback, Project-Scoped)

### 11.1 Push Notification Service Setup
- Install Firebase Admin SDK
- Install APNs library
- Create PushNotificationService
- Configure FCM credentials (can be project-specific or global)
- Configure APNs credentials (can be project-specific or global)

### 11.2 Push Notification Service
- Implement sendFCMNotification method
- Implement sendAPNsNotification method
- Implement sendPushNotification method (route to FCM or APNs based on platform)
- Add error handling
- Stub implementation for initial phase (log instead of actual send)

### 11.3 Push Notification Queue (Project-Scoped)
- Create BullMQ queue: push-notification-queue
- Create queue processor
- Include project context in job data
- Process queued push notifications
- Implement retry logic
- Handle platform-specific errors

### 11.4 Integration with Notification Delivery
- Update NotificationDeliveryService to queue push notifications for offline users
- Add logic to determine when to use push vs Pusher
- Ensure project context is maintained

---

## Phase 12: Transfer Buckets Module (Project-Scoped)

### 12.1 Transfer Buckets Module Setup
- Create TransferBucketsModule
- Set up module structure

### 12.2 Transfer Buckets DTOs
- Create UpdateThresholdDto
- Create TransferBucketResponseDto
- Add validation decorators

### 12.3 Transfer Buckets Service (Project-Scoped)
- Implement findAll method (project-scoped)
- Implement findById method (project-scoped)
- Implement updateThreshold method (project-scoped)
- Implement updateBalance method (project-scoped)
- Implement checkLowBalance method (compare balance to threshold, project-scoped)
- Emit event when balance falls below threshold (with project context)

### 12.4 Transfer Buckets Controller
- Create GET /api/v1/transfer-buckets endpoint (project-scoped)
- Create GET /api/v1/transfer-buckets/:id endpoint (project-scoped)
- Create PUT /api/v1/transfer-buckets/:id/threshold endpoint (Admin only, project-scoped)
- Add proper guards and validation

### 12.5 Bucket Monitoring Queue (Project-Scoped)
- Create BullMQ queue: bucket-monitoring-queue
- Create scheduled job to check bucket balances periodically (per project)
- Emit events when thresholds are crossed (with project context)
- Add configuration for monitoring interval

---

## Phase 13: Audit Module (Project-Scoped)

### 13.1 Audit Module Setup
- Create AuditModule
- Set up module structure

### 13.2 Audit DTOs
- Create AuditLogResponseDto
- Create AuditQueryDto (filters: date, user, action, resourceType)
- Add validation decorators

### 13.3 Audit Service (Project-Scoped)
- Create AuditService
- Implement log method (action, userId, resourceType, resourceId, metadata, projectId)
- Implement findAll method (with filters and pagination, project-scoped)
- Implement exportToCSV method (project-scoped)
- Add automatic logging for critical actions
- Ensure all queries include projectId filter (except system-level logs)

### 13.4 Audit Interceptor
- Create AuditInterceptor
- Log authentication attempts (with project context)
- Log rule changes (project-scoped)
- Log notification deliveries (project-scoped)
- Log user approvals (project-scoped)
- Add correlation IDs

### 13.5 Audit Controller
- Create GET /api/v1/audit endpoint (with filters, project-scoped)
- Create GET /api/v1/audit/export endpoint (CSV export, project-scoped)
- Add proper guards (Admin only)
- Add pagination support

---

## Phase 14: Sound Management Module (Project-Scoped)

### 14.1 Sound Management Module Setup
- Create SoundsModule
- Set up file upload configuration (multer)
- Configure S3/CDN integration

### 14.2 Sound Management DTOs
- Create UploadSoundDto
- Create SoundResponseDto
- Add validation decorators

### 14.3 Sound Management Service (Project-Scoped)
- Create SoundManagementService
- Implement uploadSound method (validate format, upload to S3/CDN, associate with project)
- Implement generateSignedUrl method (with TTL, project-scoped)
- Implement findAll method (project-scoped)
- Implement deleteSound method (project-scoped)
- Validate audio formats (mp3, ogg, wav)
- Add file size limits

### 14.4 Sound Management Controller
- Create POST /api/v1/sounds endpoint (Admin only, file upload, project-scoped)
- Create GET /api/v1/sounds endpoint (project-scoped)
- Create DELETE /api/v1/sounds/:id endpoint (Admin only, project-scoped)
- Add proper guards and validation

---

## Phase 15: Alert Suppression & Rate Limiting (Project-Scoped)

### 15.1 Rate Limiting Setup
- Install @nestjs/throttler
- Configure rate limiting module
- Set up per-project rate limits
- Set up per-user rate limits (within project)
- Set up global rate limits
- Configure rate limit storage in Redis (project-scoped keys)

### 15.2 Alert Suppression Service (Project-Scoped)
- Create AlertSuppressionService
- Implement sliding window counter in Redis (project-scoped keys)
- Check if rule triggered > N times in M seconds (within project)
- Implement suppression logic (project-scoped)
- Implement batching for suppressed alerts
- Add configuration for suppression windows (can be project-specific)

### 15.3 Alert Suppression Queue (Project-Scoped)
- Create BullMQ queue: alert-suppression-queue
- Process suppression checks (with project context)
- Batch notifications when suppression is active
- Include project context in job data

### 15.4 Integration
- Integrate suppression service into EventProcessorService
- Add suppression checks before creating notifications
- Ensure project context is maintained

---

## Phase 16: Security Enhancements (Multi-Tenant)

### 16.1 Security Middleware
- Install and configure Helmet
- Set up security headers
- Configure CORS with allowed origins
- Add XSS protection

### 16.2 Input Validation
- Ensure all DTOs have proper validation decorators
- Add custom validators where needed
- Sanitize user inputs
- Validate condition DSL syntax

### 16.3 Error Handling
- Create global exception filter
- Create custom exceptions (RuleNotFoundException, UnauthorizedRoleException, InvalidConditionException, ProjectNotFoundException, InvalidApiKeyException)
- Implement structured error responses with request IDs
- Add proper HTTP status codes
- Ensure error messages don't leak project information

### 16.4 Data Protection
- Encrypt sensitive fields at rest (if required)
- Ensure password hashing is secure
- Ensure API key hashing is secure
- Add audit logging for sensitive operations
- Ensure project isolation in all queries

### 16.5 Project Isolation Validation
- Create middleware to validate project isolation
- Ensure all database queries include projectId filter
- Add tests to verify project isolation
- Prevent cross-project data access

---

## Phase 17: Performance Optimizations (Multi-Tenant)

### 17.1 Database Optimizations
- Add composite indexes for common query patterns (including projectId)
- Optimize JSON column queries
- Add database query logging in development
- Review and optimize slow queries
- Ensure all queries use projectId index

### 17.2 Caching (Project-Scoped)
- Implement Redis caching for active users (project-scoped keys)
- Cache Pusher channel subscriptions (project-scoped)
- Cache frequently accessed rules (project-scoped)
- Add cache invalidation strategies
- Use project-scoped cache keys

### 17.3 Connection Pooling
- Optimize MySQL connection pool settings
- Optimize Redis connection pool
- Monitor connection usage

### 17.4 Batch Processing
- Implement batch Pusher triggers (project-scoped)
- Batch database inserts where possible
- Optimize notification delivery batching
- Maintain project context in batches

---

## Phase 18: Testing (Multi-Tenant)

### 18.1 Unit Tests
- Write unit tests for RuleEngineService
- Write unit tests for NotificationService (with project context)
- Write unit tests for AuthService (with project context)
- Write unit tests for ProjectsService
- Write unit tests for ApiKeyGuard
- Write unit tests for ProjectContextService
- Write unit tests for all services
- Mock external dependencies

### 18.2 Integration Tests
- Write integration tests for Auth endpoints (with project context)
- Write integration tests for Rules endpoints (project-scoped)
- Write integration tests for Notifications endpoints (project-scoped)
- Write integration tests for Events endpoints (API key auth)
- Write integration tests for Users endpoints (project-scoped)
- Test database transactions
- Test project isolation

### 18.3 E2E Tests
- Write E2E test for project creation and API key generation
- Write E2E test for API key authentication
- Write E2E test for authentication flow (with project)
- Write E2E test for rule evaluation flow (project-scoped)
- Write E2E test for notification delivery flow (project-scoped)
- Write E2E test for user approval flow (project-scoped)
- Test cross-project isolation (ensure data doesn't leak between projects)
- Test error scenarios

### 18.4 Test Setup
- Configure test database
- Set up test fixtures (multiple projects)
- Create test utilities and helpers
- Configure test coverage reporting
- Add project isolation tests

---

## Phase 19: Documentation

### 19.1 API Documentation
- Install and configure Swagger/OpenAPI
- Add API documentation decorators to all controllers
- Document request/response schemas
- Document authentication requirements (JWT and API key)
- Document rate limits (per-project)
- Add example requests and responses
- Document project-scoped endpoints

### 19.2 Code Documentation
- Add JSDoc comments to all services
- Document complex algorithms
- Add inline comments for non-obvious logic
- Document configuration options
- Document multi-tenant architecture

### 19.3 README
- Create comprehensive README
- Document setup instructions
- Document environment variables
- Document API usage examples (including API key authentication)
- Document project creation and management
- Document deployment process
- Document multi-tenant architecture

### 19.4 Integration Guide
- Create integration guide for external applications
- Document API key generation and usage
- Document event ingestion
- Provide code examples for different languages
- Document webhook configuration

---

## Phase 20: Deployment Preparation

### 20.1 Docker Setup
- Create Dockerfile with multi-stage build
- Create docker-compose.yml for local development (with multiple projects)
- Configure environment variables in Docker
- Add health check to Dockerfile

### 20.2 CI/CD Configuration
- Create GitHub Actions workflow (or similar)
- Set up automated testing
- Configure deployment pipeline
- Add environment-specific configurations

### 20.3 Environment Configuration
- Finalize production environment variables
- Set up secrets management
- Configure production database
- Configure production Redis
- Set up monitoring and alerting

### 20.4 Graceful Shutdown
- Implement graceful shutdown handler
- Close database connections
- Close Redis connections
- Finish processing queue jobs
- Handle in-flight requests

---

## Phase 21: Monitoring & Observability (Multi-Tenant)

### 21.1 Logging Enhancement
- Add structured logging with correlation IDs and project context
- Add performance logging (per-project metrics)
- Add error tracking (with project context)
- Configure log aggregation

### 21.2 Metrics (Project-Scoped)
- Add application metrics (request count, latency, error rate per project)
- Add business metrics (notifications sent per project, rules evaluated per project)
- Expose metrics endpoint
- Integrate with monitoring system
- Track per-project usage

### 21.3 Health Checks
- Enhance health check endpoint
- Add dependency health checks
- Add readiness and liveness probes
- Monitor queue health
- Monitor per-project health

---

## Phase 22: Final Polish & Optimization

### 22.1 Code Review
- Review all code for best practices
- Optimize database queries (ensure projectId indexes are used)
- Review security implementations (project isolation)
- Check error handling

### 22.2 Performance Testing
- Load test API endpoints (with multiple projects)
- Test notification delivery under load (per-project)
- Test queue processing under load
- Test project isolation under load
- Optimize based on results

### 22.3 Security Audit
- Review authentication and authorization (API key and JWT)
- Check input validation
- Review SQL injection prevention
- Check XSS protection
- Verify project isolation
- Test API key security

### 22.4 Documentation Review
- Review and update all documentation
- Ensure API documentation is complete
- Update README with latest information
- Document known limitations
- Update integration guide

---

## Key Multi-Tenant Implementation Notes

1. **All entities must include `projectId`** - This is the foundation of multi-tenancy
2. **All queries must be project-scoped** - Use base repository or query builder to automatically add projectId filter
3. **API key authentication** - External applications use API key, which automatically sets project context
4. **JWT tokens include project context** - User tokens include projectId to ensure they can only access their project's data
5. **Pusher credentials are project-specific** - Each project has its own Pusher configuration in project.settings
6. **Rate limiting is per-project** - Use project-scoped Redis keys for rate limiting
7. **All endpoints (except project management) are project-scoped** - Use guards and interceptors to ensure project context
8. **Project isolation testing** - Critical to test that data from one project cannot be accessed by another project
9. **Cache keys are project-scoped** - Use projectId in all cache keys to prevent cache collisions
10. **Queue jobs include project context** - All background jobs must include projectId in job data

