# NestJS Backend Implementation Prompt for Alert Microservice

Build a production-ready real-time alert and notification microservice using NestJS with the following specifications:

## Core Architecture Requirements

Create a NestJS REST API application with:
- **Modular architecture** with separate modules for: Auth, Rules, Notifications, Events, Users, Roles, Audit, TransferBuckets
- **Message broker integration** using Redis Streams for event ingestion
- **Pusher** for real-time notifications (server-side triggering only, no WebSocket gateway)
- **MySQL database** with TypeORM for persistence
- **Redis cache** for session management and real-time data
- **Worker queue** using Bull for background job processing
- **API versioning** (v1) with proper REST conventions
- **Focus on REST APIs only** - Mobile and Admin frontend teams will integrate separately

## Database Models

Implement TypeORM entities for MySQL:

### 1. Rule Entity
```typescript
- id: VARCHAR(36) UUID (primary key)
- name: VARCHAR(255)
- description: TEXT
- condition: TEXT (DSL expression)
- targetRoles: JSON (array of strings)
- sound: VARCHAR(255) (filename)
- priority: INT
- active: TINYINT(1) (boolean)
- createdBy: VARCHAR(36) UUID (foreign key to User)
- createdAt: DATETIME
- updatedAt: DATETIME
```

### 2. User Entity
```typescript
- id: VARCHAR(36) UUID (primary key)
- email: VARCHAR(255) (unique)
- phone: VARCHAR(20) (unique)
- password: VARCHAR(255) (hashed)
- roles: JSON (array of strings)
- status: ENUM ('pending', 'active', 'disabled', 'unverified')
- pushTokens: JSON { fcm: string, apns: string }
- pusherChannels: JSON (array of subscribed channels - cached in Redis)
- createdAt: DATETIME
- updatedAt: DATETIME
```

### 3. Event Entity
```typescript
- id: VARCHAR(36) UUID (primary key)
- type: VARCHAR(100) (indexed)
- payload: JSON
- source: VARCHAR(100)
- receivedAt: DATETIME
- processedAt: DATETIME (nullable)
```

### 4. Notification Entity
```typescript
- id: VARCHAR(36) UUID (primary key)
- ruleId: VARCHAR(36) UUID (foreign key)
- eventId: VARCHAR(36) UUID (foreign key)
- recipients: JSON (array of UUIDs)
- title: VARCHAR(255)
- message: TEXT
- sound: VARCHAR(255)
- action: JSON
- delivered: TINYINT(1) (boolean)
- pusherEventSent: TINYINT(1) (boolean)
- acknowledgedBy: JSON (array of UUIDs)
- createdAt: DATETIME
- deliveredAt: DATETIME (nullable)
```

### 5. AuditLog Entity
```typescript
- id: VARCHAR(36) UUID (primary key)
- action: VARCHAR(100)
- userId: VARCHAR(36) UUID (nullable)
- resourceType: VARCHAR(50)
- resourceId: VARCHAR(36) UUID
- metadata: JSON
- timestamp: DATETIME
- INDEX on userId, resourceType, timestamp
```

### 6. TransferBucket Entity
```typescript
- id: VARCHAR(36) UUID (primary key)
- name: VARCHAR(255)
- currentBalance: DECIMAL(19,4)
- threshold: DECIMAL(19,4)
- currency: VARCHAR(3)
- updatedAt: DATETIME
```

### 7. Role Entity
```typescript
- id: VARCHAR(36) UUID (primary key)
- name: VARCHAR(100) (unique)
- permissions: JSON (array of strings)
- description: TEXT
- createdAt: DATETIME
```

## Module Structure

### 1. AuthModule
Implement JWT-based authentication with:
- `POST /api/v1/auth/register` - User registration (sets status to 'pending')
- `POST /api/v1/auth/login` - Login with JWT token generation
- `POST /api/v1/auth/refresh` - Refresh token endpoint
- `POST /api/v1/auth/logout` - Logout
- JwtAuthGuard for protecting routes
- RolesGuard for role-based access control
- Custom decorators: `@Roles()`, `@CurrentUser()`

### 2. RulesModule
REST endpoints:
- `POST /api/v1/rules` - Create rule (Admin/RuleManager only)
- `GET /api/v1/rules` - List rules with pagination and filters
- `GET /api/v1/rules/:id` - Get single rule
- `PUT /api/v1/rules/:id` - Update rule
- `DELETE /api/v1/rules/:id` - Delete rule
- RuleEngineService to evaluate conditions using a DSL parser (use `expr-eval` or similar)

