feat(engagement): the in-app channel, core and web (engagement Phase 7)
All checks were successful
PR Checks / client-build (pull_request) Successful in 37s
PR Checks / server-tests (pull_request) Successful in 3m27s
PR Checks / bot-tests (pull_request) Successful in 8m36s

ENGAGEMENT.md Phase 7. `user_notifications`, the in-app DeliveryChannel, the
four inbox routes, and the web surface — plus the two pieces earlier phases
assigned here that Phase 7's own acceptance line omits.

Four decisions settled by the org lead before any code:

1. `inapp` defaults to `instant` — the only channel that does. Push wakes a
   device somebody is holding and email leaves the building, so both are asked
   for; an inbox item is a row on a page the user chose to open. Left `off` the
   channel ships dead.
2. The phase takes push's `deliver` (§2603) and the web per-channel preferences
   screen (Phase 3's as-built), neither of which its own bullets mention.
3. The inbox takes `/auth/me/notifications` and `/account/notifications`; the
   preferences screen moves to `…/settings`. The plain word belongs to the
   content, which is what the bell opens.
4. `ctx.inbox.push` honours the user's in-app preference when `triggerId` names
   a registered trigger, and writes when it does not.

Server
- `user_notifications` + `model/userNotifications/`. The dedupe UNIQUE is scoped
  to the USER, narrower than the outbox's `(rule, user, channel)`: an inbox has
  no channel dimension, so two rows for one event would be one item shown twice.
- `engagement/inappChannel.js` — renders by block ROLE (first heading → title,
  first button → url, the rest → body) and inserts. `pushChannel.js` — a
  content-free `{stream, ref}` tickle whose ref deep-links the inbox row.
- `engine.liveChannels` orders `inapp` first (`CHANNEL_ORDER`) so that ref
  resolves on the first sweep. An ordering, not a dependency.
- `templates.renderInappByKey` + `resolveTemplate` extracted from `renderByKey`,
  so both channels take the same fallback chain.
- `inapp.event` seed → seedVersion 2: it named `body`/`url`, which nothing
  supplies. Renamed to the structural vocabulary the projection fills in.
- `utils/userNotificationsPrune.js` — nightly, READ items only, horizon in
  `settings.user_notifications_retain_days` (default 90).
- `GET /auth/me/notifications`, `…/unread-count`, `POST …/:id/read`,
  `POST …/read-all`. Swagger + route manifest + four component schemas.

Web
- `NotificationBell` in all three headers, polling its badge once a minute and
  pausing while the tab is hidden. `PlayerInbox` at `/account/notifications`.
- The preferences screen becomes a channel matrix over
  `/auth/me/notifications/channels` — a strict superset of the push-only stream
  list it replaces. The two legacy endpoints are untouched, so the shipped
  Android app keeps its wire shape.
- Staff get the same two screens at `/admin/notifications…`: `RequirePlayer`
  keeps them out of `/account`, so without this the inbox was unreachable for
  every non-player account. `lib/notificationPaths.js` is the one mapping.

Verified: 28 new server tests (5 of them against a real MariaDB, for the three
index/statement properties that are a server contract rather than a reading of
this code) + 3 client. Server suite green, client 327 green. A live rig walked
the whole path: two rules on one event produced three outbox rows and exactly
one inbox item, the tickle carried `ref: notification:2`, and the retention
sweep dropped an aged read row while keeping an equally aged unread one.

Docs: RunicGateway/docs#TBD, RunicGateway/runicgateway.com#TBD

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2026-08-31 02:07:10 -05:00
parent 5168446c53
commit 24a3cd85b3
34 changed files with 3153 additions and 112 deletions

View File

@@ -9,6 +9,7 @@ const channelPrefs = require('../../../model/notificationChannelPrefs/notificati
const registries = require('../../../modules/registries')
const teamPrefs = require('../../../model/teams/teamNotify.model')
const { isAllowedEndpoint } = require('../../../utils/pushDispatch')
const inbox = require('../../../model/userNotifications/userNotifications.db')
const log = require('../../../utils/logger')('notifications')
@@ -146,6 +147,80 @@ async function putTeamPrefs(req, res) {
}
}
// ── The inbox (ENGAGEMENT.md §4.5 G17, Phase 7) ────────────────────────────
//
// The in-app channel's read side. Everything above this line is a PREFERENCE —
// which streams, which channels, which Teams — and everything below it is
// CONTENT addressed to the caller. They share a path prefix because a person
// calls both "notifications", and the shapes keep them apart: the preference
// endpoints are whole-set GET/PUT pairs on named sub-paths, the inbox is a
// paged GET on the bare path with POSTs that name a row.
//
// **`req.user.id` is the only user id any of these can name.** There is no route
// parameter for a user and no query string that selects one, so the ownership
// check is not something a caller can be forgetful about — it is the shape of
// the API. The model then repeats it in the WHERE clause of every statement, so
// "read someone else's notification" is a 404 twice over.
// GET /auth/me/notifications — one page of the caller's inbox, newest first.
async function getInbox(req, res) {
try {
const page = await inbox.list(req.user.id, {
limit: req.query.limit,
before: req.query.before,
unreadOnly: req.query.unread === 'true' || req.query.unread === '1',
})
// The unread count rides along on every page, so the bell and the list never
// disagree: a client that renders both from one response cannot show "3
// unread" above a list in which the third was just marked read.
return res.json({ ...page, unread: await inbox.unreadCount(req.user.id) })
} catch (err) {
log.error('getInbox', err)
return res.status(500).json({ message: 'Internal Server Error' })
}
}
// GET /auth/me/notifications/unread-count — the badge, on its own.
//
// Its own route rather than a field of the list, because it is polled: a client
// asking "is there anything new" every minute should not make the server
// assemble thirty rows and their bodies to answer with one integer.
async function getUnreadCount(req, res) {
try {
return res.json({ unread: await inbox.unreadCount(req.user.id) })
} catch (err) {
log.error('getUnreadCount', err)
return res.status(500).json({ message: 'Internal Server Error' })
}
}
// POST /auth/me/notifications/:id/read — mark one item read. Idempotent.
//
// 404 both when the row does not exist and when it belongs to somebody else,
// which is the same answer on purpose: distinguishing them would turn this route
// into a way to ask whether a given id is anybody's.
async function markRead(req, res) {
try {
const found = await inbox.markRead(req.user.id, req.params.id)
if (!found) return res.status(404).json({ message: 'Not Found' })
return res.json({ ok: true, unread: await inbox.unreadCount(req.user.id) })
} catch (err) {
log.error('markRead', err)
return res.status(500).json({ message: 'Internal Server Error' })
}
}
// POST /auth/me/notifications/read-all — mark the whole inbox read.
async function markAllRead(req, res) {
try {
const changed = await inbox.markAllRead(req.user.id)
return res.json({ ok: true, changed, unread: 0 })
} catch (err) {
log.error('markAllRead', err)
return res.status(500).json({ message: 'Internal Server Error' })
}
}
module.exports = {
registerDevice,
listDevices,
@@ -157,4 +232,8 @@ module.exports = {
putChannelPrefs,
getTeamPrefs,
putTeamPrefs,
getInbox,
getUnreadCount,
markRead,
markAllRead,
}

View File

@@ -7,7 +7,7 @@
// and never touches /admin.
const express = require('express')
const { body, param } = require('express-validator')
const { body, param, query } = require('express-validator')
const notif = require('./notifications.controller')
const { requireAuth } = require('../../../auth/session.middleware')
@@ -137,6 +137,72 @@ notifRouter.put(
notif.putChannelPrefs,
)
// ── The inbox (ENGAGEMENT.md §4.5 G17, phase 7) ────────────────────────────
//
// The in-app channel's read side, and the only routes in this file that carry
// CONTENT rather than a preference. They share the `/notifications` prefix
// because a person calls both by that name; the bare path is the inbox and the
// named sub-paths above are the settings for it.
//
// **Route order matters here and is not incidental.** `/notifications/streams`,
// `/notifications/subscriptions`, `/notifications/channels` and
// `/notifications/teams` are all declared ABOVE, and none of the routes below
// introduces a GET `/notifications/:something` that could shadow them. The one
// parameterised path is a POST, and its `:id` is digits-only.
notifRouter.get(
'/notifications',
// #swagger.tags = ['Auth · Me']
// #swagger.summary = 'One page of the callers notification inbox'
// #swagger.description = 'The in-app channels items for the signed-in user, newest first. Paged with a keyset cursor (`before`), not an offset, because the list gains rows at the top while it is being read. `unread` counts the whole inbox, not the page. There is no way to name another user: the caller is the only account these routes can read.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
// #swagger.parameters['limit'] = { in: 'query', required: false, schema: { type: 'integer', minimum: 1, maximum: 100, default: 30 }, description: 'Page size (capped at 100).' }
// #swagger.parameters['before'] = { in: 'query', required: false, schema: { type: 'integer' }, description: 'Return items with an id lower than this — the cursor from the previous page.' }
// #swagger.parameters['unread'] = { in: 'query', required: false, schema: { type: 'boolean' }, description: 'Only items that have not been read.' }
/* #swagger.responses[200] = { description: 'A page of the inbox', content: { "application/json": { schema: { $ref: "#/components/schemas/NotificationInbox" } } } } */
/* #swagger.responses[401] = { description: 'Not authenticated', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
query('limit').optional().isInt({ min: 1, max: 100 }),
query('before').optional().isInt({ min: 1 }),
query('unread').optional().isIn(['true', 'false', '1', '0']),
validate,
notif.getInbox,
)
notifRouter.get(
'/notifications/unread-count',
// #swagger.tags = ['Auth · Me']
// #swagger.summary = 'How many inbox items the caller has not read'
// #swagger.description = 'The badge. Its own route because it is polled — asking “is there anything new” should not make the server assemble a page of bodies to answer with one integer.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.responses[200] = { description: 'The unread count', content: { "application/json": { schema: { $ref: "#/components/schemas/NotificationUnreadCount" } } } } */
/* #swagger.responses[401] = { description: 'Not authenticated', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
notif.getUnreadCount,
)
notifRouter.post(
'/notifications/read-all',
// #swagger.tags = ['Auth · Me']
// #swagger.summary = 'Mark the callers whole inbox read'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.responses[200] = { description: 'Marked read', content: { "application/json": { schema: { $ref: "#/components/schemas/NotificationReadResult" } } } } */
/* #swagger.responses[401] = { description: 'Not authenticated', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
notif.markAllRead,
)
notifRouter.post(
'/notifications/:id/read',
// #swagger.tags = ['Auth · Me']
// #swagger.summary = 'Mark one inbox item read'
// #swagger.description = 'Idempotent: a second call does not move the timestamp. 404 both when no such item exists and when it belongs to another account — the same answer on purpose, so this cannot be used to ask whether an id is anybodys.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
// #swagger.parameters['id'] = { in: 'path', required: true, schema: { type: 'integer' }, description: 'Notification id (must belong to the caller).' }
/* #swagger.responses[200] = { description: 'Marked read', content: { "application/json": { schema: { $ref: "#/components/schemas/NotificationReadResult" } } } } */
/* #swagger.responses[401] = { description: 'Not authenticated', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[404] = { description: 'No such item for this user', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
param('id').isInt({ min: 1 }),
validate,
notif.markRead,
)
// ── Per-Team preferences (TEAMS.md §6.3, phase 6) ──────────────────────────
//
// The granularity per-stream opt-in cannot express: "I am in five Teams and want