NOTIFICATION & ALERT MICROSERVICE Project: Real-time Alert & Sound Triggering Microservice Purpose: Provide real-time audible alerts on mobile clients when admin-configurable conditions are met (pending transactions, low-transfer-bucket, role-filtered notifications, etc.). This doc is the single source of truth for Mobile, Frontend (Admin Panel), and Backend teams. 1. Overview & Goals Provide a microservice that evaluates incoming events and business state, then pushes real-time notifications to the mobile app which play sounds/alerts when conditions are matched. Admins configure rules/thresholds/roles via an Admin Panel. Notifications are role-aware and only delivered to authorized users. Mobile users can tap certain notifications to open an editable webview (app.catholicpay.net). The system must be secure, reliable, auditable, and easy to extend. 2. High-level Architecture Key components: Alert Microservice: REST API + Socket server + Rule Engine + Worker pool + DB for rules & audit. Message Broker: Redis Streams / RabbitMQ / Kafka for event ingestion and reliable delivery. Admin Panel: UI for rule creation, role management, thresholds, user approvals. Mobile App: WebSocket client, sound engine, webview launcher, push fallback. Authentication & Role Service: Centralized identity (JWT, OAuth2) or reuse existing auth service. 3. Core Concepts & Terminology Event: An incoming activity (pending transaction, balance update, etc.) emitted by a provider (CatholicPay system). Rule: Admin-configurable condition (e.g., pendingTransaction == true AND amount > X). Notification: A message derived from an Event that is sent to users (socket + optional push). Role: User role (MD, Finance, Ops, Admin, Support, etc.). Rules target roles. Transfer Bucket: Account/ledger that funds transfers; rules reference its balance. Webview Action: Notification action that opens app.catholicpay.net within the app; address bar is editable. 4. Feature List (Requirements) Real-time notifications via WebSockets for: Pending transaction events (bill payment, transfer). Low transfer bucket (threshold configurable). Admin can create/edit/delete rules with: Name, description, target roles, condition expression, sound file, priority, active flag. Role Management: Create roles and assign permissions; map rule visibility to roles. User Onboarding: User registers via mobile; admin must confirm and assign role(s). Notification Actions: Tap pending-transactions notification -> open webview https://app.catholicpay.net within app; user can edit address bar. Sound Management: Admin chooses which sound to play per rule; mobile plays sound (allow override mute). Audit & Logs: All triggers logged with event, rule, recipients, timestamp and status. Fallback: If the user is offline or socket unavailable: queue and send via Push Notification (FCM/APNs) or deliver on the next connection. Rate-limiting & Throttling to prevent alert storms. Secure: auth, role-based access, audit trail, encryption. 5. Data Models (JSON Schemas) 5.1 Rule { "id": "uuid", "name": "string", "description": "string", "condition": "string", // DSL or JSON expression, e.g. "event.type=='pending_tx' && event.amount > 10000" "targetRoles": ["MD","OPS","FINANCE"], "sound": "chime_v1.mp3", "priority": 10, "active": true, "createdBy": "userId", "createdAt": "ISODate", "updatedAt": "ISODate" } 5.2 Event (ingested) { "id":"uuid", "type":"pending_transaction", // or transfer_bucket_update etc. "payload": { /* event-specific data */ }, "source":"transactions_service", "receivedAt":"ISODate" } Example pending_transaction payload: { "txId":"TX_123", "userId":"U_44", "userName":"Sarah Chinny", "amount": 5000, "currency":"NGN", "status":"pending", "meta": { "billType":"electricity" } } 5.3 Notification (outgoing) { "id":"uuid", "ruleId":"uuid", "eventId":"uuid", "recipients":[ "userId1", "userId2" ], "title":"Pending Transaction Alert", "message":"A transaction (TX_123) is pending for ₦5,000", "sound":"chime_v1.mp3", "action": { "type":"open_webview", "url":"https://app.catholicpay.net", "editableAddressBar": true }, "createdAt":"ISODate", "delivered": false } 5.4 User { "id":"uuid", "email":"string", "phone":"string", "roles":["role1","role2"], "status":"pending|active|disabled|unverified", "socketIds":["socket-connection-id1"], "pushTokens":{"fcm":"xxx","apns":"yyy"}, "createdAt":"ISODate" } 6. Backend APIs (REST) & Socket Events Authentication: All REST endpoints require Authorization: Bearer with scopes. Socket connections must use token in handshake query and be validated. 6.1 REST APIs (Admin Panel) POST /api/v1/rules — create rule Body: Rule object (name, condition, roles, sound, priority, active) Auth: ADMIN_ROLE or RULE_MANAGER GET /api/v1/rules — list rules (with filters) GET /api/v1/rules/:id — retrieve rule PUT /api/v1/rules/:id — update rule DELETE /api/v1/rules/:id — delete rule GET /api/v1/roles — list roles POST /api/v1/roles — create role PUT /api/v1/roles/:id — update role (assign permissions) GET /api/v1/users/pending — list users pending approval POST /api/v1/users/:id/approve — admin approves and assigns roles Body: { roles: ["OPS", "FINANCE"] } GET /api/v1/audit — query audit logs POST /api/v1/events — (ingest events from producers) Body: Event payload. (Alternatively this can be a queue/stream endpoint.) GET /api/v1/transfer-buckets/:id — retrieve bucket info PUT /api/v1/transfer-buckets/:id/threshold — admin updates threshold 6.2 Socket Events (Realtime) Use WebSocket (Socket.IO or ws). Authenticate on handshake (JWT). Client -> Server subscribe { channels: ['pending_tx','bucket_updates'], roles: [...] } — client requests subscription (server validates roles) ack { notificationId } — acknowledge receipt/played sound open_webview_action { notificationId } — client opened webview (for audit) Server -> Client notification { notification } — delivered notification payload (includes sound, action) client should respond with ack and then play sound (subject to device mute/perms) rule_update { rule } — informs admin UI or mobile admin client of changes system:heartbeat — ping for liveliness 6.3 Event Flow (Sequence) Transaction Service emits events to Message Broker or POST /api/v1/events. Alert Microservice consumes events, evaluates active rules with Rule Engine. For matched rules, compute recipients by role (fetch active users with role). Create Notification records, log audit. Publish notification to users via: If socket connected: send notification event. Else: persist and queue for push (FCM/APNs) and mark delivered=false. Mobile client receives notification: plays sound, shows in-app banner. On tap, open webview with editable address bar. Mobile sends ack with read/play status. Admin UI shows delivery and audit logs. 7. UI/UX REQUIREMENTS 7.1 MOBILE APP UI/UX REQUIREMENTS Onboarding Flow Welcome / Splash Screen App logo Subtle “Powered by MNT” text Quick loading animation Create Account Screen Full name Email Phone number Password Submit button Success message: “Your account is pending approval from Admin.” Login Screen Email & Password “Forgot password” CTA: Log In Pending Approval Screen Message explaining that the admin will assign a role. No access to the dashboard until approved. Main Dashboard Elements: Top bar: username + role Live Status Indicator: Green dot = active socket connection Red dot = offline / disconnected Notification Centre List of active notifications Badge for unread notifications Sound Toggle Button Allows user to mute/unmute alerts Last activity timestamp UX Requirements: Alerts should appear as: Banner pop-ups Push-style notifications Sound alerts (triggered by microservice) Notification Details Screen When a notification is clicked: Pending Transaction Notification: Show transaction summary CTA button: Open in WebView WebView loads app.catholicpay.net Address bar must be visible and editable Low Transfer Bucket Notification: Show current bucket amount Show threshold No WebView needed Sound plays on arrival Settings Screen Elements: Sound settings (on/off) Notification preferences (toggle specific categories—if permitted by role) Profile info Logout button 7.2 ADMIN PANEL UI/UX REQUIREMENTS Admin Login Email & Password 2FA optional Secure login interface Dashboard Home Widgets: Total users Pending approvals Active roles Real-time system health Transfer bucket current amount Threshold amount Real-time Alerts Summary: Count of pending transactions Count of active notifications sent System logs button User Management Module User List Name, email, role, status (approved/pending) Search bar Filters User Approval Screen Approve user Assign role Toggle user active/inactive User Role Assignment UI Dropdown for roles Permissions automatically displayed Save button with confirmation dialog Role Management Module Roles List Page Role name Number of users Notification types enabled Create New Role Role name Permissions checklist Notifications the role can receive Save role button Edit Role Screen Modify permissions Modify assigned notifications Notification Management Module Pending Transaction Alerts Toggle ON/OFF Assign which roles get this alert Bucket Threshold Settings Input field for bucket threshold value Save & Update confirmation General Alert Rules Create new alert rule Select event trigger Select roles Select sound type Test sound button Sound Alert Management Module Upload custom sounds Preview sound Assign to events Delete sound Volume control System Logs Screen Logs to include: Alerts sent User login Socket connections Errors Filters must exist by: Date User Role Alert type 8. Admin Panel - Frontend 8.1 Screens Dashboard: Overview of recent events, notifications, delivery stats, and rule activity. Rules Manager: List/Create/Edit/Deactivate rules. UI elements: Rule Builder UI (visual): selection fields: eventType, conditions (amount > X, status==pending), targetRoles, sound selector, priority, active toggle. Advanced: raw condition DSL editor. Role Management: Create roles, set permission matrix, assign default rules. Users & Approvals: View pending user registrations; approve and assign roles. Transfer Buckets: List buckets, current balances, set low-threshold per bucket. Audit & Logs: Search by eventId, notificationId, userId; export CSV. Sound Library: Upload/manage sound assets (mp3/ogg); preview audio. Settings: Socket server config, push provider keys (FCM/APNs), rate-limits. 8.2 Rule Builder UX (Visual) Provide templates: Pending Transaction, Bucket Low, Custom. Example flow: Admin clicks "New Rule" → chooses Pending Transaction → sets condition amount > 10000 → chooses roles Finance, Ops → picks loud_alert.mp3 → saves → rule active. 8.3 Role Mapping UX When editing a rule, show checkboxes of roles; tooltip explains sample recipients. 9. Mobile App Requirements & UX Flows 9.1 Core Mobile Behavior Socket Connection: On app start (or when user logs in), establish WebSocket with token. Reconnect strategy with exponential backoff. Notification Handling: On notification event: show in-app toast (non-blocking), enqueue in local DB, play configured sound if device settings allow. Display persistent notification in app inbox. Play Sound: Immediately when notification arrives: Respect device mute/vibration preferences, and an in-app toggle "Play Alert Sounds". If sound file specified as remote URL, prefetch or stream. Cache common sounds for offline. Notification tap: If notification.action.type == open_webview → open internal webview to URL. Editable address bar: top of webview shows address bar populated with URL; user can edit and press Go. Acknowledgement: After sound starts playing or user taps, mobile sends ack with { notificationId, status: "played" }. Offline & Push Fallback: If app is backgrounded or socket disconnected, rely on push notifications (FCM/APNs). Tap on push should open app and the webview. User Onboarding: Sign-up flow → user in pending state → Admin must approve and assign roles before they receive role-based notifications. Admin Mobile Users: If a mobile user has admin privileges, they can visit Rules Manager via mobile? (Optional — recommend desktop for rule editing). 9.2 Permissions & UX Request audio playback permission (if needed). Ensure sounds short (≤5s) to avoid battery and annoyance. Provide user setting to disable sounds or modify sound volume inside the app. 10. Security & Access Control 10.1 Authentication & Authorization Use JWT tokens with scopes and role claims. Tokens must be short-lived with refresh token flow. Socket handshakes validate JWT and roles. All admin routes protected by ROLE_ADMIN or ROLE_RULE_MANAGER. Users cannot subscribe to roles they don’t have. 10.2 Transport Security All traffic over TLS (HTTPS and WSS). Sound assets hosted on secure CDN with signed URLs (short TTL). 10.3 Data Protection & Audit Log all events and notifications. Retention policy (e.g., logs for 90 days in hot store, archived beyond). Encrypt sensitive fields at rest where necessary. 10.4 Rate-Limit & Abuse Prevention Per-user rate limits on notifications to avoid spamming. Global rate-limiting to prevent alert storms (e.g., if 1000 pending txs occur in a minute, batch/aggregate). 11. Reliability, Retry, Offline & Edge Cases 11.1 Delivery Guarantees Use durable message broker + worker retries (exponential backoff). Notification status: pending -> sent -> acked -> failed. 11.2 Offline Users Queue notifications; deliver via Push (FCM/APNs) for backgrounded users. On next socket connection, push missed notifications and mark delivered. 11.3 Throttling & Deduplication Deduplicate events by eventId. If multiple rules fire for same event for same user, decide: Option A: Merge into single notification (preferred) Option B: Send multiple notifications ordered by priority 11.4 Alert Storms Implement "alert suppression window" (configurable): if a rule triggers > N times in M seconds for same scope, suppress or batch. 11.5 Bad Sound URLs / Missing Assets Fallback to default sound in Notification record; log missing asset.