Skip to content

Notifications Module

Overview

The Notifications Module handles all outbound communications from the IWM Platform to users. It manages multiple delivery channels (email, SMS, push, in-app), user preferences, template rendering, delivery tracking, and retry logic. The module consumes domain events from other modules and translates them into appropriate notifications.

Responsibilities

  • Multi-channel notification delivery (email, SMS, push, in-app)
  • User notification preferences management
  • Dynamic template rendering
  • Delivery tracking and retry logic
  • Event-driven notification triggering
  • Rate limiting and throttling
  • Notification history and audit

Architecture Overview


Notification Channels

Email (SendGrid)

Primary channel for transactional and marketing communications.

ConfigurationValue
ProviderSendGrid
From AddressConfigurable per notification type
Rate Limit100 emails/second
Retry Attempts3
Retry DelayExponential backoff

Supported Features:

  • HTML and plain text templates
  • Dynamic content personalization
  • Attachments (PDFs, images)
  • Click and open tracking
  • Unsubscribe links

SMS (Twilio)

For time-sensitive notifications and 2FA.

ConfigurationValue
ProviderTwilio
Sender IDConfigurable
Rate Limit10 SMS/second
Retry Attempts2
Max Length160 characters (or concatenated)

Supported Features:

  • Domestic and international delivery
  • Delivery receipts
  • 2FA codes
  • Short URLs for links

Push Notifications (Firebase FCM)

Mobile and web push notifications.

ConfigurationValue
ProviderFirebase Cloud Messaging
PlatformsiOS, Android, Web
TTL4 weeks
PriorityHigh/Normal

Supported Features:

  • Rich notifications (images, actions)
  • Topic-based broadcasting
  • Device token management
  • Silent notifications

In-App Notifications

Real-time notifications within the platform.

ConfigurationValue
DeliveryWebSocket
StorageDatabase
Retention90 days

Supported Features:

  • Real-time delivery
  • Read/unread status
  • Action buttons
  • Notification center UI

Event Triggers

What Events Trigger Which Notifications

Event-to-Notification Mapping

EventNotification TypeChannelsPriority
UserRegisteredwelcome_emailEmailNormal
UserVerifiedaccount_activatedEmail, In-AppNormal
PasswordResetRequestedpassword_resetEmailHigh
TwoFactorEnabledsecurity_alertEmail, SMSHigh
LoginFromNewDevicesecurity_alertEmail, PushHigh
KycApprovedkyc_approvedEmail, In-AppNormal
KycRejectedkyc_rejectedEmail, In-AppNormal
PartnerRegisteredpartner_welcomeEmailNormal
NewReferralnew_referralEmail, Push, In-AppNormal
CommissionCalculatedcommission_pendingIn-AppLow
CommissionPaidcommission_paidEmail, In-AppNormal
PayoutRequestedpayout_requestedEmailNormal
PayoutCompletedpayout_completedEmail, SMS, In-AppHigh
PayoutRejectedpayout_rejectedEmail, In-AppHigh
RankChangedrank_changeEmail, Push, In-AppNormal
OrderCreatedorder_confirmationEmailHigh
OrderConfirmedorder_confirmedEmail, In-AppNormal
OrderShippedorder_shippedEmail, SMS, PushHigh
OrderDeliveredorder_deliveredEmail, PushNormal
PaymentFailedpayment_failedEmail, SMSHigh
RefundCompletedrefund_completedEmail, In-AppNormal
ParticipationActivatedinvestment_activatedEmail, In-AppHigh
ReturnsDistributedreturns_creditedEmail, In-AppNormal
InvestmentMaturedinvestment_maturedEmail, Push, In-AppHigh
CartAbandonedcart_abandonedEmailLow

User Preferences

Preference Structure

Users can configure preferences per notification type and channel:

json
{
  "user_id": "uuid",
  "preferences": {
    "order_confirmation": {
      "email": true,
      "sms": false,
      "push": true,
      "in_app": true
    },
    "commission_paid": {
      "email": true,
      "sms": false,
      "push": true,
      "in_app": true
    },
    "marketing": {
      "email": false,
      "sms": false,
      "push": false,
      "in_app": false
    }
  },
  "global_settings": {
    "quiet_hours": {
      "enabled": true,
      "start": "22:00",
      "end": "08:00",
      "timezone": "Europe/Moscow"
    },
    "language": "ru",
    "email_frequency": "immediate"
  }
}

