Skip to main content

Architecture Design Document: In-App Notifications & Topic Orchestration

RFC Number: RFC-012
Feature: In-App Notifications, Topic Subscriptions & Workflow Trigger Orchestration
Status: Proposed
Author: UniConnect Core & Web Engineering
Date: 2026-10-09


1. Executive Summary & Context​

UniConnect requires a unified, real-time notification engine. The primary objective is delivering in-app notifications with rich payloads (title, description, image, call-to-action, read/unread tracking) to web clients, while ensuring that the architecture natively integrates with:

  1. UniConnect Workflows (WorkflowRegistry): Enabling workflow actions to send notifications and subscribe/unsubscribe users based on CRM business logic.
  2. WebSocket Gateway (websocket.service.js): Real-time push using existing { entity, action, payload } protocols.
  3. Relevance & Scoped Targeting: Ensuring users receive alerts only when an event is relevant to them (e.g., assigned records, group membership, role supervision).
  4. Future Omnichannel Delivery: Centralizing In-App, Browser Web Push (VAPID), Email, SMS, and WhatsApp under a single notification dispatcher.

2. High-Level Architecture​


3. Data Model (prisma/schema.prisma)​

The schema supports rich content, call-to-action objects, granular read status, and user topic subscriptions:

enum NotificationType {
INFO
SUCCESS
WARNING
ERROR
ALERT
}

// ── In-App Notification Record ────────────────────────────────────────────────
model Notification {
id Int @id @default(autoincrement())
userId Int @map("user_id") // Recipient user
title String @db.VarChar(255)
description String @db.Text
image String? @db.Text // Thumbnail, icon, or sender avatar
type NotificationType @default(INFO)
topic String? @db.VarChar(100) // E.g., "tickets:status_changed"

// Structured Call To Action
// Example: { "type": "navigate", "label": "View Ticket", "url": "/crm/tickets/101", "target": "_self" }
callToAction Json? @map("call_to_action")

// Read status tracking
isRead Boolean @default(false) @map("is_read")
readAt DateTime? @map("read_at") @db.Timestamptz(3)

// Metadata & Context (source module, record ID, workflow execution ID)
metadata Json? @map("metadata")
createdById Int? @map("created_by_id")

createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(3)

user User @relation(fields: [userId], references: [id], onDelete: Cascade)

@@index([userId, isRead, createdAt(sort: Desc)])
@@index([userId, topic])
@@index([createdAt(sort: Desc)])
@@map("notifications")
}

// ── User Topic Subscription & Channel Preferences ────────────────────────────
model UserNotificationPreference {
id Int @id @default(autoincrement())
userId Int @map("user_id")
topic String @db.VarChar(100) // E.g., "crm.leads", "tickets.*"
isSubscribed Boolean @default(true) @map("is_subscribed")

// Channel opt-ins per topic (defaults to in_app only)
inApp Boolean @default(true) @map("in_app")
webPush Boolean @default(false) @map("web_push")
email Boolean @default(false) @map("email")
sms Boolean @default(false) @map("sms")

createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(3)

user User @relation(fields: [userId], references: [id], onDelete: Cascade)

@@unique([userId, topic])
@@index([userId])
@@map("user_notification_preferences")
}

4. Audience Resolution & Relevance Management​

Enterprise users should only receive notifications relevant to their roles, groups, or direct record assignments.

Two-Layer Delivery Strategy:​

  1. Scoped Topic Hierarchy (WebSocket Broadcasts): Reusing the pattern from callTopics.util.js:
    • ticket:user:{userId}: Personal alerts (assignment, mentions, direct replies).
    • ticket:group:{groupId}: Group alerts (all agents assigned to that queue/department).
    • ticket:all: Global supervisor notifications. The backend uses websocket.sendToTopics(topics, payload) which automatically deduplicates users belonging to both personal and group targets.
  2. Audience Resolver (Workflow & Direct Actions): For workflow-driven notifications, the resolver queries the database for active group members via UserGroup and assigned agents, filters them against UserNotificationPreference, and dispatches individualized notifications.

5. Workflow Engine Integration​

Workflows integrate with the Notification system via actions registered in WorkflowRegistry:

5.1 Action: notification.sendInApp​

Allows workflow authors to send targeted in-app alerts at any stage of a business process.

  • Inputs:
    • Recipient Mode: Direct Field ({{data.assignedToId}}), Group Members ({{data.groupId}}), or Specific User.
    • Title: String with template interpolation (e.g. New high-priority lead: {{data.companyName}}).
    • Description: Template string (e.g. Lead value: {{data.estimatedValue}} assigned to you.).
    • Image: Avatar/icon URL or dynamic variable (e.g. {{data.customerAvatar}}).
    • CTA Label: String (e.g. Open Lead).
    • CTA URL: Dynamic URL (e.g. /crm/leads/{{data.id}}).
    • Type: INFO | SUCCESS | WARNING | ERROR | ALERT.

