Build a complete NestJS backend microservice for the "Notification & Alert Microservice" focusing only on the REST APIs and related backend logic (event ingestion, rule evaluation, notification creation, auditing, etc.). Do not implement any real-time socket or Pusher integration—assume notifications are created and queued for push fallback (e.g., FCM/APNs), but stub the actual push sending for now. Use NestJS best practices, including modules, controllers, services, providers, guards, interceptors, and pipes where appropriate. Key tech stack decisions: Use TypeORM with MySQL for the database (rules, audit logs, users, etc.). Use Redis for the message broker (Redis Streams for event ingestion and reliable delivery). Implement JWT authentication with @nestjs/jwt and @nestjs/passport for auth guards on REST APIs. Use BullMQ or a similar queue library integrated with Redis for worker pools and handling event processing with retries. For rule evaluation, implement a simple rule engine using a DSL parser (e.g., json-logic-js or a custom evaluator for conditions like "event.type=='pending_tx' && event.amount > 10000"). Handle push notifications fallback using a library like @nestjs/bull for queuing FCM/APNs sends (assume integration with Firebase Admin SDK or similar, but stub the actual send for now). Include rate-limiting with @nestjs/throttler. Use Winston or NestJS built-in logger for auditing and logging. Data models should match the JSON schemas provided (implement as TypeORM entities with relations). Implement all REST APIs as specified in section 6.1, with proper validation using class-validator and class-transformer. Handle event flow: Consume from Redis Streams (or via POST /api/v1/events), evaluate rules, determine recipients by roles, create notifications, queue for push (stub send), and log audit. Do not implement socket delivery. Include security: Role-based access control (RBAC) using guards, TLS assumptions, encryption for sensitive data. Handle reliability: Retries, offline delivery (via push queue), throttling, deduplication as described. Generate the full project structure, including src/ folders, app.module.ts, and all necessary files. Use TypeScript. Assume environment variables for configs like DB_URL (for MySQL), JWT_SECRET, REDIS_URL. Do not implement any socket-related features, real-time events, or frontend/mobile parts—focus only on the REST APIs and backend processing. After generating the code, provide instructions on how to run it (e.g., npm install, npm run start:dev). Here is the full specification as the single source of truth: 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. 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. 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. 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. 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. 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" } 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. 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 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. 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. 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). 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. Implement this step-by-step: First create the project skeleton with nest new, then add modules for auth, users, rules, roles, notifications, events, audit, etc. Ensure it's extensible, secure, and matches the architecture, but omit any socket/Pusher components. For notification delivery, create the records and queue them in BullMQ for push, with a processor that logs/stubs the send.