### 3. EventsModule
- `POST /api/v1/events` - Ingest events (authenticated)
- EventConsumerService to consume from Redis Streams
- EventProcessorService to evaluate events against active rules
- Queue failed processing attempts with retry logic

### 4. NotificationsModule
- NotificationService to create and deliver notifications
- PusherService to trigger events on user-specific private channels
- PushNotificationService for FCM/APNs fallback
- Rate limiting per user and globally
- Deduplication logic
- REST endpoints:
  - `GET /api/v1/notifications` - Get user's notifications with pagination
  - `GET /api/v1/notifications/:id` - Get notification details
  - `PUT /api/v1/notifications/:id/acknowledge` - Mark notification as acknowledged
  - `POST /api/v1/notifications/:id/webview-action` - Log webview open action
  - `GET /api/v1/notifications/unread-count` - Get unread notification count

### 5. UsersModule
REST endpoints:
- `GET /api/v1/users/pending` - List pending users (Admin only)
- `POST /api/v1/users/:id/approve` - Approve user and assign roles
- `GET /api/v1/users/me` - Get current user profile
- `PUT /api/v1/users/me` - Update profile
- `PUT /api/v1/users/me/push-tokens` - Update push tokens
- `GET /api/v1/users/me/pusher-auth` - Generate Pusher auth signature for private channels

### 6. RolesModule
- `GET /api/v1/roles` - List all roles
- `POST /api/v1/roles` - Create role (Admin only)
- `PUT /api/v1/roles/:id` - Update role
- `DELETE /api/v1/roles/:id` - Delete role

### 7. AuditModule
- `GET /api/v1/audit` - Query audit logs with filters (date, user, action, resourceType)
- `GET /api/v1/audit/export` - Export as CSV
- AuditService to log all critical actions

### 8. TransferBucketsModule
- `GET /api/v1/transfer-buckets` - List buckets
- `GET /api/v1/transfer-buckets/:id` - Get bucket details
- `PUT /api/v1/transfer-buckets/:id/threshold` - Update threshold
- Background job to check bucket balances and emit events

## Additional Services

### RuleEngineService
- Parse and evaluate condition expressions safely
- Support operators: `==`, `!=`, `>`, `<`, `>=`, `<=`, `&&`, `||`
- Access event properties like `event.type`, `event.amount`, `event.payload.status`

### NotificationDeliveryService
- Check user socket connection status (query Redis)
- If connected: emit via Socket.IO
- If offline: queue for push notification (Bull queue)
- Update notification.delivered status

### PushNotificationService
- Integration with Firebase Cloud Messaging (FCM) for Android
- Integration with Apple Push Notification Service (APNs) for iOS
- Fallback when WebSocket unavailable

### SoundManagementService
- Upload sound files to S3/CDN
- Generate signed URLs with TTL
- Validate audio formats (mp3, ogg, wav)
- `POST /api/v1/sounds` - Upload sound
- `GET /api/v1/sounds` - List sounds
- `DELETE /api/v1/sounds/:id` - Delete sound

## Background Jobs (Bull Queues)

Create queues for:
1. **event-processing-queue** - Process incoming events against rules
2. **notification-delivery-queue** - Deliver notifications with retry
3. **push-notification-queue** - Send push notifications
4. **bucket-monitoring-queue** - Periodic check of transfer bucket balances
5. **alert-suppression-queue** - Handle alert storm suppression

## Configuration

Use `@nestjs/config` for:
- Database connection (MySQL)
- Redis connection (cache and streams)
- JWT secrets and expiration
- Pusher configuration (app_id, key, secret, cluster)
- FCM/APNs credentials
- Rate limiting thresholds
- Alert suppression windows
- Audit log retention policy
- CDN/S3 configuration for sound files

## Security Implementation

1. **Helmet** for HTTP headers security
2. **CORS** configuration for allowed origins
3. **Rate limiting** using `@nestjs/throttler`
4. **Password hashing** with bcrypt (cost factor 12)
5. **Input validation** using class-validator on all DTOs
6. **SQL injection prevention** via TypeORM parameterized queries
7. **XSS protection** by sanitizing inputs
8. **Role-based guards** on all sensitive endpoints

## Error Handling

- Global exception filter
- Custom exceptions: `RuleNotFoundException`, `UnauthorizedRoleException`, `InvalidConditionException`
- Proper HTTP status codes
- Structured error responses with request IDs

## Logging & Monitoring