Preference Categories

CategoryNotificationsCan Disable
Security2FA, password reset, security alertsNo
TransactionalOrders, payments, investmentsNo (but can choose channels)
AccountKYC, profile updatesNo (but can choose channels)
MLMCommissions, payouts, ranksYes
MarketingPromotions, newslettersYes

Preference Management Flow


Template System

Template Structure

Templates are defined with variables for dynamic content:

templates/
├── email/
│   ├── welcome_email/
│   │   ├── subject.txt
│   │   ├── body.html
│   │   └── body.txt
│   ├── order_confirmation/
│   │   ├── subject.txt
│   │   ├── body.html
│   │   └── body.txt
│   └── ...
├── sms/
│   ├── 2fa_code.txt
│   ├── order_shipped.txt
│   └── ...
├── push/
│   ├── new_referral.json
│   ├── commission_paid.json
│   └── ...
└── in_app/
    ├── commission_pending.json
    └── ...

Template Variables

Common variables available in all templates:

VariableDescription
user.firstNameUser's first name
user.lastNameUser's last name
user.emailUser's email
platform.namePlatform name
platform.supportEmailSupport email
platform.baseUrlPlatform URL

Note: Template variables use double curly braces syntax in templates.

Example Templates

Email Template (order_confirmation/body.html):

html
<!DOCTYPE html>
<html>
<head>
    <title>Order Confirmation</title>
