Skip to content

Fix/notif and email - #458

Merged
merenyimiklos merged 44 commits into
mainfrom
fix/notif-and-email
Nov 17, 2026
Merged

merenyimiklos merged 44 commits into
mainfrom
fix/notif-and-email

Conversation

@Dasa122

@Dasa122 Dasa122 commented Nov 15, 2026

Copy link
Copy Markdown
Member

Summary

Reworks notification email end to end: delivery moves to Microsoft Graph app-only sendMail (SMTP kept for local Mailpit), substitution and moved-lesson mail carry the real details, teachers get their own moved-lesson notification, and preferences finally mean what they say — one email toggle, per-role defaults, an honest unsubscribe.

Closes #447
Refs #442

Changes

  • Transport: Microsoft Graph MIME sendMail with an app-only Entra token (cached with skew, one 401 re-mint, Retry-After honoured, per-attempt timeouts, List-Unsubscribe). SMTP remains for dev. New CHRONOS_MAIL_TRANSPORT, CHRONOS_GRAPH_MAILBOX, CHRONOS_MAIL_ENTRA_*; setup runbook in docs/email-setup.md.
  • Email content: substitution and moved-lesson mails gain details/highlights (date, class, subject, period/times, room, teachers, original → new, comment); teacher-addressed substitution and moved-lesson variants; one mailLocale rule so body and chrome never disagree.
  • In-app: notifications persist details/highlights in metadata and render them in the viewer and history; a notification stops being unread once its day has passed (school timezone).
  • Preferences: single emailEnabled channel toggle with role defaults (linked teacher on, everyone else off), announcementEmail opt-in, system messages always delivered; new authenticated /settings/notifications; teachers excluded from student lesson-change mail.
  • Unsubscribe: email only, constant-time token check, logged with the request id; the page and mail footer say system messages still arrive.
  • Admin: teacher email autofilled from the linked account on all three link paths, editable, never overwritten; index on teacher.user_id.
  • Delivery: per-channel queue state (a delivered channel is never re-sent, a disabled one is satisfied), 60 s debounce reset on edits, unconfigured transport is a skip, dead-letters go to Sentry.
  • Review fixes: public substitution endpoints no longer expose teacher.email/userId; per-recipient failure isolation; tolerant notification metadata; CSP allow-forms.

Verification

  • bun run lint
  • bun run typecheck
  • bun run build — if bundler config, routers, or server entrypoints changed
  • Translations added to both apps/iris/public/locales/en/translation.json and apps/iris/public/locales/hu/translation.json — if user-facing text changed
  • Migration generated with bun run db:generate and committed — if the schema changed

…lure

`notifications.previewTest`/`sendTest` answer 403 while
CHRONOS_ENABLE_TEST_NOTIFICATIONS is off, and the dev page showed every
failure as "Failed to render preview". Map a defined FORBIDDEN error to a new
`devNotifications.disabled` message, translated in both locales, and keep the
generic send/render strings for real failures.
…app support

- Added support for highlights in email notifications to improve visibility of key information.
- Introduced dedicated Entra app configuration for SMTP, allowing for separate authentication from the sign-in app.
- Updated notification content builders to include highlights for substitution and moved lesson notifications.
- Enhanced email templates to render highlights and adjust styles based on email accent.
- Improved environment configuration to support new SMTP settings.
- Added new utility functions for building highlights and enriched lesson details.
- Updated styles for email components to accommodate new design requirements.
- Created a new build environment file for kiosk image setup.
Production mail now goes through Graph app-only Mail.Send, chosen with
CHRONOS_MAIL_TRANSPORT=graph, while development keeps the Mailpit SMTP
relay. Both transports mint their Entra token the same way, so the
SMTP-only CHRONOS_SMTP_ENTRA_* variables become the transport-neutral
CHRONOS_MAIL_ENTRA_*.

The Graph transport compiles the message to MIME with nodemailer's
MailComposer, caches its token in the closure with one in-flight mint
shared by concurrent sends, gives every HTTP request a 30 s budget,
retries once on a 401 and reports a 429's Retry-After (seconds or HTTP
date, clamped). A MIME send always lands in the sending mailbox's Sent
Items, so docs/email-setup.md budgets the mailbox for that.

