Skip to content

Notification System OverviewΒΆ

The CyferWall Engage Backend features a powerful, template-driven notification system designed for reliability, ease of use, and comprehensive coverage of customer communication needs.

🎯 Key Features¢

⚑ Ultra-Simple API¢

// Send notification in one line
await notifications.email('case-received-customer', 'user@example.com', { caseNumber: 'CW-2025-001' })

🎨 Template-Driven¢

  • Handlebars templates with rich formatting
  • Automatic variable validation
  • Category-based organization
  • Easy testing and preview

πŸ”„ Multi-Channel SupportΒΆ

  • Email notifications (primary channel)
  • SMS notifications (urgent cases)
  • Webhook notifications (external integrations)
  • Extensible architecture for additional channels

πŸ›‘οΈ Robust Error HandlingΒΆ

  • Graceful failure with detailed error messages
  • Consistent response format across all methods
  • Comprehensive logging for debugging
  • Automatic retries (configurable)

πŸ—οΈ ArchitectureΒΆ

graph TB
    A[Application Code] --> B[Ultra-Simple API]
    B --> C[Notification Service]
    C --> D[Template Manager]
    D --> E[Template Files]

    C --> F[Email Provider]
    C --> G[SMS Provider] 
    C --> H[Webhook Service]

    I[Handlebars Engine] --> D
    J[Variable Validation] --> D
    K[Error Handling] --> C

    subgraph "Template Categories"
        E1[Customer Templates]
        E2[Internal Templates] 
        E3[Support Templates]
        E4[Operations Templates]
    end

    E --> E1
    E --> E2
    E --> E3
    E --> E4

πŸ“‚ Template OrganizationΒΆ

Templates are organized by audience and purpose:

templates/notifications/
β”œβ”€β”€ customer/          # Customer-facing notifications
β”‚   β”œβ”€β”€ case-received-customer.template.json
β”‚   β”œβ”€β”€ case-updated-customer.template.json
β”‚   └── case-escalated-customer.template.json
β”œβ”€β”€ internal/          # Internal staff notifications
β”‚   β”œβ”€β”€ case-assigned-staff.template.json
β”‚   β”œβ”€β”€ case-urgent-staff.template.json
β”‚   └── case-overdue-staff.template.json  
β”œβ”€β”€ support/           # Support team notifications
β”‚   β”œβ”€β”€ case-escalated-support.template.json
β”‚   └── case-priority-support.template.json
β”œβ”€β”€ operations/        # Operations team notifications
β”‚   β”œβ”€β”€ system-metrics-ops.template.json
β”‚   └── case-volume-ops.template.json
└── html/             # HTML template files
    β”œβ”€β”€ case-received-customer.html
    β”œβ”€β”€ case-updated-customer.html
    └── ...

πŸš€ Quick Start ExamplesΒΆ

Basic Email NotificationΒΆ

import { notifications } from '@/util/notifications/ultra-simple'

// Send customer notification
const result = await notifications.email(
  'case-received-customer',
  'john@example.com',
  {
    caseNumber: 'CW-2025-001',
    customerName: 'John Doe',
    issueType: 'Technical Support',
    urgency: 'HIGH'
  }
)

if (result.success) {
  console.log('βœ… Notification sent successfully')
} else {
  console.error('❌ Failed to send notification:', result.error)
}

Multi-Channel NotificationΒΆ

// Send both email and SMS for urgent cases
const sendUrgentNotification = async (case, customer) => {
  // Send detailed email
  const emailResult = await notifications.email(
    'case-urgent-customer', 
    customer.email, 
    {
      caseNumber: case.caseNumber,
      customerName: customer.name,
      urgency: case.urgency,
      escalationTime: '4 hours'
    }
  )

  // Send brief SMS
  const smsResult = await notifications.sms(
    customer.phone,
    `URGENT: Your case ${case.caseNumber} requires immediate attention. Check your email for details.`
  )

  // Send webhook to external monitoring
  const webhookResult = await notifications.webhook(
    'https://monitoring.example.com/urgent-case',
    {
      event: 'urgent_case_created',
      caseNumber: case.caseNumber,
      timestamp: new Date().toISOString()
    }
  )

  return { emailResult, smsResult, webhookResult }
}

Notification in Support ControllerΒΆ

import { notifications } from '@/util/notifications/ultra-simple'

export const escalateCaseController = async (req, res) => {
  try {
    // Update case in database
    const updatedCase = await db.supportCase.update({
      where: { caseNumber: req.body.caseNumber },
      data: { 
        urgency: req.body.newUrgency,
        escalatedAt: new Date()
      }
    })

    // Notify customer about escalation
    await notifications.email('case-escalated-customer', updatedCase.email, {
      caseNumber: updatedCase.caseNumber,
      customerName: updatedCase.name,
      originalUrgency: req.body.originalUrgency,
      newUrgency: req.body.newUrgency,
      escalationReason: req.body.reason
    })

    // Alert support team
    await notifications.email('case-escalated-support', 'support@cyferwall.com', {
      caseNumber: updatedCase.caseNumber,
      customerName: updatedCase.name,
      newUrgency: req.body.newUrgency,
      escalationReason: req.body.reason,
      requiresImmediateAttention: req.body.newUrgency === 'CRITICAL'
    })

    res.json({ success: true, message: 'Case escalated successfully' })
  } catch (error) {
    res.status(500).json({ error: error.message })
  }
}

