Skip to content

Notification Module ​

Overview ​

The Notification Module (src/modules/notify/) provides a template-based, multi-channel notification system. It supports:

  • Email (SMTP, AWS SES, Sendmail, Infobip)
  • In-app notifications
  • Mattermost (webhook)

Notifications are defined as templates with per-provider, per-locale contents. A layout wraps email content in a shared HTML shell. Logs track every send attempt.

Each delivery target is a configured provider instance (odp_notify_providers): a channel (email / mattermost / inapp) plus, for email, a transport type (smtp / ses / sendmail / infobip) and its credentials. Providers can receive delivery reports through a public webhook, recorded as append-only delivery events.

Architecture ​

Access ​

Notify routes are not admin-only. Every route except POST /notify/webhooks/:key checks three things:

  1. App session. The caller must have app access (requireAppAccess).
  2. App action. When app permissions are enabled (ENABLE_APP_PERMISSIONS), the caller must hold the matching action of the notify app module: view to read, manage to change configuration, trigger for POST /notify/trigger, test for POST /notify/test-send.
  3. Collection permissions. The notify services run under the caller's accountability. The permissions on the odp_notify_* collections (action, fields, row filter) decide which rows the caller reads or writes, the same as on /items.

Some routes check more:

  • GET /notify/channels needs read on odp_notify_providers.
  • POST /notify/test-send needs update on the provider row it sends through.
  • Creating a provider with is_primary promotes it in the same transaction. If the promotion is refused, no row is created.
  • A bounded session (sub-token) cannot write configuration.

An admin keeps full access. Delivery reads templates and providers through an internal path, so a notification still sends when the user who triggered it cannot read the templates.

Provider and settings credentials (provider config, webhook_secret, the legacy secret columns of odp_notify_settings) come back masked. They cannot be used in filter, sort, aggregate, groupBy, alias or deep (400), are never scanned by search, and are never selected through a relation. This applies to every caller, admin included.

Data Model ​

odp_notify_settings (singleton) ​

ColumnTypeDescription
idintegerAlways 1
email_transportvarcharsmtp, ses, sendmail
smtp_hostvarcharSMTP server hostname
smtp_portintegerSMTP port
smtp_uservarcharSMTP username
smtp_passvarcharSMTP password
smtp_securebooleanUse TLS
ses_regionvarcharAWS SES region
ses_access_keyvarcharAWS access key
ses_secret_keyvarcharAWS secret key
email_fromvarcharSender email address
admin_emailsjsonAdmin email list for cc_admin
mattermost_urlvarcharMattermost server URL
mattermost_tokenvarcharMattermost bot token
default_localevarcharDefault language (e.g., en)
default_channelsjsonDefault channels for all sends

odp_notify_providers ​

A configured provider instance. Introduced by migration 069-notify-provider-tables.ts, which also seeds initial rows from the odp_notify_settings singleton.

ColumnTypeDescription
idintegerPrimary key
namevarcharDisplay name (e.g., Email (smtp))
channelvarcharemail, mattermost, inapp
typevarcharEmail transport: smtp, ses, sendmail, infobip. null for mattermost/inapp
configjsonPer-type credentials/settings (SMTP host, SES region, Infobip base URL/API key, Mattermost URL/token, …)
is_primarybooleanPrimary provider for its channel (one per channel)
enabledbooleanWhether this provider is usable
webhook_enabledbooleanAccept delivery reports on the public webhook
webhook_secretvarcharSecret used to verify inbound webhook callbacks
created_attimestampCreation time
updated_attimestampLast update time

One primary provider per channel is enforced by a partial unique index on PostgreSQL and in the service layer on MySQL/SQLite.

odp_notify_delivery_events ​

Append-only trace of provider delivery reports (created via the public webhook). Migration 069-notify-provider-tables.ts.

ColumnTypeDescription
idintegerPrimary key
log_idintegerFK to odp_notify_logs.id (nullable, SET NULL)
provider_idintegerFK to odp_notify_providers.id (nullable, SET NULL)
provider_message_idvarcharProvider-side message id for correlation
eventvarchardelivered, bounced, rejected, deferred, opened, clicked, complaint, unsubscribed
provider_status_rawvarcharRaw provider status string
reasontextFailure/bounce reason
occurred_attimestampWhen the event happened (provider-reported)
received_attimestampWhen ODP ingested the event
provider_event_idvarcharIdempotency key (unique)
raw_payloadjsonRaw webhook payload