- Use Winston for structured logging
- Log levels: error, warn, info, debug
- Include correlation IDs for request tracing
- Audit all authentication attempts, rule changes, notification deliveries

## Testing Strategy

Generate:
- Unit tests for services (RuleEngineService, NotificationService)
- Integration tests for controllers
- E2E tests for critical flows (auth, rule evaluation, notification delivery)
- Mock external services (FCM, APNs, Redis)

## Performance Optimizations

- MySQL indexing on frequently queried fields (userId, ruleId, eventType, createdAt, status)
- Use composite indexes for common query patterns
- Redis caching for active users, Pusher channel subscriptions, and frequently accessed rules
- Connection pooling for MySQL database
- Batch processing for high-volume events using Pusher batch API
- Alert deduplication and aggregation
- Optimize JSON column queries in MySQL

## Documentation

Generate:
- Swagger/OpenAPI documentation for all REST endpoints
- Include request/response schemas
- Add authentication requirements
- Document rate limits

## Deployment Considerations

- Docker containerization with multi-stage build
- Health check endpoint: `GET /health`
- Graceful shutdown handling
- Environment-based configuration
- Separate worker processes for queue consumers

## File Structure

```
src/
├── modules/
│   ├── auth/
│   ├── rules/
│   ├── events/
│   ├── notifications/
│   ├── users/
│   ├── roles/
│   ├── audit/
│   ├── transfer-buckets/
│   └── sounds/
├── common/
│   ├── guards/
│   ├── decorators/
│   ├── filters/
│   ├── interceptors/
│   └── pipes/
├── config/
├── database/
│   ├── entities/
│   └── migrations/
└── main.ts
```

## Specific Implementation Notes

1. **Rule Condition Evaluation**: Use `expr-eval` library to safely evaluate condition strings. Sanitize inputs to prevent code injection.

2. **Pusher Integration**: 
   - Install `pusher` npm package
   - Use private channels for user-specific notifications: `private-user-{userId}`
   - Provide `/api/v1/users/me/pusher-auth` endpoint that validates JWT and returns Pusher auth signature
   - Mobile/Frontend teams will handle client-side Pusher subscription
   - Trigger notifications from backend: `pusher.trigger('private-user-123', 'notification', payload)`

3. **MySQL JSON Columns**: Use TypeORM's `@Column('json')` decorator for storing arrays and objects. Ensure proper indexing strategies for JSON queries.

4. **Alert Storm Prevention**: Implement sliding window counter in Redis. If rule triggers > N times in M seconds, suppress or batch notifications.

5. **Delivery Guarantees**: Use Redis Streams consumer groups for at-least-once delivery. Mark events as processed after successful handling.

6. **Offline Queue**: Store undelivered notifications in database with `delivered: false`. Provide API endpoint for mobile to fetch missed notifications on reconnection.

7. **Transaction Handling**: Use MySQL database transactions for critical operations (user approval + role assignment, rule creation + audit log).

8. **Pusher Channel Authentication**: Generate HMAC signature using Pusher secret for private channel authorization.

## Priority Order

Build in this sequence:
1. MySQL database models and migrations with TypeORM
2. AuthModule with JWT guards
3. RolesModule and UsersModule
4. RulesModule with basic CRUD
5. EventsModule with Redis Streams consumer
6. RuleEngineService for condition evaluation
7. NotificationsModule with REST endpoints
8. PusherService integration for real-time notifications
9. NotificationDeliveryService with Pusher triggering
10. Background jobs and Bull queues
11. TransferBucketsModule and monitoring
12. AuditModule and logging
13. PushNotificationService integration (FCM/APNs fallback)
14. SoundManagementService with S3/CDN
15. Testing and Swagger documentation

Start with a minimal viable REST API focusing on core notification flow, then add advanced features like alert suppression, push fallback, and bucket monitoring.

## Additional REST API Endpoints for Integration

### Pusher Authentication
```typescript
POST /api/v1/users/me/pusher-auth
Body: {
  socket_id: string,
  channel_name: string
}
Response: {
  auth: string (Pusher signature)
}
```

### Notification Management
```typescript
GET /api/v1/notifications?page=1&limit=20&status=unread
GET /api/v1/notifications/:id
PUT /api/v1/notifications/:id/acknowledge
POST /api/v1/notifications/:id/webview-action
GET /api/v1/notifications/unread-count
DELETE /api/v1/notifications/:id (soft delete)
```

### Health & Status
```typescript
GET /health - Basic health check
GET /api/v1/status - Detailed system status (Pusher connection, Redis, MySQL, queue health)
```