</head>
<body>
    <h1>Thank you for your order, {{user.firstName}}!</h1>

    <p>Your order <strong>#{{order.number}}</strong> has been received.</p>

    <h2>Order Details</h2>
    <table>
        {{#each order.items}}
        <tr>
            <td>{{this.name}}</td>
            <td>x{{this.quantity}}</td>
            <td>{{this.price}} {{../order.currency}}</td>
        </tr>
        {{/each}}
    </table>

    <p><strong>Total: {{order.total}} {{order.currency}}</strong></p>

    <p>
        <a href="{{platform.baseUrl}}/orders/{{order.id}}">
            View Order
        </a>
    </p>
</body>
</html>

SMS Template (order_shipped.txt):

Your order #{{order.number}} has been shipped!
Tracking: {{shipment.trackingNumber}}
Track: {{shipment.trackingUrl}}

Push Template (commission_paid.json):

json
{
  "title": "Commission Received!",
  "body": "You earned {{commission.amount}} {{commission.currency}} from {{commission.source}}",
  "icon": "commission_icon",
  "action_url": "/mlm/commissions/{{commission.id}}",
  "data": {
    "type": "commission_paid",
    "commission_id": "{{commission.id}}"
  }
}

Template Rendering Flow


Delivery Tracking

Delivery Status Flow

Notification Log Entry

FieldTypeDescription
idUUIDLog entry ID
user_idUUIDTarget user
notification_typeVARCHARType identifier
channelENUMEMAIL, SMS, PUSH, IN_APP
statusENUMDelivery status
provider_referenceVARCHARExternal message ID
sent_atTIMESTAMPSend timestamp
delivered_atTIMESTAMPDelivery confirmation
failed_atTIMESTAMPFailure timestamp
failure_reasonTEXTError details
retry_countINTRetry attempts
payloadJSONBRendered content

Retry Logic

Retry Schedule:

AttemptDelay
1st retry1 minute
2nd retry5 minutes
3rd retry15 minutes
After 3rdMarked as failed

Notification Types by Module

Authentication Notifications

TypeDescriptionChannels
welcome_emailNew user registrationEmail
email_verificationEmail verification linkEmail
password_resetPassword reset linkEmail
password_changedPassword change confirmationEmail
2fa_codeTwo-factor codeSMS, Email
2fa_enabled2FA activation confirmationEmail
2fa_disabled2FA deactivation alertEmail
login_new_deviceLogin from new deviceEmail, Push
account_lockedAccount locked alertEmail
account_unlockedAccount unlockedEmail

KYC Notifications

TypeDescriptionChannels
kyc_submittedKYC submission confirmationEmail, In-App
kyc_under_reviewKYC being reviewedEmail, In-App
kyc_approvedKYC approvedEmail, In-App
kyc_rejectedKYC rejected with reasonEmail, In-App
kyc_needs_infoAdditional info requestedEmail, In-App
kyc_expiringKYC expiration warningEmail

Order Notifications

TypeDescriptionChannels
order_confirmationOrder placedEmail
order_confirmedPayment confirmedEmail, In-App
order_processingOrder being preparedIn-App
order_shippedOrder shipped with trackingEmail, SMS, Push
order_out_for_deliveryOut for deliveryPush
order_deliveredOrder deliveredEmail, Push
order_cancelledOrder cancelledEmail, In-App
payment_failedPayment failedEmail, SMS
payment_retryPayment retry reminderEmail
refund_initiatedRefund startedEmail, In-App
refund_completedRefund processedEmail, In-App

MLM Commission Notifications

TypeDescriptionChannels
commission_pendingCommission calculatedIn-App
commission_approvedCommission approvedEmail, In-App
commission_paidCommission creditedEmail, Push, In-App
commission_reversedCommission reversedEmail, In-App
weekly_earningsWeekly earnings summaryEmail
monthly_earningsMonthly earnings reportEmail

MLM Payout Notifications

TypeDescriptionChannels
payout_requestedPayout request submittedEmail
payout_approvedPayout approvedEmail, In-App
payout_processingPayout being processedIn-App
payout_completedPayout sentEmail, SMS, In-App
payout_rejectedPayout rejectedEmail, In-App

MLM Rank Notifications

TypeDescriptionChannels
rank_promotionRank promotedEmail, Push, In-App
rank_demotion_warningDemotion warningEmail, In-App
rank_demotedRank demotedEmail, In-App
rank_qualification_progressProgress updateIn-App

MLM Referral Notifications

TypeDescriptionChannels
new_referralNew referral signupEmail, Push, In-App
referral_activatedReferral made first purchasePush, In-App
team_member_achievementTeam member milestoneIn-App

Investment Notifications

TypeDescriptionChannels
investment_submittedParticipation submittedEmail
investment_approvedInvestment approvedEmail, In-App
investment_activatedInvestment activeEmail, Push, In-App
investment_rejectedInvestment rejectedEmail, In-App
returns_distributedReturns creditedEmail, In-App
investment_maturedInvestment maturedEmail, Push, In-App
withdrawal_requestedWithdrawal submittedEmail
withdrawal_completedWithdrawal processedEmail, SMS, In-App
portfolio_updateMonthly portfolio summaryEmail

Rate Limiting and Throttling

Rate Limits by Channel

ChannelUser LimitGlobal Limit
Email20/hour100/second
SMS5/hour10/second
Push50/hour1000/second
In-AppUnlimitedN/A

Quiet Hours

Users can configure quiet hours:

  • Notifications queued during quiet hours
  • Delivered when quiet hours end
  • Security notifications bypass quiet hours

Notification Batching

Low-priority notifications can be batched:

  • Commission pending notifications
  • In-app activity updates
  • Marketing communications

Business Rules and Invariants

Delivery Rules

  1. Security notifications cannot be disabled
  2. User must have verified channel to receive notifications
  3. Failed deliveries retry up to 3 times
  4. Quiet hours respected except for security alerts
  5. Rate limits enforced per user and globally

Preference Rules

  1. New users get all notifications enabled by default
  2. Marketing defaults to disabled (opt-in)
  3. At least one channel must be enabled for transactional
  4. Preferences stored per notification type

Template Rules

  1. All templates must have fallback locale
  2. Variables must be sanitized before rendering
  3. URLs must be absolute and use HTTPS
  4. Sensitive data not logged in delivery logs

Integration Points

Consumes from Other Modules

EventSourceNotification Type
UserRegisteredCorewelcome_email
UserVerifiedCoreaccount_activated
PasswordResetRequestedCorepassword_reset
TwoFactorEnabledCore2fa_enabled
KycStatusChangedCorekyc_*
OrderCreatedCommerceorder_confirmation
OrderShippedCommerceorder_shipped
PaymentReceivedCommerceorder_confirmed
PaymentFailedCommercepayment_failed
CommissionPaidMLMcommission_paid
PayoutCompletedMLMpayout_completed
RankChangedMLMrank_*
NewReferralMLMnew_referral
ParticipationActivatedInvestmentinvestment_activated
ReturnsDistributedInvestmentreturns_distributed
InvestmentMaturedInvestmentinvestment_matured

Provides to Other Modules

InterfacePurpose
INotificationServiceSend ad-hoc notifications
IPreferenceServiceCheck/update user preferences