πŸ§ͺ Testing TemplatesΒΆ

The system includes comprehensive testing capabilities:

Test Individual TemplatesΒΆ

// Test template rendering
const test = await notifications.test('case-received-customer', {
  caseNumber: 'CW-TEST-001',
  customerName: 'Test User',
  issueType: 'TECHNICAL',
  urgency: 'MEDIUM'
})

console.log('Subject:', test.data.subject)
console.log('Content preview:', test.data.content.substring(0, 200))

Template InformationΒΆ

// Get template requirements
const info = notifications.info('case-escalated-customer')
console.log('Required variables:', info.data.required)
console.log('Optional variables:', info.data.optional)

Available TemplatesΒΆ

// List all available templates
const templates = notifications.templates()
templates.forEach(template => {
  console.log(`${template.category}/${template.id}: ${template.name}`)
})

πŸ”§ ConfigurationΒΆ

Environment VariablesΒΆ

# Email Provider (choose one)
RESEND_API_KEY="your_resend_key"
SENDGRID_API_KEY="your_sendgrid_key"

# SMS Provider (choose one)  
TWILIO_SID="your_twilio_sid"
TWILIO_TOKEN="your_twilio_token"

# Notification Settings
NOTIFICATION_FROM_EMAIL="noreply@cyferwall.com"
NOTIFICATION_FROM_NAME="CyferWall Support"
NOTIFICATION_RETRY_ATTEMPTS="3"
NOTIFICATION_TIMEOUT_MS="5000"

Service InitializationΒΆ

import { notifications } from '@/util/notifications/ultra-simple'

// Check if service is ready
if (notifications.isReady()) {
  console.log('βœ… Notification service initialized')
} else {
  console.error('❌ Notification service failed to initialize')
}

🎨 Template Features¢

Handlebars HelpersΒΆ

Custom helpers for common formatting needs:

{{!-- Date formatting --}}
Case created: {{now "YYYY-MM-DD HH:mm"}}
Days since creation: {{daysSince createdAt}}
Estimated resolution: {{daysUntil estimatedResolution}} days

{{!-- Conditional content --}}
{{#if (eq urgency "CRITICAL")}}
⚠️ This is a critical case requiring immediate attention.
{{/if}}

{{!-- Case-specific formatting --}}
Priority Score: {{priorityScore}}
{{#if assignedStaff}}
Assigned to: {{assignedStaff.name}}
{{else}}
Status: Awaiting assignment
{{/if}}

Variable ValidationΒΆ

Templates automatically validate required variables:

{
  "variables": [
    { "name": "caseNumber", "type": "string", "required": true },
    { "name": "customerName", "type": "string", "required": true },
    { "name": "urgency", "type": "enum", "required": true, "values": ["LOW", "MEDIUM", "HIGH", "CRITICAL"] },
    { "name": "estimatedResolution", "type": "string", "required": false }
  ]
}

πŸ“Š Monitoring & LoggingΒΆ

Built-in LoggingΒΆ

All notification attempts are automatically logged:

πŸ“§ Email sent - Template: case-received-customer, To: user@example.com, Subject: Case CW-2025-001 Received
πŸ“± SMS sent - To: +1234567890, Message: Your case has been updated...
πŸ”— Webhook sent - URL: https://external-api.com/webhook, Data keys: event, caseNumber, timestamp

Error TrackingΒΆ

Failed notifications are logged with detailed error information:

❌ Email failed: Template not found: invalid-template-id
❌ SMS failed: Invalid phone number format: +invalid
❌ Webhook failed: Connection timeout to https://unreachable-api.com

Performance MonitoringΒΆ

Track notification performance in your monitoring system:

const start = Date.now()
const result = await notifications.email(templateId, email, data)
const duration = Date.now() - start

// Log to your monitoring system
metrics.timing('notification.email.duration', duration)
metrics.increment(result.success ? 'notification.email.success' : 'notification.email.failure')

πŸ”’ Security ConsiderationsΒΆ

Email SecurityΒΆ

  • SPF/DKIM/DMARC records properly configured
  • Rate limiting to prevent abuse
  • Input sanitization in templates
  • No sensitive data in template variables

Template SecurityΒΆ

  • Handlebars escaping enabled by default
  • Variable validation prevents injection
  • Template isolation prevents cross-template access
  • Read-only template files in production

πŸš€ Next StepsΒΆ

  1. Quick Start Guide - Send your first notification in 5 minutes
  2. Template Management - Learn about template structure and creation
  3. Integration Guide - Integrate notifications throughout your application
  4. API Reference - Complete API documentation

Ready to start sending notifications? Quick Start Guide β†’