odp_notify_layouts ​

ColumnTypeDescription
idvarcharLayout ID (e.g., default, minimal)
namevarcharDisplay name
descriptionvarcharDescription
contenttextHTML with {{{content}}} placeholder
variables_schemajsonJSON schema for layout variables

odp_notify_templates ​

ColumnTypeDescription
idvarcharTemplate ID (e.g., welcome_email)
namevarcharDisplay name
channelsjsonArray of channel IDs
cc_adminbooleanCC admin emails on send
variables_schemajsonJSON schema for template variables
layout_idvarcharFK to odp_notify_layouts.id
statusvarcharpublished, draft, archived

odp_notify_template_contents ​

ColumnTypeDescription
idintegerPrimary key
template_idvarcharFK to odp_notify_templates.id
provider_idintegerFK to odp_notify_providers.id — the delivery provider for this content
providervarcharDEPRECATED — legacy channel value (e.g., email, inapp), kept until a later cleanup migration; use provider_id
localevarcharLanguage code (e.g., en, vi)
subjectvarcharSubject line (for email)
contenttextContent body (Handlebars template)
metadatajsonProvider-specific metadata
activebooleanIs this content active

odp_notify_logs ​

ColumnTypeDescription
idintegerPrimary key
statusvarcharpending, sending, sent, delivered, bounced, rejected, failed, cancelled
template_idvarcharFK to template (nullable for direct sends)
channelvarcharProvider channel used
provider_idintegerFK to odp_notify_providers.id (nullable, SET NULL)
provider_message_idvarcharProvider-side message id (for delivery-webhook correlation)
recipientsjsonArray of recipient addresses
ccjsonCC recipients
bccjsonBCC recipients
localevarcharLanguage used
variablesjsonVariables passed at trigger time
subject_renderedvarcharFinal rendered subject
content_renderedtextFinal rendered content
scheduled_attimestampWhen to send (null = immediate)
sent_attimestampAccepted/handed-off time
delivered_attimestampConfirmed-at-recipient time (set from a delivery webhook)
error_messagetextError description on failure
provider_responsejsonRaw provider API response
metadatajsonArbitrary metadata stored with the log

Statuses beyond sent (delivered, bounced, rejected) are advanced by inbound provider delivery events (see odp_notify_delivery_events), correlated via provider_message_id.


Settings Endpoints ​

GET /notify/settings ​

Get notification settings (singleton).

Auth required: Yes

Response 200

json
{
  "data": {
    "id": 1,
    "email_transport": "smtp",
    "smtp_host": "smtp.example.com",
    "smtp_port": 587,
    "email_from": "no-reply@example.com",
    "default_locale": "en",
    "default_channels": ["email"]
  }
}

PATCH /notify/settings ​

Update notification settings.

Auth required: Yes

Request Body

json
{
  "email_transport": "smtp",
  "smtp_host": "smtp.example.com",
  "smtp_port": 587,
  "smtp_user": "user@example.com",
  "smtp_pass": "password",
  "smtp_secure": true,
  "email_from": "no-reply@example.com"
}

Channel Endpoints ​

GET /notify/channels ​

List the static channel handler catalog — the built-in transport capabilities (email / mattermost / inapp), not configured instances. This is the descriptor list that used to be returned by GET /notify/providers.

Auth required: Yes (app access; see Access)

Response 200

json
{
  "data": [
    {
      "id": "email",
      "name": "Email",
      "description": "Send via SMTP/SES",
      "icon": "email"
    },
    {
      "id": "inapp",
      "name": "In-App",
      "description": "In-application notifications",
      "icon": "notifications"
    },
    {
      "id": "mattermost",
      "name": "Mattermost",
      "description": "Send to Mattermost channels",
      "icon": "chat"
    }
  ]
}

Provider Endpoints ​

Providers are the configured instances stored in odp_notify_providers. Access: see Access.

GET /notify/providers ​

List configured provider rows. Supports the standard query system.

Auth required: Yes (app access; see Access)

Response 200

