Phase 9d: Notification cron + multilingual templates + status badges
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / test-go-school (push) Successful in 1m10s
CI / test-go-edu-search (push) Successful in 43s
CI / test-python-klausur (push) Failing after 4m4s
CI / test-python-agent-core (push) Successful in 44s
CI / test-nodejs-website (push) Successful in 51s

Backend (school-service):
  - notification_log table with UNIQUE(event_id, lead_days, audience,
    channel) for idempotent re-runs. Status enum sent/failed/skipped.
  - internal/notifications/templates.go: per-event-type × audience ×
    lead-day-bucket × language templates in 8 languages (de/en/tr/ar/
    uk/ru/pl/fr). Fallback chain (lang→de, eventType→andere) so we
    never miss a render.
  - service.go scans cal_school_event for events whose
    (start_date - runDate) appears in notification_lead_days. For each
    due (audience, channel) tuple it dispatches via POST to the
    Matrix/Email upstreams owned by the colleague's services.
    Empty URL → status='skipped', logged for visibility.
  - dispatcher.go handles the POST, parent-recipient lookup (joins
    parent_account + parent_child + cal_school_event.affected_class_ids),
    and writeLog with the unique constraint dropping duplicate runs.
  - main.go runs a 1-hour ticker; when time.Hour()==6 it invokes the
    scanner for today. Idempotent so transient restarts don't double-
    send.
  - POST /calendar/notifications/run-now for manual trigger + backfill
    (?date=YYYY-MM-DD).
  - GET /calendar/events/:id/notifications returns notification_log
    rows scoped to the owning teacher.
  - MATRIX_SERVICE_URL + EMAIL_SERVICE_URL env vars added (default
    empty = stub mode).

Frontend (studio-v2):
  - NotificationStatus component fetches /events/:id/notifications and
    renders coloured badges per (lead, audience, channel, status).
  - DayDetail mounts NotificationStatus inside each event card when
    notify_parents or notify_students is set.

Tests:
  - 6 new Go unit tests for bucketFor + Render (de/tr/fallback paths)
    + substitute(class_suffix). 89 subtests gesamt.
  - 2 new Playwright tests: badge render with mocked log, hidden when
    notifications are off.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Benjamin Admin