Delivery is tracked per channel: a channel that succeeded is not
repeated on a later attempt, failures log at warning, and a rate-limited
email's hint reaches the queue's backoff.
A pre-split row with `channelsEnabled: false` meant every channel off, but
the settings read merged the defaults over it and the update path raised the
master switch on any channel patch, so an old unsubscribe silently turned
push and in-app back on.

`completePreferences` is now the single read shape (defaults merged, channel
flags resolved, `channelsEnabled` raised) and `applyPreferencesPatch` the
write shape (base resolved first, only patched keys applied). The legacy
unsubscribe page resolves the same flags instead of raising the switch, a
failed FCM initialization dead-letters instead of reporting "no device", the
dev test notification respects `inAppEnabled`, and the preview email carries
the manage link its footer renders.
The prefix check let backslash and tab variants through (`/\evil.com`
collapses to `//evil.com` in the URL parser); resolving the target against
`window.location.origin` and comparing origins rejects them, and `redirect`
is coerced so `?redirect=1` cannot throw the route. The private layout uses
`<Navigate replace>` and the notification settings route prefetches its
query like the other screens.
- document `channelsEnabled` as the ignored legacy master switch on the
  wire schema and note the in-app `BAD_REQUEST` of the test endpoint
- read preferences in the delivery engine and the unsubscribe page via
  `completePreferences`/`applyPreferencesPatch` instead of re-deriving
  the merge and channel flags inline
- cover the unsubscribe write (legacy off row, modern push-on row)
- regenerate the OpenAPI document for the new descriptions
Add teacher_user_id_idx (migration 0030) so getMyTeacher's lookup and the
engine's per-recipient teacher check are index lookups, and export the
teacher-existence SQL fragment from channel-defaults so the engine embeds one
predicate instead of its own EXISTS.

Widen applyPreferencesPatch's base to a partial row and test that the role
defaults are forwarded (the suite fails if they are not), spell out the
'leave the column alone' intent in updateTeacher's set, seed the settings pane
from the server response only, and document the channel defaults by role.
In-app notifications are always recorded again and the channel will be
managed separately, so `inAppEnabled` no longer exists anywhere:

- remove the flag from the wire schema, resolved preferences, channel
  defaults, the settings pane and both locale trees
- the engine inserts the inbox row unconditionally (still behind the
  per-type preference gate); role-aware email defaults and the teacher
  existence subquery are unchanged
- the dev `POST /notifications/test` handler no longer refuses when
  in-app is off, so it always drops a row into the caller's inbox
- the dev send-test form keeps its channel selector, renamed away from
  the removed preference keys
- regenerate the OpenAPI document
Email is now the only notification channel a user can switch off. Push has
no user-facing toggle: it is attempted for every notification the user has
opted into and is managed separately, and a user with no registered device
is satisfied without delivering anything.

- remove `pushEnabled` from the wire schema, resolved preferences, channel
  defaults and the delivery job; `resolveChannelFlags` collapses to
  `resolveEmailEnabled(stored, defaults)` with the same legacy rule
  (`channelsEnabled: false` -> email off, explicit value wins, else role
  default, else true)
- the engine always writes the inbox row and always enqueues the delivery;
  only email is gated, and the queue reads that flag
- the queue starts push as undelivered (always attempted), treats a
  no-device or FCM-not-configured answer as skipped, and keeps a failed FCM
  init retryable; the dead-letter still names only attempted failures
- the dev `POST /notifications/test` handler no longer refuses on a flag:
  it always records the row and queues the job
- the settings pane keeps a single Email row and the `?channel` search
  param accepts `email` only; both locale trees and docs §9 follow
- regenerate the OpenAPI document
Drop the channelDefaults note from the notifications pane and replace the
channel description with a channel-agnostic, role-agnostic line in both
locales.
Persist the email's structured details and highlight chips in the inbox
row's metadata, type the wire shape, and render both in the notification
viewer and history. The substitute-teacher multi-lesson email now emits
one detail row per lesson plus a one-sentence summary instead of a
multi-paragraph body, and the dev mocks carry sample details so the
dev-notifications page exercises the rendering.
updateMovedLesson cancelled the debounced timer before the transaction, so a
rejected reference or a rollback dropped the notification for the move that is
still stored. The dispatch after the reload already cancels and re-arms it.