json
{
  "data": [
    {
      "id": 1,
      "name": "Email (smtp)",
      "channel": "email",
      "type": "smtp",
      "config": { "host": "smtp.example.com", "port": 587, "from": "no-reply@example.com" },
      "is_primary": true,
      "enabled": true,
      "webhook_enabled": false
    }
  ]
}

POST /notify/providers ​

Create a provider instance. If is_primary is true, it is promoted to primary for its channel.

Request Body

json
{
  "name": "Infobip",
  "channel": "email",
  "type": "infobip",
  "config": { "base_url": "https://xxxxx.api.infobip.com", "api_key": "…", "from": "no-reply@example.com" },
  "is_primary": true,
  "enabled": true
}

Response 200 — Returns the new provider ID.

GET /notify/providers/:id ​

Read a single provider row.

PATCH /notify/providers/:id ​

Update a provider. Setting is_primary: true promotes it; is_primary: false clears the primary flag for its channel.

PATCH /notify/providers/:id/primary ​

Promote this provider to primary for its channel (demotes any previous primary).

Response 200 — Returns the provider ID.

DELETE /notify/providers/:id ​

Delete a provider. Fails with 400 if it is still referenced by template contents (FK RESTRICT) — disable it or remove those contents first.

Response 204


Layout Endpoints ​

GET /notify/layouts ​

List all layouts.

POST /notify/layouts ​

Create a layout.

Request Body

json
{
  "id": "branded",
  "name": "Branded Layout",
  "description": "ODP branded email template",
  "content": "<html>...<div style=\"max-width:600px\">{{{content}}}</div>...</html>"
}

The content field must contain the {{{content}}} placeholder (triple braces = unescaped HTML).

GET /notify/layouts/:id ​

PATCH /notify/layouts/:id ​

DELETE /notify/layouts/:id ​


Template Endpoints ​

GET /notify/templates ​

List all templates.

POST /notify/templates ​

Create a template.

Request Body

json
{
  "id": "welcome_email",
  "name": "Welcome Email",
  "channels": ["email"],
  "cc_admin": false,
  "layout_id": "default",
  "status": "published",
  "variables_schema": {
    "type": "object",
    "properties": {
      "user_name": { "type": "string" },
      "login_url": { "type": "string" }
    }
  }
}

GET /notify/templates/:id ​

Read a template (includes contents array).

Response 200

json
{
  "data": {
    "id": "welcome_email",
    "name": "Welcome Email",
    "channels": ["email"],
    "status": "published",
    "contents": [
      {
        "id": 1,
        "provider_id": 1,
        "locale": "en",
        "subject": "Welcome to ODP, {{user_name}}!",
        "content": "<p>Hello {{user_name}},</p><p>Click <a href=\"{{login_url}}\">here</a> to log in.</p>",
        "active": true
      }
    ]
  }
}

PATCH /notify/templates/:id ​

DELETE /notify/templates/:id ​

System templates (created by the system) cannot be deleted — only their status can be changed to archived.


Template Content Endpoints ​

GET /notify/templates/:templateId/contents ​

List all content variants for a template.

POST /notify/templates/:templateId/contents ​

Add a new content variant. provider_id is required (FK to odp_notify_providers); locale defaults to default.

Request Body

json
{
  "provider_id": 1,
  "locale": "vi",
  "subject": "Chào mừng {{user_name}} đến với ODP!",
  "content": "<p>Xin chào {{user_name}},</p>",
  "active": true
}

The credential templates password_reset, user_invitation and email_verification only take contents on an outbound channel (email, sms): a provider that stores or posts what it sends (inapp → odp_notifications, mattermost) would publish the link, so such a content is refused with 400 here and on PATCH. One already stored (or a provider whose channel changed) is not delivered: no log is created for it at trigger time, and a pending log fails.

PATCH /notify/contents/:id ​

Update a content variant.

DELETE /notify/contents/:id ​

Delete a content variant.


Log Endpoints ​

GET /notify/logs ​

List notification delivery logs.

Supports standard query system.

GET /notify/logs/:id ​

Read a single log entry.

PATCH /notify/logs/:id/cancel ​

Cancel a pending notification (status must be pending).

Response 200 — Returns the log ID.

DELETE /notify/logs/:id ​

Delete a log entry.

