# Notifications

How staff are told about their work: the bell in the sidebar, the email from
the install, and browser push (M3-07,
[REQUIREMENTS §4.9](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/docs/planning/REQUIREMENTS.md#49-notifications),
[ADR 0002](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/docs/decisions/0002-web-push-via-vapid.md)). Every send goes through the
transactional outbox of [DOMAIN-RULES §6](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/docs/planning/DOMAIN-RULES.md#6-transactional-outbox).

## What people are told about

| Event | Who is told | Default channels |
|---|---|---|
| **Assigned to me** | The new assignee, whoever chose them: a person (a macro's assign action included), a workflow rule, round-robin or skill-based routing. A pick the rotation makes because a rule asked for it counts as the rule's. Assigning a ticket to yourself tells nobody. | in-app, email, push |
| **Reply on my tickets** | The assignee, when the *contact* answers. A colleague's reply is not this. | in-app, push |
| **Mentioned in a note** | Everyone an internal note `@`-mentions (below). | in-app, email, push |
| **SLA warning** | The people, team members and department Team Leaders the warning step names; if it names none, the assignee. | in-app |
| **SLA breach** | The assignee; on a ticket nobody holds, the members of its team. | in-app, email, push |
| **Snooze ended** | The assignee, or the person who snoozed it when nobody holds the ticket, when a snooze wakes by time or because an SLA step is about to run (M14-02, [Snooze](https://helpdock.oday-bakkour.com/docs/snooze/)). A reply, a status change or *Wake now* tells nobody. | in-app, push |
| **Escalation** | The people, team members and department Team Leaders an SLA escalation step names; if it names none, the assignee and the ticket's team. Also the recipients of a workflow rule's *Notify* action, with the rule's message quoted. | in-app, email |

Three rules hold for all seven:

- **Only about tickets they can see.** A recipient must hold a role in the brand
  whose department scope covers the ticket's department — the same scope the
  ticket's row policy applies ([DOMAIN-RULES §1.2](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/docs/planning/DOMAIN-RULES.md#12-scope-rules)).
  An Agent of Billing mentioned on a Support ticket is told nothing.
- **Deactivated staff get nothing.**
- **Nobody is told about what they did themselves.**

A team reaches each member by that member's own settings.

### Mentions

A mention is `@` followed by a handle, in any script. In an internal note,
typing `@` opens the **mention picker** (M14-15): a list under the text of the
people who can see **this ticket's department**, with presence, narrowing as you
type in either script (`@om`, `@عمر`). ↑ and ↓ move, **Tab** or **Enter** write
the handle and a space, **Esc** puts the list away. It is not offered in a public
reply, nor after a letter or digit (an email address). It lists only people the
fan-out would tell (active, able to see the department, not you), and each is
shown with a handle that resolves to them alone; someone no spelling names
uniquely is not listed. Typing a handle by hand still works. The list comes from
`GET /api/brands/:brandId/tickets/:ticketId/mention-candidates?q=`
(`ticket:write`; a ticket the reader cannot see is `404`; names, handles and
presence only, never an email address). A handle names somebody in the brand by, in this order:

1. the part of their email address before the `@` — `@lina.haddad`;
2. their whole name without spaces — `@LinaHaddad`;
3. their first name — `@Lina` — **only when exactly one person in the brand has
   it**. `@Omar` in a brand with two Omars tells neither of them.

An `@` straight after a letter or digit is part of an email address, not a
mention.

## The bell

The bell sits at the inline end of the sidebar's brand row. Its accessible name
carries the count ("Notifications, 3 unread"), and the badge shows it. The panel
lists the **last 30 days** of the brand on screen, grouped by day, with an
**Unread** filter and **Mark all read**. Opening a row marks it read and opens
its ticket. Opening a ticket any other way marks every notification about it
read too (M14-10), so an email still waiting to go leaves it out.

When somebody assigns you several tickets in one [bulk edit](https://helpdock.oday-bakkour.com/docs/tickets/#bulk-edit),
the panel shows **one row**, "Omar assigned you 12 tickets", with the first three
references and "and 9 more". Opening it marks all of that operation's rows read
and goes to **My open**. Only two or more `assigned` rows of the same operation
fold (the bell folds what it has loaded; a lone assignment is its own row). The
count in "assigned you 12 tickets" is the api's total for the operation, not the
rows on screen: each row of `GET /notifications` carries `bulkOperationId` (null
for any other cause) and `bulkOperationCount`, the number of that operation's
notifications for the reader (0 without one).

A row holds ids, never content: the subject and names are read when the panel
is, under the reader's own department scope, so a ticket they can no longer see
drops out of their panel. The nightly retention job deletes rows older than 30
days in bounded batches for each brand.

New rows arrive as a `notification:created` frame on the person's own
`user:<id>` room (see [realtime](https://helpdock.oday-bakkour.com/docs/realtime/)). The frame carries ids only; the
bell re-reads its list over REST. Reading a ticket emits a separate
`notification:read` frame that refreshes the bell without announcing a new
notification or triggering a new-notification sound.

## Your account › Notifications

Your account is the first group of **Settings** (since M14-21), with four pages, each a URL of its own:
Profile (`/settings/account/profile`, where `/settings/account` lands), Notifications
(`/settings/account/notifications`), Security (`/settings/account/security`) and Email
signature (`/settings/account/signature`, see [outbound email](https://helpdock.oday-bakkour.com/docs/outbound-email/)). The old
`/me/…` addresses redirect there.

The Notifications tab is reached from the account menu or the panel's
"Notification settings" link. One checkbox per event and channel; nothing is saved until
**Save changes**, and **Discard** puts the saved state back. Preferences belong
to the person, not the brand: they are the same in every brand they work in.

The caption says where email goes and in which language: the person's app
language, set on the Security page. Above the matrix is the **Email schedule**
card (M14-11, see [Email schedule](https://helpdock.oday-bakkour.com/docs/notifications/#email-schedule) and [Pause](https://helpdock.oday-bakkour.com/docs/notifications/#pause)), and
the three kinds that can cut a Right away wait (a mention, an SLA breach, an
escalation) carry an *Urgent* caption in the matrix.

### Sounds

Below the matrix, the **Sounds** card (M14-25) plays a short sound in the browser
when something happens. Each event has a switch and a Play button, and all are
off until you turn them on:

| Event | Plays when |
|---|---|
| A live chat is waiting for an agent | a chat arrives that nobody has taken. With **Remind me every minute while it waits**, the sound repeats each minute until the chat is assigned, closed or merged |
| A new conversation | any other conversation arrives from a customer (a ticket typed in by staff stays silent) |
| A customer replied | a customer writes again on a ticket assigned to you |
| Assigned to me or mentioned | the bell gets an assignment or a mention |

Each switch saves as you press it, and the choice belongs to your account, so it
follows you to another browser. Sounds play only in a Helpdock tab that is open
and signed in, one at a time, and never for what you did yourself. A browser may
refuse sound in a background tab; the bell shows the same news, so nothing
depends on hearing it. A chat that was already waiting when you opened the tab
does not ring; only arrivals do. Two open tabs each play their own.

The sounds are four short files in `apps/admin/public/sounds/`, generated by
`apps/admin/scripts/generate-sounds.ts` from sine tones and released under
[CC0 1.0](https://creativecommons.org/publicdomain/zero/1.0/):

| File | Event | Size |
|---|---|---|
| `waiting-chat.wav` | A live chat is waiting | 21 KB |
| `new-conversation.wav` | A new conversation | 14 KB |
| `customer-reply.wav` | A customer replied | 9 KB |
| `assigned-or-mentioned.wav` | Assigned or mentioned | 15 KB |

A file is requested the first time it plays, so a person with every sound off
downloads none.

## Email

Notification emails go from the install's **system sender** — the SMTP settings
the first-run wizard saves (`smtp.*`, or `HD_SMTP_*`), the same one sign-in links
use — never from a brand's support mailbox, so a reply to one cannot land in a
ticket. They are written in the recipient's app language (English or Arabic,
right to left), link to the tickets and to the settings page, and carry no
remote images and no message bodies beyond a single notification's excerpt.

Since M14-10 email is **paced** ([ADR 0037](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/docs/decisions/0037-paced-notification-email-and-digests.md),
[DOMAIN-RULES §20](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/docs/planning/DOMAIN-RULES.md#20-notification-delivery)). The
bell is always immediate, and push stays immediate.

### Email schedule

Each person chooses one schedule, the same in every brand:

| Schedule | What arrives |
|---|---|
| **Right away** (default) | One email a short wait after the first notification, gathering what arrives meanwhile. While more keeps coming, the waits grow. |
| **Hourly digest** | At the top of each hour, what is still unread. |
| **Daily digest** | Once a day, at the hour they choose (08:00 unless changed), in their time zone. |
| **Off** | No notification email. |

The schedule is four cards on Your account › Notifications; choosing one, or
the digest hour beside *Daily digest* (a drop-down of 00:00 to 23:00, read in
your own time zone from Your account › Profile, or the current brand's until
you choose one), is saved
with **Save schedule**, and **Discard** puts the saved one back. Changing the
hour chooses *Daily digest* for you. **Send me a test email** sends one
real-looking message to your own address (never to one you type), through the
outbox, at most five an hour; it is off, with a note, on an install that has no
outgoing email.

Right away is the default for everyone, existing accounts included: an upgrade
from 1.0 replaces one email per notification with batched email (owner
decision D-25).

**Right away pacing.** The first email goes 2 minutes after the first
notification. While more arrives, each next email waits a back-off step after
the last one went: 10, 20, 40, then 60 minutes, and 60 after that. After 2 quiet
hours with nothing new, the next one waits 2 minutes again. A **mention**, an
**SLA breach** or an **escalation** may cut the wait and go at once, but no more
often than every 5 minutes and no more than 8 times a day. However they come,
one person gets at most **6** notification emails an hour and **40** a day from
one brand, digests included. Twelve notifications in an hour reach the person
as no more than six emails.

**Nothing while they are working.** While the person is online (not away, whether they chose Away or the
department's idle limit set it, M14-18) in
the brand, a Right away email waits until they have been away or offline for 5
minutes, and never more than 15 minutes in all (owner decision D-27); what they
read meanwhile drops out.

**Digests are per brand.** A person in three brands gets up to three digests,
each naming its brand in the subject (owner decision D-26). The daily digest's
hour is read in the person's own time zone (Your account › Profile, M14-12),
or the brand's until they choose one; the times in the email use the same zone.
On the day summer time ends, an hour that
happens twice sends one digest; on the day it starts, an hour that does not
exist sends none, and its rows wait for the next day's.

Daily digests over a cap at their tick wait for the next day's tick. A missed
cron hour skips that day's daily digest; pending rows wait for the next day.
The cron runs at UTC hour boundaries. In half-hour or quarter-hour zones,
08:00 means the tick in local hour 08 (for example, 08:30 in Asia/Kolkata),
rather than exactly 08:00 local time. The repeat guard records the tick hour,
even when its queued job runs late.

### What an email says

Following the `Email/NotificationBatch` artboard:

- **One notification** is its own email, as in 1.0.
- **Several** are one email, "[Acme] 6 updates since 14:52", headed by what
  happened ("4 assigned, 2 replies"), then **Needs you now** (mentions,
  breaches, escalations), then **Tickets**, folded per ticket ("Mona replied 2
  times"). Each reference links to its ticket.
- **A bulk edit's assignments** are one line, "Omar assigned you 3 tickets", for two or more tickets
  of one operation, with the references (M14-04).
- **A digest** says how many things happened since when and how many need the
  person now, and folds a kind that touched several tickets into one line ("7
  tickets assigned to you, by Omar and round-robin").

Every notification email ends "You get these because of your notification
settings. Change them", with a link to the settings page; M14-11 adds the
one-click unsubscribe beside it. Each email's `Message-ID` is derived from its
batch, so a batch that is retried is the same message.

### Checked again before it goes

A notification can wait minutes or a day for its email, so every row is checked
again when the email is sent. It is left out, for good, when:

| Check | Marked |
|---|---|
| The ticket is gone, or the person can no longer see its department, or no longer holds a role in the brand, or was deactivated | `skipped_scope` |
| They read it, in the bell or by opening the ticket | `skipped_read` |
| Their schedule is Off, they unsubscribed (M14-11), or the row was made with email off | `skipped_off` |
| They are paused | `skipped_paused` |

A batch whose every row is left out sends nothing. Missing SMTP is
`skipped_unconfigured`, distinct from the person's Off choice. Scheduling
checks SMTP before opening a batch, so an unconfigured install does not churn
batch or presence-hold jobs. If SMTP is removed after scheduling, send time
also marks rows `skipped_unconfigured`, logs a warning and finishes without
retrying.

### Pause

A pause (until a time, at most a year ahead) holds email **and** push. It drops
rather than delays: what arrives during it is marked `skipped_paused` and stays
in the bell, and nothing is sent when it ends.

**Pause notifications** on the Email schedule card offers *For 1 hour*, *Until
tomorrow 09:00*, *For 1 week* and *Until a date…* (09:00 on a day from tomorrow
to a year ahead), worked out in the same zone as the digest hour: yours from
Your account › Profile, or the brand's until you choose one. While one runs, a line heads the card
and the bell's panel: "Paused until
17:00. Email and push resume then; the bell keeps everything." with **Resume
now**.

### Unsubscribe

Every notification email (a single one, a batch, a digest and the test email)
ends with "…Change them, or unsubscribe from notification emails" and carries
`List-Unsubscribe` (an HTTPS address with a signed token) and
`List-Unsubscribe-Post: List-Unsubscribe=One-Click`
([RFC 8058](https://www.rfc-editor.org/rfc/rfc8058)), so a mail client can show
its own Unsubscribe button.

- A mail client's **POST** to that address unsubscribes at once. Its body is
  `List-Unsubscribe=One-Click`, sent url-encoded or as `multipart/form-data`
  (RFC 8058 §3.2); the route's body limit is 4 KiB.
- A person's **click** on the footer link (a `GET`) opens a confirmation page
  at `/unsubscribe/<token>` in their language and changes nothing, so a link
  scanner that follows every URL unsubscribes nobody. A browser that opens the
  `List-Unsubscribe` address itself (a `GET` asking for `text/html`) is
  redirected to that page, so the address a person and a mail client share is
  one. The button posts the same
  one-click request.
- Unsubscribing sets `notification_prefs.email_unsubscribed_at` and leaves the
  matrix, the schedule, the hour and any pause as they were. Preferences are
  global (M3-07), so it stops notification email from **every brand**; the bell,
  push you turned on and security emails keep working. A queued batch sends
  nothing and its rows are marked `skipped_off`.
- Your account › Notifications then says "You unsubscribed on 3 Oct…" with
  **Turn email back on**, which clears it and restores exactly the same
  choices. The bell's panel shows the same line.
- **Turning email back on retires older links.** The save that lifts an
  unsubscribe records `notification_prefs.email_resubscribed_at`, and a link
  from an email issued before that moment is refused with the same `404` an
  unknown token gets, on both `GET` and `POST`, so a forwarded copy of an old
  email cannot switch your email off again. Emails sent afterwards carry links
  that work. Tokens record whole seconds, so the comparison is made in whole
  seconds and a link minted in the same second as the resubscribe is refused
  too (it cannot be told from an older one); the next email carries a working
  link. Saving other settings, or turning email back on when it was never off,
  does not move the timestamp. People who turned email back on before this
  release have no timestamp, so their older links keep working until they
  expire.
- A token is good for a year from the email that carried it. It is signed
  (HMAC-SHA256, key derived with HKDF from `APP_MASTER_KEY` for this purpose
  alone), names one user and can do one thing: turn that user's notification
  email off. A forged, altered, expired or unknown token, a token for a
  deactivated account, and a token issued before the last resubscribe all
  get the same "This link has expired" page (`404`),
  so the page never says whether an address has an account here. Repeating a
  request changes nothing further; the first one writes the audit row
  `notification.email_unsubscribed`. The route is limited to 120 requests per
  address per 15 minutes. After a master key rotation, links signed under the
  previous key still work; older ones do not.

### Settings for an install

Each pacing number is an install setting, pinned from the environment like any
other ([configuration](https://helpdock.oday-bakkour.com/docs/configuration/#settings-you-can-pin-with-hd_)):

| Setting | Environment | Default |
|---|---|---|
| `notify.email.firstWaitMinutes` | `HD_NOTIFY_EMAIL_FIRST_WAIT_MINUTES` | `2` |
| `notify.email.backoffMinutes` | `HD_NOTIFY_EMAIL_BACKOFF_MINUTES` | `[10,20,40,60]` |
| `notify.email.quietResetMinutes` | `HD_NOTIFY_EMAIL_QUIET_RESET_MINUTES` | `120` |
| `notify.email.urgentIntervalMinutes` | `HD_NOTIFY_EMAIL_URGENT_INTERVAL_MINUTES` | `5` |
| `notify.email.urgentPerDay` | `HD_NOTIFY_EMAIL_URGENT_PER_DAY` | `8` |
| `notify.email.perHour` | `HD_NOTIFY_EMAIL_PER_HOUR` | `6` |
| `notify.email.perDay` | `HD_NOTIFY_EMAIL_PER_DAY` | `40` |

The presence hold (5 minutes away, 15 at most) is fixed.

## Browser push

Push needs a VAPID key pair on the install, as settings `push.vapidPublicKey` and
`push.vapidPrivateKey` (the private key is a secret setting, encrypted at rest
and never returned to a browser). The first-run wizard generates the pair when
it finishes, if the install has none, and records `install.setup.push` in the
install's audit log without either key (`apps/api/src/install/vapid-keys.ts`).
An install set up before that, or an operator who wants the pair in `.env`,
pins it from the environment instead, and the wizard then leaves it alone:

```sh
npx web-push generate-vapid-keys
# then, in .env:
HD_PUSH_VAPID_PUBLIC_KEY=B…
HD_PUSH_VAPID_PRIVATE_KEY=…
```

Without them the push column of the settings page is disabled and the card says
"Not set up on this install"; no push job is queued. While the person is
paused, no push job is queued either. Rotating the pair
invalidates every browser's subscription (ADR 0002); each person turns push on
again.

Push also needs HTTPS (or `localhost`) and a browser with a service worker and
the Push API. On iOS and iPadOS it works only for Helpdock added to the Home
Screen. Each person turns it on per browser, on the card beside the settings:
the browser asks once; **Send a test** pushes one notification to that browser
through the same path a real one takes; **Turn off** removes it. A browser that
answered "block" has to be allowed again in its own site settings.

The admin serves its service worker at `/sw.js`. It caches nothing; it shows
what is pushed and, on a click, opens the ticket.

The worker sends each push through the SSRF-safe client
([DOMAIN-RULES §13](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/docs/planning/DOMAIN-RULES.md#13-outbound-network-safety)),
because a push endpoint is a URL a browser handed the api. A push service that
answers `404` or `410`, or an endpoint the policy refuses, deletes the
subscription.

## How a notification travels

```
ticket change, SLA step, rule   →  outbox: ticket.assigned, sla.breached, …   (same transaction)
worker: fan-out                 →  notifications rows + outbox: notification.created
worker: notification.created    →  socket frame; notify.email_schedule and notify.push jobs
worker: notify.email_schedule   →  the row joins the person's pending batch, or waits for a digest
worker: notify.email_batch      →  at the batch's time: re-check, one email; one push per browser
worker: notify.digest.tick      →  hourly, per brand: a digest batch for whoever's hour it is
worker: notify.email_rebuild    →  on boot and hourly: every pending batch's job placed again
```

Pacing lives in Postgres (`notification_email_batches` and
`notification_email_pacing`, both owner-scoped like `notifications`), not in
Redis, so losing Redis loses no email: `notify.email_rebuild` puts every
pending batch's delayed job back and schedules any row whose schedule job was
lost. A `notify.email` job left in Redis from 1.0 is let go with a log line.

| Event consumed | Written by |
|---|---|
| `ticket.assigned` | `TicketsService` (a person), `autoAssign` (the rotation), a workflow rule (M3-03). A bulk edit's carries `bulkOperationId` (M14-03): the notification is stamped with it, and is not made at all once an Undo put that ticket's assignee back |
| `ticket.bulk_undone` | An Undo of a bulk edit (M14-03): withdraws the unread notifications of the listed tickets, and marks a still-pending email `withdrawn` |
| `ticket.replied`, `ticket.note_added` | `TicketsService.addMessage` (M1-03) |
| `sla.warning`, `sla.breached` | the SLA engine (M3-02); a warning may name `userIds`, `teamIds` and `departmentLeads` |
| `ticket.escalated` | an SLA escalation step (M3-02); may name `userIds`, `teamIds` and `departmentLeads` |
| `rule.notify` | a workflow rule's *Notify* action (M3-03): `{ ticketId, recipients, message, ruleId }`, delivered as an escalation |

A redelivered event writes nothing new: a notification is unique per source
event and recipient, a row joins one batch at most, a batch sends once (its
`job_receipts` key is `notify.email_batch:<batchId>`), and push jobs are keyed
by what they send.
The consumers subscribe to these events as `notifications`, beside whichever
module owns each event ([`packages/jobs`](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/packages/jobs/README.md#handling-an-event)).

## API

| Route | Permission | Does |
|---|---|---|
| `GET /api/brands/:brandId/notifications?filter=all\|unread` | `ticket:read` | The panel: `{ items, unreadCount }` |
| `POST /api/brands/:brandId/notifications/:id/read` | `ticket:read` | Marks one of the caller's own read; `404` for anyone else's |
| `POST /api/brands/:brandId/notifications/read-all` | `ticket:read` | Marks all of the caller's read in the brand |
| `POST /api/brands/:brandId/notifications/test-push` | `ticket:read` | `{ subscriptionId }`; `409` without VAPID keys |
| `POST /api/brands/:brandId/notifications/test-email` | `ticket:read` | A test email to the caller's own address through the outbox (`204`); `409` on an install without SMTP, `429` past five an hour |
| `GET /api/public/unsubscribe/:token` | public, signed token | What the confirmation page draws (`{ state: 'confirm', email, locale }`); changes nothing; `404` for any token that is no good; a request that accepts `text/html` is redirected (`302`) to `/unsubscribe/<token>` |
| `POST /api/public/unsubscribe/:token` | public, signed token | RFC 8058 one-click: body `List-Unsubscribe=One-Click`, url-encoded, JSON or multipart (`400` otherwise); unsubscribes, idempotently; `{ state: 'done', locale }` |
| `GET`, `PUT /api/me/notification-preferences` | signed in | The matrix, `sounds` (the four events and `waitingChatReminder`, each a boolean, all `false` by default), the email address and language, push status, and `emailDelivery`: `schedule` (`immediate`, `hourly`, `daily`, `off`), `digestHour` (0–23), `pausedUntil` and `unsubscribedAt`. A `PUT` takes any of `preferences`, `sounds` (all five keys; `400` for an unknown or non-boolean one), `emailSchedule`, `digestHour`, `pausedUntil` (an ISO time within a year, or `null` to resume; `400` otherwise) and `emailUnsubscribed: false` ("Turn email back on"; `true` is refused) and keeps the rest. The view also says whether the install can send email (`emailConfigured`) and the zone the digest hour and the pause presets are read in (`digestTimeZone`: the person's own, else the current brand's) |
| `POST /api/me/push-subscriptions` | signed in | `PushSubscription.toJSON()` plus a label; `https` endpoints only |
| `DELETE /api/me/push-subscriptions/:id` | signed in | Removes one of the caller's browsers |

## Upgrade and failed batches

A leftover 1.0 `notify.email` job and a delayed `notification.created` event
both recover a row whose `email_state` is null only if its email flag is on,
it is at most 24 hours old, and `job_receipts` has no `notify.email:<id>` receipt.
The old sender claimed that receipt in the send transaction. Older, disabled,
or already-sent legacy rows are dropped with an info log.

Send failures (including rendering failures) are counted durably on the batch
only when a BullMQ job exhausts its attempts. Retries within that job do not
consume the batch budget; hourly rebuilds place fresh jobs. Database and other
infrastructure errors never consume this budget. After five exhausted send
jobs, its remaining rows become `skipped_failed`, the batch becomes `failed`, and its pending slot
is released. The worker logs that terminal transition once at warn; new
notifications can open a fresh batch.


## Known gaps

- The daily digest uses the brand's time zone for anyone who has not chosen
  their own on Your account › Profile.
