> For the complete documentation index, see [llms.txt](https://docs.digit.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.digit.org/complaints-management/deploy/configure/notifications/developer-guide.md).

# Developer Guide

## Overview

For developers connecting a module to notifications or changing novu-bridge. Related: tenant-accounts.md (each workspace's own Novu organisation, and `POST /messages/_send` for sign-in codes), kafka-events.md (topics, publishing, verifying), providers.md (adapters, adding a provider), contract/ (schemas, OpenAPI, error codes, outputs).

### The two inbound kinds

|                               | Thin event (`kind: "THIN"`)                                                      | Pre-rendered envelope (`kind` absent or `"RENDERED"`) |
| ----------------------------- | -------------------------------------------------------------------------------- | ----------------------------------------------------- |
| Producer says                 | "this happened to this entity"                                                   | "send this text to this person on this channel"       |
| Messages per business event   | one                                                                              | one per recipient × channel                           |
| Recipients, language, wording | decided by novu-bridge from `NOTIFICATIONS.*` config — operators can change them | decided by the producer                               |
| Schema                        | thin-event-v1.schema.json                                                        | envelope-v1.schema.json                               |

**Use the thin event.** Keep the envelope (a permanent, non-deprecated interface) for producers you cannot change, single-recipient messages with no configurable audience, and translated foreign formats (below). Both kinds share topics, gates and the dispatch log.

### Plug a module in

Example: a trade-licence module with no notification code (examples/thin/03-module-neutral.json).

#### 1. Declare events in `NOTIFICATIONS.EventCatalogue`

One row per event. The Configurator builds its pickers and validates templates from it.

<table><thead><tr><th width="215.2421875">Field</th><th>Meaning</th></tr></thead><tbody><tr><td><code>module</code></td><td>Owner, e.g. <code>XYZ</code> (required)</td></tr><tr><td><code>eventName</code></td><td>Key: dotted, module-prefixed, unique (required). Encode the outcome, not just the action — two outcomes needing different words need two names</td></tr><tr><td><code>label</code></td><td>Picker label (required)</td></tr><tr><td><code>entityType</code></td><td>What <code>entityId</code> names</td></tr><tr><td><code>actors</code></td><td><code>[{name, label, required}]</code> — actor names your events carry (<code>ACTOR:&#x3C;name></code>)</td></tr><tr><td><code>placeholders</code></td><td><code>[{name, label, blankWhen}]</code> — token names without braces</td></tr><tr><td><code>channels</code></td><td>Allowed channels; absent = any</td></tr><tr><td><code>active</code></td><td>Absent = true</td></tr></tbody></table>

```json
{ "module": "XYZ", "eventName": "XYZ.LICENCE.RENEWED", "entityType": "LICENCE",
  "label": "Licence renewed",
  "actors": [{ "name": "holder", "label": "Licence holder", "required": true }],
  "placeholders": [{ "name": "licence_no", "label": "Licence number" },
                   { "name": "valid_until", "label": "Valid until" }],
  "channels": ["SMS", "EMAIL"], "active": true }
```

An uncatalogued `eventName` is `REJECTED / NB_EVENT_NOT_IN_CATALOGUE` and DLQ'd, except on a tenant with no catalogue rows at all. CMS rows are generated from its workflow by `local-setup/scripts/generate_event_catalogue.py` (`--check` after changing the workflow).

#### 2. Ship default routing and templates

Per tenant, at the state root, owned by operators after seeding.

```json
{ "module": "XYZ", "eventName": "XYZ.LICENCE.RENEWED", "audience": "ACTOR:holder", "channel": "SMS", "active": true }
{ "module": "XYZ", "eventName": "XYZ.LICENCE.RENEWED", "audience": "ACTOR:holder", "channel": "SMS",
  "locale": "en_IN", "subject": null,
  "body": "Licence {licence_no} is renewed until {valid_until}.", "active": true }
```

`NOTIFICATIONS.Routing` is unique on `(eventName, audience, channel)`; `NOTIFICATIONS.Template` on `(eventName, audience, channel, locale)`. Every routing row needs a template in `novu.bridge.default.locale` (`en_IN`). WhatsApp also needs `NOTIFICATIONS.ProviderTemplate`, unique on `(provider, channel, eventName, audience, locale)`, with the approved `templateId` and ordered `variables`. Shipped defaults live in `utilities/default-data-handler/src/main/resources/mdmsData-dev/NOTIFICATIONS/`.

#### 3. Publish the event

To `notifications.events` (or your own topic — kafka-events.md), and add your `eventType` to `NOVU_BRIDGE_EVENT_TYPES`.

| Required                          |                                      |
| --------------------------------- | ------------------------------------ |
| `kind`                            | `"THIN"`                             |
| `eventId`                         | uuid of the domain event             |
| `eventType`                       | your producer constant (allowlisted) |
| `module`, `eventName`, `tenantId` | as catalogued                        |

<table><thead><tr><th width="309.6328125">Optional</th><th></th></tr></thead><tbody><tr><td><code>entityId</code>, <code>entityType</code></td><td>Your handle; becomes <code>reference_number</code> on the Logs screen — send it</td></tr><tr><td><code>transactionSeed</code></td><td>Idempotency seed (below)</td></tr><tr><td><code>actors</code></td><td><code>{name: {userId, type, name, phone, email, locale}}</code></td></tr><tr><td><code>recipients</code></td><td><code>[actorRef]</code> for account-less flows (audience <code>EVENT_RECIPIENTS</code>)</td></tr><tr><td><code>data</code></td><td>token → literal value</td></tr><tr><td><code>localized</code></td><td>token → localization code, or ordered list of codes</td></tr><tr><td><code>localizationModules</code>, <code>localizationLocale</code></td><td>modules to search in order; the one locale codes are resolved in</td></tr><tr><td><code>dataByLocale</code></td><td><code>{locale: {token: value}}</code> for values that cannot be codes</td></tr><tr><td><code>ledgerEventName</code></td><td>name written to the dispatch log if it must differ from <code>eventName</code></td></tr><tr><td><code>payload</code></td><td>your block, copied to each resolved envelope's <code>data</code></td></tr><tr><td><code>schemaVersion</code>, <code>eventTime</code>, <code>producer</code></td><td>as the envelope</td></tr></tbody></table>

Do not send `channel`, `subscriberId`, `renderedBody`, `subject`, `templateKey`, `templateId` or `contentVariables`; the bridge produces them.

**Contacts.** For a recipient with an account, send only `userId` (and `type`); the bridge hydrates name, phone and email from egov-user, so no contact data goes on Kafka. Send contact fields only for account-less recipients.

**Idempotency.** The dispatch log's unique key is `(transaction_id, channel, recipient_value)` and writes are upserts. The bridge sets `transactionId = <transactionSeed>:<subscriberId>:<channel>` (`<seed>:NONE` on channel-less rows), and never re-sends a `transactionId` that is already `SENT` or `DELIVERED`. So the seed must be **one per occurrence**: identical when that occurrence is redelivered or replayed from the DLQ, different for every new one — including a repeat of the same kind on the same entity (a second `ASSIGN` into the same state, next year's renewal). A seed built only from the entity and the kind of event silently drops every repeat. CMS sends `<serviceRequestId>:<action>:<toState>:<workflow ProcessInstance id>`, falling back to `auditDetails.lastModifiedTime` for the last part; with neither it omits the seed. Absent, the seed is `<eventId>`, so keep `eventId` stable when you retry one occurrence. The skip is check-then-act: two copies of one message arriving at the same moment can both be sent.

**Localisation.** Per token, the bridge tries each code in `localized[token]`, then `dataByLocale[locale][token]`, then `data[token]`; with none, the token is left as `{token}`. Values are resolved once per event in `localizationLocale` (else the default locale); template text is chosen per recipient. Send both a literal and a code where you can, so a localisation outage degrades to the literal.

#### 4. Dry-run, then watch it land

* `POST /novu-bridge/novu-adapter/v1/dispatch/_resolve` with `{"RequestInfo": …, "event": …}` runs the real resolver against the tenant's real configuration and returns `envelopes` (fully rendered), `terminalCode` (`NB_NO_ROUTING`, `NB_NO_RECIPIENTS`, `NB_UNKNOWN_AUDIENCE_SCHEME`, `NB_RECIPIENT_LIMIT_EXCEEDED`) and `diagnostics`. Nothing is sent or written. Admin tier because it returns role holders' contacts: an admin role at the state root of the event's `tenantId`, or at a state that owns the providers (providers.md), else `NB_ADMIN_ROLE_REQUIRED` / `NB_TENANT_NOT_ALLOWED`.
* Then publish and check the Logs screen / `GET …/logs?referenceNumber=…`; `source_path` is `RESOLVED` for thin events. Where things land:

<table><thead><tr><th width="436.08984375">Outcome</th><th>Result</th></tr></thead><tbody><tr><td>No routing, no recipients, no template, unknown audience scheme, fan-out over the cap</td><td><code>SKIPPED</code> row, never DLQ'd</td></tr><tr><td>Malformed or uncatalogued event, unknown <code>eventType</code></td><td><code>REJECTED</code> row <strong>and</strong> DLQ message</td></tr><tr><td>Transport failure</td><td><code>FAILED</code> row; DLQ message if it threw</td></tr></tbody></table>

A configuration decision never throws — keep that rule when extending the resolver. Statuses and columns: contract/outputs.md; codes: contract/error-codes.md.

### How audiences resolve

<table><thead><tr><th width="167.1015625">Form</th><th width="382.92578125">Resolved by</th><th>I/O</th></tr></thead><tbody><tr><td><code>ACTOR:&#x3C;name></code></td><td>the event's <code>actors</code></td><td>none</td></tr><tr><td><code>ROLE:&#x3C;code></code></td><td>every holder of the role in the tenant (paged egov-user search as <code>NOVU_BRIDGE_INTERNAL_USER_UUID</code>, up to <code>NOVU_BRIDGE_ROLE_POOL_PAGE_SIZE</code> × <code>NOVU_BRIDGE_ROLE_POOL_MAX_PAGES</code> = 100 × 10)</td><td>directory search</td></tr><tr><td><code>EVENT_RECIPIENTS</code></td><td>the event's <code>recipients</code></td><td>none</td></tr><tr><td><code>A|B</code></td><td>first link that yields anyone</td><td>as its links</td></tr></tbody></table>

Legacy bare names: `CITIZEN` → `ACTOR:citizen`, `EMPLOYEE` → `ACTOR:assignee`, `AUTO_ESCALATE` / `SYSTEM` → dropped; anything else → `ROLE:<it>`. An unknown scheme is `SKIPPED / NB_UNKNOWN_AUDIENCE_SCHEME`, never guessed.

* Dedupe is per `(channel, subscriberKey)`, not per audience, and a key is consumed only after a successful hand-off.
* A failed audience resolution is not memoised.
* Over `novu.bridge.notifications.recipient.cap` (1000) the **whole** event is `SKIPPED / NB_RECIPIENT_LIMIT_EXCEEDED`.

### pgr-services as the reference producer

`backend/pgr-services/src/main/java/org/egov/pgr/service/notification/ThinEventBuilder.java` publishes one thin event per transition to `complaints.domain.events`. PGR keeps only what the bridge cannot know: that a transition happened; the assignee (live, else last `ASSIGN` in workflow history, sent as `actors.assignee` uuid); the thirteen placeholder values including the HRMS department/designation join; and which localisation codes apply. Worked examples: contract/examples/thin/.

### Swapping the DIGIT seams

`org.egov.novubridge.service.resolution` is module- and platform-neutral; every DIGIT client is in `service.resolution.digit`. Keep it so: nothing outside `.digit` may import an egov client.

| Interface                                                                                             | Contract                                                                             | DIGIT implementation                                                                                                                                                                                                                                                                                 |
| ----------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `RecipientResolver` — `scheme()`, `resolve(AudienceRef, ResolutionContext)`                           | Never null; empty list is a valid answer (→ `SKIPPED`); throw only on a real failure | `DigitRoleRecipientResolver` (`ROLE`); built-in `ActorRecipientResolver`, `EventRecipientsResolver`                                                                                                                                                                                                  |
| `LocaleProvider` — `preferredLocales(tenantId, requestInfo)`                                          | Empty map when the source is unreachable                                             | `DigitLocaleProvider` (digit-user-preferences-service)                                                                                                                                                                                                                                               |
| `LocalizationProvider` — `message(tenantId, locale, modules, code, requestInfo)`                      | `null` when no module has the code (next code is tried)                              | `DigitLocalizationProvider` (egov-localization)                                                                                                                                                                                                                                                      |
| `UserHydrator` — `hydrate(userId, type, tenantId, requestInfo)`                                       | `null` rather than throw; called only for a `userId` with no contact fields          | `DigitUserHydrator` (egov-user)                                                                                                                                                                                                                                                                      |
| `NotificationConfigRepository` — `routing`, `templates`, `providerTemplates`, `catalogue`, `describe` | —                                                                                    | `MdmsNotificationConfigRepository` (MDMS v2 at the state root; paged; cached `NOVU_BRIDGE_NOTIFICATIONS_CACHE_TTL_MS`, empty results included, though an empty answer never replaces a non-empty cached one; stale entries served through an MDMS outage; legacy fallback via `LegacyMasterAdapter`) |

Each DIGIT bean is `@ConditionalOnMissingBean` on its interface: define your own bean and the DIGIT one steps aside. For `RecipientResolver`, register one whose `scheme()` matches (e.g. `"ROLE"`). A product that puts contacts on the event needs no resolver code.

### Adapting a format you do not control

Use a translator bound to the topic, not shape-sniffing in the consumer. Model: `service/core/CoreSmsTranslator` + `consumer/CoreSmsConsumer`, which turn DIGIT core's `SMSRequest` on `egov.core.notification.sms` into a `CORE_SMS` envelope:

* accept every field-name variant the real producer emits (`mobileNumber`/`mobile`/`phone`/`to`, `message`/`body`/`text`, `tenantId`/`tenant`); refuse without phone or text (`NB_INVALID_CORE_SMS`);
* fill gaps from configuration (`NOVU_BRIDGE_CORE_SMS_DEFAULT_TENANT`; the country code of a national number from the tenant's `common-masters.MobileNumberValidation` rule, else `NOVU_BRIDGE_CORE_SMS_COUNTRY_CODE` — `service/TenantPhoneNumbers`) and derive `eventId` and `transactionId` (`CORE:<tenant>:<uuid>`) from the Kafka record's topic, partition, offset and timestamp: unique per send, the same on a redelivery (so the replay guard does not send an OTP twice), and without the phone number, since the id reaches logs, gateway requests and error messages;
* never guess a country code: a rule MDMS could not be asked for is not "no rule" (`TenantPhoneNumbers.RuleUnavailable`, `NB_CONFIG_UNAVAILABLE`: the translator keeps the number national and the pipeline records `FAILED`, then the consumer DLQs). Digits that start with the code are read by the rule's `mobileNumberRegex` when exactly one reading (as they are, or without the code) matches it; otherwise by `PhoneNumbers`' heuristic, "9 or more digits after the code means it is already there", which misreads a long national number that starts with the code — a German `49112345678` (area code 491) goes to `+49112345678` — unless the tenant's pattern settles it;
* drop what is no longer worth sending: an OTP (`category` `OTP`) whose `expiryTime` (epoch milliseconds) has passed is logged at INFO — without phone or text — and gets no dispatch-log row and no DLQ message;
* a translation failure is DLQ'd with no dispatch-log row, and any core-SMS DLQ message is redacted (text removed, phone masked; outputs.md);
* the consent gate is skipped for core SMS other than `PROMOTION` (the user just asked for it, often before having an account), but only because `CoreSmsConsumer` hands the event to `DomainEventConsumer.handleCoreSms` → `DispatchPipelineService.processCoreSms`. Event fields never grant it: an envelope or thin event on a shared topic, or a `/dispatch/_dry-run`, that says `CORE_SMS` is consent-checked like any other;
* the listener starts at the **latest** offset when its group has no committed offset (the domain-event listeners start at `earliest`): replaying days of queued OTPs is worse than missing them;
* wire a `@KafkaListener` on its own topic property, `@ConditionalOnProperty` so it can be switched off, and pass the result to `DomainEventConsumer.handle(event, topic)` (not straight to the pipeline, or the DLQ is lost).

If the foreign format's recipients should be configurable, emit a thin event with `EVENT_RECIPIENTS` instead (examples/thin/04-contact-override.json). Such an event is consent-checked like any other, whatever its `eventType`: with the consent gate on (`NOVU_BRIDGE_PREFERENCE_ENABLED`), a recipient without a `userId` is `SKIPPED / NB_PREFERENCE_DENIED`.

### Local testing without real gateways

* **SMS:** run a small HTTP mock on the compose network that answers in the gateway's real format (including its failure shapes, e.g. SMSCountry's and Ozeki's rejections-as-200) and logs what it received; point an SMSCountry provider's Gateway URL, or an Ozeki / Jasmin provider's URL, at it by service name. These three are DIGIT's providers mounted into the Novu worker (providers.md); a worker started without them never calls the mock, and with `NOVU_BRIDGE_DIGIT_WORKER_PROVIDERS=false` the bridge does not offer them at all.
* **Email:** run an SMTP sink with a web inbox (e.g. Mailpit) on the compose network and add it as an Email (SMTP) provider: host = service name, its SMTP port, any user/password, **Use TLS on connect** unticked. Or use Ethereal (setup-guide.md §8.5).
* **Test** on the Providers screen exercises one provider; `_resolve` shows what a thin event would produce; `POST /novu-bridge/novu-adapter/v1/dispatch/_dry-run` with `"send": true` pushes one envelope through the full pipeline (container network only — not routed by Kong). Test and `_dry-run` with `"send": true` need an admin role at a state that owns the providers (the state of `NOVU_BRIDGE_CORE_SMS_DEFAULT_TENANT`, or one in `NOVU_BRIDGE_PROVIDER_ADMIN_TENANTS`); `_resolve`, and `_dry-run` without `send`, also accept an admin role at the state root of the event's `tenantId`.
* To check that a producer change changed no message, resolve the old and new events for the same flows with `_resolve` and diff the envelopes.
* After editing the legacy seed or the PGR workflow, run `local-setup/scripts/generate_event_catalogue.py --check` and `local-setup/scripts/notifications_convert.py --check`.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.digit.org/complaints-management/deploy/configure/notifications/developer-guide.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