GET /notify/logs/stats ​

Get aggregate statistics.

Response 200

json
{
  "data": {
    "total": 500,
    "sent": 480,
    "failed": 10,
    "pending": 5,
    "cancelled": 5
  }
}

Trigger Endpoint ​

POST /notify/trigger ​

Trigger a notification by template ID.

Auth required: Yes

Request Body

json
{
  "template_id": "welcome_email",
  "recipients": ["user@example.com"],
  "cc": ["manager@example.com"],
  "variables": {
    "user_name": "John Doe",
    "login_url": "https://app.example.com/login"
  },
  "locale": "en",
  "channels": ["email"],
  "scheduled_at": "2026-03-26T12:00:00.000Z"
}
FieldRequiredDescription
template_idYesTemplate to use
recipientsYesArray of recipient addresses (email/user IDs)
ccNoCC recipients
bccNoBCC recipients
variablesNoTemplate variable values
localeNoLanguage code (defaults to default_locale)
channelsNoOverride template's default channels
scheduled_atNoISO 8601 timestamp for delayed send
metadataNoArbitrary metadata stored in the log

Response 200

json
{
  "data": {
    "log_ids": [42, 43]
  }
}

One log entry is created per channel per send.


Test Send Endpoint ​

POST /notify/test-send ​

Send a test notification directly via a configured provider (bypasses templates).

Auth required: Yes (app access; see Access)

Request Body

json
{
  "provider_id": 1,
  "recipients": ["test@example.com"],
  "subject": "Test Notification",
  "content": "<p>This is a test.</p>",
  "metadata": {}
}
FieldRequiredDescription
provider_idYesID of the configured provider (odp_notify_providers) to send through
recipientsYesArray of recipient addresses
subjectNoSubject line (defaults to empty)
contentYesBody content
metadataNoProvider-specific metadata

Response 200

json
{
  "data": {
    "success": true,
    "message": "Email sent successfully"
  }
}

Template Validation Endpoint ​

POST /notify/validate-template ​

Validate a Handlebars template string for syntax errors.

Request Body

json
{
  "template": "Hello {{user_name}}, your code is {{code}}."
}

Response 200

json
{
  "data": {
    "valid": true,
    "errors": []
  }
}

Delivery Webhook Endpoint ​

POST /notify/webhooks/:key ​

Public callback endpoint for provider delivery reports (bounces, opens, clicks, …). No user auth — each request is verified per-adapter against the webhook_secret of enabled providers whose type or channel matches :key. A dedicated rate limit applies.

  • :key selects the webhook adapter (e.g. infobip). Unknown keys return 404.
  • Verified events are parsed by the adapter and appended to odp_notify_delivery_events, advancing the correlated odp_notify_logs status.
  • Verification failure returns 401.

Response 200

json
{ "ok": true }

Template Rendering ​

Templates use Handlebars syntax:

handlebars
Hello {{user_name}},

Your invitation link: {{{invite_url}}}

{{#if is_admin}}
You have admin access.
{{/if}}
  • {{variable}} — HTML-escaped output
  • {{{variable}}} — Raw unescaped HTML (use for URLs and HTML content)
  • {{#if condition}}...{{/if}} — Conditional blocks
  • {{#each list}}...{{/each}} — Loop blocks

Layouts wrap template content using {{{content}}} (unescaped triple brace).


Worker & Async Processing ​

The NotifyWorker processes pending log entries asynchronously:

  • Runs on the same server process (not a separate process)
  • Registered via registerNotifyWorker() in server.ts
  • Scheduled sends are processed when scheduled_at <= NOW
  • Failed sends are logged with error_message set
  • Workers respect FILES_MAX_UPLOAD_CONCURRENCY (reuses the same concurrency limit)

Environment Variables ​

VariableDefaultDescription
EMAIL_FROMno-reply@example.comDefault sender address
EMAIL_TRANSPORTsmtpTransport: smtp, ses, sendmail
EMAIL_SMTP_HOSTlocalhostSMTP host
EMAIL_SMTP_PORT587SMTP port
EMAIL_SMTP_USER``SMTP username
EMAIL_SMTP_PASSWORD``SMTP password
EMAIL_SMTP_SECUREfalseUse TLS

ODP Internal API Documentation