# In-App Notification System - Setup Guide ## 🎯 Overview Complete real-time in-app notification system for Royal Enfield Workflow Management System. ## ✅ Features Implemented ### Backend: 1. **Notification Model** (`models/Notification.ts`) - Stores all in-app notifications - Tracks read/unread status - Supports priority levels (LOW, MEDIUM, HIGH, URGENT) - Metadata for request context 2. **Notification Controller** (`controllers/notification.controller.ts`) - GET `/api/v1/notifications` - List user's notifications with pagination - GET `/api/v1/notifications/unread-count` - Get unread count - PATCH `/api/v1/notifications/:notificationId/read` - Mark as read - POST `/api/v1/notifications/mark-all-read` - Mark all as read - DELETE `/api/v1/notifications/:notificationId` - Delete notification 3. **Enhanced Notification Service** (`services/notification.service.ts`) - Saves notifications to database (for in-app display) - Emits real-time socket.io events - Sends push notifications (if subscribed) - All in one call: `notificationService.sendToUsers()` 4. **Socket.io Enhancement** (`realtime/socket.ts`) - Added `join:user` event for personal notification room - Added `emitToUser()` function for targeted notifications - Real-time delivery without page refresh ### Frontend: 1. **Notification API Service** (`services/notificationApi.ts`) - Complete API client for all notification endpoints 2. **PageLayout Integration** (`components/layout/PageLayout/PageLayout.tsx`) - Real-time notification bell with unread count badge - Dropdown showing latest 10 notifications - Click to mark as read and navigate to request - "Mark all as read" functionality - Auto-refreshes when new notifications arrive - Works even if browser push notifications disabled 3. **Data Freshness** (MyRequests, OpenRequests, ClosedRequests) - Fixed stale data after DB deletion - Always shows fresh data from API ## 📦 Database Setup ### Step 1: Run Migration Execute this SQL in your PostgreSQL database: ```bash psql -U postgres -d re_workflow_db -f migrations/create_notifications_table.sql ``` OR run manually in pgAdmin/SQL tool: ```sql -- See: migrations/create_notifications_table.sql ``` ### Step 2: Verify Table Created ```sql SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'notifications'; ``` ## 🚀 How It Works ### 1. When an Event Occurs (e.g., Request Assigned): **Backend:** ```typescript await notificationService.sendToUsers( [approverId], { title: 'New request assigned', body: 'Marketing Campaign Approval - REQ-2025-12345', requestId: workflowId, requestNumber: 'REQ-2025-12345', url: `/request/REQ-2025-12345`, type: 'assignment', priority: 'HIGH', actionRequired: true } ); ``` This automatically: - ✅ Saves notification to `notifications` table - ✅ Emits `notification:new` socket event to user - ✅ Sends browser push notification (if enabled) ### 2. Frontend Receives Notification: **PageLayout** automatically: - ✅ Receives socket event in real-time - ✅ Updates notification count badge - ✅ Adds to notification dropdown - ✅ Shows blue dot for unread - ✅ User clicks → marks as read → navigates to request ## 📌 Notification Events (Major) Based on your requirement, here are the key events that trigger notifications: | Event | Type | Sent To | Priority | |-------|------|---------|----------| | Request Created | `created` | Initiator | MEDIUM | | Request Assigned | `assignment` | Approver | HIGH | | Approval Given | `approved` | Initiator | HIGH | | Request Rejected | `rejected` | Initiator | URGENT | | TAT Alert (50%) | `tat_alert` | Approver | MEDIUM | | TAT Alert (75%) | `tat_alert` | Approver | HIGH | | TAT Breached | `tat_breach` | Approver + Initiator | URGENT | | Work Note Mention | `mention` | Tagged Users | MEDIUM | | New Comment | `comment` | Participants | LOW | ## 🔧 Configuration ### Backend (.env): ```env # Already configured - no changes needed VAPID_PUBLIC_KEY=your_vapid_public_key VAPID_PRIVATE_KEY=your_vapid_private_key ``` ### Frontend (.env): ```env # Already configured VITE_API_BASE_URL=http://localhost:5000/api/v1 ``` ## ✅ Testing ### 1. Test Basic Notification: ```bash # Create a workflow and assign to an approver # Check approver's notification bell - should show count ``` ### 2. Test Real-Time Delivery: ```bash # Have 2 users logged in (different browsers) # User A creates request, assigns to User B # User B should see notification appear immediately (no refresh needed) ``` ### 3. Test TAT Notifications: ```bash # Create request with 1-hour TAT # Wait for threshold notifications (50%, 75%, 100%) # Approver should receive in-app notifications ``` ### 4. Test Work Note Mentions: ```bash # Add work note with @mention # Tagged user should receive notification ``` ## 🎨 UI Features - **Unread Badge**: Shows count (1-9, or "9+" for 10+) - **Blue Dot**: Indicates unread notifications - **Blue Background**: Highlights unread items - **Time Ago**: "5 minutes ago", "2 hours ago", etc. - **Click to Navigate**: Automatically opens the related request - **Mark All Read**: Single click to clear all unread - **Scrollable**: Shows latest 10, with "View all" link ## 📱 Fallback for Disabled Push Notifications Even if user denies browser push notifications: - ✅ In-app notifications ALWAYS work - ✅ Notifications saved to database - ✅ Real-time delivery via socket.io - ✅ No permission required - ✅ Works on all browsers ## 🔍 Debug Endpoints ```bash # Get notifications for current user GET /api/v1/notifications?page=1&limit=10 # Get only unread GET /api/v1/notifications?unreadOnly=true # Get unread count GET /api/v1/notifications/unread-count ``` ## 🎉 Benefits 1. **No Browser Permission Needed** - Always works, unlike push notifications 2. **Real-Time Updates** - Instant delivery via socket.io 3. **Persistent** - Saved in database, available after login 4. **Actionable** - Click to navigate to related request 5. **User-Friendly** - Clean UI integrated into header 6. **Complete Tracking** - Know what was sent via which channel ## 🔥 Next Steps (Optional) 1. **Email Integration**: Send email for URGENT priority notifications 2. **SMS Integration**: Critical alerts via SMS 3. **Notification Preferences**: Let users choose which events to receive 4. **Notification History Page**: Full-page view with filters 5. **Sound Alerts**: Play sound when new notification arrives 6. **Desktop Notifications**: Browser native notifications (if permitted) --- **✅ In-App Notifications are now fully operational!** Users will receive instant notifications for all major workflow events, even without browser push permissions enabled.