Re_Backend/src/emailtemplates/EMAIL_STRATEGY.md

7.0 KiB

Email Notification Strategy - Quick Reference

🎯 9 Email Scenarios (Priority Order)

CRITICAL (Always Send if Admin Enabled)

  1. TAT Breached (100%) → Approver + Management
  2. Request Rejected → Initiator

HIGH PRIORITY (Check Preferences)

  1. Request Created → Initiator
  2. Approval Request → Approver (action required)
  3. Request Approved → Initiator
  4. TAT Reminder (75%) → Approver
  5. Workflow Resumed → Approver + Initiator

MEDIUM PRIORITY (Check Preferences)

  1. TAT Reminder (50%) → Approver

LOW PRIORITY (Check Preferences)

  1. Request Closed → All Participants

🔐 Preference Control Flow

Before Sending ANY Email:

import { shouldSendEmail, EmailNotificationType } from '@/emailtemplates/emailPreferences.helper';

// Check preferences
const canSendEmail = await shouldSendEmail(
  userId,
  EmailNotificationType.APPROVAL_REQUEST
);

if (!canSendEmail) {
  logger.info(`Email skipped for user ${userId} due to preferences`);
  return; // Don't send email
}

// Proceed with email
await emailService.sendEmail(...);

Preference Logic:

Admin Enabled? ──NO──> ❌ Stop (Don't send)
      │
     YES
      │
      ▼
User Enabled? ──NO──> ❌ Stop (Don't send)
      │
     YES
      │
      ▼
   ✅ Send Email

Critical Email Override:

// For CRITICAL emails (Rejection, TAT Breach)
const canSend = await shouldSendEmailWithOverride(
  userId,
  EmailNotificationType.REQUEST_REJECTED
);
// This checks admin only, ignores user preference

📊 TAT Email Schedule (3 Reminders)

TAT Progress Template Priority Subject When
50% TATReminder Medium TAT Reminder - Early Warning Half TAT elapsed
75% TATReminder High TAT Reminder - Action Needed 3/4 TAT elapsed
100% TATBreached Critical TAT BREACHED - Urgent Deadline passed

TAT Reminder Template Customization:

// 50% Reminder
await emailNotificationService.sendTATReminder(
  workflow,
  approver,
  {
    threshold: 50,
    timeRemaining: '12 hours',
    urgency: 'early-warning'
  }
);

// 75% Reminder
await emailNotificationService.sendTATReminder(
  workflow,
  approver,
  {
    threshold: 75,
    timeRemaining: '6 hours',
    urgency: 'urgent'
  }
);

// 100% Breach
await emailNotificationService.sendTATBreached(
  workflow,
  approver,
  {
    timeOverdue: '2 hours overdue',
    notifyManagement: true
  }
);

🚫 Never Send Email For:

In-App Only (Real-Time Collaboration):

Notification Type Why In-App Only Frequency
@Mentions Real-time chat High (50-200/day)
Comments Active discussion High (100-300/day)
Documents Added Minor update Medium (20-50/day)
Status Changes Internal updates Medium (30-80/day)
AI Generated Background process Low (10-20/day)
Summary Generated Automatic Low (10-20/day)

Reason: These would flood inboxes and cause email fatigue!


💾 Important: Activity Logs

ALWAYS Capture Activities:

// Even if email/notification disabled, ALWAYS log activity
await activityService.log({
  requestId,
  type: 'approval',
  user: { userId, name },
  timestamp: new Date().toISOString(),
  action: 'Request approved',
  details: 'Approved by John Doe'
});

// This is independent of email/notification preferences
// Activity logs are for audit trail and compliance

Activities Logged Regardless of Preferences:

  • Request created
  • Assignments
  • Approvals
  • Rejections
  • TAT events (50%, 75%, 100%)
  • Pauses/Resumes
  • Comments
  • Documents
  • Status changes

🔧 Implementation Checklist

Before Starting:

  • Create emailPreferences.helper.ts Done
  • Add system config entries for email controls
  • Update user preferences schema
  • Test preference checking logic

For Each Email Type:

  1. Check admin preference
  2. Check user preference
  3. Send email only if both enabled
  4. Log activity regardless
  5. Handle errors gracefully
  6. Track metrics (sent/failed/skipped)

Critical Emails (Special Handling):

  • Request Rejected - Override user preference
  • TAT Breached - Override user preference
  • Still respect admin disable

📋 User Preference UI (Frontend)

Admin Settings Page:

Email Notifications (Global Control)
├── [✓] Enable Email Notifications
│
├── Request Lifecycle
│   ├── [✓] Request Created
│   ├── [✓] Approval Requests
│   ├── [✓] Request Approved
│   └── [✓] Request Rejected (Critical - Recommended)
│
├── TAT Alerts
│   ├── [✓] TAT 50% Reminder
│   ├── [✓] TAT 75% Reminder
│   └── [✓] TAT Breached (Critical - Recommended)
│
└── Workflow Control
    ├── [✓] Workflow Resumed
    └── [✓] Request Closed

User Preferences Page:

My Email Preferences
├── [✓] Receive Email Notifications
│
├── Request Updates
│   ├── [✓] When my request is created
│   ├── [✓] When assigned to approve
│   ├── [✓] When my request is approved
│   ├── [⚠] When my request is rejected (Cannot disable - Critical)
│
├── TAT Alerts
│   ├── [✓] TAT 50% reminder
│   ├── [✓] TAT 75% reminder
│   └── [⚠] TAT breached (Cannot disable - Critical)
│
└── Other
    ├── [✓] Workflow resumed
    └── [ ] Request closed (Optional)

Note: Critical emails cannot be disabled by users!


📊 Email Volume with Preferences

Without Preferences (All Emails):

  • ~75-205 emails/day

With Smart Defaults:

  • Users who want all: ~75-205 emails/day
  • Users who opt for critical only: ~10-20 emails/day
  • Average user: ~30-50 emails/day

Email Savings:

  • @Mentions: 50-200/day saved
  • Comments: 100-300/day saved
  • Documents: 20-50/day saved
  • Status changes: 30-80/day saved

Total saved: 200-630 potential emails/day!


Summary

Email Strategy:

  1. 9 email scenarios (high-impact only)
  2. TAT reminders at 50%, 75%, 100%
  3. Admin-level control (can disable globally)
  4. User-level control (individual preferences)
  5. Critical override (rejection, breach always sent)
  6. Activity logs always captured
  7. In-app only for collaboration (@mentions, comments)

Implementation Order:

  1. Phase 0: Preference system ← START HERE
  2. Phase 1: Email service
  3. Phase 2: Critical emails (rejection, breach)
  4. Phase 3: High priority emails
  5. Phase 4: Medium/low priority emails
  6. Phase 5: User preference UI

Ready to implement Phase 0 (Preference System)? 🚀