Phase 9c: Parent accounts, magic-link login + parent timetable view
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 31s
CI / test-go-edu-search (push) Successful in 30s
CI / test-python-klausur (push) Failing after 2m36s
CI / test-python-agent-core (push) Successful in 21s
CI / test-nodejs-website (push) Successful in 26s
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 31s
CI / test-go-edu-search (push) Successful in 30s
CI / test-python-klausur (push) Failing after 2m36s
CI / test-python-agent-core (push) Successful in 21s
CI / test-nodejs-website (push) Successful in 26s
Backend (school-service):
- parent_account, parent_child, parent_magic_link, parent_session
tables. Tokens are sha256-hashed in DB; raw goes back exactly
once to the inviting teacher.
- InviteParent upserts the parent account, links a child to a tt_
class, mints a 7-day magic link. Returns the link path so the
teacher can paste it into Matrix/Email.
- RedeemMagicLink validates + marks used + mints a 30-day session,
sets HttpOnly bp_parent_session cookie.
- ParentSessionMiddleware reads the cookie and resolves the parent.
Lives in its own router group /api/v1/parent — totally separate
from the teacher JWT path.
- ParentMe returns the account + list of children (with class name).
- ParentTimetable returns the latest completed tt_solution's lessons
for the requested child's class, with full authorization check
(parent must own a child in that class).
Frontend (studio-v2):
- lib/calendar/subject-i18n.ts maps 22 German subject names to 8
parent locales (de/en/tr/ar/uk/ru/pl/fr). Falls back to German
for custom subjects.
- ParentManager component on the Schulkalender page lets the teacher
invite parents via email + child name + class + language. Newly
minted magic-link is shown with a copy-to-clipboard button.
- app/api/parent/[...path]/route.ts proxies parent-side endpoints
via the cookie so HttpOnly survives the Next.js round-trip.
- /eltern/login?token=… redeems and redirects to /eltern.
- /eltern shows a Wochengrid with German days + translated subject
names in the parent's preferred language. Headings and weekday
labels also localised (de/en/tr/ar/uk/ru/pl/fr).
Tests:
- 3 new Go unit tests (random token, hash stability, invite-request
validator). 83 subtests gesamt.
- studio-v2: e2e/eltern.spec.ts mit 7 tests across ParentManager,
/eltern/login, /eltern overview, subject-i18n end-to-end.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
|
||||
/**
|
||||
* Proxy for the parent-side school-service endpoints. Mirrors the school
|
||||
* proxy but forwards the parent-session cookie via Set-Cookie/Cookie
|
||||
* headers so HttpOnly survives the round-trip.
|
||||
*/
|
||||
|
||||
const BACKEND_URL = process.env.SCHOOL_SERVICE_URL || 'http://school-service:8084'
|
||||
|
||||
async function proxy(request: NextRequest, params: { path: string[] }): Promise<NextResponse> {
|
||||
const path = params.path.join('/')
|
||||
const url = `${BACKEND_URL}/api/v1/parent/${path}${request.nextUrl.search}`
|
||||
|
||||
const headers: HeadersInit = { 'Content-Type': 'application/json' }
|
||||
const cookie = request.headers.get('cookie')
|
||||
if (cookie) headers['Cookie'] = cookie
|
||||
|
||||
const init: RequestInit = { method: request.method, headers }
|
||||
if (['POST', 'PUT', 'PATCH'].includes(request.method)) {
|
||||
init.body = await request.text()
|
||||
}
|
||||
|
||||
try {
|
||||
const upstream = await fetch(url, init)
|
||||
const body = await upstream.text()
|
||||
const res = new NextResponse(body, {
|
||||
status: upstream.status,
|
||||
headers: { 'Content-Type': upstream.headers.get('content-type') || 'application/json' },
|
||||
})
|
||||
// Mirror Set-Cookie back so the browser stores the parent session.
|
||||
const setCookie = upstream.headers.get('set-cookie')
|
||||
if (setCookie) res.headers.set('Set-Cookie', setCookie)
|
||||
return res
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: 'school-service nicht erreichbar', details: error instanceof Error ? error.message : 'Unknown error' },
|
||||
{ status: 502 },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(req: NextRequest, ctx: { params: Promise<{ path: string[] }> }) { return proxy(req, await ctx.params) }
|
||||
export async function POST(req: NextRequest, ctx: { params: Promise<{ path: string[] }> }) { return proxy(req, await ctx.params) }
|
||||
export async function PUT(req: NextRequest, ctx: { params: Promise<{ path: string[] }> }) { return proxy(req, await ctx.params) }
|
||||
export async function DELETE(req: NextRequest, ctx: { params: Promise<{ path: string[] }> }) { return proxy(req, await ctx.params) }
|
||||
@@ -0,0 +1,44 @@
|
||||
'use client'
|
||||
|
||||
import { Suspense, useEffect, useState } from 'react'
|
||||
import { useRouter, useSearchParams } from 'next/navigation'
|
||||
import { elternApi } from '@/lib/eltern/api'
|
||||
|
||||
function LoginInner() {
|
||||
const router = useRouter()
|
||||
const search = useSearchParams()
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [done, setDone] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
const token = search.get('token')
|
||||
if (!token) {
|
||||
setError('Kein Token in der URL. Bitte den Link aus der Einladung verwenden.')
|
||||
return
|
||||
}
|
||||
elternApi.redeem(token)
|
||||
.then(() => { setDone(true); setTimeout(() => router.replace('/eltern'), 800) })
|
||||
.catch(e => setError(e instanceof Error ? e.message : 'Login fehlgeschlagen'))
|
||||
}, [router, search])
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-indigo-900 via-purple-900 to-pink-800 text-white">
|
||||
<div className="max-w-md w-full mx-4 p-6 rounded-2xl bg-white/10 border border-white/20 backdrop-blur-xl" data-testid="eltern-login">
|
||||
<h1 className="text-2xl font-semibold mb-3">Eltern-Login</h1>
|
||||
{!error && !done && <p className="opacity-80">Pruefe Token …</p>}
|
||||
{done && <p className="text-emerald-200">Erfolgreich angemeldet. Weiterleitung …</p>}
|
||||
{error && (
|
||||
<div className="p-3 rounded-lg bg-red-500/20 border border-red-500/40 text-red-200 text-sm">{error}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function ElternLoginPage() {
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
<LoginInner />
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useCallback, useMemo } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { elternApi, type ParentMeResponse, type ParentLesson } from '@/lib/eltern/api'
|
||||
import { translateSubject } from '@/lib/calendar/subject-i18n'
|
||||
|
||||
const DAY_LABELS: Record<string, string[]> = {
|
||||
de: ['Mo', 'Di', 'Mi', 'Do', 'Fr'],
|
||||
en: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
|
||||
tr: ['Pzt', 'Sal', 'Çar', 'Per', 'Cum'],
|
||||
ar: ['الإثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة'],
|
||||
uk: ['Пн', 'Вт', 'Ср', 'Чт', 'Пт'],
|
||||
ru: ['Пн', 'Вт', 'Ср', 'Чт', 'Пт'],
|
||||
pl: ['Pon', 'Wt', 'Śr', 'Czw', 'Pt'],
|
||||
fr: ['Lun', 'Mar', 'Mer', 'Jeu', 'Ven'],
|
||||
}
|
||||
|
||||
const HEADINGS: Record<string, { greeting: string; selectChild: string; period: string; logout: string; noPlan: string }> = {
|
||||
de: { greeting: 'Willkommen', selectChild: 'Kind auswählen', period: 'Stunde', logout: 'Abmelden', noPlan: 'Noch kein Stundenplan veröffentlicht.' },
|
||||
en: { greeting: 'Welcome', selectChild: 'Select child', period: 'Period', logout: 'Sign out', noPlan: 'No timetable published yet.' },
|
||||
tr: { greeting: 'Hoş geldiniz', selectChild: 'Çocuk seç', period: 'Ders', logout: 'Çıkış', noPlan: 'Henüz ders programı yayımlanmadı.' },
|
||||
ar: { greeting: 'مرحبًا', selectChild: 'اختر الطفل', period: 'حصة', logout: 'خروج', noPlan: 'لم يتم نشر جدول حصص بعد.' },
|
||||
uk: { greeting: 'Ласкаво просимо', selectChild: 'Виберіть дитину', period: 'Урок', logout: 'Вийти', noPlan: 'Розклад ще не опубліковано.' },
|
||||
ru: { greeting: 'Добро пожаловать', selectChild: 'Выберите ребёнка', period: 'Урок', logout: 'Выйти', noPlan: 'Расписание ещё не опубликовано.' },
|
||||
pl: { greeting: 'Witamy', selectChild: 'Wybierz dziecko', period: 'Lekcja', logout: 'Wyloguj', noPlan: 'Plan lekcji nie jest jeszcze opublikowany.' },
|
||||
fr: { greeting: 'Bienvenue', selectChild: 'Choisir un enfant', period: 'Cours', logout: 'Déconnexion', noPlan: 'Aucun emploi du temps publié.' },
|
||||
}
|
||||
|
||||
function t(lang: string, key: keyof typeof HEADINGS['de']): string {
|
||||
const code = (lang || 'de').slice(0, 2)
|
||||
return HEADINGS[code]?.[key] ?? HEADINGS.de[key]
|
||||
}
|
||||
|
||||
export default function ElternPage() {
|
||||
const router = useRouter()
|
||||
const [me, setMe] = useState<ParentMeResponse | null>(null)
|
||||
const [selected, setSelected] = useState<string>('')
|
||||
const [lessons, setLessons] = useState<ParentLesson[]>([])
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const lang = me?.parent.preferred_language || 'de'
|
||||
const dayLabels = DAY_LABELS[lang.slice(0, 2)] || DAY_LABELS.de
|
||||
|
||||
const loadMe = useCallback(async () => {
|
||||
try {
|
||||
const data = await elternApi.me()
|
||||
setMe(data)
|
||||
if (data.children.length > 0) setSelected(data.children[0].tt_class_id)
|
||||
} catch (e) {
|
||||
// Not logged in → redirect to login.
|
||||
if (e instanceof Error && /session/i.test(e.message)) {
|
||||
router.replace('/eltern/login')
|
||||
return
|
||||
}
|
||||
setError(e instanceof Error ? e.message : 'Laden fehlgeschlagen')
|
||||
}
|
||||
}, [router])
|
||||
|
||||
useEffect(() => { loadMe() }, [loadMe])
|
||||
|
||||
const loadTimetable = useCallback(async () => {
|
||||
if (!selected) return
|
||||
try {
|
||||
const data = await elternApi.timetable(selected)
|
||||
setLessons(data || [])
|
||||
setError(null)
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Stundenplan laden fehlgeschlagen')
|
||||
}
|
||||
}, [selected])
|
||||
|
||||
useEffect(() => { loadTimetable() }, [loadTimetable])
|
||||
|
||||
const periodIndices = useMemo(() => {
|
||||
const set = new Set<number>()
|
||||
for (const l of lessons) set.add(l.PeriodIndex)
|
||||
return Array.from(set).sort((a, b) => a - b)
|
||||
}, [lessons])
|
||||
|
||||
const cell = (day: number, idx: number) =>
|
||||
lessons.find(l => l.DayOfWeek === day && l.PeriodIndex === idx)
|
||||
|
||||
const handleLogout = async () => {
|
||||
try { await elternApi.logout() } catch { /* ignore */ }
|
||||
router.replace('/eltern/login')
|
||||
}
|
||||
|
||||
if (!me) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-indigo-900 via-purple-900 to-pink-800 text-white">
|
||||
{error ? <span className="text-red-200">{error}</span> : <span className="opacity-70">Laedt …</span>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const activeChild = me.children.find(c => c.tt_class_id === selected)
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-indigo-900 via-purple-900 to-pink-800 text-white p-6" data-testid="eltern-page">
|
||||
<div className="max-w-5xl mx-auto">
|
||||
<header className="flex items-center justify-between mb-6">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold">{t(lang, 'greeting')}, {me.parent.email}</h1>
|
||||
<p className="text-sm text-white/60 mt-1">
|
||||
{activeChild ? `${activeChild.first_name} ${activeChild.last_name} · ${activeChild.class_name}` : ''}
|
||||
</p>
|
||||
</div>
|
||||
<button onClick={handleLogout} data-testid="eltern-logout" className="px-3 py-1.5 rounded-lg bg-white/10 hover:bg-white/20 text-sm">
|
||||
{t(lang, 'logout')}
|
||||
</button>
|
||||
</header>
|
||||
|
||||
{me.children.length > 1 && (
|
||||
<div className="mb-4">
|
||||
<label className="block text-sm mb-1 opacity-70">{t(lang, 'selectChild')}</label>
|
||||
<select
|
||||
value={selected}
|
||||
onChange={e => setSelected(e.target.value)}
|
||||
data-testid="child-selector"
|
||||
className="px-3 py-2 rounded-lg border bg-white/10 border-white/20 text-white"
|
||||
>
|
||||
{me.children.map(c => (
|
||||
<option key={c.id} value={c.tt_class_id} className="text-slate-900">
|
||||
{c.first_name} {c.last_name} ({c.class_name})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && <div className="mb-3 p-3 rounded-lg bg-red-500/20 border border-red-500/40 text-red-200">{error}</div>}
|
||||
|
||||
{periodIndices.length === 0 ? (
|
||||
<div className="rounded-2xl bg-white/10 border border-white/20 p-8 text-center opacity-70">
|
||||
{t(lang, 'noPlan')}
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-2xl bg-white/10 border border-white/20 overflow-hidden">
|
||||
<table className="w-full">
|
||||
<thead className="bg-white/5">
|
||||
<tr>
|
||||
<th className="text-left px-3 py-3 text-sm font-medium opacity-70 w-16">{t(lang, 'period')}</th>
|
||||
{dayLabels.map(d => <th key={d} className="text-left px-3 py-3 text-sm font-medium opacity-70">{d}</th>)}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{periodIndices.map(idx => (
|
||||
<tr key={idx} className="border-t border-white/10">
|
||||
<td className="px-3 py-2 font-medium text-sm">{idx}.</td>
|
||||
{[1, 2, 3, 4, 5].map(d => {
|
||||
const l = cell(d, idx)
|
||||
if (!l) return <td key={d} className="px-3 py-2 opacity-20 text-xs">—</td>
|
||||
return (
|
||||
<td key={d} className="px-2 py-1" data-testid={`eltern-cell-${d}-${idx}`}>
|
||||
<div className="rounded-md p-2 text-xs space-y-0.5 bg-indigo-500/30 border-l-2 border-indigo-300">
|
||||
<div className="font-semibold">{translateSubject(l.SubjectName, lang)}</div>
|
||||
<div className="opacity-80">{l.TeacherName.split(',')[0]}</div>
|
||||
{l.RoomName && <div className="opacity-60">{l.RoomName}</div>}
|
||||
</div>
|
||||
</td>
|
||||
)
|
||||
})}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { useTheme } from '@/lib/ThemeContext'
|
||||
import { calendarApi } from '@/lib/schulkalender/api'
|
||||
import { classesApi } from '@/lib/stundenplan/api'
|
||||
import type { ParentInviteListItem, InviteParentResponse } from '@/app/schulkalender/types'
|
||||
import type { TimetableClass } from '@/app/stundenplan/types'
|
||||
|
||||
const LANGS: { code: string; name: string }[] = [
|
||||
{ code: 'de', name: 'Deutsch' },
|
||||
{ code: 'en', name: 'English' },
|
||||
{ code: 'tr', name: 'Tuerkce' },
|
||||
{ code: 'ar', name: 'العربية' },
|
||||
{ code: 'uk', name: 'Українська' },
|
||||
{ code: 'ru', name: 'Русский' },
|
||||
{ code: 'pl', name: 'Polski' },
|
||||
{ code: 'fr', name: 'Francais' },
|
||||
]
|
||||
|
||||
export function ParentManager() {
|
||||
const { isDark } = useTheme()
|
||||
const [items, setItems] = useState<ParentInviteListItem[]>([])
|
||||
const [classes, setClasses] = useState<TimetableClass[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [showForm, setShowForm] = useState(false)
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [lastInvite, setLastInvite] = useState<InviteParentResponse | null>(null)
|
||||
const [form, setForm] = useState({
|
||||
email: '',
|
||||
preferred_language: 'de',
|
||||
child_first_name: '',
|
||||
child_last_name: '',
|
||||
tt_class_id: '',
|
||||
})
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const [list, cls] = await Promise.all([calendarApi.listParents(), classesApi.list()])
|
||||
setItems(list || [])
|
||||
setClasses(cls || [])
|
||||
setError(null)
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Laden fehlgeschlagen')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => { load() }, [load])
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setSubmitting(true)
|
||||
setError(null)
|
||||
try {
|
||||
const res = await calendarApi.inviteParent(form)
|
||||
setLastInvite(res)
|
||||
setForm({ ...form, child_first_name: '', child_last_name: '' })
|
||||
await load()
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Einladen fehlgeschlagen')
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async (childId: string) => {
|
||||
if (!confirm('Eltern-Zuordnung wirklich loeschen?')) return
|
||||
try { await calendarApi.deleteParentChild(childId); await load() }
|
||||
catch (e) { setError(e instanceof Error ? e.message : 'Loeschen fehlgeschlagen') }
|
||||
}
|
||||
|
||||
const fullLink = (path: string) =>
|
||||
typeof window === 'undefined' ? path : `${window.location.origin}${path}`
|
||||
|
||||
const copyLink = (path: string) => {
|
||||
navigator.clipboard?.writeText(fullLink(path))
|
||||
}
|
||||
|
||||
const cardClass = isDark ? 'bg-white/10 border-white/20 text-white' : 'bg-white/80 border-black/10 text-slate-900'
|
||||
const inputClass = isDark ? 'bg-white/10 border-white/20 text-white' : 'bg-white border-slate-300 text-slate-900'
|
||||
|
||||
return (
|
||||
<div className={`rounded-2xl border backdrop-blur-xl p-4 ${cardClass}`} data-testid="parent-manager">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<h3 className="text-lg font-semibold">Eltern verwalten ({items.length})</h3>
|
||||
<button
|
||||
onClick={() => setShowForm(s => !s)}
|
||||
disabled={classes.length === 0}
|
||||
data-testid="parent-invite-toggle"
|
||||
className={`px-3 py-1.5 rounded-lg text-sm font-medium disabled:opacity-50 ${isDark ? 'bg-indigo-500 hover:bg-indigo-600 text-white' : 'bg-indigo-600 hover:bg-indigo-700 text-white'}`}
|
||||
>
|
||||
{showForm ? 'Abbrechen' : '+ Eltern einladen'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{classes.length === 0 && (
|
||||
<p className={`text-sm mb-2 ${isDark ? 'text-amber-200' : 'text-amber-900'}`}>
|
||||
Zuerst Klassen im Stundenplan-Modul anlegen.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="mb-3 p-2 rounded-lg bg-red-500/20 border border-red-500/40 text-red-300 text-sm">{error}</div>
|
||||
)}
|
||||
|
||||
{showForm && (
|
||||
<form onSubmit={handleSubmit} className="mb-4 grid grid-cols-1 md:grid-cols-3 gap-2">
|
||||
<input required type="email" placeholder="Eltern-E-Mail" value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} data-testid="parent-email" className={`px-3 py-2 rounded-lg border ${inputClass}`} />
|
||||
<input required placeholder="Vorname Kind" value={form.child_first_name} onChange={e => setForm({ ...form, child_first_name: e.target.value })} data-testid="parent-child-first" className={`px-3 py-2 rounded-lg border ${inputClass}`} />
|
||||
<input required placeholder="Nachname Kind" value={form.child_last_name} onChange={e => setForm({ ...form, child_last_name: e.target.value })} data-testid="parent-child-last" className={`px-3 py-2 rounded-lg border ${inputClass}`} />
|
||||
<select required value={form.tt_class_id} onChange={e => setForm({ ...form, tt_class_id: e.target.value })} data-testid="parent-class" className={`px-3 py-2 rounded-lg border ${inputClass}`}>
|
||||
<option value="">— Klasse waehlen —</option>
|
||||
{classes.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
|
||||
</select>
|
||||
<select value={form.preferred_language} onChange={e => setForm({ ...form, preferred_language: e.target.value })} className={`px-3 py-2 rounded-lg border ${inputClass}`}>
|
||||
{LANGS.map(l => <option key={l.code} value={l.code}>{l.name}</option>)}
|
||||
</select>
|
||||
<button type="submit" disabled={submitting} data-testid="parent-invite-submit" className="px-4 py-2 rounded-lg bg-emerald-500 hover:bg-emerald-600 text-white font-medium disabled:opacity-50">
|
||||
{submitting ? 'Erstellt…' : 'Einladen'}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{lastInvite && (
|
||||
<div className={`mb-3 p-3 rounded-lg ${isDark ? 'bg-emerald-500/20 border border-emerald-500/40' : 'bg-emerald-50 border border-emerald-200'}`} data-testid="parent-invite-link">
|
||||
<div className="text-sm font-medium mb-1">Einladungs-Link fuer {lastInvite.parent.email}</div>
|
||||
<div className="flex gap-2 items-center">
|
||||
<code className={`flex-1 text-xs px-2 py-1 rounded overflow-x-auto ${isDark ? 'bg-white/10' : 'bg-white'}`}>
|
||||
{fullLink(lastInvite.magic_url)}
|
||||
</code>
|
||||
<button onClick={() => copyLink(lastInvite.magic_url)} className="text-xs px-2 py-1 rounded bg-indigo-500 hover:bg-indigo-600 text-white">Kopieren</button>
|
||||
</div>
|
||||
<p className="text-xs opacity-70 mt-1">Gueltig bis {new Date(lastInvite.expires_at).toLocaleString('de-DE')}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{loading ? (
|
||||
<div className="opacity-60 py-4 text-center text-sm">Laedt…</div>
|
||||
) : items.length === 0 ? (
|
||||
<div className="opacity-60 py-4 text-center text-sm">Keine eingeladenen Eltern.</div>
|
||||
) : (
|
||||
<table className="w-full text-sm">
|
||||
<thead className={isDark ? 'opacity-70' : 'opacity-70'}>
|
||||
<tr>
|
||||
<th className="text-left py-2">E-Mail</th>
|
||||
<th className="text-left py-2">Kind</th>
|
||||
<th className="text-left py-2">Klasse</th>
|
||||
<th className="text-left py-2">Sprache</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{items.map(it => (
|
||||
<tr key={it.child_id} className={isDark ? 'border-t border-white/10' : 'border-t border-slate-200'}>
|
||||
<td className="py-2">{it.email}</td>
|
||||
<td className="py-2">{it.child_first_name} {it.child_last_name}</td>
|
||||
<td className="py-2">{it.class_name}</td>
|
||||
<td className="py-2">{it.preferred_language}</td>
|
||||
<td className="py-2 text-right">
|
||||
<button onClick={() => handleDelete(it.child_id)} className="text-xs text-red-400 hover:text-red-300">Loeschen</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import { BundeslandWizard } from './_components/BundeslandWizard'
|
||||
import { EventModal } from './_components/EventModal'
|
||||
import { DayDetail } from './_components/DayDetail'
|
||||
import { RolloverWizard } from './_components/RolloverWizard'
|
||||
import { ParentManager } from './_components/ParentManager'
|
||||
|
||||
function monthRange(year: number, month: number): { from: string; to: string } {
|
||||
// Render the visible 6-week grid worth of holidays (covers prev/next month edges).
|
||||
@@ -168,6 +169,10 @@ export default function SchulkalenderPage() {
|
||||
onDone={() => { setShowRollover(false); loadHolidays() }}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="mt-6">
|
||||
<ParentManager />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -114,3 +114,48 @@ export const BUNDESLAENDER: { code: string; name: string }[] = [
|
||||
{ code: 'DE-SH', name: 'Schleswig-Holstein' },
|
||||
{ code: 'DE-TH', name: 'Thueringen' },
|
||||
]
|
||||
|
||||
// ---------- Parent invitations (Phase 9c) ----------
|
||||
|
||||
export interface ParentAccount {
|
||||
id: string
|
||||
email: string
|
||||
preferred_language: string
|
||||
}
|
||||
|
||||
export interface ParentChild {
|
||||
id: string
|
||||
parent_id: string
|
||||
tt_class_id: string
|
||||
first_name: string
|
||||
last_name: string
|
||||
class_name?: string
|
||||
}
|
||||
|
||||
export interface ParentInviteListItem {
|
||||
parent_id: string
|
||||
email: string
|
||||
preferred_language: string
|
||||
child_id: string
|
||||
child_first_name: string
|
||||
child_last_name: string
|
||||
class_id: string
|
||||
class_name: string
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export interface InviteParentRequest {
|
||||
email: string
|
||||
preferred_language?: string
|
||||
child_first_name: string
|
||||
child_last_name: string
|
||||
tt_class_id: string
|
||||
}
|
||||
|
||||
export interface InviteParentResponse {
|
||||
parent: ParentAccount
|
||||
child: ParentChild
|
||||
magic_token: string
|
||||
magic_url: string
|
||||
expires_at: string
|
||||
}
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import { test, expect, Page } from '@playwright/test'
|
||||
|
||||
/**
|
||||
* E2E for the Phase 9c parent-side: ParentManager on /schulkalender (teacher
|
||||
* UI) and the /eltern login + timetable view. Backend calls are intercepted
|
||||
* so the suite doesn't need a real teacher → parent invitation cycle.
|
||||
*/
|
||||
|
||||
async function mockTeacherCalendar(page: Page, opts: { classes?: unknown[]; parents?: unknown[]; invite?: unknown } = {}) {
|
||||
// Existing schulkalender mocks the page already needs.
|
||||
await page.route('**/api/school/calendar/config', async (route) => {
|
||||
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ user_id: 'dev', bundesland: 'DE-NI' }) })
|
||||
})
|
||||
await page.route(/\/api\/school\/calendar\/holidays(\?.*)?$/, async (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: '[]' }))
|
||||
await page.route(/\/api\/school\/calendar\/events(\?.*)?$/, async (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: '[]' }))
|
||||
|
||||
// ParentManager loads classes via the stundenplan API.
|
||||
await page.route('**/api/school/timetable/classes', async (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(opts.classes ?? []) }))
|
||||
|
||||
await page.route('**/api/school/calendar/parents', async (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(opts.parents ?? []) }))
|
||||
|
||||
await page.route('**/api/school/calendar/parents/invite', async (route) => {
|
||||
if (route.request().method() !== 'POST') return route.fulfill({ status: 405 })
|
||||
return route.fulfill({
|
||||
status: 201, contentType: 'application/json',
|
||||
body: JSON.stringify(opts.invite ?? {
|
||||
parent: { id: 'p1', email: 'mama@example.de', preferred_language: 'tr' },
|
||||
child: { id: 'c1', parent_id: 'p1', tt_class_id: 'class-1', first_name: 'Max', last_name: 'Mueller' },
|
||||
magic_token: 'abc123',
|
||||
magic_url: '/eltern/login?token=abc123',
|
||||
expires_at: new Date(Date.now() + 7 * 24 * 3600 * 1000).toISOString(),
|
||||
}),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
test.describe('Schulkalender — ParentManager', () => {
|
||||
test('renders empty state when no parents invited', async ({ page }) => {
|
||||
await mockTeacherCalendar(page, { classes: [{ id: 'class-1', name: '5a', grade_level: 5, student_count: 24, created_by_user_id: 'u', created_at: '' }] })
|
||||
await page.goto('/schulkalender')
|
||||
await page.waitForLoadState('networkidle')
|
||||
const manager = page.getByTestId('parent-manager')
|
||||
await expect(manager).toBeVisible()
|
||||
await expect(manager.getByText('Keine eingeladenen Eltern.')).toBeVisible()
|
||||
})
|
||||
|
||||
test('+ Eltern einladen opens the form when classes exist', async ({ page }) => {
|
||||
await mockTeacherCalendar(page, { classes: [{ id: 'class-1', name: '5a', grade_level: 5, student_count: 24, created_by_user_id: 'u', created_at: '' }] })
|
||||
await page.goto('/schulkalender')
|
||||
await page.waitForLoadState('networkidle')
|
||||
await page.getByTestId('parent-invite-toggle').click()
|
||||
await expect(page.getByTestId('parent-email')).toBeVisible()
|
||||
})
|
||||
|
||||
test('submitting invite shows the magic link to copy', async ({ page }) => {
|
||||
await mockTeacherCalendar(page, { classes: [{ id: 'class-1', name: '5a', grade_level: 5, student_count: 24, created_by_user_id: 'u', created_at: '' }] })
|
||||
await page.goto('/schulkalender')
|
||||
await page.waitForLoadState('networkidle')
|
||||
await page.getByTestId('parent-invite-toggle').click()
|
||||
await page.getByTestId('parent-email').fill('mama@example.de')
|
||||
await page.getByTestId('parent-child-first').fill('Max')
|
||||
await page.getByTestId('parent-child-last').fill('Mueller')
|
||||
await page.getByTestId('parent-class').selectOption('class-1')
|
||||
await page.getByTestId('parent-invite-submit').click()
|
||||
await expect(page.getByTestId('parent-invite-link')).toBeVisible()
|
||||
await expect(page.getByText('Einladungs-Link fuer mama@example.de')).toBeVisible()
|
||||
})
|
||||
})
|
||||
|
||||
async function mockParentApi(page: Page, opts: { redeemOk?: boolean; me?: unknown; lessons?: unknown[] } = {}) {
|
||||
const redeemOk = opts.redeemOk ?? true
|
||||
await page.route('**/api/parent/auth/redeem', async (route) => {
|
||||
if (!redeemOk) return route.fulfill({ status: 401, contentType: 'application/json', body: '{"error":"invalid"}' })
|
||||
return route.fulfill({
|
||||
status: 200, contentType: 'application/json',
|
||||
headers: { 'set-cookie': 'bp_parent_session=test; Path=/; HttpOnly' },
|
||||
body: JSON.stringify({ id: 'p1', email: 'mama@example.de', preferred_language: 'tr' }),
|
||||
})
|
||||
})
|
||||
await page.route('**/api/parent/me', async (route) => {
|
||||
return route.fulfill({
|
||||
status: 200, contentType: 'application/json',
|
||||
body: JSON.stringify(opts.me ?? {
|
||||
parent: { id: 'p1', email: 'mama@example.de', preferred_language: 'tr' },
|
||||
children: [{ id: 'c1', parent_id: 'p1', tt_class_id: 'class-1', first_name: 'Max', last_name: 'Mueller', class_name: '5a' }],
|
||||
}),
|
||||
})
|
||||
})
|
||||
await page.route(/\/api\/parent\/me\/timetable(\?.*)?$/, async (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(opts.lessons ?? []) }))
|
||||
await page.route('**/api/parent/auth/logout', async (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: '{"message":"ok"}' }))
|
||||
}
|
||||
|
||||
test.describe('Eltern — Login + Wochengrid', () => {
|
||||
test('login page shows error when no token in URL', async ({ page }) => {
|
||||
await mockParentApi(page)
|
||||
await page.goto('/eltern/login')
|
||||
await expect(page.getByTestId('eltern-login')).toBeVisible()
|
||||
await expect(page.getByText('Kein Token in der URL')).toBeVisible()
|
||||
})
|
||||
|
||||
test('valid token redirects to the parent overview', async ({ page }) => {
|
||||
await mockParentApi(page, {})
|
||||
await page.goto('/eltern/login?token=abc123')
|
||||
await page.waitForURL('**/eltern', { timeout: 3000 })
|
||||
await expect(page.getByTestId('eltern-page')).toBeVisible()
|
||||
})
|
||||
|
||||
test('shows greeting and child class on /eltern', async ({ page }) => {
|
||||
await mockParentApi(page)
|
||||
await page.goto('/eltern/login?token=abc123')
|
||||
await page.waitForURL('**/eltern')
|
||||
// Turkish greeting because preferred_language=tr.
|
||||
await expect(page.getByText('Hoş geldiniz, mama@example.de')).toBeVisible()
|
||||
await expect(page.getByText('Max Mueller · 5a')).toBeVisible()
|
||||
})
|
||||
|
||||
test('translates subject names into the parent language', async ({ page }) => {
|
||||
await mockParentApi(page, {
|
||||
lessons: [
|
||||
{ DayOfWeek: 1, PeriodIndex: 1, StartTime: '08:00', EndTime: '08:45', ClassName: '5a', SubjectName: 'Mathematik', SubjectCode: 'M', TeacherName: 'Schmidt, Anna', RoomName: 'A101', Pinned: false },
|
||||
],
|
||||
})
|
||||
await page.goto('/eltern/login?token=abc123')
|
||||
await page.waitForURL('**/eltern')
|
||||
// Turkish target = Matematik.
|
||||
await expect(page.getByTestId('eltern-cell-1-1').getByText('Matematik')).toBeVisible()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* Subject-name translations for the parent-facing weekly grid.
|
||||
*
|
||||
* The teacher enters German subject names in tt_subject.name. For parents
|
||||
* whose preferred_language differs, we look up the German name in this
|
||||
* table and substitute the localised version. If no match (custom AG,
|
||||
* Wahlfach, ...), the German original is shown.
|
||||
*
|
||||
* Keys are normalised lowercase German subject names. Languages cover the
|
||||
* 8 most-common parent locales in DE schools; everything else falls back
|
||||
* to German.
|
||||
*/
|
||||
|
||||
type SupportedLanguage = 'de' | 'en' | 'tr' | 'ar' | 'uk' | 'ru' | 'pl' | 'fr'
|
||||
|
||||
interface SubjectTranslation {
|
||||
de: string
|
||||
en: string
|
||||
tr: string
|
||||
ar: string
|
||||
uk: string
|
||||
ru: string
|
||||
pl: string
|
||||
fr: string
|
||||
}
|
||||
|
||||
const SUBJECTS: Record<string, SubjectTranslation> = {
|
||||
mathematik: { de: 'Mathematik', en: 'Mathematics', tr: 'Matematik', ar: 'الرياضيات', uk: 'Математика', ru: 'Математика', pl: 'Matematyka', fr: 'Mathématiques' },
|
||||
mathe: { de: 'Mathe', en: 'Maths', tr: 'Matematik', ar: 'الرياضيات', uk: 'Математика', ru: 'Математика', pl: 'Matematyka', fr: 'Maths' },
|
||||
deutsch: { de: 'Deutsch', en: 'German', tr: 'Almanca', ar: 'الألمانية', uk: 'Німецька мова', ru: 'Немецкий язык', pl: 'Język niemiecki', fr: 'Allemand' },
|
||||
englisch: { de: 'Englisch', en: 'English', tr: 'İngilizce', ar: 'الإنجليزية', uk: 'Англійська мова', ru: 'Английский язык', pl: 'Język angielski', fr: 'Anglais' },
|
||||
franzoesisch: { de: 'Franzoesisch', en: 'French', tr: 'Fransızca', ar: 'الفرنسية', uk: 'Французька мова', ru: 'Французский язык', pl: 'Język francuski', fr: 'Français' },
|
||||
spanisch: { de: 'Spanisch', en: 'Spanish', tr: 'İspanyolca', ar: 'الإسبانية', uk: 'Іспанська мова', ru: 'Испанский язык', pl: 'Język hiszpański', fr: 'Espagnol' },
|
||||
latein: { de: 'Latein', en: 'Latin', tr: 'Latince', ar: 'اللاتينية', uk: 'Латинська мова', ru: 'Латинский язык', pl: 'Łacina', fr: 'Latin' },
|
||||
sachkunde: { de: 'Sachkunde', en: 'General Studies', tr: 'Hayat Bilgisi', ar: 'الدراسات العامة', uk: 'Природознавство', ru: 'Окружающий мир', pl: 'Wiedza o przyrodzie', fr: 'Découverte du monde' },
|
||||
sport: { de: 'Sport', en: 'PE', tr: 'Beden Eğitimi', ar: 'التربية البدنية', uk: 'Фізкультура', ru: 'Физкультура', pl: 'WF', fr: 'EPS' },
|
||||
musik: { de: 'Musik', en: 'Music', tr: 'Müzik', ar: 'الموسيقى', uk: 'Музика', ru: 'Музыка', pl: 'Muzyka', fr: 'Musique' },
|
||||
kunst: { de: 'Kunst', en: 'Art', tr: 'Sanat', ar: 'الفن', uk: 'Мистецтво', ru: 'Искусство', pl: 'Plastyka', fr: 'Arts plastiques' },
|
||||
religion: { de: 'Religion', en: 'Religion', tr: 'Din Bilgisi', ar: 'الدين', uk: 'Релігія', ru: 'Религия', pl: 'Religia', fr: 'Religion' },
|
||||
ethik: { de: 'Ethik', en: 'Ethics', tr: 'Etik', ar: 'الأخلاق', uk: 'Етика', ru: 'Этика', pl: 'Etyka', fr: 'Éthique' },
|
||||
biologie: { de: 'Biologie', en: 'Biology', tr: 'Biyoloji', ar: 'الأحياء', uk: 'Біологія', ru: 'Биология', pl: 'Biologia', fr: 'Biologie' },
|
||||
chemie: { de: 'Chemie', en: 'Chemistry', tr: 'Kimya', ar: 'الكيمياء', uk: 'Хімія', ru: 'Химия', pl: 'Chemia', fr: 'Chimie' },
|
||||
physik: { de: 'Physik', en: 'Physics', tr: 'Fizik', ar: 'الفيزياء', uk: 'Фізика', ru: 'Физика', pl: 'Fizyka', fr: 'Physique' },
|
||||
geschichte: { de: 'Geschichte', en: 'History', tr: 'Tarih', ar: 'التاريخ', uk: 'Історія', ru: 'История', pl: 'Historia', fr: 'Histoire' },
|
||||
geografie: { de: 'Geografie', en: 'Geography', tr: 'Coğrafya', ar: 'الجغرافيا', uk: 'Географія', ru: 'География', pl: 'Geografia', fr: 'Géographie' },
|
||||
erdkunde: { de: 'Erdkunde', en: 'Geography', tr: 'Coğrafya', ar: 'الجغرافيا', uk: 'Географія', ru: 'География', pl: 'Geografia', fr: 'Géographie' },
|
||||
politik: { de: 'Politik', en: 'Civics', tr: 'Vatandaşlık', ar: 'التربية الوطنية', uk: 'Громадянознавство', ru: 'Обществознание', pl: 'Wiedza o społeczeństwie', fr: 'Éducation civique' },
|
||||
informatik: { de: 'Informatik', en: 'Computer Science', tr: 'Bilişim', ar: 'علوم الحاسوب', uk: 'Інформатика', ru: 'Информатика', pl: 'Informatyka', fr: 'Informatique' },
|
||||
wirtschaft: { de: 'Wirtschaft', en: 'Economics', tr: 'Ekonomi', ar: 'الاقتصاد', uk: 'Економіка', ru: 'Экономика', pl: 'Ekonomia', fr: 'Économie' },
|
||||
}
|
||||
|
||||
/**
|
||||
* Translate a German subject name into the requested language.
|
||||
* Falls back to the original input if no match in the table or no
|
||||
* translation for the target language.
|
||||
*/
|
||||
export function translateSubject(germanName: string, lang: string): string {
|
||||
if (!germanName) return germanName
|
||||
const key = germanName.toLowerCase().trim()
|
||||
const row = SUBJECTS[key]
|
||||
if (!row) return germanName
|
||||
const code = (lang || 'de').slice(0, 2) as SupportedLanguage
|
||||
return row[code] || row.de || germanName
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* Parent API client. Cookies (HttpOnly bp_parent_session) carry auth —
|
||||
* we never store the session token in JS-readable storage. credentials:
|
||||
* 'include' is mandatory so the cookie ships with each request.
|
||||
*/
|
||||
|
||||
const PROXY_PREFIX = '/api/parent'
|
||||
|
||||
interface FetchOptions extends RequestInit {
|
||||
expectJson?: boolean
|
||||
}
|
||||
|
||||
async function parentFetch<T>(endpoint: string, opts: FetchOptions = {}): Promise<T> {
|
||||
const res = await fetch(`${PROXY_PREFIX}${endpoint}`, {
|
||||
...opts,
|
||||
credentials: 'include',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(opts.headers as Record<string, string> | undefined),
|
||||
},
|
||||
})
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({ error: 'Unknown error' }))
|
||||
throw new Error(err.error || `HTTP ${res.status}`)
|
||||
}
|
||||
if (res.status === 204) return undefined as T
|
||||
return res.json()
|
||||
}
|
||||
|
||||
export interface ParentMeResponse {
|
||||
parent: { id: string; email: string; preferred_language: string }
|
||||
children: Array<{
|
||||
id: string
|
||||
parent_id: string
|
||||
tt_class_id: string
|
||||
first_name: string
|
||||
last_name: string
|
||||
class_name?: string
|
||||
}>
|
||||
}
|
||||
|
||||
export interface ParentLesson {
|
||||
DayOfWeek: number
|
||||
PeriodIndex: number
|
||||
StartTime: string
|
||||
EndTime: string
|
||||
ClassName: string
|
||||
SubjectName: string
|
||||
SubjectCode: string
|
||||
TeacherName: string
|
||||
RoomName: string
|
||||
Pinned: boolean
|
||||
}
|
||||
|
||||
export const elternApi = {
|
||||
redeem: (token: string) =>
|
||||
parentFetch<{ id: string; email: string; preferred_language: string }>('/auth/redeem', {
|
||||
method: 'POST', body: JSON.stringify({ token }),
|
||||
}),
|
||||
me: () => parentFetch<ParentMeResponse>('/me'),
|
||||
timetable: (classId: string) =>
|
||||
parentFetch<ParentLesson[]>(`/me/timetable?class_id=${encodeURIComponent(classId)}`),
|
||||
logout: () => parentFetch<void>('/auth/logout', { method: 'POST' }),
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import { getStundenplanToken } from '@/lib/stundenplan/api'
|
||||
import type {
|
||||
PublicEvent, SchoolCalendarConfig, UpsertSchoolCalendarConfig,
|
||||
SchoolEvent, CreateSchoolEvent, SchoolYearRolloverResult,
|
||||
ParentInviteListItem, InviteParentRequest, InviteParentResponse,
|
||||
} from '@/app/schulkalender/types'
|
||||
|
||||
async function apiFetch<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
|
||||
@@ -49,4 +50,11 @@ export const calendarApi = {
|
||||
new_year_end: newYearEnd,
|
||||
}),
|
||||
}),
|
||||
|
||||
// Phase 9c: parent invitations
|
||||
listParents: () => apiFetch<ParentInviteListItem[]>('/calendar/parents'),
|
||||
inviteParent: (data: InviteParentRequest) =>
|
||||
apiFetch<InviteParentResponse>('/calendar/parents/invite', { method: 'POST', body: JSON.stringify(data) }),
|
||||
deleteParentChild: (childId: string) =>
|
||||
apiFetch<void>(`/calendar/parents/children/${childId}`, { method: 'DELETE' }),
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user