5.2 Action: notification.manageSubscription​

Allows business workflows to subscribe or unsubscribe agents dynamically:

  • When a ticket is assigned to an agent $\rightarrow$ Subscribe agent to topic ticket:{ticketId}.
  • When a ticket is closed/resolved $\rightarrow$ Unsubscribe agent from ticket:{ticketId}.

6. Real-Time Protocol & Client Integration​

6.1 WebSocket Frame Protocol​

WebSocket frames follow UniConnect's standard envelope:

Notification Created (NOTIFICATION:CREATED)​

{
"entity": "NOTIFICATION",
"action": "CREATED",
"payload": {
"id": 105,
"title": "Lead Assigned",
"description": "Lead #4928 John Doe has been assigned to you.",
"image": "/assets/icons/lead-avatar.png",
"type": "INFO",
"callToAction": {
"type": "navigate",
"label": "View Lead",
"url": "/crm/leads/4928",
"target": "_self"
},
"isRead": false,
"createdAt": "2026-10-09T09:30:00Z"
}
}

Read Status Synced Across Tabs (NOTIFICATION:READ_UPDATED)​

{
"entity": "NOTIFICATION",
"action": "READ_UPDATED",
"payload": {
"id": 105,
"isRead": true,
"readAt": "2026-10-09T09:35:00Z"
}
}

6.2 Frontend UI Components (uc-enterprise-web)​

  • NotificationBell.tsx: Upgraded from permission-prompt button to full notification bell in DashboardHeader.tsx:
    • Ant Design <Badge count={unreadCount} overflowCount={99}>
    • Ant Design <Popover> or slide-out <Drawer>:
      • Tabs: "All" and "Unread".
      • Actions: "Mark all as read", "Clear all".
      • List Item: Avatar/image, title, formatted description, relative time (3m ago), interactive CTA button, and read/unread toggle.
  • Navigation Handler: Clicking CTA parses the url. If internal (e.g., /crm/leads/4928), it navigates via React Router without page refresh; if external, opens in a new tab.

7. Phased Implementation Plan​

Phase 1: Core In-App Notifications (MVP)​

  • Goal: Deliver functional in-app notifications with read/unread tracking and real-time WebSocket delivery.
  • Tasks:
    1. Add Notification model to uc-enterprise-core/prisma/schema.prisma and run migration.
    2. Implement services/notification/notification.service.js with actions:
      • send: Persist to DB and call websocket.sendToUser.
      • list: Paginated query with read/unread filtering.
      • unreadCount: Badge counter query.
      • markAsRead: Update single record and broadcast READ_UPDATED.
      • markAllAsRead: Bulk update and broadcast READ_ALL_UPDATED.
    3. Update uc-enterprise-web/src/configs/websocket.ts to process entity === 'NOTIFICATION'.
    4. Create notificationSlice.ts in Redux Toolkit for state management.
    5. Upgrade NotificationBell.tsx in uc-enterprise-web/src/components with Badge and Popover list.

Phase 2: Workflow Engine Integration​

  • Goal: Enable automated notifications triggered by CRM workflows.
  • Tasks:
    1. Register notification.sendInApp in WorkflowRegistry.
    2. Implement placeholder parameter resolution inside executeActionNode in workflow.methods.js.
    3. Support dynamic CTA URL generation based on workflow trigger context.
    4. Test end-to-end trigger-to-notification execution on CRM Ticket and Lead creations.

Phase 3: Topics & Relevance-Based Scoping​

  • Goal: Support topic subscriptions, group-level notifications, and user preference controls.
  • Tasks:
    1. Add UserNotificationPreference table to database.
    2. Implement AudienceResolver to determine recipient candidates via UserGroup, Assigned Agent, and Roles.
    3. Register notification.manageSubscription action in WorkflowRegistry.
    4. Add a "Notification Preferences" tab in user settings for opting in/out of specific topics.

Phase 4: Omnichannel Orchestration​

  • Goal: Centralize multi-channel delivery (In-App, Browser Web Push, Email, SMS, WhatsApp).
  • Tasks:
    1. Implement a unified dispatcher that inspects user channel preferences.
    2. Route to push.service.js (BullMQ) if web push is enabled.
    3. Route to email.service.js or sms.service.js using respective templates.
    4. Add delivery status logs to track delivered vs opened vs clicked rates.

8. Security & Permissions​

  1. Tenant & User Isolation: Users can only query, mark read, or dismiss notifications where userId === ctx.meta.user.id.
  2. Permission Check on Actions: Triggering manual broadcasts requires MANAGE_NOTIFICATIONS permission.
  3. CTA Security: URL targets are validated against relative origin paths or allowlisted external domains to prevent open redirect vulnerabilities.