Also require CHRONOS_NOTIFICATION_DELAY_{SUBSTITUTION,MOVED_LESSON} to be at
least one second, so the debounce window cannot be configured away, and note
the two known limits (process-local timers, remap not touching pending timers).
`moved_lesson` only resolved a cohort audience, so the teachers whose lesson
moved never heard about it — a teacher has no cohort. Mirror the
`substitution` / `substitution_teacher` pair with a `moved_lesson_teacher`
type raised on the same payload at both moved-lesson dispatch sites.

The payload now carries `teacherIds` (linked lesson teachers or the manual
teacher ids), and the new resolver maps them to their user accounts, skipping
teacher rows without a `userId`. The teacher mail gets its own class- and
subject-aware body, title and a details card without the redundant teacher
row; the student `moved_lesson` content and audience are unchanged.
…on-change mail

A teacher-linked account that still carries a cohort_id received the
student copy of `substitution` and `moved_lesson`. The audience resolver
gains an `excludeTeachers` option that drops accounts with a linked
teacher row via the shared `linkedTeacherExists` predicate, and
`resolveAudienceForLessonChange` sets it. The default stays false and
`resolveAudienceByCohortOrAll` is untouched, so announcements and system
messages still reach teachers; the `*_teacher` types keep their own
audiences.
…as passed

Unread now means "today": the list endpoint reports a computed
`read` (read OR created_at before the start of today in
CHRONOS_TIME_ZONE), the unread filter and the unread count apply the
same cutoff, so past-day rows no longer sit in the badge until someone
marks them. The stored column is untouched and no job sweeps it.
The list, relevant and relevant-for-cohort substitution endpoints are
unauthenticated and selected the whole teacher row, so every response
carried the substituter's email and linked user id. Select only the
columns the timetable displays and type the field with
publicTeacherSchema.
- engine: a per-recipient failure is logged and skipped instead of
  aborting the whole dispatch; the summary reports delivered/audience.
- queue: an unconfigured transport is a skip, not a retryable failure,
  for email as well as push; dead-lettered jobs are logged at error level
  with the attempted channels and sent to Sentry. The channel rules are
  extracted into pure helpers with unit tests.
- smtp: sendEmail takes the recipient name carried on the delivery job,
  so a send costs no per-recipient user.name query; the announcement mail
  label matches the UI (News item / Hír).
- unsubscribe: log the state change with the request id (minted before
  dispatch and echoed on the response), compare the HMAC with
  timingSafeEqual, and state what the preferences patch actually does.
- CSP: allow-forms so the unsubscribe confirm form can post.
- inbox: notification metadata is read tolerantly instead of failing the
  whole list on one bad row; the date range uses the school timezone like
  the unread cutoff.
- teacher audiences: one shared teacher-id -> user resolver for the
  substitution and moved-lesson mails.
- env: drop the unused cohort-reselection delay and validate the
  remaining delays as non-negative integers; type the preferences column
  default as partial JSONB.
- AGENTS.md: document both mail transports and the setup doc.
The announcement email description claimed in-app announcements always
appear, but the News item type toggle removes them; it now says the
setting does not affect them (and the en string gains its missing full
stop). The unsubscribe page gets its own error heading instead of
reusing the success title, the error page gets a retry label for a
carried return path, and the dev record hint says what it really does:
the picked record feeds the preview only.
`OutboundMessage.headers` was unvalidated API surface: nodemailer would take a
CR or LF in a name or value as the start of another header. Both transports now
pass headers through `assertSafeHeaders`, so a value built from data (a URL)
cannot inject one.

- Graph: a transport-level failure (DNS, TLS, the 30 s timeout, an abort)
  rejects instead of answering, which escaped as a `TypeError`/`DOMException`
  and broke a caller switching on `status`. It is now a `GraphMailError` with
  `status: 0`.