2026-05-22 18:12:39 +02:00
parent 85957ed5db
commit 8311b33fb3
15 changed files with 977 additions and 15 deletions
@@ -4,6 +4,7 @@ import { useTheme } from '@/lib/ThemeContext'
import { calendarApi } from '@/lib/schulkalender/api'
import type { PublicEvent, SchoolEvent } from '@/app/schulkalender/types'
import { EVENT_TYPE_COLOR, EVENT_TYPE_LABEL } from '@/app/schulkalender/types'
import { NotificationStatus } from './NotificationStatus'
interface DayDetailProps {
iso: string
@@ -84,6 +85,9 @@ export function DayDetail({ iso, holidays, events, onClose, onDeleted }: DayDeta
{e.notify_parents && ' · 📧 Eltern erinnern'}
{e.notify_students && ' · 💬 Schueler erinnern'}
</div>
{(e.notify_parents || e.notify_students) && (
<NotificationStatus eventId={e.id} />
)}
</div>
<button
onClick={() => handleDelete(e.id)}
@@ -0,0 +1,53 @@
'use client'
import { useEffect, useState } from 'react'
import { useTheme } from '@/lib/ThemeContext'
import { calendarApi } from '@/lib/schulkalender/api'
import type { NotificationLogRow } from '@/app/schulkalender/types'
interface NotificationStatusProps {
eventId: string
}
const STATUS_ICON: Record<string, string> = {
sent: '✓',
failed: '✗',
skipped: '⏱',
}
export function NotificationStatus({ eventId }: NotificationStatusProps) {
const { isDark } = useTheme()
const [rows, setRows] = useState<NotificationLogRow[]>([])
const [loading, setLoading] = useState(true)
useEffect(() => {
calendarApi.listEventNotifications(eventId)
.then(r => { setRows(r || []); setLoading(false) })
.catch(() => setLoading(false))
}, [eventId])
if (loading || rows.length === 0) return null
return (
<div className={`mt-2 pt-2 border-t text-xs ${isDark ? 'border-white/10' : 'border-black/10'}`} data-testid={`notif-status-${eventId}`}>
<div className={`font-medium mb-1 ${isDark ? 'text-white/70' : 'text-slate-600'}`}>Erinnerungen</div>
<div className="flex flex-wrap gap-2">
{rows.map((r, i) => (
<span
key={i}
title={r.error_message || `${r.status} ${r.run_date}`}
className={`px-2 py-0.5 rounded ${
r.status === 'sent' ? (isDark ? 'bg-emerald-500/30 text-emerald-100' : 'bg-emerald-100 text-emerald-900') :
r.status === 'failed' ? (isDark ? 'bg-red-500/30 text-red-100' : 'bg-red-100 text-red-900') :
(isDark ? 'bg-amber-500/30 text-amber-100' : 'bg-amber-100 text-amber-900')
}`}
>
{STATUS_ICON[r.status]} {r.lead_days === 0 ? 'Heute' : r.lead_days === 1 ? '1 Tag' : `${r.lead_days} Tage`}
{' · '}{r.audience === 'parents' ? 'Eltern' : 'Schueler'}
{' · '}{r.channel}
</span>
))}
</div>
</div>
)
}
+22
View File
@@ -159,3 +159,25 @@ export interface InviteParentResponse {
magic_url: string
expires_at: string
}
// ---------- Notifications (Phase 9d) ----------
export type NotificationStatus = 'sent' | 'failed' | 'skipped'
export interface NotificationLogRow {
lead_days: number
audience: 'parents' | 'students'
channel: 'matrix' | 'email'
status: NotificationStatus
error_message?: string
run_date: string
created_at: string
}
export interface NotificationRunResult {
date: string
sent: number
failed: number
skipped: number
already_logged: number
}
+66
View File
@@ -10,6 +10,7 @@ interface MockOpts {
config?: { user_id: string; bundesland: string } | null
holidays?: unknown[]
events?: unknown[]
notificationLog?: unknown[]
}
async function mockCalendarApi(page: Page, opts: MockOpts = {}) {
@@ -83,6 +84,16 @@ async function mockCalendarApi(page: Page, opts: MockOpts = {}) {
}),
})
})
// Phase 9d: per-event notification_log + manual trigger. NotificationStatus
// component fetches the log when an event has notify_parents/students.
await page.route(/\/api\/school\/calendar\/events\/[^/]+\/notifications$/, async (route) => {
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(opts.notificationLog ?? []) })
})
await page.route(/\/api\/school\/calendar\/notifications\/run-now.*/, async (route) => {
return route.fulfill({ status: 200, contentType: 'application/json',
body: '{"date":"2026-05-22","sent":0,"failed":0,"skipped":0,"already_logged":0}' })
})
}
test.describe('Schulkalender — Bundesland Wizard', () => {
@@ -249,3 +260,58 @@ test.describe('Schulkalender — Schuljahres-Rollover', () => {
await expect(page.getByText('2 Abschlussklassen entfernt')).toBeVisible()
})
})
// ==========================================================================
// Phase 9d — Notification-Status im DayDetail
// ==========================================================================
test.describe('Schulkalender — Notification-Status', () => {
test('shows sent badge for delivered reminders', async ({ page }) => {
const todayIso = new Date().toISOString().slice(0, 10)
await mockCalendarApi(page, {
config: { user_id: 'dev', bundesland: 'DE-NI' },
events: [{
id: 'e1', created_by_user_id: 'dev',
title: 'Pruefe Test-Event', event_type: 'projekttag',
is_school_free: false,
start_date: todayIso, end_date: todayIso,
affected_class_ids: [], visible_to_parents: true,
notify_parents: true, notify_students: false,
notification_lead_days: [7, 1],
}],
notificationLog: [
{ lead_days: 7, audience: 'parents', channel: 'email', status: 'sent', run_date: '2026-05-15', created_at: '2026-05-15T06:00:00Z' },
{ lead_days: 1, audience: 'parents', channel: 'email', status: 'skipped', run_date: '2026-05-21', created_at: '2026-05-21T06:00:00Z' },
],
})
await page.goto('/schulkalender')
await page.waitForLoadState('networkidle')
await page.getByTestId(`day-${todayIso}`).click()
await expect(page.getByTestId('day-detail')).toBeVisible()
const status = page.getByTestId('notif-status-e1')
await expect(status).toBeVisible()
await expect(status.getByText(/7 Tage.*Eltern.*email/)).toBeVisible()
await expect(status.getByText(/1 Tag.*Eltern.*email/)).toBeVisible()
})
test('hides notification status when notifications are off', async ({ page }) => {
const todayIso = new Date().toISOString().slice(0, 10)
await mockCalendarApi(page, {
config: { user_id: 'dev', bundesland: 'DE-NI' },
events: [{
id: 'e2', created_by_user_id: 'dev',
title: 'Stilles Event', event_type: 'andere',
is_school_free: false,
start_date: todayIso, end_date: todayIso,
affected_class_ids: [], visible_to_parents: true,
notify_parents: false, notify_students: false,
notification_lead_days: [],
}],
})
await page.goto('/schulkalender')
await page.waitForLoadState('networkidle')
await page.getByTestId(`day-${todayIso}`).click()
await expect(page.getByTestId('notif-status-e2')).toHaveCount(0)
})
})
+7
View File
@@ -8,6 +8,7 @@ import type {
PublicEvent, SchoolCalendarConfig, UpsertSchoolCalendarConfig,
SchoolEvent, CreateSchoolEvent, SchoolYearRolloverResult,
ParentInviteListItem, InviteParentRequest, InviteParentResponse,
NotificationLogRow, NotificationRunResult,
} from '@/app/schulkalender/types'
async function apiFetch<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
@@ -57,4 +58,10 @@ export const calendarApi = {
apiFetch<InviteParentResponse>('/calendar/parents/invite', { method: 'POST', body: JSON.stringify(data) }),
deleteParentChild: (childId: string) =>
apiFetch<void>(`/calendar/parents/children/${childId}`, { method: 'DELETE' }),
// Phase 9d: notifications.
runNotifications: (date?: string) =>
apiFetch<NotificationRunResult>('/calendar/notifications/run-now' + (date ? `?date=${date}` : ''), { method: 'POST' }),
listEventNotifications: (eventId: string) =>
apiFetch<NotificationLogRow[]>(`/calendar/events/${eventId}/notifications`),
}