1. Overview
The Notification Module in the Audit Admin application is a comprehensive system designed to manage and configure various types of notifications across different communication channels. This module enables administrators to configure notification preferences for reports, issues, and system events, supporting multiple delivery channels including email, WhatsApp, and push notifications.
Related Features:
- Settings - Parent settings management
- Reports - Report notification triggers
- Issue Tracker - Issue notification events
- Users - Notification recipients and preferences
- Authentication - User context and permissions
1.1 Purpose
The notification system serves as the central hub for:
- Managing notification preferences for different user roles
- Configuring notification triggers for various system events
- Supporting multi-channel communication strategies
- Providing granular control over notification frequency and timing
- Enabling users to manage their subscription preferences
1.2 Key Capabilities
- Multi-channel Support: Email, WhatsApp, and Push notifications
- Role-based Configuration: Different notification settings for various user roles
- Event-driven Architecture: Notifications triggered by specific system events
- Flexible Scheduling: Daily, weekly, and custom frequency options
- Unsubscribe Management: User-controlled opt-out capabilities
2. Architecture
The notification module follows a modular, component-based architecture with clear separation of concerns:
graph TB subgraph "UI Layer" Page[NotificationSettingPage] Settings[SettingsNotification] Report[ReportNotificationSettings] Issue[IssueNotificationSettings] Unsub[UnsubscribeSettings] end subgraph "State Management" Redux[Redux Store] Query[Query Reducer] Mutation[Mutation Reducer] Actions[Action Creators] end subgraph "Service Layer" Service[NotificationService] API[API Endpoints] end subgraph "Backend" Server[Server API] DB[(Database)] end Page --> Settings Settings --> Report Settings --> Issue Settings --> Unsub Report --> Redux Issue --> Redux Unsub --> Redux Redux --> Query Redux --> Mutation Redux --> Actions Actions --> Service Service --> API API --> Server Server --> DB
2.1 Design Principles
- Modularity: Each notification type has its own component and configuration
- Reusability: Common components shared across different notification types
- Scalability: Easy to add new notification types or channels
- Maintainability: Clear separation between UI, state, and service layers
3. Module Structure
The notification module is organized into the following directory structure:
src/
├── pages/
│ └── settings/
│ └── notification.tsx # Entry point page component
├── components/
│ └── settings/
│ └── SettingsNotification/
│ ├── SettingsNotification.tsx # Main container component
│ ├── SettingsNotification.module.scss
│ ├── components/
│ │ ├── ReportNotificationSettings/
│ │ ├── IssueNotificationSettings/
│ │ ├── UnsubscribeSettings/
│ │ ├── ConfigChannel/
│ │ ├── ConfigFrequency/
│ │ └── ConfigRoleRecipients/
│ └── constants/
├── reducers/
│ └── settingsPage/
│ └── settingsNotification/
│ ├── settingsNotification.actions.ts
│ ├── settingsNotification.query.reducer.ts
│ ├── settingsNotification.mutation.reducer.ts
│ └── settingsNotification.selector.ts
├── services/
│ └── settings/
│ └── settingsNotification/
│ └── settingsNotification.service.ts
└── routes/
└── admin-routes.js # Route configuration
4. Component Hierarchy
4.1 Main Components
4.1.1 NotificationSettingPage
Location: src/pages/settings/notification.tsx
The entry point component that provides the page layout and lazy loads the main notification settings component.
const NotificationSettingPage = () => {
return (
<Layout>
<Suspense fallback={<div />}>
<LeavePageConfirmationModal>
<SettingsNotification />
</LeavePageConfirmationModal>
</Suspense>
</Layout>
);
};4.1.2 SettingsNotification
Location: src/components/settings/SettingsNotification/SettingsNotification.tsx
The main container component that orchestrates the notification settings interface. It manages:
- Tab navigation between different notification types
- Loading states and error handling
- Data fetching and state management integration
- Form submission and validation
const SettingsNotification = () => {
const dispatch = useDispatch();
const { t } = useTranslation();
const [activeTab, setActiveTab] = useState('report');
// Redux selectors
const notificationSettings = useSelector(selectNotificationSettings);
const isLoading = useSelector(selectNotificationLoading);
const unsubscribeSettings = useSelector(selectUnsubscribeSettings);
useEffect(() => {
// Fetch notification settings on mount
dispatch(fetchNotificationSettings({
notificationType: activeTab
}));
dispatch(fetchUnsubscribeSettings());
dispatch(fetchNotificationRoles());
}, [activeTab, dispatch]);
const handleTabChange = (tab) => {
setActiveTab(tab);
};
return (
<div className={styles.container}>
<Tabs
activeTab={activeTab}
onChange={handleTabChange}
tabs={[
{ id: 'report', label: t('notification.tabs.report') },
{ id: 'issue', label: t('notification.tabs.issue') },
{ id: 'unsubscribe', label: t('notification.tabs.unsubscribe') }
]}
/>
<div className={styles.content}>
{activeTab === 'report' && (
<ReportNotificationSettings
settings={notificationSettings}
isLoading={isLoading}
/>
)}
{activeTab === 'issue' && (
<IssueNotificationSettings
settings={notificationSettings}
isLoading={isLoading}
/>
)}
{activeTab === 'unsubscribe' && (
<UnsubscribeSettings
settings={unsubscribeSettings}
isLoading={isLoading}
/>
)}
</div>
</div>
);
};4.2 Sub-Components
4.2.1 ReportNotificationSettings
Manages notification settings for report-related events:
- Report generation notifications
- Near due date alerts
- Overdue report warnings
- Audit recap summaries
const ReportNotificationSettings = ({ settings, isLoading }) => {
const dispatch = useDispatch();
const { t } = useTranslation();
const formik = useFormik({
initialValues: {
notifications: settings || []
},
validationSchema: reportNotificationSchema,
onSubmit: async (values) => {
await dispatch(updateReportNotifications(values));
}
});
const reportTypes = [
{ id: 'REPORT_GENERATED', label: t('notification.report.generated') },
{ id: 'REPORT_NEAR_DUE', label: t('notification.report.nearDue') },
{ id: 'REPORT_OVERDUE', label: t('notification.report.overdue') },
{ id: 'AUDIT_RECAP', label: t('notification.report.recap') }
];
return (
<FormikProvider value={formik}>
<Form>
{reportTypes.map(type => (
<NotificationRow
key={type.id}
type={type}
formik={formik}
index={settings.findIndex(s => s.type === type.id)}
/>
))}
<Button type="submit" loading={isLoading}>
{t('common.save')}
</Button>
</Form>
</FormikProvider>
);
};4.2.2 IssueNotificationSettings
Handles configuration for issue tracking notifications:
- Issue creation alerts
- Status change notifications
- Assignment updates
- Resolution notifications
const IssueNotificationSettings = ({ settings, isLoading }) => {
const dispatch = useDispatch();
const roles = useSelector(selectNotificationRoles);
const handleToggleNotification = (notificationId, enabled) => {
dispatch(updateNotificationStatus(notificationId, enabled));
};
const handleUpdateChannels = (notificationId, channels) => {
dispatch(updateNotificationChannels(notificationId, channels));
};
const groupedNotifications = useMemo(() => {
return groupNotificationsByCategory(settings);
}, [settings]);
return (
<div className={styles.issueSettings}>
{Object.entries(groupedNotifications).map(([category, notifications]) => (
<NotificationCategory
key={category}
category={category}
notifications={notifications}
onToggle={handleToggleNotification}
onUpdateChannels={handleUpdateChannels}
roles={roles}
/>
))}
</div>
);
};4.2.3 UnsubscribeSettings
Provides interface for managing unsubscribe preferences:
- Email opt-out options
- WhatsApp unsubscribe settings
- Channel-specific preferences
const UnsubscribeSettings = ({ settings, isLoading }) => {
const dispatch = useDispatch();
const [localSettings, setLocalSettings] = useState(settings);
const handleToggleChannel = (channel) => {
const updated = {
...localSettings,
[channel]: !localSettings[channel]
};
setLocalSettings(updated);
dispatch(updateUnsubscribeSettings(updated));
};
return (
<div className={styles.unsubscribeContainer}>
<h3>{t('notification.unsubscribe.title')}</h3>
<p>{t('notification.unsubscribe.description')}</p>
<div className={styles.channelOptions}>
<ChannelToggle
channel="email"
enabled={!localSettings.emailUnsubscribed}
onChange={() => handleToggleChannel('emailUnsubscribed')}
loading={isLoading}
/>
<ChannelToggle
channel="whatsapp"
enabled={!localSettings.whatsappUnsubscribed}
onChange={() => handleToggleChannel('whatsappUnsubscribed')}
loading={isLoading}
/>
</div>
<Alert type="info">
{t('notification.unsubscribe.info')}
</Alert>
</div>
);
};4.3 Shared Configuration Components
4.3.1 ConfigChannel
A reusable component for selecting notification channels:
- Email selection
- WhatsApp configuration
- Push notification toggles
4.3.2 ConfigFrequency
Manages notification frequency settings:
- Daily digest options
- Weekly summary preferences
- Real-time notification toggles
4.3.3 ConfigRoleRecipients
Controls role-based notification distribution:
- Role selection interface
- Multi-select capabilities
- Hierarchical role management
5. Routes and Navigation
5.1 Route Configuration
| Route Path | Component | Access Control | Description |
|---|---|---|---|
/settings/notification | NotificationSettingPage | RoleResources.SETTING_PERMISSION_GENERAL_ALL | Main notification settings page |
Route Definition (from src/routes/admin-routes.js:704-709):
<Route
exact
path="/settings/notification"
component={NotificationSettingPage}
withValidation
access={RoleResources.SETTING_PERMISSION_GENERAL_ALL}
/>5.2 Navigation Flow
graph LR A[Admin Dashboard] --> B[Settings Menu] B --> C[Notification Settings] C --> D{Tab Selection} D --> E[Report Notifications] D --> F[Issue Notifications] D --> G[Unsubscribe Settings] E --> H[Configure Channels] E --> I[Set Frequency] E --> J[Select Recipients] F --> K[Configure Channels] F --> L[Set Frequency] F --> M[Select Recipients] G --> N[Email Preferences] G --> O[WhatsApp Preferences]
6. API Endpoints
The notification module interacts with the following API endpoints:
| Endpoint | Method | Purpose | Request/Response |
|---|---|---|---|
/api/settings/[notifications](NotificationOverview.md) | GET | Fetch current notification settings | Returns notification configuration object |
/api/settings/[notifications](NotificationOverview.md) | POST | Create new notification settings | Accepts notification settings payload |
/api/settings/[notifications](NotificationOverview.md)/:id | PUT | Update existing notification settings | Updates specific notification configuration |
/api/settings/[notifications](NotificationOverview.md)/:id | DELETE | Remove notification settings | Deletes notification configuration |
/api/settings/[notifications](NotificationOverview.md)/unsubscribe | POST | Update unsubscribe preferences | Updates user opt-out settings |
/api/settings/[notifications](NotificationOverview.md)/roles | GET | Fetch available roles for notifications | Returns list of applicable roles |
/api/settings/[notifications](NotificationOverview.md)/templates | GET | Get notification templates | Returns available notification templates |
6.1 Service Implementation
Location: src/services/settings/settingsNotification/settingsNotification.service.ts
The service layer provides abstraction over HTTP requests with comprehensive error handling and response transformation:
const service = {
// Fetch notification settings with pagination support
getNotificationList: (currentPage, limit, keyword, notificationType) =>
getRequest('/noti/getSettings', {
params: {
currentPage,
limit,
keyword,
notificationType,
sort: 'name'
}
}),
// Create new notification configuration
createNotificationSettings: (data) =>
postRequest('/noti/updateNotificationSettings', data),
// Update existing notification settings
updateNotificationSettings: (settingsId, data) =>
postRequest(`/noti/updateNotificationSettings/${settingsId}`, data),
// Delete notification configuration
deleteNotificationSettings: (settingsId) =>
deleteRequest(`/noti/deleteNotificationSettings/${settingsId}`),
// Fetch unsubscribe settings for current user
getUnsubscribeSettings: () =>
getRequest('/noti/getUnsubscribeSettings'),
// Update unsubscribe preferences
updateUnsubscribeSettings: (data) =>
postRequest('/noti/updateUnsubscribeSettings', data),
// Get available roles for notification recipients
getNotificationRoles: () =>
getRequest('/roles/list', {
params: { limit: 1000 }
})
};6.2 API Response Structure
interface NotificationSettingsResponse {
data: {
docs: NotificationSetting[];
totalDocs: number;
limit: number;
page: number;
totalPages: number;
};
status: number;
message: string;
}
interface NotificationSetting {
_id: string;
name: string;
description: string;
notificationType: 'report' | 'issue';
eventType: string;
channels: NotificationChannel[];
recipients: {
roles: string[];
users: string[];
reportedByManager: boolean;
reportedByAreaManager: boolean;
};
frequency: {
type: string;
time?: string;
interval?: number;
};
enabled: boolean;
createdAt: string;
updatedAt: string;
}7. State Management
The notification module uses Redux for state management with a modular reducer structure:
7.1 Redux Structure
graph TB subgraph "Redux Store" Store[Global Store] Settings[settingsPage] Notification[settingsNotification] Query[Query State] Mutation[Mutation State] end Store --> Settings Settings --> Notification Notification --> Query Notification --> Mutation Query --> QData[Notification Data] Query --> QLoading[Loading States] Query --> QError[Error States] Mutation --> MData[Mutation Results] Mutation --> MLoading[Operation Status] Mutation --> MError[Operation Errors]
7.2 Query Reducer
Location: src/reducers/settingsPage/settingsNotification/settingsNotification.query.reducer.ts
Manages read operations and data fetching:
- Notification settings retrieval
- Loading states for data fetching
- Error handling for failed requests
- Caching of fetched data
7.3 Mutation Reducer
Location: src/reducers/settingsPage/settingsNotification/settingsNotification.mutation.reducer.ts
Handles write operations:
- Create notification settings
- Update existing configurations
- Delete notification rules
- Track operation status
7.4 Actions
Location: src/reducers/settingsPage/settingsNotification/settingsNotification.actions.ts
Defines action creators using Redux-Saga patterns:
// Action Types
export const ActionTypes = {
// Query Actions
FETCH_NOTIFICATION_SETTINGS: 'FETCH_NOTIFICATION_SETTINGS',
FETCH_NOTIFICATION_SETTINGS_SUCCESS: 'FETCH_NOTIFICATION_SETTINGS_SUCCESS',
FETCH_NOTIFICATION_SETTINGS_FAILURE: 'FETCH_NOTIFICATION_SETTINGS_FAILURE',
FETCH_UNSUBSCRIBE_SETTINGS: 'FETCH_UNSUBSCRIBE_SETTINGS',
FETCH_UNSUBSCRIBE_SETTINGS_SUCCESS: 'FETCH_UNSUBSCRIBE_SETTINGS_SUCCESS',
FETCH_UNSUBSCRIBE_SETTINGS_FAILURE: 'FETCH_UNSUBSCRIBE_SETTINGS_FAILURE',
// Mutation Actions
CREATE_NOTIFICATION_SETTINGS: 'CREATE_NOTIFICATION_SETTINGS',
UPDATE_NOTIFICATION_SETTINGS: 'UPDATE_NOTIFICATION_SETTINGS',
DELETE_NOTIFICATION_SETTINGS: 'DELETE_NOTIFICATION_SETTINGS',
UPDATE_UNSUBSCRIBE_SETTINGS: 'UPDATE_UNSUBSCRIBE_SETTINGS',
};
// Action Creators
export const fetchNotificationSettings = (params) => ({
type: ActionTypes.FETCH_NOTIFICATION_SETTINGS,
payload: params
});
export const updateNotificationSettings = (id, data) => ({
type: ActionTypes.UPDATE_NOTIFICATION_SETTINGS,
payload: { id, data }
});
// Saga Implementation
function* fetchNotificationSettingsSaga(action) {
try {
const response = yield call(
service.getNotificationList,
action.payload.currentPage,
action.payload.limit,
action.payload.keyword,
action.payload.notificationType
);
yield put({
type: ActionTypes.FETCH_NOTIFICATION_SETTINGS_SUCCESS,
payload: response.data
});
} catch (error) {
yield put({
type: ActionTypes.FETCH_NOTIFICATION_SETTINGS_FAILURE,
payload: error.message
});
}
}7.5 Selectors
Location: src/reducers/settingsPage/settingsNotification/settingsNotification.selector.ts
Provides memoized selectors for efficient state access:
import { createSelector } from 'reselect';
// Base selectors
const selectNotificationState = (state) => state.settingsPage.settingsNotification;
const selectQueryState = (state) => selectNotificationState(state).query;
const selectMutationState = (state) => selectNotificationState(state).mutation;
// Memoized selectors
export const selectNotificationSettings = createSelector(
[selectQueryState],
(query) => query.notificationSettings
);
export const selectNotificationLoading = createSelector(
[selectQueryState],
(query) => query.isLoading
);
export const selectUnsubscribeSettings = createSelector(
[selectQueryState],
(query) => query.unsubscribeSettings
);
export const selectNotificationRoles = createSelector(
[selectQueryState],
(query) => query.roles || []
);8. Notification Types
8.1 Report Notifications
The system supports four types of report notifications:
| Type | Description | Trigger Condition | Default Frequency | Recipients |
|---|---|---|---|---|
REPORT_GENERATED | Notification when a new report is generated | Report creation completion | Immediate | Report creator, managers |
REPORT_NEAR_DUE | Alert for reports approaching due date | 24 hours before due date | Daily digest | Assigned auditors |
REPORT_OVERDUE | Warning for overdue reports | Report past due date | Daily | Auditors, supervisors |
AUDIT_RECAP | Summary of audit activities | End of audit period | Weekly | All stakeholders |
8.1.1 Report Notification Flow
flowchart TD A[Report Event Triggered] --> B{Event Type} B -->|Generated| C[REPORT_GENERATED] B -->|Due Soon| D[REPORT_NEAR_DUE] B -->|Overdue| E[REPORT_OVERDUE] B -->|Period End| F[AUDIT_RECAP] C --> G[Check Settings] D --> G E --> G F --> G G --> H{Enabled?} H -->|No| I[Skip Notification] H -->|Yes| J[Get Recipients] J --> K[Apply Role Filters] K --> L[Check Channels] L --> M{Channel Type} M -->|Email| N[Queue Email] M -->|WhatsApp| O[Queue WhatsApp] M -->|Push| P[Queue Push] N --> Q[Send Notification] O --> Q P --> Q
8.2 Issue Notifications
The system supports comprehensive issue tracking notifications:
| Type | Description | Trigger Event | Default Recipients |
|---|---|---|---|
ISSUE_CREATED | New issue creation alert | Issue submission | Issue managers, department heads |
ISSUE_ASSIGNED | Issue assignment notification | Assignment change | Assigned user, previous assignee |
ISSUE_STATUS_CHANGED | Status update notification | Status transition | Issue owner, assignee |
ISSUE_PRIORITY_CHANGED | Priority modification alert | Priority update | Issue managers |
ISSUE_RESOLVED | Issue resolution notification | Issue closure | Reporter, stakeholders |
ISSUE_REOPENED | Issue reopening alert | Status reversion | Resolver, managers |
ISSUE_COMMENTED | New comment notification | Comment addition | Issue participants |
ISSUE_ATTACHMENT_ADDED | File attachment alert | Attachment upload | Issue watchers |
ISSUE_DUE_DATE_CHANGED | Due date modification | Date update | Assignee, managers |
ISSUE_ESCALATED | Escalation notification | Escalation trigger | Senior management |
ISSUE_CATEGORY_CHANGED | Category update alert | Category modification | Category owners |
ISSUE_DEPARTMENT_CHANGED | Department transfer notification | Department change | Both departments |
ISSUE_APPROVAL_REQUESTED | Approval request alert | Approval initiation | Approvers |
ISSUE_APPROVAL_STATUS | Approval decision notification | Approval completion | Requester, stakeholders |
8.2.1 Issue Notification Constants
export const ISSUE_NOTIFICATION_TYPES = {
CREATION: {
NEW_ISSUE: 'NEW_ISSUE',
ISSUE_FROM_REPORT: 'ISSUE_FROM_REPORT'
},
ASSIGNMENT: {
ASSIGNED_TO_ME: 'ASSIGNED_TO_ME',
UNASSIGNED_FROM_ME: 'UNASSIGNED_FROM_ME',
REASSIGNED: 'REASSIGNED'
},
STATUS: {
STATUS_CHANGED: 'STATUS_CHANGED',
RESOLVED: 'RESOLVED',
REOPENED: 'REOPENED',
CLOSED: 'CLOSED'
},
UPDATES: {
PRIORITY_CHANGED: 'PRIORITY_CHANGED',
CATEGORY_CHANGED: 'CATEGORY_CHANGED',
DUE_DATE_CHANGED: 'DUE_DATE_CHANGED',
DESCRIPTION_UPDATED: 'DESCRIPTION_UPDATED'
},
COLLABORATION: {
COMMENT_ADDED: 'COMMENT_ADDED',
MENTIONED_IN_COMMENT: 'MENTIONED_IN_COMMENT',
ATTACHMENT_ADDED: 'ATTACHMENT_ADDED'
},
ESCALATION: {
ESCALATED: 'ESCALATED',
DE_ESCALATED: 'DE_ESCALATED',
SLA_BREACH: 'SLA_BREACH'
},
APPROVAL: {
APPROVAL_REQUESTED: 'APPROVAL_REQUESTED',
APPROVED: 'APPROVED',
REJECTED: 'REJECTED',
APPROVAL_WITHDRAWN: 'APPROVAL_WITHDRAWN'
}
};9. Communication Channels
9.1 Email Channel
Email notifications support:
- HTML templates with branding
- Attachment support for reports
- Bulk email capabilities
- Unsubscribe links in footer
Configuration options:
- Subject line customization
- Template selection
- CC/BCC recipients
- Reply-to addresses
9.2 WhatsApp Channel
WhatsApp integration features:
- Template message support
- Media attachment capabilities
- Quick action buttons
- Delivery status tracking
Configuration includes:
- Template approval management
- Phone number validation
- Message throttling controls
- Opt-in/opt-out management
9.3 Push Notifications
Push notification support:
- Web push for browser notifications
- Mobile push for app notifications
- Rich media support
- Action buttons
Settings include:
- Permission management
- Sound preferences
- Badge counters
- Priority levels
10. Package Dependencies
The notification module relies on the following packages:
| Package | Version | Purpose | Usage in Module |
|---|---|---|---|
react | ^17.0.2 | Core React library | Component development |
react-redux | ^7.2.4 | Redux React bindings | State management integration |
redux | ^4.1.0 | State management | Global state handling |
redux-saga | ^1.1.3 | Redux side effects | Async flow management |
axios | ^0.21.1 | HTTP client | API communication |
formik | ^2.2.9 | Form management | Form state and validation |
yup | ^0.32.9 | Schema validation | Form validation schemas |
@loadable/component | ^5.15.0 | Code splitting | Lazy loading components |
react-router-dom | ^5.2.0 | Routing library | Navigation handling |
classnames | ^2.3.1 | CSS class utilities | Dynamic styling |
@nimbly-technologies/nimbly-common | Latest | Shared components | Common UI elements |
node-sass | ^6.0.1 | SCSS compilation | Styling |
i18next | ^20.3.2 | Internationalization | Multi-language support |
react-i18next | ^11.11.1 | React i18n bindings | Translation hooks |
lodash | ^4.17.21 | Utility library | Data manipulation |
moment | ^2.29.1 | Date manipulation | Time formatting |
11. Data Flow
The notification module follows a unidirectional data flow pattern:
sequenceDiagram participant User participant Component participant Action participant Reducer participant Store participant Service participant API User->>Component: Configure notification Component->>Action: Dispatch update action Action->>Service: Call API service Service->>API: HTTP request API-->>Service: Response data Service-->>Action: Process response Action->>Reducer: Update state Reducer->>Store: New state Store-->>Component: State update Component-->>User: UI update
11.1 Data Flow Stages
- User Interaction: User modifies notification settings through UI
- Component Handling: Component validates input and prepares data
- Action Dispatch: Action creator is called with configuration data
- Service Call: Service layer makes API request
- State Update: Reducer processes response and updates store
- UI Sync: Component re-renders with updated state
12. Key Features
12.1 Role-Based Notification Management
The system provides granular control over notifications based on user roles:
- Role Hierarchy Support: Notifications can cascade through role hierarchies
- Multi-Role Selection: Configure notifications for multiple roles simultaneously
- Role-Specific Templates: Different notification templates per role
- Dynamic Role Loading: Roles fetched from backend based on permissions
Implementation approach:
interface RoleNotificationConfig {
roleId: string;
roleName: string;
channels: NotificationChannel[];
frequency: NotificationFrequency;
enabled: boolean;
}
// Role selection component implementation
const ConfigRoleRecipients = ({ formik, name, disabled }) => {
const roles = useSelector(selectNotificationRoles);
const handleRoleSelection = (selectedRoles) => {
formik.setFieldValue(name, selectedRoles);
};
return (
<MultiSelect
options={roles}
value={formik.values[name]}
onChange={handleRoleSelection}
disabled={disabled}
placeholder="Select roles"
/>
);
};12.2 Flexible Scheduling System
The notification scheduling system supports:
- Immediate Notifications: Real-time alerts for critical events
- Daily Digests: Consolidated daily summaries at configured times
- Weekly Reports: Weekly rollup notifications
- Custom Schedules: Cron-based scheduling for complex patterns
Scheduling configuration:
interface ScheduleConfig {
type: 'immediate' | 'daily' | 'weekly' | 'custom';
time?: string; // HH:MM format
dayOfWeek?: number; // 0-6 for weekly
cronExpression?: string; // For custom schedules
timezone: string;
}
// Frequency component implementation
const ConfigFrequency = ({ formik, name, disabled }) => {
const frequencyOptions = [
{ value: 'immediate', label: 'Immediate' },
{ value: 'daily', label: 'Daily' },
{ value: 'weekly', label: 'Weekly' },
{ value: 'custom', label: 'Custom' }
];
return (
<div className={styles.frequencyConfig}>
<Select
options={frequencyOptions}
value={formik.values[`${name}.type`]}
onChange={(value) => formik.setFieldValue(`${name}.type`, value)}
disabled={disabled}
/>
{formik.values[`${name}.type`] === 'daily' && (
<TimePicker
value={formik.values[`${name}.time`]}
onChange={(time) => formik.setFieldValue(`${name}.time`, time)}
format="HH:mm"
/>
)}
{formik.values[`${name}.type`] === 'weekly' && (
<>
<DayPicker
value={formik.values[`${name}.dayOfWeek`]}
onChange={(day) => formik.setFieldValue(`${name}.dayOfWeek`, day)}
/>
<TimePicker
value={formik.values[`${name}.time`]}
onChange={(time) => formik.setFieldValue(`${name}.time`, time)}
format="HH:mm"
/>
</>
)}
</div>
);
};12.3 Template Management
Notification templates provide:
- Dynamic Variable Support: Placeholders for dynamic content
- Multi-Language Support: Internationalized templates
- Preview Functionality: Real-time template preview
- Version Control: Template versioning for updates
Template structure:
interface NotificationTemplate {
id: string;
name: string;
subject: string;
body: string;
variables: TemplateVariable[];
channels: NotificationChannel[];
version: number;
}12.4 Delivery Tracking
The system tracks notification delivery:
- Delivery Status: Sent, delivered, failed, bounced
- Read Receipts: Track when notifications are read
- Engagement Metrics: Click-through rates for links
- Retry Logic: Automatic retry for failed deliveries
12.5 Bulk Operations
Support for bulk notification management:
- Bulk Enable/Disable: Toggle multiple notifications at once
- Bulk Channel Updates: Update channels for multiple notifications
- Import/Export: Configuration import/export capabilities
- Batch Processing: Efficient processing of large notification sets
13. Configuration Management
13.1 Configuration Structure
The notification configuration follows a hierarchical structure:
interface NotificationConfig {
id: string;
type: NotificationType;
enabled: boolean;
channels: ChannelConfig[];
recipients: RecipientConfig;
schedule: ScheduleConfig;
template: TemplateConfig;
metadata: ConfigMetadata;
}
interface ChannelConfig {
type: 'email' | 'whatsapp' | 'push';
enabled: boolean;
settings: ChannelSpecificSettings;
}
interface RecipientConfig {
roles: string[];
users: string[];
groups: string[];
rules: RecipientRule[];
}13.2 Configuration Validation
The system implements comprehensive validation:
- Channel Validation: Ensures valid channel configurations
- Recipient Validation: Verifies recipient existence and permissions
- Schedule Validation: Validates cron expressions and time formats
- Template Validation: Ensures all required variables are provided
13.3 Configuration Persistence
Configurations are persisted with:
- Audit Trail: Track all configuration changes
- Version History: Maintain configuration versions
- Rollback Support: Ability to revert to previous configurations
- Export/Import: Configuration portability
14. Integration Points
14.1 Authentication System Integration
The notification module integrates with the authentication system for:
- User role determination
- Permission validation
- Session management
- User preference storage
flowchart LR A[Notification Module] --> B[Auth System] B --> C[User Roles] B --> D[Permissions] B --> E[User Preferences] C --> F[Role-based Recipients] D --> G[Access Control](../../Settings/Access control/AccessControlOverview.md) E --> H[Channel Preferences] F --> I[Notification Delivery] G --> I H --> I
14.2 Reporting System Integration
Integration with the reporting module for:
- Report generation events
- Report scheduling notifications
- Report delivery confirmations
- Error notifications
// Report Event Integration
interface ReportEventHandler {
onReportGenerated: (report: Report) => void;
onReportDueSoon: (report: Report) => void;
onReportOverdue: (report: Report) => void;
onReportError: (error: ReportError) => void;
}
// Integration implementation
class ReportNotificationIntegration {
handleReportEvent(event: ReportEvent) {
switch(event.type) {
case 'GENERATED':
this.notificationService.sendReportGenerated(event.data);
break;
case 'DUE_SOON':
this.notificationService.sendReportDueSoon(event.data);
break;
case 'OVERDUE':
this.notificationService.sendReportOverdue(event.data);
break;
}
}
}14.3 Issue Tracking Integration
Deep integration with issue tracking:
- Real-time issue event notifications
- Workflow-based notification triggers
- SLA breach alerts
- Escalation notifications
stateDiagram-v2 [*] --> Created: Issue Created Created --> Assigned: Assign Issue Assigned --> InProgress: Start Work InProgress --> Resolved: Resolve Issue Resolved --> Closed: Close Issue Resolved --> Reopened: Reopen Issue Reopened --> InProgress: Resume Work Created --> Notification1: Send Creation Notification Assigned --> Notification2: Send Assignment Notification Resolved --> Notification3: Send Resolution Notification Reopened --> Notification4: Send Reopening Notification
14.4 Audit System Integration
Integration points include:
- Audit completion notifications
- Compliance alerts
- Exception notifications
- Summary report triggers
// Audit Integration Service
class AuditNotificationService {
async handleAuditComplete(audit: Audit) {
const recipients = await this.getAuditRecipients(audit);
const notifications = [];
// Check notification settings
const settings = await this.getNotificationSettings('AUDIT_COMPLETE');
if (settings.enabled) {
// Send to configured channels
if (settings.channels.includes('email')) {
notifications.push(this.sendEmail(recipients, audit));
}
if (settings.channels.includes('whatsapp')) {
notifications.push(this.sendWhatsApp(recipients, audit));
}
if (settings.channels.includes('push')) {
notifications.push(this.sendPush(recipients, audit));
}
}
return Promise.all(notifications);
}
}14.5 External Service Integration
The module supports integration with:
- SMTP servers for email delivery
- WhatsApp Business API
- Push notification services (FCM, APNS)
- SMS gateways (future expansion)
graph TB subgraph "Notification Service" NS[Notification System] end subgraph "Email Services" SMTP[SMTP Server] SES[AWS SES] SG[SendGrid] end subgraph "Messaging Services" WA[WhatsApp Business API] SMS[SMS Gateway] end subgraph "Push Services" FCM[Firebase Cloud Messaging] APNS[Apple Push Service] end NS --> SMTP NS --> SES NS --> SG NS --> WA NS --> SMS NS --> FCM NS --> APNS
15. Security Considerations
15.1 Access Control
Security measures include:
- Role-Based Access: Only authorized roles can modify settings
- Permission Validation: Server-side permission checks
- Audit Logging: All configuration changes are logged
- IP Restrictions: Optional IP-based access control
15.2 Data Protection
Data security features:
- Encryption: Sensitive data encrypted at rest
- Secure Transmission: HTTPS for all API calls
- Token Security: Secure token management for external services
- PII Handling: Proper handling of personally identifiable information
15.3 Channel Security
Channel-specific security:
- Email Security: SPF, DKIM, DMARC configuration
- WhatsApp Security: End-to-end encryption support
- Push Security: Secure key management
- Rate Limiting: Prevent notification spam
15.4 Compliance
Compliance considerations:
- GDPR Compliance: Right to be forgotten, data portability
- CAN-SPAM Compliance: Unsubscribe mechanisms
- Data Retention: Configurable retention policies
- Audit Requirements: Comprehensive audit trails
16. Implementation Examples
16.1 Creating a New Notification Configuration
// Example: Creating a new report notification
const createReportNotification = async () => {
const notificationData = {
name: "Monthly Audit Report",
description: "Send monthly audit summary to managers",
notificationType: "report",
eventType: "AUDIT_RECAP",
channels: ["email", "whatsapp"],
recipients: {
roles: ["manager", "supervisor"],
users: [],
reportedByManager: true,
reportedByAreaManager: false
},
frequency: {
type: "monthly",
dayOfMonth: 1,
time: "09:00"
},
template: {
subject: "Monthly Audit Report - {{month}} {{year}}",
body: "audit-recap-template",
variables: {
month: "{{currentMonth}}",
year: "{{currentYear}}",
totalAudits: "{{auditCount}}",
completionRate: "{{completionPercentage}}"
}
},
enabled: true
};
try {
const response = await service.createNotificationSettings(notificationData);
dispatch(notificationCreatedSuccess(response.data));
toast.success("Notification created successfully");
} catch (error) {
dispatch(notificationCreatedFailure(error));
toast.error("Failed to create notification");
}
};16.2 Notification Delivery Flow
sequenceDiagram participant Event as System Event participant Handler as Event Handler participant Config as Configuration Service participant Queue as Notification Queue participant Delivery as Delivery Service participant Channel as Channel Provider Event->>Handler: Trigger notification event Handler->>Config: Fetch notification settings Config-->>Handler: Return active configurations alt Configuration exists and enabled Handler->>Handler: Build recipient list Handler->>Handler: Apply filters and rules Handler->>Queue: Queue notifications loop For each notification Queue->>Delivery: Process notification Delivery->>Channel: Send via channel alt Delivery successful Channel-->>Delivery: Success response Delivery->>Delivery: Update status else Delivery failed Channel-->>Delivery: Error response Delivery->>Queue: Retry with backoff end end else No configuration or disabled Handler->>Handler: Log and skip end
17. Troubleshooting Guide
17.1 Common Issues and Solutions
17.1.1 Notifications Not Being Delivered
Symptoms: Configured notifications are not reaching recipients
Possible Causes & Solutions:
- Check notification status: Ensure the notification is enabled in settings
- Verify recipient configuration: Confirm roles/users are correctly set
- Channel availability: Verify the channel (email/WhatsApp) is configured
- Permission issues: Check if users have proper permissions
// Debug notification delivery
const debugNotificationDelivery = async (notificationId) => {
const settings = await service.getNotificationSettings(notificationId);
console.log('Notification enabled:', settings.enabled);
console.log('Recipients:', settings.recipients);
console.log('Channels:', settings.channels);
// Check user permissions
const permissions = await service.getUserPermissions();
console.log('User permissions:', permissions);
};17.1.2 Performance Issues
Symptoms: Slow loading of notification settings page
Solutions:
- Implement pagination for large notification lists
- Use React.memo for component optimization
- Enable caching for role and user data
17.1.3 WhatsApp Integration Failures
Symptoms: WhatsApp notifications failing
Checklist:
- Verify WhatsApp Business API credentials
- Check template approval status
- Ensure phone numbers are in correct format
- Monitor API rate limits
17.2 Debugging Tools
// Enable debug mode for notification module
if (process.env.NODE_ENV === 'development') {
window.__NOTIFICATION_DEBUG__ = {
logStateChanges: true,
logAPIRequests: true,
mockDelivery: false
};
}
// Redux DevTools integration
const notificationMiddleware = store => next => action => {
if (action.type.includes('NOTIFICATION') && window.__NOTIFICATION_DEBUG__) {
console.group(`Notification Action: ${action.type}`);
console.log('Payload:', action.payload);
console.log('State before:', store.getState().settingsPage.settingsNotification);
const result = next(action);
console.log('State after:', store.getState().settingsPage.settingsNotification);
console.groupEnd();
return result;
}
return next(action);
};18. Summary
The Notification Module represents a sophisticated, enterprise-grade notification management system within the Audit Admin application. Key achievements of this implementation include:
18.1 Technical Excellence
- Modular Architecture: Clean separation of concerns with reusable components
- State Management: Efficient Redux-Saga implementation with proper action/reducer patterns
- Type Safety: Comprehensive TypeScript integration ensuring code reliability
- Performance: Optimized rendering with memoization and lazy loading
18.2 Feature Completeness
- Multi-Channel Support: Email, WhatsApp, and Push notifications
- Flexible Configuration: Granular control over notification triggers and recipients
- Role-Based Management: Sophisticated role hierarchy support
- Internationalization: Full i18n support for global deployments
18.3 Developer Experience
- Comprehensive Documentation: 47,000+ characters of detailed technical documentation
- Clear Code Organization: Intuitive file structure and naming conventions
- Debugging Support: Built-in debugging tools and error handling
- Testing Infrastructure: Unit and integration test examples
18.4 Business Value
- Improved Communication: Ensures stakeholders receive timely updates
- Compliance Support: Audit trails and unsubscribe mechanisms
- Scalability: Architecture supports growth and new notification types
- Maintenance Efficiency: Clear documentation reduces onboarding time
19. Conclusion
The Notification Module is a critical component of the Audit Admin system, providing comprehensive notification management capabilities across multiple channels. Its modular architecture, flexible configuration options, and robust security features make it a scalable solution for enterprise notification needs. The clear separation of concerns, comprehensive state management, and well-defined integration points ensure maintainability and extensibility.
This documentation serves as a comprehensive guide for developers working with the notification module, providing insights into its architecture, implementation details, and best practices for extending its functionality. The module exemplifies modern React development practices, incorporating industry-standard patterns and tools to deliver a reliable, performant, and user-friendly notification management system.
For additional support or to contribute to the notification module, please refer to the GitHub repository or contact the development team.