- Graph: the compiled base64 MIME is checked against `MAX_MIME_BYTES` (4 MiB,
  Graph's write-request body limit) and refused with its real size, instead of
  surfacing as a 413 that names the limit and not the message.
- Entra: a non-JSON or token-less answer no longer escapes as a raw
  `SyntaxError`/`ZodError`. The body is read tolerantly and every failure is the
  framed "Entra token request failed (status): detail" error; `expires_in` is
  still coerced, and a value that is not a number now only drops the expiry
  rather than failing the mint.
- `OUTLOOK_SCOPE` is exported beside `GRAPH_SCOPE` so a caller can name the
  scope both transports use.
`OutboundMessage.headers` had no producer, which is what made it unvalidated
surface with no purpose. Every notification mail sent for a real user now
carries `List-Unsubscribe: <…/unsubscribe?userId=…&token=…>` — the same URL the
footer already links to, built once in `sendEmail`.

There is deliberately no `List-Unsubscribe-Post`: the unsubscribe handler reads
the HMAC from the POST body, which a one-click request would not carry, so only
a link is offered.

docs/email-setup.md no longer claims no such header is sent, records why one
click is not advertised, and documents the new local size refusal and the
`status: 0` network failure.
- An unknown locale (a caller of the package can pass one at runtime) read
  `emailCopy[locale]` as `undefined` and crashed the render; every lookup now
  goes through `copyFor`, which falls back to `en`.
- `greetingFor` substitutes the name with a function replacer, so a `$&`, ``$` ``
  or `$'` in a recipient name stays literal instead of being read as a
  replacement pattern.
- Body paragraphs and detail rows are keyed by index: a repeated paragraph or a
  detail label that occurs twice (real payloads have both) produced duplicate
  React keys. Highlights are trimmed and empty ones dropped before the existing
  dedupe/cap.
…mplate

- New `entra.test.ts`: a JSON failure carries the status and Entra's own code, a
  non-JSON one still reports the status, a 200 without `access_token` is framed,
  a string `expires_in` is coerced, the tenant id is URL-encoded in the path, and
  the default scope is the Outlook one while Graph asks for its own.
- `graph.test.ts`: a token expiring inside the 60 s skew is not reused, two
  concurrent sends share one mint, a failed mint does not poison the cache, the
  two attempts get separate abort signals, a transport-level failure reports
  `status: 0`, a CR/LF header and an oversized MIME are refused before the
  network, the token request carries the Graph scope, and the 403/429/502 cases
  now assert sendMail was called exactly once (only a 401 is retried).
- `email-layout.test.ts` is `notification.test.tsx`, which is what it tests:
  the hero lead and body paragraphs, empty content, highlight dedupe/cap,
  detail rows with a repeated label, the hu labels, the literal name, the
  plain-text part, the footer separator, and the layout itself.
…tyId

- `channelsEnabled` says a stored `false` still forces email off, beating the
  role default; `emailEnabled` gets the description it was missing.
- `entityId` is described, and the preview route names the types Chronos
  actually resolves (`substitution`, `substitution_teacher`, `moved_lesson`,
  `moved_lesson_teacher`, `announcement`, `system_message`, `blog_post`) instead
  of "the real substitution, moved lesson or news record".
- The detail `{label, value}` schema points at `EmailDetail` in `packages/mail`:
  the same row shape declared twice on purpose (no shared package), so the two
  have to change together.

Generated OpenAPI regenerated with `bun run openapi:generate`.
A system message is a notice the school addresses to a class, so the
recipient must not be able to opt out of it. `system_message` now bypasses
both preference gates in the delivery engine: the per-type
`systemMessage` flag (and a legacy `channelsEnabled: false` row) cannot
suppress the in-app row, and neither can suppress the email leg.

Both decisions are pure helpers in utils/notifications/types.ts
(`isNotificationAllowed`, `resolveEmailAllowed`) so they are unit-testable
without a database or the environment; the engine passes the record it
already completed.

The preference stays in the wire contract but is documented as ignored,
and the settings UI renders it checked and disabled with a description in
both locales. The unsubscribe page, the Chronos HTML pages and the mail
footer now say system messages are still delivered.
@filc-preview-vm

filc-preview-vm Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

🗑️ Preview removed

Environment pr-458.preview.filc.petrik.hu
Commit 3286709
URL https://pr-458.preview.filc.petrik.hu
Edge check —

Posted by filc-deployer. The preview database is its own container and is
destroyed when this pull request closes.

@merenyimiklos merenyimiklos left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Az FCM-küldés sikertelen eredménye nem lehet sikeres kézbesítés

Fájl: apps/chronos/src/utils/notifications/providers/fcm.ts (111–143. sor)

Probléma: A sendEachForMulticast() válasza eszközönként jelzi a kézbesítés sikerét vagy hibáját, a sendPush() mégis { ok: true } értékkel tér vissza akkor is, ha egyik eszközre sem sikerült elküldeni az értesítést. Az új queue ezt teljesített push-csatornának jelöli, így nem történik újrapróbálkozás.

Kért módosítás: A response.successCount, response.failureCount és az egyes responses hibakódjai alapján határozd meg a valódi eredményt. Az érvénytelen tokeneket továbbra is töröld, az átmeneti hibáknál maradjon lehetőség újrapróbálkozásra. Részleges siker esetén ne küldjük újra a már sikeresen értesített eszközökre ugyanazt a push-t. Legyen teszt teljes sikertelenségre, részleges sikerre és kizárólag érvénytelen tokenekre.

Miért fontos? Egy Firebase-hiba miatt az értesítés végleg elveszhet, miközben a kézbesítési sor sikeresnek tekinti.

[P2] A beállítások mentése ne írja felül a frissebb szerverállapotot

Fájl: apps/iris/src/components/settings/notifications-pane.tsx (94–101. és 232–235. sor)

Probléma: A setPrefs((current) => current ?? seed) egyszer inicializálja a lokális állapotot. Ha az értesítési beállítások időközben másik eszközön, másik megnyitott felületen vagy leiratkozással változnak, a panel régi értékeket tartalmazhat. A Mentés gomb az egész prefs objektumot elküldi, ezért a friss szerveroldali módosításokat visszaírhatja a régi értékekre.

Kért módosítás: Kövesd külön a felhasználó által módosított mezőket, és mentéskor csak ezeket küldd a PATCH endpointnak; alternatívaként gondoskodj a háttérben frissülő szerveradatok és a még nem mentett lokális módosítások biztonságos összeolvasztásáról. Teszteld azt az esetet is, amikor az egyik felületen letiltják az e-mailt, miközben egy másik megnyitott panelen egy értesítéstípus kapcsolóját módosítják és mentik.

Miért fontos? A felhasználó tudta nélkül ismét bekapcsolódhatnak olyan értesítések, amelyeket korábban letiltott.

[P2] Tartsuk tiszteletben a Microsoft Graph Retry-After válaszát

Fájl: packages/mail/src/graph.ts (81–102. sor)

Probléma: A Retry-After értékét a MAX_RETRY_AFTER_MS = 60_000 korlátozza. Ha a Graph például 300 másodperc várakozást kér, a queue már 60 másodperc után újrapróbálkozhat.

Kért módosítás: A Graph által küldött érvényes Retry-After időt ne rövidítsd le. Ha szükséges védőkorlát, akkor azt külön, explicit kézbesítési politikaként kezeld; hosszú várakozásnál érdemes tartósan ütemezett retry-t használni. Teszteld a másodperc és HTTP-dátum formátumot, valamint a 60 másodpercnél hosszabb késleltetést is.

Miért fontos? A túl korai újrapróbálkozás újabb 429-es választ okozhat, és a kézbesítés a retry-keret kimerülésével végleg meghiúsulhat.

[P3] Az „Olvasatlanként megjelölés” művelet jelenleg félrevezető

Fájlok: apps/iris/src/components/notification-history-dialog.tsx (213–230. sor) és apps/iris/src/components/notification-viewer-dialog.tsx (103–118. sor)

Probléma: Az olvasott értesítés gombja markUnread címkét és erre utaló ikont kap, de kattintásra továbbra is markReadMutation fut. A backend jelenleg csak read: true értéket állít be.

Kért módosítás: Vagy vezess be tényleges „olvasatlanná jelölés” API-műveletet, és ezt kösd a gombhoz (a napi lejárati szabállyal összhangban), vagy az olvasott értesítéseknél ne jelenjen meg nem működő visszaállítási lehetőség. A címke, az ikon és a művelet ugyanazt jelentse.

Miért fontos? A felhasználónak a felület olyan funkciót ígér, amelyet a kattintás nem hajt végre.

The multicast batch response was never inspected, so a push that failed
on every device still reported success and the delivery queue marked the
channel satisfied. Interpret the per-device responses in a pure helper:
partial success satisfies the channel (no duplicate push to the devices
that already got it), an all-dead-token batch is terminal after the
tokens are deleted, and a transient failure stays retryable.

Isolate the invalid-token cleanup from the outcome so a database failure
there cannot turn a delivered push into a retry, and log dead-token-only
batches at info instead of warning.
The 60 s clamp made the queue resend four minutes before a
`Retry-After: 300` ran out, earning another 429 and spending the retry
budget. Report the parsed hint as-is (both the seconds and HTTP-date
forms, lower bound 0) and let the consumer decide.

The queue no longer sleeps inline between attempts: it schedules the
retry with a timer and re-enqueues the same job, so a long hint delays
that notification only instead of parking the whole batch. The schedule
is in memory, so a restart inside the window drops the pending attempt.
The pane seeded its state once and posted the whole object, so saving a
stale panel reverted a preference changed on another device or through
the unsubscribe link. Send only the keys the user touched (the endpoint
already merges a partial body server-side) and disable Save while
nothing is dirty.

A key re-toggled while its own save is in flight keeps its local value
and stays dirty, and untouched keys adopt the server's merged record.
A read notification offered a "Mark as unread" label and icon that ran
the mark-read mutation, and the viewer offered "Mark as read" for a
notification it had just auto-marked. There is no mark-unread endpoint
and read state is derived from the day the notification was created, so
the history row now offers mark-read for unread rows only and the
viewer keeps only its cohort action. Remove the now-unused key from both
locales and skip the empty footer.
One React-free package owns the i18next instance, the locale rule behind
createTranslator, the mail date and period formatters, and the en/hu
notifications namespace. Keys are typed through CustomTypeOptions, so a
missing key fails tsc, and a parity test pins both locales to the same
set. Workspaces resolve it through bun's workspace protocol.
…upe delivery

Substitution, moved-lesson, announcement, system-message, blog,
door-lock and test copy, the mail chrome and the per-type labels move
into the catalogue; the hand-written bilingual branches and the four
label maps are gone.

Adjacent refactors from the same review: one preferences read per
recipient, one unread-cutoff helper, Drizzle exists instead of raw SQL,
one test-endpoint guard, a shared teacher-email seed, a compile-time
EmailDetail guard, the retry wait capped at 15 minutes, retries
scheduled instead of slept, uniqueStrings extracted, and the room text
joined without slicing. Provider and scheduler tests cover the delivery
paths.
One reducer owns the notification preferences and their dirty set, with
the save merge covered by tests. The one-entry channel framework, the
hand-written notification type array and the duplicated highlight chips
are gone; the auth routes share one redirect schema (open-redirect guard
tested), the notifications route uses the house title effect, and the
language autosave no longer writes the unrelated group display.
@filc-preview-vm
filc-preview-vm Bot temporarily deployed to preview-pr-458 November 17, 2026 12:30 Destroyed
@merenyimiklos
merenyimiklos merged commit ef8b226 into main Nov 17, 2026
6 checks passed
@merenyimiklos
merenyimiklos deleted the fix/notif-and-email branch November 17, 2026 19:51
@github-project-automation github-project-automation Bot moved this from In review to Done in Filc Issue Tracker Nov 17, 2026

This branch was successfully deployed

No deployments
preview-pr-458 — 3286709c Deployed Nov 17, 2026 by filc-preview-vm[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

Email küldés

3 participants