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:
- UniConnect Workflows (
WorkflowRegistry): Enabling workflow actions to send notifications and subscribe/unsubscribe users based on CRM business logic. - WebSocket Gateway (
websocket.service.js): Real-time push using existing{ entity, action, payload }protocols. - Relevance & Scoped Targeting: Ensuring users receive alerts only when an event is relevant to them (e.g., assigned records, group membership, role supervision).
- 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:
- 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 useswebsocket.sendToTopics(topics, payload)which automatically deduplicates users belonging to both personal and group targets.
- Audience Resolver (Workflow & Direct Actions):
For workflow-driven notifications, the resolver queries the database for active group members via
UserGroupand assigned agents, filters them againstUserNotificationPreference, 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}}), orSpecific 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 inDashboardHeader.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.
- Ant Design
- 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:
- Add
Notificationmodel touc-enterprise-core/prisma/schema.prismaand run migration. - Implement
services/notification/notification.service.jswith actions:send: Persist to DB and callwebsocket.sendToUser.list: Paginated query with read/unread filtering.unreadCount: Badge counter query.markAsRead: Update single record and broadcastREAD_UPDATED.markAllAsRead: Bulk update and broadcastREAD_ALL_UPDATED.
- Update
uc-enterprise-web/src/configs/websocket.tsto processentity === 'NOTIFICATION'. - Create
notificationSlice.tsin Redux Toolkit for state management. - Upgrade
NotificationBell.tsxinuc-enterprise-web/src/componentswith Badge and Popover list.
- Add
Phase 2: Workflow Engine Integration
- Goal: Enable automated notifications triggered by CRM workflows.
- Tasks:
- Register
notification.sendInAppinWorkflowRegistry. - Implement placeholder parameter resolution inside
executeActionNodeinworkflow.methods.js. - Support dynamic CTA URL generation based on workflow trigger context.
- Test end-to-end trigger-to-notification execution on CRM Ticket and Lead creations.
- Register
Phase 3: Topics & Relevance-Based Scoping
- Goal: Support topic subscriptions, group-level notifications, and user preference controls.
- Tasks:
- Add
UserNotificationPreferencetable to database. - Implement
AudienceResolverto determine recipient candidates viaUserGroup, Assigned Agent, and Roles. - Register
notification.manageSubscriptionaction inWorkflowRegistry. - Add a "Notification Preferences" tab in user settings for opting in/out of specific topics.
- Add
Phase 4: Omnichannel Orchestration
- Goal: Centralize multi-channel delivery (In-App, Browser Web Push, Email, SMS, WhatsApp).
- Tasks:
- Implement a unified dispatcher that inspects user channel preferences.
- Route to
push.service.js(BullMQ) if web push is enabled. - Route to
email.service.jsorsms.service.jsusing respective templates. - Add delivery status logs to track delivered vs opened vs clicked rates.
8. Security & Permissions
- Tenant & User Isolation: Users can only query, mark read, or dismiss notifications where
userId === ctx.meta.user.id. - Permission Check on Actions: Triggering manual broadcasts requires
MANAGE_NOTIFICATIONSpermission. - CTA Security: URL targets are validated against relative origin paths or allowlisted external domains to prevent open redirect vulnerabilities.