54 Commits
Author SHA1 Message Date
admin fb38b6bb04 Fix unit persistence before saving timetable lessons
CI / build-and-test (push) Canceled after 0s
2026-11-09 21:50:36 +01:00
admin cbcb739097 Refresh case documentation on tab change and expose linking section
CI / build-and-test (push) Canceled after 0s
2026-10-28 16:36:46 +01:00
admin 3f7c055489 Fix visibility of existing documentation links in cases
CI / build-and-test (push) Canceled after 0s
2026-10-28 14:46:34 +01:00
adminandClaude Sonnet 5.5 d61a97de1e Punkteeingabe: nur angefahrene Zeilen nicht mehr als 0 Punkte/Note 6 speichern
CI / build-and-test (push) Canceled after 0s
Das Verlassen eines unveränderten Punktefelds löste Autosave aus; leere Zellen
wurden als 0 gespeichert und ergaben Note 6. Zellen melden nur noch echte
Änderungen, Zeilen ohne Werte werden nicht angelegt und haben keine Note.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-22 22:12:13 +02:00
adminandClaude Sonnet 5.5 41649b0a05 Förderschüler je Gruppe markieren und Förderarbeit darauf beschränken
GroupMembership.IsSupportStudent markiert Förderschüler unabhängig von der
Niveaudifferenzierung (Checkbox-Spalte in der Schülerliste; in differenzierten
Gruppen zählt das Förderniveau). Punkteeingabe und Deckblätter einer
Förderarbeit zeigen nur Förderschüler und Schüler mit vorhandenem Ergebnis.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-22 21:00:56 +02:00
adminandClaude Sonnet 5.5 651c9cddf8 Förderarbeit als dritte Folgearbeits-Art ergänzen
Neben Wiederholung und Nachschreibarbeit gibt es im Arbeitsdialog die Art
Förderarbeit (Exam.IsSupportWork). Sie darf am Tag der ersten Arbeit liegen,
übernimmt dessen Datum als Vorschlag und ersetzt wie eine Nachschreibarbeit
nur fehlende Noten.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-22 20:55:27 +02:00
admin 10921deb34 KI-Einstellungen um Feature- und Verbrauchsübersicht erweitern
CI / build-and-test (push) Canceled after 0s
2026-10-22 11:40:19 +02:00
admin e2f019667a Schülerberichte und erweiterte Deckblatt-Bausteine ergänzen
CI / build-and-test (push) Canceled after 0s
2026-10-22 11:24:43 +02:00
admin 336869e75f Gemeinsames PHP-Backend nach LehrerBackend ausgliedern
CI / build-and-test (push) Canceled after 0s
2026-10-19 10:03:42 +02:00
admin 97eb41a0ea Fix early departure classification and calendar markers
CI / build-and-test (push) Canceled after 0s
2026-10-08 12:04:40 +02:00
admin a3cd57e5d8 Fix class teacher full-day absence classification
CI / build-and-test (push) Canceled after 0s
2026-10-08 11:20:17 +02:00
adminandClaude Opus 5.5 e4a81e8974 Klausur-Deckblatt: Fortschrittsbalken und Erzeugung im Hintergrund
CI / build-and-test (push) Canceled after 0s
Ein Klassensatz dauert spürbar und fror den Dialog ein. GenerateAsync
setzt jetzt per Task.Run, RenderBatchToPdf meldet jeden gesetzten
Datensatz über ein optionales IProgress<int>. Das abschließende
Document.Merge meldet nichts, dort läuft der Balken unbestimmt.
Währenddessen sind die Schaltflächen gesperrt und der Dialog bleibt
offen. Ein einzelnes Deckblatt wird nicht mehr doppelt gesetzt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 09:00:15 +02:00
adminandClaude Opus 5.5 24a30881f3 Klausur-Deckblatt: Titel im Dialog je Druck anpassbar
CI / build-and-test (push) Canceled after 0s
Der interne Klausurtitel passt nicht immer aufs Deckblatt. Das neue Feld
ist mit ihm vorbelegt, ändert nur Exam.Title für diesen Druck und fällt
leer gelassen auf den internen Titel zurück.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 08:55:10 +02:00
adminandClaude Opus 5.5 2293ddb84d Klausur-Deckblatt: Bonusaufgabe in der Punktetabelle mit „Bonus“ beschriften
CI / build-and-test (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 08:25:25 +02:00
adminandClaude Opus 5.5 702694d4f4 Templating: align=center/right in fest positionierter TEXTBOX/FLOWBOX
Der Container wurde horizontal auf die Textbreite geschrumpft, sodass die
Ausrichtung wirkungslos blieb. Der Auswahlrahmen für TEXT im Designer folgt
jetzt w= bzw. der Zeilenbreite bei align=center/right.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 08:15:02 +02:00
adminandClaude Sonnet 5.5 d1f3dd5148 Templating: TEXT mit w= für zentrierte und rechtsbündige Zeilen
CI / build-and-test (push) Canceled after 0s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 23:04:46 +02:00
adminandClaude Opus 5.5 98c5f9eba0 TemplateDesigner: Klausur-Deckblatt einrichten und Punktetabelle in der Vorschau
CI / build-and-test (push) Canceled after 0s
Platzhalterkatalog und Tabellen-Zeichner liegen jetzt in LehrerApp.Templating,
damit Designer und Hauptapp dieselbe Tabelle zeichnen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 10:47:12 +02:00
adminandClaude Opus 5.5 dd92128464 Klausur-Deckblätter als Sammel-PDF aus Vorlagen vom Typ exam-cover
Neuer Dialog "Deckblätter…" bei Klausuren, Punktetabelle als Drawing mit
festen Spaltenbreiten, FLOWDRAWBOX-Attribut fit=content, Stapel-Rendering
mit Seitenzahl je Datensatz, Kursbezeichnung und konfigurierbares Kürzel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 10:39:09 +02:00
admin f56caced32 Manuellen WebUntis-Abgleich für Unterrichtsnummern und Stundenplan ergänzen
CI / build-and-test (push) Canceled after 0s
2026-10-06 13:29:05 +02:00
adminandClaude Opus 5.5 d9eac0d1d2 Zwischenstand: vorläufige Noten zu Stichtag und Anlass
CI / build-and-test (push) Canceled after 0s
Ein Zwischenstand ist ein Durchgang aus Stichtag, Anlass und
Schülerauswahl (ganze Gruppe, Teilgruppe oder Einzelfall, mit
Schnellfilter für gefährdete Schüler). Der Zeugnisnoten-Assistent geht
die gewählten Schüler im Zwischenstand-Modus durch und notiert
vorläufige schriftliche, mündliche und Gesamtnote samt Notiz.

Gespeichert wird das als eigenes Modell InterimGrade, getrennt von der
Zeugnisnote. Die Berechnung endet am Stichtag und rechnet den laufenden
Mitarbeits-Abschnitt mit ein. Zwischenstände erscheinen im Assistenten
als Liste und Marker im Verlauf sowie als graue Spalte in der
Notenübersicht (nicht in "Gesamt", nicht im PDF).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 13:01:34 +02:00
adminandClaude Opus 5.5 67c5a906d1 Zeugnisnoten-Assistent mit Mitarbeitsverlauf und Prüfungsnoten Klasse 10
CI / build-and-test (push) Canceled after 0s
Neuer Assistent (Einstieg im Zeugnisnoten-Dialog) geht die Lerngruppe
Schüler für Schüler durch: berechnete Note mit ungerundetem Wert und
Teilbereichen, Mitarbeitsgraph abschnittsweise oder als Verlauf, Arbeiten
und Einzelnoten. Das 1. Halbjahr erscheint im 2. Halbjahr nur als Kontext.

Die Endjahresnote wird jetzt in Dialog und Assistent aus den
Halbjahresnoten verrechnet (gemeinsamer ReportGradeCalculator). In Klasse 10
kommen Projektprüfung, schriftliche/mündliche Abschlussprüfung und
zusätzliche mündliche Prüfung hinzu, gewichtet nach Oberschulverordnung und
PrüfV Sek. I; gerundet wird dabei bewusst nicht automatisch.

Die Zeitleisten-Erzeugung des Mitarbeits-Assistenten liegt dafür im
gemeinsamen ParticipationTimelineBuilder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 12:09:33 +02:00
admin 20a3ce8896 update win icon
CI / build-and-test (push) Canceled after 0s
2026-10-06 10:29:54 +02:00
admin e9da06fab5 update iconset
CI / build-and-test (push) Canceled after 0s
2026-10-06 08:47:32 +02:00
admin d277e901f0 New Icon for Mac
CI / build-and-test (push) Canceled after 0s
2026-10-06 08:30:49 +02:00
adminandClaude Opus 5.5 4f61c1fbd2 Datenschutzkonforme Einzelansicht für Klausurergebnisse
CI / build-and-test (push) Canceled after 0s
Neuer Dialog ExamRevealDialog: zeigt zunächst nur den Namen eines Schülers,
erst nach „Aufdecken“ Note, Punktzahl und Punkte je Aufgabe. Blättern und
gezielte Auswahl oben; jeder Schülerwechsel deckt wieder zu. Erreichbar über
„Einzelansicht“ im Klausuren-Tab und auf der Klausuren-Hauptseite.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 08:15:45 +02:00
adminandClaude Sonnet 5.5 c0f8b98202 Nachschreibarbeiten und Arbeitsarten (Test, kontrollierte Hausaufgabe)
CI / build-and-test (push) Canceled after 0s
Nachschreibarbeiten nutzen die Wiederholungs-Verknüpfung, ersetzen aber nur
fehlende Noten; mehrere Folgearbeiten je erster Arbeit sind möglich.
Exam.Kind trennt Klausuren (schriftlich) von Tests u. Ä. (Sonstige).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-05 22:54:31 +02:00
adminandClaude Opus 5.5 d7898d5678 Punkteeingabe: Korrekturmodus wählbar, Bonusaufgaben nicht mitnummeriert
CI / build-and-test (push) Canceled after 0s
- "Enter springt: Schüler für Schüler / Aufgabe für Aufgabe" im Dialog wählbar und gemerkt;
  Umschalt+Enter zurück, Pfeiltasten springen direkt und öffnen das Eingabefeld
- Tasten per Tunnel-Handler abgefangen, bevor DataGrid/TextBox sie auswerten
- Abwesende Schüler und Aufgaben der anderen Fassung werden übersprungen
- Zellen lesen ihre Zeile aus dem DataContext (recycelte Zeilen schreiben nicht mehr falsch)
- Bonusaufgaben zählen bei der angezeigten Nummerierung nicht mit

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 23:36:12 +02:00
adminandClaude Opus 5.5 6c0a2dbd2e Nachreichungen direkt im Unterrichtsmodus erfassen
CI / build-and-test (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 23:38:45 +02:00
admin f0462bd2a1 Add animated classroom grouping with saved editable plans
CI / build-and-test (push) Canceled after 0s
2026-09-29 22:17:49 +02:00
admin d4b1419f9a Add configurable student group generator
CI / build-and-test (push) Canceled after 0s
2026-09-29 14:22:59 +02:00
admin c79d96c5ec Add intelligent random student picker
CI / build-and-test (push) Canceled after 0s
2026-09-29 14:02:48 +02:00
adminandClaude Opus 5.5 770a1833c8 Zurückgestellte Dashboard-Warnungen in eigener Gruppe sammeln
CI / build-and-test (push) Canceled after 0s
Entschärfte Warnungen (zurückgestellt oder Vorgang in Bearbeitung) liefen
bisher grau am Ende ihrer Art-Gruppe mit und zählten weiter zu den offenen
Punkten. Sie stehen jetzt in einer eingeklappten "Zurückgestellt"-Gruppe
ganz unten, mit dem Grund als Untertitel, und zählen nicht mehr mit. Nach
Fristablauf kehren sie automatisch in ihre Gruppe und die Zählung zurück.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 09:20:16 +02:00
adminandClaude Opus 5.5 7d8deaf79c Zurückstellen von Dashboard-Warnungen synchronisieren
CI / build-and-test (push) Canceled after 0s
Eine auf einem Gerät zurückgestellte Warnung stand auf den anderen weiter
rot oben, weil DashboardWarningSnooze bewusst lokal gehalten war. Save löst
jetzt db.OnChange aus, EventApplier übernimmt den Typ. Die Id wird aus
(StudentId, WarningTag) abgeleitet, damit zwei Geräte denselben Datensatz
beschreiben statt am Unique-Index ux_student_tag zu kollidieren;
Schema-Migration 7 schlüsselt bestehende lokale Einträge um.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 09:03:44 +02:00
adminandClaude Opus 5.5 9a84bbaa38 Gemeinsame Dokumentation für mehrere Beteiligte eines Vorgangs
CI / build-and-test (push) Canceled after 0s
Ein Dokumentationseintrag kann jetzt weitere Schüler*innen betreffen
(Documentation.AdditionalStudentIds, StudentId bleibt Hauptperson). Der
Eintrag existiert nur einmal, erscheint aber im Dokumentations-Tab jeder
beteiligten Person. Der Dokumentations-Dialog bietet in beiden
Vorgänge-Tabs "Betrifft außerdem" mit den Beteiligten des Vorgangs an.
Klassenlehrer-Listen, WebUntis-Abgleich, Löschfristen und
Referenzzählung berücksichtigen die weiteren Beteiligten.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 08:43:24 +02:00
admin e091b5c8de Stundenweise Fehlzeiten getrennt auswerten 2026-09-28 08:39:40 +02:00
adminandClaude Opus 5.5 aa326cf8b6 Add warning detail popup and quick blocks for Vorgänge
CI / build-and-test (push) Canceled after 0s
Dashboard warnings (attendance, homework, lateness) get a "Details" flyout
with key figures, a list of dates and the compact month calendar from the
class teacher overview, now extracted as a shared control. The calendar
now aligns days under their weekday (Mo-So header, blank leading cells).

Creating Vorgänge and documentation is supported by quick blocks with the
current figures, dated standard phrases (e.g. "Klassenleitung informiert")
and documentation templates (status snapshot, conversation, informing the
class/subject teachers, parent call, parent letter). The class teacher
Vorgänge tab uses WebUntis figures (absences across all subjects, class
register) for the same blocks and templates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 11:16:13 +02:00
admin 0f6cadc9c8 Rahmen nur am Klausurtag anzeigen 2026-09-26 10:51:58 +02:00
admin 431d023c1a Klausurvarianten, Bonuspunkte und Wiederholungen ergänzen 2026-09-26 10:42:11 +02:00
adminandClaude Sonnet 5 54ad7f7419 Defuse handled dashboard warnings and add a snooze action
CI / build-and-test (push) Canceled after 0s
Cross-class warnings (attendance, homework backlog, lateness) stayed red
and at the top even after being acted on. A warning now turns gray and
sorts to the bottom of its group once a recently-updated open Vorgang
with a matching tag exists, or once explicitly snoozed for 1/2/4 weeks.
Both are time-limited: once the grace period lapses without the
underlying number actually improving, the warning goes active again on
the next dashboard load - no background job needed since it's just
recomputed on every RebuildAttention.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-26 00:48:39 +02:00
adminandClaude Sonnet 5 3270b48850 Add student-level Vorgänge tab and homework/lateness dashboard warnings
CI / build-and-test (push) Canceled after 0s
Dashboard warnings (attendance, and now homework backlog and lateness) apply
across all classes, but the existing Vorgänge case-file tab only works for
the teacher's own class since it resolves the WebUntis classbook roster.
Instead of loosening that coupling, students get their own narrower
Vorgänge tab, and all three cross-class warnings now jump straight there,
offering to open a matching case or create a new one.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-25 23:55:54 +02:00
admin 4b73d2bea2 Automate overdue homework and show outstanding work in teaching mode
CI / build-and-test (push) Canceled after 0s
2026-09-25 22:02:00 +02:00
admin f3e23ad207 Fix Untis homework comparison and student selection 2026-09-25 21:33:54 +02:00
admin 1291b24478 Untis-Fehlzeiten und Dashboard-Hinweise verfeinern
CI / build-and-test (push) Canceled after 0s
2026-09-25 12:09:32 +02:00
admin 960d52686a Stundenplan und Untis-Namensabgleich verbessern
CI / build-and-test (push) Canceled after 0s
2026-09-25 11:54:51 +02:00
admin 45b7a2b7e6 Fix: Klausur Pull aus Untis
CI / build-and-test (push) Canceled after 0s
2026-09-24 00:19:37 +02:00
adminandClaude Sonnet 5 30f0fee0b2 fix: KI-Backend brach lange Anfragen durch PHP-Timeout ab
CI / build-and-test (push) Canceled after 0s
ai_backend_call_and_charge (db.php) hob PHPs eigenes max_execution_time
nie an, obwohl AnthropicProvider dem curl-Aufruf bis zu 180s erlaubt.
Auf vielen Hosts liegt PHPs Default bei nur 30s - sobald ein Aufruf
laenger brauchte, killte PHP das Skript mitten in curl_exec() mit einem
unabfangbaren Fatal Error statt einer sauberen {"error": "..."}-Antwort.
Der Desktop-Client zeigte dadurch nur die pauschale Fallback-Meldung
ohne Grund - sah wie ein kompletter Ausfall der Einzelstunden-KI-Planung
aus, war aber ein request-Dauer-abhaengiger Timeout, der jeden der fuenf
ai_backend_call_and_charge-Endpunkte treffen konnte.

Fix zentral in ai_backend_call_and_charge (set_time_limit(200)) statt in
jedem Endpunkt einzeln - nach Deployment vom Nutzer verifiziert. Zusaetzlich
dauerhaftes Diagnose-Logging in AiPlanningService (Statuscode/Dauer/
Antwort-Body bei Fehlern ohne auswertbaren Grund) fuer kuenftige Faelle.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-21 00:27:52 +02:00
admin f0c0479bcb feat: improve WebUntis sync and competency insights
CI / build-and-test (push) Canceled after 0s
2026-09-20 22:17:29 +02:00
adminandClaude Sonnet 5 cdb4637c65 fix: Fach-Auswahl im Kompetenzkatalog war unsichtbar
CI / build-and-test (push) Canceled after 0s
Klassenstufe (90px) + Bildungsplan-Version (160px) + die drei Buttons (JSON
importieren/exportieren, Kopieren) allein verlangten schon mehr Breite als die
MaxWidth (640) des umgebenden Panels her gab, da sie mit der Fach-Combobox in
derselben Grid-Zeile standen. Die "*"-breite Fach-Combobox wurde dadurch auf 0px
gequetscht - im Kompetenzen-Tab sichtbar war nur die (leere) Versions-Combobox,
die Fach-Auswahl selbst nicht erreichbar.

Fach/Klassenstufe/Version stehen jetzt in einer eigenen Zeile, die drei
Aktionsbuttons darunter.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-20 00:27:22 +02:00
adminandClaude Sonnet 5 ecf64fff88 fix: Sync-Ausfälle aktiv melden, Einstellungen-Absturz durch Connection-Konflikt beheben
CI / build-and-test (push) Canceled after 0s
Ein Sync-Ausfall (offline/Fehler) war bisher nur als blasser Text in der Statuszeile
sichtbar und konnte so stundenlang unbemerkt bleiben, bis auf einem anderen Gerät
Daten fehlten. SyncStatusViewModel meldet neue Ausfälle jetzt einmalig aktiv per Toast
(nicht bei jedem automatischen Retry erneut).

DatabaseEncryptionService.IsEncrypted/VerifyPassword öffneten die Datenbankdatei mit
einer zweiten, exklusiven (Direct) LiteDB-Verbindung, während LiteDbContext dieselbe
Datei bereits im Shared-Modus offen hält - jeder Aufruf (z.B. beim Öffnen der
Einstellungen) crashte reproduzierbar mit IOException. Beide öffnen jetzt ebenfalls im
Shared-Modus und erzwingen einen tatsächlichen Lesezugriff, da Shared-Verbindungen die
Datei lazy öffnen.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-20 00:07:33 +02:00
admin 22eceb3ac1 fix: Kompetenzkataloge im Sync nachreichen 2026-09-20 00:03:45 +02:00
admin 0f2a25feb5 Fix Kompetenzlisten ansicht
CI / build-and-test (push) Canceled after 0s
2026-09-19 23:52:46 +02:00
adminandClaude Sonnet 5 0942a8ebcf docs: dokumentiere Neustart-Erfordernis nach set-password/create-user
Die Server-API cached users.db im laufenden Prozess; ein externer Schreib-
zugriff der CLI wird erst nach einem Container-Neustart wirksam.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-19 23:31:11 +02:00
adminandClaude Sonnet 5 455f7765e4 feat: Kompetenz-Bewertung je Schüler/Sitzung aus Mitarbeit-Durchschnitt schätzen
CI / build-and-test (push) Canceled after 0s
Manuelle Einzelerfassung je Kompetenz war im Alltag zu aufwendig (Nutzer-Feedback). Neue
ParticipationCompetencyEstimate mittelt die bereits erfassten Aspekt-Bewertungen der Sitzung
(normiert auf dieselbe -2..+2-Achse) und rundet auf den nächsten Schritt; die Tagesflagge wirkt
symmetrisch (Spitzentag hebt, Schlaftag/Schlechter Tag senken gleichermaßen).

Die Schätzung wird nie automatisch gespeichert - sie erscheint nur als abgeschwächt dargestellter
Zellenwert (RatingCell.IsEstimated), solange keine explizite Bewertung existiert. Ein Klick setzt
den Wert bewusst und persistiert ihn wie bisher.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-19 01:57:45 +02:00
adminandClaude Sonnet 5 51e55e1464 feat: MCP-Tools für Mitarbeit-Sitzungen (ParticipationTools)
Mitarbeit-Sitzungen waren bisher komplett MCP-unerreichbar. Neue ParticipationTools-Klasse
exponiert get_participation_sessions (Datum, Kommentar, zugeordnete Kompetenzen) sowie
add_session_competency/remove_session_competency, nach demselben Einzel-Zuordnung-Muster wie
LessonPlanTools. Bewusst ohne die einzelnen Schülerbewertungen (ParticipationEntry) - die bleiben
personenbezogen und MCP-unerreichbar.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-19 00:54:19 +02:00
279 changed files with 19569 additions and 2457 deletions

No files matched your search

+12
View File
@@ -42,6 +42,13 @@ The API can also run via `docker/docker-compose.yml` (reads `JWT_SECRET` from th
### Project layout ### Project layout
The PHP backend has lived in the independent
[LehrerBackend repository](https://git.science-teaching.de/admin/LehrerBackend) since
2026-10-19 (local sibling `../LehrerBackend/`). `ai-backend/README.md` is only a pointer;
change PHP endpoints, providers, authentication and billing in LehrerBackend. Older
`ai-backend/...` paths in comments/TODO refer to the new repository root. Desktop clients and
DTOs stay here; no submodule or local backend checkout is needed to build the app.
- **LehrerApp.Core** — domain models (`Models/`), repository interfaces (`Interfaces/IRepositories.cs`), - **LehrerApp.Core** — domain models (`Models/`), repository interfaces (`Interfaces/IRepositories.cs`),
and framework-free business services (`Services/`): `GradingService` (rounding, grading-key and framework-free business services (`Services/`): `GradingService` (rounding, grading-key
validation, report-grade calculation), `SchoolYearService`, `AppLogger`, `BackupService`, validation, report-grade calculation), `SchoolYearService`, `AppLogger`, `BackupService`,
@@ -123,6 +130,11 @@ The API can also run via `docker/docker-compose.yml` (reads `JWT_SECRET` from th
idempotency forever. idempotency forever.
- `new LiteDbContext(stream)` opens an in-memory database from a `MemoryStream` — used pervasively - `new LiteDbContext(stream)` opens an in-memory database from a `MemoryStream` — used pervasively
in tests for a fast, disk-free `LiteDbContext`. in tests for a fast, disk-free `LiteDbContext`.
- `LehrerApp.Api`'s `Cli.cs` (`create-user`/`set-password`) opens `users.db` as a second, separate
`LiteDatabase` instance in a short-lived process next to the already-running server's own
instance. The write lands on disk correctly, but the running server process keeps serving logins
against its own in-memory state and never picks up the external change — `docker restart` on the
API container after running the CLI is required for the new password to actually take effect.
### Central Package Management ### Central Package Management
+1
View File
@@ -9,6 +9,7 @@
<PackageVersion Include="Avalonia.Themes.Fluent" Version="12.0.4" /> <PackageVersion Include="Avalonia.Themes.Fluent" Version="12.0.4" />
<PackageVersion Include="Avalonia.Fonts.Inter" Version="12.0.4" /> <PackageVersion Include="Avalonia.Fonts.Inter" Version="12.0.4" />
<PackageVersion Include="Avalonia.Controls.DataGrid" Version="12.0.0" /> <PackageVersion Include="Avalonia.Controls.DataGrid" Version="12.0.0" />
<PackageVersion Include="Avalonia.Labs.Lottie" Version="12.0.2" />
<!-- MVVM & DI – .NET 10 kompatibel --> <!-- MVVM & DI – .NET 10 kompatibel -->
<PackageVersion Include="CommunityToolkit.Mvvm" Version="8.4.0" /> <PackageVersion Include="CommunityToolkit.Mvvm" Version="8.4.0" />
+2
View File
@@ -24,6 +24,7 @@ internal static class Cli
} }
Console.WriteLine($"Nutzer '{username}' angelegt."); Console.WriteLine($"Nutzer '{username}' angelegt.");
Console.WriteLine("Hinweis: Server-Container neu starten, damit die Änderung wirksam wird (LiteDB im laufenden Serverprozess sieht externe Schreibzugriffe sonst nicht).");
return Task.FromResult(0); return Task.FromResult(0);
} }
@@ -47,6 +48,7 @@ internal static class Cli
} }
Console.WriteLine($"Passwort für '{username}' aktualisiert."); Console.WriteLine($"Passwort für '{username}' aktualisiert.");
Console.WriteLine("Hinweis: Server-Container neu starten, damit die Änderung wirksam wird (LiteDB im laufenden Serverprozess sieht externe Schreibzugriffe sonst nicht).");
return Task.FromResult(0); return Task.FromResult(0);
} }
+4 -3
View File
@@ -227,8 +227,9 @@ public class AiUntisStatusResponse
public class AiUntisStatusSuggestion public class AiUntisStatusSuggestion
{ {
public string Id { get; set; } = ""; public string Id { get; set; } = "";
/// Einer von "Present"/"Late"/"LeftDuringClass"/"ExcusePending"/"Excused"/"Unexcused" (siehe /// Einer von "Present"/"Late"/"SignificantlyLate"/"LeftDuringClass"/"ExcusePending"/
/// Systemprompt in ai-backend/untis-status.php) - wird client-seitig gegen genau diese Menge /// "Excused"/"Unexcused" (siehe Systemprompt in ai-backend/untis-status.php) - wird
/// geprüft, bevor er als AttendanceStatus interpretiert wird. /// client-seitig gegen genau diese Menge geprüft, bevor er als AttendanceStatus interpretiert
/// wird.
public string Status { get; set; } = ""; public string Status { get; set; } = "";
} }
@@ -29,6 +29,14 @@ public interface ISeatingPlanRepository
/// wieder her (14.3). Tut nichts, falls der Papierkorb-Eintrag nicht (mehr) existiert.</summary> /// wieder her (14.3). Tut nichts, falls der Papierkorb-Eintrag nicht (mehr) existiert.</summary>
void Restore(Guid trashId); void Restore(Guid trashId);
} }
public interface IStudentGroupPlanRepository
{
StudentGroupPlan? GetById(Guid id);
List<StudentGroupPlan> GetByGroup(Guid groupId);
List<StudentGroupPlan> GetByStudent(Guid studentId);
void Save(StudentGroupPlan plan);
void Delete(Guid id);
}
public interface IGroupMembershipRepository public interface IGroupMembershipRepository
{ {
List<GroupMembership> GetByStudent(Guid studentId); List<GroupMembership> GetByStudent(Guid studentId);
@@ -86,6 +94,13 @@ public interface IReportGradeRepository
void Save(ReportGrade grade); void Save(ReportGrade grade);
void Delete(Guid id); void Delete(Guid id);
} }
public interface IInterimGradeRepository
{
List<InterimGrade> GetByGroup(Guid groupId);
List<InterimGrade> GetByStudentAndGroup(Guid studentId, Guid groupId);
void Save(InterimGrade grade);
void Delete(Guid id);
}
public interface IUnitRepository public interface IUnitRepository
{ {
Unit? GetById(Guid id); Unit? GetById(Guid id);
@@ -218,6 +233,14 @@ public interface IVorgangRepository
/// Markiert den Vorgang als gelöscht, statt ihn hart zu entfernen (gleiches Muster wie Documentation). /// Markiert den Vorgang als gelöscht, statt ihn hart zu entfernen (gleiches Muster wie Documentation).
void Delete(Guid id); void Delete(Guid id);
} }
/// "Zurückstellen"-Zeitstempel für Dashboard-Warnungen je (StudentId, WarningTag) — wird
/// synchronisiert, siehe DashboardWarningSnooze.
public interface IDashboardWarningSnoozeRepository
{
DashboardWarningSnooze? Get(Guid studentId, string warningTag);
List<DashboardWarningSnooze> GetAll();
void Save(DashboardWarningSnooze snooze);
}
public interface IWorkTaskRepository public interface IWorkTaskRepository
{ {
List<WorkTask> GetByStatus(WorkTaskStatus status); List<WorkTask> GetByStatus(WorkTaskStatus status);
@@ -0,0 +1,30 @@
using System.Security.Cryptography;
using System.Text;
namespace LehrerApp.Core.Models;
/// <summary>
/// "Zurückstellen" einer klassenübergreifenden Dashboard-Warnung (Fehlzeiten/Hausaufgaben/
/// Verspätungen, siehe DashboardViewModel) für eine Person — ein Erinnerungs-Zeitstempel je
/// (StudentId, WarningTag), der über den Sync repliziert wird, damit eine auf Gerät A
/// zurückgestellte Warnung auf Gerät B nicht weiter rot oben steht.
/// </summary>
public class DashboardWarningSnooze
{
/// Aus (StudentId, WarningTag) abgeleitet (siehe <see cref="IdFor"/>; setzt
/// IDashboardWarningSnoozeRepository.Save) statt zufällig: stellen
/// zwei Geräte dieselbe Warnung unabhängig voneinander zurück, beschreiben sie so denselben
/// Datensatz (Last-Write-Wins im Sync), statt zwei Datensätze anzulegen, die beim Anwenden am
/// Unique-Index ux_student_tag scheitern würden.
public Guid Id { get; set; }
public Guid StudentId { get; set; }
/// Dieselben Strings wie VorgangTagDisplay.Suggestions ("Absentismus"/"Hausaufgaben"/"Verspätungen").
public string WarningTag { get; set; } = "";
public DateOnly SnoozedUntil { get; set; }
public static Guid IdFor(Guid studentId, string warningTag)
{
var hash = SHA256.HashData(Encoding.UTF8.GetBytes($"{studentId:N}:{warningTag.ToLowerInvariant()}"));
return new Guid(hash.AsSpan(0, 16));
}
}
+45
View File
@@ -15,10 +15,27 @@ public class Exam
public string? Notes { get; set; } public string? Notes { get; set; }
public DateOnly? ApprovalGrantedAt { get; set; } public DateOnly? ApprovalGrantedAt { get; set; }
public DateOnly? AnnouncedAt { get; set; } public DateOnly? AnnouncedAt { get; set; }
/// <summary>Stabile Kennung einer automatisch importierten Arbeit. Bleibt bei manuell
/// angelegten Klausuren null; aktuell wird der Präfix "webuntis-rest-exam:" verwendet.</summary>
public string? ExternalId { get; set; }
/// Verknüpft Parallelklausuren (gleiche Arbeit, mehrere Kurse) für den Kurs-Umschalter /// Verknüpft Parallelklausuren (gleiche Arbeit, mehrere Kurse) für den Kurs-Umschalter
/// auf der Klausuren-Hauptseite — Id der "Ursprungs"-Klausur, gesetzt beim Duplizieren /// auf der Klausuren-Hauptseite — Id der "Ursprungs"-Klausur, gesetzt beim Duplizieren
/// (siehe ExamDialogViewModel.Save). /// (siehe ExamDialogViewModel.Save).
public Guid? SharedExamGroupId { get; set; } public Guid? SharedExamGroupId { get; set; }
/// <summary>Optional verknüpfte ursprüngliche Arbeit derselben Lerngruppe.</summary>
public Guid? RepeatOfExamId { get; set; }
public RepeatGradeRule RepeatGradeRule { get; set; } = RepeatGradeRule.Better;
/// <summary>Art der Leistungsüberprüfung. Nur <see cref="ExamKind.Klausur"/> zählt in die
/// schriftliche Note; alle anderen Arten fließen unter "Sonstige" ein.</summary>
public ExamKind Kind { get; set; } = ExamKind.Klausur;
/// <summary>Nachschreibarbeit: inhaltlich eigene Arbeit für Schüler, die die verknüpfte
/// erste Arbeit (<see cref="RepeatOfExamId"/>) versäumt haben. Anders als eine Wiederholung
/// wird sie nur von diesen Schülern geschrieben und ersetzt deren fehlende Note.</summary>
public bool IsMakeUp { get; set; }
/// <summary>Förderarbeit: inhaltlich eigene Arbeit, die einzelne Schüler statt der verknüpften
/// ersten Arbeit schreiben — typischerweise am selben Tag, daher darf sie am Datum der ersten
/// Arbeit liegen. Zählt wie eine Nachschreibarbeit (ersetzt nur eine fehlende Note).</summary>
public bool IsSupportWork { get; set; }
public DateTime CreatedAt { get; set; } = DateTime.UtcNow; public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow; public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
} }
@@ -28,6 +45,9 @@ public class ExamTask
public string? Title { get; set; } public string? Title { get; set; }
public double MaxPoints { get; set; } public double MaxPoints { get; set; }
public double Weight { get; set; } = 1.0; public double Weight { get; set; } = 1.0;
/// <summary>Null gilt für beide Fassungen; A/B nur für die gewählte Fassung.</summary>
public ExamVariant? Variant { get; set; }
public bool IsBonus { get; set; }
public List<CompetencyReference> Competencies { get; set; } = []; public List<CompetencyReference> Competencies { get; set; } = [];
} }
public class GradingKeyEntry public class GradingKeyEntry
@@ -52,7 +72,32 @@ public class ExamResult
public double TotalPoints { get; set; } public double TotalPoints { get; set; }
public string? Grade { get; set; } public string? Grade { get; set; }
public bool Absent { get; set; } public bool Absent { get; set; }
public ExamVariant Variant { get; set; } = ExamVariant.A;
public string? Comment { get; set; } public string? Comment { get; set; }
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow; public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
} }
public enum ExamStatus { Planned, Conducted, Graded, Returned } public enum ExamStatus { Planned, Conducted, Graded, Returned }
public enum ExamVariant { A, B }
public enum RepeatGradeRule { Better, Repeat, Original }
/// <summary>Reihenfolge ist persistiert (LiteDB speichert den Enum-Wert) — nur hinten anhängen.</summary>
public enum ExamKind { Klausur, Test, KontrollierteHausaufgabe, Sonstiges }
public static class ExamFollowUpExtensions
{
/// <summary>Nachschreib- und Förderarbeiten sind inhaltlich eigene Arbeiten nur für einzelne
/// Schüler: ihre Note ersetzt eine fehlende Note der ersten Arbeit, verdrängt sie aber nie.</summary>
public static bool ReplacesMissingGrade(this Exam exam) => exam.IsMakeUp || exam.IsSupportWork;
}
public static class ExamKindExtensions
{
public static bool CountsAsWritten(this ExamKind kind) => kind == ExamKind.Klausur;
public static string Label(this ExamKind kind) => kind switch
{
ExamKind.Test => "Test",
ExamKind.KontrollierteHausaufgabe => "Kontrollierte Hausaufgabe",
ExamKind.Sonstiges => "Sonstige Arbeit",
_ => "Klausur",
};
}
+7 -1
View File
@@ -31,7 +31,8 @@ public class LearningGroup
/// <summary> /// <summary>
/// WebUntis-interne Unterrichtsnummer (lsid) dieser Lerngruppe, Grundlage für den Abruf des /// WebUntis-interne Unterrichtsnummer (lsid) dieser Lerngruppe, Grundlage für den Abruf des
/// "Fehlzeiten pro Unterricht"-Berichts. Wird von WebUntis pro Schuljahr neu vergeben und muss /// "Fehlzeiten pro Unterricht"-Berichts. Wird von WebUntis pro Schuljahr neu vergeben und muss
/// deshalb händisch je Lerngruppe/Schuljahr gepflegt werden - keine JSON-RPC-Methode liefert sie. /// deshalb je Lerngruppe/Schuljahr gepflegt werden. Der manuelle WebUntis-Zuordnungsabgleich
/// kann sie aus dem Wochenstundenplan übernehmen.
/// </summary> /// </summary>
public int? WebUntisLessonId { get; set; } public int? WebUntisLessonId { get; set; }
/// <summary> /// <summary>
@@ -67,6 +68,11 @@ public class GroupMembership
public DateOnly? JoinedAt { get; set; } public DateOnly? JoinedAt { get; set; }
public DateOnly? LeftAt { get; set; } public DateOnly? LeftAt { get; set; }
public Niveau? Niveau { get; set; } public Niveau? Niveau { get; set; }
/// <summary>Förderschüler-Markierung, unabhängig von der Niveaudifferenzierung der Gruppe
/// (<see cref="LearningGroup.IsDifferentiated"/>): auch in einem nicht differenzierten Kurs
/// bekommen einzelne Schüler eigenes Fördermaterial. Auswertung siehe
/// <see cref="Services.GroupMembershipService.IsSupportStudent"/>.</summary>
public bool IsSupportStudent { get; set; }
} }
public enum MembershipPeriod { FullYear, H1Only, H2Only, Custom } public enum MembershipPeriod { FullYear, H1Only, H2Only, Custom }
public enum GroupType { Class, Course } public enum GroupType { Class, Course }
+36
View File
@@ -258,6 +258,42 @@ public class ReportGrade
public string? OverrideValue { get; set; } public string? OverrideValue { get; set; }
public string? OverrideReason { get; set; } public string? OverrideReason { get; set; }
public bool IsLocked { get; set; } public bool IsLocked { get; set; }
/// <summary>Nur am Datensatz "Gesamtes Schuljahr": Note der Projektprüfung, wenn sie in
/// diesem Fach abgelegt wurde (Klasse 10). Zählt in der Endjahresnote wie ein weiteres
/// Halbjahr.</summary>
public string? ProjectExamGrade { get; set; }
/// <summary>Wie <see cref="ProjectExamGrade"/>, für die mündliche Abschlussprüfung im
/// gewählten Fach.</summary>
public string? OralExamGrade { get; set; }
/// <summary>Note der schriftlichen Abschlussprüfung (Deutsch, Mathematik, erste
/// Fremdsprache), nur am Jahres-Datensatz.</summary>
public string? WrittenExamGrade { get; set; }
/// <summary>Note einer zusätzlichen mündlichen Prüfung ("Nachprüfung", § 8 Abs. 3 und 4
/// PrüfV Sek. I), nur am Jahres-Datensatz. Zur Verrechnung siehe docs/Datenmodell.md.</summary>
public string? AdditionalOralExamGrade { get; set; }
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
}
/// <summary>
/// Zwischenstand: eine vorläufige Note zu einem Stichtag, wie sie zu einem Anlass (Sprechtag,
/// blauer Brief, Konferenz, Elternanfrage) genannt wurde. Bewusst getrennt von
/// <see cref="ReportGrade"/> — mehrere je Halbjahr möglich, ohne Einfluss auf die Zeugnisnote.
/// Zwischenstände mit gleichem <see cref="Date"/> und <see cref="Occasion"/> bilden einen
/// Durchgang durch (einen Teil der) Lerngruppe.
/// </summary>
public class InterimGrade
{
public Guid Id { get; set; } = Guid.NewGuid();
public Guid StudentId { get; set; }
public Guid GroupId { get; set; }
/// <summary>Stichtag: Leistungen bis einschließlich dieses Tages lagen der Note zugrunde.</summary>
public DateOnly Date { get; set; }
public string Occasion { get; set; } = "";
public string? WrittenValue { get; set; }
public string? OralValue { get; set; }
public string OverallValue { get; set; } = "";
public string? Note { get; set; }
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow; public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
} }
+3 -2
View File
@@ -52,9 +52,10 @@ public sealed record StudentReferenceSummary(
int Grades, int Grades,
int ReportGrades, int ReportGrades,
int ParticipationEntries, int ParticipationEntries,
int DocumentationEntries) int DocumentationEntries,
int StudentGroupPlans = 0)
{ {
public int Total => Memberships + ExamResults + Grades + ReportGrades public int Total => Memberships + ExamResults + Grades + ReportGrades
+ ParticipationEntries + DocumentationEntries; + ParticipationEntries + DocumentationEntries + StudentGroupPlans;
public bool HasReferences => Total > 0; public bool HasReferences => Total > 0;
} }
+17
View File
@@ -0,0 +1,17 @@
namespace LehrerApp.Core.Models;
/// <summary>Eine wiederverwendbare Einteilung innerhalb einer Lerngruppe.</summary>
public class StudentGroupPlan
{
public Guid Id { get; set; } = Guid.NewGuid();
public Guid GroupId { get; set; }
public string Name { get; set; } = "";
public List<StudentGroupPlanGroup> Groups { get; set; } = [];
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
}
public class StudentGroupPlanGroup
{
public List<Guid> StudentIds { get; set; } = [];
}
+1
View File
@@ -71,6 +71,7 @@ public enum UntisCacheKind { Absences, ClassRegister, Roster }
/// </summary> /// </summary>
public class UntisCacheFetchState public class UntisCacheFetchState
{ {
public int AbsenceReportVersion { get; set; }
public Guid Id { get; set; } = Guid.NewGuid(); public Guid Id { get; set; } = Guid.NewGuid();
public string ClassName { get; set; } = ""; public string ClassName { get; set; } = "";
public UntisCacheKind Kind { get; set; } public UntisCacheKind Kind { get; set; }
+15
View File
@@ -3,7 +3,14 @@ namespace LehrerApp.Core.Models;
public class Documentation : IHasAttachments public class Documentation : IHasAttachments
{ {
public Guid Id { get; set; } = Guid.NewGuid(); public Guid Id { get; set; } = Guid.NewGuid();
/// <summary>Hauptperson des Eintrags (bei Gruppeneinträgen <see cref="Guid.Empty"/>).</summary>
public Guid StudentId { get; set; } public Guid StudentId { get; set; }
/// <summary>
/// Weitere betroffene Schüler*innen, z.B. bei einem Vorgang mit mehreren Beteiligten: der Eintrag
/// existiert nur einmal, erscheint aber bei jeder dieser Personen (siehe <see cref="Concerns"/>).
/// Enthält nie <see cref="StudentId"/> selbst.
/// </summary>
public List<Guid> AdditionalStudentIds { get; set; } = [];
public Guid? GroupId { get; set; } public Guid? GroupId { get; set; }
/// <summary>Unterrichtssitzung, in der die Beobachtung entstanden ist.</summary> /// <summary>Unterrichtssitzung, in der die Beobachtung entstanden ist.</summary>
public Guid? ParticipationSessionId { get; set; } public Guid? ParticipationSessionId { get; set; }
@@ -33,6 +40,14 @@ public class Documentation : IHasAttachments
// Löschen entfernt den Eintrag nicht hart, sondern markiert ihn nur (Nachvollziehbarkeit, 5.1.4). // Löschen entfernt den Eintrag nicht hart, sondern markiert ihn nur (Nachvollziehbarkeit, 5.1.4).
public bool IsDeleted { get; set; } public bool IsDeleted { get; set; }
public DateTime? DeletedAt { get; set; } public DateTime? DeletedAt { get; set; }
/// Ob der Eintrag diese Person betrifft — als Hauptperson oder als weitere Beteiligte.
public bool Concerns(Guid studentId) =>
studentId != Guid.Empty && (StudentId == studentId || AdditionalStudentIds.Contains(studentId));
/// Hauptperson (falls gesetzt) gefolgt von den weiteren Beteiligten.
public IEnumerable<Guid> InvolvedStudentIds() =>
(StudentId == Guid.Empty ? [] : new[] { StudentId }).Concat(AdditionalStudentIds);
} }
public class AbsenceData public class AbsenceData
{ {
@@ -3,7 +3,8 @@ using LehrerApp.Core.Models;
namespace LehrerApp.Core.Services; namespace LehrerApp.Core.Services;
public sealed record CompetencyScore( public sealed record CompetencyScore(
double AchievedPoints, double MaxPoints, int EvidenceCount, int ParticipantCount) double AchievedPoints, double MaxPoints, int EvidenceCount, int ParticipantCount,
int ExamEvidenceCount = 0, int ParticipationEvidenceCount = 0)
{ {
public double Percent => MaxPoints <= 0 ? 0 : AchievedPoints / MaxPoints * 100.0; public double Percent => MaxPoints <= 0 ? 0 : AchievedPoints / MaxPoints * 100.0;
} }
@@ -18,6 +19,7 @@ public sealed class CompetencyAnalysisItem
public int TaughtUnitCount { get; init; } public int TaughtUnitCount { get; init; }
public int PlannedExamCount { get; init; } public int PlannedExamCount { get; init; }
public int AssessedExamCount { get; init; } public int AssessedExamCount { get; init; }
public int ParticipationSessionCount { get; init; }
public CompetencyScore? GroupScore { get; init; } public CompetencyScore? GroupScore { get; init; }
public IReadOnlyDictionary<Guid, CompetencyScore> StudentScores { get; init; } = public IReadOnlyDictionary<Guid, CompetencyScore> StudentScores { get; init; } =
new Dictionary<Guid, CompetencyScore>(); new Dictionary<Guid, CompetencyScore>();
@@ -29,7 +31,10 @@ public sealed class CompetencyAnalysisService
IReadOnlyList<CompetencyDomain> catalog, IReadOnlyList<CompetencyDomain> catalog,
IReadOnlyList<Unit> units, IReadOnlyList<Unit> units,
IReadOnlyList<Exam> exams, IReadOnlyList<Exam> exams,
IReadOnlyList<ExamResult> results) IReadOnlyList<ExamResult> results,
IReadOnlyList<ParticipationSession>? participationSessions = null,
IReadOnlyList<ParticipationEntry>? participationEntries = null,
IReadOnlyList<ParticipationAspect>? participationAspects = null)
{ {
var builders = new List<ItemBuilder>(); var builders = new List<ItemBuilder>();
var byId = new Dictionary<Guid, ItemBuilder>(); var byId = new Dictionary<Guid, ItemBuilder>();
@@ -105,7 +110,36 @@ public sealed class CompetencyAnalysisService
if (task.MaxPoints <= 0) continue; if (task.MaxPoints <= 0) continue;
var achieved = Math.Clamp(result.Points[taskIndex], 0, task.MaxPoints); var achieved = Math.Clamp(result.Points[taskIndex], 0, task.MaxPoints);
foreach (var reference in NormalizeReferences(task.Competencies)) foreach (var reference in NormalizeReferences(task.Competencies))
GetOrAdd(reference).AddScore(result.StudentId, achieved, task.MaxPoints); GetOrAdd(reference).AddExamScore(result.StudentId, achieved, task.MaxPoints);
}
}
var entriesBySession = (participationEntries ?? [])
.GroupBy(x => x.SessionId)
.ToDictionary(x => x.Key, x => x.ToList());
var aspects = participationAspects ?? [];
foreach (var session in participationSessions ?? [])
{
var references = NormalizeReferences(session.Competencies).ToList();
foreach (var reference in references)
GetOrAdd(reference).ParticipationSessions++;
if (references.Count == 0 || !entriesBySession.TryGetValue(session.Id, out var entries))
continue;
foreach (var entry in entries)
{
var estimated = ParticipationCompetencyEstimate.Estimate(
entry.Ratings, aspects, entry.DayHighlight);
foreach (var reference in references)
{
var explicitRating = entry.CompetencyRatings
.FirstOrDefault(x => x.ItemId == reference.ItemId)?.Value;
var rating = explicitRating ?? estimated;
if (rating is not null)
GetOrAdd(reference).AddParticipationScore(entry.StudentId, rating.Value);
}
} }
} }
@@ -124,14 +158,23 @@ public sealed class CompetencyAnalysisService
public int TaughtUnits { get; set; } public int TaughtUnits { get; set; }
public int PlannedExams { get; set; } public int PlannedExams { get; set; }
public int AssessedExams { get; set; } public int AssessedExams { get; set; }
public int ParticipationSessions { get; set; }
public void AddScore(Guid studentId, double achieved, double maximum) public void AddExamScore(Guid studentId, double achieved, double maximum) =>
AddScore(studentId, achieved, maximum, isParticipation: false);
public void AddParticipationScore(Guid studentId, int rating) =>
AddScore(studentId, Math.Clamp(rating, -2, 2) + 2, 4, isParticipation: true);
private void AddScore(Guid studentId, double achieved, double maximum, bool isParticipation)
{ {
if (!_scores.TryGetValue(studentId, out var score)) if (!_scores.TryGetValue(studentId, out var score))
_scores[studentId] = score = new MutableScore(); _scores[studentId] = score = new MutableScore();
score.Achieved += achieved; score.Achieved += achieved;
score.Maximum += maximum; score.Maximum += maximum;
score.EvidenceCount++; score.EvidenceCount++;
if (isParticipation) score.ParticipationEvidenceCount++;
else score.ExamEvidenceCount++;
} }
public CompetencyAnalysisItem Build() public CompetencyAnalysisItem Build()
@@ -140,6 +183,8 @@ public sealed class CompetencyAnalysisService
var achieved = _scores.Values.Sum(x => x.Achieved); var achieved = _scores.Values.Sum(x => x.Achieved);
var maximum = _scores.Values.Sum(x => x.Maximum); var maximum = _scores.Values.Sum(x => x.Maximum);
var evidence = _scores.Values.Sum(x => x.EvidenceCount); var evidence = _scores.Values.Sum(x => x.EvidenceCount);
var examEvidence = _scores.Values.Sum(x => x.ExamEvidenceCount);
var participationEvidence = _scores.Values.Sum(x => x.ParticipationEvidenceCount);
return new CompetencyAnalysisItem return new CompetencyAnalysisItem
{ {
DomainName = domainName, DomainName = domainName,
@@ -150,8 +195,10 @@ public sealed class CompetencyAnalysisService
TaughtUnitCount = TaughtUnits, TaughtUnitCount = TaughtUnits,
PlannedExamCount = PlannedExams, PlannedExamCount = PlannedExams,
AssessedExamCount = AssessedExams, AssessedExamCount = AssessedExams,
ParticipationSessionCount = ParticipationSessions,
GroupScore = maximum > 0 GroupScore = maximum > 0
? new CompetencyScore(achieved, maximum, evidence, _scores.Count) ? new CompetencyScore(achieved, maximum, evidence, _scores.Count,
examEvidence, participationEvidence)
: null, : null,
StudentScores = studentScores, StudentScores = studentScores,
}; };
@@ -163,7 +210,10 @@ public sealed class CompetencyAnalysisService
public double Achieved { get; set; } public double Achieved { get; set; }
public double Maximum { get; set; } public double Maximum { get; set; }
public int EvidenceCount { get; set; } public int EvidenceCount { get; set; }
public int ExamEvidenceCount { get; set; }
public int ParticipationEvidenceCount { get; set; }
public CompetencyScore ToScore(int participantCount) => public CompetencyScore ToScore(int participantCount) =>
new(Achieved, Maximum, EvidenceCount, participantCount); new(Achieved, Maximum, EvidenceCount, participantCount,
ExamEvidenceCount, ParticipationEvidenceCount);
} }
} }
@@ -0,0 +1,63 @@
using LehrerApp.Core.Models;
namespace LehrerApp.Core.Services;
/// <summary>Eine Spalte der Punktetabelle auf dem Klausur-Deckblatt. Bonusaufgaben tragen keine
/// Nummer; <see cref="AchievedPoints"/> ist null, solange nichts eingetragen werden soll.</summary>
public sealed record ExamCoverTaskColumn(string Number, double MaxPoints, bool IsBonus, double? AchievedPoints);
public static class ExamCoverSheetService
{
/// <summary>
/// Spalten für genau die Fassung, die der Schüler geschrieben hat. Nummeriert wird innerhalb
/// dieser Fassung (wie auf dem gedruckten Aufgabenblatt), Bonusaufgaben zählen nicht mit.
/// <paramref name="points"/> folgt wie <see cref="ExamResult.Points"/> der Reihenfolge aller
/// Aufgaben, nicht nur der dieser Fassung.
/// </summary>
public static List<ExamCoverTaskColumn> Columns(IReadOnlyList<ExamTask> orderedTasks, ExamVariant variant,
IReadOnlyList<double>? points)
{
var columns = new List<ExamCoverTaskColumn>();
var number = 0;
for (var index = 0; index < orderedTasks.Count; index++)
{
var task = orderedTasks[index];
if (!ExamScoringService.AppliesTo(task, variant)) continue;
double? achieved = points is null ? null : index < points.Count ? points[index] : 0;
columns.Add(new(task.IsBonus ? "" : (++number).ToString(), task.MaxPoints, task.IsBonus, achieved));
}
return columns;
}
/// <summary>Ein Ergebnis gilt als korrigiert, sobald Punkte oder eine Note eingetragen sind.</summary>
public static bool IsCorrected(ExamResult? result) =>
result is { Absent: false } && (result.Points.Count > 0 || !string.IsNullOrWhiteSpace(result.Grade));
}
/// <summary>Wer eine Arbeit mitschreibt — eine Regel für Punkteeingabe und Deckblätter.</summary>
public static class ExamParticipantService
{
/// <summary>Bei einer Nachschreib- oder Förderarbeit: Schüler, die die erste Arbeit bereits mit
/// Note geschrieben haben. Sonst leer.</summary>
public static HashSet<Guid> WroteOriginal(Exam exam, Func<Guid, List<ExamResult>> resultsByExam)
{
var wroteOriginal = new HashSet<Guid>();
if (exam.ReplacesMissingGrade() && exam.RepeatOfExamId is { } originalId)
foreach (var r in resultsByExam(originalId).Where(r => !r.Absent && r.Grade is not null))
wroteOriginal.Add(r.StudentId);
return wroteOriginal;
}
public static bool Includes(Exam exam, GroupMembership? membership, bool hasResult, bool wroteOriginal)
{
if (membership is not null && !GroupMembershipService.IsActiveOn(membership, exam.Date)) return false;
// Niveau-Klausur: nur Schüler mit passendem Niveau. Klausuren ohne Niveau-Zuordnung gelten
// weiterhin für die ganze Gruppe.
if (exam.Niveau.HasValue && membership?.Niveau != exam.Niveau) return false;
// Förderarbeit: nur Förderschüler (außer es gibt hier bereits ein Ergebnis).
if (exam.IsSupportWork && !hasResult && !GroupMembershipService.IsSupportStudent(membership)) return false;
// Nachschreib-/Förderarbeit: wer die erste Arbeit schon mit Note geschrieben hat, taucht nicht auf —
// außer es gibt hier bereits ein Ergebnis (nichts verstecken, was schon eingetragen wurde).
return hasResult || !wroteOriginal;
}
}
@@ -0,0 +1,44 @@
using System.Text.Json;
namespace LehrerApp.Core.Services;
/// <summary>Reihenfolge, in der Enter bei der Punkteeingabe zum nächsten Feld springt.</summary>
public enum GradingEntryOrder
{
/// Eine Arbeit komplett, dann die nächste (Enter läuft die Zeile entlang).
ByStudent,
/// Eine Aufgabe für alle, dann die nächste (Enter läuft die Spalte hinunter).
ByTask,
}
public sealed class ExamGradingSettings
{
public GradingEntryOrder EntryOrder { get; set; } = GradingEntryOrder.ByStudent;
}
/// <summary>Merkt sich den zuletzt gewählten Korrekturmodus der Punkteeingabe lokal.</summary>
public sealed class ExamGradingSettingsService
{
private readonly string _configPath;
public ExamGradingSettingsService(string appDataPath) =>
_configPath = Path.Combine(appDataPath, "examgradingsettings.json");
public ExamGradingSettings Load()
{
try
{
if (File.Exists(_configPath))
return JsonSerializer.Deserialize<ExamGradingSettings>(File.ReadAllText(_configPath))
?? new ExamGradingSettings();
}
catch { /* beschädigte Konfiguration -> Standard */ }
return new ExamGradingSettings();
}
public void Save(ExamGradingSettings settings)
{
try { File.WriteAllText(_configPath, JsonSerializer.Serialize(settings)); }
catch { /* Einstellung ist Komfort — Fehler beim Schreiben nicht an die UI durchreichen */ }
}
}
@@ -0,0 +1,116 @@
using LehrerApp.Core.Models;
namespace LehrerApp.Core.Services;
public static class ExamScoringService
{
public static bool AppliesTo(ExamTask task, ExamVariant variant) =>
task.Variant is null || task.Variant == variant;
public static double Maximum(IEnumerable<ExamTask> tasks, ExamVariant variant) =>
tasks.Where(t => AppliesTo(t, variant) && !t.IsBonus).Sum(t => t.MaxPoints);
/// <summary>
/// Anzeigenummern der Aufgaben in der gespeicherten Reihenfolge. Bonusaufgaben werden auf
/// dem Aufgabenblatt üblicherweise nicht nummeriert — würden sie mitgezählt, passten alle
/// Nummern hinter einer Bonusaufgabe nicht mehr zur gedruckten Arbeit. Sie heißen daher
/// "Bonus" (bei mehreren "Bonus 1", "Bonus 2", …). <see cref="ExamTask.Nr"/> bleibt davon
/// unberührt die reine Positions-/Sortiernummer.
/// </summary>
public static List<string> TaskNumbers(IEnumerable<bool> isBonus)
{
var flags = isBonus.ToList();
var multipleBonus = flags.Count(b => b) > 1;
int nr = 0, bonus = 0;
return flags.Select(b => b
? multipleBonus ? $"Bonus {++bonus}" : "Bonus"
: (++nr).ToString())
.ToList();
}
/// <summary>Beschriftung je Aufgabe ("Aufgabe 3", "3. Titel", "Bonus", "Bonus: Titel").</summary>
public static List<string> TaskLabels(IReadOnlyList<ExamTask> orderedTasks) =>
TaskNumbers(orderedTasks.Select(t => t.IsBonus))
.Select((number, i) =>
{
var title = orderedTasks[i].Title;
if (orderedTasks[i].IsBonus)
return string.IsNullOrWhiteSpace(title) ? number : $"{number}: {title}";
return string.IsNullOrWhiteSpace(title) ? $"Aufgabe {number}" : $"{number}. {title}";
})
.ToList();
public static double Achieved(IReadOnlyList<ExamTask> tasks, IReadOnlyList<double> points,
ExamVariant variant) => tasks.Select((task, index) =>
AppliesTo(task, variant) && index < points.Count ? points[index] : 0).Sum();
/// <summary>
/// Wählt pro Arbeit samt allen verknüpften Folgearbeiten (Wiederholung, Nachschreib-/Förderarbeit)
/// genau eine Note. Andere Arbeiten bleiben erhalten. Fehlt die erste Arbeit (Schüler war
/// abwesend), zählt die Nachschreib-/Förderarbeit allein; hat der Schüler beide geschrieben,
/// zählt immer die erste — sie ersetzen nur eine fehlende Note.
/// </summary>
public static List<string> EffectiveGrades(IEnumerable<(Exam Exam, string Grade)> entries,
GradingSystem system)
{
var chains = new List<List<(Exam Exam, string Grade)>>();
var chainByRoot = new Dictionary<Guid, List<(Exam Exam, string Grade)>>();
foreach (var entry in entries)
{
var root = entry.Exam.RepeatOfExamId ?? entry.Exam.Id;
if (!chainByRoot.TryGetValue(root, out var chain))
chains.Add(chainByRoot[root] = chain = []);
chain.Add(entry);
}
var result = new List<string>();
foreach (var chain in chains)
{
// Die erste Arbeit steht vorn, Folgearbeiten chronologisch dahinter.
var ordered = chain.OrderBy(x => x.Exam.RepeatOfExamId is null ? 0 : 1)
.ThenBy(x => x.Exam.Date).ToList();
var current = ordered[0].Grade;
foreach (var next in ordered.Skip(1))
current = Choose(current, next.Grade,
next.Exam.ReplacesMissingGrade() ? RepeatGradeRule.Original : next.Exam.RepeatGradeRule, system);
result.Add(current);
}
return result;
}
/// <summary>
/// Wie <see cref="EffectiveGrades"/>, trennt aber nach Art: Klausuren zählen als schriftliche
/// Note, Tests u. Ä. fließen unter "Sonstige" ein. Verknüpfte Arbeiten erben die Art der
/// ersten Arbeit (der Dialog erzwingt das), landen also immer im selben Topf.
/// </summary>
public static (List<string> Written, List<string> Other) EffectiveGradesByKind(
IEnumerable<(Exam Exam, string Grade)> entries, GradingSystem system)
{
var list = entries.ToList();
return (
EffectiveGrades(list.Where(x => x.Exam.Kind.CountsAsWritten()), system),
EffectiveGrades(list.Where(x => !x.Exam.Kind.CountsAsWritten()), system));
}
private static string Choose(string original, string repeat, RepeatGradeRule rule, GradingSystem system)
{
if (rule == RepeatGradeRule.Original) return original;
if (rule == RepeatGradeRule.Repeat) return repeat;
var first = GradeValue(original, system);
var second = GradeValue(repeat, system);
if (first is null || second is null) return original;
return system == GradingSystem.Grades1To6
? (second < first ? repeat : original)
: (second > first ? repeat : original);
}
private static double? GradeValue(string grade, GradingSystem system)
{
var core = grade.Trim();
var tendency = 0.0;
if (core.EndsWith('+')) { tendency = system == GradingSystem.Grades1To6 ? -1.0 / 3 : 1.0 / 3; core = core[..^1]; }
else if (core.EndsWith('-')) { tendency = system == GradingSystem.Grades1To6 ? 1.0 / 3 : -1.0 / 3; core = core[..^1]; }
return double.TryParse(core.Trim(), System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture, out var value) ? value + tendency : null;
}
}
@@ -10,7 +10,8 @@ namespace LehrerApp.Core.Services;
/// fehlt, ist die persönliche Belastung der Lehrkraft: mehr eigene Klausuren in derselben Woche /// fehlt, ist die persönliche Belastung der Lehrkraft: mehr eigene Klausuren in derselben Woche
/// bedeuten unabhängig von der Klasse mehr Erstellungsaufwand vorher und mehr Korrekturaufwand /// bedeuten unabhängig von der Klasse mehr Erstellungsaufwand vorher und mehr Korrekturaufwand
/// danach. Da eine LiteDB-Datei genau einem Nutzer gehört (siehe CLAUDE.md), sind "alle /// danach. Da eine LiteDB-Datei genau einem Nutzer gehört (siehe CLAUDE.md), sind "alle
/// Klausuren in der Datenbank" bereits gleichbedeutend mit "meine Klausuren". /// Klausuren in der Datenbank" bereits gleichbedeutend mit "meine Klausuren". Tests und andere
/// kurze Arbeiten (<see cref="ExamKind"/>) zählen bewusst nicht mit — sie sind kein Klausurblock.
/// </summary> /// </summary>
public static class ExamWeekLoadService public static class ExamWeekLoadService
{ {
@@ -24,7 +25,8 @@ public static class ExamWeekLoadService
public static int CountInSameWeek(IEnumerable<Exam> allExams, DateOnly date, Guid? excludeExamId = null) public static int CountInSameWeek(IEnumerable<Exam> allExams, DateOnly date, Guid? excludeExamId = null)
{ {
var (year, week) = IsoWeek(date); var (year, week) = IsoWeek(date);
return allExams.Count(e => e.Id != excludeExamId && IsoWeek(e.Date) == (year, week)); return allExams.Count(e => e.Id != excludeExamId && e.Kind.CountsAsWritten()
&& IsoWeek(e.Date) == (year, week));
} }
/// Gruppiert die übergebenen Klausuren nach ISO-Kalenderwoche und liefert nur die Wochen mit /// Gruppiert die übergebenen Klausuren nach ISO-Kalenderwoche und liefert nur die Wochen mit
@@ -32,6 +34,7 @@ public static class ExamWeekLoadService
/// vorausschauenden Überblick (z.B. Dashboard), nicht für die Einzelprüfung beim Anlegen. /// vorausschauenden Überblick (z.B. Dashboard), nicht für die Einzelprüfung beim Anlegen.
public static List<ExamWeekLoad> FindOverloadedWeeks(IEnumerable<Exam> exams) => public static List<ExamWeekLoad> FindOverloadedWeeks(IEnumerable<Exam> exams) =>
exams exams
.Where(e => e.Kind.CountsAsWritten())
.GroupBy(e => IsoWeek(e.Date)) .GroupBy(e => IsoWeek(e.Date))
.Where(g => g.Count() >= WarningThreshold) .Where(g => g.Count() >= WarningThreshold)
.Select(g => new ExamWeekLoad(g.Key.Year, g.Key.Week, WeekStart(g.Key.Year, g.Key.Week), g.Count())) .Select(g => new ExamWeekLoad(g.Key.Year, g.Key.Week, WeekStart(g.Key.Year, g.Key.Week), g.Count()))
+14 -3
View File
@@ -87,7 +87,7 @@ public class GradingService
/// Wandelt eine Notenangabe mit optionaler Tendenz ("3+", "2-") in einen rechnerischen /// Wandelt eine Notenangabe mit optionaler Tendenz ("3+", "2-") in einen rechnerischen
/// Notenwert um. Tendenzen verschieben um ein Drittel in Richtung der besseren Note /// Notenwert um. Tendenzen verschieben um ein Drittel in Richtung der besseren Note
/// (z.B. "3+" → 2,67, "2-" → 2,33) — der in deutschen Notensystemen übliche Drittelabstand. /// (z.B. "3+" → 2,67, "2-" → 2,33) — der in deutschen Notensystemen übliche Drittelabstand.
private static double? ParseGradeValue(string grade) public static double? ParseGradeValue(string grade)
{ {
var trimmed = grade.Trim(); var trimmed = grade.Trim();
if (trimmed.Length == 0) return null; if (trimmed.Length == 0) return null;
@@ -132,6 +132,18 @@ public class GradingService
List<(string Grade, double Weight)> participationGrades, List<(string Grade, double Weight)> participationGrades,
List<(string Grade, double Weight)> otherGrades, List<(string Grade, double Weight)> otherGrades,
GradingScheme scheme, GradingSystem system, RoundingRule rounding) GradingScheme scheme, GradingSystem system, RoundingRule rounding)
{
var weighted = CalculateReportGradeValue(examGrades, participationGrades, otherGrades, scheme);
return weighted is null ? null : RoundToGrade(weighted.Value, system, rounding);
}
/// Wie <see cref="CalculateReportGrade"/>, liefert aber den ungerundeten gewichteten Wert —
/// für Ansichten, die zeigen sollen, wie knapp eine Note zwischen zwei Stufen liegt.
public double? CalculateReportGradeValue(
List<(string Grade, double Weight)> examGrades,
List<(string Grade, double Weight)> participationGrades,
List<(string Grade, double Weight)> otherGrades,
GradingScheme scheme)
{ {
var buckets = new List<(double Avg, double Percent)>(); var buckets = new List<(double Avg, double Percent)>();
if (examGrades.Count > 0) buckets.Add((WeightedAverage(examGrades), scheme.ExamsPercent)); if (examGrades.Count > 0) buckets.Add((WeightedAverage(examGrades), scheme.ExamsPercent));
@@ -141,8 +153,7 @@ public class GradingService
var totalPercent = buckets.Sum(b => b.Percent); var totalPercent = buckets.Sum(b => b.Percent);
if (buckets.Count == 0 || totalPercent <= 0) return null; if (buckets.Count == 0 || totalPercent <= 0) return null;
var weighted = buckets.Sum(b => b.Avg * b.Percent) / totalPercent; return buckets.Sum(b => b.Avg * b.Percent) / totalPercent;
return RoundToGrade(weighted, system, rounding);
} }
} }
@@ -10,6 +10,11 @@ public enum SchoolYearPeriodKind { FullYear, H1, H2 }
/// </summary> /// </summary>
public static class GroupMembershipService public static class GroupMembershipService
{ {
/// <summary>Förderschüler ist, wer markiert ist oder in einer differenzierten Gruppe das
/// Förderniveau hat.</summary>
public static bool IsSupportStudent(GroupMembership? membership) =>
membership is { } m && (m.IsSupportStudent || m.Niveau == Niveau.Foerder);
public static bool IsActiveOn(GroupMembership membership, DateOnly date) public static bool IsActiveOn(GroupMembership membership, DateOnly date)
{ {
if (membership.JoinedAt is { } joinedAt && date < joinedAt) return false; if (membership.JoinedAt is { } joinedAt && date < joinedAt) return false;
@@ -80,6 +80,7 @@ public sealed class GroupRolloverService(
JoinedAt = targetStart, JoinedAt = targetStart,
LeftAt = null, LeftAt = null,
Niveau = membership.Niveau, Niveau = membership.Niveau,
IsSupportStudent = membership.IsSupportStudent,
}); });
} }
@@ -0,0 +1,36 @@
using LehrerApp.Core.Models;
namespace LehrerApp.Core.Services;
/// <summary>
/// Leitet aus den allgemeinen Mitarbeitsaspekten einen Kompetenzwert auf der gemeinsamen
/// Skala von -2 bis +2 ab. Explizite Kompetenzbewertungen werden vom Aufrufer bevorzugt.
/// </summary>
public static class ParticipationCompetencyEstimate
{
public static int? Estimate(IEnumerable<AspectRating> ratings,
IReadOnlyCollection<ParticipationAspect> aspects, DayHighlightKind? dayHighlight)
{
var aspectsByKey = aspects
.GroupBy(x => x.Key, StringComparer.OrdinalIgnoreCase)
.ToDictionary(x => x.Key, x => x.Last(), StringComparer.OrdinalIgnoreCase);
var normalized = ratings
.Where(x => aspectsByKey.ContainsKey(x.Key))
.Select(x =>
{
var aspect = aspectsByKey[x.Key];
return ParticipationRatingScale.Normalize(aspect.ValueType, x.Value, aspect.MaxPoints);
})
.ToList();
if (normalized.Count == 0) return null;
var adjustment = dayHighlight switch
{
DayHighlightKind.Standout => 1.0,
DayHighlightKind.Sleepy or DayHighlightKind.Rough => -1.0,
_ => 0.0,
};
return Math.Clamp((int)Math.Round(normalized.Average() + adjustment,
MidpointRounding.AwayFromZero), -2, 2);
}
}
@@ -22,7 +22,8 @@ public class PersonalDataExportService(
IExamResultRepository examResults, IExamResultRepository examResults,
IParticipationRepository participation, IParticipationRepository participation,
IDocumentationRepository documentation, IDocumentationRepository documentation,
ISeatingPlanRepository seatingPlans) ISeatingPlanRepository seatingPlans,
IStudentGroupPlanRepository? studentGroupPlans = null)
{ {
public string ExportAsJson(Guid studentId) public string ExportAsJson(Guid studentId)
{ {
@@ -56,6 +57,16 @@ public class PersonalDataExportService(
Platz = a.Column + 1, Platz = a.Column + 1,
})) }))
.ToList(), .ToList(),
GespeicherteGruppeneinteilungen = (studentGroupPlans?.GetByStudent(studentId) ?? [])
.SelectMany(plan => plan.Groups.Select((subgroup, index) => new
{
Einteilung = plan.Name,
Gruppe = index + 1,
Enthalten = subgroup.StudentIds.Contains(studentId),
}))
.Where(entry => entry.Enthalten)
.Select(entry => new { entry.Einteilung, entry.Gruppe })
.ToList(),
}; };
return JsonSerializer.Serialize(dto, new JsonSerializerOptions return JsonSerializer.Serialize(dto, new JsonSerializerOptions
+33 -19
View File
@@ -72,18 +72,19 @@ public class UntisDiffService
if (string.Equals(evt.Status, "CANCELLED", StringComparison.OrdinalIgnoreCase)) if (string.Equals(evt.Status, "CANCELLED", StringComparison.OrdinalIgnoreCase))
{ {
substitutions.Add(mapping.Kind == SubstitutionKind.Lesson if (mapping.Kind == SubstitutionKind.Lesson)
? BuildCancelledLesson(evt.Date, mapping, evt.Uid) substitutions.AddRange(BuildCancelledLessons(evt.Date, mapping, evt.Uid));
: BuildSupervisionNote(evt.Date, mapping, evt.Uid, "Laut WebUntis abgesagt.")); else
substitutions.Add(BuildSupervisionNote(evt.Date, mapping, evt.Uid, "Laut WebUntis abgesagt."));
continue; continue;
} }
if (mapping.Kind == SubstitutionKind.Lesson) if (mapping.Kind == SubstitutionKind.Lesson)
{ {
if (DeviationReason(evt, mapping) is { } reason) if (DeviationReason(evt, mapping) is { } reason)
substitutions.Add(BuildChangedLesson(evt, mapping, reason)); substitutions.AddRange(BuildChangedLessons(evt, mapping, reason));
else else
externalIdsToDelete.Add(evt.Uid); // war ggf. vorher fälschlich als Vertretung erkannt externalIdsToDelete.AddRange(ExternalIdsForPeriods(evt.Uid, mapping)); // ggf. frühere Vertretung entfernen
} }
else if (!regularDutyKeys.Contains((mapping.Weekday, mapping.AfterPeriod!.Value))) else if (!regularDutyKeys.Contains((mapping.Weekday, mapping.AfterPeriod!.Value)))
{ {
@@ -143,11 +144,11 @@ public class UntisDiffService
{ {
// War evtl. an einem früheren Poll (noch) als fehlend gemeldet - jetzt // War evtl. an einem früheren Poll (noch) als fehlend gemeldet - jetzt
// wieder im Feed vorhanden, die alte Meldung räumt sich damit selbst ab. // wieder im Feed vorhanden, die alte Meldung räumt sich damit selbst ab.
externalIdsToDelete.Add(BuildMissingExternalId(date, mapping)); externalIdsToDelete.AddRange(ExternalIdsForPeriods(BuildMissingExternalId(date, mapping), mapping));
continue; continue;
} }
substitutions.Add(BuildCancelledLesson(date, mapping, BuildMissingExternalId(date, mapping))); substitutions.AddRange(BuildCancelledLessons(date, mapping, BuildMissingExternalId(date, mapping)));
} }
} }
} }
@@ -192,19 +193,32 @@ public class UntisDiffService
private static string RemoveWhitespace(string value) => private static string RemoveWhitespace(string value) =>
new(value.Where(c => !char.IsWhiteSpace(c)).ToArray()); new(value.Where(c => !char.IsWhiteSpace(c)).ToArray());
private static SubstitutionEntry BuildCancelledLesson(DateOnly date, UntisSlotMapping mapping, string externalId) => new() private static IEnumerable<SubstitutionEntry> BuildCancelledLessons(DateOnly date, UntisSlotMapping mapping,
{ string externalId) => Periods(mapping).Select((period, index) => new SubstitutionEntry
Date = date, Kind = SubstitutionKind.Cancelled, PeriodNumber = mapping.PeriodNumber, {
Description = "Automatisch über WebUntis-Abgleich erkannt.", ExternalId = externalId, Date = date, Kind = SubstitutionKind.Cancelled, PeriodNumber = period,
}; Description = "Automatisch über WebUntis-Abgleich erkannt.",
ExternalId = PeriodExternalId(externalId, period, index),
});
private static SubstitutionEntry BuildChangedLesson(UntisIcsEvent evt, UntisSlotMapping mapping, string reason) => new() private static IEnumerable<SubstitutionEntry> BuildChangedLessons(UntisIcsEvent evt, UntisSlotMapping mapping,
{ string reason) => Periods(mapping).Select((period, index) => new SubstitutionEntry
Date = evt.Date, Kind = SubstitutionKind.Lesson, PeriodNumber = mapping.PeriodNumber, {
GroupId = mapping.GroupId, GroupLabel = mapping.ClassToken, Date = evt.Date, Kind = SubstitutionKind.Lesson, PeriodNumber = period,
Description = $"WebUntis: {evt.Summary ?? "?"} · {evt.Location} (regulär: {mapping.Summary ?? "?"}) — {reason}", GroupId = mapping.GroupId, GroupLabel = mapping.ClassToken,
ExternalId = evt.Uid, Description = $"WebUntis: {evt.Summary ?? "?"} · {evt.Location} (regulär: {mapping.Summary ?? "?"}) — {reason}",
}; ExternalId = PeriodExternalId(evt.Uid, period, index),
});
private static List<int> Periods(UntisSlotMapping mapping) => mapping.CoveredPeriods.Count > 0
? mapping.CoveredPeriods.Distinct().Order().ToList()
: mapping.PeriodNumber is { } period ? [period] : [];
private static IEnumerable<string> ExternalIdsForPeriods(string externalId, UntisSlotMapping mapping) =>
Periods(mapping).Select((period, index) => PeriodExternalId(externalId, period, index));
private static string PeriodExternalId(string externalId, int period, int index) =>
index == 0 ? externalId : $"{externalId}-period-{period}";
// Aufsichten haben keinen TimetableSlot im Hintergrund (siehe SubstitutionEntry.Kind-Doc) - // Aufsichten haben keinen TimetableSlot im Hintergrund (siehe SubstitutionEntry.Kind-Doc) -
// deshalb Kind=Supervision statt Cancelled, auch wenn der Termin verschwunden ist. // deshalb Kind=Supervision statt Cancelled, auch wenn der Termin verschwunden ist.
@@ -61,6 +61,15 @@ public sealed class ChangeHookMatrixTests
return (grade.Id, () => repo.Delete(grade.Id)); return (grade.Id, () => repo.Delete(grade.Id));
}); });
yield return Case("InterimGrade", nameof(InterimGrade), db =>
{
var repo = new InterimGradeRepository(db);
var grade = new InterimGrade { StudentId = Guid.NewGuid(), GroupId = Guid.NewGuid(),
Date = new DateOnly(2025, 11, 12), Occasion = "Sprechtag", OverallValue = "3" };
repo.Save(grade);
return (grade.Id, () => repo.Delete(grade.Id));
});
yield return Case("Unit", nameof(Unit), db => yield return Case("Unit", nameof(Unit), db =>
{ {
var repo = new UnitRepository(db); var repo = new UnitRepository(db);
+22
View File
@@ -77,4 +77,26 @@ public sealed class ChangeHookTests
Assert.Equal("Save", call.Operation); Assert.Equal("Save", call.Operation);
Assert.Same(state, call.Payload); Assert.Same(state, call.Payload);
} }
[Fact]
public void DashboardWarningSnoozeRepository_Save_LoestOnChangeAus()
{
using var db = NewInMemoryContext();
var calls = new List<(string EntityType, string EntityId, string Operation, object? Payload)>();
db.OnChange = (type, id, op, payload) => calls.Add((type, id, op, payload));
var repo = new DashboardWarningSnoozeRepository(db);
var studentId = Guid.NewGuid();
var snooze = new DashboardWarningSnooze
{
StudentId = studentId, WarningTag = "Absentismus", SnoozedUntil = new DateOnly(2026, 10, 12),
};
repo.Save(snooze);
var call = Assert.Single(calls);
Assert.Equal(nameof(DashboardWarningSnooze), call.EntityType);
Assert.Equal(DashboardWarningSnooze.IdFor(studentId, "Absentismus").ToString(), call.EntityId);
Assert.Equal("Save", call.Operation);
Assert.Same(snooze, call.Payload);
}
} }
@@ -26,6 +26,38 @@ public sealed class DatabaseEncryptionServiceTests
Assert.False(service.IsEncrypted(temp.Path)); Assert.False(service.IsEncrypted(temp.Path));
} }
/// Regression: SettingsViewModel ruft IsEncrypted/VerifyPassword mit dem Pfad der bereits
/// laufenden Datenbank auf, während LiteDbContext deren Shared-Verbindung noch offen hält
/// (z.B. bei jedem Öffnen der Einstellungen). Eine zweite Verbindung im Standard-Modus
/// (Direct) würde das mit "The process cannot access the file" quittieren.
[Fact]
public void IsEncrypted_WaehrendAndereSharedVerbindungOffenIst_WirftNicht()
{
using var temp = new TempDatabase();
using (var db = new LiteDatabase(temp.Path))
db.GetCollection<BsonDocument>("t").Insert(new BsonDocument { ["x"] = 1 });
using var open = new LiteDatabase(new ConnectionString(temp.Path) { Connection = ConnectionType.Shared });
var service = new DatabaseEncryptionService();
Assert.False(service.IsEncrypted(temp.Path));
}
[Fact]
public void VerifyPassword_WaehrendAndereSharedVerbindungOffenIst_WirftNicht()
{
using var temp = new TempDatabase();
using (var db = new LiteDatabase(temp.Path))
db.GetCollection<BsonDocument>("t").Insert(new BsonDocument { ["x"] = 1 });
var service = new DatabaseEncryptionService();
service.SetPassword(temp.Path, currentPassword: null, newPassword: "geheim123");
using var open = new LiteDatabase(new ConnectionString(temp.Path)
{ Password = "geheim123", Connection = ConnectionType.Shared });
Assert.True(service.VerifyPassword(temp.Path, "geheim123"));
Assert.False(service.VerifyPassword(temp.Path, "falsch"));
}
[Fact] [Fact]
public void SetPassword_VerschluesseltDieDatenbankUndBehaeltDieDaten() public void SetPassword_VerschluesseltDieDatenbankUndBehaeltDieDaten()
{ {
+25 -2
View File
@@ -121,7 +121,7 @@ public sealed class LiteDbContextTests
using var temp = new TempDatabase(); using var temp = new TempDatabase();
using var context = new LiteDbContext(temp.Path); using var context = new LiteDbContext(temp.Path);
Assert.Equal(6, context.SchemaVersion); Assert.Equal(7, context.SchemaVersion);
} }
[Fact] [Fact]
@@ -132,7 +132,30 @@ public sealed class LiteDbContextTests
using var second = new LiteDbContext(temp.Path); using var second = new LiteDbContext(temp.Path);
Assert.Equal(6, second.SchemaVersion); Assert.Equal(7, second.SchemaVersion);
}
[Fact]
public void MigrateDashboardWarningSnoozeIds_SchluesseltLokaleEintraegeAufAbgeleiteteIdUm()
{
using var temp = new TempDatabase();
var studentId = Guid.NewGuid();
using (var legacy = new LiteDatabase(temp.Path))
{
legacy.GetCollection<BsonDocument>("meta").Upsert(new BsonDocument { ["_id"] = 1, ["SchemaVersion"] = 6 });
legacy.GetCollection<DashboardWarningSnooze>("dashboard_warning_snoozes").Insert(new DashboardWarningSnooze
{
Id = Guid.NewGuid(), StudentId = studentId, WarningTag = "Verspätungen",
SnoozedUntil = new DateOnly(2026, 10, 12),
});
}
using var context = new LiteDbContext(temp.Path);
var snooze = Assert.Single(context.DashboardWarningSnoozes.FindAll());
Assert.Equal(DashboardWarningSnooze.IdFor(studentId, "Verspätungen"), snooze.Id);
Assert.Equal(new DateOnly(2026, 10, 12), snooze.SnoozedUntil);
} }
[Fact] [Fact]
+101
View File
@@ -8,6 +8,72 @@ public sealed class RepositoryTests
{ {
private static LiteDbContext NewInMemoryContext() => new(new MemoryStream()); private static LiteDbContext NewInMemoryContext() => new(new MemoryStream());
[Fact]
public void StudentGroupPlanRepository_SpeichertEinteilungUndLoeschtSieMitDerLerngruppe()
{
using var db = NewInMemoryContext();
var group = new LearningGroup { Name = "8a" };
new GroupRepository(db).Save(group);
var studentIds = new[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
var plan = new StudentGroupPlan
{
GroupId = group.Id,
Name = " Projektwoche ",
Groups =
[
new StudentGroupPlanGroup { StudentIds = [studentIds[0], studentIds[1]] },
new StudentGroupPlanGroup { StudentIds = [studentIds[2]] },
],
};
var changes = new List<(string Type, string Operation)>();
db.OnChange = (type, _, operation, _) => changes.Add((type, operation));
var repo = new StudentGroupPlanRepository(db);
repo.Save(plan);
Assert.Equal("Projektwoche", repo.GetById(plan.Id)?.Name);
Assert.Equal(studentIds[2], repo.GetByGroup(group.Id).Single().Groups[1].StudentIds.Single());
Assert.Equal(plan.Id, Assert.Single(repo.GetByStudent(studentIds[0])).Id);
Assert.Contains((nameof(StudentGroupPlan), "Save"), changes);
var student = new Student { Id = studentIds[0], FirstName = "Anna", LastName = "Beispiel" };
var students = new StudentRepository(db);
students.Save(student);
Assert.Throws<InvalidOperationException>(() => students.Delete(student.Id));
new GroupRepository(db).Delete(group.Id);
Assert.Empty(repo.GetByGroup(group.Id));
}
[Fact]
public void StudentGroupPlanRepository_VerhindertDoppelteSchuelerUndNamen()
{
using var db = NewInMemoryContext();
var group = new LearningGroup { Name = "8a" };
new GroupRepository(db).Save(group);
var repo = new StudentGroupPlanRepository(db);
var studentId = Guid.NewGuid();
Assert.Throws<InvalidOperationException>(() => repo.Save(new StudentGroupPlan
{
GroupId = group.Id, Name = "Doppelt",
Groups =
[
new StudentGroupPlanGroup { StudentIds = [studentId] },
new StudentGroupPlanGroup { StudentIds = [studentId] },
],
}));
repo.Save(new StudentGroupPlan
{
GroupId = group.Id, Name = "Projektwoche",
Groups = [new StudentGroupPlanGroup { StudentIds = [studentId] }],
});
Assert.Throws<InvalidOperationException>(() => repo.Save(new StudentGroupPlan
{
GroupId = group.Id, Name = "projektwoche",
Groups = [new StudentGroupPlanGroup()],
}));
}
// ── StudentRepository ───────────────────────────────────────────────────── // ── StudentRepository ─────────────────────────────────────────────────────
[Fact] [Fact]
@@ -1338,4 +1404,39 @@ public sealed class RepositoryTests
Assert.Null(repo.GetById(extra.Id)); Assert.Null(repo.GetById(extra.Id));
} }
[Fact]
public void DocumentationRepository_GetByStudent_FindetGemeinsamenEintragBeiAllenBeteiligten()
{
using var db = NewInMemoryContext();
var repo = new DocumentationRepository(db);
Guid anna = Guid.NewGuid(), ben = Guid.NewGuid(), cem = Guid.NewGuid();
var shared = new Documentation
{
StudentId = anna, AdditionalStudentIds = [ben], Title = "Konflikt", Type = DocumentationType.Incident,
};
repo.Save(shared);
Assert.Equal(shared.Id, Assert.Single(repo.GetByStudent(anna)).Id);
Assert.Equal(shared.Id, Assert.Single(repo.GetByStudent(ben)).Id);
Assert.Empty(repo.GetByStudent(cem));
Assert.Single(repo.GetByStudentAndType(ben, DocumentationType.Incident));
Assert.Empty(repo.GetByStudentAndType(ben, DocumentationType.Conversation));
}
[Fact]
public void StudentRepository_GetReferenceSummary_ZaehltAuchGemeinsameDokumentation()
{
using var db = NewInMemoryContext();
var students = new StudentRepository(db);
var ben = new Student { FirstName = "Ben", LastName = "Muster" };
students.Save(ben);
new DocumentationRepository(db).Save(new Documentation
{
StudentId = Guid.NewGuid(), AdditionalStudentIds = [ben.Id], Title = "Konflikt",
});
Assert.Equal(1, students.GetReferenceSummary(ben.Id).DocumentationEntries);
Assert.Throws<InvalidOperationException>(() => students.Delete(ben.Id));
}
} }
+13 -2
View File
@@ -10,12 +10,21 @@ namespace LehrerApp.Data;
/// </summary> /// </summary>
public class DatabaseEncryptionService public class DatabaseEncryptionService
{ {
// Beide Methoden werden auch gegen den Pfad der laufenden, bereits geöffneten Datenbank
// aufgerufen (z.B. bei jedem Öffnen der Einstellungen bzw. vor einer Passwort-Änderung) -
// LiteDbContext hält dafür längst eine ConnectionType.Shared-Verbindung offen. Ohne Shared
// hier ebenfalls zu setzen, würde die zweite Verbindung im Standard-Modus (Direct) einen
// exklusiven Dateizugriff verlangen und mit "The process cannot access the file" scheitern.
public bool IsEncrypted(string dbPath) public bool IsEncrypted(string dbPath)
{ {
if (!File.Exists(dbPath)) return false; if (!File.Exists(dbPath)) return false;
try try
{ {
using var db = new LiteDatabase(dbPath); // Shared-Verbindungen öffnen die Datei lazy - anders als Direct wirft der Konstruktor
// bei falschem/fehlendem Passwort noch nicht, erst ein tatsächlicher Zugriff liest den
// (ggf. verschlüsselten) Header.
using var db = new LiteDatabase(new ConnectionString(dbPath) { Connection = ConnectionType.Shared });
_ = db.GetCollectionNames().ToList();
return false; return false;
} }
catch (LiteException) catch (LiteException)
@@ -28,7 +37,9 @@ public class DatabaseEncryptionService
{ {
try try
{ {
using var db = new LiteDatabase(new ConnectionString(dbPath) { Password = password }); using var db = new LiteDatabase(new ConnectionString(dbPath)
{ Password = password, Connection = ConnectionType.Shared });
_ = db.GetCollectionNames().ToList();
return true; return true;
} }
catch (LiteException) catch (LiteException)
+35
View File
@@ -41,12 +41,14 @@ public class LiteDbContext : IDisposable
public ILiteCollection<Student> Students => _db.GetCollection<Student>("students"); public ILiteCollection<Student> Students => _db.GetCollection<Student>("students");
public ILiteCollection<LearningGroup> Groups => _db.GetCollection<LearningGroup>("groups"); public ILiteCollection<LearningGroup> Groups => _db.GetCollection<LearningGroup>("groups");
public ILiteCollection<SeatingPlan> SeatingPlans => _db.GetCollection<SeatingPlan>("seating_plans"); public ILiteCollection<SeatingPlan> SeatingPlans => _db.GetCollection<SeatingPlan>("seating_plans");
public ILiteCollection<StudentGroupPlan> StudentGroupPlans => _db.GetCollection<StudentGroupPlan>("student_group_plans");
public ILiteCollection<GroupMembership> Memberships => _db.GetCollection<GroupMembership>("group_memberships"); public ILiteCollection<GroupMembership> Memberships => _db.GetCollection<GroupMembership>("group_memberships");
public ILiteCollection<Exam> Exams => _db.GetCollection<Exam>("exams"); public ILiteCollection<Exam> Exams => _db.GetCollection<Exam>("exams");
public ILiteCollection<ExamResult> ExamResults => _db.GetCollection<ExamResult>("exam_results"); public ILiteCollection<ExamResult> ExamResults => _db.GetCollection<ExamResult>("exam_results");
public ILiteCollection<Grade> Grades => _db.GetCollection<Grade>("grades"); public ILiteCollection<Grade> Grades => _db.GetCollection<Grade>("grades");
public ILiteCollection<GradingScheme> GradingSchemes => _db.GetCollection<GradingScheme>("grading_schemes"); public ILiteCollection<GradingScheme> GradingSchemes => _db.GetCollection<GradingScheme>("grading_schemes");
public ILiteCollection<ReportGrade> ReportGrades => _db.GetCollection<ReportGrade>("report_grades"); public ILiteCollection<ReportGrade> ReportGrades => _db.GetCollection<ReportGrade>("report_grades");
public ILiteCollection<InterimGrade> InterimGrades => _db.GetCollection<InterimGrade>("interim_grades");
public ILiteCollection<GradingKeyTemplate> GradingKeyTemplates => _db.GetCollection<GradingKeyTemplate>("grading_key_templates"); public ILiteCollection<GradingKeyTemplate> GradingKeyTemplates => _db.GetCollection<GradingKeyTemplate>("grading_key_templates");
public ILiteCollection<Unit> Units => _db.GetCollection<Unit>("units"); public ILiteCollection<Unit> Units => _db.GetCollection<Unit>("units");
public ILiteCollection<Lesson> Lessons => _db.GetCollection<Lesson>("lessons"); public ILiteCollection<Lesson> Lessons => _db.GetCollection<Lesson>("lessons");
@@ -76,6 +78,7 @@ public class LiteDbContext : IDisposable
public ILiteCollection<UntisHubJobState> UntisHubJobStates => _db.GetCollection<UntisHubJobState>("untis_hub_job_states"); public ILiteCollection<UntisHubJobState> UntisHubJobStates => _db.GetCollection<UntisHubJobState>("untis_hub_job_states");
public ILiteCollection<UntisStudentRosterCacheEntry> UntisStudentRosterCache => _db.GetCollection<UntisStudentRosterCacheEntry>("untis_student_roster_cache"); public ILiteCollection<UntisStudentRosterCacheEntry> UntisStudentRosterCache => _db.GetCollection<UntisStudentRosterCacheEntry>("untis_student_roster_cache");
public ILiteCollection<AnnualPlanEvent> AnnualPlanEvents => _db.GetCollection<AnnualPlanEvent>("annual_plan_events"); public ILiteCollection<AnnualPlanEvent> AnnualPlanEvents => _db.GetCollection<AnnualPlanEvent>("annual_plan_events");
public ILiteCollection<DashboardWarningSnooze> DashboardWarningSnoozes => _db.GetCollection<DashboardWarningSnooze>("dashboard_warning_snoozes");
public ILiteCollection<TrashedItem> TrashedItems => _db.GetCollection<TrashedItem>("trash"); public ILiteCollection<TrashedItem> TrashedItems => _db.GetCollection<TrashedItem>("trash");
public void Checkpoint() => _db.Checkpoint(); public void Checkpoint() => _db.Checkpoint();
@@ -112,6 +115,9 @@ public class LiteDbContext : IDisposable
foreach (var reportGrade in ReportGrades.Find(g => g.GroupId == id).ToList()) foreach (var reportGrade in ReportGrades.Find(g => g.GroupId == id).ToList())
ReportGrades.Delete(reportGrade.Id); ReportGrades.Delete(reportGrade.Id);
foreach (var interimGrade in InterimGrades.Find(g => g.GroupId == id).ToList())
InterimGrades.Delete(interimGrade.Id);
foreach (var scheme in GradingSchemes.Find(s => s.GroupId == id).ToList()) foreach (var scheme in GradingSchemes.Find(s => s.GroupId == id).ToList())
GradingSchemes.Delete(scheme.Id); GradingSchemes.Delete(scheme.Id);
@@ -140,6 +146,8 @@ public class LiteDbContext : IDisposable
foreach (var plan in SeatingPlans.Find(p => p.GroupId == id).ToList()) foreach (var plan in SeatingPlans.Find(p => p.GroupId == id).ToList())
SeatingPlans.Delete(plan.Id); SeatingPlans.Delete(plan.Id);
foreach (var plan in StudentGroupPlans.Find(p => p.GroupId == id).ToList())
StudentGroupPlans.Delete(plan.Id);
// Dokumentation und Arbeitszeit sind historische Nachweise. Sie bleiben erhalten, // Dokumentation und Arbeitszeit sind historische Nachweise. Sie bleiben erhalten,
// werden aber von der nicht mehr existierenden Lerngruppe entkoppelt. // werden aber von der nicht mehr existierenden Lerngruppe entkoppelt.
@@ -273,9 +281,31 @@ public class LiteDbContext : IDisposable
MigrateCompetencyReferences(); MigrateCompetencyReferences();
version = 6; version = 6;
} }
if (version < 7)
{
MigrateDashboardWarningSnoozeIds();
version = 7;
}
WriteSchemaVersion(version); WriteSchemaVersion(version);
} }
/// DashboardWarningSnooze wird seit Schema 7 synchronisiert und braucht dafür eine aus
/// (StudentId, WarningTag) abgeleitete Id (siehe DashboardWarningSnooze.IdFor). Vorher lokal
/// angelegte Einträge mit zufälliger Id werden umgeschlüsselt, sonst kollidierte ein
/// eingehender Sync-Datensatz für dasselbe Paar am Unique-Index ux_student_tag.
private void MigrateDashboardWarningSnoozeIds()
{
var snoozes = DashboardWarningSnoozes;
foreach (var snooze in snoozes.FindAll().ToList())
{
var id = DashboardWarningSnooze.IdFor(snooze.StudentId, snooze.WarningTag);
if (snooze.Id == id) continue;
snoozes.Delete(snooze.Id);
snooze.Id = id;
snoozes.Upsert(snooze);
}
}
private int ReadSchemaVersion() private int ReadSchemaVersion()
{ {
var meta = _db.GetCollection<BsonDocument>("meta").FindById(1); var meta = _db.GetCollection<BsonDocument>("meta").FindById(1);
@@ -636,6 +666,7 @@ public class LiteDbContext : IDisposable
Groups.EnsureIndex(x => x.SchoolYear); Groups.EnsureIndex(x => x.SchoolYear);
Groups.EnsureIndex(x => x.IsActive); Groups.EnsureIndex(x => x.IsActive);
SeatingPlans.EnsureIndex(x => x.GroupId); SeatingPlans.EnsureIndex(x => x.GroupId);
StudentGroupPlans.EnsureIndex(x => x.GroupId);
Memberships.EnsureIndex(x => x.StudentId); Memberships.EnsureIndex(x => x.StudentId);
Memberships.EnsureIndex(x => x.GroupId); Memberships.EnsureIndex(x => x.GroupId);
Memberships.EnsureIndex("ux_student_group", Memberships.EnsureIndex("ux_student_group",
@@ -654,6 +685,8 @@ public class LiteDbContext : IDisposable
ReportGrades.EnsureIndex(x => x.StudentId); ReportGrades.EnsureIndex(x => x.StudentId);
ReportGrades.EnsureIndex("ux_student_group_period", ReportGrades.EnsureIndex("ux_student_group_period",
BsonExpression.Create("STRING($.StudentId) + ':' + STRING($.GroupId) + ':' + $.Period"), unique: true); BsonExpression.Create("STRING($.StudentId) + ':' + STRING($.GroupId) + ':' + $.Period"), unique: true);
InterimGrades.EnsureIndex(x => x.GroupId);
InterimGrades.EnsureIndex(x => x.StudentId);
GradingKeyTemplates.EnsureIndex(x => x.GradingSystem); GradingKeyTemplates.EnsureIndex(x => x.GradingSystem);
Units.EnsureIndex(x => x.GroupId); Units.EnsureIndex(x => x.GroupId);
Lessons.EnsureIndex(x => x.UnitId); Lessons.EnsureIndex(x => x.UnitId);
@@ -694,6 +727,8 @@ public class LiteDbContext : IDisposable
UntisStudentRosterCache.EnsureIndex(x => x.ClassName); UntisStudentRosterCache.EnsureIndex(x => x.ClassName);
UntisCacheFetchStates.EnsureIndex("ux_class_kind", UntisCacheFetchStates.EnsureIndex("ux_class_kind",
BsonExpression.Create("STRING($.ClassName) + ':' + STRING($.Kind)"), unique: true); BsonExpression.Create("STRING($.ClassName) + ':' + STRING($.Kind)"), unique: true);
DashboardWarningSnoozes.EnsureIndex("ux_student_tag",
BsonExpression.Create("STRING($.StudentId) + ':' + STRING($.WarningTag)"), unique: true);
} }
public void Dispose() => _db.Dispose(); public void Dispose() => _db.Dispose();
+44 -4
View File
@@ -32,9 +32,12 @@ public class StudentRepository(LiteDbContext db) : IStudentRepository
db.Memberships.Count(m => m.StudentId == studentId), db.Memberships.Count(m => m.StudentId == studentId),
db.ExamResults.Count(r => r.StudentId == studentId), db.ExamResults.Count(r => r.StudentId == studentId),
db.Grades.Count(g => g.StudentId == studentId), db.Grades.Count(g => g.StudentId == studentId),
db.ReportGrades.Count(g => g.StudentId == studentId), // Zwischenstände sind vorläufige Zeugnisnoten und zählen hier mit.
db.ReportGrades.Count(g => g.StudentId == studentId) + db.InterimGrades.Count(g => g.StudentId == studentId),
db.ParticipationEntries.Count(e => e.StudentId == studentId), db.ParticipationEntries.Count(e => e.StudentId == studentId),
db.Documentation.Count(d => d.StudentId == studentId)); db.Documentation.FindAll().Count(d => d.Concerns(studentId)),
db.StudentGroupPlans.FindAll().Count(plan =>
plan.Groups.Any(group => group.StudentIds.Contains(studentId))));
public void Save(Student s) public void Save(Student s)
{ {
s.ExternalIds ??= []; s.ExternalIds ??= [];
@@ -328,6 +331,27 @@ public class GradingSchemeRepository(LiteDbContext db) : IGradingSchemeRepositor
} }
} }
public class InterimGradeRepository(LiteDbContext db) : IInterimGradeRepository
{
public List<InterimGrade> GetByGroup(Guid groupId) => db.InterimGrades.Find(g => g.GroupId == groupId).ToList();
public List<InterimGrade> GetByStudentAndGroup(Guid studentId, Guid groupId) =>
db.InterimGrades.Find(g => g.StudentId == studentId && g.GroupId == groupId).ToList();
public void Save(InterimGrade g)
{
ArchivedGroupWriteGuard.EnsureActive(db, g.GroupId);
g.UpdatedAt = DateTime.UtcNow;
db.InterimGrades.Upsert(g);
db.OnChange?.Invoke(nameof(InterimGrade), g.Id.ToString(), "Save", g);
}
public void Delete(Guid id)
{
if (db.InterimGrades.FindById(id) is { } grade)
ArchivedGroupWriteGuard.EnsureActive(db, grade.GroupId);
db.InterimGrades.Delete(id);
db.OnChange?.Invoke(nameof(InterimGrade), id.ToString(), "Delete", null);
}
}
public class ReportGradeRepository(LiteDbContext db) : IReportGradeRepository public class ReportGradeRepository(LiteDbContext db) : IReportGradeRepository
{ {
public List<ReportGrade> GetByGroup(Guid groupId) => db.ReportGrades.Find(r => r.GroupId == groupId).ToList(); public List<ReportGrade> GetByGroup(Guid groupId) => db.ReportGrades.Find(r => r.GroupId == groupId).ToList();
@@ -415,10 +439,13 @@ public class LessonRepository(LiteDbContext db) : ILessonRepository
public class DocumentationRepository(LiteDbContext db) : IDocumentationRepository public class DocumentationRepository(LiteDbContext db) : IDocumentationRepository
{ {
// Filter auf AdditionalStudentIds bewusst im Speicher statt als LiteDB-Ausdruck — die Menge
// an Dokumentation pro Lehrkraft ist klein, und so gilt exakt dieselbe Regel wie Documentation.Concerns.
public List<Documentation> GetByStudent(Guid id) => public List<Documentation> GetByStudent(Guid id) =>
db.Documentation.Find(d => d.StudentId == id && !d.IsDeleted).OrderByDescending(d => d.Date).ToList(); db.Documentation.Find(d => !d.IsDeleted).Where(d => d.Concerns(id))
.OrderByDescending(d => d.Date).ToList();
public List<Documentation> GetByStudentAndType(Guid sid, DocumentationType type) => public List<Documentation> GetByStudentAndType(Guid sid, DocumentationType type) =>
db.Documentation.Find(d => d.StudentId == sid && d.Type == type && !d.IsDeleted) db.Documentation.Find(d => d.Type == type && !d.IsDeleted).Where(d => d.Concerns(sid))
.OrderByDescending(d => d.Date).ToList(); .OrderByDescending(d => d.Date).ToList();
public List<Documentation> GetAll() => public List<Documentation> GetAll() =>
db.Documentation.Find(d => !d.IsDeleted).OrderByDescending(d => d.Date).ToList(); db.Documentation.Find(d => !d.IsDeleted).OrderByDescending(d => d.Date).ToList();
@@ -901,6 +928,19 @@ public class UntisCacheFetchStateRepository(LiteDbContext db) : IUntisCacheFetch
public void Save(UntisCacheFetchState state) => db.UntisCacheFetchStates.Upsert(state); public void Save(UntisCacheFetchState state) => db.UntisCacheFetchStates.Upsert(state);
} }
public class DashboardWarningSnoozeRepository(LiteDbContext db) : IDashboardWarningSnoozeRepository
{
public DashboardWarningSnooze? Get(Guid studentId, string warningTag) =>
db.DashboardWarningSnoozes.FindOne(s => s.StudentId == studentId && s.WarningTag == warningTag);
public List<DashboardWarningSnooze> GetAll() => db.DashboardWarningSnoozes.FindAll().ToList();
public void Save(DashboardWarningSnooze snooze)
{
snooze.Id = DashboardWarningSnooze.IdFor(snooze.StudentId, snooze.WarningTag);
db.DashboardWarningSnoozes.Upsert(snooze);
db.OnChange?.Invoke(nameof(DashboardWarningSnooze), snooze.Id.ToString(), "Save", snooze);
}
}
public class UntisHubJobStateRepository(LiteDbContext db) : IUntisHubJobStateRepository public class UntisHubJobStateRepository(LiteDbContext db) : IUntisHubJobStateRepository
{ {
public UntisHubJobState? Get(UntisHubJobKind kind, Guid? groupId) => public UntisHubJobState? Get(UntisHubJobKind kind, Guid? groupId) =>
@@ -0,0 +1,55 @@
using LehrerApp.Core.Interfaces;
using LehrerApp.Core.Models;
namespace LehrerApp.Data.Repositories;
public class StudentGroupPlanRepository(LiteDbContext db) : IStudentGroupPlanRepository
{
public StudentGroupPlan? GetById(Guid id) => db.StudentGroupPlans.FindById(id);
public List<StudentGroupPlan> GetByGroup(Guid groupId) =>
db.StudentGroupPlans.Find(p => p.GroupId == groupId)
.OrderByDescending(p => p.UpdatedAt).ToList();
public List<StudentGroupPlan> GetByStudent(Guid studentId) =>
db.StudentGroupPlans.FindAll()
.Where(plan => plan.Groups.Any(group => group.StudentIds.Contains(studentId)))
.OrderByDescending(plan => plan.UpdatedAt).ToList();
public void Save(StudentGroupPlan plan)
{
if (db.Groups.FindById(plan.GroupId) is null)
throw new InvalidOperationException("Die zugehörige Lerngruppe existiert nicht.");
ArchivedGroupWriteGuard.EnsureActive(db, plan.GroupId);
plan.Name = plan.Name?.Trim() ?? "";
if (plan.Name.Length == 0)
throw new ArgumentException("Bitte einen Namen für die Gruppeneinteilung eingeben.");
plan.Groups ??= [];
if (plan.Groups.Count == 0)
throw new InvalidOperationException("Die Gruppeneinteilung enthält keine Gruppen.");
var ids = plan.Groups.SelectMany(g => g.StudentIds ?? []).ToList();
if (ids.Count != ids.Distinct().Count())
throw new InvalidOperationException("Ein Schüler darf nur in einer Gruppe stehen.");
if (db.StudentGroupPlans.Find(p => p.GroupId == plan.GroupId)
.Any(p => p.Id != plan.Id && string.Equals(p.Name, plan.Name, StringComparison.OrdinalIgnoreCase)))
throw new InvalidOperationException("Eine gespeicherte Einteilung mit diesem Namen gibt es bereits.");
if (db.StudentGroupPlans.FindById(plan.Id) is { } existing)
{
if (existing.GroupId != plan.GroupId)
throw new InvalidOperationException("Eine Gruppeneinteilung kann nicht in eine andere Lerngruppe verschoben werden.");
plan.CreatedAt = existing.CreatedAt;
}
plan.UpdatedAt = DateTime.UtcNow;
db.StudentGroupPlans.Upsert(plan);
db.OnChange?.Invoke(nameof(StudentGroupPlan), plan.Id.ToString(), "Save", plan);
}
public void Delete(Guid id)
{
if (db.StudentGroupPlans.FindById(id) is not { } plan) return;
ArchivedGroupWriteGuard.EnsureActive(db, plan.GroupId);
db.StudentGroupPlans.Delete(id);
db.OnChange?.Invoke(nameof(StudentGroupPlan), id.ToString(), "Delete", null);
}
}
@@ -18,7 +18,7 @@ public sealed class AiPlanningServiceTests
FakeCompetencyDomains competencyDomains, FakeAlternativeLessonPaths altPaths, FakeCompetencyDomains competencyDomains, FakeAlternativeLessonPaths altPaths,
FakeCompetencyCatalogVersions? competencyVersions = null) => FakeCompetencyCatalogVersions? competencyVersions = null) =>
new(new HttpClient(), lessons, groups, subjects, competencyDomains, new(new HttpClient(), lessons, groups, subjects, competencyDomains,
competencyVersions ?? new FakeCompetencyCatalogVersions(), altPaths); competencyVersions ?? new FakeCompetencyCatalogVersions(), altPaths, TestSupport.BuildAppLogger());
[Fact] [Fact]
public void ParsePlanningLessons_AkzeptiertNormaleAntwortUndDeutschesDatum() public void ParsePlanningLessons_AkzeptiertNormaleAntwortUndDeutschesDatum()
@@ -92,7 +92,8 @@ public sealed class AiPlanningServiceTests
BaseAddress = new Uri("https://example.invalid/"), BaseAddress = new Uri("https://example.invalid/"),
}; };
var service = new AiPlanningService(http, new FakeLessons(), new FakeGroups([]), new FakeSubjects([]), var service = new AiPlanningService(http, new FakeLessons(), new FakeGroups([]), new FakeSubjects([]),
new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions(), new FakeAlternativeLessonPaths([])); new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions(), new FakeAlternativeLessonPaths([]),
TestSupport.BuildAppLogger());
var error = await Assert.ThrowsAsync<AiBackendException>(() => var error = await Assert.ThrowsAsync<AiBackendException>(() =>
service.RequestPlanAsync(new Unit(), "", "token")); service.RequestPlanAsync(new Unit(), "", "token"));
@@ -191,7 +192,8 @@ public sealed class AiPlanningServiceTests
BaseAddress = new Uri("https://example.invalid/"), BaseAddress = new Uri("https://example.invalid/"),
}; };
return new AiPlanningService(http, new FakeLessons(), new FakeGroups([]), new FakeSubjects([]), return new AiPlanningService(http, new FakeLessons(), new FakeGroups([]), new FakeSubjects([]),
new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions(), new FakeAlternativeLessonPaths([])); new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions(), new FakeAlternativeLessonPaths([]),
TestSupport.BuildAppLogger());
} }
private sealed class StaticResponseHandler(HttpStatusCode status, string body) : HttpMessageHandler private sealed class StaticResponseHandler(HttpStatusCode status, string body) : HttpMessageHandler
@@ -9,6 +9,38 @@ namespace LehrerApp.Desktop.Tests;
public sealed class ClassTeacherViewModelsTests public sealed class ClassTeacherViewModelsTests
{ {
[Theory]
[InlineData("Früher gegangen", 2, 90)]
[InlineData("Vorzeitig verlassen", 0, 20)]
public void FruehesGehen_IstTeilfehlzeitUndImKalenderGesondertErkennbar(string reason, int periods, int minutes)
{
var date = new DateOnly(2026, 9, 3);
var row = new ClassAbsenceDaySummaryRow(date, "Müller Ada", 1, periods, minutes,
[], [], ["nicht entsch."], [reason], null, null, true);
Assert.True(row.IsEarlyDeparture);
Assert.False(row.CountsAsFullDay);
Assert.False(row.IsLate);
Assert.True(row.IsPartialAbsence);
var marker = Assert.Single(ClassTeacherDetailsViewModel.BuildDayEvents(date, [row], [], false));
Assert.Equal("G", marker.Code);
Assert.Equal("#C62828", marker.ColorHex);
Assert.Contains("Früher gegangen", marker.Tooltip);
Assert.Contains("Unentschuldigt", marker.Tooltip);
Assert.DoesNotContain("Ganzer Fehltag", marker.Tooltip);
}
[Fact]
public void Kalender_GanzeFehltageBehaltenEigenesKuerzel()
{
var date = new DateOnly(2026, 9, 3);
var row = new ClassAbsenceDaySummaryRow(date, "Müller Ada", 1, 6, 270,
[], [], ["nicht entsch."], ["Absent"], null, null, true);
var marker = Assert.Single(ClassTeacherDetailsViewModel.BuildDayEvents(date, [row], [], false));
Assert.Equal("U", marker.Code);
Assert.Contains("Ganzer Fehltag", marker.Tooltip);
}
[Fact] [Fact]
public void Monatskalender_KodiertFehlzeitenUndBlendetHausaufgabenStandardmaessigAus() public void Monatskalender_KodiertFehlzeitenUndBlendetHausaufgabenStandardmaessigAus()
{ {
@@ -32,7 +64,7 @@ public sealed class ClassTeacherViewModelsTests
Assert.Equal(0, days.Count % 5); Assert.Equal(0, days.Count % 5);
Assert.Contains(days.SelectMany(d => d.Events), e => e.Code == "V"); Assert.Contains(days.SelectMany(d => d.Events), e => e.Code == "V");
Assert.Contains(days.SelectMany(d => d.Events), e => e.Code == "U"); Assert.Contains(days.SelectMany(d => d.Events), e => e.Code == "T");
Assert.Contains(days.SelectMany(d => d.Events), e => e.Code == "!"); Assert.Contains(days.SelectMany(d => d.Events), e => e.Code == "!");
Assert.DoesNotContain(days.SelectMany(d => d.Events), e => e.Code == "H"); Assert.DoesNotContain(days.SelectMany(d => d.Events), e => e.Code == "H");
@@ -65,10 +97,10 @@ public sealed class ClassTeacherViewModelsTests
Assert.Equal(30, days.Count); Assert.Equal(30, days.Count);
Assert.False(days[0].HasSignal); Assert.False(days[0].HasSignal);
Assert.Equal("1", days[0].DayNumber); Assert.Equal("1", days[0].DayNumber);
Assert.Equal("U", days[2].SignalCode); // stärker als der parallele Klassenbucheintrag Assert.Equal("T", days[2].SignalCode); // stärker als der parallele Klassenbucheintrag
Assert.True(days[2].IsToday); Assert.True(days[2].IsToday);
Assert.Contains("Ada Müller", days[2].Tooltip); Assert.Contains("Ada Müller", days[2].Tooltip);
Assert.Equal("E", days[3].SignalCode); Assert.Equal("T", days[3].SignalCode);
Assert.False(days[4].HasSignal); // Hausaufgaben bleiben im Widget bewusst ausgeblendet Assert.False(days[4].HasSignal); // Hausaufgaben bleiben im Widget bewusst ausgeblendet
} }
@@ -87,7 +119,7 @@ public sealed class ClassTeacherViewModelsTests
var days = ClassTeacherOverviewViewModel.BuildCompactMonthDays(month, absences, [], month, var days = ClassTeacherOverviewViewModel.BuildCompactMonthDays(month, absences, [], month,
"Ada Müller"); "Ada Müller");
Assert.Equal("U", days[2].SignalCode); Assert.Equal("T", days[2].SignalCode);
Assert.False(days[3].HasSignal); Assert.False(days[3].HasSignal);
} }
@@ -107,7 +139,7 @@ public sealed class ClassTeacherViewModelsTests
Assert.True(drawing.ContentHeight > 0); Assert.True(drawing.ContentHeight > 0);
Assert.Contains(drawing.Commands.OfType<DrawStringEx>(), c => c.Text == "Ada Müller"); Assert.Contains(drawing.Commands.OfType<DrawStringEx>(), c => c.Text == "Ada Müller");
Assert.Contains(drawing.Commands.OfType<DrawStringEx>(), c => c.Text == "U"); Assert.Contains(drawing.Commands.OfType<DrawStringEx>(), c => c.Text == "T");
Assert.DoesNotContain(drawing.Commands.OfType<DrawStringEx>(), c => c.Text == "E"); Assert.DoesNotContain(drawing.Commands.OfType<DrawStringEx>(), c => c.Text == "E");
} }
@@ -367,6 +399,24 @@ public sealed class ClassTeacherViewModelsTests
Assert.False(andere.CountsAsFullDay); Assert.False(andere.CountsAsFullDay);
} }
[Fact]
public void GroupByStudentAndDay_ZweiFehlstundenBleibenTeilfehlzeit()
{
var entries = new[]
{
new UntisClassAbsenceEntryDto("Muster Max", 1, "6a", 20260824, 1, 45, "HED", "Che", null,
null, 1, null, true, null, 3, "nicht entsch.", false),
new UntisClassAbsenceEntryDto("Muster Max", 1, "6a", 20260824, 1, 45, "PAN", "Kunst", null,
null, 2, null, true, null, 4, "nicht entsch.", false),
};
var row = Assert.Single(ClassAbsenceDaySummaryRow.GroupByStudentAndDay(entries));
Assert.False(row.CountsAsFullDay);
Assert.True(row.IsPartialAbsence);
Assert.Equal("2 Fehlstunden", row.KindLabel);
}
[Fact] [Fact]
public void GroupByStudentAndDay_TrenntGleichenNamenAnUnterschiedlichenTagen() public void GroupByStudentAndDay_TrenntGleichenNamenAnUnterschiedlichenTagen()
{ {
@@ -509,11 +559,14 @@ public sealed class ClassTeacherViewModelsTests
termStart: new DateOnly(2026, 8, 1))); termStart: new DateOnly(2026, 8, 1)));
Assert.True(row.HasYearSummary); Assert.True(row.HasYearSummary);
Assert.Equal(2, row.YearAbsenceDayCount); Assert.Equal(1, row.YearAbsenceDayCount);
Assert.Equal(1, row.YearUnexcusedDayCount); Assert.Equal(1, row.YearUnexcusedDayCount);
Assert.Equal(10, row.YearAbsenceRatePercent); Assert.Equal(2, row.YearAbsencePeriodCount);
Assert.Contains("10 %", row.YearSummaryLabel); Assert.Equal(2, row.YearExcusedPeriodCount);
Assert.Contains("2 von 20", row.YearSummaryTooltip); Assert.Equal(5, row.YearAbsenceRatePercent);
Assert.Contains("5 %", row.YearSummaryLabel);
Assert.Contains("1 von 20", row.YearSummaryTooltip);
Assert.Contains("2 Fehlstunden", row.YearSummaryTooltip);
Assert.Contains("seit 01.08.", row.YearSummaryTooltip); Assert.Contains("seit 01.08.", row.YearSummaryTooltip);
Assert.Contains("1 unentschuldigt", row.YearSummaryTooltip); Assert.Contains("1 unentschuldigt", row.YearSummaryTooltip);
} }
@@ -577,24 +630,30 @@ public sealed class ClassTeacherViewModelsTests
} }
[Fact] [Fact]
public void RosterBuild_UnentschuldigtUndVerspaetetZaehltAlsUnentschuldigtNichtAlsVerspaetung() public void RosterBuild_UnentschuldigteFehlstundeZaehltNichtAlsGanzerFehltag()
{ {
// Wer unentschuldigt UND verspätet ist, bleibt der schwerwiegendere Fall (dieselbe // Kernfall: Eine Schülerin fehlt aus Protest eine Unterrichtsstunde. Das bleibt
// Rangfolge wie AttentionRank/StatusKind/BuildTrend: Unentschuldigt vor Verspätet) — zählt // unentschuldigt und score-relevant, darf im Zeugnis-/Jahresstand aber nicht als ganzer
// deshalb weiter voll in die Quote statt in YearLateDayCount zu verschwinden. // unentschuldigter Fehltag erscheinen.
var students = new[] { Student(1001, "Ada Müller") }; var students = new[] { Student(1001, "Ada Müller") };
var yearAbsences = new[] var yearAbsences = new[]
{ {
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 8, 10), "Müller Ada", 1001, 0, 60, new ClassAbsenceDaySummaryRow(new DateOnly(2026, 8, 10), "Müller Ada", 1001, 1, 45,
["Deu"], [1], ["nicht entsch."], ["Verspätung"], null, null, false), ["Deu"], [1], ["nicht entsch."], ["Absent"], "Aus Protest gegangen", null, false),
}; };
var row = Assert.Single(ClassTeacherRosterRow.Build(students, [], [], var row = Assert.Single(ClassTeacherRosterRow.Build(students, [], [],
new DateOnly(2026, 8, 26), yearAbsences, schoolDaysElapsed: 20, termStart: new DateOnly(2026, 8, 1))); new DateOnly(2026, 8, 26), yearAbsences, schoolDaysElapsed: 20, termStart: new DateOnly(2026, 8, 1)));
Assert.Equal(1, row.YearAbsenceDayCount); Assert.Equal(0, row.YearAbsenceDayCount);
Assert.Equal(1, row.YearUnexcusedDayCount); Assert.Equal(0, row.YearUnexcusedDayCount);
Assert.Equal(1, row.YearAbsencePeriodCount);
Assert.Equal(1, row.YearUnexcusedPeriodCount);
Assert.Equal(0, row.YearLateDayCount); Assert.Equal(0, row.YearLateDayCount);
Assert.Equal(0, row.YearAbsenceRatePercent);
Assert.Contains("1 Fehlstunde", row.YearSummaryLabel);
Assert.Contains("1 unentschuldigt", row.YearSummaryTooltip);
Assert.Equal(0.5, row.PatternScore, precision: 10); // 1 von typischerweise 6 Stunden × Tagesgewicht 3
} }
[Fact] [Fact]
@@ -754,7 +813,8 @@ public sealed class ClassTeacherViewModelsTests
var row = Assert.Single(ClassTeacherRosterRow.Build(students, [], [], new DateOnly(2026, 8, 26), var row = Assert.Single(ClassTeacherRosterRow.Build(students, [], [], new DateOnly(2026, 8, 26),
yearAbsences, schoolDaysElapsed: 10)); yearAbsences, schoolDaysElapsed: 10));
Assert.Equal(1, row.YearAbsenceDayCount); Assert.Equal(0, row.YearAbsenceDayCount);
Assert.Equal(2, row.YearAbsencePeriodCount);
} }
[Fact] [Fact]
@@ -963,9 +1023,9 @@ public sealed class ClassTeacherViewModelsTests
var absences = new[] var absences = new[]
{ {
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 8, 24), "Fehlt Cem", 1001, 1, 45, new ClassAbsenceDaySummaryRow(new DateOnly(2026, 8, 24), "Fehlt Cem", 1001, 1, 45,
["Deu"], [1], ["nicht entsch."], ["Absent"], null, null, false), ["Deu"], [1], ["nicht entsch."], ["Absent"], null, null, true),
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 8, 25), "Fehlt Cem", 1001, 1, 45, new ClassAbsenceDaySummaryRow(new DateOnly(2026, 8, 25), "Fehlt Cem", 1001, 1, 45,
["Deu"], [1], ["nicht entsch."], ["Absent"], null, null, false), ["Deu"], [1], ["nicht entsch."], ["Absent"], null, null, true),
}; };
var names = new Dictionary<string, string> { [UntisNameMatching.NameKey("Fehlt Cem")] = "Cem Fehlt" }; var names = new Dictionary<string, string> { [UntisNameMatching.NameKey("Fehlt Cem")] = "Cem Fehlt" };
@@ -978,6 +1038,26 @@ public sealed class ClassTeacherViewModelsTests
Assert.False(notice.CanCreateReminder); Assert.False(notice.CanCreateReminder);
} }
[Fact]
public void DetectLatePatterns_StundenweisesUnentschuldigtesFehlenBleibtEigeneWarnstufe()
{
var absences = new[]
{
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 9, 21), "Protest Ada", 1001, 1, 45,
["Deu"], [2], ["nicht entsch."], ["Absent"], null, null, false),
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 9, 24), "Protest Ada", 1001, 1, 45,
["Mat"], [4], ["nicht entsch."], ["Absent"], null, null, false),
};
var names = new Dictionary<string, string>
{ [UntisNameMatching.NameKey("Protest Ada")] = "Ada Protest" };
var notice = Assert.Single(ClassTeacherOverviewViewModel.DetectLatePatterns(
absences, names, sevenDayStart: new DateOnly(2026, 9, 20)));
Assert.Contains("stundenweise unentschuldigte Fehlzeiten", notice.Message);
Assert.Equal(ClassTeacherStatusKind.Warning, notice.Kind);
}
// ── Aggregierte Klassenbuch-Kategorien (Feature-Idee 5) ────────────────── // ── Aggregierte Klassenbuch-Kategorien (Feature-Idee 5) ──────────────────
[Fact] [Fact]
@@ -1230,6 +1310,18 @@ public sealed class ClassTeacherViewModelsTests
Assert.Empty(result); Assert.Empty(result);
} }
[Fact]
public void FilterAvailableDocumentation_BeruecksichtigtWeitereBeteiligte()
{
Guid ada = Guid.NewGuid(), ben = Guid.NewGuid();
var shared = new Documentation { StudentId = Guid.NewGuid(), AdditionalStudentIds = [ben] };
var vorgang = new Vorgang { StudentIds = [ada, ben] };
var result = ClassTeacherCasesViewModel.FilterAvailableDocumentation([shared], vorgang);
Assert.Equal(shared.Id, Assert.Single(result).Id);
}
// ── Konfigurierbare Gewichtung + Dämpfung/Rückfall-Warnung nach geschlossenem Vorgang ───────── // ── Konfigurierbare Gewichtung + Dämpfung/Rückfall-Warnung nach geschlossenem Vorgang ─────────
[Fact] [Fact]
@@ -40,7 +40,8 @@ public sealed class CompetencyOverviewViewModelTests
Items = [k1], Items = [k1],
}); });
var vm = new CompetencyOverviewTabViewModel(units, new FakeExams([exam]), results, var vm = new CompetencyOverviewTabViewModel(units, new FakeExams([exam]), results,
catalog, versions, new FakeStudents([student]), new CompetencyAnalysisService()); catalog, versions, new FakeStudents([student]), new FakeSessions([]), new FakeEntries(),
new FakeAspects(), new CompetencyAnalysisService());
vm.Initialize(group); vm.Initialize(group);
@@ -70,4 +71,52 @@ public sealed class CompetencyOverviewViewModelTests
Assert.Equal("Stand solide", row.Recommendation); Assert.Equal("Stand solide", row.Recommendation);
} }
[Fact]
public void Initialize_AutomatischeMitarbeitsschaetzung_FuelltKompetenzprofil()
{
var subjectId = Guid.NewGuid();
var group = new LearningGroup { SubjectId = subjectId, GradeLevel = 8 };
var student = new Student { FirstName = "Ada", LastName = "Lovelace" };
var competency = new CompetencyItem { Code = "K1", Description = "Kompetenz" };
var versions = new FakeCompetencyCatalogVersions();
var version = versions.GetOrCreateDefault(subjectId);
var catalog = new FakeCompetencyDomains();
catalog.Add(new CompetencyDomain
{
SubjectId = subjectId,
GradeLevel = 8,
VersionId = version.Id,
Name = "Bereich",
Items = [competency],
});
var session = new ParticipationSession
{
GroupId = group.Id,
Competencies = [new CompetencyReference
{
ItemId = competency.Id,
Code = competency.Code,
Description = competency.Description,
}],
};
var entries = new FakeEntries();
entries.Add(new ParticipationEntry
{
SessionId = session.Id,
StudentId = student.Id,
Ratings = [new AspectRating { Key = "quality", Value = 1 }],
});
var vm = new CompetencyOverviewTabViewModel(new FakeUnits(), new FakeExams([]),
new FakeResults(), catalog, versions, new FakeStudents([student]),
new FakeSessions([session]), entries, new FakeAspects(), new CompetencyAnalysisService());
vm.Initialize(group);
var row = Assert.Single(vm.Rows);
Assert.Equal("1× bewertet", row.ParticipationCoverage);
Assert.Contains("75 %", row.GroupResult);
Assert.Contains("1 Mitarbeitswert", row.StudentResult);
}
} }
@@ -1,3 +1,4 @@
using CommunityToolkit.Mvvm.Input;
using LehrerApp.Core.Models; using LehrerApp.Core.Models;
using LehrerApp.Core.Services; using LehrerApp.Core.Services;
using LehrerApp.Desktop.ViewModels; using LehrerApp.Desktop.ViewModels;
@@ -83,12 +84,42 @@ public sealed class DashboardViewModelTests
private static IEnumerable<AttentionItem> Items(DashboardViewModel vm, AttentionKind kind) => private static IEnumerable<AttentionItem> Items(DashboardViewModel vm, AttentionKind kind) =>
vm.Attention.Where(g => g.Kind == kind).SelectMany(g => g.Items); vm.Attention.Where(g => g.Kind == kind).SelectMany(g => g.Items);
/// Entschärfte Warnungen stehen nicht in ihrer Art-Gruppe, sondern gesammelt in der
/// "Zurückgestellt"-Gruppe am Ende.
private static IEnumerable<AttentionItem> DeferredItems(DashboardViewModel vm) =>
vm.Attention.Where(g => g.IsDeferred).SelectMany(g => g.Items);
/// AttentionItem traegt fuer MissingTeachingTime kein eigenes Date-Feld (Title ist bereits der /// AttentionItem traegt fuer MissingTeachingTime kein eigenes Date-Feld (Title ist bereits der
/// formatierte Anzeigetext) — das genaue Datum steckt im mitgegebenen Action-Parameter /// formatierte Anzeigetext) — das genaue Datum steckt im mitgegebenen Action-Parameter
/// (derselbe MissingTeachingTimeItem, den auch der "Erfassen"-Dialog erhaelt). /// (derselbe MissingTeachingTimeItem, den auch der "Erfassen"-Dialog erhaelt).
private static DateOnly MissingTimeDate(AttentionItem item) => private static DateOnly MissingTimeDate(AttentionItem item) =>
((MissingTeachingTimeItem)item.Actions.Single().Parameter!).Date; ((MissingTeachingTimeItem)item.Actions.Single().Parameter!).Date;
[Fact]
public void OpenExcuses_ZeigtNurSchuelerAusEigenerKlasse()
{
var today = DateOnly.FromDateTime(DateTime.Today);
var ownClass = new LearningGroup { Name = "Meine 9c", IsOwnClass = true };
var otherClass = new LearningGroup { Name = "Fremde 8a", IsOwnClass = false };
var ownStudent = new Student { FirstName = "Anna", LastName = "Eigen" };
var otherStudent = new Student { FirstName = "Ben", LastName = "Fremd" };
var ownSession = new ParticipationSession { GroupId = ownClass.Id, Date = today.AddDays(-1) };
var otherSession = new ParticipationSession { GroupId = otherClass.Id, Date = today.AddDays(-1) };
var entries = new FakeEntries();
entries.Add(new ParticipationEntry
{ SessionId = ownSession.Id, StudentId = ownStudent.Id, Attendance = AttendanceStatus.ExcusePending });
entries.Add(new ParticipationEntry
{ SessionId = otherSession.Id, StudentId = otherStudent.Id, Attendance = AttendanceStatus.ExcusePending });
var vm = BuildVm(ownClass, new Lesson { GroupId = ownClass.Id, Date = today },
allGroups: [ownClass, otherClass], students: new FakeStudents([ownStudent, otherStudent]),
sessions: new FakeSessions([ownSession, otherSession]), entries: entries);
var excuse = Assert.Single(Items(vm, AttentionKind.Excuse));
Assert.Equal(ownStudent.FullName, excuse.Title);
Assert.DoesNotContain(Items(vm, AttentionKind.Excuse), item => item.Title == otherStudent.FullName);
}
private static PeriodScheduleService NewPeriodSchedule() private static PeriodScheduleService NewPeriodSchedule()
{ {
var tempPath = System.IO.Path.Combine( var tempPath = System.IO.Path.Combine(
@@ -118,6 +149,7 @@ public sealed class DashboardViewModelTests
FakeExams? exams = null, FakeResults? results = null, FakeGrades? grades = null, FakeExams? exams = null, FakeResults? results = null, FakeGrades? grades = null,
FakeReportGrades? reportGrades = null, FakeMemberships? memberships = null, FakeReportGrades? reportGrades = null, FakeMemberships? memberships = null,
FakeWorkTasks? tasks = null, FakeStudents? students = null, FakeDocumentation? documentation = null, FakeWorkTasks? tasks = null, FakeStudents? students = null, FakeDocumentation? documentation = null,
FakeVorgangRepository? vorgaenge = null, FakeDashboardWarningSnoozeRepository? warningSnoozes = null,
DashboardSettingsService? dashboardSettings = null, FakeSchoolHolidays? schoolHolidays = null, DashboardSettingsService? dashboardSettings = null, FakeSchoolHolidays? schoolHolidays = null,
FakeLessons? lessons = null, FakeSubstitutionEntries? substitutions = null, FakeLessons? lessons = null, FakeSubstitutionEntries? substitutions = null,
FakeSessions? sessions = null, FakeEntries? entries = null, FakeSessions? sessions = null, FakeEntries? entries = null,
@@ -132,6 +164,7 @@ public sealed class DashboardViewModelTests
reportGrades ?? new FakeReportGrades(), memberships ?? new FakeMemberships([]), reportGrades ?? new FakeReportGrades(), memberships ?? new FakeMemberships([]),
tasks ?? new FakeWorkTasks(), sessions ?? new FakeSessions([]), entries ?? new FakeEntries(), tasks ?? new FakeWorkTasks(), sessions ?? new FakeSessions([]), entries ?? new FakeEntries(),
students ?? new FakeStudents([]), documentation ?? new FakeDocumentation(), students ?? new FakeStudents([]), documentation ?? new FakeDocumentation(),
vorgaenge ?? new FakeVorgangRepository(), warningSnoozes ?? new FakeDashboardWarningSnoozeRepository(),
slots ?? new FakeTimetableSlots(), periodSchedule ?? NewPeriodSchedule(), slots ?? new FakeTimetableSlots(), periodSchedule ?? NewPeriodSchedule(),
new AttendanceBalanceService(), new SchoolYearService(), dashboardSettings ?? NewDashboardSettings(), new AttendanceBalanceService(), new SchoolYearService(), dashboardSettings ?? NewDashboardSettings(),
schoolHolidays ?? new FakeSchoolHolidays(), new PublicHolidayService(), NewCalendarSettings(), schoolHolidays ?? new FakeSchoolHolidays(), new PublicHolidayService(), NewCalendarSettings(),
@@ -780,6 +813,363 @@ public sealed class DashboardViewModelTests
var item = Assert.Single(Items(vm, AttentionKind.Attendance)); var item = Assert.Single(Items(vm, AttentionKind.Attendance));
Assert.Equal(student.FullName, item.Title); Assert.Equal(student.FullName, item.Title);
Assert.Equal("30 %", item.TrailingText); Assert.Equal("30 %", item.TrailingText);
Assert.True(item.IsCrossClassWarning);
Assert.Equal(AttentionKind.Attendance, vm.Attention.First().Kind);
}
/// Fehlzeiten-Warnungen landen seit der Verknüpfung mit dem schülerbezogenen "Vorgänge"-Tab auf
/// OnNavigateToStudentCase (mit dem passenden Tag "Absentismus") statt auf OnNavigateToStudent.
[Fact]
public void AttendanceWarnings_NavigiertUeberOnNavigateToStudentCaseMitAbsentismusTag()
{
var today = DateOnly.FromDateTime(DateTime.Today);
var group = new LearningGroup { Name = "9c" };
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
var sessions = new FakeSessions([]);
var entries = new FakeEntries();
for (var i = 0; i < 10; i++)
{
var session = new ParticipationSession { GroupId = group.Id, Date = today.AddDays(-i - 1) };
sessions.Save(session);
var status = i < 3 ? AttendanceStatus.Unexcused : AttendanceStatus.Present;
entries.Add(new ParticipationEntry { SessionId = session.Id, StudentId = student.Id, Attendance = status });
}
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
students: new FakeStudents([student]), sessions: sessions, entries: entries);
Guid? navigatedStudentId = null; string? navigatedTag = null; string? navigatedTitle = null;
vm.OnNavigateToStudentCase = (id, tag, title) => { navigatedStudentId = id; navigatedTag = tag; navigatedTitle = title; };
vm.OnNavigateToStudent = _ => throw new InvalidOperationException("sollte nicht mehr aufgerufen werden");
Assert.Single(Items(vm, AttentionKind.Attendance)).Navigate!.Invoke();
Assert.Equal(student.Id, navigatedStudentId);
Assert.Equal("Absentismus", navigatedTag);
Assert.Equal("Fehlzeiten", navigatedTitle);
}
[Fact]
public void MissingHomeworkWarnings_UnterSchwellenwertKeineWarnung()
{
var today = DateOnly.FromDateTime(DateTime.Today);
var group = new LearningGroup { Name = "9c" };
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
var sessions = new FakeSessions([]);
var entries = new FakeEntries();
// Nur 2 offene Hausaufgaben — Schwelle liegt bei 3.
for (var i = 0; i < 2; i++)
{
var session = new ParticipationSession { GroupId = group.Id, Date = today.AddDays(-i - 1) };
sessions.Save(session);
entries.Add(new ParticipationEntry
{ SessionId = session.Id, StudentId = student.Id, Homework = HomeworkStatus.MissingOpen });
}
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
students: new FakeStudents([student]), sessions: sessions, entries: entries);
Assert.Empty(Items(vm, AttentionKind.MissingHomework));
}
[Fact]
public void MissingHomeworkWarnings_MeldetAbSchwellenwertUndZaehltPartiallyCompletedAlsOffen()
{
var today = DateOnly.FromDateTime(DateTime.Today);
var group = new LearningGroup { Name = "9c" };
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
var sessions = new FakeSessions([]);
var entries = new FakeEntries();
// 3 offene/überfällige Hausaufgaben (davon eine PartiallyCompleted, zählt laut
// HomeworkDisplay.CountsAsMissing ebenfalls als offen) — erreicht die Schwelle von 3.
var statuses = new[] { HomeworkStatus.MissingOpen, HomeworkStatus.MissingOverdue, HomeworkStatus.PartiallyCompleted };
for (var i = 0; i < statuses.Length; i++)
{
var session = new ParticipationSession { GroupId = group.Id, Date = today.AddDays(-i - 1) };
sessions.Save(session);
entries.Add(new ParticipationEntry { SessionId = session.Id, StudentId = student.Id, Homework = statuses[i] });
}
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
students: new FakeStudents([student]), sessions: sessions, entries: entries);
var item = Assert.Single(Items(vm, AttentionKind.MissingHomework));
Assert.Equal(student.FullName, item.Title);
Assert.Equal("3 offen", item.TrailingText);
Guid? navigatedStudentId = null; string? navigatedTag = null;
vm.OnNavigateToStudentCase = (id, tag, _) => { navigatedStudentId = id; navigatedTag = tag; };
item.Navigate!.Invoke();
Assert.Equal(student.Id, navigatedStudentId);
Assert.Equal("Hausaufgaben", navigatedTag);
}
[Fact]
public void LatenessWarnings_UnterSchwellenwertKeineWarnung()
{
var today = DateOnly.FromDateTime(DateTime.Today);
var group = new LearningGroup { Name = "9c" };
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
var sessions = new FakeSessions([]);
var entries = new FakeEntries();
// Nur 7 Verspätungen — Schwelle liegt bei 8.
for (var i = 0; i < 7; i++)
{
var session = new ParticipationSession { GroupId = group.Id, Date = today.AddDays(-i - 1) };
sessions.Save(session);
entries.Add(new ParticipationEntry { SessionId = session.Id, StudentId = student.Id, Attendance = AttendanceStatus.Late });
}
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
students: new FakeStudents([student]), sessions: sessions, entries: entries);
Assert.Empty(Items(vm, AttentionKind.Lateness));
}
/// Regressionsschutz: Late/SignificantlyLate zählen bewusst NICHT in die Fehlzeitenquote hinein
/// (AttendanceBalanceService behandelt sie als Present) — auch wenn ein Schüler die neue
/// Verspätungs-Schwelle reißt, darf die bestehende Fehlzeiten-Warnung dadurch nicht auftauchen.
[Fact]
public void LatenessWarnings_MeldetAbSchwellenwertUndZaehltNichtAlsFehlzeit()
{
var today = DateOnly.FromDateTime(DateTime.Today);
var group = new LearningGroup { Name = "9c" };
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
var sessions = new FakeSessions([]);
var entries = new FakeEntries();
// 5x Late, 3x SignificantlyLate — zusammen 8, erreicht die Schwelle.
for (var i = 0; i < 8; i++)
{
var session = new ParticipationSession { GroupId = group.Id, Date = today.AddDays(-i - 1) };
sessions.Save(session);
var status = i < 5 ? AttendanceStatus.Late : AttendanceStatus.SignificantlyLate;
entries.Add(new ParticipationEntry { SessionId = session.Id, StudentId = student.Id, Attendance = status });
}
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
students: new FakeStudents([student]), sessions: sessions, entries: entries);
var item = Assert.Single(Items(vm, AttentionKind.Lateness));
Assert.Equal(student.FullName, item.Title);
Assert.Equal("8× verspätet", item.TrailingText);
Assert.Empty(Items(vm, AttentionKind.Attendance));
}
// ── Entschärfen (Nutzer-Feedback: "erledigt" wirkt grau/hinten, ohne dauerhaft stumm zu bleiben) ──
private static (Student Handled, Student Active) BuildTwoOverThresholdStudents(
LearningGroup group, DateOnly today, FakeSessions sessions, FakeEntries entries)
{
var handled = new Student { FirstName = "Anna", LastName = "Bearbeitet" };
var active = new Student { FirstName = "Ben", LastName = "Unbearbeitet" };
foreach (var student in new[] { handled, active })
for (var i = 0; i < 10; i++)
{
var session = new ParticipationSession { GroupId = group.Id, Date = today.AddDays(-i - 1) };
sessions.Save(session);
var status = i < 3 ? AttendanceStatus.Unexcused : AttendanceStatus.Present;
entries.Add(new ParticipationEntry { SessionId = session.Id, StudentId = student.Id, Attendance = status });
}
return (handled, active);
}
[Fact]
public void AttendanceWarnings_MitKuerzlichBearbeitetemVorgang_WandertInZurueckgestelltGruppe()
{
var today = DateOnly.FromDateTime(DateTime.Today);
var group = new LearningGroup { Name = "9c" };
var sessions = new FakeSessions([]);
var entries = new FakeEntries();
var (handled, active) = BuildTwoOverThresholdStudents(group, today, sessions, entries);
var vorgaenge = new FakeVorgangRepository();
vorgaenge.Add(new Vorgang
{
Title = "Fehlzeiten", StudentIds = [handled.Id], Tags = ["Absentismus"],
Status = VorgangStatus.Open, UpdatedAt = DateTime.UtcNow.AddDays(-2),
});
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
students: new FakeStudents([handled, active]), sessions: sessions, entries: entries,
vorgaenge: vorgaenge);
var item = Assert.Single(Items(vm, AttentionKind.Attendance));
Assert.False(item.IsDefused);
Assert.Equal(active.FullName, item.Title);
var deferred = Assert.Single(DeferredItems(vm));
Assert.True(deferred.IsDefused);
Assert.Equal(handled.FullName, deferred.Title);
Assert.Equal("Fehlzeiten · Vorgang in Bearbeitung", deferred.Subtitle);
}
[Fact]
public void AttendanceWarnings_VorgangAelterAlsFrist_BleibtScharf()
{
var today = DateOnly.FromDateTime(DateTime.Today);
var group = new LearningGroup { Name = "9c" };
var sessions = new FakeSessions([]);
var entries = new FakeEntries();
var (handled, _) = BuildTwoOverThresholdStudents(group, today, sessions, entries);
var vorgaenge = new FakeVorgangRepository();
// 20 Tage her — jenseits der 14-Tage-Frist (VorgangDefusalGraceDays).
vorgaenge.Add(new Vorgang
{
Title = "Fehlzeiten", StudentIds = [handled.Id], Tags = ["Absentismus"],
Status = VorgangStatus.Open, UpdatedAt = DateTime.UtcNow.AddDays(-20),
});
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
students: new FakeStudents([handled]), sessions: sessions, entries: entries, vorgaenge: vorgaenge);
Assert.False(Assert.Single(Items(vm, AttentionKind.Attendance)).IsDefused);
}
[Fact]
public void AttendanceWarnings_AktiveZurueckstellungIstEntschaerft_AbgelaufeneNichtMehr()
{
var today = DateOnly.FromDateTime(DateTime.Today);
var group = new LearningGroup { Name = "9c" };
var sessions = new FakeSessions([]);
var entries = new FakeEntries();
var (handled, active) = BuildTwoOverThresholdStudents(group, today, sessions, entries);
var snoozes = new FakeDashboardWarningSnoozeRepository();
snoozes.Save(new DashboardWarningSnooze { StudentId = handled.Id, WarningTag = "Absentismus", SnoozedUntil = today.AddDays(7) });
snoozes.Save(new DashboardWarningSnooze { StudentId = active.Id, WarningTag = "Absentismus", SnoozedUntil = today.AddDays(-1) });
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
students: new FakeStudents([handled, active]), sessions: sessions, entries: entries,
warningSnoozes: snoozes);
Assert.Equal(active.FullName, Assert.Single(Items(vm, AttentionKind.Attendance)).Title);
var deferred = Assert.Single(DeferredItems(vm));
Assert.Equal(handled.FullName, deferred.Title);
Assert.Equal($"Fehlzeiten · zurückgestellt bis {today.AddDays(7):dd.MM.}", deferred.Subtitle);
}
[Fact]
public void ZurueckgestelltGruppe_StehtEingeklapptAmEndeUndZaehltNichtMit()
{
var today = DateOnly.FromDateTime(DateTime.Today);
var group = new LearningGroup { Name = "9c" };
var sessions = new FakeSessions([]);
var entries = new FakeEntries();
var (handled, active) = BuildTwoOverThresholdStudents(group, today, sessions, entries);
var snoozes = new FakeDashboardWarningSnoozeRepository();
snoozes.Save(new DashboardWarningSnooze { StudentId = handled.Id, WarningTag = "Absentismus", SnoozedUntil = today.AddDays(7) });
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
students: new FakeStudents([handled, active]), sessions: sessions, entries: entries,
warningSnoozes: snoozes);
var last = vm.Attention.Last();
Assert.True(last.IsDeferred);
Assert.Null(last.Kind);
Assert.False(last.IsExpanded);
Assert.Equal(1, vm.AttentionCount);
Assert.True(vm.HasOpenAttention);
}
[Fact]
public void ZurueckgestelltGruppe_AufklappzustandUeberlebtNeuaufbauUndFilterBlendetAus()
{
var today = DateOnly.FromDateTime(DateTime.Today);
var group = new LearningGroup { Name = "9c" };
var sessions = new FakeSessions([]);
var entries = new FakeEntries();
var (handled, active) = BuildTwoOverThresholdStudents(group, today, sessions, entries);
var snoozes = new FakeDashboardWarningSnoozeRepository();
snoozes.Save(new DashboardWarningSnooze { StudentId = handled.Id, WarningTag = "Absentismus", SnoozedUntil = today.AddDays(7) });
snoozes.Save(new DashboardWarningSnooze { StudentId = active.Id, WarningTag = "Absentismus", SnoozedUntil = today.AddDays(7) });
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
students: new FakeStudents([handled, active]), sessions: sessions, entries: entries,
warningSnoozes: snoozes);
// Nur noch zurückgestellte Warnungen: kein offener Punkt, Kachel bleibt aber erreichbar.
Assert.Equal(0, vm.AttentionCount);
Assert.False(vm.HasOpenAttention);
Assert.False(vm.AttentionCard.IsEmpty);
vm.Attention.Single(g => g.IsDeferred).ToggleExpandedCommand.Execute(null);
var filter = vm.AttentionFilters.Single(f => f.Kind == AttentionKind.Attendance);
filter.IsActive = false;
Assert.DoesNotContain(vm.Attention, g => g.IsDeferred);
filter.IsActive = true;
Assert.True(vm.Attention.Single(g => g.IsDeferred).IsExpanded);
}
[Fact]
public async Task SnoozeAction_FragtNachUndEntschaerftDieWarnungSofort()
{
var today = DateOnly.FromDateTime(DateTime.Today);
var group = new LearningGroup { Name = "9c" };
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
var sessions = new FakeSessions([]);
var entries = new FakeEntries();
for (var i = 0; i < 10; i++)
{
var session = new ParticipationSession { GroupId = group.Id, Date = today.AddDays(-i - 1) };
sessions.Save(session);
var status = i < 3 ? AttendanceStatus.Unexcused : AttendanceStatus.Present;
entries.Add(new ParticipationEntry { SessionId = session.Id, StudentId = student.Id, Attendance = status });
}
var snoozes = new FakeDashboardWarningSnoozeRepository();
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
students: new FakeStudents([student]), sessions: sessions, entries: entries, warningSnoozes: snoozes);
string? shownMessage = null;
vm.OnPickSnoozeDuration = message => { shownMessage = message; return Task.FromResult<int?>(14); };
var item = Assert.Single(Items(vm, AttentionKind.Attendance));
Assert.False(item.IsDefused);
var snoozeAction = Assert.Single(item.Actions, a => a.Label == "Zurückstellen");
await ((IAsyncRelayCommand)snoozeAction.Command).ExecuteAsync(null);
Assert.Contains(student.FullName, shownMessage);
var saved = Assert.Single(snoozes.GetAll());
Assert.Equal(student.Id, saved.StudentId);
Assert.Equal("Absentismus", saved.WarningTag);
Assert.Equal(today.AddDays(14), saved.SnoozedUntil);
Assert.Empty(Items(vm, AttentionKind.Attendance));
Assert.True(Assert.Single(DeferredItems(vm)).IsDefused);
Assert.Equal(0, vm.AttentionCount);
}
[Fact]
public async Task SnoozeAction_AbbruchSpeichertNichts()
{
var today = DateOnly.FromDateTime(DateTime.Today);
var group = new LearningGroup { Name = "9c" };
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
var sessions = new FakeSessions([]);
var entries = new FakeEntries();
for (var i = 0; i < 10; i++)
{
var session = new ParticipationSession { GroupId = group.Id, Date = today.AddDays(-i - 1) };
sessions.Save(session);
var status = i < 3 ? AttendanceStatus.Unexcused : AttendanceStatus.Present;
entries.Add(new ParticipationEntry { SessionId = session.Id, StudentId = student.Id, Attendance = status });
}
var snoozes = new FakeDashboardWarningSnoozeRepository();
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
students: new FakeStudents([student]), sessions: sessions, entries: entries, warningSnoozes: snoozes);
vm.OnPickSnoozeDuration = _ => Task.FromResult<int?>(null);
var item = Assert.Single(Items(vm, AttentionKind.Attendance));
var snoozeAction = Assert.Single(item.Actions, a => a.Label == "Zurückstellen");
await ((IAsyncRelayCommand)snoozeAction.Command).ExecuteAsync(null);
Assert.Empty(snoozes.GetAll());
Assert.False(Assert.Single(Items(vm, AttentionKind.Attendance)).IsDefused);
} }
[Fact] [Fact]
@@ -308,4 +308,89 @@ public sealed class DocumentationDialogViewModelTests
Assert.Null(storage.OpenRead(storageId)); Assert.Null(storage.OpenRead(storageId));
} }
// ── Weitere Beteiligte ("Betrifft außerdem") ─────────────────────────────
[Fact]
public void WeitereBeteiligte_NeuerEintrag_UebernimmtAuswahlOhneHauptperson()
{
var anna = new StudentOption(Guid.NewGuid(), "Anna Beispiel");
var ben = new StudentOption(Guid.NewGuid(), "Ben Muster");
var cem = new StudentOption(Guid.NewGuid(), "Cem Test");
var vm = new DocumentationDialogViewModel(anna.Id, null, new FakeAttachmentStorage(),
coStudentOptions: [anna, ben, cem])
{
Title = "Konflikt", TypeName = "Vorkommnis",
};
Assert.True(vm.HasCoStudents);
Assert.True(vm.CoStudents.Single(c => c.Id == anna.Id).IsPrimary);
foreach (var c in vm.CoStudents) c.IsSelected = true;
vm.SaveCommand.Execute(null);
Assert.Equal(anna.Id, vm.Result!.StudentId);
Assert.Equal([ben.Id, cem.Id], vm.Result.AdditionalStudentIds);
}
[Fact]
public void WeitereBeteiligte_NurHauptpersonAlsKandidat_BlendetAuswahlAus()
{
var anna = new StudentOption(Guid.NewGuid(), "Anna Beispiel");
var vm = new DocumentationDialogViewModel(anna.Id, null, new FakeAttachmentStorage(), coStudentOptions: [anna]);
Assert.False(vm.HasCoStudents);
}
[Fact]
public void WeitereBeteiligte_WechselDerHauptperson_VerschiebtAusblendung()
{
var anna = new StudentOption(Guid.NewGuid(), "Anna Beispiel");
var ben = new StudentOption(Guid.NewGuid(), "Ben Muster");
var vm = new DocumentationDialogViewModel(anna.Id, null, new FakeAttachmentStorage(), [anna, ben],
coStudentOptions: [anna, ben])
{
Title = "Konflikt", TypeName = "Vorkommnis",
};
vm.CoStudents.Single(c => c.Id == anna.Id).IsSelected = true;
vm.SelectedStudent = ben;
vm.SaveCommand.Execute(null);
Assert.True(vm.CoStudents.Single(c => c.Id == ben.Id).IsPrimary);
Assert.Equal(ben.Id, vm.Result!.StudentId);
Assert.Equal([anna.Id], vm.Result.AdditionalStudentIds);
}
[Fact]
public void WeitereBeteiligte_BearbeitenOhneKandidaten_BehaeltBestehendeBei()
{
Guid anna = Guid.NewGuid(), ben = Guid.NewGuid();
var existing = new Documentation { StudentId = anna, AdditionalStudentIds = [ben], Title = "Konflikt" };
var vm = new DocumentationDialogViewModel(ben, existing, new FakeAttachmentStorage());
vm.SaveCommand.Execute(null);
Assert.Equal(anna, vm.Result!.StudentId);
Assert.Equal([ben], vm.Result.AdditionalStudentIds);
}
[Fact]
public void WeitereBeteiligte_Bearbeiten_AbwahlEntferntNurAngeboteneKandidaten()
{
var anna = new StudentOption(Guid.NewGuid(), "Anna Beispiel");
var ben = new StudentOption(Guid.NewGuid(), "Ben Muster");
var outsider = Guid.NewGuid();
var existing = new Documentation
{
StudentId = anna.Id, AdditionalStudentIds = [ben.Id, outsider], Title = "Konflikt",
};
var vm = new DocumentationDialogViewModel(anna.Id, existing, new FakeAttachmentStorage(),
coStudentOptions: [anna, ben]);
Assert.True(vm.CoStudents.Single(c => c.Id == ben.Id).IsSelected);
vm.CoStudents.Single(c => c.Id == ben.Id).IsSelected = false;
vm.SaveCommand.Execute(null);
Assert.Equal([outsider], vm.Result!.AdditionalStudentIds);
}
} }
@@ -0,0 +1,343 @@
using LehrerApp.Core.Models;
using LehrerApp.Core.Services;
using LehrerApp.Desktop.Services;
using LehrerApp.Desktop.ViewModels.Groups;
using LehrerApp.Templating;
using Xunit;
namespace LehrerApp.Desktop.Tests;
public sealed class ExamCoverSheetTests : IDisposable
{
private readonly string _directory = Path.Combine(Path.GetTempPath(), $"lehrerapp-cover-tests-{Guid.NewGuid():N}");
private readonly LearningGroup _group = new() { Name = "9 Ch G", SchoolYear = "2025/26", GradeLevel = 9 };
private readonly Student _anna = new() { FirstName = "Anna", LastName = "Adler" };
private readonly Student _ben = new() { FirstName = "Ben", LastName = "Bauer" };
private readonly Exam _exam;
private readonly FakeResults _results = new();
private const string Layout = """
PAGE 210 297 mm
#pragma format-version 3
#pragma page-template first
TEXT 20 20 $Student.Name size=12
#pragma flow-slot body x=20 y=40 w=170 h=230
#pragma end-page-template
#pragma content-flow body
TEXT $Exam.Title size=14
FLOWDRAWBOX $Exam.PointsTable w=170 h=120 fit=content gap=10
TEXT "Gesamtpunkte: $Result.Points von $Exam.MaxPoints Punkte" size=11 gap=8
TEXT "Note: $Result.Grade" size=14 gap=4
#pragma end-content-flow
""";
public ExamCoverSheetTests()
{
Directory.CreateDirectory(_directory);
_exam = new Exam
{
GroupId = _group.Id, Title = "Atombau und PSE", Date = new DateOnly(2025, 12, 18), ExamNumber = 1,
Tasks =
[
new() { Nr = 1, MaxPoints = 5 }, new() { Nr = 2, MaxPoints = 12 },
new() { Nr = 3, MaxPoints = 3, IsBonus = true },
],
GradingKey = [new() { Grade = "1", MinPercent = 90 }, new() { Grade = "6", MinPercent = 0 }],
};
}
[Fact]
public void PointsTable_BrichtBeiFesterSpaltenbreiteInWeitereBloeckeUm()
{
var eight = Enumerable.Range(1, 8).Select(n => new ExamCoverTaskColumn(n.ToString(), n, false, null)).ToList();
var oneBlock = ExamPointsTableDrawingBuilder.Build(eight.Take(6).ToList(), 170);
var twoBlocks = ExamPointsTableDrawingBuilder.Build(eight, 170);
Assert.Equal(6, ExamPointsTableDrawingBuilder.ColumnsPerBlock(170));
Assert.True(twoBlocks.ContentHeight > 2 * oneBlock.ContentHeight);
// Spalten bleiben gleich breit - der zweite Block verkleinert nichts.
Assert.Equal(Widths(oneBlock), Widths(twoBlocks));
Assert.All(twoBlocks.Commands.OfType<DrawRectangle>(), r => Assert.True(r.X + r.Width <= 170));
}
[Fact]
public void PointsTable_Bonusaufgabe_OhneNummerMitPlusVorDerPunktzahl()
{
var drawing = ExamPointsTableDrawingBuilder.Build(
[
new("1", 5, false, 4.5), new("", 3, true, 1),
]);
var texts = drawing.Commands.OfType<DrawStringEx>().Select(x => x.Text).ToList();
Assert.Equal(["Aufgabe", "Max. Punktzahl", "Punktzahl", "Nr. 1", "5", "4,5", "Bonus", "+3", "1"], texts);
}
[Fact]
public void PointsTable_VorlageInPunkt_SkaliertDenMillimeterEntwurf()
{
List<ExamCoverTaskColumn> columns = [new("1", 5, false, null)];
var scale = 72f / 25.4f;
var millimeters = ExamPointsTableDrawingBuilder.Build(columns, 170);
var points = ExamPointsTableDrawingBuilder.Build(columns, 170 * scale, scale);
Assert.Equal(millimeters.ContentHeight * scale, points.ContentHeight, 2);
}
[Fact]
public void Dialog_ZeigtNurDeckblattVorlagen_AusBeidenBibliotheken()
{
var letters = Store(); var worksheets = Store();
Import(letters, "brief", "Brief", null);
Import(letters, "deckblatt-a", "Deckblatt A", TemplateReportTypes.ExamCover);
Import(worksheets, "deckblatt-b", "Deckblatt B", TemplateReportTypes.ExamCover);
var vm = Build([letters, worksheets]);
Assert.Equal(["Deckblatt A", "Deckblatt B"], vm.Templates.Select(x => x.Name));
}
[Fact]
public void Dialog_VorDerKorrektur_BlankoVorausgewaehlt_NachBeginnAusgefuellt()
{
Assert.False(Build([Store()]).FillResults);
_results.Add(new ExamResult { ExamId = _exam.Id, StudentId = _anna.Id, Points = [4, 10, 0], TotalPoints = 14 });
Assert.True(Build([Store()]).FillResults);
}
[Fact]
public void Dialog_AbwesenderSchueler_IstStandardmaessigAbgewaehlt()
{
_results.Add(new ExamResult { ExamId = _exam.Id, StudentId = _ben.Id, Absent = true });
var vm = Build([Store()]);
Assert.True(vm.Students.Single(s => s.Model.Id == _anna.Id).IsIncluded);
Assert.False(vm.Students.Single(s => s.Model.Id == _ben.Id).IsIncluded);
}
[Fact]
public async Task Generate_SchreibtEinSammelPdfMitEinerSeiteJeSchueler()
{
_results.Add(new ExamResult
{ ExamId = _exam.Id, StudentId = _anna.Id, Points = [4.5, 12, 1], TotalPoints = 17.5 });
var store = Store();
Import(store, "deckblatt", "Deckblatt", TemplateReportTypes.ExamCover);
var vm = Build([store]);
var output = Path.Combine(_directory, "deckblaetter.pdf");
Assert.True(await vm.GenerateAsync(output));
using var document = UglyToad.PdfPig.PdfDocument.Open(output);
Assert.Equal(2, document.NumberOfPages);
var anna = Normalize(document.GetPage(1).Text);
var ben = Normalize(document.GetPage(2).Text);
Assert.Contains(Normalize(_anna.FullName), anna);
Assert.Contains(Normalize(_ben.FullName), ben);
Assert.Contains("AtombauundPSE", anna);
// Bonusaufgabe zählt nicht zur erreichbaren Punktzahl; erreichte Bonuspunkte schon.
Assert.Contains("Gesamtpunkte:17,5von17Punkte", anna);
Assert.Contains("Note:1", anna);
Assert.Contains("+3", anna);
// Ben ist noch nicht korrigiert: Linien zum Ausfüllen statt Punkten und Note.
Assert.Contains($"Gesamtpunkte:{ExamCoverPlaceholderBuilder.BlankPoints}von17Punkte", ben);
Assert.Contains("1 davon ohne Punkte und Note", vm.StatusMessage);
Assert.False(vm.IsGenerating);
Assert.True(vm.CanGenerate);
}
[Fact]
public async Task Generate_OhnePunkteEintragen_BleibtAuchBeiKorrigiertenBlanko()
{
_results.Add(new ExamResult
{ ExamId = _exam.Id, StudentId = _anna.Id, Points = [4.5, 12, 1], TotalPoints = 17.5 });
var store = Store();
Import(store, "deckblatt", "Deckblatt", TemplateReportTypes.ExamCover);
var vm = Build([store]);
vm.FillResults = false;
var output = Path.Combine(_directory, "blanko.pdf");
Assert.True(await vm.GenerateAsync(output));
using var document = UglyToad.PdfPig.PdfDocument.Open(output);
Assert.DoesNotContain("17,5", Normalize(document.GetPage(1).Text));
}
[Fact]
public async Task Generate_ZuVieleAufgabenFuerEineSeite_WarntImStatus()
{
_exam.Tasks = Enumerable.Range(1, 80).Select(n => new ExamTask { Nr = n, MaxPoints = 1 }).ToList();
var store = Store();
Import(store, "deckblatt", "Deckblatt", TemplateReportTypes.ExamCover);
var vm = Build([store]);
Assert.True(await vm.GenerateAsync(Path.Combine(_directory, "lang.pdf")));
Assert.Contains("passen nicht auf eine Seite", vm.StatusMessage);
}
[Theory]
[InlineData(GroupType.Course, Niveau.E, "E-Kurs")]
[InlineData(GroupType.Course, Niveau.G, "G-Kurs")]
[InlineData(GroupType.Course, Niveau.Foerder, "")]
[InlineData(GroupType.Course, null, "")]
[InlineData(GroupType.Class, Niveau.G, "")]
public void CourseLabel_NurImKursMitEOderGNiveau(GroupType type, Niveau? niveau, string expected) =>
Assert.Equal(expected, ExamCoverPlaceholderBuilder.CourseLabel(new LearningGroup { Type = type }, niveau));
[Fact]
public void Platzhalter_KursAusKlausurOderMitgliedschaft_KuerzelAusDemDialog()
{
_group.Type = GroupType.Course;
var store = Store();
Import(store, "deckblatt", "Deckblatt", TemplateReportTypes.ExamCover);
var template = store.Load(store.GetTemplates().Single());
Dictionary<string, PlaceholderValue> Values(Niveau? studentNiveau) => ExamCoverPlaceholderBuilder.Build(
_exam, _group, "Chemie", _anna, null, false, new GradingService(), template, new DateOnly(2026, 1, 1),
studentNiveau, " MON HED ");
Assert.Equal(new TextValue("E-Kurs"), Values(Niveau.E)["Exam.Course"]);
Assert.Equal(new TextValue("MON HED"), Values(null)["Teacher.Abbreviation"]);
_exam.Niveau = Niveau.G;
Assert.Equal(new TextValue("G-Kurs"), Values(Niveau.E)["Exam.Course"]);
}
[Fact]
public void Platzhalter_TitelAusDemDialog_LeerNimmtDenKlausurtitel()
{
var store = Store();
Import(store, "deckblatt", "Deckblatt", TemplateReportTypes.ExamCover);
var template = store.Load(store.GetTemplates().Single());
Dictionary<string, PlaceholderValue> Values(string? title) => ExamCoverPlaceholderBuilder.Build(
_exam, _group, "Chemie", _anna, null, false, new GradingService(), template, new DateOnly(2026, 1, 1),
title: title);
Assert.Equal(new TextValue("Klassenarbeit Nr. 1"), Values(" Klassenarbeit Nr. 1 ")["Exam.Title"]);
Assert.Equal(new TextValue("Atombau und PSE"), Values(" ")["Exam.Title"]);
Assert.Equal(new TextValue("Atombau und PSE"), Values(null)["Exam.Title"]);
}
[Fact]
public void Dialog_TitelIstMitDemKlausurtitelVorbelegt()
{
var store = Store();
Import(store, "deckblatt", "Deckblatt", TemplateReportTypes.ExamCover);
var vm = Build([store]);
Assert.Equal("Atombau und PSE", vm.CoverTitle);
vm.CoverTitle = "Klassenarbeit Nr. 1";
Assert.Equal("Atombau und PSE", _exam.Title);
}
// Der Vorlagen-Designer bietet genau diesen Katalog an - liefert die Hauptapp einen Namen
// nicht oder mit anderem Typ, scheitert die Vorlage erst beim Drucken.
[Fact]
public void Platzhalter_DeckenDenKatalogDesDesignersMitGleichenTypenAb()
{
var store = Store();
Import(store, "deckblatt", "Deckblatt", TemplateReportTypes.ExamCover);
var template = store.Load(store.GetTemplates().Single());
var values = ExamCoverPlaceholderBuilder.Build(_exam, _group, "Chemie", _anna, null, false,
new GradingService(), template, new DateOnly(2026, 1, 1));
Assert.All(ExamCoverPlaceholders.All, known =>
{
Assert.True(values.ContainsKey(known.Name), $"{known.Name} fehlt");
Assert.Equal(known.Type, values[known.Name].Type);
});
}
[Fact]
public void TeacherSettings_SpeichertDasKuerzel()
{
new TeacherSettingsService(_directory).SaveAbbreviation(" HED ");
Assert.Equal("HED", new TeacherSettingsService(_directory).LoadAbbreviation());
}
[Theory]
[InlineData(RepeatGradeRule.Better, "bessere Note")]
[InlineData(RepeatGradeRule.Repeat, "Note der Wiederholungsarbeit")]
[InlineData(RepeatGradeRule.Original, "Note der ersten Arbeit")]
public void Wiederholungsbaustein_ZeigtDieGespeicherteBewertungsregel(RepeatGradeRule rule, string expected)
{
var original = new Exam { GroupId = _group.Id, Title = "Erste Arbeit", Date = _exam.Date.AddDays(-14) };
_exam.RepeatOfExamId = original.Id; _exam.RepeatGradeRule = rule;
var template = new LoadedTemplate(new TemplateManifest(), new LayoutParser().Parse(
"PAGE 210 297 mm\nFLOWDRAWBOX 20 20 170 240 $Exam.RepeatInfo fit=content"), new Dictionary<string, byte[]>());
var drawing = GradeReportDrawingBuilder.Repeat(_exam, original, new ExamResult { Grade = "4" }, template);
var text = string.Join(" ", drawing.Commands.OfType<DrawStringEx>().Select(c => c.Text));
Assert.Contains(expected, text);
Assert.Contains("Note der ersten Arbeit: 4", text);
_exam.IsMakeUp = true;
text = string.Join(" ", GradeReportDrawingBuilder.Repeat(_exam, original, null, template).Commands.OfType<DrawStringEx>().Select(c => c.Text));
Assert.Contains("Nachschreibarbeit", text);
Assert.Contains("ersetzt die versäumte", text);
}
[Fact]
public async Task Zwischenstandsbaustein_VerlangtDurchgangUndAlleAusgewaehltenSchueler()
{
var store = Store();
var source = Path.Combine(_directory, "zwischenstand.lavorlage");
TemplatePackage.Create(source, new TemplateManifest { Id = "zwischenstand", Name = "Zwischenstand",
Metadata = new() { [TemplateMetadataKeys.ReportType] = TemplateReportTypes.ExamCover },
Placeholders = [new(ReportTextDrawing.InterimGrades, PlaceholderType.Drawing)] },
"PAGE 210 297 mm\nFLOWDRAWBOX 20 20 170 240 $Student.InterimGrades fit=content", new Dictionary<string, byte[]>());
store.Import(source);
var interims = new FakeInterimGrades();
interims.Save(new() { StudentId = _anna.Id, GroupId = _group.Id, Date = _exam.Date, Occasion = "Sprechtag", OverallValue = "2" });
var vm = new ExamCoverSheetDialogViewModel(_exam, _group, "Chemie", new FakeStudents([_anna, _ben]),
new FakeMemberships([]), _results, new GradingService(), [store], new QuestTemplateRenderer(), interims: interims);
var output = Path.Combine(_directory, "zwischenstand.pdf");
Assert.True(vm.UsesInterimGrades);
Assert.False(await vm.GenerateAsync(output));
Assert.Contains("auswählen", vm.StatusMessage);
vm.SelectedInterimRun = vm.InterimRuns.Single();
Assert.False(await vm.GenerateAsync(output));
Assert.Contains(_ben.FullName, vm.StatusMessage);
Assert.False(File.Exists(output));
vm.Students.Single(s => s.Model.Id == _ben.Id).IsIncluded = false;
Assert.True(await vm.GenerateAsync(output));
using var document = UglyToad.PdfPig.PdfDocument.Open(output);
Assert.Contains("Sprechtag", document.GetPage(1).Text);
}
private static string Normalize(string text) => text.Replace(" ", "");
private static List<float> Widths(DrawingValue drawing) =>
drawing.Commands.OfType<DrawRectangle>().Select(r => r.Width).Distinct().Order().ToList();
private ExamCoverSheetDialogViewModel Build(IReadOnlyList<TemplateStore> stores) =>
new(_exam, _group, "Chemie", new FakeStudents([_anna, _ben]), new FakeMemberships([]), _results,
new GradingService(), stores, new QuestTemplateRenderer());
private TemplateStore Store() => new(Path.Combine(_directory, $"store-{Guid.NewGuid():N}"));
private void Import(TemplateStore store, string id, string name, string? reportType)
{
var source = Path.Combine(_directory, $"{Guid.NewGuid():N}.lavorlage");
var manifest = new TemplateManifest
{
Id = id, Name = name,
Placeholders =
[
new("Student.Name", PlaceholderType.Text), new("Exam.Title", PlaceholderType.Text),
new("Exam.MaxPoints", PlaceholderType.Text), new("Result.Points", PlaceholderType.Text),
new("Result.Grade", PlaceholderType.Text),
new(ExamPointsTableDrawingBuilder.PlaceholderName, PlaceholderType.Drawing),
],
};
if (reportType is not null) manifest.Metadata[TemplateMetadataKeys.ReportType] = reportType;
TemplatePackage.Create(source, manifest, Layout, new Dictionary<string, byte[]>());
store.Import(source);
}
public void Dispose() { if (Directory.Exists(_directory)) Directory.Delete(_directory, true); }
}
@@ -61,4 +61,104 @@ public sealed class ExamDialogViewModelTests
Assert.Equal("", vm.WeekLoadHint); Assert.Equal("", vm.WeekLoadHint);
} }
[Fact]
public void BonusNachtraeglichMarkiert_BerechnetGespeichertesErgebnisNeu()
{
var exam = MakeExam(new DateOnly(2026, 5, 12));
exam.Tasks = [new ExamTask { Nr = 1, MaxPoints = 10 }, new ExamTask { Nr = 2, MaxPoints = 2 }];
exam.GradingKey = GradingService.DefaultKey1To6();
var result = new ExamResult { ExamId = exam.Id, StudentId = Guid.NewGuid(),
Points = [8, 2], TotalPoints = 10, Grade = "2" };
var results = new FakeResults();
results.Add(result);
var vm = new ExamDialogViewModel(new FakeExams([exam]), new FakeCompetencyDomains(),
new FakeGradingKeyTemplates(), new GradingService(), exam.GroupId, null, 9,
GradingSystem.Grades1To6, "Chemie", false, exam, null,
results: results);
vm.Tasks[1].IsBonus = true;
vm.SaveCommand.Execute(null);
Assert.True(exam.Tasks[1].IsBonus);
Assert.Equal(10, result.TotalPoints);
Assert.Equal("1", result.Grade);
}
// ── Förderarbeit ─────────────────────────────────────────────────────────
private static (ExamDialogViewModel Vm, Exam Original) BuildFollowUpViewModel(DateOnly originalDate)
{
var original = new Exam { GroupId = Guid.NewGuid(), Title = "Atombau", Date = originalDate };
var vm = new ExamDialogViewModel(new FakeExams([original]), new FakeCompetencyDomains(),
new FakeGradingKeyTemplates(), new GradingService(), original.GroupId, null, 9,
GradingSystem.Grades1To6, "Chemie", false, null, null);
vm.Title = "Atombau (Förder)";
vm.Tasks.Add(new ExamTaskEditItem("A1", 10, 1, [], []) { OnChanged = () => { } });
vm.Tasks[0].MaxPoints = 10;
vm.SelectedOriginalExam = original;
return (vm, original);
}
[Fact]
public void Foerderarbeit_UebernimmtDatumDerErstenArbeitUndDarfAmSelbenTagLiegen()
{
var (vm, original) = BuildFollowUpViewModel(new DateOnly(2026, 10, 14));
vm.FollowUpKindName = "Förderarbeit";
Assert.Equal("14.10.2026", vm.DateText);
vm.SaveCommand.Execute(null);
Assert.Equal("", vm.RepeatError);
Assert.NotNull(vm.Result);
Assert.True(vm.Result!.IsSupportWork);
Assert.False(vm.Result.IsMakeUp);
Assert.Equal(original.Id, vm.Result.RepeatOfExamId);
Assert.Equal(original.Date, vm.Result.Date);
}
[Fact]
public void Foerderarbeit_VorDerErstenArbeit_WirdAbgelehnt()
{
var (vm, _) = BuildFollowUpViewModel(new DateOnly(2026, 10, 14));
vm.FollowUpKindName = "Förderarbeit";
vm.DateText = "13.10.2026";
vm.SaveCommand.Execute(null);
Assert.Contains("Förderarbeit", vm.RepeatError);
Assert.Null(vm.Result);
}
[Fact]
public void Nachschreibarbeit_AmSelbenTag_BleibtAbgelehnt()
{
var (vm, _) = BuildFollowUpViewModel(new DateOnly(2026, 10, 14));
vm.FollowUpKindName = "Nachschreibarbeit";
vm.DateText = "14.10.2026";
vm.SaveCommand.Execute(null);
Assert.Contains("Nachschreibarbeit", vm.RepeatError);
Assert.Null(vm.Result);
}
[Fact]
public void Foerderarbeit_WirdBeimBearbeitenWiederhergestelltOhneDatumZuUeberschreiben()
{
var original = new Exam { GroupId = Guid.NewGuid(), Title = "Atombau", Date = new DateOnly(2026, 10, 14) };
var support = new Exam
{
GroupId = original.GroupId, Title = "Förder", Date = new DateOnly(2026, 10, 16),
RepeatOfExamId = original.Id, IsSupportWork = true,
};
var vm = new ExamDialogViewModel(new FakeExams([original, support]), new FakeCompetencyDomains(),
new FakeGradingKeyTemplates(), new GradingService(), original.GroupId, null, 9,
GradingSystem.Grades1To6, "Chemie", false, support, null);
Assert.True(vm.IsSupportWork);
Assert.Equal("16.10.2026", vm.DateText);
Assert.False(vm.ShowRepeatRule);
}
} }
@@ -1,3 +1,4 @@
using LehrerApp.Core.Interfaces;
using LehrerApp.Core.Models; using LehrerApp.Core.Models;
using LehrerApp.Core.Services; using LehrerApp.Core.Services;
using LehrerApp.Desktop.ViewModels.Groups; using LehrerApp.Desktop.ViewModels.Groups;
@@ -62,4 +63,166 @@ public sealed class ExamGradingDialogViewModelTests
Assert.True(vm.Rows[0].Absent); Assert.True(vm.Rows[0].Absent);
} }
private static ExamGradingDialogViewModel CreateGrid(int studentCount, params ExamTask[] tasks)
{
var group = new LearningGroup { Name = "Q1 Chemie" };
var students = Enumerable.Range(0, studentCount)
.Select(i => new Student { FirstName = "S", LastName = $"N{i}" }).ToList();
var memberships = new FakeMemberships(
students.Select(s => new GroupMembership { GroupId = group.Id, StudentId = s.Id }).ToList());
var exam = new Exam
{
GroupId = group.Id, Title = "Klausur 1", Tasks = [.. tasks],
GradingKey = GradingService.DefaultKey1To6(),
};
return new ExamGradingDialogViewModel(new FakeResults(), new FakeStudents(students), memberships,
new GradingService(), exam, group.Id);
}
private static ExamTask[] ThreeTasks() =>
[
new() { Nr = 1, MaxPoints = 5 },
new() { Nr = 2, MaxPoints = 5 },
new() { Nr = 3, MaxPoints = 5 },
];
[Fact]
public void Enter_SchülerFürSchüler_LäuftDieZeileEntlangUndDannInDieNächste()
{
var vm = CreateGrid(2, ThreeTasks());
Assert.Equal((0, 1), vm.NextCell(0, 0, GradingMove.Next));
Assert.Equal((1, 0), vm.NextCell(0, 2, GradingMove.Next));
Assert.Null(vm.NextCell(1, 2, GradingMove.Next));
Assert.Equal((0, 2), vm.NextCell(1, 0, GradingMove.Previous));
}
[Fact]
public void Enter_AufgabeFürAufgabe_LäuftDieSpalteHinunterUndDannZurNächstenAufgabe()
{
var vm = CreateGrid(2, ThreeTasks());
vm.EntryOrderName = vm.EntryOrderOptions[1];
Assert.Equal((1, 0), vm.NextCell(0, 0, GradingMove.Next));
Assert.Equal((0, 1), vm.NextCell(1, 0, GradingMove.Next));
Assert.Equal((1, 0), vm.NextCell(0, 1, GradingMove.Previous));
}
[Fact]
public void Navigation_ÜberspringtAbwesendeUndAndereFassung()
{
var vm = CreateGrid(3,
new ExamTask { Nr = 1, MaxPoints = 5 },
new ExamTask { Nr = 2, MaxPoints = 5, Variant = ExamVariant.B },
new ExamTask { Nr = 3, MaxPoints = 5 });
vm.Rows[1].Absent = true;
Assert.Equal((0, 2), vm.NextCell(0, 0, GradingMove.Next));
Assert.Equal((0, 2), vm.NextCell(0, 0, GradingMove.Right));
Assert.Equal((2, 0), vm.NextCell(0, 0, GradingMove.Down));
Assert.Null(vm.NextCell(0, 0, GradingMove.Up));
}
[Fact]
public void Spaltenüberschriften_ZählenBonusaufgabenNichtMit()
{
var vm = CreateGrid(1,
new ExamTask { Nr = 1, MaxPoints = 5 },
new ExamTask { Nr = 2, MaxPoints = 2, IsBonus = true },
new ExamTask { Nr = 3, MaxPoints = 5, Title = "Redox" });
Assert.Equal(["Aufgabe 1", "★ Bonus", "2. Redox"], vm.TaskHeaders);
}
private sealed class RecordingResults : FakeResults, IExamResultRepository
{
public List<ExamResult> Saved { get; } = [];
public new void Save(ExamResult result) => Saved.Add(result);
}
private static (ExamGradingDialogViewModel Vm, RecordingResults Results) CreateRecordingGrid(
ExamResult? existing = null)
{
var group = new LearningGroup { Name = "Q1 Chemie" };
var student = new Student { FirstName = "Ben", LastName = "Cordes" };
var exam = new Exam
{
GroupId = group.Id, Title = "Klausur 1", Tasks = [.. ThreeTasks()],
GradingKey = GradingService.DefaultKey1To6(),
};
var results = new RecordingResults();
if (existing is not null)
{
existing.ExamId = exam.Id; existing.StudentId = student.Id;
results.Add(existing);
}
var vm = new ExamGradingDialogViewModel(results, new FakeStudents([student]),
new FakeMemberships([new GroupMembership { GroupId = group.Id, StudentId = student.Id }]),
new GradingService(), exam, group.Id);
return (vm, results);
}
[Fact]
public void NurAngefahreneZelle_LegtKeinErgebnisMitNullPunktenAn()
{
var (vm, results) = CreateRecordingGrid();
// Fokus in die Zelle und wieder heraus ohne Eingabe: die View meldet das als TrySetValue(null).
vm.Rows[0].Cells[0].TrySetValue(null);
vm.Rows[0].Cells[1].TrySetValue(null);
Assert.Empty(results.Saved);
Assert.Equal("", vm.Rows[0].GradeDisplay);
}
[Fact]
public void ErsterEingetragenerWert_LegtDasErgebnisAn()
{
var (vm, results) = CreateRecordingGrid();
vm.Rows[0].Cells[0].TrySetValue(4);
var saved = Assert.Single(results.Saved);
Assert.Equal([4, 0, 0], saved.Points);
Assert.Equal(4, saved.TotalPoints);
}
[Fact]
public void UnveraenderterWert_SpeichertNichtErneut()
{
var (vm, results) = CreateRecordingGrid();
vm.Rows[0].Cells[0].TrySetValue(4);
vm.Rows[0].Cells[0].TrySetValue(4);
Assert.Single(results.Saved);
}
[Fact]
public void LeereZeileMitBestehendemErgebnis_WirdAlsUnkorrigiertGespeichertNichtAlsNull()
{
var (vm, results) = CreateRecordingGrid(
new ExamResult { Points = [4], TotalPoints = 4, Grade = "4" });
vm.Rows[0].Cells[0].TrySetValue(null);
var saved = Assert.Single(results.Saved);
Assert.Empty(saved.Points);
Assert.Null(saved.Grade);
Assert.False(ExamCoverSheetService.IsCorrected(saved));
}
[Fact]
public void AbwesendheitOhnePunkte_WirdOhnePunkteUndNoteGespeichert()
{
var (vm, results) = CreateRecordingGrid();
vm.Rows[0].Absent = true;
var saved = Assert.Single(results.Saved);
Assert.True(saved.Absent);
Assert.Empty(saved.Points);
Assert.Null(saved.Grade);
}
} }
@@ -0,0 +1,94 @@
using LehrerApp.Core.Models;
using LehrerApp.Core.Services;
using LehrerApp.Desktop.ViewModels.Groups;
using Xunit;
namespace LehrerApp.Desktop.Tests;
/// Deckt 1.7.1 (datenschutzkonforme Einzelansicht) ab.
public sealed class ExamRevealDialogViewModelTests
{
private static (ExamRevealDialogViewModel Vm, Student Anna, Student Ben) Build()
{
var group = new LearningGroup { Name = "Q1 Chemie" };
var anna = new Student { FirstName = "Anna", LastName = "Bauer" };
var ben = new Student { FirstName = "Ben", LastName = "Cordes" };
var withoutResult = new Student { FirstName = "Cara", LastName = "Diehl" };
var exam = new Exam
{
GroupId = group.Id,
Title = "Klausur 1",
Tasks =
[
new ExamTask { Nr = 1, MaxPoints = 10 },
new ExamTask { Nr = 2, MaxPoints = 10, Variant = ExamVariant.A },
new ExamTask { Nr = 3, MaxPoints = 20, Variant = ExamVariant.B },
],
GradingKey = GradingService.DefaultKey1To6(),
};
var results = new FakeResults();
// Bewusst in "falscher" Reihenfolge eingefügt — die Liste sortiert nach Nachname.
results.Add(new ExamResult { ExamId = exam.Id, StudentId = ben.Id, Absent = true });
results.Add(new ExamResult
{
ExamId = exam.Id, StudentId = anna.Id, Points = [7.5, 9, 0], TotalPoints = 16.5,
Grade = "2", Variant = ExamVariant.A,
});
var vm = new ExamRevealDialogViewModel(results, new FakeStudents([ben, withoutResult, anna]),
new GradingService(), exam);
return (vm, anna, ben);
}
[Fact]
public void Start_ZeigtErstenSchülerZugedeckt_UndNurSchülerMitErgebnis()
{
var (vm, _, _) = Build();
Assert.Equal(["Bauer, Anna", "Cordes, Ben"], vm.Students.Select(s => s.ListName));
Assert.Equal("Anna Bauer", vm.SelectedStudent!.DisplayName);
Assert.False(vm.IsRevealed);
Assert.Equal("1 / 2", vm.PositionLabel);
}
[Fact]
public void Ergebnis_ZeigtNotePunkteUndNurAufgabenDerGeschriebenenFassung()
{
var (vm, _, _) = Build();
var anna = vm.SelectedStudent!;
Assert.Equal("2", anna.GradeDisplay);
Assert.Equal("16,5 von 20 Punkten", anna.PointsDisplay);
Assert.Equal(
[new ExamRevealTaskRow("Aufgabe 1", "7,5", "10"), new ExamRevealTaskRow("Aufgabe 2", "9", "10")],
anna.Tasks);
}
[Fact]
public void Schülerwechsel_DecktWiederZu()
{
var (vm, _, _) = Build();
vm.RevealCommand.Execute(null);
Assert.True(vm.IsRevealed);
vm.NextCommand.Execute(null);
Assert.False(vm.IsRevealed);
Assert.Equal("Ben Cordes", vm.SelectedStudent!.DisplayName);
Assert.True(vm.SelectedStudent.Absent);
Assert.Empty(vm.SelectedStudent.Tasks);
Assert.False(vm.NextCommand.CanExecute(null));
Assert.True(vm.PreviousCommand.CanExecute(null));
}
[Fact]
public void Zudecken_VerstecktErgebnisWieder()
{
var (vm, _, _) = Build();
vm.RevealCommand.Execute(null);
vm.HideCommand.Execute(null);
Assert.False(vm.IsRevealed);
}
}
@@ -0,0 +1,34 @@
using LehrerApp.Core.Models;
using LehrerApp.Core.Services;
using LehrerApp.Desktop.ViewModels.Groups;
using Xunit;
namespace LehrerApp.Desktop.Tests;
public class ExamVariantScoringTests
{
[Fact]
public void Fassungswechsel_BerechnetPunkteUndNoteNeu()
{
var tasks = new List<ExamTask>
{
new() { Nr = 1, MaxPoints = 10 },
new() { Nr = 2, MaxPoints = 5, Variant = ExamVariant.A },
new() { Nr = 3, MaxPoints = 8, Variant = ExamVariant.B },
new() { Nr = 4, MaxPoints = 2, IsBonus = true },
};
var existing = new ExamResult { Points = [8, 5, 8, 2] };
var row = new ExamResultRow(Guid.NewGuid(), "Test", tasks, existing,
GradingService.DefaultKey1To6(), 15, new GradingService());
Assert.Equal(15, row.TotalPoints);
Assert.False(row.Cells[2].IsApplicable);
row.VariantName = "B";
Assert.Equal(18, row.TotalPoints);
Assert.False(row.Cells[1].IsApplicable);
Assert.True(row.Cells[2].IsApplicable);
Assert.Equal(ExamVariant.B, row.ToModel(Guid.NewGuid()).Variant);
}
}
+65 -3
View File
@@ -30,7 +30,8 @@ public static class TestSupport
/// solange AiSettingsService.IsLoggedIn false ist. /// solange AiSettingsService.IsLoggedIn false ist.
public static AiPlanningService BuildAiPlanningService() => new( public static AiPlanningService BuildAiPlanningService() => new(
new HttpClient(), new FakeLessons(), new FakeGroups([]), new FakeSubjects([]), new HttpClient(), new FakeLessons(), new FakeGroups([]), new FakeSubjects([]),
new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions(), new FakeAlternativeLessonPaths([])); new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions(), new FakeAlternativeLessonPaths([]),
BuildAppLogger());
/// Analog zu <see cref="BuildAiSettingsService"/>, eigenes Temp-Verzeichnis je Aufruf. /// Analog zu <see cref="BuildAiSettingsService"/>, eigenes Temp-Verzeichnis je Aufruf.
public static McpSettingsService BuildMcpSettingsService() public static McpSettingsService BuildMcpSettingsService()
@@ -178,6 +179,22 @@ public class FakeSeatingPlans(List<SeatingPlan>? initial = null) : ISeatingPlanR
public void Restore(Guid trashId) { } public void Restore(Guid trashId) { }
} }
public class FakeStudentGroupPlans : IStudentGroupPlanRepository
{
private readonly List<StudentGroupPlan> _plans = [];
public StudentGroupPlan? GetById(Guid id) => _plans.FirstOrDefault(p => p.Id == id);
public List<StudentGroupPlan> GetByGroup(Guid groupId) =>
_plans.Where(p => p.GroupId == groupId).ToList();
public List<StudentGroupPlan> GetByStudent(Guid studentId) =>
_plans.Where(p => p.Groups.Any(g => g.StudentIds.Contains(studentId))).ToList();
public void Save(StudentGroupPlan plan)
{
_plans.RemoveAll(p => p.Id == plan.Id);
_plans.Add(plan);
}
public void Delete(Guid id) => _plans.RemoveAll(p => p.Id == id);
}
public class FakeTrash(List<TrashedItem>? initial = null) : ITrashRepository public class FakeTrash(List<TrashedItem>? initial = null) : ITrashRepository
{ {
private readonly List<TrashedItem> _all = initial ?? []; private readonly List<TrashedItem> _all = initial ?? [];
@@ -239,6 +256,14 @@ public class FakeAspects : IParticipationAspectRepository
public void Delete(Guid id) => _all.RemoveAll(a => a.Id == id); public void Delete(Guid id) => _all.RemoveAll(a => a.Id == id);
} }
public class FakeSections(List<ParticipationSection>? initial = null) : IParticipationSectionRepository
{
private readonly List<ParticipationSection> _all = initial ?? [];
public List<ParticipationSection> GetByGroup(Guid groupId) => _all.Where(s => s.GroupId == groupId).ToList();
public void Save(ParticipationSection section) { _all.RemoveAll(s => s.Id == section.Id); _all.Add(section); }
public void Delete(Guid id) => _all.RemoveAll(s => s.Id == id);
}
public class FakeGrades : IGradeRepository public class FakeGrades : IGradeRepository
{ {
private readonly List<Grade> _all = []; private readonly List<Grade> _all = [];
@@ -319,15 +344,41 @@ public class FakeDocumentation : IDocumentationRepository
private readonly List<Documentation> _all = []; private readonly List<Documentation> _all = [];
public void Add(Documentation d) => _all.Add(d); public void Add(Documentation d) => _all.Add(d);
public List<Documentation> GetByStudent(Guid studentId) => public List<Documentation> GetByStudent(Guid studentId) =>
_all.Where(d => d.StudentId == studentId && !d.IsDeleted).ToList(); _all.Where(d => d.Concerns(studentId) && !d.IsDeleted).ToList();
public List<Documentation> GetByStudentAndType(Guid studentId, DocumentationType type) => public List<Documentation> GetByStudentAndType(Guid studentId, DocumentationType type) =>
_all.Where(d => d.StudentId == studentId && d.Type == type && !d.IsDeleted).ToList(); _all.Where(d => d.Concerns(studentId) && d.Type == type && !d.IsDeleted).ToList();
public List<Documentation> GetAll() => _all.Where(d => !d.IsDeleted).ToList(); public List<Documentation> GetAll() => _all.Where(d => !d.IsDeleted).ToList();
public void Save(Documentation doc) { _all.RemoveAll(d => d.Id == doc.Id); _all.Add(doc); } public void Save(Documentation doc) { _all.RemoveAll(d => d.Id == doc.Id); _all.Add(doc); }
public void Delete(Guid id) { var d = _all.FirstOrDefault(x => x.Id == id); if (d is not null) d.IsDeleted = true; } public void Delete(Guid id) { var d = _all.FirstOrDefault(x => x.Id == id); if (d is not null) d.IsDeleted = true; }
public void HardDelete(Guid id) => _all.RemoveAll(d => d.Id == id); public void HardDelete(Guid id) => _all.RemoveAll(d => d.Id == id);
} }
public class FakeVorgangRepository : IVorgangRepository
{
private readonly List<Vorgang> _all = [];
public void Add(Vorgang v) => _all.Add(v);
public List<Vorgang> GetAll() => _all.Where(v => !v.IsDeleted).ToList();
public List<Vorgang> GetByStudent(Guid studentId) =>
_all.Where(v => !v.IsDeleted && v.StudentIds.Contains(studentId)).ToList();
public Vorgang? GetById(Guid id) => _all.FirstOrDefault(v => v.Id == id && !v.IsDeleted);
public void Save(Vorgang vorgang) { _all.RemoveAll(v => v.Id == vorgang.Id); _all.Add(vorgang); }
public void Delete(Guid id) { var v = _all.FirstOrDefault(x => x.Id == id); if (v is not null) v.IsDeleted = true; }
}
public class FakeDashboardWarningSnoozeRepository : IDashboardWarningSnoozeRepository
{
private readonly List<DashboardWarningSnooze> _all = [];
public DashboardWarningSnooze? Get(Guid studentId, string warningTag) =>
_all.FirstOrDefault(s => s.StudentId == studentId && s.WarningTag == warningTag);
public List<DashboardWarningSnooze> GetAll() => _all.ToList();
public void Save(DashboardWarningSnooze snooze)
{
snooze.Id = DashboardWarningSnooze.IdFor(snooze.StudentId, snooze.WarningTag);
_all.RemoveAll(s => s.Id == snooze.Id);
_all.Add(snooze);
}
}
public class FakeAttachmentStorage : IAttachmentStorage public class FakeAttachmentStorage : IAttachmentStorage
{ {
private readonly Dictionary<string, byte[]> _blobs = []; private readonly Dictionary<string, byte[]> _blobs = [];
@@ -630,6 +681,17 @@ public class FakeTimeEntries : ITimeEntryRepository
public void Restore(Guid trashId) { } // siehe FakeSeatingPlans.Restore public void Restore(Guid trashId) { } // siehe FakeSeatingPlans.Restore
} }
public class FakeInterimGrades : IInterimGradeRepository
{
private readonly List<InterimGrade> _all = [];
public List<InterimGrade> All => _all;
public List<InterimGrade> GetByGroup(Guid groupId) => _all.Where(g => g.GroupId == groupId).ToList();
public List<InterimGrade> GetByStudentAndGroup(Guid studentId, Guid groupId) =>
_all.Where(g => g.StudentId == studentId && g.GroupId == groupId).ToList();
public void Save(InterimGrade grade) { _all.RemoveAll(g => g.Id == grade.Id); _all.Add(grade); }
public void Delete(Guid id) => _all.RemoveAll(g => g.Id == id);
}
public class FakeReportGrades : IReportGradeRepository public class FakeReportGrades : IReportGradeRepository
{ {
private readonly List<ReportGrade> _all = []; private readonly List<ReportGrade> _all = [];
@@ -22,11 +22,12 @@ public sealed class GroupDetailViewModelTests
new FakeDocumentation(), tasks, groups, new AttendanceBalanceService(), new GradingService(), new SchoolYearService()), new FakeDocumentation(), tasks, groups, new AttendanceBalanceService(), new GradingService(), new SchoolYearService()),
new ParticipationTabViewModel(new FakeSessions([]), new FakeEntries(), new FakeAspects(), new ParticipationTabViewModel(new FakeSessions([]), new FakeEntries(), new FakeAspects(),
students, memberships, groups, new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions()), students, memberships, groups, new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions()),
new GradeOverviewTabViewModel(grades, exams, new FakeResults(), students, memberships, new GradingService()), new GradeOverviewTabViewModel(grades, exams, new FakeResults(), students, memberships, new FakeInterimGrades(), new GradingService()),
new PlanningTabViewModel(new FakeUnits(), new FakeLessons(), groups, subjects, new PlanningTabViewModel(new FakeUnits(), new FakeLessons(), groups, subjects,
new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions(), TestSupport.BuildAiSettingsService(), new FakeSessions([])), new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions(), TestSupport.BuildAiSettingsService(), new FakeSessions([])),
new CompetencyOverviewTabViewModel(new FakeUnits(), exams, new FakeResults(), new CompetencyOverviewTabViewModel(new FakeUnits(), exams, new FakeResults(),
new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions(), students, new CompetencyAnalysisService()), new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions(), students,
new FakeSessions([]), new FakeEntries(), new FakeAspects(), new CompetencyAnalysisService()),
new SeatingPlanTabViewModel(new FakeSeatingPlans(), students, memberships, new SeatingPlanTabViewModel(new FakeSeatingPlans(), students, memberships,
new FakeSessions([]), new FakeEntries(), new FakeAspects()), new FakeSessions([]), new FakeEntries(), new FakeAspects()),
new GroupDocumentationTabViewModel(new FakeDocumentation(), students, groups)); new GroupDocumentationTabViewModel(new FakeDocumentation(), students, groups));
@@ -254,7 +254,8 @@ public sealed class HazardAssessmentWizardViewModelTests
aiSettings.SetEnabled(true); aiSettings.SetEnabled(true);
aiSettings.SetCredentialsAndToken("sebastian", "token-abc"); aiSettings.SetCredentialsAndToken("sebastian", "token-abc");
var ai = new AiPlanningService(new HttpClient(), new FakeLessons(), new FakeGroups([]), var ai = new AiPlanningService(new HttpClient(), new FakeLessons(), new FakeGroups([]),
new FakeSubjects([]), new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions(), new FakeAlternativeLessonPaths([])); new FakeSubjects([]), new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions(), new FakeAlternativeLessonPaths([]),
TestSupport.BuildAppLogger());
var unit = new Unit { Title = "Redoxreaktionen" }; var unit = new Unit { Title = "Redoxreaktionen" };
var lesson = new Lesson { Topic = "Natrium in Wasser" }; var lesson = new Lesson { Topic = "Natrium in Wasser" };
@@ -0,0 +1,40 @@
using LehrerApp.Core.Models;
using LehrerApp.Desktop.Services;
using Xunit;
namespace LehrerApp.Desktop.Tests;
public sealed class HomeworkOverdueServiceTests
{
[Fact]
public void Advance_Nach14Kalendertagen_NurOffeneNachreichungen()
{
var today = new DateOnly(2026, 9, 25);
var group = new LearningGroup { IsActive = true };
var archived = new LearningGroup { IsActive = false };
var dueSession = new ParticipationSession { GroupId = group.Id, Date = today.AddDays(-14) };
var recentSession = new ParticipationSession { GroupId = group.Id, Date = today.AddDays(-13) };
var archivedSession = new ParticipationSession { GroupId = archived.Id, Date = today.AddDays(-30) };
var open = new ParticipationEntry { SessionId = dueSession.Id, Homework = HomeworkStatus.MissingOpen };
var legacy = new ParticipationEntry { SessionId = dueSession.Id, HomeworkMissing = true };
var submitted = new ParticipationEntry { SessionId = dueSession.Id, Homework = HomeworkStatus.SubmittedLate };
var partial = new ParticipationEntry { SessionId = dueSession.Id, Homework = HomeworkStatus.PartiallyCompleted };
var recent = new ParticipationEntry { SessionId = recentSession.Id, Homework = HomeworkStatus.MissingOpen };
var oldArchived = new ParticipationEntry { SessionId = archivedSession.Id, Homework = HomeworkStatus.MissingOpen };
var entries = new FakeEntries();
foreach (var entry in new[] { open, legacy, submitted, partial, recent, oldArchived }) entries.Add(entry);
var service = new HomeworkOverdueService(new FakeGroups([group, archived]),
new FakeSessions([dueSession, recentSession, archivedSession]), entries);
Assert.Equal(2, service.Advance(today));
Assert.Equal(HomeworkStatus.MissingOverdue, open.Homework);
Assert.Equal(HomeworkStatus.MissingOverdue, legacy.Homework);
Assert.True(open.HomeworkMissing);
Assert.True(legacy.HomeworkMissing);
Assert.Equal(HomeworkStatus.SubmittedLate, submitted.Homework);
Assert.Equal(HomeworkStatus.PartiallyCompleted, partial.Homework);
Assert.Equal(HomeworkStatus.MissingOpen, recent.Homework);
Assert.Equal(HomeworkStatus.MissingOpen, oldArchived.Homework);
Assert.Equal(0, service.Advance(today));
}
}
@@ -9,6 +9,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" /> <PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="PdfPig" />
<PackageReference Include="xunit" /> <PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio"> <PackageReference Include="xunit.runner.visualstudio">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
@@ -8,6 +8,43 @@ namespace LehrerApp.Desktop.Tests;
public sealed class LessonDialogViewModelTests public sealed class LessonDialogViewModelTests
{ {
[Fact]
public void Save_PersistsParentBeforeLesson()
{
var lessons = new FakeLessons();
var unitId = Guid.NewGuid();
var vm = new LessonDialogViewModel(lessons, new FakeShorthandCodes([]),
new FakeAlternativeLessonPaths([]), new FakeTimetableSlots(), NewPeriodSchedule(),
new FakeAttachmentStorage(), unitId, Guid.NewGuid(), "10c", "Chemie", [], [], null);
vm.Topic = "Test";
vm.DateText = "09.11.2026";
var called = false;
vm.BeforeSave = () =>
{
Assert.Empty(lessons.GetByUnit(unitId));
called = true;
};
vm.SaveCommand.Execute(null);
Assert.True(called);
Assert.Equal(unitId, Assert.Single(lessons.GetByUnit(unitId)).UnitId);
}
[Fact]
public void Save_InvalidInputDoesNotPersistParent()
{
var vm = BuildVm(Guid.NewGuid(), Guid.NewGuid());
var called = false;
vm.BeforeSave = () => called = true;
vm.DateText = "invalid";
vm.SaveCommand.Execute(null);
Assert.False(called);
Assert.Null(vm.Result);
}
private static PeriodScheduleService NewPeriodSchedule() private static PeriodScheduleService NewPeriodSchedule()
{ {
var tempPath = System.IO.Path.Combine( var tempPath = System.IO.Path.Combine(
+92 -2
View File
@@ -17,7 +17,8 @@ public sealed class McpToolsTests
{ {
"download_lesson_attachment", "get_competency_catalog", "get_competency_plan_versions", "download_lesson_attachment", "get_competency_catalog", "get_competency_plan_versions",
"get_exams", "get_grades", "get_exams", "get_grades",
"get_groups", "get_lesson_plans", "get_named_untis_absence_pattern", "get_schedule", "get_groups", "get_lesson_plans", "get_named_untis_absence_pattern",
"get_participation_sessions", "get_schedule",
"get_students", "get_subjects", "get_time_entries", "get_untis_absence_rows", "get_students", "get_subjects", "get_time_entries", "get_untis_absence_rows",
"get_untis_hub_status", "list_letter_templates", "render_letter", "get_untis_hub_status", "list_letter_templates", "render_letter",
}, },
@@ -31,10 +32,12 @@ public sealed class McpToolsTests
new[] new[]
{ {
"add_competency_item", "add_lesson_attachment", "add_lesson_competency", "add_lesson_phase", "add_competency_item", "add_lesson_attachment", "add_lesson_competency", "add_lesson_phase",
"add_session_competency",
"apply_untis_absence_status", "create_competency_domain", "create_competency_plan_version", "apply_untis_absence_status", "create_competency_domain", "create_competency_plan_version",
"create_grade_entry", "create_lesson", "create_grade_entry", "create_lesson",
"create_subject", "create_time_entry", "create_unit", "move_lesson", "remove_competency_item", "create_subject", "create_time_entry", "create_unit", "move_lesson", "remove_competency_item",
"remove_lesson_competency", "remove_lesson_phase", "update_competency_domain", "remove_lesson_competency", "remove_lesson_phase", "remove_session_competency",
"update_competency_domain",
"update_competency_item", "update_competency_plan_version", "update_group_competency_version", "update_competency_item", "update_competency_plan_version", "update_group_competency_version",
"update_lesson", "update_lesson_phase", "update_student_group_assignment", "update_lesson", "update_lesson_phase", "update_student_group_assignment",
"update_subject", "update_unit", "update_subject", "update_unit",
@@ -1026,4 +1029,91 @@ public sealed class McpToolsTests
Assert.False(result.Applied); Assert.False(result.Applied);
Assert.Equal(0, confirmation.CallCount); Assert.Equal(0, confirmation.CallCount);
} }
// ── ParticipationTools ───────────────────────────────────────────────────────────────────
[Fact]
public void GetParticipationSessions_LiefertDatumKommentarUndKompetenzenDerGruppe()
{
var groupId = Guid.NewGuid();
var item = new CompetencyItem { Code = "K1", Description = "Kompetenz" };
var session = new ParticipationSession
{
GroupId = groupId, Date = new DateOnly(2026, 1, 12), Comment = "Sitzplan",
Competencies = [new CompetencyReference { ItemId = item.Id, Code = item.Code, Description = item.Description }],
};
var sessions = new FakeSessions([session]);
var tool = new ParticipationTools(sessions, new FakeCompetencyDomains(), new FakeMcpConfirmation());
var result = Assert.Single(tool.GetParticipationSessions(groupId));
Assert.Equal(session.Id, result.Id);
Assert.Equal("Sitzplan", result.Comment);
var competency = Assert.Single(result.Competencies);
Assert.Equal(item.Id, competency.ItemId);
Assert.Equal("K1", competency.Code);
}
[Fact]
public async Task AddSessionCompetency_NutzerBestaetigt_OrdnetKompetenzZu()
{
var session = new ParticipationSession { Date = new DateOnly(2026, 1, 12) };
var sessions = new FakeSessions([session]);
var domains = new FakeCompetencyDomains();
var item = new CompetencyItem { Code = "K1", Description = "Kompetenz" };
domains.Add(new CompetencyDomain { Name = "Bereich", Items = [item] });
var tool = new ParticipationTools(sessions, domains, new FakeMcpConfirmation());
var result = await tool.AddSessionCompetency(session.Id, item.Id);
Assert.True(result.Applied);
var stored = Assert.Single(sessions.GetById(session.Id)!.Competencies);
Assert.Equal(item.Id, stored.ItemId);
}
[Fact]
public async Task AddSessionCompetency_UnbekannteId_LiefertFehlerOhneNachfrage()
{
var session = new ParticipationSession { Date = new DateOnly(2026, 1, 12) };
var sessions = new FakeSessions([session]);
var confirmation = new FakeMcpConfirmation();
var tool = new ParticipationTools(sessions, new FakeCompetencyDomains(), confirmation);
var result = await tool.AddSessionCompetency(session.Id, Guid.NewGuid());
Assert.False(result.Applied);
Assert.Equal(0, confirmation.CallCount);
}
[Fact]
public async Task RemoveSessionCompetency_NutzerBestaetigt_EntferntKompetenz()
{
var item = new CompetencyItem { Code = "K1", Description = "Kompetenz" };
var session = new ParticipationSession
{
Date = new DateOnly(2026, 1, 12),
Competencies = [new CompetencyReference { ItemId = item.Id, Code = item.Code, Description = item.Description }],
};
var sessions = new FakeSessions([session]);
var tool = new ParticipationTools(sessions, new FakeCompetencyDomains(), new FakeMcpConfirmation());
var result = await tool.RemoveSessionCompetency(session.Id, item.Id);
Assert.True(result.Applied);
Assert.Empty(sessions.GetById(session.Id)!.Competencies);
}
[Fact]
public async Task RemoveSessionCompetency_NichtZugeordnet_LiefertFehlerOhneNachfrage()
{
var session = new ParticipationSession { Date = new DateOnly(2026, 1, 12) };
var sessions = new FakeSessions([session]);
var confirmation = new FakeMcpConfirmation();
var tool = new ParticipationTools(sessions, new FakeCompetencyDomains(), confirmation);
var result = await tool.RemoveSessionCompetency(session.Id, Guid.NewGuid());
Assert.False(result.Applied);
Assert.Equal(0, confirmation.CallCount);
}
} }
@@ -0,0 +1,98 @@
using LehrerApp.Core.Models;
using LehrerApp.Desktop.ViewModels.Groups;
using Xunit;
namespace LehrerApp.Desktop.Tests;
/// Nutzer-Feedback: Kompetenzen je Sitzung von Hand zu bewerten ist zu aufwendig - eine Schätzung
/// aus dem allgemeinen Mitarbeit-Durchschnitt ersetzt die manuelle Erfassung im Regelfall.
public sealed class ParticipationCompetencyEstimateTests
{
private static readonly AspectColumnDef Quality = new(new ParticipationAspect { Key = "quality", ValueType = AspectValueType.Scale5 });
private static readonly AspectColumnDef Quantity = new(new ParticipationAspect { Key = "quantity", ValueType = AspectValueType.Scale5 });
private static readonly AspectColumnDef Points = new(new ParticipationAspect { Key = "points", ValueType = AspectValueType.Points, MaxPoints = 4 });
[Fact]
public void Estimate_OhneBewertungen_LiefertNull()
{
var estimate = ParticipationCompetencyEstimate.Estimate([], [Quality], null);
Assert.Null(estimate);
}
[Fact]
public void Estimate_MittelwertMehrererAspekte_RundetAufNaechstenSchritt()
{
var ratings = new List<AspectRating>
{
new() { Key = "quality", Value = 1 },
new() { Key = "quantity", Value = 2 },
};
var estimate = ParticipationCompetencyEstimate.Estimate(ratings, [Quality, Quantity], null);
Assert.Equal(2, estimate); // Mittelwert 1.5 -> AwayFromZero gerundet auf 2
}
[Fact]
public void Estimate_Spitzentag_HebtDieSchaetzungAn()
{
var ratings = new List<AspectRating> { new() { Key = "quality", Value = 0 } };
var estimate = ParticipationCompetencyEstimate.Estimate(ratings, [Quality], DayHighlightKind.Standout);
Assert.Equal(1, estimate);
}
[Fact]
public void Estimate_Schlaftag_SenktDieSchaetzung()
{
var ratings = new List<AspectRating> { new() { Key = "quality", Value = 0 } };
var estimate = ParticipationCompetencyEstimate.Estimate(ratings, [Quality], DayHighlightKind.Sleepy);
Assert.Equal(-1, estimate);
}
[Fact]
public void Estimate_SchlechterTag_SenktDieSchaetzungGleichWieSchlaftag()
{
var ratings = new List<AspectRating> { new() { Key = "quality", Value = 0 } };
var estimate = ParticipationCompetencyEstimate.Estimate(ratings, [Quality], DayHighlightKind.Rough);
Assert.Equal(-1, estimate);
}
[Fact]
public void Estimate_KapptAufDenGueltigenBereich()
{
var ratings = new List<AspectRating> { new() { Key = "quality", Value = 2 } };
var estimate = ParticipationCompetencyEstimate.Estimate(ratings, [Quality], DayHighlightKind.Standout);
Assert.Equal(2, estimate); // 2 + 1 würde 3 ergeben, wird auf 2 gekappt
}
[Fact]
public void Estimate_BeruecksichtigtNurBewerteteAspekte()
{
// "quantity" wurde nie bewertet - fließt nicht als 0 in den Mittelwert ein.
var ratings = new List<AspectRating> { new() { Key = "quality", Value = 2 } };
var estimate = ParticipationCompetencyEstimate.Estimate(ratings, [Quality, Quantity], null);
Assert.Equal(2, estimate);
}
[Fact]
public void Estimate_PunkteAspekt_WirdAufDieMinus2Bis2AchseNormiert()
{
// 4 von 4 Punkten -> oberes Ende der Achse (+2).
var ratings = new List<AspectRating> { new() { Key = "points", Value = 4 } };
var estimate = ParticipationCompetencyEstimate.Estimate(ratings, [Points], null);
Assert.Equal(2, estimate);
}
}
@@ -87,6 +87,49 @@ public sealed class ParticipationSessionEditingTests
Assert.Null(sessions.GetById(session.Id)); Assert.Null(sessions.GetById(session.Id));
} }
[Fact]
public void Sitzung_MitBewertetenAspektenAberOhneKompetenzbewertung_ZeigtGeschaetztenWert()
{
var subjectId = Guid.NewGuid();
var group = new LearningGroup { Name = "8a", SchoolYear = "2026/27", SubjectId = subjectId, GradeLevel = 8 };
var student = new Student { FirstName = "Ada", LastName = "Lovelace" };
var item = new CompetencyItem { Code = "K1", Description = "Kompetenz" };
var session = new ParticipationSession
{
GroupId = group.Id, Date = new DateOnly(2026, 8, 19),
Competencies = [new CompetencyReference { ItemId = item.Id, Code = item.Code, Description = item.Description }],
};
var sessions = new FakeSessions([session]);
var entries = new FakeEntries();
entries.Add(new ParticipationEntry
{
SessionId = session.Id, StudentId = student.Id,
Ratings = [new AspectRating { Key = "quality", Value = 2 }],
});
var aspects = new FakeAspects();
aspects.Save(new ParticipationAspect
{
Key = "quality", Label = "Qualität", ValueType = AspectValueType.Scale5, IsActive = true,
});
var versions = new FakeCompetencyCatalogVersions();
var version = versions.GetOrCreateDefault(subjectId);
var domains = new FakeCompetencyDomains();
domains.Add(new CompetencyDomain
{
SubjectId = subjectId, GradeLevel = 8, VersionId = version.Id, Name = "Bereich", Items = [item],
});
var vm = new ParticipationTabViewModel(sessions, entries, aspects, new FakeStudents([student]),
new FakeMemberships([]), new FakeGroups([group]), domains, versions);
vm.Initialize(group.Id, group.SchoolYear);
vm.SelectedSession = vm.Sessions.Single(s => s.Id == session.Id);
var row = Assert.Single(vm.StudentRows);
var cell = Assert.Single(row.CompetencyCells);
Assert.True(cell.IsEstimated);
Assert.Equal(2, cell.Value); // einziger bewerteter Aspekt "quality" = 2, kein Tageshighlight
}
[Fact] [Fact]
public async Task LoeschenBefehl_BrichtBeiAbgelehnterBestaetigungAb() public async Task LoeschenBefehl_BrichtBeiAbgelehnterBestaetigungAb()
{ {
@@ -31,8 +31,14 @@ public sealed class PersonalDataExportServiceTests
Assignments = [new SeatAssignment { Row = 1, Column = 2, StudentId = studentId }], Assignments = [new SeatAssignment { Row = 1, Column = 2, StudentId = studentId }],
}, },
]); ]);
var groupPlans = new FakeStudentGroupPlans();
groupPlans.Save(new StudentGroupPlan
{
GroupId = groupId, Name = "Projektwoche",
Groups = [new StudentGroupPlanGroup { StudentIds = [studentId] }],
});
var service = new PersonalDataExportService(students, groups, memberships, grades, results, entries, var service = new PersonalDataExportService(students, groups, memberships, grades, results, entries,
documentation, seatingPlans); documentation, seatingPlans, groupPlans);
var json = service.ExportAsJson(studentId); var json = service.ExportAsJson(studentId);
@@ -41,6 +47,7 @@ public sealed class PersonalDataExportServiceTests
Assert.Contains("\"Value\": \"2\"", json); Assert.Contains("\"Value\": \"2\"", json);
Assert.Contains("\"Sitzplan\": \"Standard\"", json); Assert.Contains("\"Sitzplan\": \"Standard\"", json);
Assert.Contains("\"Reihe\": 2", json); Assert.Contains("\"Reihe\": 2", json);
Assert.Contains("Projektwoche", json);
} }
[Fact] [Fact]
@@ -53,4 +60,23 @@ public sealed class PersonalDataExportServiceTests
Assert.Throws<InvalidOperationException>(() => service.ExportAsJson(Guid.NewGuid())); Assert.Throws<InvalidOperationException>(() => service.ExportAsJson(Guid.NewGuid()));
} }
[Fact]
public void ExportAsJson_EnthaeltGespeichertenPlanAuchNachEndeDerMitgliedschaft()
{
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
var groupId = Guid.NewGuid();
var plans = new FakeStudentGroupPlans();
plans.Save(new StudentGroupPlan
{
GroupId = groupId, Name = "Alte Projektgruppe",
Groups = [new StudentGroupPlanGroup { StudentIds = [student.Id] }],
});
var service = new PersonalDataExportService(
new FakeStudents([student]), new FakeGroups([]), new FakeMemberships([]),
new FakeGrades(), new FakeResults(), new FakeEntries(), new FakeDocumentation(),
new FakeSeatingPlans(), plans);
Assert.Contains("Alte Projektgruppe", service.ExportAsJson(student.Id));
}
} }
@@ -0,0 +1,89 @@
using LehrerApp.Core.Models;
using LehrerApp.Desktop.ViewModels.Groups;
using Xunit;
namespace LehrerApp.Desktop.Tests;
public sealed class RandomStudentPickerViewModelTests
{
private static (RandomStudentPickerViewModel Vm, List<Student> Students, LearningGroup Group) Build(int seed = 17)
{
var group = new LearningGroup { Name = "8a" };
var students = new List<Student>
{
new() { FirstName = "Anna", LastName = "Adler" },
new() { FirstName = "Ben", LastName = "Bauer" },
new() { FirstName = "Cem", LastName = "Can" },
};
var memberships = students.Select(s => new GroupMembership
{
GroupId = group.Id,
StudentId = s.Id,
}).ToList();
var vm = new RandomStudentPickerViewModel(
new FakeStudents(students), new FakeGroups([group]), new FakeMemberships(memberships),
new FakeSessions([]), new FakeEntries(), group.Id, new Random(seed));
return (vm, students, group);
}
[Fact]
public void Vollrunde_ZiehtAlleEinmal_BevorJemandWiederholtWird()
{
var (vm, _, _) = Build();
var names = new List<string>();
for (var i = 0; i < 3; i++)
{
vm.DrawCommand.Execute(null);
names.Add(vm.SelectedStudentName);
}
Assert.Equal(3, names.Distinct().Count());
Assert.Contains("Alle waren dran", vm.StatusText);
}
[Fact]
public void Reset_StartetZiehungOhneAngezeigtenNamenNeu()
{
var (vm, _, _) = Build();
vm.DrawCommand.Execute(null);
vm.ResetCommand.Execute(null);
Assert.False(vm.HasDrawnStudent);
Assert.Equal("Bereit?", vm.SelectedStudentName);
}
[Fact]
public void NurHeuteAktiveMitglieder_StehenZurAuswahl()
{
var group = new LearningGroup { Name = "8a" };
var active = new Student { FirstName = "Aktiv", LastName = "A" };
var former = new Student { FirstName = "Ehemalig", LastName = "E" };
var memberships = new List<GroupMembership>
{
new() { GroupId = group.Id, StudentId = active.Id },
new() { GroupId = group.Id, StudentId = former.Id, LeftAt = DateOnly.FromDateTime(DateTime.Today).AddDays(-1) },
};
var vm = new RandomStudentPickerViewModel(
new FakeStudents([active, former]), new FakeGroups([group]), new FakeMemberships(memberships),
new FakeSessions([]), new FakeEntries(), group.Id, new Random(1));
vm.DrawCommand.Execute(null);
Assert.Equal(active.FullName, vm.SelectedStudentName);
}
[Fact]
public void IntelligenteZiehung_VermeidetDirekteWiederholung()
{
var (vm, _, _) = Build(2);
vm.SelectionModeName = RandomStudentPickerViewModel.IntelligentLabel;
vm.DrawCommand.Execute(null);
var first = vm.SelectedStudentName;
vm.DrawCommand.Execute(null);
Assert.NotEqual(first, vm.SelectedStudentName);
}
}
@@ -78,4 +78,16 @@ public sealed class RatingCellTests
var cell = new RatingCell(Guid.NewGuid(), "k", 2); var cell = new RatingCell(Guid.NewGuid(), "k", 2);
Assert.Equal("++", cell.DisplayLabel); Assert.Equal("++", cell.DisplayLabel);
} }
[Fact]
public void SetValue_AufGeschaetzterZelle_MarkiertSieAlsBestaetigt()
{
var cell = new RatingCell(Guid.NewGuid(), "k", 1, isEstimated: true);
Assert.True(cell.IsEstimated);
cell.SetValue(1); // bestätigt zufällig denselben Wert wie die Schätzung
Assert.False(cell.IsEstimated);
Assert.Equal(1, cell.Value);
}
} }
@@ -0,0 +1,575 @@
using LehrerApp.Core.Models;
using LehrerApp.Core.Services;
using LehrerApp.Desktop.ViewModels.Groups;
using Xunit;
namespace LehrerApp.Desktop.Tests;
/// Tests für den Zeugnisnoten-Assistenten: eigenständige Halbjahre (H1 nur als Kontext in H2),
/// Endjahresnote aus den beiden Halbjahresnoten, Speichern/Festschreiben über dieselben
/// ReportGrade-Datensätze wie der Zeugnisnoten-Dialog sowie die beiden Graph-Modi.
public sealed class ReportGradeAssistantViewModelTests
{
private static readonly Guid GroupId = Guid.NewGuid();
private static readonly Student Anna = new() { Id = Guid.NewGuid(), FirstName = "Anna", LastName = "Beispiel" };
private static readonly Student Ben = new() { Id = Guid.NewGuid(), FirstName = "Ben", LastName = "Muster" };
private sealed class Fixture
{
public List<Exam> Exams { get; } = [];
public FakeResults Results { get; } = new();
public FakeGrades Grades { get; } = new();
public FakeReportGrades ReportGrades { get; } = new();
public List<ParticipationSession> Sessions { get; } = [];
public FakeEntries Entries { get; } = new();
public List<ParticipationSection> Sections { get; } = [];
public FakeInterimGrades InterimGrades { get; } = new();
public ReportGradeAssistantViewModel Build(DateOnly today, int gradeLevel = 8, InterimRunOptions? interim = null)
{
var schemes = new FakeSchemes();
schemes.SetForGroup(GroupId, new GradingScheme { ExamsPercent = 50, ParticipationPercent = 40, OtherPercent = 10 });
return new ReportGradeAssistantViewModel(
Grades, new FakeExams(Exams), Results, new FakeStudents([Anna, Ben]), new FakeMemberships([]),
schemes, ReportGrades, new FakeSessions(Sessions), Entries, new FakeAspects(),
new FakeSections(Sections), InterimGrades, new AttendanceBalanceService(), new GradingService(),
GroupId, GroupType.Class, GradingSystem.Grades1To6, "Testkurs", "2025/26", gradeLevel, today, interim);
}
public InterimRunDialogViewModel BuildRunDialog(DateOnly today, Guid? preselected = null)
{
var schemes = new FakeSchemes();
schemes.SetForGroup(GroupId, new GradingScheme { ExamsPercent = 50, ParticipationPercent = 40, OtherPercent = 10 });
return new InterimRunDialogViewModel(
Grades, new FakeExams(Exams), Results, new FakeStudents([Anna, Ben]), new FakeMemberships([]),
schemes, ReportGrades, new FakeSessions(Sessions), Entries, new FakeAspects(),
new FakeSections(Sections), InterimGrades, new GradingService(),
GroupId, GroupType.Class, GradingSystem.Grades1To6, "Testkurs", "2025/26", preselected, today);
}
public void AddSession(DateOnly date, int rating)
{
var session = new ParticipationSession { Id = Guid.NewGuid(), GroupId = GroupId, Date = date };
Sessions.Add(session);
Entries.Add(new ParticipationEntry { SessionId = session.Id, StudentId = Anna.Id,
Ratings = [new AspectRating { Key = "quality", Value = rating }] });
}
public Exam AddExam(string title, DateOnly date, string annaGrade)
{
var exam = new Exam { Id = Guid.NewGuid(), GroupId = GroupId, Title = title, Date = date };
Exams.Add(exam);
Results.Add(new ExamResult { ExamId = exam.Id, StudentId = Anna.Id, Grade = annaGrade });
return exam;
}
public void AddParticipation(DateOnly date, string value, string? note = null) =>
Grades.Add(new Grade { StudentId = Anna.Id, GroupId = GroupId, Category = GradeCategory.Participation,
Date = date, Value = value, Note = note });
}
private static readonly DateOnly InH1 = new(2025, 11, 10);
private static readonly DateOnly InH2 = new(2026, 4, 20);
[Fact]
public void Vorbelegung_WaehltDasLaufendeHalbjahr()
{
Assert.Equal(ParticipationPeriod.H1, new Fixture().Build(InH1).SelectedPeriod.Period);
Assert.Equal(ParticipationPeriod.H2, new Fixture().Build(InH2).SelectedPeriod.Period);
}
[Fact]
public void Halbjahr_BerechnetNoteUndZeigtTeilbereiche()
{
var f = new Fixture();
f.AddExam("K1", new DateOnly(2025, 10, 1), "2");
f.AddParticipation(new DateOnly(2025, 10, 15), "3");
var vm = f.Build(InH1);
// (2*50 + 3*40) / 90 = 2,44 -> 2
Assert.Equal("2", vm.CalculatedDisplay);
Assert.Contains("2,44", vm.CalculationDetail);
Assert.Equal(["2,00", "3,00", "–"], vm.Tiles.Select(t => t.Value));
Assert.Equal("2", vm.Students[0].GradeDisplay);
Assert.Equal(AssistantGradeStatus.Open, vm.Students[0].Status);
}
[Fact]
public void ZweitesHalbjahr_ErstesZaehltNichtWirdAberAlsKontextGezeigt()
{
var f = new Fixture();
f.AddExam("K1", new DateOnly(2025, 10, 1), "5");
f.AddExam("K2", new DateOnly(2026, 3, 1), "2");
f.AddParticipation(new DateOnly(2025, 12, 1), "5");
var vm = f.Build(InH2);
Assert.Equal("2", vm.CalculatedDisplay);
Assert.Equal(2, vm.Works.Count);
Assert.True(vm.Works[0].IsContext);
Assert.False(vm.Works[1].IsContext);
Assert.True(Assert.Single(vm.ParticipationGrades).IsContext);
vm.ShowPreviousHalf = false;
Assert.Equal("K2", Assert.Single(vm.Works).Title);
Assert.Empty(vm.ParticipationGrades);
Assert.Equal("2", vm.CalculatedDisplay);
}
[Fact]
public void Schuljahr_VerrechnetHalbjahresnotenUndBevorzugtGespeicherteEntscheidung()
{
var f = new Fixture();
f.AddExam("K1", new DateOnly(2025, 10, 1), "2");
f.AddExam("K2", new DateOnly(2026, 3, 1), "4");
var vm = f.Build(InH2);
vm.SelectedPeriod = vm.PeriodOptions.Single(p => p.Period == ParticipationPeriod.FullYear);
// (2 + 4) / 2 = 3
Assert.Equal("3", vm.CalculatedDisplay);
Assert.Equal(["2", "4"], vm.Tiles.Select(t => t.Value));
// Pädagogisch übersteuerte Halbjahresnote geht in die Verrechnung ein, nicht die berechnete.
f.ReportGrades.Save(new ReportGrade { StudentId = Anna.Id, GroupId = GroupId, Period = "1. Halbjahr",
CalculatedValue = "2", OverrideValue = "1", OverrideReason = "starke Entwicklung" });
vm.SelectedPeriod = vm.PeriodOptions.Single(p => p.Period == ParticipationPeriod.H2);
vm.SelectedPeriod = vm.PeriodOptions.Single(p => p.Period == ParticipationPeriod.FullYear);
// (1 + 4) / 2 = 2,5 -> kaufmännisch 3, pädagogisch 2
Assert.Equal("3", vm.CalculatedDisplay);
Assert.Contains("2,50", vm.CalculationDetail);
vm.RoundingRule = RoundingRule.Pedagogical;
Assert.Equal("2", vm.CalculatedDisplay);
}
[Fact]
public void Klasse10_PruefungsnotenZaehlenWieWeitereHalbjahre()
{
var f = new Fixture();
f.AddExam("K1", new DateOnly(2025, 10, 1), "2");
f.AddExam("K2", new DateOnly(2026, 3, 1), "2");
var vm = f.Build(InH2, gradeLevel: 10);
vm.SelectedPeriod = vm.PeriodOptions.Single(p => p.Period == ParticipationPeriod.FullYear);
Assert.True(vm.CanEnterExamGrades);
Assert.Equal("2", vm.CalculatedDisplay);
// (2 + 2 + 5) / 3 = 3
vm.ProjectExamGrade = "5";
Assert.Equal("3", vm.CalculatedDisplay);
Assert.Equal(3, vm.Tiles.Count);
// (2 + 2 + 5 + 5) / 4 = 3,5 -> 4
vm.OralExamGrade = "5";
Assert.Equal("4", vm.CalculatedDisplay);
Assert.Contains("4 Teilnoten", vm.CalculationDetail);
vm.SaveCommand.Execute(null);
var record = f.ReportGrades.GetByStudentGroupPeriod(Anna.Id, GroupId, "Gesamtes Schuljahr");
Assert.Equal("5", record!.ProjectExamGrade);
Assert.Equal("5", record.OralExamGrade);
Assert.Equal("4", record.CalculatedValue);
Assert.Equal("4", vm.Students[0].GradeDisplay);
}
private static ReportGradeAssistantViewModel Klasse10Schuljahr(Fixture f, string h1, string h2)
{
f.AddExam("K1", new DateOnly(2025, 10, 1), h1);
f.AddExam("K2", new DateOnly(2026, 3, 1), h2);
var vm = f.Build(InH2, gradeLevel: 10);
vm.SelectedPeriod = vm.PeriodOptions.Single(p => p.Period == ParticipationPeriod.FullYear);
return vm;
}
[Fact]
public void Klasse10_SchriftlichePruefungGehtMitEinemDrittelEin()
{
var vm = Klasse10Schuljahr(new Fixture(), "2", "2");
// § 14 Abs. 3 ObSchVO: (2 * 2 + 5) / 3 = 3,0
vm.WrittenExamGrade = "5";
Assert.Equal("3", vm.CalculatedDisplay);
}
[Fact]
public void Klasse10_ZusaetzlicheMuendlicheImSchriftlichenFach_EinsZuEinsOhneRundung()
{
var f = new Fixture();
var vm = Klasse10Schuljahr(f, "4", "4");
vm.WrittenExamGrade = "6";
// (4 + 4 + 6) / 3 = 4,67 -> 5
Assert.Equal("5", vm.CalculatedDisplay);
// § 13 Abs. 2 PrüfV: (6 + 3) / 2 = 4,5 — bleibt ungerundet; (4 + 4 + 4,5) / 3 = 4,17 -> 4
vm.AdditionalOralExamGrade = "3";
Assert.Equal("4", vm.CalculatedDisplay);
Assert.Contains("4,17", vm.CalculationDetail);
var tile = vm.Tiles.Single(t => t.Label == "Prüfungsleistung");
Assert.Equal("4,5", tile.Value);
Assert.Contains("zwischen 4 und 5", tile.Hint);
vm.SaveCommand.Execute(null);
var record = f.ReportGrades.GetByStudentGroupPeriod(Anna.Id, GroupId, "Gesamtes Schuljahr");
Assert.Equal("6", record!.WrittenExamGrade);
Assert.Equal("3", record.AdditionalOralExamGrade);
}
[Fact]
public void GenauZwischenZweiNoten_WeistAufPaedagogischeEntscheidungHin()
{
var f = new Fixture();
f.AddExam("K1", new DateOnly(2025, 10, 1), "2");
f.AddExam("K2", new DateOnly(2026, 3, 1), "3");
var vm = f.Build(InH2);
Assert.Empty(vm.BorderlineHint);
vm.SelectedPeriod = vm.PeriodOptions.Single(p => p.Period == ParticipationPeriod.FullYear);
// (2 + 3) / 2 = 2,5
Assert.Contains("zwischen 2 und 3", vm.BorderlineHint);
vm.ToggleLockCommand.Execute(null);
Assert.Empty(vm.BorderlineHint);
}
[Fact]
public void Klasse10_NachpruefungOhneAbschlusspruefung_ZweiZuEins()
{
var vm = Klasse10Schuljahr(new Fixture(), "5", "5");
// § 13 Abs. 3 PrüfV: (2 * 5 + 3) / 3 = 4,33 -> 4
vm.AdditionalOralExamGrade = "3";
Assert.Equal("4", vm.CalculatedDisplay);
}
[Fact]
public void Klasse10_NurEinHalbjahr_UnterrichtlicheLeistungZaehltTrotzdemDoppelt()
{
var f = new Fixture();
f.AddExam("K2", new DateOnly(2026, 3, 1), "2");
var vm = f.Build(InH2, gradeLevel: 10);
vm.SelectedPeriod = vm.PeriodOptions.Single(p => p.Period == ParticipationPeriod.FullYear);
// (2 * 2 + 5) / 3 = 3 — nicht (2 + 5) / 2 = 3,5 -> 4
vm.OralExamGrade = "5";
Assert.Equal("3", vm.CalculatedDisplay);
}
[Fact]
public void Klasse10_WiderspruechlichePruefungen_WerdenAbgelehnt()
{
var f = new Fixture();
var vm = Klasse10Schuljahr(f, "3", "3");
vm.WrittenExamGrade = "3";
vm.OralExamGrade = "2";
vm.SaveCommand.Execute(null);
Assert.NotEmpty(vm.OralExamGradeError);
vm.WrittenExamGrade = "";
vm.AdditionalOralExamGrade = "4";
vm.SaveCommand.Execute(null);
Assert.NotEmpty(vm.AdditionalOralExamGradeError);
Assert.Equal(0, f.ReportGrades.SavedCount);
}
[Fact]
public void Klasse10_UngueltigePruefungsnote_WirdNichtGespeichert()
{
var f = new Fixture();
f.AddExam("K1", new DateOnly(2025, 10, 1), "2");
var vm = f.Build(InH2, gradeLevel: 10);
vm.SelectedPeriod = vm.PeriodOptions.Single(p => p.Period == ParticipationPeriod.FullYear);
vm.ProjectExamGrade = "gut";
vm.SaveCommand.Execute(null);
Assert.NotEmpty(vm.ProjectExamGradeError);
Assert.Equal(0, f.ReportGrades.SavedCount);
}
[Fact]
public void PruefungsnotenNurInKlasse10UndNurFuerDasSchuljahr()
{
var klasse8 = new Fixture().Build(InH2);
klasse8.SelectedPeriod = klasse8.PeriodOptions.Single(p => p.Period == ParticipationPeriod.FullYear);
Assert.False(klasse8.CanEnterExamGrades);
Assert.False(new Fixture().Build(InH2, gradeLevel: 10).CanEnterExamGrades);
}
[Fact]
public void Speichern_UebersteuernOhneBegruendung_WirdAbgelehnt()
{
var f = new Fixture();
f.AddExam("K1", new DateOnly(2025, 10, 1), "3");
var vm = f.Build(InH1);
vm.OverrideValue = "2";
vm.SaveCommand.Execute(null);
Assert.NotEmpty(vm.OverrideReasonError);
Assert.Equal(0, f.ReportGrades.SavedCount);
vm.OverrideReason = "mündlich deutlich stärker";
vm.SaveCommand.Execute(null);
var record = f.ReportGrades.GetByStudentGroupPeriod(Anna.Id, GroupId, "1. Halbjahr");
Assert.NotNull(record);
Assert.Equal("3", record.CalculatedValue);
Assert.Equal("2", record.OverrideValue);
Assert.Equal("2", vm.Students[0].GradeDisplay);
Assert.Equal(AssistantGradeStatus.Saved, vm.Students[0].Status);
}
[Fact]
public void SpeichernUndWeiter_GehtZumNaechstenSchueler()
{
var f = new Fixture();
f.AddExam("K1", new DateOnly(2025, 10, 1), "3");
var vm = f.Build(InH1);
vm.SaveAndNextCommand.Execute(null);
Assert.Equal(Ben.Id, vm.SelectedStudent!.StudentId);
Assert.Equal("2 / 2", vm.ProgressText);
Assert.False(vm.NextStudentCommand.CanExecute(null));
}
[Fact]
public void Festschreiben_FriertBerechnetenStandEin()
{
var f = new Fixture();
f.AddExam("K1", new DateOnly(2025, 10, 1), "3");
var vm = f.Build(InH1);
vm.ToggleLockCommand.Execute(null);
Assert.True(vm.IsLocked);
Assert.Equal(AssistantGradeStatus.Locked, vm.Students[0].Status);
// Eine später eingetragene Arbeit ändert den festgeschriebenen Stand nicht mehr.
f.AddExam("K2", new DateOnly(2025, 12, 1), "1");
vm.SelectedPeriod = vm.PeriodOptions.Single(p => p.Period == ParticipationPeriod.H2);
vm.SelectedPeriod = vm.PeriodOptions.Single(p => p.Period == ParticipationPeriod.H1);
Assert.Equal("3", vm.CalculatedDisplay);
vm.ToggleLockCommand.Execute(null);
Assert.False(vm.IsLocked);
Assert.Equal("2", vm.CalculatedDisplay);
}
[Fact]
public void Mitarbeitsgraph_AbschnitteBlaetternUndVerlaufAmStueck()
{
var f = new Fixture();
f.Sections.Add(new ParticipationSection { GroupId = GroupId, Label = "Abschnitt 1",
StartDate = new DateOnly(2025, 8, 20), EndDate = new DateOnly(2025, 9, 30) });
f.Sections.Add(new ParticipationSection { GroupId = GroupId, Label = "Abschnitt 2",
StartDate = new DateOnly(2025, 10, 1), EndDate = new DateOnly(2025, 10, 31) });
f.AddParticipation(new DateOnly(2025, 9, 30), "2", "Abschnitt: Abschnitt 1");
foreach (var date in new[] { new DateOnly(2025, 9, 2), new DateOnly(2025, 10, 7), new DateOnly(2025, 11, 4) })
{
var session = new ParticipationSession { Id = Guid.NewGuid(), GroupId = GroupId, Date = date };
f.Sessions.Add(session);
f.Entries.Add(new ParticipationEntry { SessionId = session.Id, StudentId = Anna.Id,
Ratings = [new AspectRating { Key = "quality", Value = 1 }] });
}
var vm = f.Build(InH1);
Assert.True(vm.IsSectionMode);
Assert.Equal("1 / 3", vm.SectionPosition);
Assert.Contains("Abschnittsnote 2", vm.SectionTitle);
Assert.Single(Assert.Single(vm.ChartGroups).Points);
Assert.False(vm.PreviousSectionCommand.CanExecute(null));
vm.NextSectionCommand.Execute(null);
Assert.Contains("keine Abschnittsnote", vm.SectionTitle);
vm.NextSectionCommand.Execute(null);
Assert.Contains("vorläufig", vm.SectionTitle);
Assert.True(vm.ChartGroups[0].IsOpen);
Assert.False(vm.NextSectionCommand.CanExecute(null));
vm.IsSectionMode = false;
Assert.Equal(3, vm.ChartGroups.Count);
Assert.Equal(3, vm.ChartGroups.Sum(g => g.Points.Count));
}
// ── Zwischenstand (2.7.5) ────────────────────────────────────────────────
private static InterimRunOptions Sprechtag(params Guid[] students) =>
new(new DateOnly(2025, 11, 12), "Sprechtag", students);
[Fact]
public void Zwischenstand_RechnetNurBisZumStichtagUndMitLaufenderMitarbeit()
{
var f = new Fixture();
f.AddExam("K1", new DateOnly(2025, 10, 1), "2");
f.AddExam("K2", new DateOnly(2025, 12, 1), "6"); // nach dem Stichtag
f.AddSession(new DateOnly(2025, 10, 20), -2); // laufender Abschnitt, schwache Mitarbeit
var vm = f.Build(InH1, interim: Sprechtag(Anna.Id));
Assert.True(vm.IsInterimMode);
Assert.Equal(Anna.Id, Assert.Single(vm.Students).StudentId);
Assert.Equal("K1", Assert.Single(vm.Works).Title);
Assert.Equal("2", vm.InterimWritten);
Assert.NotNull(vm.InterimOral);
Assert.Contains("laufender Abschnitt", vm.Tiles.Single(t => t.Label == "Mitarbeit").Hint);
// Die schwache laufende Mitarbeit zieht den Gesamtstand unter die reine Klausurnote.
Assert.True(int.Parse(vm.InterimOverall!) > 2);
Assert.Contains("12.11.2025", vm.CalculationDetail);
// Die Zeugnisnoten-Berechnung selbst bleibt ohne laufenden Abschnitt.
var report = f.Build(InH1);
Assert.Equal("–", report.Tiles.Single(t => t.Label == "Mitarbeit").Value);
}
[Fact]
public void Zwischenstand_NotierenSpeichertGetrenntVonDerZeugnisnote()
{
var f = new Fixture();
f.AddExam("K1", new DateOnly(2025, 10, 1), "3");
var vm = f.Build(InH1, interim: Sprechtag(Anna.Id, Ben.Id));
vm.InterimOverall = "";
vm.NoteInterimCommand.Execute(null);
Assert.NotEmpty(vm.InterimOverallError);
Assert.Empty(f.InterimGrades.All);
vm.InterimOverall = "3-";
vm.InterimNote = "Mitarbeit muss besser werden";
vm.NoteInterimAndNextCommand.Execute(null);
var entry = Assert.Single(f.InterimGrades.All);
Assert.Equal(Anna.Id, entry.StudentId);
Assert.Equal(new DateOnly(2025, 11, 12), entry.Date);
Assert.Equal("Sprechtag", entry.Occasion);
Assert.Equal("3", entry.WrittenValue);
Assert.Equal("3-", entry.OverallValue);
Assert.Equal(0, f.ReportGrades.SavedCount);
Assert.Equal(AssistantGradeStatus.Noted, vm.Students[0].Status);
Assert.Equal("3-", vm.Students[0].GradeDisplay);
Assert.Equal(Ben.Id, vm.SelectedStudent!.StudentId);
// Erneutes Notieren im selben Durchgang überschreibt statt zu verdoppeln.
vm.SelectedStudent = vm.Students[0];
Assert.True(vm.HasInterimEntry);
Assert.Equal("3-", vm.InterimOverall);
vm.InterimOverall = "4";
vm.NoteInterimCommand.Execute(null);
Assert.Equal("4", Assert.Single(f.InterimGrades.All).OverallValue);
vm.RemoveInterimCommand.Execute(null);
Assert.Empty(f.InterimGrades.All);
Assert.Equal(AssistantGradeStatus.Open, vm.Students[0].Status);
}
[Fact]
public void Zwischenstaende_ErscheinenImZeugnisnotenModusAlsListeUndMarker()
{
var f = new Fixture();
f.AddExam("K1", new DateOnly(2025, 10, 1), "3");
f.InterimGrades.Save(new InterimGrade { StudentId = Anna.Id, GroupId = GroupId,
Date = new DateOnly(2025, 11, 12), Occasion = "Sprechtag", WrittenValue = "3", OverallValue = "3" });
var vm = f.Build(new DateOnly(2025, 12, 10));
var row = Assert.Single(vm.InterimEntries);
Assert.Equal("12.11.2025 · Sprechtag", row.Title);
Assert.Equal("schriftlich 3", row.Detail);
Assert.Contains(vm.ChartGroups.SelectMany(g => g.Points), p => p.ExamLabel == "Zwischenstand: 3");
Assert.True(vm.IsReportMode);
}
[Fact]
public void Startdialog_VorauswahlGefaehrdeteUndBestaetigen()
{
var f = new Fixture();
f.AddExam("K1", new DateOnly(2025, 10, 1), "5");
f.Results.Add(new ExamResult { ExamId = f.Exams[0].Id, StudentId = Ben.Id, Grade = "2" });
var vm = f.BuildRunDialog(new DateOnly(2025, 11, 12));
Assert.All(vm.Students, s => Assert.True(s.IsSelected));
Assert.Equal(["5", "2"], vm.Students.Select(s => s.ProvisionalDisplay));
vm.SelectAtRiskCommand.Execute(null);
Assert.Equal([Anna.Id], vm.Students.Where(s => s.IsSelected).Select(s => s.StudentId));
vm.OccasionName = "Blauer Brief";
Assert.True(vm.Confirm());
Assert.Equal(new DateOnly(2025, 11, 12), vm.Result!.Date);
Assert.Equal("Blauer Brief", vm.Result.Occasion);
Assert.Equal([Anna.Id], vm.Result.StudentIds);
}
[Fact]
public void Startdialog_EinzelfallUndValidierung()
{
var f = new Fixture();
var vm = f.BuildRunDialog(new DateOnly(2025, 11, 12), preselected: Ben.Id);
Assert.Equal([Ben.Id], vm.Students.Where(s => s.IsSelected).Select(s => s.StudentId));
vm.OccasionName = "Elternanfrage";
vm.OccasionDetail = "Frau Muster";
Assert.Equal("Elternanfrage: Frau Muster", vm.Occasion);
vm.SelectNoneCommand.Execute(null);
Assert.False(vm.Confirm());
Assert.NotEmpty(vm.SelectionError);
vm.DateText = "12.11.2030";
Assert.False(vm.Confirm());
Assert.NotEmpty(vm.DateTextError);
}
[Fact]
public void Startdialog_BegonnenenDurchgangFortsetzen()
{
var f = new Fixture();
f.InterimGrades.Save(new InterimGrade { StudentId = Anna.Id, GroupId = GroupId,
Date = new DateOnly(2025, 11, 12), Occasion = "Sprechtag: 1. Elternsprechtag", OverallValue = "3" });
var vm = f.BuildRunDialog(new DateOnly(2025, 12, 1));
vm.SelectedExistingRun = Assert.Single(vm.ExistingRuns);
Assert.Equal("12.11.2025", vm.DateText);
Assert.Equal("Sprechtag: 1. Elternsprechtag", vm.Occasion);
Assert.Equal("notiert: 3", vm.Students.Single(s => s.StudentId == Anna.Id).NotedDisplay);
Assert.Equal("", vm.Students.Single(s => s.StudentId == Ben.Id).NotedDisplay);
}
[Fact]
public void Notenuebersicht_ZeigtZwischenstaendeAlsEigeneSpalteOhneEinflussAufGesamt()
{
var f = new Fixture();
f.AddExam("K1", new DateOnly(2025, 10, 1), "2");
f.InterimGrades.Save(new InterimGrade { StudentId = Anna.Id, GroupId = GroupId,
Date = new DateOnly(2025, 11, 12), Occasion = "Sprechtag", OverallValue = "5" });
var vm = new GradeOverviewTabViewModel(f.Grades, new FakeExams(f.Exams), f.Results,
new FakeStudents([Anna, Ben]), new FakeMemberships([]), f.InterimGrades, new GradingService());
vm.Initialize(GroupId, GradingSystem.Grades1To6, GroupType.Class, "Testkurs", "2025/26");
var column = vm.Columns.Last();
Assert.True(column.IsInterim);
Assert.Equal("Zwischenstand 12.11. Sprechtag", column.Header);
var anna = vm.Rows.Single(r => r.StudentId == Anna.Id);
Assert.Equal("5", anna.Cells.Last());
Assert.Equal("2.00", anna.TotalDisplay);
Assert.Equal("", vm.Rows.Single(r => r.StudentId == Ben.Id).Cells.Last());
}
}
@@ -186,6 +186,33 @@ public class ReportGradeCalculationTests
Assert.Equal("1", annaNachSperre.FinalDisplay); Assert.Equal("1", annaNachSperre.FinalDisplay);
} }
[Fact]
public void Schuljahr_WirdAusHalbjahresnotenUndPruefungsnotenVerrechnet()
{
// H1: eine 1 und eine 2 -> 1,5 -> 2. H2: eine 4 -> 4.
var h1a = new Exam { Id = Guid.NewGuid(), GroupId = GroupId, Date = new DateOnly(2025, 9, 10), Title = "K1" };
var h1b = new Exam { Id = Guid.NewGuid(), GroupId = GroupId, Date = new DateOnly(2025, 11, 10), Title = "K2" };
var h2 = new Exam { Id = Guid.NewGuid(), GroupId = GroupId, Date = new DateOnly(2026, 3, 10), Title = "K3" };
var results = new FakeResults();
results.Add(new ExamResult { ExamId = h1a.Id, StudentId = Anna.Id, Grade = "1" });
results.Add(new ExamResult { ExamId = h1b.Id, StudentId = Anna.Id, Grade = "2" });
results.Add(new ExamResult { ExamId = h2.Id, StudentId = Anna.Id, Grade = "4" });
var reportGrades = new FakeReportGrades();
var vm = BuildViewModel(new FakeGrades(), new FakeSchemes(), reportGrades, new FakeExams([h1a, h1b, h2]), results);
// Aus den Halbjahresnoten: (2 + 4) / 2 = 3 — nicht aus allen Arbeiten ((1+2+4)/3 = 2,33 -> 2).
Assert.Equal("3", vm.Rows.Single(r => r.StudentId == Anna.Id).CalculatedValue);
// Klasse 10: eine im Fach abgelegte Projektprüfung zählt wie ein drittes Halbjahr.
reportGrades.Save(new ReportGrade { StudentId = Anna.Id, GroupId = GroupId, Period = "Gesamtes Schuljahr",
ProjectExamGrade = "6" });
vm.Refresh();
// (2 + 4 + 6) / 3 = 4
Assert.Equal("4", vm.Rows.Single(r => r.StudentId == Anna.Id).CalculatedValue);
}
[Fact] [Fact]
public void ExportCsv_EnthaeltAlleSchuelerDerGruppe() public void ExportCsv_EnthaeltAlleSchuelerDerGruppe()
{ {
@@ -0,0 +1,135 @@
using System.Net;
using System.Text;
using LehrerApp.Desktop.Services;
using Xunit;
namespace LehrerApp.Desktop.Tests;
public sealed partial class SettingsViewModelTests
{
private const string UsageJson = """
{"apiVersion":"1","schema":"lehrerbackend.usage.v1",
"period":{"days":28,"from":"2026-09-24T12:00:00","to":"2026-10-22T12:00:00"},
"totals":{"calls":3,"chargedUsd":"0.300000","chargedEur":null},
"byAction":[
{"actionId":"plan","label":"Unterricht planen","operation":null,"calls":2,"chargedUsd":"0.200000","chargedEur":"0.180000"},
{"actionId":"worksheet_rewrite_openai","label":"Text überarbeiten","operation":"rewrite","calls":1,"chargedUsd":"0.100000","chargedEur":null}],
"entries":[{"at":"2026-10-22T11:00:00","actionId":"plan","label":"Unterricht planen","operation":null,"status":"settled","chargedUsd":"0.100000","chargedEur":"0.090000"}],
"entriesTruncated":true,"features":{"spellcheck":true}}
""";
private static AiPlanningService AiWithHandler(Func<HttpRequestMessage, Task<HttpResponseMessage>> handler) =>
new(new HttpClient(new AccountHandler(handler)) { BaseAddress = new Uri("https://example.invalid/backend/") },
new FakeLessons(), new FakeGroups([]), new FakeSubjects([]), new FakeCompetencyDomains(),
new FakeCompetencyCatalogVersions(), new FakeAlternativeLessonPaths([]), TestSupport.BuildAppLogger());
private static HttpResponseMessage JsonResponse(string json, HttpStatusCode status = HttpStatusCode.OK) =>
new(status) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
private sealed class AccountHandler(Func<HttpRequestMessage, Task<HttpResponseMessage>> handler) : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => handler(request);
}
[Fact]
public async Task AiAccount_AuthUndVerbrauchWerdenGeladenUndWaehrungenBleibenGetrennt()
{
var requests = new List<string>();
var ai = AiWithHandler(request =>
{
Assert.Equal("Bearer", request.Headers.Authorization?.Scheme);
Assert.Equal("test-token", request.Headers.Authorization?.Parameter);
requests.Add(request.RequestUri!.PathAndQuery);
return Task.FromResult(JsonResponse(request.RequestUri.AbsolutePath.EndsWith("status.php")
? """{"balanceUsd":3.5,"balanceEur":3.1}""" : UsageJson));
});
var settings = TestSupport.BuildAiSettingsService();
var vm = BuildViewModel(aiSettings: settings, aiPlanning: ai);
settings.SetCredentialsAndToken("test", "test-token");
await vm.RefreshAiAccountCommand.ExecuteAsync(null);
Assert.Equal(["/backend/status.php", "/backend/api/v1/usage.php?days=28"], requests);
Assert.Contains("3,50 USD", vm.AiBalanceDisplay);
Assert.Contains("3,10 €", vm.AiBalanceDisplay);
Assert.True(vm.AiHasUsage);
Assert.Equal(2, vm.AiUsageGroups.Count);
Assert.Equal(3, vm.AiUsageGroups.Sum(g => g.Calls));
Assert.Contains("0,30 USD", vm.AiUsageSummary);
Assert.DoesNotContain("€", vm.AiUsageSummary); // Euro-Gegenwert nicht für alle Aufrufe vorhanden
Assert.Equal("Unterricht planen", Assert.Single(vm.AiUsageEntries).Label);
Assert.Contains("neuesten 1", vm.AiUsageStatus);
Assert.Contains("2×", vm.AiFeatures.Single(f => f.ActionId == "plan").Usage);
Assert.Equal("Kostenlos", vm.AiFeatures.Single(f => f.ActionId == null).Usage);
Assert.False(vm.AiIsRefreshing);
}
[Fact]
public async Task AiAccount_AltesBackend_BehaeltGuthabenUndErklaertFehlendenVerbrauch()
{
var ai = AiWithHandler(request => Task.FromResult(request.RequestUri!.AbsolutePath.EndsWith("status.php")
? JsonResponse("""{"balanceUsd":2}""") : JsonResponse("{}", HttpStatusCode.NotFound)));
var settings = TestSupport.BuildAiSettingsService();
var vm = BuildViewModel(aiSettings: settings, aiPlanning: ai);
settings.SetCredentialsAndToken("test", "token");
await vm.RefreshAiAccountCommand.ExecuteAsync(null);
Assert.Equal("Guthaben: 2,00 USD", vm.AiBalanceDisplay);
Assert.Contains("noch keine Verbrauchsübersicht", vm.AiUsageStatus);
Assert.Empty(vm.AiUsageGroups);
Assert.False(vm.AiIsRefreshing);
}
[Fact]
public async Task AiAccount_AbmeldenWaerendLaden_VerhindertRueckkehrDerKontodaten()
{
var response = new TaskCompletionSource<HttpResponseMessage>();
var settings = TestSupport.BuildAiSettingsService();
var vm = BuildViewModel(aiSettings: settings, aiPlanning: AiWithHandler(_ => response.Task));
settings.SetCredentialsAndToken("test", "token");
var refresh = vm.RefreshAiAccountCommand.ExecuteAsync(null);
Assert.True(vm.AiIsRefreshing);
vm.AiLogoutCommand.Execute(null);
response.SetResult(JsonResponse("""{"balanceUsd":99}"""));
await refresh;
Assert.False(settings.IsLoggedIn);
Assert.False(vm.AiIsLoggedIn);
Assert.False(vm.AiIsRefreshing);
Assert.Empty(vm.AiBalanceDisplay);
Assert.Empty(vm.AiUsageEntries);
Assert.Empty(vm.AiUsageGroups);
Assert.Contains("Nach der Anmeldung", vm.AiUsageStatus);
}
[Theory]
[InlineData("{}")]
[InlineData("<html>Fehler</html>")]
[InlineData("null")]
public async Task AiAccount_UngueltigesGuthaben_LiefertVerstaendlichenFehler(string json)
{
var ai = AiWithHandler(_ => Task.FromResult(JsonResponse(json)));
var error = await Assert.ThrowsAsync<AiBackendException>(() => ai.GetAccountBalanceAsync("token"));
Assert.Contains("Guthaben", error.Message);
}
[Theory]
[InlineData("0.300000", "null")]
[InlineData("lehrerbackend.usage.v1", "unbekannt")]
[InlineData("2026-10-22T11:00:00", "ungueltig")]
public void AiUsage_UngueltigeAntwortWirdAbgelehnt(string oldValue, string newValue)
{
Assert.Throws<AiBackendException>(() => AiUsageReport.Parse(UsageJson.Replace(oldValue, newValue)));
}
[Fact]
public async Task AiAccount_NetzwerkfehlerUndAbgelaufeneAnmeldungWerdenErklaert()
{
var unavailable = AiWithHandler(_ => throw new HttpRequestException());
Assert.Contains("nicht erreichbar", (await Assert.ThrowsAsync<AiBackendException>(() => unavailable.GetUsageAsync("token"))).Message);
var expired = AiWithHandler(_ => Task.FromResult(JsonResponse("{}", HttpStatusCode.Unauthorized)));
Assert.Contains("Anmeldung abgelaufen", (await Assert.ThrowsAsync<AiBackendException>(() => expired.GetUsageAsync("token"))).Message);
}
}
@@ -11,7 +11,7 @@ using LehrerApp.Templating;
namespace LehrerApp.Desktop.Tests; namespace LehrerApp.Desktop.Tests;
public sealed class SettingsViewModelTests public sealed partial class SettingsViewModelTests
{ {
private static SettingsViewModel BuildViewModel(FakeSchoolHolidays? holidays = null, private static SettingsViewModel BuildViewModel(FakeSchoolHolidays? holidays = null,
FakeSupervisionDuties? supervisionDuties = null, FakeSupervisionDuties? supervisionDuties = null,
@@ -19,7 +19,7 @@ public sealed class SettingsViewModelTests
FakeCompetencyCatalogVersions? competencyVersions = null, FakeCompetencyCatalogVersions? competencyVersions = null,
EventQueue? eventQueue = null, SyncKeyStatus? syncKeyStatus = null, EventQueue? eventQueue = null, SyncKeyStatus? syncKeyStatus = null,
SyncKeyRecoveryService? syncKeyRecovery = null, AppearanceSettingsService? appearance = null, SyncKeyRecoveryService? syncKeyRecovery = null, AppearanceSettingsService? appearance = null,
TrashViewModel? trashTab = null) TrashViewModel? trashTab = null, AiSettingsService? aiSettings = null, AiPlanningService? aiPlanning = null)
{ {
// Bewusst kein "using": SchoolCalendarSettingsService liest den Pfad erst bei SetState, // Bewusst kein "using": SchoolCalendarSettingsService liest den Pfad erst bei SetState,
// das Verzeichnis muss über die Lebensdauer des ViewModels bestehen bleiben. // das Verzeichnis muss über die Lebensdauer des ViewModels bestehen bleiben.
@@ -37,7 +37,7 @@ public sealed class SettingsViewModelTests
new FakeDocumentation(), new FakeStudents([]), new FakeShorthandCodes([]), new FakeDocumentation(), new FakeStudents([]), new FakeShorthandCodes([]),
holidays ?? new FakeSchoolHolidays(), new SchoolCalendarSettingsService(tempPath), holidays ?? new FakeSchoolHolidays(), new SchoolCalendarSettingsService(tempPath),
new PeriodScheduleService(tempPath), supervisionDuties ?? new FakeSupervisionDuties(), new PeriodScheduleService(tempPath), supervisionDuties ?? new FakeSupervisionDuties(),
new TemplateStore(tempPath), new WorksheetTemplateStore(new TemplateStore(tempPath, subfolder: "worksheet-template-packages")), TestSupport.BuildAiSettingsService(), TestSupport.BuildAiPlanningService(), new TemplateStore(tempPath), new WorksheetTemplateStore(new TemplateStore(tempPath, subfolder: "worksheet-template-packages")), aiSettings ?? TestSupport.BuildAiSettingsService(), aiPlanning ?? TestSupport.BuildAiPlanningService(),
TestSupport.BuildMcpSettingsService(), TestSupport.BuildMcpSettingsService(),
TestSupport.BuildMcpClientRegistrationService(), TestSupport.BuildMcpClientRegistrationService(),
TestSupport.BuildWebUntisSettingsService(), TestSupport.BuildWebUntisSettingsService(),
@@ -513,6 +513,35 @@ public sealed class SettingsViewModelTests
Assert.Equal([0, 1], stored.Select(x => x.SortOrder)); Assert.Equal([0, 1], stored.Select(x => x.SortOrder));
} }
[Fact]
public void Kompetenzkatalog_Aktualisieren_ZeigtNachtraeglicheMcpAenderung()
{
var subject = new Subject { Name = "Naturwissenschaften", ShortName = "Nawi" };
var repository = new FakeCompetencyDomains();
var versions = new FakeCompetencyCatalogVersions();
var version = versions.GetOrCreateDefault(subject.Id);
var vm = BuildViewModel(subjects: new FakeSubjects([subject]), competencyDomains: repository,
competencyVersions: versions);
vm.CatalogSubject = vm.Subjects.Single();
Assert.True(vm.HasNoCatalogDomains);
repository.Add(new CompetencyDomain
{
SubjectId = subject.Id,
GradeLevel = 10,
VersionId = version.Id,
Name = "Erkenntnisgewinnung",
Items = [new CompetencyItem { Code = "EG1", Description = "Modelle verwenden" }],
});
vm.RefreshCompetencyCatalogCommand.Execute(null);
var domain = Assert.Single(vm.Domains);
Assert.Equal("Erkenntnisgewinnung", domain.Name);
Assert.False(vm.HasNoCatalogDomains);
}
[Fact] [Fact]
public void Kompetenzen_Umsortieren_PersistiertSortOrder() public void Kompetenzen_Umsortieren_PersistiertSortOrder()
{ {
@@ -0,0 +1,253 @@
using LehrerApp.Core.Models;
using LehrerApp.Desktop.ViewModels.Groups;
using Xunit;
namespace LehrerApp.Desktop.Tests;
public sealed class StudentGroupGeneratorViewModelTests
{
private static (StudentGroupGeneratorViewModel Vm, List<Student> Students, LearningGroup Group,
FakeSessions Sessions, FakeEntries Entries) Build(int studentCount = 10,
FakeStudentGroupPlans? savedPlans = null)
{
var group = new LearningGroup { Name = "8a", GradingSystem = GradingSystem.Grades1To6 };
var students = Enumerable.Range(1, studentCount).Select(i => new Student
{
FirstName = $"Kind{i:00}", LastName = "Test",
}).ToList();
var memberships = students.Select(s => new GroupMembership
{
GroupId = group.Id, StudentId = s.Id,
}).ToList();
var sessions = new FakeSessions([]);
var entries = new FakeEntries();
var vm = new StudentGroupGeneratorViewModel(
new FakeStudents(students), new FakeGroups([group]), new FakeMemberships(memberships),
sessions, entries, new FakeGrades(), group.Id, new Random(7), savedPlans);
return (vm, students, group, sessions, entries);
}
[Fact]
public void ManuelleUmverteilung_WirdGespeichertUndSpaeterWiederGeladen()
{
var plans = new FakeStudentGroupPlans();
var (vm, students, group, _, _) = Build(6, plans);
vm.TargetGroupCount = 2;
vm.CountPriority = 100;
vm.GenerateCommand.Execute(null);
var source = vm.GeneratedGroups[0];
var target = vm.GeneratedGroups[1];
var member = source.Members[0];
Assert.True(vm.MoveStudent(member, target));
Assert.False(vm.MoveStudent(member, target));
Assert.DoesNotContain(member, source.Members);
vm.PlanName = "Projektwoche";
vm.SavePlanCommand.Execute(null);
var saved = Assert.Single(plans.GetByGroup(group.Id));
Assert.Equal("Projektwoche", saved.Name);
Assert.Contains(member.Id, saved.Groups[1].StudentIds);
Assert.False(vm.HasUnsavedChanges);
vm.GenerateCommand.Execute(null);
vm.SelectedSavedPlan = Assert.Single(vm.SavedPlans);
vm.LoadSavedPlanCommand.Execute(null);
Assert.Contains(vm.GeneratedGroups[1].Members, m => m.Id == member.Id);
Assert.DoesNotContain(vm.GeneratedGroups[0].Members, m => m.Id == member.Id);
Assert.False(vm.HasUnsavedChanges);
Assert.Equal("Projektwoche", vm.PlanName);
var reopened = new StudentGroupGeneratorViewModel(
new FakeStudents(students), new FakeGroups([group]),
new FakeMemberships(students.Select(s => new GroupMembership
{
GroupId = group.Id, StudentId = s.Id,
}).ToList()),
new FakeSessions([]), new FakeEntries(), new FakeGrades(), group.Id,
savedPlans: plans);
reopened.SelectedSavedPlan = Assert.Single(reopened.SavedPlans);
reopened.LoadSavedPlanCommand.Execute(null);
Assert.Contains(reopened.GeneratedGroups[1].Members, m => m.Id == member.Id);
reopened.PlanName = "Projektwoche aktualisiert";
reopened.SavePlanCommand.Execute(null);
Assert.Equal("Projektwoche aktualisiert", Assert.Single(plans.GetByGroup(group.Id)).Name);
}
[Fact]
public void SpeichernUeberschreibtAusgewaehltenPlanErstNachDemLaden()
{
var plans = new FakeStudentGroupPlans();
var (vm, _, group, _, _) = Build(6, plans);
vm.GenerateCommand.Execute(null);
vm.PlanName = "Alter Plan";
vm.SavePlanCommand.Execute(null);
vm.GenerateCommand.Execute(null);
vm.SelectedSavedPlan = Assert.Single(vm.SavedPlans);
vm.PlanName = "Neuer Plan";
vm.SavePlanCommand.Execute(null);
Assert.Equal(2, plans.GetByGroup(group.Id).Count);
Assert.Contains(plans.GetByGroup(group.Id), p => p.Name == "Alter Plan");
Assert.Contains(plans.GetByGroup(group.Id), p => p.Name == "Neuer Plan");
}
[Fact]
public void FesteZielgroesse_ErzeugtPassendeAnzahlMitKleinerAusnahme()
{
var (vm, _, _, _, _) = Build(10);
vm.TargetGroupSize = 4;
vm.TargetGroupCount = 2;
vm.SizePriority = 100;
vm.CountPriority = 20;
vm.GenerateCommand.Execute(null);
Assert.Equal(3, vm.GeneratedGroups.Count);
Assert.Equal(new[] { 3, 3, 4 }, vm.GeneratedGroups.Select(g => g.Members.Count).OrderBy(x => x));
Assert.Contains("nicht gleichzeitig", vm.WarningText);
}
[Fact]
public void FesteGruppenanzahl_HatVorrangVorZielgroesse()
{
var (vm, _, _, _, _) = Build(10);
vm.TargetGroupSize = 3;
vm.TargetGroupCount = 2;
vm.SizePriority = 20;
vm.CountPriority = 100;
vm.GenerateCommand.Execute(null);
Assert.Equal(2, vm.GeneratedGroups.Count);
Assert.All(vm.GeneratedGroups, group => Assert.Equal(5, group.Members.Count));
}
[Fact]
public void AdHoc_SchliesstHeuteAbwesendeAus()
{
var (vm, students, group, sessions, entries) = Build(6);
var session = new ParticipationSession { GroupId = group.Id, Date = DateOnly.FromDateTime(DateTime.Today) };
sessions.Save(session);
entries.Add(new ParticipationEntry
{
SessionId = session.Id, StudentId = students[0].Id, Attendance = AttendanceStatus.Excused,
});
vm.ParticipantModeName = StudentGroupGeneratorViewModel.AdHocModeLabel;
vm.TargetGroupCount = 2;
vm.CountPriority = 100;
vm.GenerateCommand.Execute(null);
var names = vm.GeneratedGroups.SelectMany(g => g.Members).Select(m => m.Name).ToList();
Assert.Equal(5, names.Count);
Assert.DoesNotContain(students[0].FullName, names);
Assert.Contains("fehlt heute", vm.WarningText);
}
[Fact]
public void AdHoc_OhneHeutigeErfassung_WarntUndNutztAlleAktiven()
{
var (vm, students, _, _, _) = Build(6);
vm.ParticipantModeName = StudentGroupGeneratorViewModel.AdHocModeLabel;
vm.GenerateCommand.Execute(null);
Assert.Equal(students.Count, vm.GeneratedGroups.SelectMany(g => g.Members).Count());
Assert.Contains("keine Anwesenheit", vm.WarningText);
}
[Fact]
public void Leistungsverteilung_UnterscheidetHomogeneUndHeterogeneGruppen()
{
var group = new LearningGroup { Name = "Kurs", GradingSystem = GradingSystem.Grades1To6 };
var students = new[] { "A", "B", "C", "D" }.Select(name => new Student
{
FirstName = name, LastName = "Test",
}).ToList();
var memberships = students.Select(s => new GroupMembership { GroupId = group.Id, StudentId = s.Id }).ToList();
var grades = new FakeGrades();
var values = new[] { "1", "2", "5", "6" };
for (var i = 0; i < students.Count; i++)
grades.Add(new Grade { GroupId = group.Id, StudentId = students[i].Id, Value = values[i] });
var vm = new StudentGroupGeneratorViewModel(
new FakeStudents(students), new FakeGroups([group]), new FakeMemberships(memberships),
new FakeSessions([]), new FakeEntries(), grades, group.Id, new Random(3))
{
TargetGroupCount = 2,
CountPriority = 100,
PerformanceDistribution = -100,
};
vm.GenerateCommand.Execute(null);
var homogeneousFirst = vm.GeneratedGroups[0].Members.Select(m => m.Name).ToHashSet();
Assert.Contains(students[0].FullName, homogeneousFirst);
Assert.Contains(students[1].FullName, homogeneousFirst);
vm.PerformanceDistribution = 100;
vm.GenerateCommand.Execute(null);
Assert.All(vm.GeneratedGroups, generated =>
{
var names = generated.Members.Select(m => m.Name).ToHashSet();
Assert.True(names.Overlaps([students[0].FullName, students[1].FullName]));
Assert.True(names.Overlaps([students[2].FullName, students[3].FullName]));
});
}
[Fact]
public void Paarregeln_ErzwingenZusammenUndTrennenMitHoherPrioritaet()
{
var (vm, students, _, _, _) = Build(6);
vm.TargetGroupCount = 2;
vm.CountPriority = 100;
vm.PerformanceDistribution = 0;
vm.ForcedPairPriority = 100;
vm.SelectedPairStudentA = vm.PairCandidates.Single(s => s.Id == students[0].Id);
vm.SelectedPairStudentB = vm.PairCandidates.Single(s => s.Id == students[1].Id);
vm.AddForcedPairCommand.Execute(null);
vm.SelectedPairStudentA = vm.PairCandidates.Single(s => s.Id == students[2].Id);
vm.SelectedPairStudentB = vm.PairCandidates.Single(s => s.Id == students[3].Id);
vm.AddExcludedPairCommand.Execute(null);
vm.GenerateCommand.Execute(null);
var groupByName = vm.GeneratedGroups.SelectMany((group, index) =>
group.Members.Select(member => (member.Name, index)))
.ToDictionary(x => x.Name, x => x.index);
Assert.Equal(groupByName[students[0].FullName], groupByName[students[1].FullName]);
Assert.NotEqual(groupByName[students[2].FullName], groupByName[students[3].FullName]);
}
[Fact]
public void FoerderschuelerWerdenMoeglichstGleichmaessigVerteilt()
{
var group = new LearningGroup { Name = "Kurs" };
var students = Enumerable.Range(1, 8).Select(i => new Student
{
FirstName = $"Kind{i}", LastName = "Test",
}).ToList();
var memberships = students.Select((student, index) => new GroupMembership
{
GroupId = group.Id,
StudentId = student.Id,
Niveau = index < 4 ? Niveau.Foerder : null,
}).ToList();
var vm = new StudentGroupGeneratorViewModel(
new FakeStudents(students), new FakeGroups([group]), new FakeMemberships(memberships),
new FakeSessions([]), new FakeEntries(), new FakeGrades(), group.Id, new Random(4))
{
TargetGroupCount = 2,
CountPriority = 100,
PerformanceDistribution = -100,
DistributeSupportStudents = true,
};
vm.GenerateCommand.Execute(null);
var supportNames = students.Take(4).Select(s => s.FullName).ToHashSet();
Assert.All(vm.GeneratedGroups, generated =>
Assert.Equal(2, generated.Members.Count(member => supportNames.Contains(member.Name))));
}
}
@@ -0,0 +1,129 @@
using LehrerApp.Core.Models;
using LehrerApp.Core.Services;
using LehrerApp.Desktop.Services;
using LehrerApp.Desktop.ViewModels.Students;
using LehrerApp.Templating;
using Xunit;
namespace LehrerApp.Desktop.Tests;
public sealed class StudentReportTests
{
private readonly Student _student = new() { FirstName = "Erika", LastName = "Beispiel" };
private readonly LearningGroup _group = new() { Name = "9 Ch G", SchoolYear = "2026/27" };
private readonly DateOnly _date = new(2026, 10, 1);
private readonly FakeDocumentation _docs = new();
private readonly FakeEntries _entries = new();
private readonly FakeAspects _aspects = new();
private readonly List<ParticipationSession> _sessions = [];
private StudentReportService Service() => new(new FakeSessions(_sessions), _entries, _aspects,
new FakeExams([]), new FakeResults(), new FakeGrades(), new FakeMemberships([]),
new FakeCompetencyDomains(), _docs, new GradingService(), new CompetencyAnalysisService());
private Dictionary<string, PlaceholderValue> Build(StudentReportOptions? options = null) => Service().Build(
_student, _group, StudentReportTemplate.Create(), options ?? new(_date, _date.AddMonths(1), null, IncludeInterim: false));
[Fact]
public void Dokumentation_IstAufSchuelerGruppeZeitraumUndFreigabeBegrenzt()
{
Documentation Doc(string title) => new() { StudentId = _student.Id, GroupId = _group.Id, Date = _date, Title = title };
_docs.Add(Doc("sichtbar"));
var confidential = Doc("vertraulich"); confidential.IsConfidential = true; _docs.Add(confidential);
var draft = Doc("Entwurf"); draft.IsDraft = true; _docs.Add(draft);
var deleted = Doc("gelöscht"); deleted.IsDeleted = true; _docs.Add(deleted);
var otherGroup = Doc("fremdeGruppe"); otherGroup.GroupId = Guid.NewGuid(); _docs.Add(otherGroup);
var otherStudent = Doc("fremderSchüler"); otherStudent.StudentId = Guid.NewGuid(); _docs.Add(otherStudent);
var outside = Doc("außerhalb"); outside.Date = _date.AddDays(-1); _docs.Add(outside);
var text = Text((DrawingValue)Build()[StudentReportTemplate.Documentation]);
Assert.Contains("sichtbar", text);
foreach (var hidden in new[] { "vertraulich", "Entwurf", "gelöscht", "fremdeGruppe", "fremderSchüler", "außerhalb" })
Assert.DoesNotContain(hidden, text);
var included = Build(new(_date, _date, null, IncludeInterim: false, IncludeConfidential: true));
Assert.Contains("[Vertraulich]", Text((DrawingValue)included[StudentReportTemplate.Documentation]));
}
[Fact]
public void Zwischenstand_MussZumSchuelerZurGruppeUndZumZeitraumPassen()
{
var interim = new InterimGrade { StudentId = _student.Id, GroupId = _group.Id, Date = _date,
Occasion = "Sprechtag", OralValue = "2", WrittenValue = "3", OverallValue = "2-3" };
var values = Build(new(_date, _date, interim));
Assert.Contains("2-3", Text((DrawingValue)values[ReportTextDrawing.InterimGrades]));
interim.StudentId = Guid.NewGuid();
Assert.Throws<InvalidDataException>(() => Build(new(_date, _date, interim)));
interim.StudentId = _student.Id; interim.GroupId = Guid.NewGuid();
Assert.Throws<InvalidDataException>(() => Build(new(_date, _date, interim)));
interim.GroupId = _group.Id; interim.Date = _date.AddDays(1);
Assert.Throws<InvalidDataException>(() => Build(new(_date, _date, interim)));
}
[Fact]
public void AbgewaehlteBausteineBleibenLeer()
{
var values = Build(new(_date, _date, null, false, false, false, false, false));
Assert.All(StudentReportTemplate.Drawings, name => Assert.Empty(((DrawingValue)values[name]).Commands));
}
[Fact]
public void Hausaufgaben_AltdatenUndFremdeSitzungen()
{
var session = new ParticipationSession { GroupId = _group.Id, Date = _date };
_sessions.Add(session);
_entries.Add(new() { StudentId = _student.Id, SessionId = session.Id, HomeworkMissing = true });
_entries.Add(new() { StudentId = _student.Id, SessionId = Guid.NewGuid(), Homework = HomeworkStatus.Completed });
var text = Text((DrawingValue)Build()[StudentReportTemplate.Homework]);
Assert.Contains("Nicht gemacht", text);
Assert.DoesNotContain("Hausaufgabe gemacht", text);
}
[Fact]
public void Standardbericht_RenderbarMitGraphUndMehrseitigerDokumentation()
{
_aspects.Save(new() { Key = "quality", Label = "Qualität", Weight = 1 });
for (var i = 0; i < 4; i++)
{
var session = new ParticipationSession { GroupId = _group.Id, Date = _date.AddDays(i) };
_sessions.Add(session);
_entries.Add(new() { StudentId = _student.Id, SessionId = session.Id,
Ratings = [new() { Key = "quality", Value = i - 2 }], Homework = HomeworkStatus.Completed });
}
for (var i = 0; i < 55; i++) _docs.Add(new() { StudentId = _student.Id, GroupId = _group.Id,
Date = _date, Title = $"Eintrag {i:D2}", Content = "Lange Beobachtung mit einem ausführlichen Text über die regelmäßige Mitarbeit im Unterricht und die Lernfortschritte." });
var pdf = new QuestTemplateRenderer().RenderToPdf(StudentReportTemplate.Create(), new ReportProvider(Build()));
using var document = UglyToad.PdfPig.PdfDocument.Open(pdf);
Assert.True(document.NumberOfPages > 1);
Assert.All(document.GetPages(), page => Assert.Contains(_student.FullName.Replace(" ", ""), page.Text.Replace(" ", "")));
var text = string.Concat(document.GetPages().Select(p => p.Text)).Replace(" ", "");
Assert.Contains(_student.FullName.Replace(" ", ""), text);
Assert.Contains("Lerngruppe:9ChG", text);
Assert.Contains("GewichteteMitarbeit", text);
Assert.Contains("Eintrag54", text);
Assert.Contains("Lernfortschritte.", text);
}
[Fact]
public async Task Dialog_UngueltigeDatumsangabenErzeugenKeineDatei()
{
var directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
try
{
var vm = new StudentReportDialogViewModel(_student,
new FakeMemberships([new() { StudentId = _student.Id, GroupId = _group.Id }]),
new FakeGroups([_group]), new FakeInterimGrades(), Service(), new QuestTemplateRenderer(),
new SchoolYearService(), [new TemplateStore(directory)]);
vm.From = "31.02.2026";
var output = Path.Combine(directory, "bericht.pdf");
Assert.False(await vm.GenerateAsync(output));
Assert.False(File.Exists(output));
Assert.Contains("TT.MM.JJJJ", vm.StatusMessage);
}
finally { if (Directory.Exists(directory)) Directory.Delete(directory, true); }
}
private sealed class ReportProvider(IReadOnlyDictionary<string, PlaceholderValue> values) : ITemplateDataProvider
{ public IReadOnlyDictionary<string, PlaceholderValue> GetValues() => values; }
private static string Text(DrawingValue drawing) => string.Join(" ", drawing.Commands.OfType<DrawStringEx>().Select(c => c.Text));
}
@@ -0,0 +1,181 @@
using LehrerApp.Core.Models;
using LehrerApp.Desktop.ViewModels.ClassTeacher;
using LehrerApp.Desktop.ViewModels.Students;
using Xunit;
namespace LehrerApp.Desktop.Tests;
/// Tests für den schülerbezogenen "Vorgänge"-Tab im Schülerdetail (StudentVorgaengeViewModel) —
/// der universelle, klassenübergreifende Einstiegspunkt für die Dashboard-Warnungen (Fehlzeiten,
/// Hausaufgaben-Rückstand, Verspätungen). Anders als ClassTeacherCasesViewModel keine
/// Roster-/WebUntis-Abhängigkeit, deshalb reine In-Memory-Fakes ohne Untis-Cache-Setup.
public sealed class StudentVorgaengeViewModelTests
{
[Fact]
public async Task BestehenderAkteneintrag_KannNachtraeglichVerknuepftUndWiederGeloestWerden()
{
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
var doc = new Documentation { StudentId = student.Id, Title = "Bericht" };
var documentation = new FakeDocumentation();
documentation.Add(doc);
var vorgaenge = new FakeVorgangRepository();
var vorgang = new Vorgang { Title = "Vorgang", StudentIds = [student.Id] };
vorgaenge.Add(vorgang);
var vm = BuildVm(vorgaenge, documentation, new FakeStudents([student]));
vm.Load(student.Id);
var item = Assert.Single(vm.Cases);
item.IsRevealed = true;
var available = Assert.Single(item.AvailableDocumentation);
var notifications = new List<string?>();
item.PropertyChanged += (_, e) => notifications.Add(e.PropertyName);
// Die View bindet schon vor dem Befuellen der Collections an diese Eigenschaften.
item.AvailableDocumentation.Clear();
Assert.Contains(nameof(VorgangItem.HasAvailableDocumentation), notifications);
Assert.False(item.HasAvailableDocumentation);
item.AvailableDocumentation.Add(available);
Assert.True(item.HasAvailableDocumentation);
await item.LinkCommand.ExecuteAsync(available);
var linked = Assert.Single(vm.Cases);
Assert.True(linked.IsRevealed);
Assert.True(linked.HasLinkedDocumentation);
Assert.False(linked.HasAvailableDocumentation);
Assert.Equal(doc.Id, Assert.Single(linked.LinkedDocumentation).Model.Id);
Assert.Contains(doc.Id, vorgaenge.GetById(vorgang.Id)!.DocumentationIds);
await linked.UnlinkCommand.ExecuteAsync(linked.LinkedDocumentation[0]);
var unlinked = Assert.Single(vm.Cases);
Assert.False(unlinked.HasLinkedDocumentation);
Assert.True(unlinked.HasAvailableDocumentation);
Assert.Empty(vorgaenge.GetById(vorgang.Id)!.DocumentationIds);
Assert.Equal(doc.Id, Assert.Single(documentation.GetByStudent(student.Id)).Id);
}
private static StudentVorgaengeViewModel BuildVm(FakeVorgangRepository? vorgaenge = null,
FakeDocumentation? documentation = null, FakeStudents? students = null) =>
new(vorgaenge ?? new FakeVorgangRepository(), documentation ?? new FakeDocumentation(),
students ?? new FakeStudents([]));
[Fact]
public void Load_ZeigtNurVorgaengeDiesesSchuelers()
{
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
var other = new Student { FirstName = "Ben", LastName = "Fremd" };
var vorgaenge = new FakeVorgangRepository();
vorgaenge.Add(new Vorgang { Title = "Eigener Vorgang", StudentIds = [student.Id] });
vorgaenge.Add(new Vorgang { Title = "Fremder Vorgang", StudentIds = [other.Id] });
var vm = BuildVm(vorgaenge: vorgaenge, students: new FakeStudents([student, other]));
vm.Load(student.Id);
var item = Assert.Single(vm.Cases);
Assert.Equal("Eigener Vorgang", item.Model.Title);
}
[Fact]
public void Load_OnlyOpenFiltertGeschlosseneVorgaenge()
{
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
var vorgaenge = new FakeVorgangRepository();
vorgaenge.Add(new Vorgang { Title = "Offen", StudentIds = [student.Id], Status = VorgangStatus.Open });
vorgaenge.Add(new Vorgang { Title = "Geschlossen", StudentIds = [student.Id], Status = VorgangStatus.Closed });
var vm = BuildVm(vorgaenge: vorgaenge, students: new FakeStudents([student]));
vm.Load(student.Id);
Assert.Equal("Offen", Assert.Single(vm.Cases).Model.Title);
vm.OnlyOpen = false;
Assert.Equal(2, vm.Cases.Count);
}
[Fact]
public async Task HandleWarningNavigation_RevealtBestehendenOffenenVorgangMitPassendemTag_OhneRueckfrage()
{
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
var vorgaenge = new FakeVorgangRepository();
vorgaenge.Add(new Vorgang { Title = "Fehlzeiten", StudentIds = [student.Id], Tags = ["Absentismus"] });
var vm = BuildVm(vorgaenge: vorgaenge, students: new FakeStudents([student]));
vm.Load(student.Id);
var confirmCalled = false;
vm.OnConfirmCreateForWarning = _ => { confirmCalled = true; return Task.FromResult(true); };
await vm.HandleWarningNavigation("Absentismus", "Fehlzeiten");
Assert.False(confirmCalled);
Assert.True(Assert.Single(vm.Cases).IsRevealed);
}
[Fact]
public async Task HandleWarningNavigation_IgnoriertGeschlosseneVorgaengeMitPassendemTag()
{
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
var vorgaenge = new FakeVorgangRepository();
vorgaenge.Add(new Vorgang
{ Title = "Alt", StudentIds = [student.Id], Tags = ["Absentismus"], Status = VorgangStatus.Closed });
var vm = BuildVm(vorgaenge: vorgaenge, students: new FakeStudents([student]));
vm.Load(student.Id); // OnlyOpen=true (Default) -> der geschlossene Vorgang ist gar nicht in Cases
var confirmCalled = false;
vm.OnConfirmCreateForWarning = _ => { confirmCalled = true; return Task.FromResult(false); };
vm.OnEditVorgang = (_, _) => Task.FromResult<Vorgang?>(null);
await vm.HandleWarningNavigation("Absentismus", "Fehlzeiten");
Assert.True(confirmCalled);
}
[Fact]
public async Task HandleWarningNavigation_KeinPassenderVorgang_FragtNachUndLegtAnBeiZustimmung()
{
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
var vorgaenge = new FakeVorgangRepository();
var vm = BuildVm(vorgaenge: vorgaenge, students: new FakeStudents([student]));
vm.Load(student.Id);
string? confirmedTag = null;
vm.OnConfirmCreateForWarning = tag => { confirmedTag = tag; return Task.FromResult(true); };
List<StudentOption>? passedOptions = null;
Vorgang? passedDraft = null;
vm.OnEditVorgang = (options, editing) =>
{
passedOptions = options;
passedDraft = editing;
return Task.FromResult(editing);
};
await vm.HandleWarningNavigation("Hausaufgaben", "Hausaufgaben");
Assert.Equal("Hausaufgaben", confirmedTag);
Assert.Equal(student.Id, Assert.Single(passedOptions!).Id);
Assert.Equal("Hausaufgaben", passedDraft!.Title);
Assert.Contains("Hausaufgaben", passedDraft.Tags);
Assert.Equal([student.Id], passedDraft.StudentIds);
var created = Assert.Single(vorgaenge.GetAll());
Assert.Equal("Hausaufgaben", created.Title);
Assert.True(Assert.Single(vm.Cases).IsRevealed);
}
[Fact]
public async Task HandleWarningNavigation_KeinPassenderVorgang_LegtNichtsAnBeiAblehnung()
{
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
var vorgaenge = new FakeVorgangRepository();
var vm = BuildVm(vorgaenge: vorgaenge, students: new FakeStudents([student]));
vm.Load(student.Id);
vm.OnConfirmCreateForWarning = _ => Task.FromResult(false);
var editDialogCalled = false;
vm.OnEditVorgang = (_, _) => { editDialogCalled = true; return Task.FromResult<Vorgang?>(null); };
await vm.HandleWarningNavigation("Verspätungen", "Verspätungen");
Assert.False(editDialogCalled);
Assert.Empty(vorgaenge.GetAll());
Assert.Empty(vm.Cases);
}
}
@@ -0,0 +1,199 @@
using LehrerApp.Core.Models;
using LehrerApp.Core.Services;
using LehrerApp.Desktop.Services;
using LehrerApp.Desktop.ViewModels;
using LehrerApp.Desktop.ViewModels.ClassTeacher;
using LehrerApp.Desktop.ViewModels.Students;
using Xunit;
namespace LehrerApp.Desktop.Tests;
/// Tests für die Belege hinter den klassenübergreifenden Dashboard-Warnungen: das Detail-Popup
/// (StudentWarningDetailViewModel), die Schnellbausteine im Vorgang-Dialog und die
/// Dokumentationsvorlagen im schülerbezogenen Vorgänge-Tab. Alle Termine liegen ab
/// Schuljahresbeginn, damit die Tests unabhängig vom Ausführungsdatum im laufenden Schuljahr landen.
public sealed class StudentWarningEvidenceTests
{
private readonly Student _student = new() { FirstName = "Anna", LastName = "Beispiel" };
private readonly LearningGroup _group = new() { Name = "9c Mathe" };
private readonly List<ParticipationSession> _sessions = [];
private readonly FakeEntries _entries = new();
private readonly DateOnly _start;
public StudentWarningEvidenceTests()
{
var sy = new SchoolYearService();
_start = sy.SchoolYearStart(sy.CurrentSchoolYear());
}
private void AddEntry(int dayOffset, AttendanceStatus? attendance = null, HomeworkStatus? homework = null)
{
var session = new ParticipationSession { GroupId = _group.Id, Date = _start.AddDays(dayOffset) };
_sessions.Add(session);
_entries.Add(new ParticipationEntry
{ SessionId = session.Id, StudentId = _student.Id, Attendance = attendance, Homework = homework });
}
private StudentWarningEvidenceService BuildService() => new(new FakeStudents([_student]),
new FakeSessions(_sessions), _entries, new FakeGroups([_group]), new SchoolYearService(),
new AttendanceBalanceService());
[Fact]
public void Build_ZaehltWieDieDashboardWarnungen()
{
AddEntry(0, AttendanceStatus.Present);
AddEntry(1, AttendanceStatus.Excused);
AddEntry(2, AttendanceStatus.Unexcused);
AddEntry(3, AttendanceStatus.ExcusePending);
AddEntry(4, AttendanceStatus.OtherSchoolEvent);
AddEntry(5, AttendanceStatus.Late, HomeworkStatus.MissingOpen);
AddEntry(6, AttendanceStatus.SignificantlyLate, HomeworkStatus.Completed);
var e = BuildService().Build(_student.Id);
Assert.Equal(7, e.Balance.TotalChecked);
Assert.Equal(3, e.Absences.Count); // Schulveranstaltung zählt nicht als Fehlzeit
Assert.Equal(["A", "U", "E"], e.Absences.Select(a => a.Code)); // neueste zuerst
Assert.Equal(2, e.Lateness.Count);
Assert.Equal(1, e.SignificantlyLateCount);
Assert.Equal("9c Mathe", Assert.Single(e.MissingHomework).GroupName);
Assert.Equal("Anna Beispiel", e.StudentNaturalName);
}
[Fact]
public void QuickBlocks_NurBausteineMitInhalt()
{
AddEntry(0, AttendanceStatus.Unexcused);
AddEntry(1, AttendanceStatus.Present);
var blocks = StudentEvidenceText.QuickBlocks(BuildService().Build(_student.Id));
Assert.Equal(["Fehlquote", "Fehltermine"], blocks.Select(b => b.Label));
Assert.Contains("Fehlquote 50 %", blocks[0].Text);
Assert.Contains("9c Mathe", blocks[1].Text);
}
[Fact]
public void VorgangDialog_InsertQuickBlock_HaengtAnStattZuErsetzen()
{
var vm = new VorgangDialogViewModel([new StudentOption(_student.Id, "Anna")], null,
[new VorgangQuickBlock("Fehlquote", "Stand: 25 %")]) { Description = "Eigene Notiz" };
vm.InsertQuickBlockCommand.Execute(vm.QuickBlocks[0]);
Assert.Equal("Eigene Notiz\n\nStand: 25 %", vm.Description);
Assert.Equal("Vorgang anlegen", vm.DialogTitle);
}
[Fact]
public void Vorlage_ElternanrufUebernimmtZahlenPassendZumVorgangsTag()
{
for (var i = 0; i < 3; i++) AddEntry(i, AttendanceStatus.Present, HomeworkStatus.MissingOverdue);
var vorgang = new Vorgang { Title = "Hausaufgaben", StudentIds = [_student.Id], Tags = ["Hausaufgaben"] };
var doc = VorgangDocumentationTemplates.Build(VorgangDocumentationTemplates.ParentCall, vorgang,
BuildService().Build(_student.Id))!;
Assert.Equal(DocumentationType.ParentCall, doc.Type);
Assert.Equal(_student.Id, doc.StudentId);
Assert.StartsWith("Aktueller Stand: 3 nicht bzw. unvollständig erledigte Hausaufgaben", doc.ParentCallData!.Points[0].Text);
Assert.DoesNotContain(doc.ParentCallData.Points, p => p.Text.Contains("Fehlquote"));
}
[Fact]
public void DetailPopup_StartetImMonatDesJuengstenBelegsUndZeigtKuerzel()
{
AddEntry(0, AttendanceStatus.Unexcused);
AddEntry(0, AttendanceStatus.Excused); // zweite Stunde am selben Tag: U gewinnt
AddEntry(1, AttendanceStatus.Late);
var vm = new StudentWarningDetailViewModel(AttentionKind.Attendance, BuildService().Build(_student.Id));
Assert.Equal(new DateOnly(_start.Year, _start.Month, 1), vm.Month);
var first = vm.CalendarDays.Single(d => d.Date == _start);
Assert.Equal("U", first.SignalCode);
Assert.Contains("Krank, entschuldigt", first.Tooltip);
Assert.Equal("V", vm.CalendarDays.Single(d => d.Date == _start.AddDays(1)).SignalCode);
Assert.False(vm.PreviousMonthCommand.CanExecute(null)); // vor Schuljahresbeginn gibt es nichts
Assert.Equal(2, vm.Events.Count);
}
[Fact]
public async Task HandleWarningNavigation_BelegtBeschreibungMitAktuellemStandVor()
{
for (var i = 0; i < 4; i++) AddEntry(i, AttendanceStatus.Unexcused);
var vm = new StudentVorgaengeViewModel(new FakeVorgangRepository(), new FakeDocumentation(),
new FakeStudents([_student]), BuildService());
vm.Load(_student.Id);
vm.OnConfirmCreateForWarning = _ => Task.FromResult(true);
Vorgang? draft = null;
vm.OnEditVorgang = (_, editing) => { draft = editing; return Task.FromResult<Vorgang?>(null); };
await vm.HandleWarningNavigation("Absentismus", "Fehlzeiten");
Assert.Contains("Fehlquote 100 %", draft!.Description);
Assert.Contains("Fehltermine:", draft.Description);
Assert.False(vm.IsPersisted(draft));
}
[Fact]
public async Task GemeinsamerVorgang_DokumentationFuerMehrereErscheintAuchBeimZweitenSchueler()
{
var ben = new Student { FirstName = "Ben", LastName = "Muster" };
var students = new FakeStudents([_student, ben]);
var vorgaenge = new FakeVorgangRepository();
var vorgang = new Vorgang { Title = "Streit", StudentIds = [_student.Id, ben.Id], Tags = ["Konflikte"] };
vorgaenge.Add(vorgang);
var documentation = new FakeDocumentation();
var vm = new StudentVorgaengeViewModel(vorgaenge, documentation, students);
vm.Load(_student.Id);
List<StudentOption> offered = [];
vm.OnEditDocumentation = (studentId, coStudents, _) =>
{
offered = coStudents;
return Task.FromResult<Documentation?>(new Documentation
{
StudentId = studentId, AdditionalStudentIds = [ben.Id], Title = "Gespräch mit beiden",
});
};
await vm.CreateAndLinkDocumentationCommand.ExecuteAsync(Assert.Single(vm.Cases));
Assert.Equal([_student.Id, ben.Id], offered.Select(o => o.Id));
var benView = new StudentVorgaengeViewModel(vorgaenge, documentation, students);
benView.Load(ben.Id);
var linked = Assert.Single(Assert.Single(benView.Cases).LinkedDocumentation);
Assert.Equal("Gespräch mit beiden", linked.Model.Title);
Assert.Contains("Muster", linked.StudentName);
Assert.Contains("Beispiel", linked.StudentName);
}
[Fact]
public async Task VorlageAusVorgangstab_OeffnetEntwurfUndVerknuepftNachSpeichern()
{
AddEntry(0, AttendanceStatus.Unexcused);
var vorgaenge = new FakeVorgangRepository();
var vorgang = new Vorgang { Title = "Fehlzeiten", StudentIds = [_student.Id], Tags = ["Absentismus"] };
vorgaenge.Add(vorgang);
var documentation = new FakeDocumentation();
var vm = new StudentVorgaengeViewModel(vorgaenge, documentation, new FakeStudents([_student]), BuildService());
vm.Load(_student.Id);
var wasDraft = false;
vm.OnEditDocumentation = (_, _, editing) =>
{
wasDraft = vm.IsNewDocumentationDraft(editing!);
return Task.FromResult(editing);
};
var item = Assert.Single(vm.Cases);
Assert.True(item.HasDocumentationTemplates);
await item.CreateFromTemplateCommand.ExecuteAsync(VorgangDocumentationTemplates.Conversation);
Assert.True(wasDraft);
var saved = Assert.Single(documentation.GetByStudent(_student.Id));
Assert.Equal(DocumentationType.Conversation, saved.Type);
Assert.Contains("Fehlquote 100 %", saved.Content);
Assert.Contains(saved.Id, vorgang.DocumentationIds);
Assert.True(Assert.Single(vm.Cases).IsRevealed);
}
}
@@ -1,6 +1,7 @@
using System.Net; using System.Net;
using System.Net.Http.Json; using System.Net.Http.Json;
using LehrerApp.Data; using LehrerApp.Data;
using LehrerApp.Desktop.Services;
using LehrerApp.Desktop.ViewModels; using LehrerApp.Desktop.ViewModels;
using LehrerApp.Sync; using LehrerApp.Sync;
using LehrerApp.Sync.Crypto; using LehrerApp.Sync.Crypto;
@@ -80,6 +81,39 @@ public sealed class SyncStatusViewModelTests
Assert.Contains("Bitte aktualisiere die LehrerApp", SyncStatusViewModel.IncompatibleVersionMessage); Assert.Contains("Bitte aktualisiere die LehrerApp", SyncStatusViewModel.IncompatibleVersionMessage);
} }
/// Regression: ein Sync-Ausfall (z.B. Server nicht erreichbar) war früher nur an einem
/// blassen "Offline"-Text in der Statuszeile erkennbar - ein Gerät konnte so stundenlang
/// unbemerkt nicht synchronisieren. NotificationService bekommt jetzt aktiv eine Meldung,
/// sobald der Status neu auf Offline/Error wechselt.
[Fact]
public async Task SyncOffline_MeldetSichAktivUeberNotificationService()
{
using var temp = new TempSyncEngine(new OfflineStubHandler());
var notifications = new NotificationService();
var vm = new SyncStatusViewModel(temp.Engine, notifications);
await temp.Engine.SyncNowAsync();
Assert.Equal("Offline", vm.StatusText);
Assert.Single(notifications.Toasts);
Assert.Equal(SyncStatusViewModel.OfflineMessage, notifications.Toasts[0].Message);
}
/// Ein erneuter automatischer Retry im selben Offline-Zustand darf keinen weiteren Toast
/// auslösen - sonst würde der Nutzer alle paar Minuten dieselbe Meldung sehen.
[Fact]
public async Task SyncOffline_WiederholterRetry_MeldetNurEinmal()
{
using var temp = new TempSyncEngine(new OfflineStubHandler());
var notifications = new NotificationService();
var vm = new SyncStatusViewModel(temp.Engine, notifications);
await temp.Engine.SyncNowAsync();
await temp.Engine.SyncNowAsync();
Assert.Single(notifications.Toasts);
}
private sealed class PullEventStubHandler : HttpMessageHandler private sealed class PullEventStubHandler : HttpMessageHandler
{ {
protected override Task<HttpResponseMessage> SendAsync( protected override Task<HttpResponseMessage> SendAsync(
@@ -113,6 +147,13 @@ public sealed class SyncStatusViewModelTests
}); });
} }
private sealed class OfflineStubHandler : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken) =>
Task.FromResult(new HttpResponseMessage(HttpStatusCode.Unauthorized));
}
private sealed class IncompatibleVersionStubHandler : HttpMessageHandler private sealed class IncompatibleVersionStubHandler : HttpMessageHandler
{ {
protected override Task<HttpResponseMessage> SendAsync( protected override Task<HttpResponseMessage> SendAsync(
@@ -0,0 +1,160 @@
using LehrerApp.Core.Models;
using LehrerApp.Desktop.ViewModels.Groups;
using Xunit;
namespace LehrerApp.Desktop.Tests;
public sealed class TeachingModeOutstandingHomeworkViewModelTests
{
[Fact]
public void Refresh_ZeigtJungeOffeneNachreichungenUndFiltertAktuellAbwesende()
{
var date = new DateOnly(2026, 9, 25);
var group = new LearningGroup { Name = "10c Chemie" };
var amelia = new Student { FirstName = "Amelia", LastName = "Gerste" };
var ben = new Student { FirstName = "Ben", LastName = "Muster" };
var carl = new Student { FirstName = "Carl", LastName = "Beispiel" };
var oldMember = new Student { FirstName = "Dana", LastName = "Alt" };
var previous = new ParticipationSession { GroupId = group.Id, Date = date.AddDays(-5) };
var older = new ParticipationSession { GroupId = group.Id, Date = date.AddDays(-130) };
var current = new ParticipationSession { GroupId = group.Id, Date = date };
var memberships = new FakeMemberships([
new GroupMembership { StudentId = amelia.Id, GroupId = group.Id },
new GroupMembership { StudentId = ben.Id, GroupId = group.Id },
new GroupMembership { StudentId = carl.Id, GroupId = group.Id },
new GroupMembership { StudentId = oldMember.Id, GroupId = group.Id,
Period = MembershipPeriod.Custom, JoinedAt = date.AddDays(-30), LeftAt = date.AddDays(-1) },
]);
var entries = new FakeEntries();
entries.Add(new ParticipationEntry { SessionId = previous.Id, StudentId = amelia.Id,
Homework = HomeworkStatus.MissingOverdue });
var benEntry = new ParticipationEntry { SessionId = previous.Id, StudentId = ben.Id,
Homework = HomeworkStatus.MissingOpen };
entries.Add(benEntry);
entries.Add(new ParticipationEntry { SessionId = previous.Id, StudentId = carl.Id,
Homework = HomeworkStatus.SubmittedLate });
entries.Add(new ParticipationEntry { SessionId = previous.Id, StudentId = oldMember.Id,
Homework = HomeworkStatus.MissingOverdue });
entries.Add(new ParticipationEntry { SessionId = older.Id, StudentId = ben.Id,
Homework = HomeworkStatus.MissingOverdue });
entries.Add(new ParticipationEntry { SessionId = current.Id, StudentId = ben.Id,
Attendance = AttendanceStatus.Present });
entries.Add(new ParticipationEntry { SessionId = current.Id, StudentId = amelia.Id,
Attendance = AttendanceStatus.ExcusePending });
var vm = new TeachingModeOutstandingHomeworkViewModel(group.Id, date,
new FakeStudents([amelia, ben, carl, oldMember]), memberships,
new FakeSessions([previous, older, current]), entries);
vm.SetCurrentSessionId(current.Id);
vm.IsExpanded = true;
Assert.Equal(ben.FullName, Assert.Single(vm.Rows).StudentName);
Assert.Equal("Offene Nachreichungen (1)", vm.Header);
vm.IncludeAbsentStudents = true;
Assert.Equal(2, vm.Rows.Count);
Assert.Contains(vm.Rows, r => r.StudentName == amelia.FullName &&
r.Status == HomeworkStatus.MissingOverdue);
vm.IncludeAbsentStudents = false;
var currentAmelia = entries.GetBySessionAndStudent(current.Id, amelia.Id)!;
currentAmelia.Attendance = AttendanceStatus.Present;
entries.Save(currentAmelia);
vm.Refresh();
Assert.Equal(2, vm.Rows.Count);
benEntry.Homework = HomeworkStatus.SubmittedLate;
entries.Save(benEntry);
vm.Refresh();
Assert.Equal(amelia.FullName, Assert.Single(vm.Rows).StudentName);
}
[Theory]
[InlineData(HomeworkStatus.MissingOpen, "submitted", HomeworkStatus.SubmittedLate)]
[InlineData(HomeworkStatus.MissingOpen, "final", HomeworkStatus.MissingOverdue)]
[InlineData(HomeworkStatus.MissingOpen, "partial", HomeworkStatus.PartialMissingOverdue)]
[InlineData(HomeworkStatus.MissingOverdue, "submitted", HomeworkStatus.SubmittedLate)]
[InlineData(HomeworkStatus.PartiallyCompleted, "submitted", HomeworkStatus.PartialSubmittedLate)]
[InlineData(HomeworkStatus.PartiallyCompleted, "final", HomeworkStatus.PartialMissingOverdue)]
[InlineData(HomeworkStatus.PartialMissingOverdue, "submitted", HomeworkStatus.PartialSubmittedLate)]
public void Zeilenaktionen_SetzenPassendenEndstatus(HomeworkStatus start, string action, HomeworkStatus expected)
{
var (vm, entries, entry) = CreateSingle(start);
vm.Refresh();
var row = Assert.Single(vm.Rows);
var command = action switch
{
"submitted" => row.MarkSubmittedCommand,
"final" => row.MarkFinalCommand,
_ => row.MarkPartialCommand,
};
command.Execute(null);
var saved = entries.GetBySessionAndStudent(entry.SessionId, entry.StudentId)!;
Assert.Equal(expected, saved.Homework);
Assert.Equal(HomeworkDisplay.CountsAsMissing(expected), saved.HomeworkMissing);
Assert.Equal(HomeworkDisplay.CountsAsMissing(expected), vm.Rows.Count == 1);
}
[Fact]
public void Zeilenaktionen_BietenNurSinnvolleOptionenAn()
{
var (vm, _, _) = CreateSingle(HomeworkStatus.MissingOverdue);
vm.Refresh();
var overdue = Assert.Single(vm.Rows);
Assert.False(overdue.CanMarkFinal);
Assert.True(overdue.CanMarkPartial);
(vm, _, _) = CreateSingle(HomeworkStatus.PartiallyCompleted);
vm.Refresh();
var partial = Assert.Single(vm.Rows);
Assert.True(partial.CanMarkFinal);
Assert.False(partial.CanMarkPartial);
(vm, _, _) = CreateSingle(HomeworkStatus.MissingOpen, isReadOnly: true);
vm.Refresh();
Assert.False(Assert.Single(vm.Rows).CanEdit);
}
[Fact]
public void Undo_StelltVorherigenStatusWiederHer()
{
var (vm, entries, entry) = CreateSingle(HomeworkStatus.MissingOpen);
var changed = 0;
vm.OnHomeworkChanged = () => changed++;
vm.Refresh();
Assert.False(vm.UndoCommand.CanExecute(null));
vm.Rows[0].MarkSubmittedCommand.Execute(null);
Assert.Empty(vm.Rows);
Assert.NotNull(vm.LastChangeLabel);
Assert.True(vm.UndoCommand.CanExecute(null));
vm.UndoCommand.Execute(null);
var saved = entries.GetBySessionAndStudent(entry.SessionId, entry.StudentId)!;
Assert.Equal(HomeworkStatus.MissingOpen, saved.Homework);
Assert.True(saved.HomeworkMissing);
Assert.Single(vm.Rows);
Assert.Null(vm.LastChangeLabel);
Assert.False(vm.UndoCommand.CanExecute(null));
Assert.Equal(2, changed);
}
private static (TeachingModeOutstandingHomeworkViewModel Vm, FakeEntries Entries, ParticipationEntry Entry)
CreateSingle(HomeworkStatus status, bool isReadOnly = false)
{
var date = new DateOnly(2026, 9, 25);
var group = new LearningGroup { Name = "10c Chemie" };
var student = new Student { FirstName = "Ben", LastName = "Muster" };
var session = new ParticipationSession { GroupId = group.Id, Date = date.AddDays(-5) };
var entries = new FakeEntries();
var entry = new ParticipationEntry { SessionId = session.Id, StudentId = student.Id,
Homework = status, HomeworkMissing = true };
entries.Add(entry);
var vm = new TeachingModeOutstandingHomeworkViewModel(group.Id, date,
new FakeStudents([student]),
new FakeMemberships([new GroupMembership { StudentId = student.Id, GroupId = group.Id }]),
new FakeSessions([session]), entries, isReadOnly);
return (vm, entries, entry);
}
}
@@ -64,6 +64,44 @@ public sealed class TimetableViewModelTests
Assert.Equal(6 + 10 * 6, vm.WeekItems.Count); Assert.Equal(6 + 10 * 6, vm.WeekItems.Count);
} }
[Fact]
public void Load_MarkiertDieAktuelleStundeAusDemHinterlegtenStundenraster()
{
var tempPath = Path.Combine(Path.GetTempPath(), $"lehrerapp-currentperiod-tests-{Guid.NewGuid():N}");
Directory.CreateDirectory(tempPath);
var schedule = new PeriodScheduleService(tempPath);
schedule.SetPeriods([
new PeriodTimeEntry { PeriodNumber = 2, Start = new TimeOnly(8, 0), End = new TimeOnly(8, 45) },
new PeriodTimeEntry { PeriodNumber = 3, Start = new TimeOnly(9, 0), End = new TimeOnly(9, 45) },
]);
var vm = BuildViewModel(new FakeTimetableSlots(), new FakeGroups([]), periodSchedule: schedule);
vm.Clock = () => new DateTime(2026, 9, 21, 9, 15, 0); // Montag, 3. Stunde
vm.Load();
var periodLabels = vm.WeekItems.Where(x => x.IsPeriodLabel).ToList();
Assert.True(periodLabels.Single(x => x.PeriodNumber == 3).IsCurrentPeriod);
Assert.DoesNotContain(periodLabels, x => x.PeriodNumber != 3 && x.IsCurrentPeriod);
}
[Fact]
public void Load_InAndererKalenderwoche_MarkiertKeineAktuelleStunde()
{
var tempPath = Path.Combine(Path.GetTempPath(), $"lehrerapp-currentperiod-tests-{Guid.NewGuid():N}");
Directory.CreateDirectory(tempPath);
var schedule = new PeriodScheduleService(tempPath);
schedule.SetPeriods([
new PeriodTimeEntry { PeriodNumber = 3, Start = new TimeOnly(9, 0), End = new TimeOnly(9, 45) },
]);
var vm = BuildViewModel(new FakeTimetableSlots(), new FakeGroups([]), periodSchedule: schedule);
vm.Clock = () => new DateTime(2026, 9, 21, 9, 15, 0);
vm.WeekOffset = 1;
vm.Load();
Assert.DoesNotContain(vm.WeekItems, x => x.IsCurrentPeriod);
}
[Fact] [Fact]
public void Load_ZeigtZugewieseneGruppeInDerPassendenZelle() public void Load_ZeigtZugewieseneGruppeInDerPassendenZelle()
{ {
@@ -69,4 +69,16 @@ public sealed class UntisComparisonToolsTests
Assert.Contains("row-id", result.Message); Assert.Contains("row-id", result.Message);
Assert.Equal(0, confirmation.CallCount); // erst gar nicht bis zur Bestätigung vorgedrungen Assert.Equal(0, confirmation.CallCount); // erst gar nicht bis zur Bestätigung vorgedrungen
} }
[Fact]
public async Task ApplyUntisAbsenceStatus_ErheblichVerspaetet_IstZulaessigerZielstatus()
{
var tool = Build();
var result = await tool.ApplyUntisAbsenceStatus(
"nie-vergeben", nameof(AttendanceStatus.SignificantlyLate));
Assert.False(result.Applied);
Assert.Contains("row-id", result.Message); // Statusvalidierung wurde erfolgreich passiert
}
} }
@@ -0,0 +1,61 @@
using LehrerApp.Core.Models;
using LehrerApp.Desktop.Services;
using Xunit;
namespace LehrerApp.Desktop.Tests;
public sealed class UntisLessonAbsenceHelperTests
{
[Theory]
[InlineData(0, AttendanceStatus.Late)]
[InlineData(9, AttendanceStatus.Late)]
[InlineData(10, AttendanceStatus.SignificantlyLate)]
[InlineData(44, AttendanceStatus.SignificantlyLate)]
public void MapStatus_StaffeltVerspaetungAbZehnMinuten(
int absentMinutes, AttendanceStatus expected)
{
Assert.Equal(expected, UntisLessonAbsenceHelper.MapStatus(Absence(absentMinutes)));
}
[Fact]
public void MatchesUntisStatus_ErheblichVerspaetetAkzeptiertAllgemeinesUntisVerspaetet()
{
var matches = UntisLessonAbsenceHelper.MatchesUntisStatus(
AttendanceStatus.SignificantlyLate, AttendanceStatus.Late);
Assert.True(matches);
}
[Fact]
public void MatchesUntisStatus_NachgereichteEntschuldigungBleibtAenderung()
{
var matches = UntisLessonAbsenceHelper.MatchesUntisStatus(
AttendanceStatus.SignificantlyLate, AttendanceStatus.Excused);
Assert.False(matches);
}
[Fact]
public void MatchesUntisStatus_IstFuerVerspaetungsPraezisierungGerichtet()
{
var matches = UntisLessonAbsenceHelper.MatchesUntisStatus(
AttendanceStatus.Late, AttendanceStatus.SignificantlyLate);
Assert.False(matches);
}
[Theory]
[InlineData(AttendanceStatus.Late)]
[InlineData(AttendanceStatus.SignificantlyLate)]
[InlineData(AttendanceStatus.ExcusePending)]
[InlineData(AttendanceStatus.Excused)]
[InlineData(AttendanceStatus.Unexcused)]
public void MatchesUntisStatus_GleicherStatusPasst(AttendanceStatus status)
{
Assert.True(UntisLessonAbsenceHelper.MatchesUntisStatus(status, status));
}
private static UntisLessonAbsenceDto Absence(int absentMinutes) => new(
"Testschüler", 20260925, 1, 0, absentMinutes, 0, 800, 845,
"Verspätung", 1, false, null, true);
}
@@ -1,4 +1,5 @@
using LehrerApp.Desktop.ViewModels.ClassTeacher; using LehrerApp.Desktop.ViewModels.ClassTeacher;
using LehrerApp.Core.Models;
using Xunit; using Xunit;
namespace LehrerApp.Desktop.Tests; namespace LehrerApp.Desktop.Tests;
@@ -9,6 +10,8 @@ public sealed class UntisNameMatchingTests
[InlineData("Ben Schmidt", "Schmidt Ben")] [InlineData("Ben Schmidt", "Schmidt Ben")]
[InlineData("Ada Müller", "MÜLLER ADA")] [InlineData("Ada Müller", "MÜLLER ADA")]
[InlineData("Max Mustermann", "mustermann max")] [InlineData("Max Mustermann", "mustermann max")]
[InlineData("Gerste, Amelia", "Gerste Amelia")]
[InlineData("Müller-Ada", "Ada Müller")]
public void NamesMatch_IstReihenfolgeUndGrossKleinschreibungUnabhaengig(string a, string b) => public void NamesMatch_IstReihenfolgeUndGrossKleinschreibungUnabhaengig(string a, string b) =>
Assert.True(UntisNameMatching.NamesMatch(a, b)); Assert.True(UntisNameMatching.NamesMatch(a, b));
@@ -19,17 +22,39 @@ public sealed class UntisNameMatchingTests
public void NamesMatch_LehntUnterschiedlicheOderFehlendeNamenAb(string? a, string b) => public void NamesMatch_LehntUnterschiedlicheOderFehlendeNamenAb(string? a, string b) =>
Assert.False(UntisNameMatching.NamesMatch(a, b)); Assert.False(UntisNameMatching.NamesMatch(a, b));
// Regression: Student.FullName liefert "Nachname, Vorname" (mit Komma) für Anzeigezwecke. // Regression: Student.FullName liefert "Nachname, Vorname" (mit Komma), während WebUntis
// Wird dieser String direkt an NamesMatch übergeben, bleibt das Komma am Wort kleben // denselben Namen je nach Bericht ohne Komma und in wechselnder Reihenfolge liefert.
// ("gerste," != "gerste") und der Abgleich gegen WebUntis-Namen (immer ohne Komma) schlägt
// fehl - genau das ließ den Anwesenheitskalender/die Fehlzeitenliste im Elternbrief leer
// bleiben, obwohl echte Fehlzeiten vorlagen. Aufrufer müssen deshalb "Vorname Nachname" ohne
// Komma bilden (siehe StudentAttendanceCalendarDrawingBuilder.StudentAttendanceCalendarService
// und ClassTeacherOverviewViewModel.cs:1173), statt Student.FullName direkt zu verwenden.
[Fact] [Fact]
public void NamesMatch_KommaGetrennterAnzeigename_PasstNichtOhneUmformung() public void NamesMatch_KommaGetrennterAnzeigename_PasstZumUntisNamenOhneKomma()
{ {
Assert.False(UntisNameMatching.NamesMatch("Gerste, Amelia", "Gerste Amelia")); Assert.True(UntisNameMatching.NamesMatch("Gerste, Amelia", "Gerste Amelia"));
Assert.True(UntisNameMatching.NamesMatch("Amelia Gerste", "Gerste Amelia")); }
[Fact]
public void BuildClassNameIndex_VerwendetDieselbeInstanzWieDieAuswahlliste()
{
var candidate = new Student { FirstName = "Amelia", LastName = "Gerste" };
var repositoryCopy = new Student
{
Id = candidate.Id, FirstName = candidate.FirstName, LastName = candidate.LastName,
};
var index = UntisNameMatching.BuildClassNameIndex([candidate], [repositoryCopy]);
Assert.Same(candidate, index[UntisNameMatching.NameKey("Gerste Amelia")]);
}
[Fact]
public void BuildClassNameIndex_GleicheNamenInVerschiedenenKlassenBleibenEindeutig()
{
var classStudent = new Student { FirstName = "Amelia", LastName = "Gerste" };
var otherStudent = new Student { FirstName = "Amelia", LastName = "Gerste" };
var candidates = new[] { classStudent, otherStudent };
Assert.Empty(UntisNameMatching.BuildNameIndex(candidates));
var index = UntisNameMatching.BuildClassNameIndex(candidates,
[new Student { Id = classStudent.Id, FirstName = "Amelia", LastName = "Gerste" }]);
Assert.Same(classStudent, index[UntisNameMatching.NameKey("Gerste Amelia")]);
} }
} }
@@ -187,6 +187,45 @@ public sealed class UntisReportCacheServiceTests
Assert.Equal(4, handler.Requests.Count); // keine weiteren Anfragen - aus dem Cache bedient Assert.Equal(4, handler.Requests.Count); // keine weiteren Anfragen - aus dem Cache bedient
} }
[Fact]
public async Task GetAbsencesAsync_AlterHistorischerBerichtWirdErsetztUndDanachGecacht()
{
var day = DateOnly.FromDateTime(DateTime.Today).AddDays(-30);
var csv = Encoding.UTF8.GetBytes(
"Schüler*innen\tKlasse\tDatum\tFehlstd.\tFehlmin.\tFehltage\r\n" +
$"Muster Max\t10c\t{day:dd.MM.yy}\t2\t90\t0\r\n");
var schoolyears = "{\"result\":[{\"id\":7,\"name\":\"2026/27\",\"startDate\":20260801,\"endDate\":20270731}]}";
var handler = new QueueHandler(
Json("{\"result\":{\"sessionId\":\"s\"}}"), Json(schoolyears), Json(schoolyears),
Json("{\"result\":[{\"id\":874,\"name\":\"10c\"}]}"),
Json("{\"data\":{\"finished\":true,\"error\":false,\"reportParams\":\"get=rpt.tmp&name=AbsencePerStudent&format=csv\"}}"),
new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(csv) },
Json("{\"result\":{}}"));
await using var untis = new WebUntisIntegrationService(new HttpClient(handler), TestSupport.BuildWebUntisSettingsService());
await untis.ConnectAsync(new WebUntisCredentials("bk-ostvest", "arche.webuntis.com", "lehrkraft", "geheim"));
var absences = new FakeUntisAbsenceCache();
absences.InsertRange([new UntisAbsenceCacheEntry
{
ClassName = "10c", StudentName = "Muster Max", Date = Int(day),
AbsentPeriods = 2, CountsAsFullDay = true,
}]);
var states = new FakeUntisCacheFetchStates();
states.Save(new UntisCacheFetchState
{
ClassName = "10c", Kind = UntisCacheKind.Absences,
HotWindowFetchedAt = DateTime.UtcNow, ColdCoverageStartDate = Int(day),
});
var cache = new UntisReportCacheService(untis, absences, new FakeUntisClassRegisterCache(),
new FakeUntisStudentRosterCache(), states);
var first = Assert.Single(await cache.GetAbsencesAsync("10c", day, day));
Assert.False(first.CountsAsFullDay);
Assert.Equal(2, first.AbsentPeriods);
var requestCount = handler.Requests.Count;
Assert.False(Assert.Single(await cache.GetAbsencesAsync("10c", day, day)).CountsAsFullDay);
Assert.Equal(requestCount, handler.Requests.Count);
}
private static HttpResponseMessage Json(string json) => new(HttpStatusCode.OK) private static HttpResponseMessage Json(string json) => new(HttpStatusCode.OK)
{ {
Content = new StringContent(json, Encoding.UTF8, "application/json"), Content = new StringContent(json, Encoding.UTF8, "application/json"),
@@ -0,0 +1,135 @@
using LehrerApp.Core.Models;
using LehrerApp.Desktop.ViewModels.ClassTeacher;
using LehrerApp.Desktop.ViewModels.Students;
using LehrerApp.Desktop.Views.Shared;
using Xunit;
namespace LehrerApp.Desktop.Tests;
/// Tests für Standardformulierungen, schülerabhängige Bausteine im Vorgang-Dialog, den WebUntis-Stand
/// der Klassenlehrer-Vorgänge und die Wochentags-Ausrichtung des kompakten Monatskalenders.
public sealed class VorgangBausteineTests
{
[Fact]
public void KompakterKalender_BeginntInDerSpalteDesWochentags()
{
// 1. September 2026 ist ein Dienstag -> eine Leerzelle (Montag) davor.
var days = Enumerable.Range(1, 30).Select(d => new ClassTeacherCompactCalendarDay(
new DateOnly(2026, 9, d), "", "#00000000", "", false)).ToList();
var cells = CompactMonthCalendar.BuildCells(days);
Assert.True(cells[0].IsPlaceholder);
Assert.Equal(new DateOnly(2026, 9, 1), cells[1].Day!.Date);
Assert.Equal(31, cells.Count);
}
[Fact]
public void KompakterKalender_MonatsbeginnAmMontag_OhneLeerzelle()
{
var days = new[] { new ClassTeacherCompactCalendarDay(new DateOnly(2026, 6, 1), "", "", "", false) };
Assert.False(CompactMonthCalendar.BuildCells(days)[0].IsPlaceholder);
}
[Fact]
public void Standardformulierung_WirdAlsZeileAngehaengt()
{
var vm = new VorgangDialogViewModel([new StudentOption(Guid.NewGuid(), "Anna")], null,
phraseBlocks: VorgangPhraseBlocks.ForStudent(new DateOnly(2026, 9, 26))) { Description = "Notiz" };
vm.InsertPhraseCommand.Execute(vm.PhraseBlocks.First(p => p.Label == "Klassenleitung informiert"));
Assert.Equal("Notiz\n26.09.2026: Klassenleitung informiert.", vm.Description);
}
[Fact]
public void SchuelerBausteine_FolgenDerAuswahlImDialog()
{
var anna = new StudentOption(Guid.NewGuid(), "Anna");
var ben = new StudentOption(Guid.NewGuid(), "Ben");
var vm = new VorgangDialogViewModel([anna, ben], null,
studentQuickBlocks: ids => ids.Select(id => new VorgangQuickBlock(id == anna.Id ? "A" : "B", "")).ToList());
Assert.False(vm.HasQuickBlocks);
vm.StudentOptions[1].IsSelected = true;
Assert.Equal(["B"], vm.QuickBlocks.Select(b => b.Label));
vm.StudentOptions[0].IsSelected = true;
Assert.Equal(["A", "B"], vm.QuickBlocks.Select(b => b.Label));
}
private static ClassAbsenceDaySummaryRow Absence(DateOnly date, string name, int periods, bool unexcused,
bool fullDay = false, string reason = "Krankheit") => new(date, name, null, periods, periods * 45,
["M"], [1], [unexcused ? "nicht entschuldigt" : "entschuldigt"], [reason], null, null, fullDay);
[Fact]
public void KlassenlehrerStand_ZaehltFehlzeitenVerspaetungenUndKlassenbuch()
{
var student = new StudentOption(Guid.NewGuid(), "Beispiel Anna");
var today = new DateOnly(2026, 9, 26);
var absences = new[]
{
Absence(today.AddDays(-3), "Anna Beispiel", 6, unexcused: true, fullDay: true),
Absence(today.AddDays(-5), "Anna Beispiel", 2, unexcused: false),
Absence(today.AddDays(-6), "Anna Beispiel", 0, unexcused: false, reason: "Verspätung"),
Absence(today.AddDays(-3), "Ben Fremd", 6, unexcused: true),
};
var register = new[]
{
new ClassTeacherClassRegisterRow(today.AddDays(-2), "D", "Anna Beispiel", "MUE", "Hausaufgaben fehlen", "Negativ", null),
new ClassTeacherClassRegisterRow(today.AddDays(-1), "E", "Anna Beispiel", "SCH", "Lob", "Positiv", null),
};
var facts = ClassTeacherStudentFacts.Build(student, "Anna Beispiel", "2026/27", today, absences, register);
Assert.Equal(8, facts.AbsentPeriods);
Assert.Equal(1, facts.UnexcusedDays);
Assert.Equal(2, facts.PartialAbsentPeriods);
Assert.Equal(0, facts.UnexcusedPartialPeriods);
Assert.Single(facts.LateDays);
Assert.Equal(1, facts.NegativeRegisterCount);
Assert.Single(facts.HomeworkEntries);
Assert.Contains("1 ganzer Fehltag und 2 weitere Fehlstunden", facts.AbsenceShort);
var labels = facts.QuickBlocks(withName: true).Select(b => b.Label).ToList();
Assert.Contains("Fehlzeiten · Beispiel Anna", labels);
var ctx = facts.TemplateContext(new Vorgang { Title = "Fehlzeiten", Tags = ["Absentismus"] });
Assert.Equal([facts.AbsenceShort], ctx.SituationLines);
var letter = VorgangDocumentationTemplates.Build(VorgangDocumentationTemplates.ParentLetter,
new Vorgang { Title = "Fehlzeiten", Tags = ["Absentismus"] }, ctx)!;
Assert.StartsWith("Sehr geehrte Erziehungsberechtigte von Anna Beispiel", letter.ParentLetterData!.DraftContent);
}
[Fact]
public void KlassenlehrerStand_UnentschuldigteFehlstundeWirdNichtAlsFehltagBezeichnet()
{
var student = new StudentOption(Guid.NewGuid(), "Beispiel Anna");
var today = new DateOnly(2026, 9, 28);
var facts = ClassTeacherStudentFacts.Build(student, "Anna Beispiel", "2026/27", today,
[Absence(today.AddDays(-4), "Anna Beispiel", 1, unexcused: true)], []);
Assert.Equal(0, facts.FullDays);
Assert.Equal(0, facts.UnexcusedDays);
Assert.Equal(1, facts.PartialAbsentPeriods);
Assert.Equal(1, facts.UnexcusedPartialPeriods);
Assert.Contains("0 ganze Fehltage und 1 weitere Fehlstunde", facts.AbsenceShort);
Assert.Contains("unentschuldigt: 0 ganze Tage, 1 Fehlstunde", facts.AbsenceShort);
Assert.Contains("1 Fehlstunde · Unentschuldigt", facts.AbsenceBlock);
}
[Fact]
public void Vorlage_KlassenleitungInformieren()
{
var id = Guid.NewGuid();
var ctx = new VorgangTemplateContext(id, "Anna Beispiel", new DateOnly(2026, 9, 26), ["Fehlquote 25 %"],
new Dictionary<string, VorgangSnapshot>());
var doc = VorgangDocumentationTemplates.Build(VorgangDocumentationTemplates.InformClassTeacher,
new Vorgang { Title = "Fehlzeiten" }, ctx)!;
Assert.Equal(DocumentationType.Conversation, doc.Type);
Assert.Equal(["Klassenleitung"], doc.Participants);
Assert.Contains("Klassenleitung am 26.09.2026 informiert über:\n- Fehlquote 25 %", doc.Content);
Assert.Equal(id, doc.StudentId);
}
}
@@ -0,0 +1,167 @@
using System.Net;
using System.Text;
using LehrerApp.Core.Models;
using LehrerApp.Core.Services;
using LehrerApp.Desktop.Services;
using LehrerApp.Desktop.ViewModels.Groups;
using LehrerApp.WebUntis;
using Xunit;
namespace LehrerApp.Desktop.Tests;
public sealed class WebUntisHomeworkComparisonViewModelTests
{
[Theory]
[InlineData("Fehlende HA", "Buch vergessen", "Negativ", true)]
[InlineData("Sonstiges", "HA nicht dabei", "Negativ", false)]
[InlineData(null, "HA nicht dabei", "Negativ", true)]
[InlineData("Hausaufgaben fehlen", null, "Negativ", true)]
[InlineData("Verhalten", "Schüler war unruhig", "Negativ", false)]
[InlineData("Hausaufgaben", "HA gemacht", "Positiv", false)]
[InlineData("Sonstiges", "Schach gespielt", "Negativ", false)]
public void IsMissingHomeworkEntry_ErkenntAuchDasWebUntisKuerzel(
string? category, string? entryText, string group, bool expected)
{
var entry = new UntisClassRegisterEventDto("10c", 20260925, "Che", "Gerste Amelia",
category, group, entryText);
Assert.Equal(expected, WebUntisHomeworkComparisonViewModel.IsMissingHomeworkEntry(entry));
}
[Fact]
public async Task Load_ZeigtFehlendeHaAuchOhneHausaufgabeImFreitext()
{
const string report = "Klasse\tDatum\tFach\tName\tBenutzer\tEintragskategorie\tKategoriegruppe\tText\r\n" +
"10c\t25.09.26\tChe\tGerste Amelia\tlehrkraft\tFehlende HA\tNegativ\tChe: Buch vergessen\r\n" +
"10c\t25.09.26\tChe\tGerste Amelia\tlehrkraft\tHausaufgaben\tPositiv\tChe: alles erledigt\r\n";
var handler = new QueueHandler(
Json("{\"result\":{\"sessionId\":\"s\"}}"),
Json("{\"result\":[{\"id\":1,\"name\":\"2026/27\",\"startDate\":20260801,\"endDate\":20270731}]}"),
Json("{\"data\":{\"finished\":true,\"error\":false," +
"\"reportParams\":\"get=rpt.tmp&name=ClassregEventPerStudent&format=csv\"}}"),
new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(Encoding.UTF8.GetBytes(report)),
});
var settings = TestSupport.BuildWebUntisSettingsService();
var credentials = new WebUntisCredentials("schule", "arche.webuntis.com", "lehrkraft", "geheim");
settings.SetApiCredentials(credentials);
await using var untis = new WebUntisIntegrationService(new HttpClient(handler), settings);
await untis.ConnectAsync(credentials);
var vm = new WebUntisHomeworkComparisonViewModel(untis, new FakeStudents([]),
new FakeGroups([]), new FakeSubjects([]), new FakeMemberships([]),
new FakeSessions([]), new FakeEntries(), new SchoolYearService())
{
StartDate = new DateTimeOffset(2026, 9, 24, 12, 0, 0, TimeSpan.Zero),
EndDate = new DateTimeOffset(2026, 9, 26, 12, 0, 0, TimeSpan.Zero),
};
await vm.LoadCommand.ExecuteAsync(null);
Assert.Equal("Gerste Amelia", Assert.Single(vm.Rows).UntisStudentName);
Assert.Contains("1 passende Einträge von 2", vm.Status);
}
[Fact]
public async Task LoadUndApply_TrenntBestehendenStatus_ZielstatusUndLokaleEintraege()
{
const string report = "Klasse\tDatum\tFach\tName\tBenutzer\tEintragskategorie\tKategoriegruppe\tText\r\n" +
"10c\t25.09.26\tChe\tGerste Amelia\tlehrkraft\tFehlende HA\tNegativ\tChe: nicht gemacht\r\n" +
"10c\t25.09.26\tChe\tMuster Ben\tlehrkraft\tFehlende HA\tNegativ\tChe: nicht gemacht\r\n";
var handler = new QueueHandler(
Json("{\"result\":{\"sessionId\":\"s\"}}"),
Json("{\"result\":[{\"id\":1,\"name\":\"2026/27\",\"startDate\":20260801,\"endDate\":20270731}]}"),
Json("{\"data\":{\"finished\":true,\"error\":false," +
"\"reportParams\":\"get=rpt.tmp&name=ClassregEventPerStudent&format=csv\"}}"),
new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(Encoding.UTF8.GetBytes(report)),
});
var settings = TestSupport.BuildWebUntisSettingsService();
var credentials = new WebUntisCredentials("schule", "arche.webuntis.com", "lehrkraft", "geheim");
settings.SetApiCredentials(credentials);
await using var untis = new WebUntisIntegrationService(new HttpClient(handler), settings);
await untis.ConnectAsync(credentials);
var date = new DateOnly(2026, 9, 25);
var schoolYear = new SchoolYearService();
var chemistry = new Subject { Name = "Chemie", ShortName = "Che" };
var biology = new Subject { Name = "Biologie", ShortName = "Bio" };
var classGroup = new LearningGroup { Name = "10c", Type = GroupType.Class,
SchoolYear = schoolYear.CurrentSchoolYear(date) };
var chemistryGroup = new LearningGroup { Name = "Chemie 10c", Type = GroupType.Course,
SubjectId = chemistry.Id, SchoolYear = classGroup.SchoolYear };
var biologyGroup = new LearningGroup { Name = "Biologie 10c", Type = GroupType.Course,
SubjectId = biology.Id, SchoolYear = classGroup.SchoolYear };
var amelia = new Student { FirstName = "Amelia", LastName = "Gerste" };
var ben = new Student { FirstName = "Ben", LastName = "Muster" };
var carl = new Student { FirstName = "Carl", LastName = "Beispiel" };
var chemistrySession = new ParticipationSession { GroupId = chemistryGroup.Id, Date = date };
var biologySession = new ParticipationSession { GroupId = biologyGroup.Id, Date = date };
var memberships = new FakeMemberships([
new GroupMembership { StudentId = amelia.Id, GroupId = chemistryGroup.Id },
new GroupMembership { StudentId = amelia.Id, GroupId = biologyGroup.Id },
new GroupMembership { StudentId = ben.Id, GroupId = chemistryGroup.Id },
new GroupMembership { StudentId = carl.Id, GroupId = chemistryGroup.Id },
]);
var participation = new FakeEntries();
participation.Add(new ParticipationEntry { SessionId = chemistrySession.Id, StudentId = amelia.Id,
Homework = HomeworkStatus.MissingOpen, HomeworkMissing = true });
participation.Add(new ParticipationEntry { SessionId = biologySession.Id, StudentId = amelia.Id,
Homework = HomeworkStatus.PartiallyCompleted, HomeworkMissing = true });
participation.Add(new ParticipationEntry { SessionId = chemistrySession.Id, StudentId = carl.Id,
Homework = HomeworkStatus.MissingOverdue, HomeworkMissing = true });
var vm = new WebUntisHomeworkComparisonViewModel(untis,
new FakeStudents([amelia, ben, carl]),
new FakeGroups([classGroup, chemistryGroup, biologyGroup]),
new FakeSubjects([chemistry, biology]), memberships,
new FakeSessions([chemistrySession, biologySession]), participation, schoolYear)
{
StartDate = new DateTimeOffset(2026, 9, 24, 12, 0, 0, TimeSpan.Zero),
EndDate = new DateTimeOffset(2026, 9, 26, 12, 0, 0, TimeSpan.Zero),
};
await vm.LoadCommand.ExecuteAsync(null);
var existing = Assert.Single(vm.Rows, r => r.AssignedStudent?.Id == amelia.Id);
Assert.False(existing.Selected);
Assert.Equal(HomeworkDisplay.Label(HomeworkStatus.MissingOpen), existing.LocalStatus);
Assert.Equal(HomeworkDisplay.Label(HomeworkStatus.MissingOpen), existing.SelectedStatusName);
var newRow = Assert.Single(vm.Rows, r => r.AssignedStudent?.Id == ben.Id);
Assert.True(newRow.Selected);
Assert.Equal("Noch kein Status erfasst", newRow.LocalStatus);
Assert.Equal(2, vm.LocalOnlyRows.Count);
Assert.Contains(vm.LocalOnlyRows, r => r.StudentName == amelia.FullName && r.GroupName == biologyGroup.Name);
Assert.Contains(vm.LocalOnlyRows, r => r.StudentName == carl.FullName && r.GroupName == chemistryGroup.Name);
newRow.AssignedStudent = carl;
Assert.Single(vm.LocalOnlyRows);
Assert.False(newRow.Selected);
newRow.AssignedStudent = ben;
Assert.Equal(2, vm.LocalOnlyRows.Count);
newRow.SelectedStatusName = HomeworkDisplay.Label(HomeworkStatus.SubmittedLate);
vm.ApplyCommand.Execute(null);
var saved = participation.GetBySessionAndStudent(chemistrySession.Id, ben.Id);
Assert.Equal(HomeworkStatus.SubmittedLate, saved?.Homework);
Assert.False(saved?.HomeworkMissing);
Assert.Equal(HomeworkDisplay.Label(HomeworkStatus.SubmittedLate), newRow.LocalStatus);
Assert.False(newRow.Selected);
Assert.Equal(HomeworkStatus.MissingOpen,
participation.GetBySessionAndStudent(chemistrySession.Id, amelia.Id)?.Homework);
}
private static HttpResponseMessage Json(string json) => new(HttpStatusCode.OK)
{
Content = new StringContent(json, Encoding.UTF8, "application/json"),
};
private sealed class QueueHandler(params HttpResponseMessage[] responses) : HttpMessageHandler
{
private readonly Queue<HttpResponseMessage> _responses = new(responses);
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken) => Task.FromResult(_responses.Dequeue());
}
}
@@ -0,0 +1,208 @@
using LehrerApp.Core.Interfaces;
using LehrerApp.Core.Models;
using LehrerApp.Core.Services;
using LehrerApp.Desktop.Services;
using Xunit;
namespace LehrerApp.Desktop.Tests;
public sealed class WebUntisRestSyncProcessorTests
{
private static readonly DateOnly Monday = new(2026, 9, 28);
[Fact]
public void Process_AusfallImDoppelblock_SchreibtBeideStundenUndIstIdempotent()
{
var group = new LearningGroup { Id = Guid.NewGuid(), Name = "8c" };
var mappings = new FakeUntisSlotMappings();
mappings.Add(new UntisSlotMapping
{
Weekday = DayOfWeek.Tuesday, StartTime = new TimeOnly(9, 40), Summary = "NAT",
ClassToken = "8c", Kind = SubstitutionKind.Lesson, GroupId = group.Id,
PeriodNumber = 3, CoveredPeriods = [3, 4], Confirmed = true,
});
var substitutions = new FakeSubstitutionEntries();
var processor = BuildProcessor(mappings, substitutions, new RecordingExams(), [group]);
var cancelled = Entry([100, 101], "2026-09-29T09:40", "2026-09-29T11:10",
"NORMAL_TEACHING_PERIOD", "CANCELLED", "NAT", "8c");
var first = processor.Process([cancelled], Monday, Monday.AddDays(13), Monday.AddDays(27));
var second = processor.Process([cancelled], Monday, Monday.AddDays(13), Monday.AddDays(27));
Assert.Equal(2, first.SubstitutionChanges);
Assert.Equal(0, second.SubstitutionChanges);
Assert.Equal([3, 4], substitutions.GetAll().Select(entry => entry.PeriodNumber).Order().ToArray());
Assert.All(substitutions.GetAll(), entry => Assert.Equal(SubstitutionKind.Cancelled, entry.Kind));
}
[Fact]
public void Process_Exam_LegtArbeitMitTitelAnUndEntferntSieNachVerschwinden()
{
var group = new LearningGroup { Id = Guid.NewGuid(), Name = "Mat_E" };
var mappings = new FakeUntisSlotMappings();
mappings.Add(new UntisSlotMapping
{
Weekday = DayOfWeek.Tuesday, StartTime = new TimeOnly(9, 40), Summary = "Mat_E",
ClassToken = "10a;10b;10c;Gastro", Kind = SubstitutionKind.Lesson, GroupId = group.Id,
PeriodNumber = 3, CoveredPeriods = [3, 4], Confirmed = true,
});
var exams = new RecordingExams();
var processor = BuildProcessor(mappings, new FakeSubstitutionEntries(), exams, [group]);
var exam = Entry([2002979, 2002982], "2026-09-29T09:40", "2026-09-29T11:10",
"EXAM", "REGULAR", "Mat_E", "10a", "Arbeit 1. Mathearbeit");
var imported = processor.Process([exam], Monday, Monday.AddDays(13), Monday.AddDays(27));
var unchanged = processor.Process([exam], Monday, Monday.AddDays(13), Monday.AddDays(27));
var removed = processor.Process([], Monday, Monday.AddDays(13), Monday.AddDays(27));
Assert.Equal(1, imported.ExamChanges);
Assert.Equal(0, unchanged.ExamChanges);
Assert.Equal(1, removed.ExamChanges);
Assert.Empty(exams.GetAll());
}
[Fact]
public void Process_DoppeltAngelegteArbeitDurchGeraeteSync_WirdAufEinenDatensatzReduziert()
{
var group = new LearningGroup { Id = Guid.NewGuid(), Name = "Mat_E" };
var mappings = new FakeUntisSlotMappings();
mappings.Add(new UntisSlotMapping
{
Weekday = DayOfWeek.Tuesday, StartTime = new TimeOnly(9, 40), Summary = "Mat_E",
ClassToken = "10a", Kind = SubstitutionKind.Lesson, GroupId = group.Id,
PeriodNumber = 3, CoveredPeriods = [3, 4], Confirmed = true,
});
var exam = Entry([2002979, 2002982], "2026-09-29T09:40", "2026-09-29T11:10",
"EXAM", "REGULAR", "Mat_E", "10a", "Arbeit 1. Mathearbeit");
var externalId = WebUntisRestSyncProcessor.ExamPrefix + "2002979-2002982";
// Zwei Geräte haben dieselbe WebUntis-Arbeit unabhängig voneinander (vor dem gegenseitigen
// Sync) mit derselben ExternalId, aber unterschiedlicher Id angelegt.
var olderDuplicate = new Exam
{
GroupId = group.Id, Date = new DateOnly(2026, 9, 29), Title = "Arbeit 1. Mathearbeit",
ExternalId = externalId, CreatedAt = new DateTime(2026, 9, 22, 8, 0, 0, DateTimeKind.Utc),
};
var newerDuplicate = new Exam
{
GroupId = group.Id, Date = new DateOnly(2026, 9, 29), Title = "Arbeit 1. Mathearbeit",
ExternalId = externalId, CreatedAt = new DateTime(2026, 9, 22, 9, 0, 0, DateTimeKind.Utc),
};
var exams = new RecordingExams([olderDuplicate, newerDuplicate]);
var processor = BuildProcessor(mappings, new FakeSubstitutionEntries(), exams, [group]);
var result = processor.Process([exam], Monday, Monday.AddDays(13), Monday.AddDays(27));
var remaining = Assert.Single(exams.GetAll());
Assert.Equal(olderDuplicate.Id, remaining.Id);
Assert.Equal(1, result.ExamChanges);
}
[Fact]
public void Process_DupliziertMitBereitsBenoteterKlausur_LoeschtNurDenNochPlanentenDatensatz()
{
var group = new LearningGroup { Id = Guid.NewGuid(), Name = "Mat_E" };
var mappings = new FakeUntisSlotMappings();
mappings.Add(new UntisSlotMapping
{
Weekday = DayOfWeek.Tuesday, StartTime = new TimeOnly(9, 40), Summary = "Mat_E",
ClassToken = "10a", Kind = SubstitutionKind.Lesson, GroupId = group.Id,
PeriodNumber = 3, CoveredPeriods = [3, 4], Confirmed = true,
});
var exam = Entry([2002979, 2002982], "2026-09-29T09:40", "2026-09-29T11:10",
"EXAM", "REGULAR", "Mat_E", "10a", "Arbeit 1. Mathearbeit");
var externalId = WebUntisRestSyncProcessor.ExamPrefix + "2002979-2002982";
var gradedDuplicate = new Exam
{
GroupId = group.Id, Date = new DateOnly(2026, 9, 29), Title = "Arbeit 1. Mathearbeit",
ExternalId = externalId, Status = ExamStatus.Graded,
};
var plannedDuplicate = new Exam
{
GroupId = group.Id, Date = new DateOnly(2026, 9, 29), Title = "Arbeit 1. Mathearbeit",
ExternalId = externalId,
};
var exams = new RecordingExams([gradedDuplicate, plannedDuplicate]);
var processor = BuildProcessor(mappings, new FakeSubstitutionEntries(), exams, [group]);
processor.Process([exam], Monday, Monday.AddDays(13), Monday.AddDays(27));
var remaining = Assert.Single(exams.GetAll());
Assert.Equal(gradedDuplicate.Id, remaining.Id);
}
[Fact]
public void Process_ManuelleArbeitAmSelbenTag_WirdNichtDupliziertOderGeloescht()
{
var group = new LearningGroup { Id = Guid.NewGuid(), Name = "Mat_E" };
var manual = new Exam { GroupId = group.Id, Date = new DateOnly(2026, 9, 29), Title = "1. Arbeit" };
var exams = new RecordingExams([manual]);
var mappings = new FakeUntisSlotMappings();
mappings.Add(new UntisSlotMapping
{
Weekday = DayOfWeek.Tuesday, StartTime = new TimeOnly(9, 40), Summary = "Mat_E",
ClassToken = "10a", GroupId = group.Id, PeriodNumber = 3, CoveredPeriods = [3, 4], Confirmed = true,
});
var processor = BuildProcessor(mappings, new FakeSubstitutionEntries(), exams, [group]);
processor.Process([Entry([1], "2026-09-29T09:40", "2026-09-29T11:10", "EXAM", "REGULAR",
"Mat_E", "10a", "Arbeit aus WebUntis")], Monday, Monday.AddDays(13), Monday.AddDays(27));
Assert.Same(manual, Assert.Single(exams.GetAll()));
Assert.Null(manual.ExternalId);
}
[Fact]
public void Process_UebernommeneRegulaereAufsicht_WirdAlsAenderungErfasst()
{
var duties = new FakeSupervisionDuties();
duties.Add(new SupervisionDuty { Weekday = DayOfWeek.Wednesday, AfterPeriod = 2, Location = "PH grün" });
var substitutions = new FakeSubstitutionEntries();
var processor = BuildProcessor(new FakeUntisSlotMappings(), substitutions, new RecordingExams(), [], duties);
var entry = new UntisTimetableGridEntryDto([17], new DateTime(2026, 9, 30, 9, 20, 0),
new DateTime(2026, 9, 30, 9, 40, 0), "BREAK_SUPERVISION", "CHANGED", "SUBSTITUTED",
null, null, null, null,
[new UntisGridResourceChangeDto(null,
new UntisGridResourceDto("TEACHER", "REMOVED", "HED", null, "HED"))]);
processor.Process([entry], Monday, Monday.AddDays(13), Monday.AddDays(27));
var change = Assert.Single(substitutions.GetAll());
Assert.Equal(SubstitutionKind.Supervision, change.Kind);
Assert.Equal(2, change.AfterPeriod);
Assert.Contains("übernommen", change.Description);
}
private static WebUntisRestSyncProcessor BuildProcessor(FakeUntisSlotMappings mappings,
FakeSubstitutionEntries substitutions, IExamRepository exams, List<LearningGroup> groups,
FakeSupervisionDuties? supervisionDuties = null)
{
var path = Path.Combine(Path.GetTempPath(), $"lehrerapp-rest-sync-tests-{Guid.NewGuid():N}");
Directory.CreateDirectory(path);
var periods = new PeriodScheduleService(path);
periods.SetPeriods([
new PeriodTimeEntry { PeriodNumber = 2, Start = new TimeOnly(8, 35), End = new TimeOnly(9, 20) },
new PeriodTimeEntry { PeriodNumber = 3, Start = new TimeOnly(9, 40), End = new TimeOnly(10, 25) },
new PeriodTimeEntry { PeriodNumber = 4, Start = new TimeOnly(10, 25), End = new TimeOnly(11, 10) },
]);
return new WebUntisRestSyncProcessor(mappings, substitutions, exams, new FakeGroups(groups),
supervisionDuties ?? new FakeSupervisionDuties(), periods);
}
private static UntisTimetableGridEntryDto Entry(IReadOnlyList<int> ids, string start, string end,
string type, string status, string subject, string className, string? lessonInfo = null) => new(
ids, DateTime.Parse(start), DateTime.Parse(end), type, status, null, null, null, lessonInfo, null,
[
new UntisGridResourceChangeDto(new UntisGridResourceDto("CLASS", "REGULAR", className, null, className), null),
new UntisGridResourceChangeDto(new UntisGridResourceDto("SUBJECT", "REGULAR", subject, null, subject), null),
]);
private sealed class RecordingExams(List<Exam>? initial = null) : IExamRepository
{
private readonly List<Exam> _all = initial ?? [];
public Exam? GetById(Guid id) => _all.FirstOrDefault(exam => exam.Id == id);
public List<Exam> GetAll() => _all.ToList();
public List<Exam> GetByGroup(Guid groupId) => _all.Where(exam => exam.GroupId == groupId).ToList();
public void Save(Exam exam) { _all.RemoveAll(item => item.Id == exam.Id); _all.Add(exam); }
public void Delete(Guid id) => _all.RemoveAll(exam => exam.Id == id);
}
}
@@ -0,0 +1,111 @@
using System.Net;
using System.Text;
using LehrerApp.Core.Models;
using LehrerApp.Desktop.Services;
using LehrerApp.Desktop.ViewModels.Planning;
using Xunit;
namespace LehrerApp.Desktop.Tests;
public sealed class WebUntisTimetableImportTests
{
[Fact]
public async Task Load_IsReadOnly_AndSaveUpdatesOnlyLessonIdsByDefault()
{
await using var fixture = new Fixture();
await fixture.Vm.LoadCommand.ExecuteAsync(null);
Assert.Null(fixture.Group.WebUntisLessonId);
Assert.Null(fixture.Settings.TeacherUntisId);
Assert.Single(fixture.Slots.GetAll());
Assert.Equal(38926, Assert.Single(fixture.Vm.Rows).LessonId);
fixture.Vm.SaveCommand.Execute(null);
Assert.True(fixture.Vm.Saved);
Assert.Equal(38926, fixture.Group.WebUntisLessonId);
Assert.Equal(DayOfWeek.Friday, Assert.Single(fixture.Slots.GetAll()).Weekday);
}
[Theory]
[InlineData(false, 2)]
[InlineData(true, 1)]
public async Task TimetableUpdates_OnlyRemoveOldSlotsWhenExplicitlySelected(bool replace, int expected)
{
await using var fixture = new Fixture();
await fixture.Vm.LoadCommand.ExecuteAsync(null);
fixture.Vm.UpdateLessonIds = false;
fixture.Vm.UpdateTimetable = true;
fixture.Vm.ReplaceTimetable = replace;
fixture.Vm.SaveCommand.Execute(null);
Assert.True(fixture.Vm.Saved);
Assert.Null(fixture.Group.WebUntisLessonId);
Assert.Equal(expected, fixture.Slots.GetAll().Count);
Assert.Contains(fixture.Slots.GetAll(), slot => slot.Weekday == DayOfWeek.Monday);
}
[Fact]
public async Task ConflictingLessonIds_BlockAllChanges_UntilExcluded()
{
await using var fixture = new Fixture();
await fixture.Vm.LoadCommand.ExecuteAsync(null);
fixture.Vm.Rows.Add(new WebUntisTimetableRow
{
Weekday = DayOfWeek.Tuesday, PeriodNumber = 1, TimeLabel = "07:50", UntisLabel = "7a",
SuggestedGroupName = "7a", LessonId = 999, SelectedGroup = fixture.Vm.Rows[0].SelectedGroup,
});
fixture.Vm.UpdateTimetable = true;
fixture.Vm.SaveCommand.Execute(null);
Assert.False(fixture.Vm.Saved);
Assert.Null(fixture.Group.WebUntisLessonId);
Assert.Single(fixture.Slots.GetAll());
Assert.Contains("Mehrere Unterrichtsnummern", fixture.Vm.Status);
fixture.Vm.Rows[1].ApplyLessonId = false;
fixture.Vm.SaveCommand.Execute(null);
Assert.True(fixture.Vm.Saved);
Assert.Equal(38926, fixture.Group.WebUntisLessonId);
}
[Fact]
public async Task SaveWithoutLoadedWeek_DoesNotClearTimetable()
{
await using var fixture = new Fixture();
fixture.Vm.UpdateTimetable = fixture.Vm.ReplaceTimetable = true;
fixture.Vm.SaveCommand.Execute(null);
Assert.False(fixture.Vm.Saved);
Assert.Single(fixture.Slots.GetAll());
}
private sealed class Fixture : IAsyncDisposable
{
public LearningGroup Group { get; } = new() { Name = "7a" };
public FakeTimetableSlots Slots { get; } = new();
public WebUntisSettingsService Settings { get; } = TestSupport.BuildWebUntisSettingsService();
private readonly WebUntisIntegrationService _service;
public WebUntisTimetableImportViewModel Vm { get; }
public Fixture()
{
Settings.SetApiCredentials(new("school", "example.webuntis.com", "teacher", "password"));
_service = new(new HttpClient(new Handler()), Settings);
Slots.Add(new() { Weekday = DayOfWeek.Friday, PeriodNumber = 4, GroupId = Group.Id });
Vm = new(_service, Settings, Slots, new FakeGroups([Group]))
{
SelectedTeacher = new(89, "Teacher", null, null, null, true, []),
WeekDate = new DateTimeOffset(2026, 10, 5, 0, 0, 0, TimeSpan.Zero),
};
}
public ValueTask DisposeAsync() => _service.DisposeAsync();
}
private sealed class Handler : HttpMessageHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken token)
{
var body = request.Content is null ? "" : await request.Content.ReadAsStringAsync(token);
var json = request.RequestUri!.AbsolutePath.Contains("weekly/data")
? """{"data":{"result":{"data":{"elementPeriods":{"89":[{"id":2013854,"lessonId":38926},{"id":2013854,"lessonId":38926}]}}}}}"""
: body.Contains("authenticate") ? """{"result":{"sessionId":"s"}}"""
: body.Contains("getTimetable") ? """{"result":[{"id":2013854,"date":20261005,"startTime":750,"endTime":835,"kl":[{"id":4,"name":"7a"}],"te":[],"su":[],"ro":[]}]}"""
: body.Contains("getTimegridUnits") ? """{"result":[{"day":1,"timeUnits":[{"name":"1","startTime":750,"endTime":835}]}]}"""
: """{"result":{}}""";
return new(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
}
}
}
+41
View File
@@ -15,6 +15,7 @@ using LehrerApp.Desktop.ViewModels.Planning;
using LehrerApp.Desktop.ViewModels.Students; using LehrerApp.Desktop.ViewModels.Students;
using LehrerApp.Desktop.ViewModels.Workload; using LehrerApp.Desktop.ViewModels.Workload;
using LehrerApp.Desktop.Views; using LehrerApp.Desktop.Views;
using LehrerApp.Desktop.Views.Shared;
using LehrerApp.Desktop.Views.Workload; using LehrerApp.Desktop.Views.Workload;
using LehrerApp.Sync; using LehrerApp.Sync;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
@@ -28,6 +29,7 @@ public class App : Application
private static bool _exitHandlerAttached; private static bool _exitHandlerAttached;
private static Task _initialPolls = Task.CompletedTask; private static Task _initialPolls = Task.CompletedTask;
private static readonly CancellationTokenSource StartupCancellation = new(); private static readonly CancellationTokenSource StartupCancellation = new();
private static DispatcherTimer? _homeworkOverdueTimer;
public override void Initialize() => AvaloniaXamlLoader.Load(this); public override void Initialize() => AvaloniaXamlLoader.Load(this);
@@ -100,6 +102,7 @@ public class App : Application
splash?.SetProgress(60, "Papierkorb aufräumen …"); splash?.SetProgress(60, "Papierkorb aufräumen …");
await Task.Run(() => Services.GetRequiredService<ITrashRepository>() await Task.Run(() => Services.GetRequiredService<ITrashRepository>()
.PurgeOlderThan(DateTime.UtcNow.AddDays(-30))); .PurgeOlderThan(DateTime.UtcNow.AddDays(-30)));
await AdvanceHomeworkAsync();
if (!_exitHandlerAttached) if (!_exitHandlerAttached)
{ {
@@ -126,6 +129,7 @@ public class App : Application
main.EnableFinalSync(syncEngine); main.EnableFinalSync(syncEngine);
desktop.MainWindow = main; desktop.MainWindow = main;
main.Show(); main.Show();
StartHomeworkOverdueTimer();
splash?.SetProgress(100, "Bereit"); splash?.SetProgress(100, "Bereit");
windowToClose?.Close(); windowToClose?.Close();
AppBootstrapper.Logger.Info($"Start: Hauptfenster nach {timer.ElapsedMilliseconds} ms geöffnet."); AppBootstrapper.Logger.Info($"Start: Hauptfenster nach {timer.ElapsedMilliseconds} ms geöffnet.");
@@ -152,6 +156,30 @@ public class App : Application
}); });
} }
private static async Task AdvanceHomeworkAsync()
{
try
{
var changed = await Task.Run(() => Services.GetRequiredService<HomeworkOverdueService>()
.Advance(DateOnly.FromDateTime(DateTime.Today)));
if (changed > 0) AppBootstrapper.Logger.Info($"{changed} offene Hausaufgaben als nicht nachgereicht markiert.");
}
catch (Exception ex) { AppBootstrapper.Logger.Error("Hausaufgaben-Fristprüfung fehlgeschlagen.", ex); }
}
private static void StartHomeworkOverdueTimer()
{
var timer = new DispatcherTimer { Interval = TimeSpan.FromHours(1) };
timer.Tick += async (_, _) =>
{
timer.Stop();
await AdvanceHomeworkAsync();
if (_serviceProvider is not null) timer.Start();
};
_homeworkOverdueTimer = timer;
timer.Start();
}
/// <summary>Wechselt die Darstellung sofort, ohne Neustart (12.4) — Avalonia stylt den /// <summary>Wechselt die Darstellung sofort, ohne Neustart (12.4) — Avalonia stylt den
/// gesamten sichtbaren Baum automatisch neu, sobald sich <see cref="ThemeVariant"/> /// gesamten sichtbaren Baum automatisch neu, sobald sich <see cref="ThemeVariant"/>
/// ändert.</summary> /// ändert.</summary>
@@ -165,6 +193,7 @@ public class App : Application
private static void DisposeServices() private static void DisposeServices()
{ {
_homeworkOverdueTimer?.Stop();
var serviceProvider = Interlocked.Exchange(ref _serviceProvider, null); var serviceProvider = Interlocked.Exchange(ref _serviceProvider, null);
if (serviceProvider is null) return; if (serviceProvider is null) return;
@@ -206,10 +235,12 @@ public class App : Application
var dash = Services.GetRequiredService<DashboardViewModel>(); var dash = Services.GetRequiredService<DashboardViewModel>();
dash.OnNavigateToGroup = id => main.NavigateToGroupDetail(id); dash.OnNavigateToGroup = id => main.NavigateToGroupDetail(id);
dash.OnNavigateToStudent = id => main.NavigateToStudent(id); dash.OnNavigateToStudent = id => main.NavigateToStudent(id);
dash.OnNavigateToStudentCase = (id, tag, title) => main.NavigateToStudentCase(id, tag, title);
dash.OnNavigateToLesson = id => main.NavigateToGroupDetail(id, 3); // Tab "Mitarbeit" dash.OnNavigateToLesson = id => main.NavigateToGroupDetail(id, 3); // Tab "Mitarbeit"
dash.OnNavigateToExam = id => main.NavigateToGroupDetail(id, 4); // Tab "Klausuren" dash.OnNavigateToExam = id => main.NavigateToGroupDetail(id, 4); // Tab "Klausuren"
dash.OnNavigateToUnplannedLesson = id => main.NavigateToGroupDetail(id, 6); // Tab "Planung" dash.OnNavigateToUnplannedLesson = id => main.NavigateToGroupDetail(id, 6); // Tab "Planung"
dash.OnAddMissingTeachingTime = item => ShowMissingTeachingTimeDialog(item, dash); dash.OnAddMissingTeachingTime = item => ShowMissingTeachingTimeDialog(item, dash);
dash.OnPickSnoozeDuration = ShowSnoozeDurationDialog;
var examsOverview = Services.GetRequiredService<ViewModels.Exams.ExamsOverviewViewModel>(); var examsOverview = Services.GetRequiredService<ViewModels.Exams.ExamsOverviewViewModel>();
examsOverview.OnNavigateToGroups = () => main.NavigateToCommand.Execute(NavItem.Groups); examsOverview.OnNavigateToGroups = () => main.NavigateToCommand.Execute(NavItem.Groups);
@@ -265,6 +296,16 @@ public class App : Application
Services.GetRequiredService<WorkTaskListViewModel>().Load(); Services.GetRequiredService<WorkTaskListViewModel>().Load();
} }
private static async Task<int?> ShowSnoozeDurationDialog(string message)
{
if (Application.Current?.ApplicationLifetime is not IClassicDesktopStyleApplicationLifetime
{ MainWindow: { } owner }) return null;
var vm = new SnoozeDurationDialogInfo { Message = message };
var dialog = new SnoozeDurationDialog { DataContext = vm };
return await dialog.ShowDialog<int?>(owner);
}
private static async Task ShowMissingTeachingTimeDialog(MissingTeachingTimeItem item, DashboardViewModel dashboard) private static async Task ShowMissingTeachingTimeDialog(MissingTeachingTimeItem item, DashboardViewModel dashboard)
{ {
if (Application.Current?.ApplicationLifetime is not IClassicDesktopStyleApplicationLifetime if (Application.Current?.ApplicationLifetime is not IClassicDesktopStyleApplicationLifetime
+30 -16
View File
@@ -122,6 +122,7 @@ public static class AppBootstrapper
services.AddSingleton<PdfExportService>(); services.AddSingleton<PdfExportService>();
services.AddSingleton<ITemplateLoader, TemplateLoader>(); services.AddSingleton<ITemplateLoader, TemplateLoader>();
services.AddSingleton<ITemplateRenderer, QuestTemplateRenderer>(); services.AddSingleton<ITemplateRenderer, QuestTemplateRenderer>();
services.AddSingleton<ITemplateBatchRenderer, QuestTemplateRenderer>();
services.AddSingleton(_ => new TemplateStore(appData)); services.AddSingleton(_ => new TemplateStore(appData));
services.AddSingleton(_ => new WorksheetTemplateStore(new TemplateStore(appData, subfolder: "worksheet-template-packages"))); services.AddSingleton(_ => new WorksheetTemplateStore(new TemplateStore(appData, subfolder: "worksheet-template-packages")));
@@ -156,6 +157,7 @@ public static class AppBootstrapper
services.AddSingleton<IStudentRepository, StudentRepository>(); services.AddSingleton<IStudentRepository, StudentRepository>();
services.AddSingleton<IGroupRepository, GroupRepository>(); services.AddSingleton<IGroupRepository, GroupRepository>();
services.AddSingleton<ISeatingPlanRepository, SeatingPlanRepository>(); services.AddSingleton<ISeatingPlanRepository, SeatingPlanRepository>();
services.AddSingleton<IStudentGroupPlanRepository, StudentGroupPlanRepository>();
services.AddSingleton<ITrashRepository, TrashRepository>(); services.AddSingleton<ITrashRepository, TrashRepository>();
services.AddSingleton<IGroupMembershipRepository, GroupMembershipRepository>(); services.AddSingleton<IGroupMembershipRepository, GroupMembershipRepository>();
services.AddSingleton<IExamRepository, ExamRepository>(); services.AddSingleton<IExamRepository, ExamRepository>();
@@ -163,11 +165,13 @@ public static class AppBootstrapper
services.AddSingleton<IGradeRepository, GradeRepository>(); services.AddSingleton<IGradeRepository, GradeRepository>();
services.AddSingleton<IGradingSchemeRepository, GradingSchemeRepository>(); services.AddSingleton<IGradingSchemeRepository, GradingSchemeRepository>();
services.AddSingleton<IReportGradeRepository, ReportGradeRepository>(); services.AddSingleton<IReportGradeRepository, ReportGradeRepository>();
services.AddSingleton<IInterimGradeRepository, InterimGradeRepository>();
services.AddSingleton<IGradingKeyTemplateRepository, GradingKeyTemplateRepository>(); services.AddSingleton<IGradingKeyTemplateRepository, GradingKeyTemplateRepository>();
services.AddSingleton<IUnitRepository, UnitRepository>(); services.AddSingleton<IUnitRepository, UnitRepository>();
services.AddSingleton<ILessonRepository, LessonRepository>(); services.AddSingleton<ILessonRepository, LessonRepository>();
services.AddSingleton<IDocumentationRepository, DocumentationRepository>(); services.AddSingleton<IDocumentationRepository, DocumentationRepository>();
services.AddSingleton<IVorgangRepository, VorgangRepository>(); services.AddSingleton<IVorgangRepository, VorgangRepository>();
services.AddSingleton<IDashboardWarningSnoozeRepository, DashboardWarningSnoozeRepository>();
services.AddSingleton<IWorkTaskRepository, WorkTaskRepository>(); services.AddSingleton<IWorkTaskRepository, WorkTaskRepository>();
services.AddSingleton<ITimeEntryRepository, TimeEntryRepository>(); services.AddSingleton<ITimeEntryRepository, TimeEntryRepository>();
services.AddSingleton<IParticipationSessionRepository, ParticipationSessionRepository>(); services.AddSingleton<IParticipationSessionRepository, ParticipationSessionRepository>();
@@ -197,6 +201,7 @@ public static class AppBootstrapper
services.AddSingleton<GradingService>(); services.AddSingleton<GradingService>();
services.AddSingleton<CompetencyAnalysisService>(); services.AddSingleton<CompetencyAnalysisService>();
services.AddSingleton<SchoolYearService>(); services.AddSingleton<SchoolYearService>();
services.AddSingleton<HomeworkOverdueService>();
services.AddSingleton<GroupRolloverService>(); services.AddSingleton<GroupRolloverService>();
services.AddSingleton<PublicHolidayService>(); services.AddSingleton<PublicHolidayService>();
services.AddSingleton(_ => new SchoolCalendarSettingsService(appData)); services.AddSingleton(_ => new SchoolCalendarSettingsService(appData));
@@ -205,7 +210,9 @@ public static class AppBootstrapper
services.AddSingleton(_ => new DashboardSettingsService(appData)); services.AddSingleton(_ => new DashboardSettingsService(appData));
services.AddSingleton(_ => new PatternScoreSettingsService(appData)); services.AddSingleton(_ => new PatternScoreSettingsService(appData));
services.AddSingleton(_ => new WindowSettingsService(appData)); services.AddSingleton(_ => new WindowSettingsService(appData));
services.AddSingleton(_ => new ExamGradingSettingsService(appData));
services.AddSingleton(_ => new AppearanceSettingsService(appData)); services.AddSingleton(_ => new AppearanceSettingsService(appData));
services.AddSingleton(_ => new TeacherSettingsService(appData));
services.AddSingleton<PlanningExchangeService>(); services.AddSingleton<PlanningExchangeService>();
// ── KI-Unterstützung (4.5.9, optional – nur wenn in den Einstellungen aktiviert) ────── // ── KI-Unterstützung (4.5.9, optional – nur wenn in den Einstellungen aktiviert) ──────
@@ -231,29 +238,31 @@ public static class AppBootstrapper
services.AddSingleton<GroupMembershipTools>(); services.AddSingleton<GroupMembershipTools>();
services.AddSingleton<LetterTemplateTools>(); services.AddSingleton<LetterTemplateTools>();
services.AddSingleton<StudentAttendanceCalendarService>(); services.AddSingleton<StudentAttendanceCalendarService>();
services.AddSingleton<StudentReportService>();
services.AddSingleton<CompetencyTools>(); services.AddSingleton<CompetencyTools>();
services.AddSingleton<GroupTools>(); services.AddSingleton<GroupTools>();
services.AddSingleton<ParticipationTools>();
services.AddSingleton<UntisComparisonTools>(); services.AddSingleton<UntisComparisonTools>();
services.AddSingleton<McpServerHostedService>(); services.AddSingleton<McpServerHostedService>();
services.AddSingleton<McpClientRegistrationService>(); services.AddSingleton<McpClientRegistrationService>();
// ── WebUntis-iCal-Abgleich (optional – nur wenn URL hinterlegt und aktiviert) ───────── // ── WebUntis-Stundenplan-Abgleich (REST bei API-Zugang, sonst optionaler iCal-Fallback) ─
var untisSettings = new WebUntisSettingsService(appData); var untisSettings = new WebUntisSettingsService(appData);
services.AddSingleton(untisSettings); services.AddSingleton(untisSettings);
services.AddSingleton<UntisMatchingService>(); services.AddSingleton<UntisMatchingService>();
services.AddSingleton<UntisDiffService>(); services.AddSingleton<UntisDiffService>();
if (untisSettings.Enabled && !string.IsNullOrEmpty(untisSettings.GetIcalUrl())) services.AddSingleton(sp => new WebUntisIntegrationService(new HttpClient(), untisSettings));
{ services.AddSingleton<WebUntisRestSyncProcessor>();
services.AddSingleton(sp => new UntisSyncService( services.AddSingleton(sp => new UntisSyncService(
new HttpClient(), untisSettings, new HttpClient(), untisSettings,
sp.GetRequiredService<IUntisSnapshotRepository>(), sp.GetRequiredService<IUntisSlotMappingRepository>(), sp.GetRequiredService<IUntisSnapshotRepository>(), sp.GetRequiredService<IUntisSlotMappingRepository>(),
sp.GetRequiredService<ISubstitutionEntryRepository>(), sp.GetRequiredService<IGroupRepository>(), sp.GetRequiredService<ISubstitutionEntryRepository>(), sp.GetRequiredService<IGroupRepository>(),
sp.GetRequiredService<ITimetableSlotRepository>(), sp.GetRequiredService<ISupervisionDutyRepository>(), sp.GetRequiredService<ITimetableSlotRepository>(), sp.GetRequiredService<ISupervisionDutyRepository>(),
sp.GetRequiredService<ISchoolHolidayRepository>(), sp.GetRequiredService<PublicHolidayService>(), sp.GetRequiredService<ISchoolHolidayRepository>(), sp.GetRequiredService<PublicHolidayService>(),
sp.GetRequiredService<SchoolCalendarSettingsService>(), sp.GetRequiredService<PeriodScheduleService>(), sp.GetRequiredService<SchoolCalendarSettingsService>(), sp.GetRequiredService<PeriodScheduleService>(),
sp.GetRequiredService<UntisMatchingService>(), sp.GetRequiredService<UntisDiffService>(), sp.GetRequiredService<UntisMatchingService>(), sp.GetRequiredService<UntisDiffService>(),
sp.GetRequiredService<AppLogger>())); sp.GetRequiredService<AppLogger>(), sp.GetRequiredService<WebUntisIntegrationService>(),
} sp.GetRequiredService<WebUntisRestSyncProcessor>()));
// ── Schulweiter Jahresplan (informativer ClassyPlan-iCal, kein Stundenplan-Abgleich) ── // ── Schulweiter Jahresplan (informativer ClassyPlan-iCal, kein Stundenplan-Abgleich) ──
var annualPlanSettings = new AnnualPlanSettingsService(appData); var annualPlanSettings = new AnnualPlanSettingsService(appData);
@@ -271,7 +280,6 @@ public static class AppBootstrapper
services.AddSingleton(syncSettings); services.AddSingleton(syncSettings);
services.AddSingleton(_ => new SyncAuthService(new HttpClient())); services.AddSingleton(_ => new SyncAuthService(new HttpClient()));
services.AddSingleton(sp => new SchoolWeatherService(new HttpClient(), syncSettings)); services.AddSingleton(sp => new SchoolWeatherService(new HttpClient(), syncSettings));
services.AddSingleton(sp => new WebUntisIntegrationService(new HttpClient(), untisSettings));
services.AddSingleton<UntisReportCacheService>(); services.AddSingleton<UntisReportCacheService>();
services.AddSingleton<UntisHubService>(); services.AddSingleton<UntisHubService>();
// War dieses Gerät schon eingeloggt, aber sync.key fehlt(e), wurde gerade eben (unten) // War dieses Gerät schon eingeloggt, aber sync.key fehlt(e), wurde gerade eben (unten)
@@ -356,6 +364,8 @@ public static class AppBootstrapper
// Transient: neue Instanz pro Navigation (für Detailseiten) // Transient: neue Instanz pro Navigation (für Detailseiten)
services.AddTransient<GroupDetailViewModel>(); services.AddTransient<GroupDetailViewModel>();
services.AddTransient<StudentDetailViewModel>(); services.AddTransient<StudentDetailViewModel>();
services.AddTransient<StudentWarningEvidenceService>();
services.AddTransient<StudentVorgaengeViewModel>();
services.AddTransient<GroupOverviewViewModel>(); services.AddTransient<GroupOverviewViewModel>();
services.AddTransient<ParticipationTabViewModel>(); services.AddTransient<ParticipationTabViewModel>();
services.AddTransient<GradeOverviewTabViewModel>(); services.AddTransient<GradeOverviewTabViewModel>();
@@ -374,8 +384,12 @@ public static class AppBootstrapper
// Sync-agnostischer Hook auf LiteDbContext (siehe LiteDbContext.OnChange) wird erst hier, // Sync-agnostischer Hook auf LiteDbContext (siehe LiteDbContext.OnChange) wird erst hier,
// außerhalb der Repository-Registrierung, mit der tatsächlichen Sync-Logik verbunden. // außerhalb der Repository-Registrierung, mit der tatsächlichen Sync-Logik verbunden.
if (!string.IsNullOrEmpty(serverUrl)) if (!string.IsNullOrEmpty(serverUrl))
provider.GetRequiredService<LiteDbContext>().OnChange = {
provider.GetRequiredService<SyncEventPublisher>().Publish; var context = provider.GetRequiredService<LiteDbContext>();
var publisher = provider.GetRequiredService<SyncEventPublisher>();
context.OnChange = publisher.Publish;
publisher.BackfillCompetencyCatalog(context);
}
return provider; return provider;
} }
@@ -0,0 +1 @@
{"v":"5.7.8","fr":25,"ip":0,"op":25,"w":1080,"h":1080,"nm":"[ pecah Asset - Games Roda Keberuntungan ] EMOS - Juni","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"link-tengah Outlines","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[538.46,407.962,0],"ix":2,"l":2},"a":{"a":0,"k":[65.18,65.182,0],"ix":1,"l":2},"s":{"a":0,"k":[100,100,100],"ix":6,"l":2}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[-1.586,31.425],[-31.425,-1.586],[1.586,-31.426],[31.425,1.588]],"o":[[1.588,-31.423],[31.426,1.588],[-1.589,31.425],[-31.425,-1.586]],"v":[[-56.9,-2.875],[2.873,-56.901],[56.9,2.873],[-2.874,56.899]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ind":1,"ty":"sh","ix":2,"ks":{"a":0,"k":{"i":[[-1.668,33.037],[33.036,1.668],[1.668,-33.037],[-33.036,-1.671]],"o":[[1.67,-33.037],[-33.037,-1.668],[-1.67,33.036],[33.037,1.668]],"v":[[59.817,3.02],[3.021,-59.818],[-59.817,-3.022],[-3.022,59.818]],"c":true},"ix":2},"nm":"Path 2","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"mm","mm":1,"nm":"Merge Paths 1","mn":"ADBE Vector Filter - Merge","hd":false},{"ty":"fl","c":{"a":0,"k":[0.2196078431372549,0.28627450980392155,0.8196078431372549,1],"ix":4},"o":{"a":0,"k":100,"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[65.181,65.182],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":6,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false},{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[-28.146,-8.66],[8.66,-28.146],[28.147,8.66],[-7.333,25.672]],"o":[[28.146,8.661],[-8.66,28.144],[-28.146,-8.661],[8.09,-28.315]],"v":[[14.668,-49.317],[50.116,15.469],[-14.669,49.694],[-50.116,-13.869]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ind":1,"ty":"sh","ix":2,"ks":{"a":0,"k":{"i":[[-30.651,-9.431],[-9.431,30.652],[30.651,9.432],[9.431,-30.652]],"o":[[30.652,9.432],[9.432,-30.652],[-30.652,-9.431],[-9.431,30.651]],"v":[[-17.078,55.5],[55.499,17.076],[17.077,-55.501],[-55.5,-17.077]],"c":true},"ix":2},"nm":"Path 2","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"mm","mm":1,"nm":"Merge Paths 1","mn":"ADBE Vector Filter - Merge","hd":false},{"ty":"fl","c":{"a":0,"k":[1,1,1,1],"ix":4},"o":{"a":0,"k":100,"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[65.181,65.182],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 2","np":6,"cix":2,"bm":0,"ix":2,"mn":"ADBE Vector Group","hd":false},{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[-1.55,30.701],[30.701,1.55],[1.55,-30.701],[-30.702,-1.552]],"o":[[1.552,-30.701],[-30.701,-1.55],[-1.552,30.701],[30.701,1.55]],"v":[[55.589,2.806],[2.808,-55.59],[-55.588,-2.809],[-2.808,55.59]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0.3686274509803922,0.4470588235294118,0.8941176470588236,1],"ix":4},"o":{"a":0,"k":100,"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[65.18,65.182],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 3","np":4,"cix":2,"bm":0,"ix":3,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":25,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"Arrow Outlines","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":0,"s":[0]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":4,"s":[-17]},{"t":7,"s":[10]}],"ix":10,"x":"var $bm_rt;\n$bm_rt = loopOut('cycle', 0);"},"p":{"a":0,"k":[882.284,387.765,0],"ix":2,"l":2},"a":{"a":0,"k":[90.2,66.694,0],"ix":1,"l":2},"s":{"a":0,"k":[100,100,100],"ix":6,"l":2}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[1.184,-20.641],[-20.642,-1.186],[-1.183,20.641],[20.643,1.183]],"o":[[-1.185,20.643],[20.643,1.184],[1.186,-20.644],[-20.643,-1.185]],"v":[[-37.376,-2.145],[-2.144,37.377],[37.375,2.146],[2.145,-37.375]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0.2196078431372549,0.28627450980392155,0.8196078431372549,1],"ix":4},"o":{"a":0,"k":100,"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[112.538,63.94],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k"Line truncated
@@ -0,0 +1 @@
{"v":"5.6.6","fr":60,"ip":60,"op":120,"w":600,"h":600,"nm":"development and submittals","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"person-top-face-outlinne Outlines","parent":8,"sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[73.415,-16.001,0],"ix":2},"a":{"a":0,"k":[33.313,42.52,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[4.515,0],[2.745,1.593],[0,10.18],[-5.843,10.003],[-8.233,4.781],[-6.463,-3.719],[0,-10.181],[5.754,-10.093],[8.234,-4.692]],"o":[[-3.276,0],[-6.551,-3.718],[0,-9.561],[5.754,-10.004],[8.853,-5.046],[6.551,3.718],[0,9.561],[-5.843,10.092],[-5.223,2.921]],"v":[[-13.102,41.52],[-22.221,39.13],[-32.313,17.529],[-23.283,-12.836],[-1.505,-35.765],[22.22,-37.801],[32.313,-16.2],[23.372,14.165],[1.593,37.094]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ind":1,"ty":"sh","ix":2,"ks":{"a":0,"k":{"i":[[2.214,0],[4.161,-2.301],[5.312,-9.118],[0,-8.41],[-4.516,-2.656],[-6.816,3.895],[-0.089,0],[-5.222,9.119],[0,8.498],[4.603,2.656]],"o":[[-3.452,0],[-7.348,4.25],[-5.312,9.118],[0,7.879],[4.514,2.656],[0.089,0],[7.17,-4.16],[5.224,-9.118],[0,-7.88],[-1.682,-0.973]],"v":[[13.013,-33.995],[1.505,-30.454],[-18.06,-9.738],[-26.205,17.529],[-19.21,33.818],[-1.594,31.782],[-1.416,31.693],[17.882,11.066],[26.027,-16.2],[18.945,-32.49]],"c":true},"ix":2},"nm":"Path 2","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"mm","mm":1,"nm":"Merge Paths 1","mn":"ADBE Vector Filter - Merge","hd":false},{"ty":"st","c":{"a":0,"k":[0,0,0,1],"ix":3},"o":{"a":0,"k":100,"ix":4},"w":{"a":0,"k":0.4,"ix":5},"lc":1,"lj":1,"ml":10,"bm":0,"nm":"Stroke 1","mn":"ADBE Vector Graphic - Stroke","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0,0,1],"ix":4},"o":{"a":0,"k":100,"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[33.313,42.52],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":5,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":300,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"person-top-face-face Outlines","parent":8,"sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[73.324,-15.34,0],"ix":2},"a":{"a":0,"k":[29.464,39.069,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[-8.056,4.692],[-5.223,9.119],[0,9.295],[5.312,3.099],[8.056,-4.692],[5.223,-9.207],[0,-9.384],[-5.312,-3.098]],"o":[[8.056,-4.692],[5.312,-9.118],[0,-9.296],[-5.312,-3.098],[-8.056,4.692],[-5.312,9.119],[0,9.296],[5.312,2.833]],"v":[[0,33.773],[20.627,11.995],[29.214,-16.775],[20.627,-35.722],[0,-33.684],[-20.627,-11.818],[-29.214,17.041],[-20.627,35.986]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[1,1,1,1],"ix":4},"o":{"a":0,"k":100,"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[29.464,39.07],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":300,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"person-top-body-front-outline Outlines","parent":8,"sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[73.461,58.935,0],"ix":2},"a":{"a":0,"k":[53.718,49.646,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0.531,0],[0.443,0.266],[0,1.151],[-8.764,15.05],[-13.633,7.967],[-10.358,-5.932],[-0.886,-14.431],[0.974,-0.531],[0,0]],"o":[[-0.62,0],[-0.973,-0.531],[0.886,-14.784],[9.649,-16.732],[14.253,-8.233],[9.471,5.488],[0.088,1.151],[0,0],[-0.62,0.354]],"v":[[-49.619,48.646],[-51.214,48.204],[-52.719,45.371],[-37.846,-0.929],[-1.638,-39.173],[36.607,-42.714],[52.63,-11.906],[51.125,-9.074],[-48.025,48.204]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ind":1,"ty":"sh","ix":2,"ks":{"a":0,"k":{"i":[[4.249,0],[7.437,-4.249],[9.119,-15.758],[1.682,-12.305],[0,0],[7.171,4.161]],"o":[[-6.286,0],[-12.837,7.436],[-7.082,12.306],[0,0],[-1.063,-11.332],[-3.364,-1.948]],"v":[[22.089,-40.147],[1.372,-33.773],[-32.622,2.169],[-46.079,39.971],[46.257,-13.324],[33.508,-37.314]],"c":true},"ix":2},"nm":"Path 2","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"mm","mm":1,"nm":"Merge Paths 1","mn":"ADBE Vector Filter - Merge","hd":false},{"ty":"st","c":{"a":0,"k":[0,0,0,1],"ix":3},"o":{"a":0,"k":100,"ix":4},"w":{"a":0,"k":0.4,"ix":5},"lc":1,"lj":1,"ml":10,"bm":0,"nm":"Stroke 1",Line truncated
@@ -18,6 +18,7 @@
<PackageReference Include="Avalonia.Themes.Fluent" /> <PackageReference Include="Avalonia.Themes.Fluent" />
<PackageReference Include="Avalonia.Fonts.Inter" /> <PackageReference Include="Avalonia.Fonts.Inter" />
<PackageReference Include="Avalonia.Controls.DataGrid" /> <PackageReference Include="Avalonia.Controls.DataGrid" />
<PackageReference Include="Avalonia.Labs.Lottie" />
<PackageReference Include="CommunityToolkit.Mvvm" /> <PackageReference Include="CommunityToolkit.Mvvm" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" /> <PackageReference Include="Microsoft.Extensions.DependencyInjection" />
<PackageReference Include="QuestPDF" /> <PackageReference Include="QuestPDF" />
@@ -0,0 +1,5 @@
using System.Text.Json.Serialization;
namespace LehrerApp.Desktop.Services;
public sealed record AiAccountBalance([property: JsonRequired] decimal BalanceUsd, decimal? BalanceEur);
+66 -19
View File
@@ -74,7 +74,7 @@ public class GermanTimeOnlyJsonConverter : JsonConverter<TimeOnly>
public class AiPlanningService(HttpClient http, ILessonRepository lessons, public class AiPlanningService(HttpClient http, ILessonRepository lessons,
IGroupRepository groups, ISubjectRepository subjects, IGroupRepository groups, ISubjectRepository subjects,
ICompetencyDomainRepository competencyDomains, ICompetencyCatalogVersionRepository competencyVersions, ICompetencyDomainRepository competencyDomains, ICompetencyCatalogVersionRepository competencyVersions,
IAlternativeLessonPathRepository altPaths) IAlternativeLessonPathRepository altPaths, AppLogger logger)
{ {
// Wire-Format zum PHP-Backend ist camelCase (siehe ai-backend/) — beide Seiten sind hier // Wire-Format zum PHP-Backend ist camelCase (siehe ai-backend/) — beide Seiten sind hier
// im eigenen Zugriff, daher bewusst konsistent camelCase statt der C#-üblichen PascalCase-Defaults. // im eigenen Zugriff, daher bewusst konsistent camelCase statt der C#-üblichen PascalCase-Defaults.
@@ -93,19 +93,33 @@ public class AiPlanningService(HttpClient http, ILessonRepository lessons,
/// Websuche in substance.php (falscher Tool-Bezeichner, fehlender Beta-Header o.ä.) der /// Websuche in substance.php (falscher Tool-Bezeichner, fehlender Beta-Header o.ä.) der
/// eigentliche Grund nirgends sichtbar, nur "Die Anfrage ist fehlgeschlagen". /// eigentliche Grund nirgends sichtbar, nur "Die Anfrage ist fehlgeschlagen".
/// </summary> /// </summary>
private static async Task<AiBackendException> BuildRequestFailedExceptionAsync(HttpResponseMessage resp) private async Task<AiBackendException> BuildRequestFailedExceptionAsync(HttpResponseMessage resp)
{ {
string? backendReason = null; string? backendReason = null;
string? rawResponse = null; string? rawResponse = null;
var responseText = await resp.Content.ReadAsStringAsync();
try try
{ {
var responseText = await resp.Content.ReadAsStringAsync();
var body = JsonSerializer.Deserialize<BackendErrorResult>(responseText, JsonOptions); var body = JsonSerializer.Deserialize<BackendErrorResult>(responseText, JsonOptions);
backendReason = string.IsNullOrWhiteSpace(body?.Error) ? null : body!.Error; backendReason = string.IsNullOrWhiteSpace(body?.Error) ? null : body!.Error;
rawResponse = string.IsNullOrWhiteSpace(body?.RawResponse) ? null : body!.RawResponse; rawResponse = string.IsNullOrWhiteSpace(body?.RawResponse) ? null : body!.RawResponse;
} }
catch { /* Antwortkörper war kein valides {"error": "..."}-JSON - Fallback unten greift. */ } catch { /* Antwortkörper war kein valides {"error": "..."}-JSON - Fallback unten greift. */ }
// Diagnose für "sofortige, grundlose" Fehlschläge (2026-09-21): das Backend selbst liefert
// bei jedem eigenen Fehlerpfad ein {"error": "..."} zurück (ai_backend_fail) - landet der
// Fallback unten trotzdem ohne Grund, kam die Antwort nie bei plan.php an (Proxy/Webserver-
// Fehlerseite, z.B. 413 Payload Too Large) oder PHP ist mitten im Request abgestürzt. Ohne
// Content-Type/Statuscode/Rohtext lässt sich das von hier aus nicht unterscheiden.
if (backendReason is null)
{
logger.Warn("AiPlanningService: Backend-Fehler ohne auswertbaren Grund. " +
$"Status={(int)resp.StatusCode} {resp.StatusCode}, " +
$"Content-Type={resp.Content.Headers.ContentType?.MediaType ?? "(keiner)"}, " +
$"Body-Länge={responseText.Length}, " +
$"Body (erste 500 Zeichen)={responseText[..Math.Min(500, responseText.Length)]}");
}
return new AiBackendException(backendReason is null return new AiBackendException(backendReason is null
? "Die Anfrage an den KI-Dienst ist fehlgeschlagen." ? "Die Anfrage an den KI-Dienst ist fehlgeschlagen."
: $"Die Anfrage an den KI-Dienst ist fehlgeschlagen: {backendReason}", rawResponse); : $"Die Anfrage an den KI-Dienst ist fehlgeschlagen: {backendReason}", rawResponse);
@@ -132,25 +146,49 @@ public class AiPlanningService(HttpClient http, ILessonRepository lessons,
return result?.Token ?? throw new AiBackendException("Unerwartete Antwort des KI-Dienstes."); return result?.Token ?? throw new AiBackendException("Unerwartete Antwort des KI-Dienstes.");
} }
public async Task<decimal> GetBalanceAsync(string token) public async Task<decimal> GetBalanceAsync(string token) =>
{ (await GetAccountBalanceAsync(token)).BalanceUsd;
using var req = new HttpRequestMessage(HttpMethod.Get, "status.php");
req.Headers.Authorization = new("Bearer", token);
public async Task<AiAccountBalance> GetAccountBalanceAsync(string token)
{
using var resp = await GetAccountResponseAsync("status.php", token);
try
{
return await resp.Content.ReadFromJsonAsync<AiAccountBalance>(JsonOptions)
?? throw new AiBackendException("Das Guthaben des KI-Dienstes konnte nicht verarbeitet werden.");
}
catch (JsonException)
{
throw new AiBackendException("Das Guthaben des KI-Dienstes konnte nicht verarbeitet werden.");
}
}
public async Task<AiUsageReport> GetUsageAsync(string token)
{
using var resp = await GetAccountResponseAsync("api/v1/usage.php?days=28", token);
return AiUsageReport.Parse(await resp.Content.ReadAsStringAsync());
}
private async Task<HttpResponseMessage> GetAccountResponseAsync(string path, string token)
{
using var req = new HttpRequestMessage(HttpMethod.Get, path);
req.Headers.Authorization = new("Bearer", token);
HttpResponseMessage resp; HttpResponseMessage resp;
try { resp = await http.SendAsync(req); } try { resp = await http.SendAsync(req); }
catch (HttpRequestException) catch (Exception ex) when (ex is HttpRequestException or OperationCanceledException)
{ {
throw new AiBackendException("Der KI-Dienst ist nicht erreichbar. Bitte Internetverbindung prüfen."); throw new AiBackendException("Der KI-Dienst ist nicht erreichbar. Bitte später erneut versuchen.");
} }
if (resp.IsSuccessStatusCode) return resp;
if (resp.StatusCode == HttpStatusCode.Unauthorized) var status = resp.StatusCode;
throw new AiBackendException("Anmeldung abgelaufen. Bitte in den Einstellungen erneut anmelden."); resp.Dispose();
if (!resp.IsSuccessStatusCode) throw new AiBackendException(status switch
throw new AiBackendException("Guthaben konnte nicht abgerufen werden."); {
HttpStatusCode.Unauthorized => "Anmeldung abgelaufen. Bitte in den Einstellungen erneut anmelden.",
var result = await resp.Content.ReadFromJsonAsync<BalanceResult>(JsonOptions); HttpStatusCode.NotFound when path.StartsWith("api/v1/usage") =>
return result?.BalanceUsd ?? 0m; "Dieses Backend stellt noch keine Verbrauchsübersicht bereit.",
_ => "Die Kontodaten des KI-Dienstes konnten nicht abgerufen werden."
});
} }
/// <summary>Rein (nur Repository-Lesezugriffe, kein Netzwerk) — testbar mit Fakes.</summary> /// <summary>Rein (nur Repository-Lesezugriffe, kein Netzwerk) — testbar mit Fakes.</summary>
@@ -354,19 +392,29 @@ public class AiPlanningService(HttpClient http, ILessonRepository lessons,
Content = JsonContent.Create(request, options: JsonOptions), Content = JsonContent.Create(request, options: JsonOptions),
}; };
req.Headers.Authorization = new("Bearer", token); req.Headers.Authorization = new("Bearer", token);
var requestBytes = await req.Content!.ReadAsByteArrayAsync();
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
HttpResponseMessage resp; HttpResponseMessage resp;
try { resp = await http.SendAsync(req); } try { resp = await http.SendAsync(req); }
catch (TaskCanceledException) catch (TaskCanceledException)
{ {
logger.Warn($"AiPlanningService: plan.php-Anfrage nach {stopwatch.ElapsedMilliseconds}ms " +
$"abgebrochen (Client-Timeout), Request-Größe={requestBytes.Length} Bytes.");
throw new AiBackendException( throw new AiBackendException(
"Die KI-Anfrage hat länger als 3½ Minuten gedauert und wurde beendet. " + "Die KI-Anfrage hat länger als 3½ Minuten gedauert und wurde beendet. " +
"Falls das wiederholt passiert, bitte das Zeitlimit des Webserver-Proxys prüfen."); "Falls das wiederholt passiert, bitte das Zeitlimit des Webserver-Proxys prüfen.");
} }
catch (HttpRequestException) catch (HttpRequestException ex)
{ {
logger.Warn($"AiPlanningService: plan.php-Anfrage nach {stopwatch.ElapsedMilliseconds}ms " +
$"ohne Antwort gescheitert, Request-Größe={requestBytes.Length} Bytes: {ex.Message}");
throw new AiBackendException("Der KI-Dienst ist nicht erreichbar. Bitte Internetverbindung prüfen."); throw new AiBackendException("Der KI-Dienst ist nicht erreichbar. Bitte Internetverbindung prüfen.");
} }
stopwatch.Stop();
if (!resp.IsSuccessStatusCode)
logger.Warn($"AiPlanningService: plan.php antwortete nach {stopwatch.ElapsedMilliseconds}ms " +
$"mit {(int)resp.StatusCode} {resp.StatusCode}, Request-Größe={requestBytes.Length} Bytes.");
if (resp.StatusCode == HttpStatusCode.Unauthorized) if (resp.StatusCode == HttpStatusCode.Unauthorized)
throw new AiBackendException("Anmeldung abgelaufen. Bitte in den Einstellungen erneut anmelden."); throw new AiBackendException("Anmeldung abgelaufen. Bitte in den Einstellungen erneut anmelden.");
@@ -671,7 +719,6 @@ public class AiPlanningService(HttpClient http, ILessonRepository lessons,
} }
private class LoginResult { public string Token { get; set; } = ""; } private class LoginResult { public string Token { get; set; } = ""; }
private class BalanceResult { public decimal BalanceUsd { get; set; } }
private class BackendErrorResult private class BackendErrorResult
{ {
public string? Error { get; set; } public string? Error { get; set; }
@@ -0,0 +1,86 @@
using System.Globalization;
using System.Text.Json;
namespace LehrerApp.Desktop.Services;
/// <summary>Verbrauch einer Aktion im Zeitraum, z. B. „Text korrigieren“ oder eine Planung der LehrerApp (alle Apps am selben Backend).</summary>
/// <param name="Operation">Funktion der Arbeitsblatt-API; null bei Aktionen anderer Apps.</param>
/// <param name="ChargedEur">Nur, wenn für jeden Aufruf der Euro-Gegenwert dokumentiert ist; sonst null (der Dienst schätzt nichts).</param>
public sealed record AiUsageGroup(string ActionId, string Label, string? Operation, int Calls, decimal ChargedUsd, decimal? ChargedEur);
/// <summary>Ein berechneter Aufruf. <see cref="At"/> ist die Uhrzeit der Datenbank des Dienstes, ohne Zeitzone.</summary>
public sealed record AiUsageEntry(DateTime At, string ActionId, string Label, string? Operation, string Status, decimal ChargedUsd, decimal? ChargedEur);
/// <param name="SpellcheckGranted">Ob die Rechtschreibprüfung über das Backend freigegeben ist; null, wenn der Dienst es nicht meldet.</param>
public sealed record AiUsageReport(int Days, DateTime From, DateTime To, int Calls, decimal ChargedUsd, decimal? ChargedEur,
IReadOnlyList<AiUsageGroup> ByAction, IReadOnlyList<AiUsageEntry> Entries, bool EntriesTruncated, bool? SpellcheckGranted)
{
/// <summary>
/// Liest die Antwort von <c>api/v1/usage.php</c>. Unbekannte zusätzliche Felder werden übergangen (der Dienst darf wachsen), fehlende oder
/// unplausible Pflichtfelder sind ein Fehler.
/// </summary>
public static AiUsageReport Parse(string json)
{
try
{
using var document = JsonDocument.Parse(json, new JsonDocumentOptions { MaxDepth = 16 });
var root = document.RootElement;
Need(root.GetProperty("apiVersion").GetString() == "1" && root.GetProperty("schema").GetString() == "lehrerbackend.usage.v1");
var period = root.GetProperty("period");
var days = period.GetProperty("days").GetInt32();
var totals = root.GetProperty("totals");
var groups = new List<AiUsageGroup>();
foreach (var item in root.GetProperty("byAction").EnumerateArray())
{
Need(groups.Count < 256);
groups.Add(new(Text(item, "actionId", 64), Text(item, "label", 200), Operation(item), item.GetProperty("calls").GetInt32(),
RequiredMoney(item, "chargedUsd"), Money(item, "chargedEur")));
}
var entries = new List<AiUsageEntry>();
foreach (var item in root.GetProperty("entries").EnumerateArray())
{
Need(entries.Count < 1000);
entries.Add(new(Date(item.GetProperty("at").GetString()), Text(item, "actionId", 64), Text(item, "label", 200), Operation(item), Text(item, "status", 32),
RequiredMoney(item, "chargedUsd"), Money(item, "chargedEur")));
}
bool? spellcheck = root.TryGetProperty("features", out var features) && features.TryGetProperty("spellcheck", out var flag) && flag.ValueKind is JsonValueKind.True or JsonValueKind.False
? flag.GetBoolean() : null;
var calls = totals.GetProperty("calls").GetInt32();
Need(days is >= 1 and <= 366 && calls >= 0 && groups.All(g => g.Calls >= 0 && g.ChargedUsd >= 0 && g.ChargedEur is null or >= 0) && entries.All(e => e.ChargedUsd >= 0));
return new(days, Date(period.GetProperty("from").GetString()), Date(period.GetProperty("to").GetString()), calls, RequiredMoney(totals, "chargedUsd"), Money(totals, "chargedEur"),
groups, entries, root.GetProperty("entriesTruncated").GetBoolean(), spellcheck);
}
catch (Exception e) when (e is JsonException or InvalidOperationException or KeyNotFoundException or FormatException or ArgumentException or OverflowException)
{ throw new AiBackendException("Die Verbrauchsdaten des KI-Dienstes konnten nicht verarbeitet werden."); }
}
private static void Need(bool condition) { if (!condition) throw new FormatException(); }
private static string Text(JsonElement item, string name, int max)
{
var value = item.GetProperty(name).GetString();
Need(!string.IsNullOrWhiteSpace(value) && value.Length <= max);
return value!;
}
private static string? Operation(JsonElement item) =>
item.TryGetProperty("operation", out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null;
private static decimal RequiredMoney(JsonElement item, string name) =>
Money(item, name) ?? throw new FormatException();
private static decimal? Money(JsonElement item, string name)
{
if (!item.TryGetProperty(name, out var value) || value.ValueKind == JsonValueKind.Null) return null;
// Dezimaltext mit höchstens sechs Nachkommastellen wie im ganzen Vertrag, nie eine Fließkommazahl
var text = value.GetString();
Need(text is not null && System.Text.RegularExpressions.Regex.IsMatch(text, @"^\d{1,9}(\.\d{1,6})?$"));
return decimal.Parse(text!, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture);
}
private static DateTime Date(string? text)
{
Need(DateTime.TryParseExact(text, "yyyy-MM-dd'T'HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out _));
return DateTime.ParseExact(text!, "yyyy-MM-dd'T'HH:mm:ss", CultureInfo.InvariantCulture);
}
}
@@ -0,0 +1,85 @@
using System.Globalization;
using LehrerApp.Core.Models;
using LehrerApp.Core.Services;
using LehrerApp.Desktop.ViewModels.Groups;
using LehrerApp.Templating;
namespace LehrerApp.Desktop.Services;
/// <summary>Platzhalterwerte für Klausur-Deckblätter (Vorlagen mit
/// <c>report-type=exam-cover</c>): die Standardwerte der Elternbriefe (Student.*, Group.Name, …)
/// plus Exam.*, Result.* und die Punktetabelle. Alle Punktwerte gelten für die Fassung, die der
/// Schüler geschrieben hat.</summary>
public static class ExamCoverPlaceholderBuilder
{
/// <summary>Stehen statt Punkten bzw. Note auf dem Blatt, solange nichts eingetragen wird —
/// als Linie zum Ausfüllen von Hand.</summary>
public const string BlankPoints = "_________", BlankGrade = "_____";
private static readonly CultureInfo German = CultureInfo.GetCultureInfo("de-DE");
/// <param name="result">Ergebnis des Schülers oder null. Punkte und Note werden nur
/// eingetragen, wenn <paramref name="fillResults"/> gesetzt und das Ergebnis korrigiert ist.</param>
/// <param name="studentNiveau">Niveau des Schülers in dieser Lerngruppe, falls die Arbeit
/// selbst keinem Niveau zugeordnet ist.</param>
/// <param name="title">Titel für das Deckblatt, falls er vom internen Klausurtitel abweichen
/// soll; null oder leer nimmt den Klausurtitel.</param>
public static Dictionary<string, PlaceholderValue> Build(Exam exam, LearningGroup group, string subjectName,
Student student, ExamResult? result, bool fillResults, GradingService grading, LoadedTemplate template,
DateOnly today, Niveau? studentNiveau = null, string teacherAbbreviation = "",
string? title = null, Exam? original = null, ExamResult? originalResult = null,
InterimGrade? interim = null)
{
var tasks = exam.Tasks.OrderBy(t => t.Nr).ToList();
var variant = result?.Variant ?? ExamVariant.A;
var maximum = ExamScoringService.Maximum(tasks, variant);
var filled = fillResults && ExamCoverSheetService.IsCorrected(result);
var values = LetterPlaceholderBuilder.BuildStandardValues(student, contact: null, group, today, "", "");
values["Group.GradeLevel"] = new TextValue(group.GradeLevel > 0 ? group.GradeLevel.ToString() : "");
values["Subject.Name"] = new TextValue(subjectName);
values["Exam.Title"] = new TextValue(string.IsNullOrWhiteSpace(title) ? exam.Title : title.Trim());
values["Exam.Date"] = new DateValue(exam.Date);
values["Exam.Number"] = new TextValue(exam.ExamNumber?.ToString() ?? "");
values["Exam.Kind"] = new TextValue(exam.Kind.Label());
values["Exam.Niveau"] = new TextValue(exam.Niveau.HasValue ? NiveauDisplay.ToName(exam.Niveau) : "");
values["Exam.Course"] = new TextValue(CourseLabel(group, exam.Niveau ?? studentNiveau));
values["Teacher.Abbreviation"] = new TextValue(teacherAbbreviation.Trim());
values["Exam.Variant"] = new TextValue(tasks.Any(t => t.Variant is not null) ? variant.ToString() : "");
values["Exam.MaxPoints"] = new TextValue(Format(maximum));
values["Exam.ApprovalDate"] = new TextValue(Format(exam.ApprovalGrantedAt));
values["Exam.AnnouncedDate"] = new TextValue(Format(exam.AnnouncedAt));
values["Exam.ReturnDate"] = new TextValue(Format(exam.ReturnedAt));
values["Result.Points"] = new TextValue(filled ? Format(result!.TotalPoints) : BlankPoints);
values["Result.Percent"] = new TextValue(filled && maximum > 0
? (result!.TotalPoints / maximum).ToString("0 %", German) : "");
values["Result.Grade"] = new TextValue(filled
? result!.Grade ?? grading.CalculateGrade(result.TotalPoints, maximum, exam.GradingKey) : BlankGrade);
// Ohne Box in der Vorlage gibt es nichts zu zeichnen (die Tabelle ist optional).
values[ExamPointsTableDrawingBuilder.PlaceholderName] =
LetterPlaceholderBuilder.FindDeclaredDrawingBox(template, ExamPointsTableDrawingBuilder.PlaceholderName) is { } box
? ExamPointsTableDrawingBuilder.Build(
ExamCoverSheetService.Columns(tasks, variant, filled ? result!.Points : null),
box.Width, box.MillimeterScale)
: new DrawingValue([], 0);
values[ReportTextDrawing.RepeatInfo] = DrawingBoxLocator.Find(template, ReportTextDrawing.RepeatInfo) is null
? new DrawingValue([], 0) : GradeReportDrawingBuilder.Repeat(exam, original, originalResult, template);
values[ReportTextDrawing.InterimGrades] = interim is null
? new DrawingValue([], 0) : GradeReportDrawingBuilder.Interim(interim, template);
return values;
}
/// <summary>"E-Kurs" / "G-Kurs" für die äußere Differenzierung; leer im Klassenverband und
/// ohne E-/G-Zuordnung.</summary>
public static string CourseLabel(LearningGroup group, Niveau? niveau) =>
group.Type == GroupType.Class ? "" : niveau switch
{
Niveau.E => "E-Kurs",
Niveau.G => "G-Kurs",
_ => "",
};
private static string Format(double value) => value.ToString("0.##", German);
private static string Format(DateOnly? date) => date?.ToString("dd.MM.yyyy", CultureInfo.InvariantCulture) ?? "";
}
@@ -0,0 +1,35 @@
using Avalonia.Controls;
using LehrerApp.Core.Interfaces;
using LehrerApp.Core.Models;
using LehrerApp.Core.Services;
using LehrerApp.Desktop.ViewModels.Groups;
using LehrerApp.Desktop.Views.Groups;
using LehrerApp.Templating;
using Microsoft.Extensions.DependencyInjection;
namespace LehrerApp.Desktop.Services;
/// <summary>Öffnet den Deckblatt-Dialog zu einer Klausur — ein Einstieg für die Klausuren-
/// Hauptseite und den Klausuren-Tab der Lerngruppe.</summary>
public static class ExamCoverSheetDialogs
{
public static async Task ShowAsync(Control source, Exam exam)
{
var group = App.Services.GetRequiredService<IGroupRepository>().GetById(exam.GroupId);
if (group is null || TopLevel.GetTopLevel(source) is not Window owner) return;
var subject = group.SubjectId is { } subjectId
? App.Services.GetRequiredService<ISubjectRepository>().GetById(subjectId)?.Name ?? ""
: "";
var vm = new ExamCoverSheetDialogViewModel(exam, group, subject,
App.Services.GetRequiredService<IStudentRepository>(),
App.Services.GetRequiredService<IGroupMembershipRepository>(),
App.Services.GetRequiredService<IExamResultRepository>(),
App.Services.GetRequiredService<GradingService>(),
[App.Services.GetRequiredService<TemplateStore>(), App.Services.GetRequiredService<WorksheetTemplateStore>().Store],
App.Services.GetRequiredService<ITemplateBatchRenderer>(),
App.Services.GetRequiredService<TeacherSettingsService>().LoadAbbreviation(),
App.Services.GetRequiredService<IExamRepository>(),
App.Services.GetRequiredService<IInterimGradeRepository>());
await new ExamCoverSheetDialog { DataContext = vm }.ShowDialog(owner);
}
}
@@ -0,0 +1,21 @@
using LehrerApp.Core.Services;
using LehrerApp.Templating;
namespace LehrerApp.Desktop.Services;
/// <summary>Brücke von den Klausurdaten zur Punktetabelle des Deckblatts. Gezeichnet wird in
/// <see cref="ExamPointsTableDrawing"/> (Vorlagenbibliothek), damit der Vorlagen-Designer dieselbe
/// Tabelle in der Vorschau zeigt.</summary>
public static class ExamPointsTableDrawingBuilder
{
public const string PlaceholderName = ExamPointsTableDrawing.PlaceholderName;
public static DrawingValue Build(IReadOnlyList<ExamCoverTaskColumn> columns, float contentWidth = 170,
float millimeterScale = 1) =>
ExamPointsTableDrawing.Build(
columns.Select(c => new ExamPointsTableColumn(c.Number, c.MaxPoints, c.IsBonus, c.AchievedPoints)).ToList(),
contentWidth, millimeterScale);
public static int ColumnsPerBlock(float contentWidth, float millimeterScale = 1) =>
ExamPointsTableDrawing.ColumnsPerBlock(contentWidth, millimeterScale);
}
@@ -0,0 +1,51 @@
using LehrerApp.Core.Models;
using LehrerApp.Core.Services;
using LehrerApp.Templating;
namespace LehrerApp.Desktop.Services;
public static class GradeReportDrawingBuilder
{
public static DrawingValue Interim(InterimGrade grade, LoadedTemplate template) =>
Text(template, ReportTextDrawing.InterimGrades, "Vorläufiger Notenzwischenstand",
[
$"Stichtag: {grade.Date:dd.MM.yyyy} · {grade.Occasion}",
$"Mündlich: {Value(grade.OralValue)}",
$"Schriftlich: {Value(grade.WrittenValue)}",
$"Vorläufige Zeugnisnote: {Value(grade.OverallValue)}",
"Dieser Zwischenstand ist keine festgeschriebene Zeugnisnote.",
]);
public static DrawingValue Repeat(Exam exam, Exam? original, ExamResult? originalResult,
LoadedTemplate template)
{
if (exam.RepeatOfExamId is null) return new DrawingValue([], 0);
if (original is null || original.Id != exam.RepeatOfExamId || original.GroupId != exam.GroupId)
throw new InvalidDataException("Die verknüpfte erste Arbeit ist nicht verfügbar.");
var rule = exam.IsSupportWork ? "Die Förderarbeit ersetzt die erste Arbeit. Liegen beide Noten vor, zählt die erste Arbeit."
: exam.IsMakeUp ? "Die Nachschreibarbeit ersetzt die versäumte erste Arbeit. Liegen beide Noten vor, zählt die erste Arbeit."
: exam.RepeatGradeRule switch
{
RepeatGradeRule.Repeat => "Für die Bewertung zählt die Note der Wiederholungsarbeit.",
RepeatGradeRule.Original => "Für die Bewertung zählt die Note der ersten Arbeit.",
_ => "Für die Bewertung zählt die bessere Note aus beiden Arbeiten.",
};
var grade = originalResult?.Grade;
if (string.IsNullOrWhiteSpace(grade) && ExamCoverSheetService.IsCorrected(originalResult))
grade = new GradingService().CalculateGrade(originalResult!.TotalPoints,
ExamScoringService.Maximum(original.Tasks, originalResult.Variant), original.GradingKey);
var firstGrade = originalResult is { Absent: true } ? "abwesend" : Value(grade);
return Text(template, ReportTextDrawing.RepeatInfo,
exam.IsSupportWork ? "Förderarbeit" : exam.IsMakeUp ? "Nachschreibarbeit" : "Wiederholungsarbeit",
[$"Erste Arbeit: {original.Title} vom {original.Date:dd.MM.yyyy}",
$"Note der ersten Arbeit: {firstGrade}", rule]);
}
public static DrawingValue Text(LoadedTemplate template, string name, string title, IEnumerable<string> paragraphs)
{
if (DrawingBoxLocator.Find(template, name) is not { } box) return new DrawingValue([], 0);
return ReportTextDrawing.Build(title, paragraphs, box.Width, box.MillimeterScale, box.Height, box.IsFixed);
}
private static string Value(string? value) => string.IsNullOrWhiteSpace(value) ? "nicht erfasst" : value;
}
@@ -0,0 +1,33 @@
using LehrerApp.Core.Interfaces;
using LehrerApp.Core.Models;
namespace LehrerApp.Desktop.Services;
/// <summary>Schließt nicht nachgereichte Hausaufgaben 14 Kalendertage nach der Unterrichtsstunde.
/// Nur noch offene Nachreichungen werden geändert; andere Stati und archivierte Gruppen bleiben
/// unangetastet.</summary>
public sealed class HomeworkOverdueService(
IGroupRepository groups, IParticipationSessionRepository sessions,
IParticipationRepository participation)
{
public const int GracePeriodDays = 14;
public int Advance(DateOnly today)
{
var cutoff = today.AddDays(-GracePeriodDays);
var activeGroupIds = groups.GetAll().Where(g => g.IsActive).Select(g => g.Id).ToHashSet();
var changed = 0;
foreach (var session in sessions.GetAll()
.Where(s => s.Date <= cutoff && activeGroupIds.Contains(s.GroupId)))
foreach (var entry in participation.GetBySession(session.Id))
{
if (entry.Homework != HomeworkStatus.MissingOpen &&
!(entry.Homework is null && entry.HomeworkMissing)) continue;
entry.Homework = HomeworkStatus.MissingOverdue;
entry.HomeworkMissing = true;
participation.Save(entry);
changed++;
}
return changed;
}
}
@@ -51,34 +51,8 @@ public static class LetterPlaceholderBuilder
_ => false, _ => false,
}; };
/// <summary>Tatsächliche DRAWBOX/FLOWDRAWBOX-Größe eines Platzhalters (in der Maßeinheit der /// <summary>Siehe <see cref="DrawingBoxLocator"/> — dort liegt die Suche, damit auch der
/// Vorlage) plus dem Umrechnungsfaktor "1mm in dieser Maßeinheit". DrawingValue-Builder wie /// Vorlagen-Designer sie nutzen kann.</summary>
/// <see cref="StudentAttendanceCalendarDrawingBuilder"/> entwerfen ihr Raster in Millimetern;
/// ohne MillimeterScale bliebe das bei einer in "pt" (statt "mm") deklarierten Vorlage viel zu
/// klein (1 "mm-Einheit" würde als 1pt ≈ 0.35mm gerendert). IsFixed unterscheidet DRAWBOX (feste,
/// nicht umbrechende Box - Inhalt, der die Höhe sprengt, wird von QuestTemplateRenderer
/// stillschweigend am unteren Rand abgeschnitten statt umzubrechen) von FLOWDRAWBOX (fließt bei
/// Bedarf automatisch auf weitere Seiten, siehe DrawingElementRenderer.Slice) - nur bei
/// IsFixed=true darf/muss ein Builder seine Höhe an Height anpassen.</summary>
public readonly record struct DeclaredDrawingBox(float Width, float Height, float MillimeterScale, bool IsFixed);
public static DeclaredDrawingBox? FindDeclaredDrawingBox(LoadedTemplate template, string placeholderName) => public static DeclaredDrawingBox? FindDeclaredDrawingBox(LoadedTemplate template, string placeholderName) =>
FindDeclaredDrawingBox(template.Layout, placeholderName) ?? DrawingBoxLocator.Find(template, placeholderName);
(template.ContinuationLayout is not null ? FindDeclaredDrawingBox(template.ContinuationLayout, placeholderName) : null);
private static DeclaredDrawingBox? FindDeclaredDrawingBox(TemplateLayout layout, string placeholderName)
{
var box = layout.Elements.Concat(layout.PageTemplates.SelectMany(p => p.Elements))
.Concat(layout.ContentFlows.SelectMany(f => f.Elements))
.Select(e => e switch
{
DrawBoxElement draw when draw.Placeholder == placeholderName => ((float Width, float Height, bool IsFixed)?)(draw.Width, draw.Height, true),
FlowDrawBoxElement flow when flow.Placeholder == placeholderName => (flow.Width, flow.Height, false),
_ => null,
})
.FirstOrDefault(b => b is not null);
if (box is null) return null;
var millimeterScale = UnitConverter.Points(1, "mm") / UnitConverter.Points(1, layout.Unit);
return new DeclaredDrawingBox(box.Value.Width, box.Value.Height, millimeterScale, box.Value.IsFixed);
}
} }
@@ -32,13 +32,15 @@ public sealed class McpServerHostedService : IAsyncDisposable
StudentTools studentTools, ExamTools examTools, GradeTools gradeTools, StudentTools studentTools, ExamTools examTools, GradeTools gradeTools,
ScheduleTools scheduleTools, TimeEntryTools timeEntryTools, LessonPlanTools lessonPlanTools, ScheduleTools scheduleTools, TimeEntryTools timeEntryTools, LessonPlanTools lessonPlanTools,
GroupMembershipTools groupMembershipTools, LetterTemplateTools letterTemplateTools, GroupMembershipTools groupMembershipTools, LetterTemplateTools letterTemplateTools,
CompetencyTools competencyTools, UntisComparisonTools untisComparisonTools, GroupTools groupTools) CompetencyTools competencyTools, UntisComparisonTools untisComparisonTools, GroupTools groupTools,
ParticipationTools participationTools)
{ {
_settings = settings; _settings = settings;
_logger = logger; _logger = logger;
_serverOptions = BuildServerOptions( _serverOptions = BuildServerOptions(
studentTools, examTools, gradeTools, scheduleTools, timeEntryTools, lessonPlanTools, studentTools, examTools, gradeTools, scheduleTools, timeEntryTools, lessonPlanTools,
groupMembershipTools, letterTemplateTools, competencyTools, untisComparisonTools, groupTools); groupMembershipTools, letterTemplateTools, competencyTools, untisComparisonTools, groupTools,
participationTools);
} }
/// <summary>Setzt die Pipe-Server-Accept-Loop auf, falls aktiviert. Ohne Wirkung, falls /// <summary>Setzt die Pipe-Server-Accept-Loop auf, falls aktiviert. Ohne Wirkung, falls
@@ -115,7 +117,8 @@ public sealed class McpServerHostedService : IAsyncDisposable
StudentTools studentTools, ExamTools examTools, GradeTools gradeTools, StudentTools studentTools, ExamTools examTools, GradeTools gradeTools,
ScheduleTools scheduleTools, TimeEntryTools timeEntryTools, LessonPlanTools lessonPlanTools, ScheduleTools scheduleTools, TimeEntryTools timeEntryTools, LessonPlanTools lessonPlanTools,
GroupMembershipTools groupMembershipTools, LetterTemplateTools letterTemplateTools, GroupMembershipTools groupMembershipTools, LetterTemplateTools letterTemplateTools,
CompetencyTools competencyTools, UntisComparisonTools untisComparisonTools, GroupTools groupTools) CompetencyTools competencyTools, UntisComparisonTools untisComparisonTools, GroupTools groupTools,
ParticipationTools participationTools)
{ {
var toolCollection = new McpServerPrimitiveCollection<McpServerTool>(); var toolCollection = new McpServerPrimitiveCollection<McpServerTool>();
@@ -187,6 +190,8 @@ public sealed class McpServerHostedService : IAsyncDisposable
"Listet anonymisierte Fehlzeiten-Diskrepanzen einer Lerngruppe gegenüber WebUntis (keine Schülernamen, nur eine row-id je Zeile)."); "Listet anonymisierte Fehlzeiten-Diskrepanzen einer Lerngruppe gegenüber WebUntis (keine Schülernamen, nur eine row-id je Zeile).");
AddReadTool(untisComparisonTools.GetNamedUntisAbsencePattern, "get_named_untis_absence_pattern", AddReadTool(untisComparisonTools.GetNamedUntisAbsencePattern, "get_named_untis_absence_pattern",
"Liefert Fehlzeiten MIT Schülername für explizit angegebene Schüler-IDs - Ausnahme von der sonstigen Anonymisierung, erfordert jedes Mal eine gesonderte Nutzerbestätigung."); "Liefert Fehlzeiten MIT Schülername für explizit angegebene Schüler-IDs - Ausnahme von der sonstigen Anonymisierung, erfordert jedes Mal eine gesonderte Nutzerbestätigung.");
AddReadTool(participationTools.GetParticipationSessions, "get_participation_sessions",
"Listet Mitarbeit-Sitzungen einer Lerngruppe (Datum, Kommentar, zugeordnete Kompetenzen), ohne die einzelnen Schülerbewertungen.");
AddWriteTool(timeEntryTools.CreateTimeEntry, "create_time_entry", AddWriteTool(timeEntryTools.CreateTimeEntry, "create_time_entry",
"Schlägt einen neuen Zeiterfassungs-Eintrag vor (Bestätigung durch den Nutzer nötig)."); "Schlägt einen neuen Zeiterfassungs-Eintrag vor (Bestätigung durch den Nutzer nötig).");
@@ -236,6 +241,10 @@ public sealed class McpServerHostedService : IAsyncDisposable
"Ändert Name/Standardstatus einer Bildungsplan-Version (Bestätigung durch den Nutzer nötig)."); "Ändert Name/Standardstatus einer Bildungsplan-Version (Bestätigung durch den Nutzer nötig).");
AddWriteTool(groupTools.UpdateGroupCompetencyVersion, "update_group_competency_version", AddWriteTool(groupTools.UpdateGroupCompetencyVersion, "update_group_competency_version",
"Setzt oder löscht die Bildungsplan-Version eines Kurses/einer Klasse (Bestätigung durch den Nutzer nötig)."); "Setzt oder löscht die Bildungsplan-Version eines Kurses/einer Klasse (Bestätigung durch den Nutzer nötig).");
AddWriteTool(participationTools.AddSessionCompetency, "add_session_competency",
"Ordnet einer Mitarbeit-Sitzung eine Kompetenz zu (Bestätigung durch den Nutzer nötig).");
AddWriteTool(participationTools.RemoveSessionCompetency, "remove_session_competency",
"Entfernt eine Kompetenz von einer Mitarbeit-Sitzung (Bestätigung durch den Nutzer nötig).");
AddWriteTool(untisComparisonTools.ApplyUntisAbsenceStatus, "apply_untis_absence_status", AddWriteTool(untisComparisonTools.ApplyUntisAbsenceStatus, "apply_untis_absence_status",
"Übernimmt einen Statusvorschlag für eine über get_untis_absence_rows gelieferte row-id (Bestätigung durch den Nutzer nötig, nennt keinen Schülernamen)."); "Übernimmt einen Statusvorschlag für eine über get_untis_absence_rows gelieferte row-id (Bestätigung durch den Nutzer nötig, nennt keinen Schülernamen).");
@@ -34,6 +34,7 @@ public static class McpToolScope
"get_untis_hub_status", "get_untis_hub_status",
"get_untis_absence_rows", "get_untis_absence_rows",
"get_named_untis_absence_pattern", "get_named_untis_absence_pattern",
"get_participation_sessions",
]; ];
/// <summary>Write-Tools (Phase 2+3) — jeder Aufruf läuft über <see cref="IMcpConfirmationService"/>, /// <summary>Write-Tools (Phase 2+3) — jeder Aufruf läuft über <see cref="IMcpConfirmationService"/>,
@@ -67,6 +68,8 @@ public static class McpToolScope
"create_competency_plan_version", "create_competency_plan_version",
"update_competency_plan_version", "update_competency_plan_version",
"update_group_competency_version", "update_group_competency_version",
"add_session_competency",
"remove_session_competency",
"apply_untis_absence_status", "apply_untis_absence_status",
]; ];
@@ -39,6 +39,12 @@ public record LessonAttachmentDto(string StorageId, string FileName, long SizeBy
/// Zusatzabfrage lesen kann, auch wenn das Katalog-Item inzwischen gelöscht wurde.</summary> /// Zusatzabfrage lesen kann, auch wenn das Katalog-Item inzwischen gelöscht wurde.</summary>
public record CompetencyReferenceDto(Guid ItemId, string Code, string Description); public record CompetencyReferenceDto(Guid ItemId, string Code, string Description);
/// <summary>Mitarbeit-Sitzung (siehe ParticipationTools) - bewusst ohne die einzelnen
/// Schülerbewertungen (personenbezogen, nicht über MCP erreichbar, siehe Klassenkommentar).</summary>
public record ParticipationSessionDto(
Guid Id, Guid GroupId, DateOnly Date, Guid? LessonId, string? Comment,
List<CompetencyReferenceDto> Competencies);
public record LessonDto( public record LessonDto(
Guid Id, Guid UnitId, Guid GroupId, DateOnly Date, int? LessonNumber, string Topic, Guid Id, Guid UnitId, Guid GroupId, DateOnly Date, int? LessonNumber, string Topic,
string? Homework, string? PlanningIdeas, LessonStatus Status, List<CompetencyReferenceDto> Competencies, string? Homework, string? PlanningIdeas, LessonStatus Status, List<CompetencyReferenceDto> Competencies,
@@ -17,6 +17,7 @@ public class GroupMembershipTools(
[Description("Schüler-ID.")] Guid studentId, [Description("Schüler-ID.")] Guid studentId,
[Description("Lerngruppen-ID.")] Guid groupId, [Description("Lerngruppen-ID.")] Guid groupId,
[Description("Niveau: E, G oder Foerder. Unverändert lassen: weglassen.")] Niveau? niveau = null, [Description("Niveau: E, G oder Foerder. Unverändert lassen: weglassen.")] Niveau? niveau = null,
[Description("Förderschüler-Markierung (auch ohne Niveaudifferenzierung der Gruppe). Unverändert lassen: weglassen.")] bool? isSupportStudent = null,
[Description("Zeitraum: FullYear, H1Only, H2Only oder Custom. Unverändert lassen: weglassen.")] MembershipPeriod? period = null, [Description("Zeitraum: FullYear, H1Only, H2Only oder Custom. Unverändert lassen: weglassen.")] MembershipPeriod? period = null,
[Description("Beitrittsdatum bei Custom-Zeitraum, Format YYYY-MM-DD.")] DateOnly? joinedAt = null, [Description("Beitrittsdatum bei Custom-Zeitraum, Format YYYY-MM-DD.")] DateOnly? joinedAt = null,
[Description("Austrittsdatum bei Custom-Zeitraum, Format YYYY-MM-DD.")] DateOnly? leftAt = null, [Description("Austrittsdatum bei Custom-Zeitraum, Format YYYY-MM-DD.")] DateOnly? leftAt = null,
@@ -34,6 +35,7 @@ public class GroupMembershipTools(
var changes = new StringBuilder(); var changes = new StringBuilder();
if (niveau is not null && niveau != target.Niveau) { changes.AppendLine($"Niveau: {NiveauName(target.Niveau)} → {NiveauName(niveau)}"); target.Niveau = niveau; } if (niveau is not null && niveau != target.Niveau) { changes.AppendLine($"Niveau: {NiveauName(target.Niveau)} → {NiveauName(niveau)}"); target.Niveau = niveau; }
if (isSupportStudent is not null && isSupportStudent != target.IsSupportStudent) { changes.AppendLine($"Förderschüler: {(target.IsSupportStudent ? "ja" : "nein")} → {(isSupportStudent.Value ? "ja" : "nein")}"); target.IsSupportStudent = isSupportStudent.Value; }
if (period is not null && period != target.Period) { changes.AppendLine($"Zeitraum: {target.Period} → {period}"); target.Period = period.Value; } if (period is not null && period != target.Period) { changes.AppendLine($"Zeitraum: {target.Period} → {period}"); target.Period = period.Value; }
if (joinedAt is not null && joinedAt != target.JoinedAt) { changes.AppendLine($"Beitritt: {target.JoinedAt:dd.MM.yyyy} → {joinedAt:dd.MM.yyyy}"); target.JoinedAt = joinedAt; } if (joinedAt is not null && joinedAt != target.JoinedAt) { changes.AppendLine($"Beitritt: {target.JoinedAt:dd.MM.yyyy} → {joinedAt:dd.MM.yyyy}"); target.JoinedAt = joinedAt; }
if (leftAt is not null && leftAt != target.LeftAt) { changes.AppendLine($"Austritt: {target.LeftAt:dd.MM.yyyy} → {leftAt:dd.MM.yyyy}"); target.LeftAt = leftAt; } if (leftAt is not null && leftAt != target.LeftAt) { changes.AppendLine($"Austritt: {target.LeftAt:dd.MM.yyyy} → {leftAt:dd.MM.yyyy}"); target.LeftAt = leftAt; }
@@ -57,6 +59,7 @@ public class GroupMembershipTools(
{ {
Id = m.Id, StudentId = m.StudentId, GroupId = m.GroupId, AddedOn = m.AddedOn, Id = m.Id, StudentId = m.StudentId, GroupId = m.GroupId, AddedOn = m.AddedOn,
Period = m.Period, JoinedAt = m.JoinedAt, LeftAt = m.LeftAt, Niveau = m.Niveau, Period = m.Period, JoinedAt = m.JoinedAt, LeftAt = m.LeftAt, Niveau = m.Niveau,
IsSupportStudent = m.IsSupportStudent,
}; };
private static string NiveauName(Niveau? n) => n switch private static string NiveauName(Niveau? n) => n switch
@@ -26,7 +26,7 @@ public class LetterTemplateTools(
public List<LetterTemplateDto> ListLetterTemplates() public List<LetterTemplateDto> ListLetterTemplates()
{ {
var result = new List<LetterTemplateDto>(); var result = new List<LetterTemplateDto>();
foreach (var installed in templates.GetTemplates()) foreach (var installed in templates.GetTemplates().Where(x => !x.IsExamCover && !x.IsStudentReport))
{ {
try try
{ {
@@ -0,0 +1,72 @@
using System.ComponentModel;
using LehrerApp.Core.Interfaces;
using LehrerApp.Core.Models;
namespace LehrerApp.Desktop.Services.Mcp.Tools;
/// <summary>MCP-Tools für Mitarbeit-Sitzungen (<see cref="ParticipationSession"/>) - Nutzer-Nachtrag.
/// Bewusst nur die Sitzung selbst (Datum, Kommentar, Kompetenzzuordnung), NICHT die einzelnen
/// Schülerbewertungen (<see cref="ParticipationEntry"/>/<see cref="AspectRating"/>): das wären
/// personenbezogene Bewertungsdaten je Schüler, analog zu Documentation/Vorgang bewusst nicht über
/// MCP erreichbar (siehe McpToolScope). "add_session_competency"/"remove_session_competency" folgen
/// demselben Muster wie LessonPlanTools.AddLessonCompetency/RemoveLessonCompetency: einzelne
/// Kompetenz statt ganze Liste ersetzen, um kein "letzter Schreiber gewinnt" zu riskieren, und mit
/// Katalog-Validierung der übergebenen itemId.</summary>
public class ParticipationTools(
IParticipationSessionRepository sessions, ICompetencyDomainRepository competencyDomains,
IMcpConfirmationService confirmation)
{
[Description("Listet Mitarbeit-Sitzungen einer Lerngruppe (Datum, Kommentar, zugeordnete Kompetenzen) - ohne die einzelnen Schülerbewertungen.")]
public List<ParticipationSessionDto> GetParticipationSessions(
[Description("Lerngruppen-ID, aus get_groups.")] Guid groupId) =>
sessions.GetByGroup(groupId).Select(ToDto).ToList();
[Description("Ordnet einer Mitarbeit-Sitzung eine Kompetenz aus dem Katalog zu (siehe get_competency_catalog). Muss der Nutzer erst bestätigen.")]
public async Task<WriteResultDto> AddSessionCompetency(
[Description("ID der Mitarbeit-Sitzung, aus get_participation_sessions.")] Guid sessionId,
[Description("ID der Einzelkompetenz, aus get_competency_catalog.")] Guid itemId,
CancellationToken ct = default)
{
var session = sessions.GetById(sessionId);
if (session is null) return new WriteResultDto(false, null, "Unbekannte Sitzungs-ID.");
var item = FindCompetencyItem(itemId);
if (item is null) return new WriteResultDto(false, null, "Unbekannte Kompetenz-ID.");
if (session.Competencies.Any(c => c.ItemId == itemId))
return new WriteResultDto(true, session.Id, "Kompetenz ist bereits zugeordnet.");
var message = $"Kompetenz „{item.Code}“ zur Mitarbeit-Sitzung vom {session.Date:dd.MM.yyyy} hinzufügen?";
if (!await confirmation.ConfirmAsync("Kompetenz zuordnen?", message, ct))
return new WriteResultDto(false, null, "Vom Nutzer abgelehnt oder nicht bestätigt.");
session.Competencies.Add(new CompetencyReference { ItemId = item.Id, Code = item.Code, Description = item.Description });
sessions.Save(session);
return new WriteResultDto(true, session.Id, "Kompetenz zugeordnet.");
}
[Description("Entfernt eine Kompetenz von einer Mitarbeit-Sitzung. Muss der Nutzer erst bestätigen.")]
public async Task<WriteResultDto> RemoveSessionCompetency(
[Description("ID der Mitarbeit-Sitzung.")] Guid sessionId,
[Description("ID der Einzelkompetenz, wie in get_participation_sessions hinterlegt.")] Guid itemId,
CancellationToken ct = default)
{
var session = sessions.GetById(sessionId);
if (session is null) return new WriteResultDto(false, null, "Unbekannte Sitzungs-ID.");
var existing = session.Competencies.FirstOrDefault(c => c.ItemId == itemId);
if (existing is null) return new WriteResultDto(false, null, "Diese Kompetenz ist dieser Sitzung nicht zugeordnet.");
var message = $"Kompetenz „{existing.Code}“ von der Mitarbeit-Sitzung vom {session.Date:dd.MM.yyyy} entfernen?";
if (!await confirmation.ConfirmAsync("Kompetenz entfernen?", message, ct))
return new WriteResultDto(false, null, "Vom Nutzer abgelehnt oder nicht bestätigt.");
session.Competencies.Remove(existing);
sessions.Save(session);
return new WriteResultDto(true, session.Id, "Kompetenz entfernt.");
}
private CompetencyItem? FindCompetencyItem(Guid itemId) =>
competencyDomains.GetAll().SelectMany(d => d.Items).FirstOrDefault(i => i.Id == itemId);
private static ParticipationSessionDto ToDto(ParticipationSession s) => new(
s.Id, s.GroupId, s.Date, s.LessonId, s.Comment,
s.Competencies.Select(c => new CompetencyReferenceDto(c.ItemId, c.Code, c.Description)).ToList());
}
@@ -36,7 +36,8 @@ public class UntisComparisonTools(
private static readonly AttendanceStatus[] SelectableStatuses = private static readonly AttendanceStatus[] SelectableStatuses =
[ [
AttendanceStatus.ExcusePending, AttendanceStatus.Excused, AttendanceStatus.Unexcused, AttendanceStatus.ExcusePending, AttendanceStatus.Excused, AttendanceStatus.Unexcused,
AttendanceStatus.Late, AttendanceStatus.LeftDuringClass, AttendanceStatus.Present, AttendanceStatus.Late, AttendanceStatus.SignificantlyLate,
AttendanceStatus.LeftDuringClass, AttendanceStatus.Present,
]; ];
// In-Memory, pro Prozesslaufzeit - eine row-id aus GetUntisAbsenceRows ist nur bis zum nächsten // In-Memory, pro Prozesslaufzeit - eine row-id aus GetUntisAbsenceRows ist nur bis zum nächsten
@@ -102,7 +103,7 @@ public class UntisComparisonTools(
[Description("Übernimmt einen Statusvorschlag für eine über get_untis_absence_rows gelieferte row-id in den lokalen Anwesenheitsstatus. Muss der Nutzer erst in einem Dialog in LehrerApp bestätigen; die Bestätigungsmeldung nennt bewusst KEINEN Schülernamen (nur Datum, Lerngruppe, Zielstatus).")] [Description("Übernimmt einen Statusvorschlag für eine über get_untis_absence_rows gelieferte row-id in den lokalen Anwesenheitsstatus. Muss der Nutzer erst in einem Dialog in LehrerApp bestätigen; die Bestätigungsmeldung nennt bewusst KEINEN Schülernamen (nur Datum, Lerngruppe, Zielstatus).")]
public async Task<WriteResultDto> ApplyUntisAbsenceStatus( public async Task<WriteResultDto> ApplyUntisAbsenceStatus(
[Description("row-id aus get_untis_absence_rows.")] string rowId, [Description("row-id aus get_untis_absence_rows.")] string rowId,
[Description("Zielstatus: Present, Late, LeftDuringClass, ExcusePending, Excused oder Unexcused.")] string status, [Description("Zielstatus: Present, Late, SignificantlyLate, LeftDuringClass, ExcusePending, Excused oder Unexcused.")] string status,
CancellationToken ct = default) CancellationToken ct = default)
{ {
if (!Enum.TryParse<AttendanceStatus>(status, out var target) || !SelectableStatuses.Contains(target)) if (!Enum.TryParse<AttendanceStatus>(status, out var target) || !SelectableStatuses.Contains(target))
@@ -202,6 +203,7 @@ public class UntisComparisonTools(
AttendanceStatus.Excused => "Krank, entschuldigt", AttendanceStatus.Excused => "Krank, entschuldigt",
AttendanceStatus.Unexcused => "Krank, unentschuldigt", AttendanceStatus.Unexcused => "Krank, unentschuldigt",
AttendanceStatus.Late => "Verspätet", AttendanceStatus.Late => "Verspätet",
AttendanceStatus.SignificantlyLate => "Erheblich verspätet",
AttendanceStatus.LeftDuringClass => "Während des Unterrichts abgängig", AttendanceStatus.LeftDuringClass => "Während des Unterrichts abgängig",
_ => s.ToString()!, _ => s.ToString()!,
}; };
@@ -151,7 +151,7 @@ public static class StudentAttendanceCalendarDrawingBuilder
y = gridStartY + 11 * k + 9 * k + maxWeeks * cellHeight + designTrailingGapY * k; y = gridStartY + 11 * k + 9 * k + maxWeeks * cellHeight + designTrailingGapY * k;
commands.Add(new DrawStringEx(0, y, 8 * k, contentWidthDesign, commands.Add(new DrawStringEx(0, y, 8 * k, contentWidthDesign,
"U unentschuldigt · A abwesend · V verspätet · E entschuldigt · ! Klassenbuch", "U/E/A ganztägig · T teilweise · G gegangen · V verspätet · ! Klassenbuch",
DrawingTextAlignment.AlignLeft, 6.5f * finalScale, Color: "#6B7280")); DrawingTextAlignment.AlignLeft, 6.5f * finalScale, Color: "#6B7280"));
return new DrawingValue(commands, y + 9 * k); return new DrawingValue(commands, y + 9 * k);
} }
@@ -0,0 +1,107 @@
using LehrerApp.Core.Interfaces;
using LehrerApp.Core.Models;
using LehrerApp.Core.Services;
using LehrerApp.Desktop.ViewModels.Groups;
using LehrerApp.Desktop.ViewModels.Students;
using LehrerApp.Templating;
namespace LehrerApp.Desktop.Services;
public sealed record StudentReportOptions(DateOnly From, DateOnly To, InterimGrade? Interim,
bool IncludeInterim = true, bool IncludeParticipation = true, bool IncludeCompetencies = true,
bool IncludeHomework = true, bool IncludeDocumentation = true, bool IncludeConfidential = false,
string Comment = "");
/// <summary>Stellt die vorhandenen Bewertungen eines Schülers für eine Lerngruppe zusammen.
/// Die Berechnungen stammen aus denselben Diensten wie die interaktiven Auswertungen.</summary>
public sealed class StudentReportService(
IParticipationSessionRepository sessions, IParticipationRepository entries,
IParticipationAspectRepository aspects, IExamRepository exams, IExamResultRepository results,
IGradeRepository grades, IGroupMembershipRepository memberships,
ICompetencyDomainRepository domains, IDocumentationRepository documentation,
GradingService grading, CompetencyAnalysisService competencies)
{
public Dictionary<string, PlaceholderValue> Build(Student student, LearningGroup group,
LoadedTemplate template, StudentReportOptions options)
{
if (options.From > options.To) throw new InvalidDataException("Das Ende des Berichtszeitraums liegt vor dem Beginn.");
var values = LetterPlaceholderBuilder.BuildStandardValues(student, null, group, DateOnly.FromDateTime(DateTime.Today), "", "");
values["Report.Period"] = new TextValue($"{options.From:dd.MM.yyyy} - {options.To:dd.MM.yyyy}");
values["Report.Comment"] = new MultilineValue(options.Comment);
foreach (var name in StudentReportTemplate.Drawings) values[name] = new DrawingValue([], 0);
if (options.IncludeInterim && Uses(ReportTextDrawing.InterimGrades))
{
var interim = options.Interim;
if (interim is null || interim.StudentId != student.Id || interim.GroupId != group.Id
|| interim.Date < options.From || interim.Date > options.To)
throw new InvalidDataException("Bitte einen gespeicherten Zwischenstand dieses Schülers im Berichtszeitraum auswählen oder den Baustein abwählen.");
values[ReportTextDrawing.InterimGrades] = GradeReportDrawingBuilder.Interim(interim, template);
}
var membership = memberships.GetByStudentAndGroup(student.Id, group.Id);
bool Within(DateOnly date) => date >= options.From && date <= options.To
&& (membership is null || GroupMembershipService.IsActiveOn(membership, date));
var groupSessions = sessions.GetByGroup(group.Id).Where(s => Within(s.Date)).OrderBy(s => s.Date).ToList();
var bySession = groupSessions.ToDictionary(s => s.Id);
var studentEntries = entries.GetByStudent(student.Id).Where(e => bySession.ContainsKey(e.SessionId)).ToList();
var applicableAspects = aspects.GetDefaults().Concat(aspects.GetByGroup(group.Id))
.GroupBy(a => a.Key).Select(g => g.Last()).ToList();
if (options.IncludeParticipation && Uses(StudentReportTemplate.Participation))
{
var timeline = new ParticipationTimelineBuilder(sessions, entries, aspects, exams, results, grades,
membership is null ? new Dictionary<Guid, GroupMembership>() : new() { [student.Id] = membership },
grading, group.Id, group.GradingSystem);
var points = timeline.BuildPoints(student.Id).Where(p => !p.IsExam && Within(p.Date)).ToList();
List<ReportChartSeries> series = [new("Gewichtete Mitarbeit", "#6C5CE7",
points.Where(p => p.WeightedValue.HasValue).Select(p => new ReportChartPoint(p.Date, p.WeightedValue!.Value)).ToList())];
string[] colors = ["#2E86DE", "#E67E22", "#16A085", "#C0392B"];
foreach (var (aspect, index) in applicableAspects.Select((a, i) => (a, i)))
series.Add(new(aspect.Label, colors[index % colors.Length],
points.Where(p => p.AspectValues.ContainsKey(aspect.Key)).Select(p => new ReportChartPoint(p.Date,
ParticipationRatingScale.Normalize(aspect.ValueType, p.AspectValues[aspect.Key], aspect.MaxPoints))).ToList()));
var box = DrawingBoxLocator.Find(template, StudentReportTemplate.Participation)!.Value;
var drawing = ParticipationReportDrawing.Build(series, options.From, options.To, box.Width, box.MillimeterScale);
if (drawing.ContentHeight > box.Height)
throw new InvalidDataException("Der Mitarbeitsgraph benötigt eine höhere Zeichenbox in der Vorlage.");
values[StudentReportTemplate.Participation] = drawing;
}
if (options.IncludeCompetencies && Uses(StudentReportTemplate.Competencies))
{
var groupExams = exams.GetByGroup(group.Id).Where(e => Within(e.Date)).ToList();
var examIds = groupExams.Select(e => e.Id).ToHashSet();
var scores = competencies.Analyze(domains.GetAll(), [], groupExams,
results.GetByStudent(student.Id).Where(r => examIds.Contains(r.ExamId)).ToList(),
groupSessions, studentEntries, applicableAspects);
var lines = scores.Where(s => s.StudentScores.ContainsKey(student.Id)).Select(s =>
{
var score = s.StudentScores[student.Id];
return $"{s.Code} {s.Description}: {score.Percent.ToString("0", System.Globalization.CultureInfo.GetCultureInfo("de-DE"))} % ({score.EvidenceCount} Bewertungen)";
}).ToList();
Add(StudentReportTemplate.Competencies, "Kompetenzen", lines, "Keine Kompetenzbewertungen im gewählten Zeitraum.");
}
if (options.IncludeHomework && Uses(StudentReportTemplate.Homework))
Add(StudentReportTemplate.Homework, "Hausaufgaben", studentEntries.Where(e => HomeworkDisplay.Effective(e) is not null)
.OrderBy(e => bySession[e.SessionId].Date).Select(e =>
$"{bySession[e.SessionId].Date:dd.MM.yyyy}: {HomeworkDisplay.Label(HomeworkDisplay.Effective(e))}").ToList(),
"Keine Hausaufgabenkontrollen im gewählten Zeitraum.");
if (options.IncludeDocumentation && Uses(StudentReportTemplate.Documentation))
{
var lines = documentation.GetByStudent(student.Id)
.Where(d => !d.IsDeleted && !d.IsDraft && (options.IncludeConfidential || !d.IsConfidential)
&& d.GroupId == group.Id && Within(d.Date) && d.Concerns(student.Id))
.OrderBy(d => d.Date).Select(d =>
$"{d.Date:dd.MM.yyyy} · {DocumentationTypeDisplay.Label(d.Type)}: {d.Title}"
+ (d.IsConfidential ? " [Vertraulich]" : "") + "\n" + d.Content).ToList();
lines.AddRange(studentEntries.Where(e => !string.IsNullOrWhiteSpace(e.Note)).OrderBy(e => bySession[e.SessionId].Date)
.Select(e => $"{bySession[e.SessionId].Date:dd.MM.yyyy} · Unterrichtsnotiz: {e.Note}"));
Add(StudentReportTemplate.Documentation, "Klassenbucheinträge und Unterrichtsnotizen", lines,
"Keine freigegebenen Einträge mit Bezug zu dieser Lerngruppe im gewählten Zeitraum.");
}
return values;
bool Uses(string name) => DrawingBoxLocator.Find(template, name) is not null;
void Add(string name, string title, List<string> lines, string empty) =>
values[name] = GradeReportDrawingBuilder.Text(template, name, title, lines.Count > 0 ? lines : [empty]);
}
}
@@ -0,0 +1,122 @@
using System.Globalization;
using LehrerApp.Core.Interfaces;
using LehrerApp.Core.Models;
using LehrerApp.Core.Services;
using LehrerApp.Desktop.ViewModels.Groups;
namespace LehrerApp.Desktop.Services;
public enum StudentEvidenceKind { Absence, Lateness, Homework }
/// <summary>Ein einzelner Beleg hinter einer klassenübergreifenden Warnung (ein Fehltermin, eine
/// Verspätung, eine offene Hausaufgabe) — Code/Farbe bewusst identisch mit der Klassenlehrer-
/// Monatsansicht (ClassTeacherDetailsViewModel.BuildDayEvents: U/E/A/V/H), damit dasselbe Kürzel in
/// beiden Widgets dasselbe bedeutet.</summary>
public sealed record StudentEvidenceEvent(DateOnly Date, string GroupName, string Label, string Code,
string ColorHex, StudentEvidenceKind Kind)
{
private static readonly CultureInfo De = new("de-DE");
public string DateLabel => Date.ToString("ddd dd.MM.", De);
public string ListLine => $"{Date:dd.MM.yyyy} · {GroupName}: {Label}";
}
/// <summary>Momentaufnahme aller Belege einer/eines Schüler*in im laufenden Schuljahr. Grundlage
/// sowohl für das Detail-Popup der Dashboard-Warnungen als auch für die Schnellbausteine/Vorlagen
/// beim Anlegen von Vorgängen und Dokumentation — beides soll exakt dieselben Zahlen zeigen, die
/// die Warnung ausgelöst haben.</summary>
public sealed record StudentWarningEvidence(
Guid StudentId, string StudentName, string StudentFirstName, string StudentNaturalName, string SchoolYear, DateOnly From, DateOnly To, DateOnly AsOf,
AttendanceBalance Balance,
IReadOnlyList<StudentEvidenceEvent> Absences,
IReadOnlyList<StudentEvidenceEvent> Lateness,
IReadOnlyList<StudentEvidenceEvent> MissingHomework)
{
public int SignificantlyLateCount => Lateness.Count(e => e.Code == "V!");
}
/// <summary>
/// Sammelt die Belege hinter den drei klassenübergreifenden Dashboard-Warnungen (Fehlzeiten,
/// Hausaufgaben-Rückstand, Verspätungen) für eine/n einzelne/n Schüler*in. Zählt bewusst nach
/// denselben Regeln wie DashboardViewModel.LoadAttendanceWarnings/LoadMissingHomeworkWarnings/
/// LoadLatenessWarnings (Schuljahreszeitraum, AttendanceBalanceService, HomeworkDisplay.CountsAsMissing,
/// Late/SignificantlyLate) — eine abweichende Zahl im Popup als in der Warnzeile wäre verwirrend.
/// Keine eigene Persistenz, rein lesend.
/// </summary>
public class StudentWarningEvidenceService
{
private readonly IStudentRepository _students;
private readonly IParticipationSessionRepository _sessions;
private readonly IParticipationRepository _entries;
private readonly IGroupRepository _groups;
private readonly SchoolYearService _sy;
private readonly AttendanceBalanceService _attendanceBalance;
private readonly Func<DateTime> _now;
public StudentWarningEvidenceService(IStudentRepository students, IParticipationSessionRepository sessions,
IParticipationRepository entries, IGroupRepository groups, SchoolYearService sy,
AttendanceBalanceService attendanceBalance, Func<DateTime>? now = null)
{
_students = students;
_sessions = sessions;
_entries = entries;
_groups = groups;
_sy = sy;
_attendanceBalance = attendanceBalance;
_now = now ?? (() => DateTime.Now);
}
public StudentWarningEvidence Build(Guid studentId)
{
var schoolYear = _sy.CurrentSchoolYear();
var from = _sy.SchoolYearStart(schoolYear);
var to = _sy.SchoolYearEnd(schoolYear);
var sessions = _sessions.GetAll().ToDictionary(s => s.Id);
var groupNames = _groups.GetAll(includeInactive: true).ToDictionary(g => g.Id, g => g.Name);
var dated = _entries.GetByStudent(studentId)
.Select(e => (Entry: e, Session: sessions.GetValueOrDefault(e.SessionId)))
.Where(x => x.Session is not null && x.Session.Date >= from && x.Session.Date <= to)
.Select(x => (x.Entry, x.Session!.Date, Group: groupNames.GetValueOrDefault(x.Session.GroupId, "")))
.OrderByDescending(x => x.Date).ThenBy(x => x.Group)
.ToList();
var balance = _attendanceBalance.Calculate(dated.Select(x => (x.Date, x.Entry.Attendance)), from, to);
var absences = new List<StudentEvidenceEvent>();
var lateness = new List<StudentEvidenceEvent>();
var homework = new List<StudentEvidenceEvent>();
foreach (var (entry, date, group) in dated)
{
if (AbsenceEvent(entry.Attendance, date, group) is { } absence) absences.Add(absence);
if (entry.Attendance is AttendanceStatus.Late or AttendanceStatus.SignificantlyLate)
lateness.Add(new StudentEvidenceEvent(date, group, AttendanceDisplay.Label(entry.Attendance),
entry.Attendance == AttendanceStatus.SignificantlyLate ? "V!" : "V", "#EF6C00",
StudentEvidenceKind.Lateness));
var hw = HomeworkDisplay.Effective(entry);
if (HomeworkDisplay.CountsAsMissing(hw))
homework.Add(new StudentEvidenceEvent(date, group, HomeworkDisplay.Label(hw), "H", "#6A1B9A",
StudentEvidenceKind.Homework));
}
var student = _students.GetById(studentId);
return new StudentWarningEvidence(studentId, student?.FullName ?? "", student?.FirstName ?? "",
student is null ? "" : $"{student.FirstName} {student.LastName}".Trim(), schoolYear, from, to, DateOnly.FromDateTime(_now()),
balance, absences, lateness, homework);
}
/// Nur die Status, die AttendanceBalanceService in die Fehlquote einrechnet (entschuldigt,
/// unentschuldigt, Entschuldigung offen) — schulisch veranlasste Abwesenheit zählt dort nicht als
/// Fehlzeit und taucht deshalb auch hier nicht als Beleg auf.
private static StudentEvidenceEvent? AbsenceEvent(AttendanceStatus? status, DateOnly date, string group)
{
var (code, color) = status switch
{
AttendanceStatus.Unexcused or AttendanceStatus.Truant or AttendanceStatus.LeftDuringClass => ("U", "#C62828"),
AttendanceStatus.ExcusePending => ("A", "#1565C0"),
AttendanceStatus.Excused => ("E", "#2E7D32"),
_ => ("", ""),
};
return code == "" ? null
: new StudentEvidenceEvent(date, group, AttendanceDisplay.Label(status), code, color, StudentEvidenceKind.Absence);
}
}
@@ -0,0 +1,41 @@
using System.Text.Json;
namespace LehrerApp.Desktop.Services;
internal sealed class TeacherSettingsConfig
{
public string Abbreviation { get; set; } = "";
}
/// <summary>Angaben zur Lehrkraft, die auf Formularen erscheinen (bisher nur das Kürzel fürs
/// Klausur-Deckblatt) — aus der Konfiguration statt fest in der Vorlage, damit eine weitergegebene
/// Vorlage nicht das Kürzel ihres Erstellers trägt.</summary>
public sealed class TeacherSettingsService
{
private readonly string _configPath;
public TeacherSettingsService(string appDataPath) =>
_configPath = Path.Combine(appDataPath, "teachersettings.json");
public string LoadAbbreviation()
{
try
{
if (File.Exists(_configPath))
return JsonSerializer.Deserialize<TeacherSettingsConfig>(File.ReadAllText(_configPath))
?.Abbreviation ?? "";
}
catch { /* beschädigte Konfiguration -> leer */ }
return "";
}
public void SaveAbbreviation(string abbreviation)
{
try
{
File.WriteAllText(_configPath,
JsonSerializer.Serialize(new TeacherSettingsConfig { Abbreviation = abbreviation.Trim() }));
}
catch { /* Einstellung ist Komfort — Fehler beim Schreiben nicht an die UI durchreichen */ }
}
}
@@ -13,23 +13,41 @@ namespace LehrerApp.Desktop.Services;
public static class UntisLessonAbsenceHelper public static class UntisLessonAbsenceHelper
{ {
private const int FullLessonMinutes = 45; private const int FullLessonMinutes = 45;
// Bewusst zentral gehalten: Die Einstufung ist nur eine überprüfbare Vorauswahl und kann hier
// leicht an eine geänderte schulische Praxis angepasst werden.
public const int SignificantLatenessThresholdMinutes = 10;
// Der Bericht liefert keinen Entschuldigungstext, nur Minutenwerte, ein Bearbeitet-Datum und die // Der Bericht liefert keinen Entschuldigungstext, nur Minutenwerte, ein Bearbeitet-Datum und die
// (laut Schule) über Klammerung der ENr codierte Entscheidung des Klassenlehrers - ENr in // (laut Schule) über Klammerung der ENr codierte Entscheidung des Klassenlehrers - ENr in
// Klammern bedeutet unentschuldigt, ohne Klammern abgeschlossen/entschuldigt. Reihenfolge ist // Klammern bedeutet unentschuldigt, ohne Klammern abgeschlossen/entschuldigt. Reihenfolge ist
// wichtig: "nach Hause entlassen" zählt immer als vorzeitige Entlassung, unabhängig von der // wichtig: "nach Hause entlassen" zählt immer als vorzeitige Entlassung, unabhängig von der
// Dauer; darunter zählt jede Fehlzeit unter einer vollen Stunde (45 Min.) immer als Verspätung // Dauer; darunter zählt jede Fehlzeit unter einer vollen Stunde (45 Min.) immer als Verspätung
// oder sonstiger Teilverlust, nie als komplette Abwesenheit - der Text "Verspätung" allein ist // oder sonstiger Teilverlust, nie als komplette Abwesenheit. Ab zehn Minuten wird für die
// laut Schule nicht zuverlässig genug, deshalb primär über die Minutenschwelle erkannt. // überprüfbare Vorauswahl die lokale Präzisierung "erheblich verspätet" verwendet. Der Text
// "Verspätung" allein ist laut Schule nicht zuverlässig genug, deshalb primär über die
// Minutenschwellen erkannt.
public static AttendanceStatus MapStatus(UntisLessonAbsenceDto absence) public static AttendanceStatus MapStatus(UntisLessonAbsenceDto absence)
{ {
if (IsEarlyRelease(absence)) return AttendanceStatus.LeftDuringClass; if (IsEarlyRelease(absence)) return AttendanceStatus.LeftDuringClass;
if (absence.AbsentMinutes < FullLessonMinutes) return AttendanceStatus.Late; if (absence.AbsentMinutes < SignificantLatenessThresholdMinutes) return AttendanceStatus.Late;
if (absence.AbsentMinutes < FullLessonMinutes) return AttendanceStatus.SignificantlyLate;
if (string.IsNullOrWhiteSpace(absence.HandledOn)) return AttendanceStatus.ExcusePending; if (string.IsNullOrWhiteSpace(absence.HandledOn)) return AttendanceStatus.ExcusePending;
if (absence.ExternKey is null) return AttendanceStatus.ExcusePending; if (absence.ExternKey is null) return AttendanceStatus.ExcusePending;
return absence.ExternKeyInParentheses ? AttendanceStatus.Unexcused : AttendanceStatus.Excused; return absence.ExternKeyInParentheses ? AttendanceStatus.Unexcused : AttendanceStatus.Excused;
} }
/// <summary>
/// Prüft, ob der lokale Status die Aussage des WebUntis-Status bereits erfüllt. WebUntis kennt
/// nur die allgemeine Kategorie "verspätet"; die lokale Kategorie "erheblich verspätet" ist
/// eine bewusst genauere Einstufung und darf deshalb nicht auf "verspätet" zurückgestuft
/// werden. Die Regel ist absichtlich gerichtet: Ergibt die Minutenschwelle umgekehrt eine
/// erhebliche Verspätung, bleibt die Hochstufung von lokal "verspätet" erkennbar. Andere
/// Änderungen (z.B. eine nachgereichte Entschuldigung) bleiben echte Abweichungen.
/// </summary>
public static bool MatchesUntisStatus(AttendanceStatus? localStatus, AttendanceStatus untisStatus) =>
localStatus == untisStatus ||
localStatus == AttendanceStatus.SignificantlyLate && untisStatus == AttendanceStatus.Late;
private static bool IsEarlyRelease(UntisLessonAbsenceDto absence) => private static bool IsEarlyRelease(UntisLessonAbsenceDto absence) =>
absence.Reason?.Contains("entlassen", StringComparison.OrdinalIgnoreCase) == true; absence.Reason?.Contains("entlassen", StringComparison.OrdinalIgnoreCase) == true;
Loaded 100 of 279 files, more files were not shown because too many files have changed in this diff. Show more