# Real-time Notification System ## Overview The notification system provides real-time and email notifications for task management events using Socket.io and Nodemailer. ## Features ### Real-time Notifications (Socket.io) - Instant push notifications to connected clients - User-specific notification channels - Support for multiple device connections per user - Notification acknowledgment and read status tracking ### Email Notifications (Nodemailer) - Configurable email delivery (instant, hourly, daily, weekly digests) - HTML email templates with priority indicators - Email queuing with retry mechanism using Bull queue - SMTP configuration support ### Notification Types - `TASK_ASSIGNED` - When a task is assigned to a user - `TASK_UPDATED` - When task details are modified - `TASK_COMPLETED` - When a task is marked as done - `TASK_OVERDUE` - When a task passes its due date - `COMMENT_ADDED` - When someone comments on a task - `MENTION` - When a user is mentioned - `STATUS_CHANGED` - When task status changes - `DEADLINE_APPROACHING` - Reminder for upcoming deadlines - `WORKFLOW_TRIGGERED` - When workflow events occur - `COLLABORATION_INVITE` - When invited to collaborate ### Priority Levels - `URGENT` - Red indicator, immediate attention required - `HIGH` - Yellow indicator, high priority - `MEDIUM` - Blue indicator, normal priority - `LOW` - Gray indicator, low priority ## Configuration ### Environment Variables ```env # Socket.io Configuration PORT=3000 CORS_ORIGIN=http://localhost:3000 # Email Configuration (Optional) SMTP_HOST=smtp.gmail.com SMTP_PORT=587 SMTP_SECURE=false SMTP_USER=your-email@gmail.com SMTP_PASS=your-app-password SMTP_FROM=noreply@taskmanagement.com # Redis Configuration (for email queue) REDIS_HOST=localhost REDIS_PORT=6379 # JWT Configuration JWT_SECRET=your-secret-key # Directus Configuration DIRECTUS_URL=http://localhost:8055 DIRECTUS_EMAIL=admin@example.com DIRECTUS_PASSWORD=admin-password ``` ## API Endpoints ### REST API #### Get Notifications ``` GET /api/notifications Query params: page, limit, unreadOnly ``` #### Mark as Read ``` PUT /api/notifications/:notificationId/read ``` #### Mark All as Read ``` PUT /api/notifications/read-all ``` #### Get Preferences ``` GET /api/notifications/preferences ``` #### Update Preferences ``` PUT /api/notifications/preferences Body: { email: {...}, realtime: {...}, doNotDisturb: {...} } ``` #### Subscribe to Types ``` POST /api/notifications/subscribe Body: { types: ['task_assigned', 'mention'] } ``` #### Unsubscribe from Types ``` POST /api/notifications/unsubscribe Body: { types: ['task_overdue'] } ``` ### Socket.io Events #### Client → Server Events - `notification:markRead` - Mark single notification as read - `notification:markAllRead` - Mark all notifications as read - `notification:updatePreferences` - Update user preferences - `notification:subscribe` - Subscribe to notification types - `notification:unsubscribe` - Unsubscribe from notification types #### Server → Client Events - `notification:new` - New notification received - `notification:read` - Notification marked as read - `notifications:allRead` - All notifications marked as read - `notifications:pending` - Batch of pending notifications - `preferences:updated` - Preferences updated successfully ## Testing ### 1. Start the Server ```bash npm run dev ``` ### 2. Open Test Client Open `src/notifications/test-client.html` in a browser ### 3. Generate JWT Token ```javascript // Generate test JWT token const jwt = require('jsonwebtoken'); const token = jwt.sign( { userId: 'test-user-id' }, 'your-secret-key', { expiresIn: '1h' } ); console.log(token); ``` ### 4. Connect and Test 1. Enter the JWT token in the test client 2. Click "Connect" 3. Send test notifications 4. Verify real-time delivery ### 5. Test with Node.js Client ```bash node test-notification.js ``` ## Integration with Task System The notification system automatically sends notifications when: 1. **Task Assignment**: Users receive notifications when assigned to tasks 2. **Status Changes**: Notifications on task status transitions 3. **Due Date Alerts**: Automatic reminders for approaching deadlines 4. **Comments**: Notifications when comments are added to tasks 5. **Mentions**: Direct notifications when mentioned in tasks/comments ### Example Integration ```typescript // In task assignment service await notificationService.sendNotification(assigneeId, { type: NotificationType.TASK_ASSIGNED, priority: NotificationPriority.HIGH, title: 'New Task Assigned', message: `You have been assigned to: ${task.title}`, actionUrl: `/tasks/${taskId}`, actions: [{ label: 'View Task', action: 'view_task', url: `/tasks/${taskId}` }] }); ``` ## User Preferences Users can configure: ### Email Preferences - Enable/disable email notifications - Set delivery frequency (instant, hourly, daily, weekly) - Select notification types to receive via email ### Real-time Preferences - Enable/disable real-time notifications - Select notification types for real-time delivery - Enable/disable sound alerts - Enable/disable desktop notifications ### Do Not Disturb - Enable DND mode - Set DND schedule (start/end times) - Configure timezone for DND ## Architecture ``` ┌─────────────┐ ┌──────────────┐ ┌─────────────┐ │ Client │────▶│ Socket.io │────▶│ Notification│ │ (Browser) │ │ Server │ │ Service │ └─────────────┘ └──────────────┘ └─────────────┘ │ │ ▼ ▼ ┌──────────────┐ ┌─────────────┐ │ Express │ │ Email │ │ REST API │ │ Queue │ └──────────────┘ └─────────────┘ │ │ ▼ ▼ ┌──────────────┐ ┌─────────────┐ │ Directus │ │ SMTP │ │ Database │ │ Server │ └──────────────┘ └─────────────┘ ``` ## Troubleshooting ### Socket.io Connection Issues - Verify JWT token is valid - Check CORS configuration - Ensure server is running on correct port - Check firewall/proxy settings ### Email Delivery Issues - Verify SMTP credentials - Check spam folder - Ensure Redis is running for queue - Review email queue logs ### Notification Not Received - Check user preferences - Verify user is not in DND mode - Check notification type subscriptions - Review server logs for errors ## Future Enhancements - [ ] Push notifications (FCM/APNs) - [ ] SMS notifications (Twilio) - [ ] Slack/Teams integration - [ ] Custom notification templates - [ ] Notification scheduling - [ ] Advanced filtering and search - [ ] Notification analytics - [ ] Bulk notification management