From 988e9eef91303300a18b6ceb5c363b4d2e13c821 Mon Sep 17 00:00:00 2001 From: Dasa122 Date: Tue, 10 Nov 2026 23:08:30 +0100 Subject: [PATCH 01/44] fix(iris): report disabled test notifications instead of a render failure `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. --- apps/iris/public/locales/en/translation.json | 3 +- apps/iris/public/locales/hu/translation.json | 3 +- apps/iris/src/hooks/dev-notifications.ts | 37 ++++++++++++++++--- .../_private/admin/dev/notifications.tsx | 10 ++++- 4 files changed, 44 insertions(+), 9 deletions(-) diff --git a/apps/iris/public/locales/en/translation.json b/apps/iris/public/locales/en/translation.json index 2baed0aa..13386e03 100644 --- a/apps/iris/public/locales/en/translation.json +++ b/apps/iris/public/locales/en/translation.json @@ -606,7 +606,8 @@ "sendAllSuccess": "Sample sent for every type", "sendSuccess": "Test sent via: {{channels}}", "sendError": "Failed to send test notification", - "previewError": "Failed to render preview" + "previewError": "Failed to render preview", + "disabled": "Test notifications are disabled on this server (set CHRONOS_ENABLE_TEST_NOTIFICATIONS=true and restart Chronos)" }, "teachers": { "title": "Teachers", diff --git a/apps/iris/public/locales/hu/translation.json b/apps/iris/public/locales/hu/translation.json index 23a34e42..257c0067 100644 --- a/apps/iris/public/locales/hu/translation.json +++ b/apps/iris/public/locales/hu/translation.json @@ -606,7 +606,8 @@ "sendAllSuccess": "Minden típushoz elküldve a minta", "sendSuccess": "Teszt elküldve: {{channels}}", "sendError": "Nem sikerült elküldeni a teszt értesítést", - "previewError": "Nem sikerült renderelni az előnézetet" + "previewError": "Nem sikerült renderelni az előnézetet", + "disabled": "A teszt értesítések ki vannak kapcsolva ezen a szerveren (állítsd be: CHRONOS_ENABLE_TEST_NOTIFICATIONS=true, és indítsd újra a Chronost)" }, "teachers": { "title": "Tanárok", diff --git a/apps/iris/src/hooks/dev-notifications.ts b/apps/iris/src/hooks/dev-notifications.ts index 9df476f2..43249e6e 100644 --- a/apps/iris/src/hooks/dev-notifications.ts +++ b/apps/iris/src/hooks/dev-notifications.ts @@ -1,5 +1,6 @@ import { notificationTypeValues } from '@filcdev/api/domains/notifications'; - +import { ERROR_CODE } from '@filcdev/api/errors'; +import { isDefinedError } from '@orpc/client'; import { useMutation } from '@tanstack/react-query'; import { useTranslation } from 'react-i18next'; import { toast } from 'sonner'; @@ -128,6 +129,22 @@ type PreviewTestPayload = Parameters[0]; type MutationCallbacks = { silent?: boolean }; +/** + * `sendTest`/`previewTest` answer 403 when the server has + * `CHRONOS_ENABLE_TEST_NOTIFICATIONS` off. Report that instead of a generic + * send/render failure, which reads like a bug in the template. + * + * Generic so a typed mutation error and an `unknown` catch variable both fit: + * `isDefinedError` only narrows a known error union. + */ +export const describeTestNotificationError = ( + error: T, + message: { disabled: string; fallback: string } +) => + isDefinedError(error) && error.code === ERROR_CODE.FORBIDDEN + ? message.disabled + : message.fallback; + /** Send a dev-only test notification with granular channel options. */ export function useSendTestNotification({ silent = false, @@ -135,9 +152,14 @@ export function useSendTestNotification({ const { t } = useTranslation(); return useMutation( orpc.notifications.sendTest.mutationOptions({ - onError: () => { + onError: (error) => { if (!silent) { - toast.error(t('devNotifications.sendError')); + toast.error( + describeTestNotificationError(error, { + disabled: t('devNotifications.disabled'), + fallback: t('devNotifications.sendError'), + }) + ); } }, onSuccess: (data) => { @@ -168,8 +190,13 @@ export function usePreviewTestNotification() { return useMutation({ mutationFn: async (payload: PreviewTestPayload) => (await api.notifications.previewTest(payload)).html, - onError: () => { - toast.error(t('devNotifications.previewError')); + onError: (error) => { + toast.error( + describeTestNotificationError(error, { + disabled: t('devNotifications.disabled'), + fallback: t('devNotifications.previewError'), + }) + ); }, }); } diff --git a/apps/iris/src/routes/_private/admin/dev/notifications.tsx b/apps/iris/src/routes/_private/admin/dev/notifications.tsx index 6d601570..8a98283d 100644 --- a/apps/iris/src/routes/_private/admin/dev/notifications.tsx +++ b/apps/iris/src/routes/_private/admin/dev/notifications.tsx @@ -24,6 +24,7 @@ import { useTranslation } from 'react-i18next'; import { toast } from 'sonner'; import { PermissionGuard } from '@/components/util/permission-guard'; import { + describeTestNotificationError, NOTIFICATION_MOCKS, NOTIFICATION_TYPES, usePreviewTestNotification, @@ -145,8 +146,13 @@ function DevNotificationsPage() { }) ); toast.success(t('devNotifications.sendAllSuccess')); - } catch { - toast.error(t('devNotifications.sendError')); + } catch (error) { + toast.error( + describeTestNotificationError(error, { + disabled: t('devNotifications.disabled'), + fallback: t('devNotifications.sendError'), + }) + ); } }; From 53c07eb73799ba9928c29f21d158398e2b88b513 Mon Sep 17 00:00:00 2001 From: Dasa122 Date: Wed, 11 Nov 2026 00:07:35 +0100 Subject: [PATCH 02/44] feat(mail): render an optional details block in notification emails --- .../chronos/src/utils/notifications/engine.ts | 1 + .../src/utils/notifications/providers/smtp.ts | 7 +++- apps/chronos/src/utils/notifications/queue.ts | 1 + apps/chronos/src/utils/notifications/types.ts | 4 ++ packages/mail/src/index.ts | 1 + packages/mail/src/templates/notification.tsx | 39 +++++++++++++++++-- packages/mail/src/templates/styles.ts | 33 ++++++++++++++++ packages/mail/src/templates/types.ts | 4 ++ 8 files changed, 85 insertions(+), 5 deletions(-) diff --git a/apps/chronos/src/utils/notifications/engine.ts b/apps/chronos/src/utils/notifications/engine.ts index 89a2479d..cb9ad0e0 100644 --- a/apps/chronos/src/utils/notifications/engine.ts +++ b/apps/chronos/src/utils/notifications/engine.ts @@ -261,6 +261,7 @@ async function fireNotification( enqueue({ channelsEnabled, content: content.content, + details: content.details, email: user.email, language: user.language, notificationId: notif.id, diff --git a/apps/chronos/src/utils/notifications/providers/smtp.ts b/apps/chronos/src/utils/notifications/providers/smtp.ts index 22f18264..4f54325f 100644 --- a/apps/chronos/src/utils/notifications/providers/smtp.ts +++ b/apps/chronos/src/utils/notifications/providers/smtp.ts @@ -1,6 +1,7 @@ import { createHmac } from 'node:crypto'; import { createMailTransport, + type EmailDetail, type MailTransport, renderEmail, type SmtpAuth, @@ -97,7 +98,7 @@ export async function sendEmail( to: string, type: NotificationType, locale: string, - body: { content: string; title: string }, + body: { content: string; details?: EmailDetail[]; title: string }, userId: string ): Promise { const tp = getMailer(); @@ -121,6 +122,7 @@ export async function sendEmail( 'notification', { content: body.content, + details: body.details, locale: lang, recipientName: recipient?.name, title: body.title, @@ -155,13 +157,14 @@ export async function sendEmail( export async function renderPreviewEmail( type: NotificationType, locale: string, - body: { content: string; title: string } + body: { content: string; details?: EmailDetail[]; title: string } ): Promise { const lang = locale === 'en' ? 'en' : 'hu'; const { html } = await renderEmail( 'notification', { content: body.content, + details: body.details, locale: lang, recipientName: lang === 'en' ? 'John Doe' : 'Minta Felhasználó', title: body.title, diff --git a/apps/chronos/src/utils/notifications/queue.ts b/apps/chronos/src/utils/notifications/queue.ts index f032e873..270e885e 100644 --- a/apps/chronos/src/utils/notifications/queue.ts +++ b/apps/chronos/src/utils/notifications/queue.ts @@ -36,6 +36,7 @@ async function processJob(job: DeliveryJob): Promise { job.language, { content: job.content, + details: job.details, title: job.title, }, job.userId diff --git a/apps/chronos/src/utils/notifications/types.ts b/apps/chronos/src/utils/notifications/types.ts index ce685608..f1b39052 100644 --- a/apps/chronos/src/utils/notifications/types.ts +++ b/apps/chronos/src/utils/notifications/types.ts @@ -1,3 +1,5 @@ +import type { EmailDetail } from '@filcdev/mail'; + export type NotificationType = | 'substitution' | 'substitution_teacher' @@ -45,6 +47,7 @@ export type AudienceUser = { export type NotificationContent = { title: string; content: string; + details?: EmailDetail[]; metadata?: Record; }; @@ -70,6 +73,7 @@ export type DeliveryJob = { type: NotificationType; title: string; content: string; + details?: EmailDetail[]; channelsEnabled: boolean; /** Locale the recipient's `buildContent` ran with; the email wrapper uses it too. */ language: string; diff --git a/packages/mail/src/index.ts b/packages/mail/src/index.ts index e1392f60..d7bdcaa5 100644 --- a/packages/mail/src/index.ts +++ b/packages/mail/src/index.ts @@ -9,6 +9,7 @@ import type { export type { Branding, + EmailDetail, Locale, NotificationEmailData, RenderedEmail, diff --git a/packages/mail/src/templates/notification.tsx b/packages/mail/src/templates/notification.tsx index 82ec2ed8..c150e004 100644 --- a/packages/mail/src/templates/notification.tsx +++ b/packages/mail/src/templates/notification.tsx @@ -1,14 +1,29 @@ -import { Button, Text } from '@react-email/components'; +import { Button, Column, Row, Section, Text } from '@react-email/components'; import { EmailLayout } from './email-layout'; import { emailCopy, greetingFor } from './i18n'; import { renderEmailElement } from './render'; -import { buttonStyle, greetingStyle, textStyle } from './styles'; +import { + buttonStyle, + detailLabelCellStyle, + detailLabelStyle, + detailsSectionStyle, + detailValueCellStyle, + detailValueStyle, + greetingStyle, + textStyle, +} from './styles'; import type { Branding, NotificationEmailData, RenderedEmail } from './types'; +const PARAGRAPH_BREAK = /\n+/; + export const renderNotification = ( data: NotificationEmailData, branding: Branding ): Promise => { + const paragraphs = data.content + .split(PARAGRAPH_BREAK) + .filter((paragraph) => paragraph.trim().length > 0); + const element = ( {greetingFor(data.locale, data.recipientName)} - {data.content} + {paragraphs.map((paragraph) => ( + + {paragraph} + + ))} + {data.details?.length ? ( +
+ {data.details.map((detail) => ( + + + {detail.label} + + + {detail.value} + + + ))} +
+ ) : undefined} diff --git a/packages/mail/src/templates/styles.ts b/packages/mail/src/templates/styles.ts index f2f9bce3..cf76c32b 100644 --- a/packages/mail/src/templates/styles.ts +++ b/packages/mail/src/templates/styles.ts @@ -70,6 +70,39 @@ export const textStyle: CSSProperties = { margin: '0 0 16px', }; +export const detailsSectionStyle: CSSProperties = { + borderTop: '1px solid #f0f0f2', + margin: '4px 0 0', + padding: '18px 0 0', +}; + +export const detailLabelStyle: CSSProperties = { + color: '#71717a', + fontSize: '11px', + letterSpacing: '0.04em', + margin: 0, + paddingBottom: 2, + textTransform: 'uppercase', +}; + +export const detailValueStyle: CSSProperties = { + color: '#18181b', + fontSize: '14px', + lineHeight: 1.45, + margin: 0, +}; + +export const detailLabelCellStyle: CSSProperties = { + padding: '0 12px 8px 0', + verticalAlign: 'top', + width: '38%', +}; + +export const detailValueCellStyle: CSSProperties = { + padding: '0 0 8px', + verticalAlign: 'top', +}; + export const buttonStyle: CSSProperties = { backgroundColor: '#0d9488', borderRadius: '26px', diff --git a/packages/mail/src/templates/types.ts b/packages/mail/src/templates/types.ts index 1c05ca85..8d7ec6ee 100644 --- a/packages/mail/src/templates/types.ts +++ b/packages/mail/src/templates/types.ts @@ -1,5 +1,8 @@ export type Locale = 'en' | 'hu'; +/** One label/value row in the optional details block of a notification email. */ +export type EmailDetail = { label: string; value: string }; + export type Branding = { appName: string; appUrl: string; @@ -13,6 +16,7 @@ export type RenderedEmail = { export type NotificationEmailData = { content: string; + details?: EmailDetail[]; locale: Locale; recipientName?: string | null; title: string; From 586bc2e6f0e272919a1ceab83acb4ed00b482f0f Mon Sep 17 00:00:00 2001 From: Dasa122 Date: Wed, 11 Nov 2026 00:07:41 +0100 Subject: [PATCH 03/44] feat(chronos): build substitution and moved-lesson email details and preview real records --- apps/chronos/openapi/chronos-openapi.json | 6 +- .../src/modules/news/_notifications.ts | 102 +++++----- .../modules/notifications/notifications.ts | 136 ++++++++++++- .../src/modules/timetable/_notifications.ts | 179 ++++++++++++++---- .../src/modules/timetable/moved-lesson.ts | 166 ++++++++++++++-- .../src/modules/timetable/substitution.ts | 66 +++---- .../notifications/substitution-teacher.ts | 104 +++++++++- packages/api/src/contract/notifications.ts | 2 +- packages/api/src/domains/notifications.ts | 1 + 9 files changed, 609 insertions(+), 153 deletions(-) diff --git a/apps/chronos/openapi/chronos-openapi.json b/apps/chronos/openapi/chronos-openapi.json index 614e9699..1fc18e8f 100644 --- a/apps/chronos/openapi/chronos-openapi.json +++ b/apps/chronos/openapi/chronos-openapi.json @@ -31610,7 +31610,7 @@ "/notifications/test/preview": { "post": { "operationId": "postNotificationsTestPreview", - "description": "Development helper: render a notification template without sending it (needs CHRONOS_ENABLE_TEST_NOTIFICATIONS)", + "description": "Development helper: render a notification template without sending it (needs CHRONOS_ENABLE_TEST_NOTIFICATIONS). When entityId is given, the real substitution, moved lesson or news record is rendered through the same builders as the live pipeline instead of the supplied text.", "tags": [ "Notifications" ], @@ -31624,6 +31624,10 @@ "content": { "type": "string" }, + "entityId": { + "type": "string", + "format": "uuid" + }, "language": { "enum": [ "en", diff --git a/apps/chronos/src/modules/news/_notifications.ts b/apps/chronos/src/modules/news/_notifications.ts index 42e73ecd..8b09fa72 100644 --- a/apps/chronos/src/modules/news/_notifications.ts +++ b/apps/chronos/src/modules/news/_notifications.ts @@ -1,7 +1,10 @@ import { env } from '#utils/environment'; import { resolveAudienceByCohortOrAll } from '#utils/notifications/engine'; import { isHungarianLocale } from '#utils/notifications/locale'; -import type { NotificationHandler } from '#utils/notifications/types'; +import type { + NotificationContent, + NotificationHandler, +} from '#utils/notifications/types'; /** The payload is the record this module's own handlers dispatch with. */ function byCohortOrAll(payload: unknown) { @@ -9,6 +12,52 @@ function byCohortOrAll(payload: unknown) { return resolveAudienceByCohortOrAll(p.cohortIds); } +export function buildAnnouncementContent( + payload: { title: string }, + locale: string +): NotificationContent { + const title = payload.title || ''; + const prefix = isHungarianLocale(locale) + ? 'Új bejelentés' + : 'New announcement'; + return { + content: `${prefix}: ${title}`, + title: isHungarianLocale(locale) ? 'Új bejelentés' : 'New Announcement', + }; +} + +export function buildSystemMessageContent( + payload: { title: string }, + locale: string +): NotificationContent { + const title = payload.title || ''; + const prefix = isHungarianLocale(locale) ? 'Rendszerüzenet' : 'System notice'; + return { + content: `${prefix}: ${title}`, + title: isHungarianLocale(locale) ? 'Rendszerüzenet' : 'System Message', + }; +} + +export function buildBlogPostContent( + payload: { slug?: string; title: string }, + locale: string +): NotificationContent { + const title = payload.title || ''; + const cta = isHungarianLocale(locale) + ? 'koppints az olvasáshoz' + : 'tap to read'; + const prefix = isHungarianLocale(locale) ? 'Új bejegyzés' : 'New post'; + const content = `${prefix}: ${title} — ${cta}`; + const result: NotificationContent = { + content, + title: isHungarianLocale(locale) ? 'Új blogbejegyzés' : 'New Blog Post', + }; + if (payload.slug) { + result.metadata = { slug: payload.slug }; + } + return result; +} + /** * The notifications the news module owns: an announcement, a system notice and * a published blog post. Each is written in the recipient's language, because @@ -16,63 +65,24 @@ function byCohortOrAll(payload: unknown) { */ export const newsNotifications: readonly NotificationHandler[] = [ { - buildContent: (payload, locale) => { - const p = payload as { title: string }; - const title = p.title || ''; - const prefix = isHungarianLocale(locale) - ? 'Új bejelentés' - : 'New announcement'; - const content = `${prefix}: ${title}`; - return { - content, - title: isHungarianLocale(locale) ? 'Új bejelentés' : 'New Announcement', - }; - }, + buildContent: (payload, locale) => + buildAnnouncementContent(payload as { title: string }, locale), getAudience: byCohortOrAll, getDelay: () => env.notificationDelayAnnouncement, preferenceKey: 'announcement', type: 'announcement', }, { - buildContent: (payload, locale) => { - const p = payload as { title: string }; - const title = p.title || ''; - const prefix = isHungarianLocale(locale) - ? 'Rendszerüzenet' - : 'System notice'; - const content = `${prefix}: ${title}`; - return { - content, - title: isHungarianLocale(locale) ? 'Rendszerüzenet' : 'System Message', - }; - }, + buildContent: (payload, locale) => + buildSystemMessageContent(payload as { title: string }, locale), getAudience: byCohortOrAll, getDelay: () => env.notificationDelaySystemMessage, preferenceKey: 'systemMessage', type: 'system_message', }, { - buildContent: (payload, locale) => { - const p = payload as { title: string; slug?: string }; - const title = p.title || ''; - const cta = isHungarianLocale(locale) - ? 'koppints az olvasáshoz' - : 'tap to read'; - const prefix = isHungarianLocale(locale) ? 'Új bejegyzés' : 'New post'; - const content = `${prefix}: ${title} — ${cta}`; - const result: { - content: string; - title: string; - metadata?: Record; - } = { - content, - title: isHungarianLocale(locale) ? 'Új blogbejegyzés' : 'New Blog Post', - }; - if (p.slug) { - result.metadata = { slug: p.slug }; - } - return result; - }, + buildContent: (payload, locale) => + buildBlogPostContent(payload as { slug?: string; title: string }, locale), getAudience: () => resolveAudienceByCohortOrAll(), getDelay: () => env.notificationDelayBlogPost, preferenceKey: 'blogPost', diff --git a/apps/chronos/src/modules/notifications/notifications.ts b/apps/chronos/src/modules/notifications/notifications.ts index e2094ed5..e52777d7 100644 --- a/apps/chronos/src/modules/notifications/notifications.ts +++ b/apps/chronos/src/modules/notifications/notifications.ts @@ -1,24 +1,45 @@ import { colorSchemeSchema } from '@filcdev/api/domains/theme'; +import { getLogger } from '@logtape/logtape'; import { ORPCError } from '@orpc/server'; import { and, count, desc, eq, sql } from 'drizzle-orm'; import { db } from '#database'; import { user as userTable } from '#database/schema/authentication'; import { requireAuthentication } from '#middleware/auth'; +import { + buildAnnouncementContent, + buildBlogPostContent, + buildSystemMessageContent, +} from '#modules/news/_notifications'; +import { announcement, blogPost, systemMessage } from '#modules/news/schema'; +import { resolveTitle } from '#modules/news/utils/shared'; import { fcmToken, notification, userPreferences, } from '#modules/notifications/schema'; +import { + buildMovedLessonNotificationContent, + buildSubstitutionNotificationContent, +} from '#modules/timetable/_notifications'; +import { loadMovedLessonNotificationPayload } from '#modules/timetable/moved-lesson'; +import { substitution, substitutionLessonMTM } from '#modules/timetable/schema'; import { base } from '#orpc'; import { env } from '#utils/environment'; -import { forbidden, notFound } from '#utils/http'; +import { badRequest, forbidden, notFound } from '#utils/http'; import { sendPush } from '#utils/notifications/providers/fcm'; import { renderPreviewEmail, sendEmail, } from '#utils/notifications/providers/smtp'; import { enqueue } from '#utils/notifications/queue'; -import { DEFAULT_NOTIFICATION_PREFERENCES } from '#utils/notifications/types'; +import { loadSubstitutionTeacherPayload } from '#utils/notifications/substitution-teacher'; +import { + DEFAULT_NOTIFICATION_PREFERENCES, + type NotificationContent, + type NotificationType, +} from '#utils/notifications/types'; + +const logger = getLogger(['chronos', 'notifications', 'preview']); export const listNotifications = base.notifications.list .use(requireAuthentication) @@ -443,6 +464,101 @@ export const sendTestNotification = base.notifications.sendTest return results; }); +/** + * Resolve the content, details and title of a real record for the preview + * endpoint, through the same builders the live pipeline uses. A type with no + * loadable record (or an unsupported one) is refused rather than faked. + */ +async function resolvePreviewContent( + type: NotificationType, + entityId: string, + locale: string +): Promise { + switch (type) { + case 'substitution': { + const [row] = await db + .select() + .from(substitution) + .where(eq(substitution.id, entityId)) + .limit(1); + + if (!row) { + throw notFound('Substitution not found'); + } + + const lessonRows = await db + .select({ lessonId: substitutionLessonMTM.lessonId }) + .from(substitutionLessonMTM) + .where(eq(substitutionLessonMTM.substitutionId, entityId)); + const lessonIds = lessonRows.map((link) => link.lessonId); + + const payload = { + ...(await loadSubstitutionTeacherPayload({ + comment: row.comment, + date: row.date, + lessonIds, + substituter: row.substituter, + })), + lessonIds, + }; + + return buildSubstitutionNotificationContent(payload, locale); + } + case 'moved_lesson': { + const payload = await loadMovedLessonNotificationPayload(entityId); + if (!payload) { + throw notFound('Moved lesson not found'); + } + + return buildMovedLessonNotificationContent(payload, locale); + } + case 'announcement': { + const [row] = await db + .select() + .from(announcement) + .where(eq(announcement.id, entityId)) + .limit(1); + + if (!row) { + throw notFound('Announcement not found'); + } + + return buildAnnouncementContent( + { title: resolveTitle(row.title) }, + locale + ); + } + case 'system_message': { + const [row] = await db + .select() + .from(systemMessage) + .where(eq(systemMessage.id, entityId)) + .limit(1); + + if (!row) { + throw notFound('System message not found'); + } + + return buildSystemMessageContent({ title: row.title }, locale); + } + case 'blog_post': { + const [row] = await db + .select() + .from(blogPost) + .where(eq(blogPost.id, entityId)) + .limit(1); + + if (!row) { + throw notFound('Blog post not found'); + } + + return buildBlogPostContent({ slug: row.slug, title: row.title }, locale); + } + default: + throw badRequest('No records to preview for this notification type'); + } +} + export const previewTestNotification = base.notifications.previewTest .use(requireAuthentication) .handler(async ({ input }) => { @@ -452,6 +568,22 @@ export const previewTestNotification = base.notifications.previewTest ); } + const locale = input.language ?? 'hu'; + + if (input.entityId) { + logger.debug('Rendering preview of {type} record {entityId}', { + entityId: input.entityId, + type: input.type, + }); + const rendered = await resolvePreviewContent( + input.type, + input.entityId, + locale + ); + const html = await renderPreviewEmail(input.type, locale, rendered); + return { html }; + } + const body = input; const subject = body.subject ?? 'Filc test message'; const content = diff --git a/apps/chronos/src/modules/timetable/_notifications.ts b/apps/chronos/src/modules/timetable/_notifications.ts index 1a97cef8..027a63ed 100644 --- a/apps/chronos/src/modules/timetable/_notifications.ts +++ b/apps/chronos/src/modules/timetable/_notifications.ts @@ -1,3 +1,4 @@ +import type { EmailDetail } from '@filcdev/mail'; import { env } from '#utils/environment'; import { resolveAudienceForLessonChange, @@ -5,11 +6,15 @@ import { } from '#utils/notifications/engine'; import { isHungarianLocale } from '#utils/notifications/locale'; import { + buildSubstitutionDetails, buildSubstitutionTeacherContent, resolveSubstituteTeacherAudience, type SubstitutionTeacherPayload, } from '#utils/notifications/substitution-teacher'; -import type { NotificationHandler } from '#utils/notifications/types'; +import type { + NotificationContent, + NotificationHandler, +} from '#utils/notifications/types'; const DAY_NAMES_EN = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']; const DAY_NAMES_HU = ['Hétfő', 'Kedd', 'Szerda', 'Csütörtök', 'Péntek']; @@ -92,7 +97,7 @@ function substitutionContentEn( return `A new substitution has been posted for ${dateStr}.${timetableCta}`; } -function buildSubstitutionContent( +export function buildSubstitutionContent( p: { date?: Date; substituter?: string | null; lessonIds?: string[] }, locale: string ): string { @@ -105,15 +110,31 @@ function buildSubstitutionContent( : substitutionContentEn(dateStr, subName, lessonCount); } +/** + * The complete student-facing `substitution` notification: the one-sentence + * body, the structured details and the title. Shared by the live pipeline and + * the dev preview so both render the same thing. + */ +export function buildSubstitutionNotificationContent( + payload: SubstitutionTeacherPayload & { lessonIds?: string[] }, + locale: string +): NotificationContent { + return { + content: buildSubstitutionContent(payload, locale), + details: buildSubstitutionDetails(payload, locale), + title: isHungarianLocale(locale) ? 'Új helyettesítés' : 'New Substitution', + }; +} + function periodLabel(period: string, locale: string): string { return isHungarianLocale(locale) ? `${period}. óra` : `Period ${period}`; } function movedLessonContentHu( p: { - room?: string; - startingDay?: string; - startingPeriod?: string; + room?: string | null; + startingDay?: string | null; + startingPeriod?: string | null; }, multiple: boolean ): string { @@ -134,9 +155,9 @@ function movedLessonContentHu( function movedLessonContentEn( p: { - room?: string; - startingDay?: string; - startingPeriod?: string; + room?: string | null; + startingDay?: string | null; + startingPeriod?: string | null; }, multiple: boolean ): string { @@ -154,6 +175,106 @@ function movedLessonContentEn( return `Your lesson has been moved to ${location}.${suffix}`; } +export type MovedLessonNotificationSource = { + startingDay?: string | null; + startingPeriod?: string | null; + room?: string | null; +}; + +/** The one-sentence moved-lesson body, shared by the pipeline and the preview. */ +export function buildMovedLessonContent( + payload: MovedLessonNotificationSource & { lessonIds?: string[] }, + locale: string +): string { + const multiple = (payload.lessonIds?.length ?? 0) > 1; + return isHungarianLocale(locale) + ? movedLessonContentHu(payload, multiple) + : movedLessonContentEn(payload, multiple); +} + +/** Everything `buildMovedLessonDetails` reads off a moved lesson. */ +export type MovedLessonDetailsPayload = { + cohortNames: string[]; + comment?: string | null; + date: Date; + original: { + day?: string | null; + period?: number | null; + room?: string | null; + teacherNames: string[]; + }; + subjectNames: string[]; + target: { + day?: string | null; + period?: number | null; + room?: string | null; + }; +}; + +/** Structured label/value rows for the `moved_lesson` email. */ +export function buildMovedLessonDetails( + payload: MovedLessonDetailsPayload, + locale: string +): EmailDetail[] { + const hu = isHungarianLocale(locale); + const { cohortNames, comment, date, original, subjectNames, target } = + payload; + + const label = { + class: hu ? 'Osztály' : 'Class', + comment: hu ? 'Megjegyzés' : 'Comment', + date: hu ? 'Dátum' : 'Date', + original: hu ? 'Eredeti' : 'Original', + subject: hu ? 'Tantárgy' : 'Subject', + target: hu ? 'Új' : 'New', + teacher: hu ? 'Tanár' : 'Teacher', + }; + + const location = ( + day: string | null | undefined, + period: number | null | undefined, + room: string | null | undefined + ): string => + [ + day ? dayName(day, locale) : '', + period == null ? '' : periodLabel(String(period), locale), + room ?? '', + ] + .filter(Boolean) + .join(', '); + + const rows: EmailDetail[] = [ + { label: label.date, value: formatDate(date, locale) }, + { label: label.class, value: cohortNames.join(', ') }, + { label: label.subject, value: subjectNames.join(', ') }, + { + label: label.original, + value: location(original.day, original.period, original.room), + }, + { + label: label.target, + value: location(target.day, target.period, target.room), + }, + { label: label.teacher, value: original.teacherNames.join(', ') }, + { label: label.comment, value: comment?.trim() ?? '' }, + ]; + + return rows.filter((row) => row.value.length > 0); +} + +/** The complete moved-lesson notification, shared by the pipeline and preview. */ +export function buildMovedLessonNotificationContent( + payload: MovedLessonNotificationSource & + MovedLessonDetailsPayload & { lessonIds?: string[] }, + locale: string +): NotificationContent { + return { + content: buildMovedLessonContent(payload, locale), + details: buildMovedLessonDetails(payload, locale), + title: isHungarianLocale(locale) ? 'Áthelyezett óra' : 'Moved Lesson', + }; +} + /** * The notifications the timetable owns. A substitution or a moved lesson goes * to the cohorts that own the affected lessons, the substitute is told what @@ -163,19 +284,11 @@ function movedLessonContentEn( */ export const timetableNotifications: readonly NotificationHandler[] = [ { - buildContent: (payload, locale) => { - const p = payload as { - date?: Date; - substituter?: string | null; - lessonIds?: string[]; - }; - return { - content: buildSubstitutionContent(p, locale), - title: isHungarianLocale(locale) - ? 'Új helyettesítés' - : 'New Substitution', - }; - }, + buildContent: (payload, locale) => + buildSubstitutionNotificationContent( + payload as SubstitutionTeacherPayload & { lessonIds?: string[] }, + locale + ), getAudience: (payload) => resolveAudienceForLessonChange(payload), getDelay: () => env.notificationDelaySubstitution, preferenceKey: 'substitution', @@ -194,24 +307,12 @@ export const timetableNotifications: readonly NotificationHandler[] = [ type: 'substitution_teacher', }, { - buildContent: (payload, locale) => { - const p = payload as { - cohortIds?: string[]; - date?: Date; - lessonIds?: string[]; - room?: string; - startingDay?: string; - startingPeriod?: string; - }; - const multiple = (p.lessonIds?.length ?? 0) > 1; - const content = isHungarianLocale(locale) - ? movedLessonContentHu(p, multiple) - : movedLessonContentEn(p, multiple); - return { - content, - title: isHungarianLocale(locale) ? 'Áthelyezett óra' : 'Moved Lesson', - }; - }, + buildContent: (payload, locale) => + buildMovedLessonNotificationContent( + payload as MovedLessonDetailsPayload & + MovedLessonNotificationSource & { lessonIds?: string[] }, + locale + ), getAudience: (payload) => resolveAudienceForLessonChange(payload), getDelay: () => env.notificationDelayMovedLesson, preferenceKey: 'movedLesson', diff --git a/apps/chronos/src/modules/timetable/moved-lesson.ts b/apps/chronos/src/modules/timetable/moved-lesson.ts index 916f6f0c..62e94987 100644 --- a/apps/chronos/src/modules/timetable/moved-lesson.ts +++ b/apps/chronos/src/modules/timetable/moved-lesson.ts @@ -576,6 +576,139 @@ async function attachEnrichedLessons(rows: MovedLessonRow[]) { }); } +/** Everything the moved-lesson email builders read off one moved lesson. */ +export type MovedLessonNotificationPayload = { + cohortIds: string[]; + cohortNames: string[]; + comment: string | null; + date: Date; + lessonIds: string[]; + original: { + day: string | null; + period: number | null; + room: string | null; + subject: string | null; + teacherNames: string[]; + }; + room: string | null; + startingDay: string | null; + startingPeriod: string | null; + subjectNames: string[]; + target: { + day: string | null; + period: number | null; + room: string | null; + }; +}; + +const uniqueNames = (values: (string | null | undefined)[]): string[] => [ + ...new Set(values.filter((value): value is string => !!value)), +]; + +type EnrichedMovedLesson = Awaited< + ReturnType +>[number]; + +/** The audience cohort ids and their display names for one moved lesson. */ +function movedLessonCohorts(enriched: EnrichedMovedLesson): { + cohortIds: string[]; + cohortNames: string[]; +} { + if (enriched.manual) { + return { + cohortIds: enriched.movedLesson.manualCohortIds, + cohortNames: uniqueNames(enriched.manual.cohorts.map((c) => c.name)), + }; + } + + return { + cohortIds: enriched.lessons.flatMap((l) => l.cohorts.map((c) => c.id)), + cohortNames: uniqueNames( + enriched.lessons.flatMap((l) => l.cohorts.map((c) => c.name)) + ), + }; +} + +/** + * Load one moved lesson with the same enriched relations the list endpoint + * uses, shaped for the notification builders. Returns null when the row no + * longer exists. + */ +export async function loadMovedLessonNotificationPayload( + movedLessonId: string +): Promise { + const [row] = await db + .select({ + classroom, + dayDefinition, + lessons: sql`COALESCE( + ARRAY_AGG(DISTINCT ${movedLessonLessonMTM.lessonId}) FILTER (WHERE ${movedLessonLessonMTM.lessonId} IS NOT NULL), + ARRAY[]::text[] + )`.as('lessons'), + movedLesson, + period, + }) + .from(movedLesson) + .leftJoin(period, eq(movedLesson.startingPeriod, period.id)) + .leftJoin(dayDefinition, eq(movedLesson.startingDay, dayDefinition.id)) + .leftJoin(classroom, eq(movedLesson.room, classroom.id)) + .leftJoin( + movedLessonLessonMTM, + eq(movedLesson.id, movedLessonLessonMTM.movedLessonId) + ) + .where(eq(movedLesson.id, movedLessonId)) + .groupBy(movedLesson.id, period.id, dayDefinition.id, classroom.id); + + if (!row) { + return null; + } + + const [enriched] = await attachEnrichedLessons([row]); + if (!enriched) { + return null; + } + + const lessonRow = enriched.movedLesson; + const lessons = enriched.lessons; + const manual = enriched.manual; + const firstLesson = lessons[0]; + + const { cohortIds, cohortNames } = movedLessonCohorts(enriched); + const subjectNames = manual + ? uniqueNames([manual.subject?.name]) + : uniqueNames(lessons.map((l) => l.subject?.name)); + const teacherNames = manual + ? uniqueNames(manual.teachers.map((t) => t.name)) + : uniqueNames(lessons.flatMap((l) => l.teachers.map((t) => t.name))); + const originalRooms = manual + ? uniqueNames([manual.sourceRoom?.name]) + : uniqueNames(lessons.flatMap((l) => l.classrooms.map((c) => c.name))); + + return { + cohortIds, + cohortNames, + comment: lessonRow.comment, + date: lessonRow.date, + lessonIds: lessons.map((l) => l.id), + original: { + day: manual ? null : (firstLesson?.day?.name ?? null), + period: manual ? null : (firstLesson?.period?.period ?? null), + room: originalRooms.join(', ') || null, + subject: subjectNames.join(', ') || null, + teacherNames, + }, + room: lessonRow.room, + startingDay: lessonRow.startingDay, + startingPeriod: lessonRow.startingPeriod, + subjectNames, + target: { + day: enriched.dayDefinition?.name ?? null, + period: enriched.period?.period ?? null, + room: enriched.classroom?.name ?? null, + }, + }; +} + export const getAllMovedLessons = base.timetable.movedLessons.list.handler( async () => { const movedLessons = await db @@ -822,14 +955,16 @@ export const createMovedLesson = base.timetable.movedLessons.create return row; }); - dispatchPendingNotification(newMovedLesson.id, 'moved_lesson', { - cohortIds: manualValues.manualCohortIds, - date: newMovedLesson.date, - lessonIds: lessonIds ?? [], - room: newMovedLesson.room, - startingDay: newMovedLesson.startingDay, - startingPeriod: newMovedLesson.startingPeriod, - }); + const notificationPayload = await loadMovedLessonNotificationPayload( + newMovedLesson.id + ); + if (notificationPayload) { + dispatchPendingNotification( + newMovedLesson.id, + 'moved_lesson', + notificationPayload + ); + } return newMovedLesson; }); @@ -884,7 +1019,6 @@ export const updateMovedLesson = base.timetable.movedLessons.update ).map(({ lessonId }) => lessonId); const { - effectiveLessonIds, effectiveManualCohortIds, effectiveManualSourceRoomId, effectiveManualSubjectId, @@ -968,16 +1102,10 @@ export const updateMovedLesson = base.timetable.movedLessons.update // deleted via ON DELETE SET NULL leaves `manualSubjectId` null while the // cohorts (and therefore the audience) remain. `createMovedLesson` passes // `manualCohortIds` unconditionally for the same reason. - dispatchPendingNotification(id, 'moved_lesson', { - cohortIds: hasManualFields(updatedMovedLesson) - ? updatedMovedLesson.manualCohortIds - : [], - date: updatedMovedLesson.date, - lessonIds: effectiveLessonIds, - room: updatedMovedLesson.room, - startingDay: updatedMovedLesson.startingDay, - startingPeriod: updatedMovedLesson.startingPeriod, - }); + const notificationPayload = await loadMovedLessonNotificationPayload(id); + if (notificationPayload) { + dispatchPendingNotification(id, 'moved_lesson', notificationPayload); + } return updatedMovedLesson; }); diff --git a/apps/chronos/src/modules/timetable/substitution.ts b/apps/chronos/src/modules/timetable/substitution.ts index 96a1dba5..6e743316 100644 --- a/apps/chronos/src/modules/timetable/substitution.ts +++ b/apps/chronos/src/modules/timetable/substitution.ts @@ -525,21 +525,19 @@ export const createSubstitution = base.timetable.substitutions.create { isolationLevel: 'serializable' } ); - dispatchPendingNotification(result.id, 'substitution', { - date: result.date, - lessonIds, - substituter, - }); - - dispatchPendingNotification( - result.id, - 'substitution_teacher', - await loadSubstitutionTeacherPayload({ + const payload = { + ...(await loadSubstitutionTeacherPayload({ + comment, date: result.date, lessonIds, substituter, - }) - ); + })), + comment, + lessonIds, + }; + + dispatchPendingNotification(result.id, 'substitution', payload); + dispatchPendingNotification(result.id, 'substitution_teacher', payload); return result; }); @@ -826,21 +824,19 @@ export const createManualSubstitution = base.timetable.substitutions.manual { isolationLevel: 'serializable' } ); - dispatchPendingNotification(result.id, 'substitution', { - date: result.date, - lessonIds: [manualLessonId], - substituter, - }); - - dispatchPendingNotification( - result.id, - 'substitution_teacher', - await loadSubstitutionTeacherPayload({ + const payload = { + ...(await loadSubstitutionTeacherPayload({ + comment, date: result.date, lessonIds: [manualLessonId], substituter, - }) - ); + })), + comment, + lessonIds: [manualLessonId], + }; + + dispatchPendingNotification(result.id, 'substitution', payload); + dispatchPendingNotification(result.id, 'substitution_teacher', payload); return result; }); @@ -970,21 +966,19 @@ export const updateSubstitution = base.timetable.substitutions.update 'substituter' in body ? body.substituter : existing.substituter; const updatedDate = body.date ?? existing.date; - dispatchPendingNotification(id, 'substitution', { - date: updatedDate, - lessonIds: updatedLessonIds, - substituter: updatedSubstituter, - }); - - dispatchPendingNotification( - id, - 'substitution_teacher', - await loadSubstitutionTeacherPayload({ + const payload = { + ...(await loadSubstitutionTeacherPayload({ + comment: updatedSubstitution.comment, date: updatedDate, lessonIds: updatedLessonIds, substituter: updatedSubstituter, - }) - ); + })), + comment: updatedSubstitution.comment, + lessonIds: updatedLessonIds, + }; + + dispatchPendingNotification(id, 'substitution', payload); + dispatchPendingNotification(id, 'substitution_teacher', payload); return updatedSubstitution; }); diff --git a/apps/chronos/src/utils/notifications/substitution-teacher.ts b/apps/chronos/src/utils/notifications/substitution-teacher.ts index 2644bc42..6b95b429 100644 --- a/apps/chronos/src/utils/notifications/substitution-teacher.ts +++ b/apps/chronos/src/utils/notifications/substitution-teacher.ts @@ -1,3 +1,4 @@ +import type { EmailDetail } from '@filcdev/mail'; import { eq, inArray } from 'drizzle-orm'; import { db } from '#database'; import { user as userTable } from '#database/schema/authentication'; @@ -31,10 +32,14 @@ export type SubstitutionTeacherLesson = { /** Payload carrying everything needed to notify the substitute teacher. */ export type SubstitutionTeacherPayload = { + /** Optional note the substitution was created with. */ + comment?: string | null; date: Date; lessons: SubstitutionTeacherLesson[]; /** The substitute teacher id. */ substituter: string | null; + /** The substitute teacher's display name, resolved by the loader. */ + substituterName: string | null; }; /** "07:10:00" -> "07:10"; anything else -> null. */ @@ -63,20 +68,18 @@ const periodLabel = (periodNo: number | null, hu: boolean): string => { * and replaced teacher(s). */ export async function loadSubstitutionTeacherPayload(args: { + comment?: string | null; date: Date; lessonIds: string[]; substituter: string | null | undefined; }): Promise { - const { date, lessonIds, substituter } = args; + const { comment, date, lessonIds, substituter } = args; + const substituterId = substituter ?? null; const lessons = lessonIds.length ? await db.select().from(lesson).where(inArray(lesson.id, lessonIds)) : []; - if (lessons.length === 0) { - return { date, lessons: [], substituter: substituter ?? null }; - } - const subjectIds = [...new Set(lessons.map((l) => l.subjectId))].filter( (id): id is string => id != null ); @@ -89,9 +92,12 @@ export async function loadSubstitutionTeacherPayload(args: { ]; const periodIds = [...new Set(lessons.map((l) => l.periodId))]; const teacherIds = [ - ...new Set( - lessons.flatMap((l) => (Array.isArray(l.teacherIds) ? l.teacherIds : [])) - ), + ...new Set([ + ...lessons.flatMap((l) => + Array.isArray(l.teacherIds) ? l.teacherIds : [] + ), + ...(substituterId ? [substituterId] : []), + ]), ]; const [subjects, classrooms, periods, teachers, cohortRows] = @@ -150,7 +156,15 @@ export async function loadSubstitutionTeacherPayload(args: { }; }); - return { date, lessons: lessonDetails, substituter: substituter ?? null }; + return { + comment: comment ?? null, + date, + lessons: lessonDetails, + substituter: substituterId, + substituterName: substituterId + ? (teacherMap.get(substituterId) ?? null) + : null, + }; } /** Resolve the linked user (and thus email) of the substitute teacher. */ @@ -292,3 +306,75 @@ export function buildSubstitutionTeacherContent( title, }; } + +const uniqueStrings = (values: (string | null | undefined)[]): string[] => [ + ...new Set(values.filter((value): value is string => !!value)), +]; + +/** + * Build the structured label/value rows for the student-facing `substitution` + * email. Every row is optional: a row whose value is empty is omitted. + */ +export function buildSubstitutionDetails( + payload: SubstitutionTeacherPayload, + locale: string +): EmailDetail[] { + const hu = isHungarianLocale(locale); + const { comment, date, lessons, substituter, substituterName } = payload; + + const label = { + cancelled: hu ? 'Lemarad' : 'Cancelled', + class: hu ? 'Osztály' : 'Class', + comment: hu ? 'Megjegyzés' : 'Comment', + date: hu ? 'Dátum' : 'Date', + lesson: hu ? 'Óra' : 'Lesson', + room: hu ? 'Terem' : 'Room', + subject: hu ? 'Tantárgy' : 'Subject', + substitute: hu ? 'Helyettesítő' : 'Substitute', + substituted: hu ? 'Helyettesített tanár' : 'Substituted teacher', + }; + + const lessonLabels = lessons + .map((entry) => { + let timeRange = ''; + if (entry.startTime) { + timeRange = entry.endTime + ? ` (${entry.startTime} - ${entry.endTime})` + : ` (${entry.startTime})`; + } + return `${periodLabel(entry.period, hu)}${timeRange}`.trim(); + }) + .filter((value) => value.length > 0); + + const rows: EmailDetail[] = [ + { label: label.date, value: formatDate(date, hu) }, + { + label: label.class, + value: uniqueStrings(lessons.map((entry) => entry.cohortName)).join(', '), + }, + { + label: label.subject, + value: uniqueStrings(lessons.map((entry) => entry.subjectName)).join( + ', ' + ), + }, + { label: label.lesson, value: lessonLabels.join(' · ') }, + { + label: label.room, + value: uniqueStrings(lessons.flatMap((entry) => entry.rooms)).join(', '), + }, + { + label: label.substituted, + value: uniqueStrings( + lessons.flatMap((entry) => entry.substitutedTeachers) + ).join(', '), + }, + { + label: label.substitute, + value: substituter ? (substituterName ?? '') : label.cancelled, + }, + { label: label.comment, value: comment?.trim() ?? '' }, + ]; + + return rows.filter((row) => row.value.length > 0); +} diff --git a/packages/api/src/contract/notifications.ts b/packages/api/src/contract/notifications.ts index 99663b12..55ad06ae 100644 --- a/packages/api/src/contract/notifications.ts +++ b/packages/api/src/contract/notifications.ts @@ -106,7 +106,7 @@ export const notificationsContract = { filcRoute({ auth: true, description: - 'Development helper: render a notification template without sending it (needs CHRONOS_ENABLE_TEST_NOTIFICATIONS)', + 'Development helper: render a notification template without sending it (needs CHRONOS_ENABLE_TEST_NOTIFICATIONS). When entityId is given, the real substitution, moved lesson or news record is rendered through the same builders as the live pipeline instead of the supplied text.', method: 'POST', operationId: 'postNotificationsTestPreview', path: '/notifications/test/preview', diff --git a/packages/api/src/domains/notifications.ts b/packages/api/src/domains/notifications.ts index 061d004c..8a98b6fc 100644 --- a/packages/api/src/domains/notifications.ts +++ b/packages/api/src/domains/notifications.ts @@ -124,6 +124,7 @@ export type SendTestNotificationInput = z.infer< export const previewTestNotificationSchema = z.object({ content: z.string().optional(), + entityId: z.uuid().optional(), language: z.enum(['en', 'hu']).optional(), subject: z.string().optional(), type: notificationTypeSchema, From e2ee51f8451a3c3c3d3fc67ec871c66474b968ce Mon Sep 17 00:00:00 2001 From: Dasa122 Date: Wed, 11 Nov 2026 00:11:00 +0100 Subject: [PATCH 04/44] fix(chronos): name the substitute teacher and complete the moved-lesson details --- .../src/modules/timetable/_notifications.ts | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/apps/chronos/src/modules/timetable/_notifications.ts b/apps/chronos/src/modules/timetable/_notifications.ts index 027a63ed..643c6d81 100644 --- a/apps/chronos/src/modules/timetable/_notifications.ts +++ b/apps/chronos/src/modules/timetable/_notifications.ts @@ -1,4 +1,5 @@ import type { EmailDetail } from '@filcdev/mail'; +import { isMatchingWeekday } from '#modules/timetable/utils/weekday'; import { env } from '#utils/environment'; import { resolveAudienceForLessonChange, @@ -43,6 +44,19 @@ function dayName(day: string, locale: string): string { if (num >= 1 && num <= names.length) { return names[num - 1] ?? day; } + + // Day definitions store a localized name ("Szerda", "Hétfő"), not a number. + // Match it against the shared weekday aliases and translate it for the + // recipient's locale, so the EN email says "Wednesday" rather than "Szerda". + for (let index = 0; index < WEEKDAY_NAMES_EN.length; index++) { + if (isMatchingWeekday(index, day)) { + const weekday = isHungarianLocale(locale) + ? WEEKDAY_NAMES_HU[index] + : WEEKDAY_NAMES_EN[index]; + return weekday ?? day; + } + } + return day; } @@ -98,12 +112,12 @@ function substitutionContentEn( } export function buildSubstitutionContent( - p: { date?: Date; substituter?: string | null; lessonIds?: string[] }, + p: { date?: Date; lessonIds?: string[]; substituterName?: string | null }, locale: string ): string { const date = p.date ? new Date(p.date) : null; const dateStr = date ? formatDate(date, locale) : ''; - const subName = p.substituter ?? ''; + const subName = p.substituterName ?? ''; const lessonCount = p.lessonIds?.length ?? 0; return isHungarianLocale(locale) ? substitutionContentHu(dateStr, subName, lessonCount) From 7d7d1083799930c96ac24c902ec8aaf7786b67bb Mon Sep 17 00:00:00 2001 From: Dasa122 Date: Wed, 11 Nov 2026 00:12:37 +0100 Subject: [PATCH 05/44] feat(iris): preview real notification records and desktop/phone sizes --- apps/iris/public/locales/en/translation.json | 8 + apps/iris/public/locales/hu/translation.json | 8 + apps/iris/src/hooks/dev-notifications.ts | 130 +++++++++++++++- apps/iris/src/hooks/moved-lessons.ts | 3 +- apps/iris/src/hooks/news.ts | 3 +- apps/iris/src/hooks/substitutions.ts | 3 +- .../_private/admin/dev/notifications.tsx | 139 ++++++++++++++++-- 7 files changed, 274 insertions(+), 20 deletions(-) diff --git a/apps/iris/public/locales/en/translation.json b/apps/iris/public/locales/en/translation.json index 13386e03..ddebc579 100644 --- a/apps/iris/public/locales/en/translation.json +++ b/apps/iris/public/locales/en/translation.json @@ -587,6 +587,12 @@ "title": "Test notifications", "description": "Send test notifications and preview email templates (development only)", "type": "Notification type", + "record": "Real record", + "recordNone": "Use the typed text", + "recordPlaceholder": "Choose a record", + "recordHint": "This record's own content is used instead of the subject and content above.", + "recordLessonCount_one": "{{count}} lesson", + "recordLessonCount_other": "{{count}} lessons", "language": "Language", "recipientEmail": "Recipient email", "recipientEmailPlaceholder": "optional@example.com", @@ -602,6 +608,8 @@ "preview": "Preview email", "previewTitle": "Email preview", "previewDescription": "Rendered template without sending.", + "previewDesktop": "Desktop", + "previewPhone": "Phone", "sendAll": "Send all types", "sendAllSuccess": "Sample sent for every type", "sendSuccess": "Test sent via: {{channels}}", diff --git a/apps/iris/public/locales/hu/translation.json b/apps/iris/public/locales/hu/translation.json index 257c0067..705736b3 100644 --- a/apps/iris/public/locales/hu/translation.json +++ b/apps/iris/public/locales/hu/translation.json @@ -587,6 +587,12 @@ "title": "Teszt értesítések", "description": "Teszt értesítések küldése és e-mail sablonok előnézete (csak fejlesztés)", "type": "Értesítés típusa", + "record": "Valódi rekord", + "recordNone": "A beírt szöveg használata", + "recordPlaceholder": "Válassz rekordot", + "recordHint": "A rekord saját tartalma jelenik meg a fenti tárgy és tartalom helyett.", + "recordLessonCount_one": "{{count}} óra", + "recordLessonCount_other": "{{count}} óra", "language": "Nyelv", "recipientEmail": "Címzett e-mail", "recipientEmailPlaceholder": "opcionalis@example.com", @@ -602,6 +608,8 @@ "preview": "E-mail előnézet", "previewTitle": "E-mail előnézet", "previewDescription": "Renderelt sablon küldés nélkül.", + "previewDesktop": "Asztali", + "previewPhone": "Telefon", "sendAll": "Minden típus küldése", "sendAllSuccess": "Minden típushoz elküldve a minta", "sendSuccess": "Teszt elküldve: {{channels}}", diff --git a/apps/iris/src/hooks/dev-notifications.ts b/apps/iris/src/hooks/dev-notifications.ts index 43249e6e..f9dd04bb 100644 --- a/apps/iris/src/hooks/dev-notifications.ts +++ b/apps/iris/src/hooks/dev-notifications.ts @@ -1,13 +1,19 @@ import { notificationTypeValues } from '@filcdev/api/domains/notifications'; import { ERROR_CODE } from '@filcdev/api/errors'; import { isDefinedError } from '@orpc/client'; -import { useMutation } from '@tanstack/react-query'; +import { useMutation, useQuery } from '@tanstack/react-query'; import { useTranslation } from 'react-i18next'; import { toast } from 'sonner'; +import { useMovedLessons } from '@/hooks/moved-lessons'; +import { useAdminSystemMessages, useAnnouncements } from '@/hooks/news'; +import { useSubstitutions } from '@/hooks/substitutions'; +import { getLocalizedWeekdayName, parseDateOnly } from '@/utils/date-locale'; import { api, orpc } from '@/utils/orpc'; export const NOTIFICATION_TYPES = notificationTypeValues; +type NotificationType = (typeof NOTIFICATION_TYPES)[number]; + type MockText = { content: string; title: string }; /** Realistic sample content per notification type, localized. */ @@ -145,6 +151,128 @@ export const describeTestNotificationError = ( ? message.disabled : message.fallback; +/** Date-only ISO label for the record picker; the API sends a local midnight. */ +function formatRecordDate(value: Date | string): string { + const date = parseDateOnly(value); + const month = String(date.getMonth() + 1).padStart(2, '0'); + const day = String(date.getDate()).padStart(2, '0'); + return `${date.getFullYear()}-${month}-${day}`; +} + +/** "3. óra" / "Period 3", mirroring the backend's notification period label. */ +function formatPeriodNumber( + period: number, + language: string, + periodWord: string +): string { + return language.toLowerCase().startsWith('hu') + ? `${period}. ${periodWord.toLocaleLowerCase()}` + : `${periodWord} ${period}`; +} + +/** + * Pickable real records for the dev preview, one short label per record. Every + * list is gated on the selected type so the page only fetches what it shows. + * Types the preview endpoint cannot render return an empty list. + */ +export function useTestNotificationRecordOptions( + type: NotificationType +): { id: string; label: string }[] { + const { i18n, t } = useTranslation(); + const substitutions = useSubstitutions(type === 'substitution'); + const movedLessons = useMovedLessons(type === 'moved_lesson'); + const announcements = useAnnouncements(type === 'announcement'); + const systemMessages = useAdminSystemMessages(type === 'system_message'); + const blogPosts = useQuery({ + ...orpc.news.blogs.list.queryOptions({ + input: { limit: 50, offset: 0 }, + }), + enabled: type === 'blog_post', + select: (payload) => payload.items, + }); + + switch (type) { + case 'substitution': + return (substitutions.data ?? []).map((item) => { + const lesson = item.lessons[0]; + const cohort = lesson?.cohorts[0]?.name; + const subject = lesson?.subject?.name; + const period = lesson?.period?.period; + const parts = [formatRecordDate(item.substitution.date)]; + if (cohort) { + parts.push(cohort); + } + if (subject) { + parts.push(subject); + } + if (period != null) { + parts.push( + formatPeriodNumber(period, i18n.language, t('substitution.period')) + ); + } + if (!(cohort || subject || period != null)) { + parts.push( + t('devNotifications.recordLessonCount', { + count: item.lessons.length, + }) + ); + } + return { id: item.substitution.id, label: parts.join(' · ') }; + }); + case 'moved_lesson': + return (movedLessons.data ?? []).map((item) => { + const subject = + item.manual?.subject?.name ?? item.lessons[0]?.subject?.name; + const day = item.dayDefinition + ? getLocalizedWeekdayName( + item.dayDefinition.name, + item.dayDefinition.short, + i18n.language, + 'long' + ) + : null; + const period = item.period?.period; + const target = [ + day, + period == null + ? null + : formatPeriodNumber( + period, + i18n.language, + t('substitution.period') + ), + ] + .filter(Boolean) + .join(', '); + const parts = [formatRecordDate(item.movedLesson.date)]; + if (subject) { + parts.push(subject); + } + if (target) { + parts.push(`→ ${target}`); + } + return { id: item.movedLesson.id, label: parts.join(' · ') }; + }); + case 'announcement': + return (announcements.data ?? []).map((item) => ({ + id: item.id, + label: `${formatRecordDate(item.validFrom)} · ${item.title ?? t('announcements.untitled')}`, + })); + case 'system_message': + return (systemMessages.data ?? []).map((item) => ({ + id: item.id, + label: `${formatRecordDate(item.validFrom)} · ${item.title}`, + })); + case 'blog_post': + return (blogPosts.data ?? []).map((item) => ({ + id: item.id, + label: `${formatRecordDate(item.publishedAt ?? item.createdAt)} · ${item.title}`, + })); + default: + return []; + } +} + /** Send a dev-only test notification with granular channel options. */ export function useSendTestNotification({ silent = false, diff --git a/apps/iris/src/hooks/moved-lessons.ts b/apps/iris/src/hooks/moved-lessons.ts index 39182143..ef87c676 100644 --- a/apps/iris/src/hooks/moved-lessons.ts +++ b/apps/iris/src/hooks/moved-lessons.ts @@ -38,9 +38,10 @@ export type MutationCallbacks = { }; /** Full moved-lesson list. */ -export function useMovedLessons() { +export function useMovedLessons(enabled = true) { return useQuery({ ...orpc.timetable.movedLessons.list.queryOptions(), + enabled, select: (data) => data.items, }); } diff --git a/apps/iris/src/hooks/news.ts b/apps/iris/src/hooks/news.ts index 24e98015..736b9196 100644 --- a/apps/iris/src/hooks/news.ts +++ b/apps/iris/src/hooks/news.ts @@ -30,7 +30,7 @@ type CohortsResponse = Awaited>['items']; export type Cohort = CohortsResponse[number]; /** Full announcement list including expired entries. */ -export function useAnnouncements() { +export function useAnnouncements(enabled = true) { return useQuery({ ...orpc.news.announcements.list.queryOptions({ // The admin table is the one place kiosk-only items stay visible. @@ -40,6 +40,7 @@ export function useAnnouncements() { includeKioskOnly: 'true', }, }), + enabled, select: (payload) => payload.items, }); } diff --git a/apps/iris/src/hooks/substitutions.ts b/apps/iris/src/hooks/substitutions.ts index a8ba07da..85590a40 100644 --- a/apps/iris/src/hooks/substitutions.ts +++ b/apps/iris/src/hooks/substitutions.ts @@ -15,9 +15,10 @@ export type SubstitutionItem = SubstitutionsResponse[number]; export type Teacher = NonNullable; /** Full substitution list. */ -export function useSubstitutions() { +export function useSubstitutions(enabled = true) { return useQuery({ ...orpc.timetable.substitutions.list.queryOptions(), + enabled, select: (data) => data.items, }); } diff --git a/apps/iris/src/routes/_private/admin/dev/notifications.tsx b/apps/iris/src/routes/_private/admin/dev/notifications.tsx index 8a98283d..12026666 100644 --- a/apps/iris/src/routes/_private/admin/dev/notifications.tsx +++ b/apps/iris/src/routes/_private/admin/dev/notifications.tsx @@ -18,8 +18,8 @@ import { import { Textarea } from '@filcdev/ui/components/textarea'; import { useForm, useStore } from '@tanstack/react-form'; import { createFileRoute, Navigate } from '@tanstack/react-router'; -import { Eye, Send } from 'lucide-react'; -import { useEffect, useState } from 'react'; +import { Eye, Monitor, Send, Smartphone } from 'lucide-react'; +import { useEffect, useId, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { toast } from 'sonner'; import { PermissionGuard } from '@/components/util/permission-guard'; @@ -29,10 +29,13 @@ import { NOTIFICATION_TYPES, usePreviewTestNotification, useSendTestNotification, + useTestNotificationRecordOptions, } from '@/hooks/dev-notifications'; type ChannelKey = 'emailEnabled' | 'inAppEnabled' | 'pushEnabled'; +type PreviewMode = 'desktop' | 'phone'; + const CHANNELS: Array<{ key: ChannelKey; label: string }> = [ { key: 'inAppEnabled', label: 'devNotifications.channelInApp' }, { key: 'emailEnabled', label: 'devNotifications.channelEmail' }, @@ -75,6 +78,12 @@ function DevNotificationsPage() { const { t } = useTranslation(); const [previewHtml, setPreviewHtml] = useState(null); const [previewOpen, setPreviewOpen] = useState(false); + const [previewMode, setPreviewMode] = useState('desktop'); + const [selectedRecord, setSelectedRecord] = useState<{ + id: string; + type: FormValues['type']; + } | null>(null); + const recordFieldId = useId(); const sendNotification = useSendTestNotification(); const sendAllNotification = useSendTestNotification({ silent: true }); @@ -99,6 +108,14 @@ function DevNotificationsPage() { }); const values = useStore(form.store, (state) => state.values); + const recordOptions = useTestNotificationRecordOptions(values.type); + const recordId = + selectedRecord && + selectedRecord.type === values.type && + recordOptions.some((option) => option.id === selectedRecord.id) + ? selectedRecord.id + : ''; + const recordSelected = recordId !== ''; // Keep subject/content filled with per-type mock data when the type or // language changes, so each type can be previewed/sent with one click. @@ -112,12 +129,20 @@ function DevNotificationsPage() { const handlePreview = async () => { try { - const html = await previewNotification.mutateAsync({ - content: values.content || undefined, - language: values.language, - subject: values.subject || undefined, - type: values.type, - }); + const html = await previewNotification.mutateAsync( + recordSelected + ? { + entityId: recordId, + language: values.language, + type: values.type, + } + : { + content: values.content || undefined, + language: values.language, + subject: values.subject || undefined, + type: values.type, + } + ); setPreviewHtml(html); setPreviewOpen(true); } catch { @@ -221,6 +246,43 @@ function DevNotificationsPage() { + {recordOptions.length > 0 && ( + + + {t('devNotifications.record')} + + + {recordSelected && ( +

+ {t('devNotifications.recordHint')} +

+ )} +
+ )} + {(field) => ( @@ -246,6 +308,7 @@ function DevNotificationsPage() { {t('devNotifications.subject')} field.handleChange(e.target.value)} placeholder={t('devNotifications.subjectPlaceholder')} @@ -262,6 +325,7 @@ function DevNotificationsPage() { {t('devNotifications.content')}