Compare commits
75
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
455f7765e4 | ||
|
|
51e55e1464 | ||
|
|
845cc5fc4c | ||
|
|
dc2f58c4dc | ||
|
|
f97edff2fe | ||
|
|
4ffba35eff | ||
|
|
f1cf01ff88 | ||
|
|
3c74e3873a | ||
|
|
9dc7ebab0e | ||
|
|
839242194e | ||
|
|
c128fc6741 | ||
|
|
4542f263fc | ||
|
|
86a97d91a7 | ||
|
|
763d7744be | ||
|
|
77fe9b1c79 | ||
|
|
92e497b54f | ||
|
|
861f2c76ca | ||
|
|
ef3e9dbbb6 | ||
|
|
03a5e0dd9c | ||
|
|
6dccf96039 | ||
|
|
6e57bf407d | ||
|
|
0b5cfc5522 | ||
|
|
09cbbf1b77 | ||
|
|
1671796844 | ||
|
|
70dc78904c | ||
|
|
7b660c7152 | ||
|
|
3675b70004 | ||
|
|
eb1b2340b7 | ||
|
|
b8193be6ec | ||
|
|
0962845ead | ||
|
|
42c650518c | ||
|
|
2c791258a1 | ||
|
|
c528bd825f | ||
|
|
56ab5067e6 | ||
|
|
bfe214ecf2 | ||
|
|
d979a84e7b | ||
|
|
3f8813df51 | ||
|
|
19aa302487 | ||
|
|
a4733c156b | ||
|
|
e6c30b0bc7 | ||
|
|
55fba2cadb | ||
|
|
dd2e1e7c61 | ||
|
|
0c60a54c4d | ||
|
|
9567d8d616 | ||
|
|
98f5573999 | ||
|
|
455c61c946 | ||
|
|
6af4bee1f0 | ||
|
|
c3ce1a7204 | ||
|
|
ba52109eaa | ||
|
|
bd0d7e47ea | ||
|
|
2ec8adac61 | ||
|
|
e86125e5f9 | ||
|
|
86e114580f | ||
|
|
835cccadec | ||
|
|
709ea88c2a | ||
|
|
73453fd88d | ||
|
|
265190b3aa | ||
|
|
fedfceb81d | ||
|
|
7ef0c95a73 | ||
|
|
94946ffefb | ||
|
|
3cccb3226c | ||
|
|
988a293c42 | ||
|
|
92f9a75ec1 | ||
|
|
0a419c4c11 | ||
|
|
216708e879 | ||
|
|
0d5fb6d146 | ||
|
|
1d9521fc60 | ||
|
|
4af83c3e68 | ||
|
|
15463bc292 | ||
|
|
987b49e761 | ||
|
|
fb7a015b42 | ||
|
|
09e97efb61 | ||
|
|
d297f9f109 | ||
|
|
de6d4236a2 | ||
|
|
edf7510765 |
No files matched your search
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(git commit -m ' *)"
|
||||
]
|
||||
}
|
||||
}
|
||||
Vendored
+6
-5
@@ -47,11 +47,12 @@
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Desktop + API (gleichzeitig)",
|
||||
"configurations": [
|
||||
"Desktop App starten",
|
||||
"API Server starten"
|
||||
]
|
||||
"name": "API Tests starten",
|
||||
"type": "coreclr",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "API bauen",
|
||||
"program": "${workspaceFolder}/LehrerApp.Api.Tests/bin/Debug/net10.0/LehrerApp.Api.Tests.dll",
|
||||
"args": [],
|
||||
}
|
||||
],
|
||||
"compounds": [
|
||||
|
||||
@@ -25,6 +25,9 @@
|
||||
<!-- API -->
|
||||
<PackageVersion Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.0" />
|
||||
|
||||
<!-- MCP-Server (lokal, siehe TODO.md) -->
|
||||
<PackageVersion Include="ModelContextProtocol.Core" Version="2.2.0" />
|
||||
|
||||
<!-- Tests -->
|
||||
<PackageVersion Include="xunit" Version="2.9.3" />
|
||||
<PackageVersion Include="xunit.runner.visualstudio" Version="2.8.2" />
|
||||
|
||||
@@ -76,6 +76,9 @@ public class AiLesson
|
||||
public List<AiPhaseStep> Phases { get; set; } = [];
|
||||
public string? Homework { get; set; }
|
||||
public string? Reflection { get; set; }
|
||||
/// Rohentwurf/erste Ideen der Lehrkraft vor der Feinplanung (siehe Lesson.PlanningIdeas) — reiner
|
||||
/// Kontext für die KI wie Homework/Reflection, wird symmetrisch übernommen/zurückgegeben.
|
||||
public string? PlanningIdeas { get; set; }
|
||||
}
|
||||
|
||||
public class AiPhaseStep
|
||||
@@ -100,6 +103,10 @@ public class AiPlanningResponse
|
||||
{
|
||||
public List<AiLesson> Lessons { get; set; } = [];
|
||||
public string? Summary { get; set; }
|
||||
// Vom Backend zusätzlich mitgelieferte, unveränderte Modellantwort. Wird nur benötigt, falls
|
||||
// die typisierte Deserialisierung scheitert; bei einer regulär verarbeiteten Antwort wird sie
|
||||
// weder angezeigt noch gespeichert.
|
||||
public string? RawResponse { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -174,3 +181,54 @@ public class AiSubstanceResearchResponse
|
||||
public string ActivityRestriction { get; set; } = "";
|
||||
public string Source { get; set; } = "";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wire-Vertrag für den Fehlzeiten-Statusvorschlag (ai-backend/untis-status.php, Nutzer-Feedback
|
||||
/// zum Untis-Hub: der aus WebUntis abgeleitete Zielstatus war über den Anzeigetext oft nicht
|
||||
/// nachvollziehbar). Bewusst OHNE jeden Personenbezug - <see cref="AiUntisStatusRow.Id"/> ist eine
|
||||
/// rein technische, für die KI bedeutungslose Kennung, über die der Desktop-Client die Antwort
|
||||
/// zurückordnet; kein Name, keine Klasse, kein Datum verlässt damit die App. Mehrere Zeilen eines
|
||||
/// Abgleichslaufs werden in einer Anfrage gebündelt statt je Zeile einzeln (Kosten/Latenz).
|
||||
/// </summary>
|
||||
public class AiUntisStatusRequest
|
||||
{
|
||||
public List<AiUntisStatusRow> Rows { get; set; } = [];
|
||||
}
|
||||
|
||||
public class AiUntisStatusRow
|
||||
{
|
||||
public string Id { get; set; } = "";
|
||||
public string ReasonText { get; set; } = "";
|
||||
public int AbsentMinutes { get; set; }
|
||||
/// True, wenn WebUntis für den Eintrag bereits ein Bearbeitungsdatum führt (unabhängig vom
|
||||
/// tatsächlichen Datum, das aus Datenschutzgründen nicht mitgeschickt wird).
|
||||
public bool HandledOn { get; set; }
|
||||
/// Schulinterne Konvention: Klammerung der Entschuldigungsnummer bedeutet unentschuldigt, ohne
|
||||
/// Klammern entschuldigt; null, wenn keine Nummer hinterlegt ist (siehe UntisDiffService-Analog
|
||||
/// in WebUntisLessonAbsenceComparisonViewModel.MapStatus).
|
||||
public bool? ExternKeyInParentheses { get; set; }
|
||||
/// Bereits regelbasiert ermittelter Status (siehe MapStatus) - der Systemprompt bittet die KI,
|
||||
/// nur bei eindeutigem Widerspruch im Freitext davon abzuweichen, statt bei Unsicherheit zu raten.
|
||||
public string CurrentGuess { get; set; } = "";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Enthält absichtlich GENAU eine Zeile je gesendeter <see cref="AiUntisStatusRow.Id"/> - der
|
||||
/// Client verwirft die gesamte Antwort, wenn die zurückgegebene Id-Menge nicht exakt der
|
||||
/// gesendeten entspricht (siehe AiPlanningService.RequestUntisStatusSuggestionsAsync), statt sich
|
||||
/// auf die Reihenfolge zu verlassen. So bleibt eine Verwechslung zwischen Vorschlag und Zeile
|
||||
/// strukturell ausgeschlossen, nicht nur im Regelfall vermieden.
|
||||
/// </summary>
|
||||
public class AiUntisStatusResponse
|
||||
{
|
||||
public List<AiUntisStatusSuggestion> Suggestions { get; set; } = [];
|
||||
}
|
||||
|
||||
public class AiUntisStatusSuggestion
|
||||
{
|
||||
public string Id { get; set; } = "";
|
||||
/// Einer von "Present"/"Late"/"LeftDuringClass"/"ExcusePending"/"Excused"/"Unexcused" (siehe
|
||||
/// Systemprompt in ai-backend/untis-status.php) - wird client-seitig gegen genau diese Menge
|
||||
/// geprüft, bevor er als AttendanceStatus interpretiert wird.
|
||||
public string Status { get; set; } = "";
|
||||
}
|
||||
@@ -95,6 +95,7 @@ public interface IUnitRepository
|
||||
}
|
||||
public interface ILessonRepository
|
||||
{
|
||||
Lesson? GetById(Guid id);
|
||||
List<Lesson> GetByUnit(Guid unitId);
|
||||
List<Lesson> GetByGroupAndDate(Guid groupId, DateOnly date);
|
||||
List<Lesson> GetByGroupAndRange(Guid groupId, DateOnly from, DateOnly to);
|
||||
@@ -170,6 +171,14 @@ public interface IUntisCacheFetchStateRepository
|
||||
UntisCacheFetchState? Get(string className, UntisCacheKind kind);
|
||||
void Save(UntisCacheFetchState state);
|
||||
}
|
||||
/// Zuletzt-Lauf-Status der Untis-Hub-Jobs (siehe TODO.md) - je (Kind, GroupId), GroupId null bei
|
||||
/// den dashboard-weiten Jobs.
|
||||
public interface IUntisHubJobStateRepository
|
||||
{
|
||||
UntisHubJobState? Get(UntisHubJobKind kind, Guid? groupId);
|
||||
List<UntisHubJobState> GetAll();
|
||||
void Save(UntisHubJobState state);
|
||||
}
|
||||
/// Vom Nutzer bestätigte Zuordnungen WebUntis-Wochenmuster → LearningGroup.
|
||||
public interface IUntisSlotMappingRepository
|
||||
{
|
||||
@@ -200,6 +209,15 @@ public interface IDocumentationRepository
|
||||
/// Entfernt den Eintrag endgültig — nur für die Löschfristen-Bereinigung (5.4.2).
|
||||
void HardDelete(Guid id);
|
||||
}
|
||||
public interface IVorgangRepository
|
||||
{
|
||||
List<Vorgang> GetAll();
|
||||
List<Vorgang> GetByStudent(Guid studentId);
|
||||
Vorgang? GetById(Guid id);
|
||||
void Save(Vorgang vorgang);
|
||||
/// Markiert den Vorgang als gelöscht, statt ihn hart zu entfernen (gleiches Muster wie Documentation).
|
||||
void Delete(Guid id);
|
||||
}
|
||||
public interface IWorkTaskRepository
|
||||
{
|
||||
List<WorkTask> GetByStatus(WorkTaskStatus status);
|
||||
@@ -266,12 +284,34 @@ public interface ISubjectRepository
|
||||
}
|
||||
public interface ICompetencyDomainRepository
|
||||
{
|
||||
List<CompetencyDomain> GetBySubjectAndGrade(Guid subjectId, int gradeLevel);
|
||||
List<CompetencyDomain> GetBySubjectAndGrade(Guid subjectId, int gradeLevel, Guid versionId);
|
||||
// Über alle Klassenstufen einer Version eines Fachs hinweg - für einen Überblick über den
|
||||
// gesamten Katalog einer Version (z.B. MCP-Tool get_competency_catalog ohne gradeLevel-Filter),
|
||||
// ohne dass der Aufrufer erst jede vorkommende Klassenstufe einzeln erraten/abfragen müsste.
|
||||
List<CompetencyDomain> GetBySubjectAndVersion(Guid subjectId, Guid versionId);
|
||||
// Über alle Fächer/Klassenstufen/Versionen hinweg - für Aufrufer, die eine CompetencyItem.Id
|
||||
// auflösen müssen, ohne vorher das Fach der Zuordnung zu kennen (z.B. MCP add_lesson_competency).
|
||||
List<CompetencyDomain> GetAll();
|
||||
CompetencyDomain? GetById(Guid id);
|
||||
void Save(CompetencyDomain domain);
|
||||
void Delete(Guid id);
|
||||
void DeleteBySubjectAndGrade(Guid subjectId, int gradeLevel);
|
||||
void ReplaceForSubjectAndGrade(Guid subjectId, int gradeLevel, List<CompetencyDomain> domains);
|
||||
void DeleteBySubjectGradeAndVersion(Guid subjectId, int gradeLevel, Guid versionId);
|
||||
void ReplaceForSubjectGradeAndVersion(Guid subjectId, int gradeLevel, Guid versionId, List<CompetencyDomain> domains);
|
||||
}
|
||||
|
||||
public interface ICompetencyCatalogVersionRepository
|
||||
{
|
||||
List<CompetencyCatalogVersion> GetBySubject(Guid subjectId);
|
||||
CompetencyCatalogVersion? GetById(Guid id);
|
||||
/// <summary>Liefert die Standardversion des Fachs und legt sie an ("Bestehender Kompetenzkatalog"),
|
||||
/// falls noch keine existiert - so brauchen Aufrufer, die nur einen Guid für die Domain-Suche
|
||||
/// benötigen, keinen eigenen Anlegen-oder-Lesen-Ablauf.</summary>
|
||||
CompetencyCatalogVersion GetOrCreateDefault(Guid subjectId);
|
||||
void Save(CompetencyCatalogVersion version);
|
||||
/// <summary>Blockiert (InvalidOperationException), wenn noch ein CompetencyDomain oder eine
|
||||
/// LearningGroup diese Version referenziert, oder wenn sie die Standardversion ihres Fachs ist
|
||||
/// (erst eine andere Version des Fachs als Standard setzen).</summary>
|
||||
void Delete(Guid id);
|
||||
}
|
||||
public interface IShorthandCodeRepository
|
||||
{
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
namespace LehrerApp.Core.Mcp;
|
||||
|
||||
/// <summary>
|
||||
/// Named-Pipe-Konvention zwischen dem Avalonia-Hauptprozess (Pipe-Server, siehe
|
||||
/// LehrerApp.Desktop/Services/Mcp) und LehrerApp.McpBridge (Pipe-Client). Bewusst als einzelne
|
||||
/// geteilte Konstante statt eigener Bibliothek — die Bridge reicht JSON-RPC-Nachrichten unverändert
|
||||
/// durch und braucht sonst keine gemeinsamen Typen mit der App (siehe Planungsdokument).
|
||||
/// </summary>
|
||||
public static class McpPipeConstants
|
||||
{
|
||||
public const string PipeName = "LehrerApp.Mcp";
|
||||
|
||||
/// <summary>
|
||||
/// Unter macOS/Linux emuliert .NET Named Pipes über eine Socket-Datei unter
|
||||
/// <see cref="Path.GetTempPath"/> (intern "CoreFxPipe_" + Name), und die liest dafür die
|
||||
/// TMPDIR-Umgebungsvariable des jeweiligen Prozesses. LehrerApp.Desktop (von Finder/Dock
|
||||
/// gestartet) bekommt das reguläre per-Login-Session-TMPDIR unter /var/folders/.../T,
|
||||
/// während LehrerApp.McpBridge als Kindprozess von Claude Desktop oft eine reduzierte
|
||||
/// Umgebung mit TMPDIR=/tmp erbt - beide Prozesse suchen die Pipe-Datei dann an
|
||||
/// unterschiedlichen Orten und finden sich nie ("MCP nicht erreichbar, obwohl LehrerApp
|
||||
/// läuft", auch wenn beide Prozesse laufen und die Pipe grundsätzlich offen ist). Fix: TMPDIR
|
||||
/// für beide Prozesse hart auf denselben Ordner setzen, bevor die erste
|
||||
/// NamedPipeServerStream/-ClientStream-Instanz entsteht - dieselbe ApplicationData-Basis wie
|
||||
/// AppBootstrapper (siehe dort) wird anders als TMPDIR zuverlässig an Kindprozesse
|
||||
/// weitergereicht. Muss als eine der ersten Anweisungen in Main aufgerufen werden (Desktop wie
|
||||
/// Bridge), auf Windows ein No-op (dort nutzen Named Pipes den Kernel-Namespace, keine
|
||||
/// Socket-Datei).
|
||||
/// </summary>
|
||||
public static void EnsureStableUnixSocketDirectory()
|
||||
{
|
||||
if (OperatingSystem.IsWindows()) return;
|
||||
var dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
||||
"LehrerApp", "ipc");
|
||||
Directory.CreateDirectory(dir);
|
||||
Environment.SetEnvironmentVariable("TMPDIR", dir);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,11 @@ public class CompetencyDomain
|
||||
public Guid Id { get; set; } = Guid.NewGuid();
|
||||
public Guid SubjectId { get; set; }
|
||||
public int GradeLevel { get; set; }
|
||||
/// <summary>Bildungsplan-Version dieses Bereichs (<see cref="CompetencyCatalogVersion"/>) - ein
|
||||
/// Fach kann mehrere parallel gültige Versionen haben (altes/neues Bildungsplan, während dieser
|
||||
/// klassenstufenweise hochwächst). Wird von der Migration für bestehende Datensätze auf die
|
||||
/// jeweilige Standardversion des Fachs gesetzt.</summary>
|
||||
public Guid VersionId { get; set; }
|
||||
public string Name { get; set; } = "";
|
||||
public string Code { get; set; } = "";
|
||||
public int SortOrder { get; set; }
|
||||
@@ -12,6 +17,22 @@ public class CompetencyDomain
|
||||
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
/// <summary>Eine Bildungsplan-Version eines Fachs (z.B. "Bildungsplan 2016" vs. "Bildungsplan 2026").
|
||||
/// Ermöglicht es, während ein neuer Bildungsplan klassenstufenweise hochwächst, alten und neuen
|
||||
/// Kompetenzkatalog parallel zu pflegen - <see cref="LearningGroup.CompetencyCatalogVersionId"/>
|
||||
/// wählt je Kurs/Klasse, welche Version gilt. Je Fach ist genau eine Version <see cref="IsDefault"/>
|
||||
/// (Kurse ohne explizite Wahl nutzen sie, siehe Doc-Kommentar auf <see cref="LearningGroup"/>).</summary>
|
||||
public class CompetencyCatalogVersion
|
||||
{
|
||||
public Guid Id { get; set; } = Guid.NewGuid();
|
||||
public Guid SubjectId { get; set; }
|
||||
public string Name { get; set; } = "";
|
||||
public bool IsDefault { get; set; }
|
||||
public int SortOrder { get; set; }
|
||||
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
public class CompetencyItem
|
||||
{
|
||||
public Guid Id { get; set; } = Guid.NewGuid();
|
||||
@@ -19,3 +40,17 @@ public class CompetencyItem
|
||||
public string Description { get; set; } = "";
|
||||
public int SortOrder { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Referenz auf eine Kompetenz aus dem Katalog, momentaufnahmeartig gespeichert (analog zu
|
||||
/// Exam.GradingKey/Exam.Tasks, siehe Datenmodell.md "Bewusst gespeicherte Momentaufnahmen"):
|
||||
/// Code/Description werden zum Zuordnungszeitpunkt kopiert. Solange ItemId noch im Katalog
|
||||
/// auflösbar ist, zeigt die UI die live aufgelöste Fassung (ein Rename wirkt sich sofort überall
|
||||
/// aus); wird das Item gelöscht, bleibt die hier gespeicherte historische Fassung lesbar statt
|
||||
/// spurlos zu verschwinden. ItemId == Guid.Empty markiert eine nie aufgelöste Referenz (z.B. aus
|
||||
/// einem plattformübergreifenden Import) - Code/Description sind dann die einzige Information.</summary>
|
||||
public class CompetencyReference
|
||||
{
|
||||
public Guid ItemId { get; set; }
|
||||
public string Code { get; set; } = "";
|
||||
public string Description { get; set; } = "";
|
||||
}
|
||||
@@ -28,7 +28,7 @@ public class ExamTask
|
||||
public string? Title { get; set; }
|
||||
public double MaxPoints { get; set; }
|
||||
public double Weight { get; set; } = 1.0;
|
||||
public List<string> CompetencyCodes { get; set; } = [];
|
||||
public List<CompetencyReference> Competencies { get; set; } = [];
|
||||
}
|
||||
public class GradingKeyEntry
|
||||
{
|
||||
|
||||
@@ -8,6 +8,14 @@ public class LearningGroup
|
||||
public Guid? SubjectId { get; set; }
|
||||
public string SchoolYear { get; set; } = "";
|
||||
public int GradeLevel { get; set; }
|
||||
/// <summary>
|
||||
/// Gewählte Bildungsplan-Version (<see cref="CompetencyCatalogVersion"/>) für den Kompetenzkatalog
|
||||
/// dieses Kurses/dieser Klasse. Null bedeutet bewusst nicht "keine Version", sondern "Standardversion
|
||||
/// des Fachs" (<see cref="CompetencyCatalogVersion.IsDefault"/>) - analog dazu, dass das Schuljahr
|
||||
/// nicht auf der Mitgliedschaft dupliziert wird, sondern von der Gruppe geerbt wird. So brauchen
|
||||
/// bestehende Kurse ohne neuen Bildungsplan keine Migration.
|
||||
/// </summary>
|
||||
public Guid? CompetencyCatalogVersionId { get; set; }
|
||||
public GradingSystem GradingSystem { get; set; }
|
||||
public int? HoursPerWeek { get; set; }
|
||||
public bool IsActive { get; set; } = true;
|
||||
@@ -27,6 +35,14 @@ public class LearningGroup
|
||||
/// </summary>
|
||||
public int? WebUntisLessonId { get; set; }
|
||||
/// <summary>
|
||||
/// Blendet diese Lerngruppe im UntisHub (siehe <see cref="Services"/>-Layer im Desktop-Projekt:
|
||||
/// UntisHubService) aus, auch wenn <see cref="WebUntisLessonId"/> gesetzt ist - z.B. für
|
||||
/// Klassenrat/AGs, die zwar eine WebUntis-Unterrichtsnummer haben, aber nicht auf
|
||||
/// Fehlzeiten/offene Periods hin überwacht werden sollen. Default false (alte Datensätze
|
||||
/// verhalten sich unverändert wie bisher).
|
||||
/// </summary>
|
||||
public bool ExcludedFromUntisHub { get; set; }
|
||||
/// <summary>
|
||||
/// Vorgängergruppe aus dem Hochstufen (<see cref="Services.GroupRolloverService"/>) —
|
||||
/// ermöglicht einen Schuljahresvergleich (z.B. Klausurschnitt) über die Kette hinweg.
|
||||
/// Wird ausschließlich beim Hochstufen automatisch gesetzt; vor Einführung dieses Felds
|
||||
|
||||
@@ -7,7 +7,7 @@ public class ParticipationSession
|
||||
public DateOnly Date { get; set; } = DateOnly.FromDateTime(DateTime.Today);
|
||||
public Guid? LessonId { get; set; }
|
||||
public string? Comment { get; set; }
|
||||
public List<string> CompetencyCodes { get; set; } = [];
|
||||
public List<CompetencyReference> Competencies { get; set; } = [];
|
||||
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
|
||||
}
|
||||
@@ -101,7 +101,7 @@ public class ParticipationSection
|
||||
|
||||
public class CompetencyRating
|
||||
{
|
||||
public string Code { get; set; } = "";
|
||||
public Guid ItemId { get; set; }
|
||||
public int Value { get; set; }
|
||||
}
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ public class Unit
|
||||
public string Title { get; set; } = "";
|
||||
public DateOnly? StartDate { get; set; }
|
||||
public DateOnly? EndDate { get; set; }
|
||||
public List<string> Competencies { get; set; } = [];
|
||||
public List<CompetencyReference> Competencies { get; set; } = [];
|
||||
public UnitStatus Status { get; set; } = UnitStatus.Planned;
|
||||
public string? Notes { get; set; }
|
||||
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||
@@ -54,7 +54,15 @@ public class Lesson : IHasAttachments
|
||||
/// Optionaler Stundenbeginn — solange kein Stundenplan (Kapitel 4.3) existiert, manuell
|
||||
/// gepflegt. Dient nur der abgeleiteten Uhrzeit-Anzeige je Phase in <see cref="Phases"/>.
|
||||
public TimeOnly? StartTime { get; set; }
|
||||
/// Grobe Ideen/erster Entwurf, festgehalten lange bevor der Verlaufsplan (<see cref="Phases"/>)
|
||||
/// feingeplant wird (Nutzer-Feedback: die eigentliche Ideenfindung liegt zeitlich oft weit vor
|
||||
/// der Feinplanung) — bewusst ein eigenes Feld statt Zweckentfremdung von <see cref="Reflection"/>
|
||||
/// (die ist nach der Stunde) oder <see cref="Unit.Notes"/> (die ist auf Einheitenebene, nicht je
|
||||
/// Stunde). Wird auch der KI-Planungsunterstützung (4.5.9) als Kontext mitgegeben, damit erste
|
||||
/// eigene Ideen bei der KI-gestützten Weiterplanung nicht erneut abgetippt werden müssen.
|
||||
public string? PlanningIdeas { get; set; }
|
||||
public List<LessonPhaseStep> Phases { get; set; } = [];
|
||||
public TeachingTimelineState? TeachingTimeline { get; set; }
|
||||
public string? Homework { get; set; }
|
||||
/// Markiert, dass die hier eingetragene Hausaufgabe in einer Folgestunde besprochen/kontrolliert
|
||||
/// wurde — treibt das Stundenplan-Badge "Hausaufgabe kontrollieren" (4.5.4).
|
||||
@@ -63,6 +71,11 @@ public class Lesson : IHasAttachments
|
||||
/// wenn die Hausaufgabe absichtlich nicht mehr kontrolliert wird).
|
||||
public bool HomeworkCheckDismissed { get; set; }
|
||||
public string? Reflection { get; set; }
|
||||
/// Kompetenzen aus dem Katalog, die dieser Stunde als Ganzes zugeordnet sind — analog zu
|
||||
/// <see cref="Unit.Competencies"/>, aber auf Stundenebene statt Einheitenebene. Bewusst noch
|
||||
/// keine Verknüpfung je einzelner <see cref="LessonPhaseStep"/> (siehe TODO.md 4.5.8, weiterhin
|
||||
/// offen); diese Liste deckt nur die gröbere Zuordnung ab.
|
||||
public List<CompetencyReference> Competencies { get; set; } = [];
|
||||
public LessonStatus Status { get; set; } = LessonStatus.Planned;
|
||||
/// Material/Arbeitsblätter sowie fachspezifische Anhänge (z.B. Experiment- und
|
||||
/// Gefährdungsbeurteilungs-Dokumente im Chemieunterricht) — dieselbe Anhang-Infrastruktur wie
|
||||
@@ -89,6 +102,14 @@ public class LessonPhaseStep
|
||||
public string Activity { get; set; } = "";
|
||||
public string Material { get; set; } = "";
|
||||
public string Shorthand { get; set; } = "";
|
||||
/// Der über <see cref="AiPlanning.AiPlanningService.BuildMaterialPrompt"/> erzeugte, vollständige
|
||||
/// Prompt für diese Phase (4.5.20), sofern die KI beim letzten "Übernehmen" einen Medienvorschlag
|
||||
/// gemacht hatte — anders als der reine Vorschlagstext (<c>AiPhaseStep.MaterialSuggestion</c>,
|
||||
/// nur transient während der Review) bewusst hier persistiert (Nutzer-Feedback: der Prompt soll
|
||||
/// auch nach dem Übernehmen noch abrufbar/erneut kopierbar bleiben, statt nur einmalig im
|
||||
/// Review-Dialog verfügbar zu sein). Rein informativ, kein Datenmodell-Bezug zu einem separaten
|
||||
/// "Material"-Konzept, das es weiterhin nicht gibt — siehe TODO.md 4.5.26.
|
||||
public string? MaterialPrompt { get; set; }
|
||||
/// <summary>
|
||||
/// null = Hauptweg. Sonst Verweis auf einen benannten <see cref="AlternativeLessonPath"/> aus
|
||||
/// dem Katalog, über den Phasen alternativer Unterrichtsverläufe zusammengehören —
|
||||
@@ -103,7 +124,7 @@ public enum UnitStatus { Planned, Active, Completed }
|
||||
// Planned=0 und Conducted=1 bleiben absichtlich an ihren bisherigen numerischen Positionen:
|
||||
// LiteDB hat diese Werte bereits gespeichert. Die neuen Zustände werden nur angehängt, damit
|
||||
// vorhandene Daten ohne Migration weiterhin korrekt gelesen werden.
|
||||
public enum LessonStatus { Planned = 0, Conducted = 1, Draft = 2, Ready = 3 }
|
||||
public enum LessonStatus { Planned = 0, Conducted = 1, Draft = 2, Ready = 3, Cancelled = 4 }
|
||||
|
||||
/// <summary>
|
||||
/// Katalogeintrag für einen wiederverwendbaren "alternativen Ablauf" (z.B. "Kurzversion" bei
|
||||
@@ -239,3 +260,21 @@ public class ReportGrade
|
||||
public bool IsLocked { get; set; }
|
||||
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
/// <summary>Live timing is separate from the original lesson plan.</summary>
|
||||
public class TeachingTimelineState
|
||||
{
|
||||
public DateTime StartUtc { get; set; }
|
||||
public DateTime EndUtc { get; set; }
|
||||
public DateTime? HeldSinceUtc { get; set; }
|
||||
public Guid? HeldPhaseId { get; set; }
|
||||
public List<TeachingPhaseTiming> Phases { get; set; } = [];
|
||||
public List<Guid> TransferredPhaseIds { get; set; } = [];
|
||||
}
|
||||
|
||||
public class TeachingPhaseTiming
|
||||
{
|
||||
public Guid PhaseId { get; set; }
|
||||
public double Minutes { get; set; }
|
||||
public bool ExplicitlyStarted { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
namespace LehrerApp.Core.Models;
|
||||
|
||||
public enum UntisHubJobKind
|
||||
{
|
||||
FehlzeitenKurz,
|
||||
FehlzeitenLang,
|
||||
OffenePeriods,
|
||||
Klassenbuchabgleich,
|
||||
Hausaufgabenabgleich,
|
||||
}
|
||||
|
||||
/// <summary>Wann welcher WebUntis-Abgleich ("Untis-Hub"-Job, siehe TODO.md) zuletzt lief und mit
|
||||
/// welchem Ergebnis - ein Datensatz pro (<see cref="Kind"/>, <see cref="GroupId"/>). Bei den drei
|
||||
/// dashboard-weiten Jobs (<see cref="UntisHubJobKind.OffenePeriods"/>,
|
||||
/// <see cref="UntisHubJobKind.Klassenbuchabgleich"/>, <see cref="UntisHubJobKind.Hausaufgabenabgleich"/>)
|
||||
/// ist <see cref="GroupId"/> null; die beiden Fehlzeiten-Kadenzen sind je Lerngruppe getrennt.</summary>
|
||||
public class UntisHubJobState
|
||||
{
|
||||
public Guid Id { get; set; } = Guid.NewGuid();
|
||||
public UntisHubJobKind Kind { get; set; }
|
||||
public Guid? GroupId { get; set; }
|
||||
public DateTime? LastRunAt { get; set; }
|
||||
public string? LastResultSummary { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
namespace LehrerApp.Core.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Fallmappe für ein konkretes, laufendes Problem mit einer/einem oder mehreren Schüler*innen
|
||||
/// (z.B. Schuleschwänzen, wiederholte Hausaufgaben-Verweigerung, ein Konflikt) — bündelt Titel,
|
||||
/// Problembeschreibung, Schlagwörter sowie die dazugehörigen <see cref="Documentation"/>-Einträge
|
||||
/// und eingefrorene WebUntis-Klassenbucheinträge an einem Ort, statt sie über datumsgefilterte
|
||||
/// Listen verstreut zu lassen. Bewusst nur Referenzen (<see cref="DocumentationIds"/>) statt
|
||||
/// gecachtem Inhalt — die Datenmenge pro Lehrkraft ist klein genug, dass ein Cache nur
|
||||
/// Invalidierungs-Komplexität einführen würde, ohne echten Nutzen (siehe TODO.md, Präzedenzfall
|
||||
/// 5.3.3: eine Plan-ID-Gruppierung für Förderpläne wurde aus demselben Grund verworfen).
|
||||
/// </summary>
|
||||
public class Vorgang
|
||||
{
|
||||
public Guid Id { get; set; } = Guid.NewGuid();
|
||||
public string Title { get; set; } = "";
|
||||
public string Description { get; set; } = "";
|
||||
public List<Guid> StudentIds { get; set; } = [];
|
||||
/// Freie Labels, z.B. "Absentismus", "Hausaufgaben", "Verspätungen", "Konflikte" —
|
||||
/// siehe VorgangTagDisplay.Suggestions im Desktop-Projekt für die Vorschlagsliste.
|
||||
public List<string> Tags { get; set; } = [];
|
||||
public VorgangStatus Status { get; set; } = VorgangStatus.Open;
|
||||
public List<Guid> DocumentationIds { get; set; } = [];
|
||||
public List<VorgangClassRegisterEntry> ClassRegisterEntries { get; set; } = [];
|
||||
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
|
||||
public DateTime? ClosedAt { get; set; }
|
||||
public bool IsDeleted { get; set; }
|
||||
public DateTime? DeletedAt { get; set; }
|
||||
}
|
||||
|
||||
public enum VorgangStatus { Open, Closed }
|
||||
|
||||
/// <summary>
|
||||
/// Eingefrorene Kopie einer WebUntis-Klassenbuchzeile zum Zeitpunkt des Anheftens an einen
|
||||
/// <see cref="Vorgang"/> — keine Referenz per ID, da weder <c>UntisForeignClassRegisterEventDto</c>
|
||||
/// noch <c>UntisClassRegisterCacheEntry</c> eine über einen Cache-Refresh hinweg stabile ID haben.
|
||||
/// </summary>
|
||||
public class VorgangClassRegisterEntry
|
||||
{
|
||||
public DateOnly Date { get; set; }
|
||||
public string StudentName { get; set; } = "";
|
||||
public string? Subject { get; set; }
|
||||
public string? TeacherUsername { get; set; }
|
||||
public string? CategoryName { get; set; }
|
||||
public string? CategoryGroup { get; set; }
|
||||
public string? Text { get; set; }
|
||||
public DateTime PinnedAt { get; set; } = DateTime.UtcNow;
|
||||
}
|
||||
@@ -32,31 +32,54 @@ public sealed class CompetencyAnalysisService
|
||||
IReadOnlyList<ExamResult> results)
|
||||
{
|
||||
var builders = new List<ItemBuilder>();
|
||||
var byCode = new Dictionary<string, ItemBuilder>(StringComparer.OrdinalIgnoreCase);
|
||||
var byId = new Dictionary<Guid, ItemBuilder>();
|
||||
// Referenzen, die nie einem Katalogeintrag zugeordnet werden konnten (ItemId == Guid.Empty,
|
||||
// z.B. aus einem plattformübergreifenden Import) haben keine gemeinsame Id, über die
|
||||
// mehrfache Zuordnungen derselben Kompetenz zusammengeführt werden könnten - dafür wird
|
||||
// ersatzweise der Code-Text als Merge-Schlüssel verwendet.
|
||||
var byUnresolvedCode = new Dictionary<string, ItemBuilder>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
foreach (var domain in catalog.OrderBy(x => x.SortOrder))
|
||||
foreach (var item in domain.Items.OrderBy(x => x.SortOrder))
|
||||
{
|
||||
var builder = new ItemBuilder(domain.Name, domain.Code, item.Code, item.Description);
|
||||
builders.Add(builder);
|
||||
if (!string.IsNullOrWhiteSpace(item.Code)) byCode.TryAdd(item.Code.Trim(), builder);
|
||||
byId.TryAdd(item.Id, builder);
|
||||
}
|
||||
|
||||
ItemBuilder GetOrAdd(string rawCode)
|
||||
// Solange die Referenz noch im aktuellen Katalog auflösbar ist, zählt die LIVE-Fassung
|
||||
// (ein Rename wirkt sich damit sofort aus). Ist sie es nicht mehr (gelöscht, andere
|
||||
// Bildungsplan-Version, oder nie aufgelöster plattformübergreifender Import), wird ein
|
||||
// Platzhalter aus der zum Zuordnungszeitpunkt gespeicherten Momentaufnahme synthetisiert -
|
||||
// dadurch bleibt (anders als bei der bisherigen reinen Code-Textkonserve) sogar die echte
|
||||
// historische Beschreibung erhalten.
|
||||
ItemBuilder GetOrAdd(CompetencyReference reference)
|
||||
{
|
||||
var code = rawCode.Trim();
|
||||
if (byCode.TryGetValue(code, out var existing)) return existing;
|
||||
var added = new ItemBuilder("Nicht im Katalog", "", code,
|
||||
"Dieser Kompetenzcode wird noch verwendet, ist aber nicht im aktuellen Katalog enthalten.");
|
||||
byCode[code] = added;
|
||||
var description = string.IsNullOrWhiteSpace(reference.Description)
|
||||
? "Diese Kompetenz wird noch verwendet, ist aber nicht (mehr) im aktuellen Katalog enthalten."
|
||||
: reference.Description;
|
||||
|
||||
if (reference.ItemId == Guid.Empty)
|
||||
{
|
||||
var codeKey = reference.Code.Trim();
|
||||
if (byUnresolvedCode.TryGetValue(codeKey, out var existingUnresolved)) return existingUnresolved;
|
||||
var addedUnresolved = new ItemBuilder("Nicht im Katalog", "", reference.Code, description);
|
||||
byUnresolvedCode[codeKey] = addedUnresolved;
|
||||
builders.Add(addedUnresolved);
|
||||
return addedUnresolved;
|
||||
}
|
||||
|
||||
if (byId.TryGetValue(reference.ItemId, out var existing)) return existing;
|
||||
var added = new ItemBuilder("Nicht im Katalog", "", reference.Code, description);
|
||||
byId[reference.ItemId] = added;
|
||||
builders.Add(added);
|
||||
return added;
|
||||
}
|
||||
|
||||
foreach (var unit in units)
|
||||
foreach (var code in NormalizeCodes(unit.Competencies))
|
||||
foreach (var reference in NormalizeReferences(unit.Competencies))
|
||||
{
|
||||
var builder = GetOrAdd(code);
|
||||
var builder = GetOrAdd(reference);
|
||||
if (unit.Status == UnitStatus.Planned) builder.PlannedUnits++;
|
||||
else builder.TaughtUnits++;
|
||||
}
|
||||
@@ -64,10 +87,10 @@ public sealed class CompetencyAnalysisService
|
||||
var resultsByExam = results.GroupBy(x => x.ExamId).ToDictionary(x => x.Key, x => x.ToList());
|
||||
foreach (var exam in exams)
|
||||
{
|
||||
var examCodes = NormalizeCodes(exam.Tasks.SelectMany(x => x.CompetencyCodes));
|
||||
foreach (var code in examCodes)
|
||||
var examReferences = NormalizeReferences(exam.Tasks.SelectMany(x => x.Competencies));
|
||||
foreach (var reference in examReferences)
|
||||
{
|
||||
var builder = GetOrAdd(code);
|
||||
var builder = GetOrAdd(reference);
|
||||
if (exam.Status == ExamStatus.Planned) builder.PlannedExams++;
|
||||
else builder.AssessedExams++;
|
||||
}
|
||||
@@ -81,17 +104,16 @@ public sealed class CompetencyAnalysisService
|
||||
var task = exam.Tasks[taskIndex];
|
||||
if (task.MaxPoints <= 0) continue;
|
||||
var achieved = Math.Clamp(result.Points[taskIndex], 0, task.MaxPoints);
|
||||
foreach (var code in NormalizeCodes(task.CompetencyCodes))
|
||||
GetOrAdd(code).AddScore(result.StudentId, achieved, task.MaxPoints);
|
||||
foreach (var reference in NormalizeReferences(task.Competencies))
|
||||
GetOrAdd(reference).AddScore(result.StudentId, achieved, task.MaxPoints);
|
||||
}
|
||||
}
|
||||
|
||||
return builders.Select(x => x.Build()).ToList();
|
||||
}
|
||||
|
||||
private static bool HasCode(string? value) => !string.IsNullOrWhiteSpace(value);
|
||||
private static IEnumerable<string> NormalizeCodes(IEnumerable<string> codes) =>
|
||||
codes.Where(HasCode).Select(x => x.Trim()).Distinct(StringComparer.OrdinalIgnoreCase);
|
||||
private static IEnumerable<CompetencyReference> NormalizeReferences(IEnumerable<CompetencyReference> references) =>
|
||||
references.DistinctBy(x => x.ItemId);
|
||||
|
||||
private sealed class ItemBuilder(
|
||||
string domainName, string domainCode, string code, string description)
|
||||
|
||||
@@ -15,6 +15,7 @@ public sealed class CompetencyCatalogImportPreview
|
||||
public required Guid SubjectId { get; init; }
|
||||
public required string SubjectName { get; init; }
|
||||
public required int GradeLevel { get; init; }
|
||||
public required Guid VersionId { get; init; }
|
||||
public required List<CompetencyDomain> ImportedDomains { get; init; }
|
||||
public required string ExistingFingerprint { get; init; }
|
||||
public List<string> Warnings { get; init; } = [];
|
||||
@@ -28,7 +29,7 @@ public sealed class CompetencyCatalogImportPreview
|
||||
public sealed class CompetencyCatalogImportService(ICompetencyDomainRepository repository)
|
||||
{
|
||||
public CompetencyCatalogImportPreview Analyze(
|
||||
string json, Guid subjectId, string subjectName, int gradeLevel)
|
||||
string json, Guid subjectId, string subjectName, int gradeLevel, Guid versionId)
|
||||
{
|
||||
CatalogDto dto;
|
||||
try
|
||||
@@ -100,7 +101,7 @@ public sealed class CompetencyCatalogImportService(ICompetencyDomainRepository r
|
||||
if (dto.GradeLevel is > 0 and <= 13 && dto.GradeLevel != gradeLevel)
|
||||
warnings.Add($"Die Datei nennt Klassenstufe {dto.GradeLevel}, ausgewählt ist Klassenstufe {gradeLevel}.");
|
||||
|
||||
var existing = repository.GetBySubjectAndGrade(subjectId, gradeLevel);
|
||||
var existing = repository.GetBySubjectAndGrade(subjectId, gradeLevel, versionId);
|
||||
var conflicts = new List<CompetencyCatalogImportConflict>();
|
||||
var newDomains = 0;
|
||||
var newItems = 0;
|
||||
@@ -147,6 +148,7 @@ public sealed class CompetencyCatalogImportService(ICompetencyDomainRepository r
|
||||
SubjectId = subjectId,
|
||||
SubjectName = subjectName,
|
||||
GradeLevel = gradeLevel,
|
||||
VersionId = versionId,
|
||||
ImportedDomains = imported,
|
||||
ExistingFingerprint = Fingerprint(existing),
|
||||
Warnings = warnings,
|
||||
@@ -160,7 +162,7 @@ public sealed class CompetencyCatalogImportService(ICompetencyDomainRepository r
|
||||
public void Apply(CompetencyCatalogImportPreview preview, CompetencyCatalogImportMode mode,
|
||||
IReadOnlySet<string>? useImportedConflicts = null)
|
||||
{
|
||||
var current = repository.GetBySubjectAndGrade(preview.SubjectId, preview.GradeLevel);
|
||||
var current = repository.GetBySubjectAndGrade(preview.SubjectId, preview.GradeLevel, preview.VersionId);
|
||||
if (Fingerprint(current) != preview.ExistingFingerprint)
|
||||
throw new InvalidOperationException(
|
||||
"Der Kompetenzkatalog wurde seit der Vorschau verändert. Bitte öffne den Import erneut.");
|
||||
@@ -169,7 +171,7 @@ public sealed class CompetencyCatalogImportService(ICompetencyDomainRepository r
|
||||
? preview.ImportedDomains.Select((d, index) => CloneAsNew(d, preview.SubjectId, preview.GradeLevel, index)).ToList()
|
||||
: Merge(current, preview, useImportedConflicts ?? new HashSet<string>());
|
||||
|
||||
repository.ReplaceForSubjectAndGrade(preview.SubjectId, preview.GradeLevel, result);
|
||||
repository.ReplaceForSubjectGradeAndVersion(preview.SubjectId, preview.GradeLevel, preview.VersionId, result);
|
||||
}
|
||||
|
||||
private static List<CompetencyDomain> Merge(List<CompetencyDomain> existing,
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
using LehrerApp.Core.Interfaces;
|
||||
|
||||
namespace LehrerApp.Core.Services;
|
||||
|
||||
/// <summary>Löst die für einen Kurs/eine Klasse geltende Bildungsplan-Version auf: die explizit am
|
||||
/// Kurs gewählte Version (<see cref="Models.LearningGroup.CompetencyCatalogVersionId"/>), falls sie
|
||||
/// noch existiert, sonst die Standardversion des Fachs (siehe Doc-Kommentar auf dem Feld). Ohne Fach
|
||||
/// gibt es keine Version (<see cref="Guid.Empty"/>).</summary>
|
||||
public static class CompetencyCatalogVersionResolver
|
||||
{
|
||||
public static Guid Resolve(ICompetencyCatalogVersionRepository versions, Guid? subjectId, Guid? groupVersionId)
|
||||
{
|
||||
if (subjectId is not Guid sid) return Guid.Empty;
|
||||
if (groupVersionId is Guid vid && versions.GetById(vid) is { } explicitVersion) return explicitVersion.Id;
|
||||
return versions.GetOrCreateDefault(sid).Id;
|
||||
}
|
||||
}
|
||||
@@ -12,11 +12,13 @@ public sealed class DashboardCardSetting
|
||||
/// <summary>Speichert Sichtbarkeit und Reihenfolge der Dashboard-Kacheln lokal.</summary>
|
||||
public sealed class DashboardSettingsService
|
||||
{
|
||||
// "attention" fasst die frueheren sieben Kacheln missingteachingtime/excuses/corrections/
|
||||
// unplanned/alerts/attendance/support zusammen (siehe AttentionItem.cs im Desktop-Projekt).
|
||||
// Alte gespeicherte dashboardsettings.json-Dateien mit den frueheren Keys sind unproblematisch:
|
||||
// Load() unten verwirft unbekannte Keys ohnehin stillschweigend und ergaenzt neue als sichtbar.
|
||||
public static readonly string[] DefaultCardOrder =
|
||||
[
|
||||
"today", "tasks", "calendar", "excuses", "upcoming",
|
||||
"corrections", "unplanned", "alerts", "attendance", "support", "groups", "examload",
|
||||
"missingteachingtime",
|
||||
"today", "tasks", "attention", "calendar", "upcoming", "groups", "examload",
|
||||
];
|
||||
|
||||
private readonly string _configPath;
|
||||
|
||||
@@ -16,7 +16,7 @@ public sealed class LessonSchedulingService(ILessonRepository lessons)
|
||||
{
|
||||
foreach (var other in lessons.GetByUnit(lesson.UnitId))
|
||||
{
|
||||
if (other.Id == lesson.Id || other.Status == LessonStatus.Conducted || other.Date <= oldDate)
|
||||
if (other.Id == lesson.Id || other.Status is LessonStatus.Conducted or LessonStatus.Cancelled || other.Date <= oldDate)
|
||||
continue;
|
||||
other.Date = other.Date.AddDays(delta);
|
||||
lessons.Save(other);
|
||||
@@ -67,7 +67,7 @@ public sealed class LessonSchedulingService(ILessonRepository lessons)
|
||||
HomeworkChecked = source.HomeworkChecked,
|
||||
HomeworkCheckDismissed = source.HomeworkCheckDismissed,
|
||||
Reflection = source.Reflection,
|
||||
Status = source.Status == LessonStatus.Conducted ? LessonStatus.Draft : source.Status,
|
||||
Status = source.Status is LessonStatus.Conducted or LessonStatus.Cancelled ? LessonStatus.Draft : source.Status,
|
||||
};
|
||||
source.Homework = null;
|
||||
source.HomeworkChecked = false;
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace LehrerApp.Core.Services;
|
||||
|
||||
/// <summary>Gewichte für ClassTeacherRosterRow.PatternScore (Klassenlehrer-Bereich, "Gesamtbild")
|
||||
/// — Default-Werte entsprechen den ursprünglich fest verdrahteten Konstanten.</summary>
|
||||
public sealed class PatternScoreWeights
|
||||
{
|
||||
public double UnexcusedDayWeight { get; set; } = 3.0;
|
||||
public double ExcusedDayWeight { get; set; } = 1.0;
|
||||
public double LateDayWeight { get; set; } = 0.5;
|
||||
public double NegativeClassRegisterEntryWeight { get; set; } = 1.0;
|
||||
public double ConcerningKeywordBonus { get; set; } = 1.5;
|
||||
public double SuspensionKeywordWeight { get; set; } = 15.0;
|
||||
}
|
||||
|
||||
/// <summary>Speichert die Gewichte lokal, gleiches Muster wie WorkloadSettingsService/
|
||||
/// DashboardSettingsService.</summary>
|
||||
public sealed class PatternScoreSettingsService
|
||||
{
|
||||
private readonly string _configPath;
|
||||
|
||||
public PatternScoreSettingsService(string appDataPath) =>
|
||||
_configPath = Path.Combine(appDataPath, "patternscoreweights.json");
|
||||
|
||||
public PatternScoreWeights Load()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(_configPath))
|
||||
return JsonSerializer.Deserialize<PatternScoreWeights>(File.ReadAllText(_configPath))
|
||||
?? new PatternScoreWeights();
|
||||
}
|
||||
catch { /* beschädigte Konfiguration -> Standardgewichte */ }
|
||||
return new PatternScoreWeights();
|
||||
}
|
||||
|
||||
public void Save(PatternScoreWeights weights) =>
|
||||
File.WriteAllText(_configPath, JsonSerializer.Serialize(weights));
|
||||
}
|
||||
@@ -123,7 +123,7 @@ public sealed class ChangeHookCascadeTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CompetencyDomainRepository_ReplaceForSubjectAndGrade_LoestDeleteFuerAlteUndSaveFuerNeueAus()
|
||||
public void CompetencyDomainRepository_ReplaceForSubjectGradeAndVersion_LoestDeleteFuerAlteUndSaveFuerNeueAus()
|
||||
{
|
||||
using var db = NewInMemoryContext();
|
||||
var repo = new CompetencyDomainRepository(db);
|
||||
@@ -132,7 +132,7 @@ public sealed class ChangeHookCascadeTests
|
||||
var calls = new List<(string EntityType, string Operation)>();
|
||||
db.OnChange = (type, id, op, payload) => calls.Add((type, op));
|
||||
|
||||
repo.ReplaceForSubjectAndGrade(subjectId, 8,
|
||||
repo.ReplaceForSubjectGradeAndVersion(subjectId, 8, Guid.Empty,
|
||||
[
|
||||
new CompetencyDomain { Name = "Neu 1" },
|
||||
new CompetencyDomain { Name = "Neu 2" },
|
||||
@@ -145,7 +145,7 @@ public sealed class ChangeHookCascadeTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CompetencyDomainRepository_DeleteBySubjectAndGrade_LoestEinEreignisProDomaenAus()
|
||||
public void CompetencyDomainRepository_DeleteBySubjectGradeAndVersion_LoestEinEreignisProDomaenAus()
|
||||
{
|
||||
using var db = NewInMemoryContext();
|
||||
var repo = new CompetencyDomainRepository(db);
|
||||
@@ -155,7 +155,7 @@ public sealed class ChangeHookCascadeTests
|
||||
var calls = new List<(string EntityType, string Operation)>();
|
||||
db.OnChange = (type, id, op, payload) => calls.Add((type, op));
|
||||
|
||||
repo.DeleteBySubjectAndGrade(subjectId, 8);
|
||||
repo.DeleteBySubjectGradeAndVersion(subjectId, 8, Guid.Empty);
|
||||
|
||||
Assert.Equal(2, calls.Count);
|
||||
Assert.All(calls, c => Assert.Equal((nameof(CompetencyDomain), "Delete"), c));
|
||||
@@ -193,4 +193,21 @@ public sealed class ChangeHookCascadeTests
|
||||
var call = Assert.Single(calls);
|
||||
Assert.Equal((nameof(Documentation), "Delete"), call);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void VorgangRepository_Delete_LoestSaveMitIsDeletedAus()
|
||||
{
|
||||
using var db = NewInMemoryContext();
|
||||
var repo = new VorgangRepository(db);
|
||||
var vorgang = new Vorgang { Title = "Konflikt" };
|
||||
repo.Save(vorgang);
|
||||
var calls = new List<(string EntityType, string Operation, object? Payload)>();
|
||||
db.OnChange = (type, id, op, payload) => calls.Add((type, op, payload));
|
||||
|
||||
repo.Delete(vorgang.Id);
|
||||
|
||||
var call = Assert.Single(calls);
|
||||
Assert.Equal((nameof(Vorgang), "Save"), (call.EntityType, call.Operation));
|
||||
Assert.True(((Vorgang)call.Payload!).IsDeleted);
|
||||
}
|
||||
}
|
||||
@@ -121,6 +121,14 @@ public sealed class ChangeHookMatrixTests
|
||||
return (subject.Id, () => repo.Delete(subject.Id));
|
||||
});
|
||||
|
||||
yield return Case("CompetencyCatalogVersion", nameof(CompetencyCatalogVersion), db =>
|
||||
{
|
||||
var repo = new CompetencyCatalogVersionRepository(db);
|
||||
var version = new CompetencyCatalogVersion { SubjectId = Guid.NewGuid(), Name = "Bildungsplan 2026" };
|
||||
repo.Save(version);
|
||||
return (version.Id, () => repo.Delete(version.Id));
|
||||
});
|
||||
|
||||
yield return Case("ShorthandCode", nameof(ShorthandCode), db =>
|
||||
{
|
||||
var repo = new ShorthandCodeRepository(db);
|
||||
|
||||
@@ -57,4 +57,24 @@ public sealed class ChangeHookTests
|
||||
|
||||
Assert.Null(exception);
|
||||
}
|
||||
|
||||
// Kein eigener Fall in ChangeHookMatrixTests: UntisHubJobStateRepository kennt kein Delete
|
||||
// (siehe IUntisHubJobStateRepository), passt also nicht in deren Save+Delete-Tabellenform.
|
||||
[Fact]
|
||||
public void UntisHubJobStateRepository_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 UntisHubJobStateRepository(db);
|
||||
var state = new UntisHubJobState { Kind = UntisHubJobKind.OffenePeriods, LastRunAt = DateTime.UtcNow };
|
||||
|
||||
repo.Save(state);
|
||||
|
||||
var call = Assert.Single(calls);
|
||||
Assert.Equal(nameof(UntisHubJobState), call.EntityType);
|
||||
Assert.Equal(state.Id.ToString(), call.EntityId);
|
||||
Assert.Equal("Save", call.Operation);
|
||||
Assert.Same(state, call.Payload);
|
||||
}
|
||||
}
|
||||
@@ -121,7 +121,7 @@ public sealed class LiteDbContextTests
|
||||
using var temp = new TempDatabase();
|
||||
using var context = new LiteDbContext(temp.Path);
|
||||
|
||||
Assert.Equal(4, context.SchemaVersion);
|
||||
Assert.Equal(6, context.SchemaVersion);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -132,7 +132,139 @@ public sealed class LiteDbContextTests
|
||||
|
||||
using var second = new LiteDbContext(temp.Path);
|
||||
|
||||
Assert.Equal(4, second.SchemaVersion);
|
||||
Assert.Equal(6, second.SchemaVersion);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MigrateCompetencyCatalogVersions_ErzeugtStandardversionJeFachUndVerknuepftBestehendeBereiche()
|
||||
{
|
||||
using var temp = new TempDatabase();
|
||||
var subjectAId = Guid.NewGuid();
|
||||
var subjectBId = Guid.NewGuid();
|
||||
var domainA1Id = Guid.NewGuid();
|
||||
var domainA2Id = Guid.NewGuid();
|
||||
var domainBId = Guid.NewGuid();
|
||||
|
||||
using (var legacy = new LiteDatabase(temp.Path))
|
||||
{
|
||||
var domains = legacy.GetCollection<BsonDocument>("competency_domains");
|
||||
domains.Insert(new BsonDocument
|
||||
{
|
||||
["_id"] = domainA1Id, [nameof(CompetencyDomain.SubjectId)] = subjectAId,
|
||||
[nameof(CompetencyDomain.GradeLevel)] = 8, [nameof(CompetencyDomain.Name)] = "Bereich A1",
|
||||
});
|
||||
domains.Insert(new BsonDocument
|
||||
{
|
||||
["_id"] = domainA2Id, [nameof(CompetencyDomain.SubjectId)] = subjectAId,
|
||||
[nameof(CompetencyDomain.GradeLevel)] = 9, [nameof(CompetencyDomain.Name)] = "Bereich A2",
|
||||
});
|
||||
domains.Insert(new BsonDocument
|
||||
{
|
||||
["_id"] = domainBId, [nameof(CompetencyDomain.SubjectId)] = subjectBId,
|
||||
[nameof(CompetencyDomain.GradeLevel)] = 8, [nameof(CompetencyDomain.Name)] = "Bereich B",
|
||||
});
|
||||
}
|
||||
|
||||
using var context = new LiteDbContext(temp.Path);
|
||||
|
||||
var versions = context.CompetencyCatalogVersions.FindAll().ToList();
|
||||
var versionA = Assert.Single(versions, v => v.SubjectId == subjectAId);
|
||||
var versionB = Assert.Single(versions, v => v.SubjectId == subjectBId);
|
||||
Assert.True(versionA.IsDefault);
|
||||
Assert.True(versionB.IsDefault);
|
||||
Assert.Equal("Bestehender Kompetenzkatalog", versionA.Name);
|
||||
|
||||
var domainsAfter = context.CompetencyDomains.FindAll().ToDictionary(d => d.Id);
|
||||
Assert.Equal(versionA.Id, domainsAfter[domainA1Id].VersionId);
|
||||
Assert.Equal(versionA.Id, domainsAfter[domainA2Id].VersionId);
|
||||
Assert.Equal(versionB.Id, domainsAfter[domainBId].VersionId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MigrateCompetencyReferences_LoestCodesGegenKatalogAufUndBehaeltUnbekannteAlsText()
|
||||
{
|
||||
using var temp = new TempDatabase();
|
||||
var unitId = Guid.NewGuid();
|
||||
var examId = Guid.NewGuid();
|
||||
var sessionId = Guid.NewGuid();
|
||||
var entryId = Guid.NewGuid();
|
||||
var itemId = Guid.NewGuid();
|
||||
|
||||
using (var legacy = new LiteDatabase(temp.Path))
|
||||
{
|
||||
legacy.GetCollection<BsonDocument>("competency_domains").Insert(new BsonDocument
|
||||
{
|
||||
["_id"] = Guid.NewGuid(),
|
||||
[nameof(CompetencyDomain.Name)] = "Bereich",
|
||||
[nameof(CompetencyDomain.Items)] = new BsonArray
|
||||
{
|
||||
new BsonDocument
|
||||
{
|
||||
["_id"] = itemId,
|
||||
[nameof(CompetencyItem.Code)] = "K1",
|
||||
[nameof(CompetencyItem.Description)] = "Erste Kompetenz",
|
||||
},
|
||||
},
|
||||
});
|
||||
legacy.GetCollection<BsonDocument>("units").Insert(new BsonDocument
|
||||
{
|
||||
["_id"] = unitId,
|
||||
[nameof(Unit.GroupId)] = Guid.NewGuid(),
|
||||
[nameof(Unit.Competencies)] = new BsonArray { "K1", "ALT" },
|
||||
});
|
||||
legacy.GetCollection<BsonDocument>("exams").Insert(new BsonDocument
|
||||
{
|
||||
["_id"] = examId,
|
||||
[nameof(Exam.GroupId)] = Guid.NewGuid(),
|
||||
[nameof(Exam.Tasks)] = new BsonArray
|
||||
{
|
||||
new BsonDocument { ["Nr"] = 1, ["MaxPoints"] = 10.0, ["CompetencyCodes"] = new BsonArray { "K1" } },
|
||||
},
|
||||
});
|
||||
legacy.GetCollection<BsonDocument>("participation_sessions").Insert(new BsonDocument
|
||||
{
|
||||
["_id"] = sessionId,
|
||||
[nameof(ParticipationSession.GroupId)] = Guid.NewGuid(),
|
||||
["CompetencyCodes"] = new BsonArray { "K1" },
|
||||
});
|
||||
legacy.GetCollection<BsonDocument>("participation").Insert(new BsonDocument
|
||||
{
|
||||
["_id"] = entryId,
|
||||
[nameof(ParticipationEntry.SessionId)] = sessionId,
|
||||
[nameof(ParticipationEntry.StudentId)] = Guid.NewGuid(),
|
||||
[nameof(ParticipationEntry.CompetencyRatings)] = new BsonArray
|
||||
{
|
||||
new BsonDocument { ["Code"] = "K1", ["Value"] = 2 },
|
||||
new BsonDocument { ["Code"] = "UNBEKANNT", ["Value"] = 1 },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
using var context = new LiteDbContext(temp.Path);
|
||||
|
||||
var unit = context.Units.FindById(unitId);
|
||||
Assert.Equal(2, unit!.Competencies.Count);
|
||||
var known = unit.Competencies.Single(c => c.Code == "K1");
|
||||
Assert.Equal(itemId, known.ItemId);
|
||||
Assert.Equal("Erste Kompetenz", known.Description);
|
||||
var unknown = unit.Competencies.Single(c => c.Code == "ALT");
|
||||
Assert.Equal(Guid.Empty, unknown.ItemId);
|
||||
|
||||
var exam = context.Exams.FindById(examId);
|
||||
var task = Assert.Single(exam!.Tasks);
|
||||
var examRef = Assert.Single(task.Competencies);
|
||||
Assert.Equal(itemId, examRef.ItemId);
|
||||
|
||||
var session = context.ParticipationSessions.FindById(sessionId);
|
||||
var sessionRef = Assert.Single(session!.Competencies);
|
||||
Assert.Equal(itemId, sessionRef.ItemId);
|
||||
|
||||
// Rating mit unbekanntem Code wird verworfen (kein sinnvoll erhaltbarer Zahlenwert ohne
|
||||
// erkennbare Identität) - nur das auflösbare Rating bleibt übrig.
|
||||
var entry = context.ParticipationEntries.FindById(entryId);
|
||||
var rating = Assert.Single(entry!.CompetencyRatings);
|
||||
Assert.Equal(itemId, rating.ItemId);
|
||||
Assert.Equal(2, rating.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -715,6 +715,67 @@ public sealed class RepositoryTests
|
||||
Assert.Null(storage.OpenRead(attachmentId));
|
||||
}
|
||||
|
||||
// ── VorgangRepository ─────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void VorgangRepository_Save_SetztUpdatedAt()
|
||||
{
|
||||
using var db = NewInMemoryContext();
|
||||
var repo = new VorgangRepository(db);
|
||||
var vorgang = new Vorgang { Title = "Schuleschwänzen Max" };
|
||||
|
||||
repo.Save(vorgang);
|
||||
|
||||
var raw = db.Vorgaenge.FindById(vorgang.Id);
|
||||
Assert.NotNull(raw);
|
||||
Assert.True((DateTime.UtcNow - raw!.UpdatedAt).TotalSeconds < 5);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void VorgangRepository_GetByStudent_FindetVorgaengeMitMehrerenSchuelern()
|
||||
{
|
||||
using var db = NewInMemoryContext();
|
||||
var repo = new VorgangRepository(db);
|
||||
var ada = Guid.NewGuid();
|
||||
var ben = Guid.NewGuid();
|
||||
var other = Guid.NewGuid();
|
||||
var shared = new Vorgang { Title = "Konflikt", StudentIds = [ada, ben] };
|
||||
var unrelated = new Vorgang { Title = "Anderes", StudentIds = [other] };
|
||||
repo.Save(shared);
|
||||
repo.Save(unrelated);
|
||||
|
||||
Assert.Equal([shared.Id], repo.GetByStudent(ada).Select(v => v.Id));
|
||||
Assert.Equal([shared.Id], repo.GetByStudent(ben).Select(v => v.Id));
|
||||
Assert.Empty(repo.GetByStudent(Guid.NewGuid()));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void VorgangRepository_Delete_MarkiertNurAlsGeloescht()
|
||||
{
|
||||
using var db = NewInMemoryContext();
|
||||
var repo = new VorgangRepository(db);
|
||||
var vorgang = new Vorgang { Title = "Hausaufgaben fehlen" };
|
||||
repo.Save(vorgang);
|
||||
|
||||
repo.Delete(vorgang.Id);
|
||||
|
||||
Assert.Empty(repo.GetAll());
|
||||
Assert.Null(repo.GetById(vorgang.Id));
|
||||
var raw = db.Vorgaenge.FindById(vorgang.Id);
|
||||
Assert.NotNull(raw);
|
||||
Assert.True(raw!.IsDeleted);
|
||||
Assert.NotNull(raw.DeletedAt);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void VorgangRepository_GetById_LiefertNullFuerUnbekannteId()
|
||||
{
|
||||
using var db = NewInMemoryContext();
|
||||
var repo = new VorgangRepository(db);
|
||||
|
||||
Assert.Null(repo.GetById(Guid.NewGuid()));
|
||||
}
|
||||
|
||||
// ── LessonRepository ──────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
@@ -1188,4 +1249,93 @@ public sealed class RepositoryTests
|
||||
Assert.Equal(studentId, item.StudentId);
|
||||
Assert.True(item.IsDone);
|
||||
}
|
||||
|
||||
// ── CompetencyCatalogVersionRepository ──────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void CompetencyCatalogVersionRepository_GetOrCreateDefault_LegtGenauEinmalAn()
|
||||
{
|
||||
using var db = NewInMemoryContext();
|
||||
var repo = new CompetencyCatalogVersionRepository(db);
|
||||
var subjectId = Guid.NewGuid();
|
||||
|
||||
var first = repo.GetOrCreateDefault(subjectId);
|
||||
var second = repo.GetOrCreateDefault(subjectId);
|
||||
|
||||
Assert.Equal(first.Id, second.Id);
|
||||
Assert.True(first.IsDefault);
|
||||
Assert.Single(repo.GetBySubject(subjectId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CompetencyCatalogVersionRepository_Save_NimmtVorherigeStandardversionZurueck()
|
||||
{
|
||||
using var db = NewInMemoryContext();
|
||||
var repo = new CompetencyCatalogVersionRepository(db);
|
||||
var subjectId = Guid.NewGuid();
|
||||
var alt = repo.GetOrCreateDefault(subjectId);
|
||||
var neu = new CompetencyCatalogVersion { SubjectId = subjectId, Name = "Bildungsplan 2026", IsDefault = true };
|
||||
|
||||
repo.Save(neu);
|
||||
|
||||
Assert.False(repo.GetById(alt.Id)!.IsDefault);
|
||||
Assert.True(repo.GetById(neu.Id)!.IsDefault);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CompetencyCatalogVersionRepository_Delete_BlockiertStandardversion()
|
||||
{
|
||||
using var db = NewInMemoryContext();
|
||||
var repo = new CompetencyCatalogVersionRepository(db);
|
||||
var version = repo.GetOrCreateDefault(Guid.NewGuid());
|
||||
|
||||
Assert.Throws<InvalidOperationException>(() => repo.Delete(version.Id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CompetencyCatalogVersionRepository_Delete_BlockiertBeiReferenzierendemKompetenzbereich()
|
||||
{
|
||||
using var db = NewInMemoryContext();
|
||||
var versionRepo = new CompetencyCatalogVersionRepository(db);
|
||||
var domainRepo = new CompetencyDomainRepository(db);
|
||||
var subjectId = Guid.NewGuid();
|
||||
var version = new CompetencyCatalogVersion { SubjectId = subjectId, Name = "Bildungsplan 2026" };
|
||||
versionRepo.Save(version);
|
||||
domainRepo.Save(new CompetencyDomain { SubjectId = subjectId, GradeLevel = 5, VersionId = version.Id, Name = "Bereich" });
|
||||
|
||||
Assert.Throws<InvalidOperationException>(() => versionRepo.Delete(version.Id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CompetencyCatalogVersionRepository_Delete_BlockiertBeiReferenzierenderGruppe()
|
||||
{
|
||||
using var db = NewInMemoryContext();
|
||||
var versionRepo = new CompetencyCatalogVersionRepository(db);
|
||||
var groupRepo = new GroupRepository(db);
|
||||
var subject = new Subject { Name = "Chemie" };
|
||||
new SubjectRepository(db).Save(subject);
|
||||
var version = new CompetencyCatalogVersion { SubjectId = subject.Id, Name = "Bildungsplan 2026" };
|
||||
versionRepo.Save(version);
|
||||
groupRepo.Save(new LearningGroup
|
||||
{
|
||||
Name = "9a", SchoolYear = "2025/26", SubjectId = subject.Id, CompetencyCatalogVersionId = version.Id,
|
||||
});
|
||||
|
||||
Assert.Throws<InvalidOperationException>(() => versionRepo.Delete(version.Id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CompetencyCatalogVersionRepository_Delete_ErlaubtUnbenutzteNichtStandardversion()
|
||||
{
|
||||
using var db = NewInMemoryContext();
|
||||
var repo = new CompetencyCatalogVersionRepository(db);
|
||||
var subjectId = Guid.NewGuid();
|
||||
repo.GetOrCreateDefault(subjectId);
|
||||
var extra = new CompetencyCatalogVersion { SubjectId = subjectId, Name = "Entwurf" };
|
||||
repo.Save(extra);
|
||||
|
||||
repo.Delete(extra.Id);
|
||||
|
||||
Assert.Null(repo.GetById(extra.Id));
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,7 @@ public class LiteDbContext : IDisposable
|
||||
/// Aktuelle Schema-Version. Migrationsschritte werden versioniert unter
|
||||
/// <see cref="RunVersionedMigrations"/> ergänzt, statt bei jedem Start erneut
|
||||
/// (idempotent, aber unnötig) über alle Daten zu laufen.
|
||||
private const int CurrentSchemaVersion = 4;
|
||||
private const int CurrentSchemaVersion = 6;
|
||||
|
||||
private readonly LiteDatabase _db;
|
||||
|
||||
@@ -51,6 +51,7 @@ public class LiteDbContext : IDisposable
|
||||
public ILiteCollection<Unit> Units => _db.GetCollection<Unit>("units");
|
||||
public ILiteCollection<Lesson> Lessons => _db.GetCollection<Lesson>("lessons");
|
||||
public ILiteCollection<Documentation> Documentation => _db.GetCollection<Documentation>("documentation");
|
||||
public ILiteCollection<Vorgang> Vorgaenge => _db.GetCollection<Vorgang>("vorgaenge");
|
||||
public ILiteStorage<string> Attachments => _db.GetStorage<string>("attachments", "attachments_chunks");
|
||||
public ILiteCollection<WorkTask> Tasks => _db.GetCollection<WorkTask>("tasks");
|
||||
public ILiteCollection<TimeEntry> TimeEntries => _db.GetCollection<TimeEntry>("time_entries");
|
||||
@@ -60,6 +61,7 @@ public class LiteDbContext : IDisposable
|
||||
public ILiteCollection<ParticipationSection> ParticipationSections => _db.GetCollection<ParticipationSection>("participation_sections");
|
||||
public ILiteCollection<Subject> Subjects => _db.GetCollection<Subject>("subjects");
|
||||
public ILiteCollection<CompetencyDomain> CompetencyDomains => _db.GetCollection<CompetencyDomain>("competency_domains");
|
||||
public ILiteCollection<CompetencyCatalogVersion> CompetencyCatalogVersions => _db.GetCollection<CompetencyCatalogVersion>("competency_catalog_versions");
|
||||
public ILiteCollection<ShorthandCode> ShorthandCodes => _db.GetCollection<ShorthandCode>("shorthand_codes");
|
||||
public ILiteCollection<AlternativeLessonPath> AlternativeLessonPaths => _db.GetCollection<AlternativeLessonPath>("alternative_lesson_paths");
|
||||
public ILiteCollection<TimetableSlot> TimetableSlots => _db.GetCollection<TimetableSlot>("timetable_slots");
|
||||
@@ -71,6 +73,7 @@ public class LiteDbContext : IDisposable
|
||||
public ILiteCollection<UntisAbsenceCacheEntry> UntisAbsenceCache => _db.GetCollection<UntisAbsenceCacheEntry>("untis_absence_cache");
|
||||
public ILiteCollection<UntisClassRegisterCacheEntry> UntisClassRegisterCache => _db.GetCollection<UntisClassRegisterCacheEntry>("untis_classregister_cache");
|
||||
public ILiteCollection<UntisCacheFetchState> UntisCacheFetchStates => _db.GetCollection<UntisCacheFetchState>("untis_cache_fetch_state");
|
||||
public ILiteCollection<UntisHubJobState> UntisHubJobStates => _db.GetCollection<UntisHubJobState>("untis_hub_job_states");
|
||||
public ILiteCollection<UntisStudentRosterCacheEntry> UntisStudentRosterCache => _db.GetCollection<UntisStudentRosterCacheEntry>("untis_student_roster_cache");
|
||||
public ILiteCollection<AnnualPlanEvent> AnnualPlanEvents => _db.GetCollection<AnnualPlanEvent>("annual_plan_events");
|
||||
public ILiteCollection<TrashedItem> TrashedItems => _db.GetCollection<TrashedItem>("trash");
|
||||
@@ -260,6 +263,16 @@ public class LiteDbContext : IDisposable
|
||||
MigrateLessonAlternativePaths();
|
||||
version = 4;
|
||||
}
|
||||
if (version < 5)
|
||||
{
|
||||
MigrateCompetencyCatalogVersions();
|
||||
version = 5;
|
||||
}
|
||||
if (version < 6)
|
||||
{
|
||||
MigrateCompetencyReferences();
|
||||
version = 6;
|
||||
}
|
||||
WriteSchemaVersion(version);
|
||||
}
|
||||
|
||||
@@ -483,6 +496,139 @@ public class LiteDbContext : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Backfill für <see cref="CompetencyDomain.VersionId"/>: bestehende Bereiche (vor
|
||||
/// Einführung der Bildungsplan-Versionierung, also ohne VersionId) bekommen je Fach genau eine
|
||||
/// neu angelegte Standardversion ("Bestehender Kompetenzkatalog"). LearningGroup.CompetencyCatalogVersionId
|
||||
/// bleibt bewusst null (= Standardversion) - siehe Doc-Kommentar auf dem Feld.</summary>
|
||||
private void MigrateCompetencyCatalogVersions()
|
||||
{
|
||||
var defaultVersionBySubject = new Dictionary<Guid, Guid>();
|
||||
foreach (var domain in CompetencyDomains.FindAll().ToList())
|
||||
{
|
||||
if (domain.VersionId != Guid.Empty) continue;
|
||||
if (!defaultVersionBySubject.TryGetValue(domain.SubjectId, out var versionId))
|
||||
{
|
||||
var version = new CompetencyCatalogVersion
|
||||
{
|
||||
SubjectId = domain.SubjectId, Name = "Bestehender Kompetenzkatalog", IsDefault = true,
|
||||
};
|
||||
CompetencyCatalogVersions.Upsert(version);
|
||||
versionId = version.Id;
|
||||
defaultVersionBySubject[domain.SubjectId] = versionId;
|
||||
}
|
||||
domain.VersionId = versionId;
|
||||
CompetencyDomains.Update(domain);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>TODO 16.5: stellt Unit/Lesson/ExamTask/ParticipationSession-Kompetenzzuordnungen von
|
||||
/// Freitext-Codes auf stabile CompetencyItem.Id-Referenzen um (siehe CompetencyReference).
|
||||
/// Jeder alte Code wird gegen den Katalog aufgelöst (erster Treffer über alle Fächer/Versionen
|
||||
/// hinweg, case-insensitiv) und als Momentaufnahme {ItemId, Code, Description} gespeichert;
|
||||
/// ohne Treffer bleibt der Text als ItemId=Guid.Empty erhalten statt verloren zu gehen. Bei
|
||||
/// ExamTask/ParticipationSession wird das Feld zugleich von "CompetencyCodes" auf "Competencies"
|
||||
/// umbenannt (das alte typisierte Feld existiert nicht mehr). ParticipationEntry.CompetencyRatings
|
||||
/// ohne auflösbaren Code werden verworfen - ein Zahlenwert ohne erkennbare Identität ist nicht
|
||||
/// sinnvoll erhaltbar.</summary>
|
||||
private void MigrateCompetencyReferences()
|
||||
{
|
||||
var byCode = new Dictionary<string, CompetencyItem>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var domain in CompetencyDomains.FindAll())
|
||||
foreach (var item in domain.Items)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(item.Code)) continue;
|
||||
byCode.TryAdd(item.Code.Trim(), item);
|
||||
}
|
||||
|
||||
BsonArray ConvertCodesToReferences(BsonValue oldValue)
|
||||
{
|
||||
var result = new BsonArray();
|
||||
if (!oldValue.IsArray) return result;
|
||||
foreach (var entry in oldValue.AsArray)
|
||||
{
|
||||
if (!entry.IsString) continue;
|
||||
var code = entry.AsString.Trim();
|
||||
if (code.Length == 0) continue;
|
||||
result.Add(byCode.TryGetValue(code, out var item)
|
||||
? new BsonDocument
|
||||
{
|
||||
[nameof(CompetencyReference.ItemId)] = item.Id,
|
||||
[nameof(CompetencyReference.Code)] = item.Code,
|
||||
[nameof(CompetencyReference.Description)] = item.Description,
|
||||
}
|
||||
: new BsonDocument
|
||||
{
|
||||
[nameof(CompetencyReference.ItemId)] = Guid.Empty,
|
||||
[nameof(CompetencyReference.Code)] = code,
|
||||
[nameof(CompetencyReference.Description)] = "",
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
var units = _db.GetCollection<BsonDocument>("units");
|
||||
foreach (var doc in units.FindAll().ToList())
|
||||
{
|
||||
if (!doc.TryGetValue(nameof(Unit.Competencies), out var old)) continue;
|
||||
doc[nameof(Unit.Competencies)] = ConvertCodesToReferences(old);
|
||||
units.Update(doc);
|
||||
}
|
||||
|
||||
var lessonDocs = _db.GetCollection<BsonDocument>("lessons");
|
||||
foreach (var doc in lessonDocs.FindAll().ToList())
|
||||
{
|
||||
if (!doc.TryGetValue(nameof(Lesson.Competencies), out var old)) continue;
|
||||
doc[nameof(Lesson.Competencies)] = ConvertCodesToReferences(old);
|
||||
lessonDocs.Update(doc);
|
||||
}
|
||||
|
||||
var exams = _db.GetCollection<BsonDocument>("exams");
|
||||
foreach (var doc in exams.FindAll().ToList())
|
||||
{
|
||||
if (!doc.TryGetValue(nameof(Exam.Tasks), out var tasksValue) || !tasksValue.IsArray) continue;
|
||||
var changed = false;
|
||||
foreach (var taskValue in tasksValue.AsArray)
|
||||
{
|
||||
if (taskValue is not BsonDocument task) continue;
|
||||
if (!task.TryGetValue("CompetencyCodes", out var old)) continue;
|
||||
task.Remove("CompetencyCodes");
|
||||
task[nameof(ExamTask.Competencies)] = ConvertCodesToReferences(old);
|
||||
changed = true;
|
||||
}
|
||||
if (changed) exams.Update(doc);
|
||||
}
|
||||
|
||||
var sessions = _db.GetCollection<BsonDocument>("participation_sessions");
|
||||
foreach (var doc in sessions.FindAll().ToList())
|
||||
{
|
||||
if (!doc.TryGetValue("CompetencyCodes", out var old)) continue;
|
||||
doc.Remove("CompetencyCodes");
|
||||
doc[nameof(ParticipationSession.Competencies)] = ConvertCodesToReferences(old);
|
||||
sessions.Update(doc);
|
||||
}
|
||||
|
||||
var entries = _db.GetCollection<BsonDocument>("participation");
|
||||
foreach (var doc in entries.FindAll().ToList())
|
||||
{
|
||||
if (!doc.TryGetValue(nameof(ParticipationEntry.CompetencyRatings), out var ratingsValue) || !ratingsValue.IsArray) continue;
|
||||
var newRatings = new BsonArray();
|
||||
foreach (var ratingValue in ratingsValue.AsArray)
|
||||
{
|
||||
if (ratingValue is not BsonDocument rating) continue;
|
||||
if (!rating.TryGetValue("Code", out var codeVal) || !codeVal.IsString) continue;
|
||||
if (!byCode.TryGetValue(codeVal.AsString.Trim(), out var item)) continue;
|
||||
var value = rating.TryGetValue(nameof(CompetencyRating.Value), out var v) && v.IsNumber ? v.AsInt32 : 0;
|
||||
newRatings.Add(new BsonDocument
|
||||
{
|
||||
[nameof(CompetencyRating.ItemId)] = item.Id,
|
||||
[nameof(CompetencyRating.Value)] = value,
|
||||
});
|
||||
}
|
||||
doc[nameof(ParticipationEntry.CompetencyRatings)] = newRatings;
|
||||
entries.Update(doc);
|
||||
}
|
||||
}
|
||||
|
||||
private void EnsureIndexes()
|
||||
{
|
||||
Students.EnsureIndex(x => x.LastName);
|
||||
@@ -528,6 +674,8 @@ public class LiteDbContext : IDisposable
|
||||
Subjects.EnsureIndex("ux_subject_name", BsonExpression.Create("LOWER(TRIM($.Name))"), unique: true);
|
||||
CompetencyDomains.EnsureIndex(x => x.SubjectId);
|
||||
CompetencyDomains.EnsureIndex(x => x.GradeLevel);
|
||||
CompetencyDomains.EnsureIndex(x => x.VersionId);
|
||||
CompetencyCatalogVersions.EnsureIndex(x => x.SubjectId);
|
||||
ShorthandCodes.EnsureIndex("ux_shorthand_code", BsonExpression.Create("LOWER(TRIM($.Code))"), unique: true);
|
||||
AlternativeLessonPaths.EnsureIndex("ux_alt_lesson_path_name", BsonExpression.Create("LOWER(TRIM($.Name))"), unique: true);
|
||||
TimetableSlots.EnsureIndex(x => x.GroupId);
|
||||
|
||||
@@ -357,6 +357,20 @@ public class UnitRepository(LiteDbContext db) : IUnitRepository
|
||||
public void Save(Unit u)
|
||||
{
|
||||
ArchivedGroupWriteGuard.EnsureActive(db, u.GroupId);
|
||||
// Persistenz-Invariante: auch Importe und künftig hinzukommende Aufrufer dürfen keine
|
||||
// zweite laufende Einheit in derselben Lerngruppe hinterlassen. Der Einheiten-Dialog
|
||||
// kündigt diese automatische Ablösung vorher sichtbar an.
|
||||
if (u.Status == UnitStatus.Active)
|
||||
{
|
||||
foreach (var previous in db.Units.Find(x => x.GroupId == u.GroupId &&
|
||||
x.Status == UnitStatus.Active && x.Id != u.Id))
|
||||
{
|
||||
previous.Status = UnitStatus.Completed;
|
||||
previous.UpdatedAt = DateTime.UtcNow;
|
||||
db.Units.Upsert(previous);
|
||||
db.OnChange?.Invoke(nameof(Unit), previous.Id.ToString(), "Save", previous);
|
||||
}
|
||||
}
|
||||
u.UpdatedAt = DateTime.UtcNow;
|
||||
db.Units.Upsert(u);
|
||||
db.OnChange?.Invoke(nameof(Unit), u.Id.ToString(), "Save", u);
|
||||
@@ -372,6 +386,7 @@ public class UnitRepository(LiteDbContext db) : IUnitRepository
|
||||
|
||||
public class LessonRepository(LiteDbContext db) : ILessonRepository
|
||||
{
|
||||
public Lesson? GetById(Guid id) => db.Lessons.FindById(id);
|
||||
public List<Lesson> GetByUnit(Guid id) =>
|
||||
db.Lessons.Find(l => l.UnitId == id).OrderBy(l => l.Date).ThenBy(l => l.LessonNumber).ToList();
|
||||
public List<Lesson> GetByGroupAndDate(Guid gid, DateOnly date) =>
|
||||
@@ -431,6 +446,37 @@ public class DocumentationRepository(LiteDbContext db) : IDocumentationRepositor
|
||||
}
|
||||
}
|
||||
|
||||
public class VorgangRepository(LiteDbContext db) : IVorgangRepository
|
||||
{
|
||||
public List<Vorgang> GetAll() =>
|
||||
db.Vorgaenge.Find(v => !v.IsDeleted).OrderByDescending(v => v.UpdatedAt).ToList();
|
||||
public List<Vorgang> GetByStudent(Guid studentId) =>
|
||||
GetAll().Where(v => v.StudentIds.Contains(studentId)).ToList();
|
||||
public Vorgang? GetById(Guid id)
|
||||
{
|
||||
var vorgang = db.Vorgaenge.FindById(id);
|
||||
return vorgang is null || vorgang.IsDeleted ? null : vorgang;
|
||||
}
|
||||
public void Save(Vorgang vorgang)
|
||||
{
|
||||
vorgang.UpdatedAt = DateTime.UtcNow;
|
||||
db.Vorgaenge.Upsert(vorgang);
|
||||
db.OnChange?.Invoke(nameof(Vorgang), vorgang.Id.ToString(), "Save", vorgang);
|
||||
}
|
||||
public void Delete(Guid id)
|
||||
{
|
||||
var vorgang = db.Vorgaenge.FindById(id);
|
||||
if (vorgang is null) return;
|
||||
vorgang.IsDeleted = true;
|
||||
vorgang.DeletedAt = DateTime.UtcNow;
|
||||
db.Vorgaenge.Update(vorgang);
|
||||
// Weiches Löschen ist inhaltlich eine Änderung, kein Entfernen -> "Save", damit ein
|
||||
// anwendendes Gerät den IsDeleted-Stand einfach übernimmt statt den Datensatz zu entfernen
|
||||
// (gleiches Muster wie DocumentationRepository.Delete).
|
||||
db.OnChange?.Invoke(nameof(Vorgang), id.ToString(), "Save", vorgang);
|
||||
}
|
||||
}
|
||||
|
||||
public class WorkTaskRepository(LiteDbContext db) : IWorkTaskRepository
|
||||
{
|
||||
public List<WorkTask> GetByStatus(WorkTaskStatus s) =>
|
||||
@@ -624,8 +670,9 @@ public class SubjectRepository(LiteDbContext db) : ISubjectRepository
|
||||
}
|
||||
public void Delete(Guid id)
|
||||
{
|
||||
if (db.Groups.Exists(g => g.SubjectId == id) || db.CompetencyDomains.Exists(d => d.SubjectId == id))
|
||||
throw new InvalidOperationException("Das Fach wird noch von einer Lerngruppe oder einem Kompetenzkatalog verwendet.");
|
||||
if (db.Groups.Exists(g => g.SubjectId == id) || db.CompetencyDomains.Exists(d => d.SubjectId == id)
|
||||
|| db.CompetencyCatalogVersions.Exists(v => v.SubjectId == id))
|
||||
throw new InvalidOperationException("Das Fach wird noch von einer Lerngruppe, einem Kompetenzkatalog oder einer Bildungsplan-Version verwendet.");
|
||||
db.Subjects.Delete(id);
|
||||
db.OnChange?.Invoke(nameof(Subject), id.ToString(), "Delete", null);
|
||||
}
|
||||
@@ -854,13 +901,33 @@ public class UntisCacheFetchStateRepository(LiteDbContext db) : IUntisCacheFetch
|
||||
public void Save(UntisCacheFetchState state) => db.UntisCacheFetchStates.Upsert(state);
|
||||
}
|
||||
|
||||
public class UntisHubJobStateRepository(LiteDbContext db) : IUntisHubJobStateRepository
|
||||
{
|
||||
public UntisHubJobState? Get(UntisHubJobKind kind, Guid? groupId) =>
|
||||
db.UntisHubJobStates.FindOne(s => s.Kind == kind && s.GroupId == groupId);
|
||||
|
||||
public List<UntisHubJobState> GetAll() => db.UntisHubJobStates.FindAll().ToList();
|
||||
|
||||
public void Save(UntisHubJobState state)
|
||||
{
|
||||
db.UntisHubJobStates.Upsert(state);
|
||||
db.OnChange?.Invoke(nameof(UntisHubJobState), state.Id.ToString(), "Save", state);
|
||||
}
|
||||
}
|
||||
|
||||
public class CompetencyDomainRepository(LiteDbContext db) : ICompetencyDomainRepository
|
||||
{
|
||||
public List<CompetencyDomain> GetBySubjectAndGrade(Guid subjectId, int gradeLevel) =>
|
||||
public List<CompetencyDomain> GetBySubjectAndGrade(Guid subjectId, int gradeLevel, Guid versionId) =>
|
||||
db.CompetencyDomains
|
||||
.Find(d => d.SubjectId == subjectId && d.GradeLevel == gradeLevel)
|
||||
.Find(d => d.SubjectId == subjectId && d.GradeLevel == gradeLevel && d.VersionId == versionId)
|
||||
.OrderBy(d => d.SortOrder)
|
||||
.ToList();
|
||||
public List<CompetencyDomain> GetBySubjectAndVersion(Guid subjectId, Guid versionId) =>
|
||||
db.CompetencyDomains
|
||||
.Find(d => d.SubjectId == subjectId && d.VersionId == versionId)
|
||||
.OrderBy(d => d.GradeLevel).ThenBy(d => d.SortOrder)
|
||||
.ToList();
|
||||
public List<CompetencyDomain> GetAll() => db.CompetencyDomains.FindAll().ToList();
|
||||
public CompetencyDomain? GetById(Guid id) => db.CompetencyDomains.FindById(id);
|
||||
public void Save(CompetencyDomain d)
|
||||
{
|
||||
@@ -873,22 +940,22 @@ public class CompetencyDomainRepository(LiteDbContext db) : ICompetencyDomainRep
|
||||
db.CompetencyDomains.Delete(id);
|
||||
db.OnChange?.Invoke(nameof(CompetencyDomain), id.ToString(), "Delete", null);
|
||||
}
|
||||
public void DeleteBySubjectAndGrade(Guid subjectId, int gradeLevel)
|
||||
public void DeleteBySubjectGradeAndVersion(Guid subjectId, int gradeLevel, Guid versionId)
|
||||
{
|
||||
foreach (var d in db.CompetencyDomains
|
||||
.Find(d => d.SubjectId == subjectId && d.GradeLevel == gradeLevel)
|
||||
.Find(d => d.SubjectId == subjectId && d.GradeLevel == gradeLevel && d.VersionId == versionId)
|
||||
.ToList())
|
||||
{
|
||||
db.CompetencyDomains.Delete(d.Id);
|
||||
db.OnChange?.Invoke(nameof(CompetencyDomain), d.Id.ToString(), "Delete", null);
|
||||
}
|
||||
}
|
||||
public void ReplaceForSubjectAndGrade(Guid subjectId, int gradeLevel, List<CompetencyDomain> domains)
|
||||
public void ReplaceForSubjectGradeAndVersion(Guid subjectId, int gradeLevel, Guid versionId, List<CompetencyDomain> domains)
|
||||
{
|
||||
db.ExecuteInTransaction(() =>
|
||||
{
|
||||
foreach (var domain in db.CompetencyDomains
|
||||
.Find(d => d.SubjectId == subjectId && d.GradeLevel == gradeLevel).ToList())
|
||||
.Find(d => d.SubjectId == subjectId && d.GradeLevel == gradeLevel && d.VersionId == versionId).ToList())
|
||||
{
|
||||
db.CompetencyDomains.Delete(domain.Id);
|
||||
db.OnChange?.Invoke(nameof(CompetencyDomain), domain.Id.ToString(), "Delete", null);
|
||||
@@ -898,6 +965,7 @@ public class CompetencyDomainRepository(LiteDbContext db) : ICompetencyDomainRep
|
||||
{
|
||||
domain.SubjectId = subjectId;
|
||||
domain.GradeLevel = gradeLevel;
|
||||
domain.VersionId = versionId;
|
||||
domain.UpdatedAt = now;
|
||||
db.CompetencyDomains.Upsert(domain);
|
||||
db.OnChange?.Invoke(nameof(CompetencyDomain), domain.Id.ToString(), "Save", domain);
|
||||
@@ -906,6 +974,57 @@ public class CompetencyDomainRepository(LiteDbContext db) : ICompetencyDomainRep
|
||||
}
|
||||
}
|
||||
|
||||
public class CompetencyCatalogVersionRepository(LiteDbContext db) : ICompetencyCatalogVersionRepository
|
||||
{
|
||||
public List<CompetencyCatalogVersion> GetBySubject(Guid subjectId) =>
|
||||
db.CompetencyCatalogVersions
|
||||
.Find(v => v.SubjectId == subjectId)
|
||||
.OrderBy(v => v.SortOrder)
|
||||
.ToList();
|
||||
public CompetencyCatalogVersion? GetById(Guid id) => db.CompetencyCatalogVersions.FindById(id);
|
||||
public CompetencyCatalogVersion GetOrCreateDefault(Guid subjectId)
|
||||
{
|
||||
var existing = GetBySubject(subjectId).FirstOrDefault(v => v.IsDefault);
|
||||
if (existing is not null) return existing;
|
||||
var version = new CompetencyCatalogVersion
|
||||
{
|
||||
SubjectId = subjectId, Name = "Bestehender Kompetenzkatalog", IsDefault = true,
|
||||
};
|
||||
Save(version);
|
||||
return version;
|
||||
}
|
||||
public void Save(CompetencyCatalogVersion v)
|
||||
{
|
||||
v.Name = v.Name.Trim();
|
||||
if (v.Name.Length == 0) throw new ArgumentException("Der Name der Version darf nicht leer sein.");
|
||||
if (v.IsDefault)
|
||||
{
|
||||
// Höchstens eine Standardversion je Fach - beim Setzen alle anderen des Fachs zurücknehmen.
|
||||
foreach (var other in db.CompetencyCatalogVersions.Find(o => o.SubjectId == v.SubjectId && o.Id != v.Id && o.IsDefault).ToList())
|
||||
{
|
||||
other.IsDefault = false;
|
||||
other.UpdatedAt = DateTime.UtcNow;
|
||||
db.CompetencyCatalogVersions.Upsert(other);
|
||||
db.OnChange?.Invoke(nameof(CompetencyCatalogVersion), other.Id.ToString(), "Save", other);
|
||||
}
|
||||
}
|
||||
v.UpdatedAt = DateTime.UtcNow;
|
||||
db.CompetencyCatalogVersions.Upsert(v);
|
||||
db.OnChange?.Invoke(nameof(CompetencyCatalogVersion), v.Id.ToString(), "Save", v);
|
||||
}
|
||||
public void Delete(Guid id)
|
||||
{
|
||||
var version = db.CompetencyCatalogVersions.FindById(id);
|
||||
if (version is null) return;
|
||||
if (version.IsDefault)
|
||||
throw new InvalidOperationException("Die Standardversion eines Fachs kann nicht gelöscht werden. Erst eine andere Version als Standard setzen.");
|
||||
if (db.CompetencyDomains.Exists(d => d.VersionId == id) || db.Groups.Exists(g => g.CompetencyCatalogVersionId == id))
|
||||
throw new InvalidOperationException("Die Version wird noch von einem Kompetenzkatalog oder einem Kurs verwendet.");
|
||||
db.CompetencyCatalogVersions.Delete(id);
|
||||
db.OnChange?.Invoke(nameof(CompetencyCatalogVersion), id.ToString(), "Delete", null);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Papierkorb (14.3) — bewusst nicht sync-fähig: TrashedItem wird nie über
|
||||
/// db.OnChange gemeldet, bleibt also rein lokal auf dem Gerät, auf dem gelöscht wurde. Ein
|
||||
/// "Fehlklick sofort rückgängig machen"-Werkzeug, kein geräteübergreifendes Archiv.</summary>
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
using LehrerApp.Core.AiPlanning;
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Desktop.Services;
|
||||
using LehrerApp.Desktop.ViewModels.Groups;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using Xunit;
|
||||
|
||||
namespace LehrerApp.Desktop.Tests;
|
||||
@@ -12,8 +15,200 @@ namespace LehrerApp.Desktop.Tests;
|
||||
public sealed class AiPlanningServiceTests
|
||||
{
|
||||
private static AiPlanningService Build(FakeLessons lessons, FakeGroups groups, FakeSubjects subjects,
|
||||
FakeCompetencyDomains competencyDomains, FakeAlternativeLessonPaths altPaths) =>
|
||||
new(new HttpClient(), lessons, groups, subjects, competencyDomains, altPaths);
|
||||
FakeCompetencyDomains competencyDomains, FakeAlternativeLessonPaths altPaths,
|
||||
FakeCompetencyCatalogVersions? competencyVersions = null) =>
|
||||
new(new HttpClient(), lessons, groups, subjects, competencyDomains,
|
||||
competencyVersions ?? new FakeCompetencyCatalogVersions(), altPaths);
|
||||
|
||||
[Fact]
|
||||
public void ParsePlanningLessons_AkzeptiertNormaleAntwortUndDeutschesDatum()
|
||||
{
|
||||
const string json = """
|
||||
{"lessons":[{"id":null,"date":"15.09.2026","lessonNumber":2,"topic":"Redox","startTime":"08:35","phases":[]}],"summary":"ok"}
|
||||
""";
|
||||
|
||||
var lesson = Assert.Single(AiPlanningService.ParsePlanningLessons(json));
|
||||
|
||||
Assert.Equal("Redox", lesson.Topic);
|
||||
Assert.Equal(new DateOnly(2026, 9, 15), lesson.Date);
|
||||
Assert.Equal(new TimeOnly(8, 35), lesson.StartTime);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParsePlanningLessons_AkzeptiertEinzelneMarkierteStunde()
|
||||
{
|
||||
const string json = """
|
||||
{"topic":"Nur diese Stunde","phases":[{"name":"Einstieg","durationMinutes":5,"activity":"Impuls","material":"Bild","shorthand":"UG"}]}
|
||||
""";
|
||||
|
||||
var lesson = Assert.Single(AiPlanningService.ParsePlanningLessons(json));
|
||||
|
||||
Assert.Equal("Nur diese Stunde", lesson.Topic);
|
||||
Assert.Single(lesson.Phases);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParsePlanningLessons_UngueltigeMarkierung_LiefertVerstaendlichenFehler()
|
||||
{
|
||||
var error = Assert.Throws<AiBackendException>(() =>
|
||||
AiPlanningService.ParsePlanningLessons("Hier kommt das JSON: { kaputt }"));
|
||||
|
||||
Assert.Contains("noch kein gültiges Stunden-JSON", error.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RequestPlanAsync_Backendfehler_BewahrtOriginalantwortFuerRettung()
|
||||
{
|
||||
const string body = """
|
||||
{"error":"Kein gültiges JSON.","rawResponse":"Vorspann\n{kaputt}"}
|
||||
""";
|
||||
var service = BuildWithResponse(HttpStatusCode.BadGateway, body);
|
||||
|
||||
var error = await Assert.ThrowsAsync<AiBackendException>(() =>
|
||||
service.RequestPlanAsync(new Unit(), "", "token"));
|
||||
|
||||
Assert.Equal("Vorspann\n{kaputt}", error.RawResponse);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RequestPlanAsync_Typfehler_BewahrtEingebetteteOriginalantwortFuerRettung()
|
||||
{
|
||||
const string body = """
|
||||
{"lessons":[{"topic":"Test","date":"kein Datum"}],"rawResponse":"DIE ORIGINALANTWORT"}
|
||||
""";
|
||||
var service = BuildWithResponse(HttpStatusCode.OK, body);
|
||||
|
||||
var error = await Assert.ThrowsAsync<AiBackendException>(() =>
|
||||
service.RequestPlanAsync(new Unit(), "", "token"));
|
||||
|
||||
Assert.Equal("DIE ORIGINALANTWORT", error.RawResponse);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RequestPlanAsync_Zeitueberschreitung_LiefertKonkreteProxyMeldung()
|
||||
{
|
||||
var http = new HttpClient(new CanceledResponseHandler())
|
||||
{
|
||||
BaseAddress = new Uri("https://example.invalid/"),
|
||||
};
|
||||
var service = new AiPlanningService(http, new FakeLessons(), new FakeGroups([]), new FakeSubjects([]),
|
||||
new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions(), new FakeAlternativeLessonPaths([]));
|
||||
|
||||
var error = await Assert.ThrowsAsync<AiBackendException>(() =>
|
||||
service.RequestPlanAsync(new Unit(), "", "token"));
|
||||
|
||||
Assert.Contains("3½ Minuten", error.Message);
|
||||
Assert.Contains("Webserver-Proxys", error.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Rettungsdialog_ImportiertMarkierteStundeAlsNeu()
|
||||
{
|
||||
var group = new LearningGroup();
|
||||
var unit = new Unit { GroupId = group.Id, Title = "T" };
|
||||
var lessons = new FakeLessons();
|
||||
var service = Build(lessons, new FakeGroups([group]), new FakeSubjects([]),
|
||||
new FakeCompetencyDomains(), new FakeAlternativeLessonPaths([]));
|
||||
var vm = new AiResponseRescueDialogViewModel(service, lessons, unit, "Rohantwort");
|
||||
|
||||
vm.ParseSelection("""{"topic":"Gerettete Stunde","phases":[]}""");
|
||||
vm.ImportAsNewCommand.Execute(null);
|
||||
|
||||
Assert.True(vm.Result);
|
||||
Assert.Equal("Gerettete Stunde", Assert.Single(lessons.GetByUnit(unit.Id)).Topic);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RequestUntisStatusSuggestionsAsync_PassendeIds_LiefertZuordnung()
|
||||
{
|
||||
const string body = """
|
||||
{"suggestions":[{"id":"0","status":"Excused"},{"id":"1","status":"Unexcused"}]}
|
||||
""";
|
||||
var service = BuildWithResponse(HttpStatusCode.OK, body);
|
||||
var rows = new[]
|
||||
{
|
||||
new AiUntisStatusRow { Id = "0", CurrentGuess = "ExcusePending" },
|
||||
new AiUntisStatusRow { Id = "1", CurrentGuess = "ExcusePending" },
|
||||
};
|
||||
|
||||
var suggestions = await service.RequestUntisStatusSuggestionsAsync(rows, "token");
|
||||
|
||||
Assert.Equal("Excused", suggestions["0"]);
|
||||
Assert.Equal("Unexcused", suggestions["1"]);
|
||||
}
|
||||
|
||||
// Kernabsicherung gegen Verwechslung (Nutzer-Feedback zum Untis-Hub, siehe
|
||||
// AiPlanningService.RequestUntisStatusSuggestionsAsync): weicht die zurückgegebene Id-Menge
|
||||
// auch nur minimal von der gesendeten ab (hier: eine erfundene Id "2" statt "1"), wird die
|
||||
// gesamte Antwort verworfen statt sich auf eine möglicherweise vermischte Zuordnung zu verlassen.
|
||||
[Fact]
|
||||
public async Task RequestUntisStatusSuggestionsAsync_AbweichendeIdMenge_VerwirftKomplett()
|
||||
{
|
||||
const string body = """
|
||||
{"suggestions":[{"id":"0","status":"Excused"},{"id":"2","status":"Unexcused"}]}
|
||||
""";
|
||||
var service = BuildWithResponse(HttpStatusCode.OK, body);
|
||||
var rows = new[]
|
||||
{
|
||||
new AiUntisStatusRow { Id = "0", CurrentGuess = "ExcusePending" },
|
||||
new AiUntisStatusRow { Id = "1", CurrentGuess = "ExcusePending" },
|
||||
};
|
||||
|
||||
var suggestions = await service.RequestUntisStatusSuggestionsAsync(rows, "token");
|
||||
|
||||
Assert.Empty(suggestions);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RequestUntisStatusSuggestionsAsync_DoppelteId_VerwirftKomplett()
|
||||
{
|
||||
const string body = """
|
||||
{"suggestions":[{"id":"0","status":"Excused"},{"id":"0","status":"Unexcused"}]}
|
||||
""";
|
||||
var service = BuildWithResponse(HttpStatusCode.OK, body);
|
||||
var rows = new[] { new AiUntisStatusRow { Id = "0", CurrentGuess = "ExcusePending" } };
|
||||
|
||||
var suggestions = await service.RequestUntisStatusSuggestionsAsync(rows, "token");
|
||||
|
||||
Assert.Empty(suggestions);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RequestUntisStatusSuggestionsAsync_KeineZeilen_KeinNetzwerkaufruf()
|
||||
{
|
||||
var service = Build(new FakeLessons(), new FakeGroups([]), new FakeSubjects([]),
|
||||
new FakeCompetencyDomains(), new FakeAlternativeLessonPaths([]));
|
||||
|
||||
var suggestions = await service.RequestUntisStatusSuggestionsAsync([], "token");
|
||||
|
||||
Assert.Empty(suggestions);
|
||||
}
|
||||
|
||||
private static AiPlanningService BuildWithResponse(HttpStatusCode status, string body)
|
||||
{
|
||||
var http = new HttpClient(new StaticResponseHandler(status, body))
|
||||
{
|
||||
BaseAddress = new Uri("https://example.invalid/"),
|
||||
};
|
||||
return new AiPlanningService(http, new FakeLessons(), new FakeGroups([]), new FakeSubjects([]),
|
||||
new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions(), new FakeAlternativeLessonPaths([]));
|
||||
}
|
||||
|
||||
private sealed class StaticResponseHandler(HttpStatusCode status, string body) : HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
|
||||
CancellationToken cancellationToken) => Task.FromResult(new HttpResponseMessage(status)
|
||||
{
|
||||
Content = new StringContent(body, Encoding.UTF8, "application/json"),
|
||||
});
|
||||
}
|
||||
|
||||
private sealed class CanceledResponseHandler : HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
|
||||
CancellationToken cancellationToken) => Task.FromCanceled<HttpResponseMessage>(
|
||||
new CancellationToken(canceled: true));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildContext_FuelltGruppenUndFachKontext()
|
||||
@@ -42,14 +237,16 @@ public sealed class AiPlanningServiceTests
|
||||
var unit = new Unit { GroupId = group.Id, Title = "T" };
|
||||
|
||||
var domains = new FakeCompetencyDomains();
|
||||
var versions = new FakeCompetencyCatalogVersions();
|
||||
var version = versions.GetOrCreateDefault(subject.Id);
|
||||
domains.Add(new CompetencyDomain
|
||||
{
|
||||
SubjectId = subject.Id, GradeLevel = 9, Name = "Chemische Reaktionen",
|
||||
SubjectId = subject.Id, GradeLevel = 9, VersionId = version.Id, Name = "Chemische Reaktionen",
|
||||
Items = [new CompetencyItem { Code = "C1", Description = "Redoxreaktionen erklären" }],
|
||||
});
|
||||
|
||||
var service = Build(new FakeLessons(), new FakeGroups([group]), new FakeSubjects([subject]),
|
||||
domains, new FakeAlternativeLessonPaths([]));
|
||||
domains, new FakeAlternativeLessonPaths([]), versions);
|
||||
|
||||
var context = service.BuildContext(unit, "");
|
||||
|
||||
|
||||
@@ -1,12 +1,333 @@
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Core.Services;
|
||||
using LehrerApp.Desktop.Services;
|
||||
using LehrerApp.Desktop.ViewModels.ClassTeacher;
|
||||
using LehrerApp.Templating;
|
||||
using Xunit;
|
||||
|
||||
namespace LehrerApp.Desktop.Tests;
|
||||
|
||||
public sealed class ClassTeacherViewModelsTests
|
||||
{
|
||||
[Fact]
|
||||
public void Monatskalender_KodiertFehlzeitenUndBlendetHausaufgabenStandardmaessigAus()
|
||||
{
|
||||
var month = new DateOnly(2026, 9, 1);
|
||||
var absences = new[]
|
||||
{
|
||||
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 9, 2), "Müller Ada", 1, 0, 12,
|
||||
["Deu"], [1], ["entsch."], ["Verspätung"], null, null, false),
|
||||
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 9, 3), "Schmidt Ben", 2, 2, 90,
|
||||
["Mathe"], [1, 2], ["nicht entsch."], ["Absent"], null, null, false),
|
||||
};
|
||||
var register = new[]
|
||||
{
|
||||
new ClassTeacherClassRegisterRow(new DateOnly(2026, 9, 3), "Deu", "Schmidt Ben", "test",
|
||||
"Störung", "Negativ", "Unterricht massiv gestört"),
|
||||
new ClassTeacherClassRegisterRow(new DateOnly(2026, 9, 4), "Mathe", "Müller Ada", "test",
|
||||
"Hausaufgaben", "Negativ", "Hausaufgaben fehlen"),
|
||||
};
|
||||
|
||||
var days = ClassTeacherDetailsViewModel.BuildCalendarDays(month, absences, register, includeHomework: false);
|
||||
|
||||
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 == "U");
|
||||
Assert.Contains(days.SelectMany(d => d.Events), e => e.Code == "!");
|
||||
Assert.DoesNotContain(days.SelectMany(d => d.Events), e => e.Code == "H");
|
||||
|
||||
var withHomework = ClassTeacherDetailsViewModel.BuildCalendarDays(month, absences, register, includeHomework: true);
|
||||
Assert.Contains(withHomework.SelectMany(d => d.Events), e => e.Code == "H");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Kompaktkalender_ZeigtNurMonatstageUndJeTagDasStaerksteSignal()
|
||||
{
|
||||
var month = new DateOnly(2026, 9, 1);
|
||||
var absences = new[]
|
||||
{
|
||||
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 9, 3), "Müller Ada", 1, 2, 90,
|
||||
["Deu"], [1, 2], ["nicht entsch."], ["Absent"], null, null, false),
|
||||
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 9, 4), "Schmidt Ben", 2, 2, 90,
|
||||
["Mathe"], [1, 2], ["entsch."], ["Absent"], null, null, false),
|
||||
};
|
||||
var register = new[]
|
||||
{
|
||||
new UntisForeignClassRegisterEventDto("6a", 20260903, "Deu", "Müller Ada", "test",
|
||||
"Störung", "Negativ", "Unterricht gestört"),
|
||||
new UntisForeignClassRegisterEventDto("6a", 20260905, "Mathe", "Schmidt Ben", "test",
|
||||
"Hausaufgaben", "Negativ", "Hausaufgaben fehlen"),
|
||||
};
|
||||
|
||||
var days = ClassTeacherOverviewViewModel.BuildCompactMonthDays(month, absences, register,
|
||||
new DateOnly(2026, 9, 3));
|
||||
|
||||
Assert.Equal(30, days.Count);
|
||||
Assert.False(days[0].HasSignal);
|
||||
Assert.Equal("1", days[0].DayNumber);
|
||||
Assert.Equal("U", days[2].SignalCode); // stärker als der parallele Klassenbucheintrag
|
||||
Assert.True(days[2].IsToday);
|
||||
Assert.Contains("Ada Müller", days[2].Tooltip);
|
||||
Assert.Equal("E", days[3].SignalCode);
|
||||
Assert.False(days[4].HasSignal); // Hausaufgaben bleiben im Widget bewusst ausgeblendet
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Kompaktkalender_KannAufEinzelnenSchuelerEingeschraenktWerden()
|
||||
{
|
||||
var month = new DateOnly(2026, 9, 1);
|
||||
var absences = new[]
|
||||
{
|
||||
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 9, 3), "Müller Ada", 1, 2, 90,
|
||||
["Deu"], [1, 2], ["nicht entsch."], ["Absent"], null, null, false),
|
||||
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 9, 4), "Schmidt Ben", 2, 2, 90,
|
||||
["Mathe"], [1, 2], ["entsch."], ["Absent"], null, null, false),
|
||||
};
|
||||
|
||||
var days = ClassTeacherOverviewViewModel.BuildCompactMonthDays(month, absences, [], month,
|
||||
"Ada Müller");
|
||||
|
||||
Assert.Equal("U", days[2].SignalCode);
|
||||
Assert.False(days[3].HasSignal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ElternbriefKalender_LiefertPortablenDrawingPlatzhalterFuerSchueler()
|
||||
{
|
||||
var month = new DateOnly(2026, 9, 1);
|
||||
var absences = new[]
|
||||
{
|
||||
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 9, 3), "Müller Ada", 1, 2, 90,
|
||||
["Deu"], [1, 2], ["nicht entsch."], ["Absent"], null, null, false),
|
||||
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 9, 4), "Schmidt Ben", 2, 2, 90,
|
||||
["Mathe"], [1, 2], ["entsch."], ["Absent"], null, null, false),
|
||||
};
|
||||
|
||||
var drawing = StudentAttendanceCalendarDrawingBuilder.Build("Ada Müller", month, absences, []);
|
||||
|
||||
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 == "U");
|
||||
Assert.DoesNotContain(drawing.Commands.OfType<DrawStringEx>(), c => c.Text == "E");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ElternbriefKalender_UnterstuetztEinBisDreiMonateUndGroessen()
|
||||
{
|
||||
var start = new DateOnly(2026, 9, 18);
|
||||
var small = StudentAttendanceCalendarDrawingBuilder.Build("Ada Müller",
|
||||
new AttendanceCalendarOptions(start, 3, AttendanceCalendarSize.Small), [], []);
|
||||
var large = StudentAttendanceCalendarDrawingBuilder.Build("Ada Müller",
|
||||
new AttendanceCalendarOptions(start, 3, AttendanceCalendarSize.Large), [], []);
|
||||
var labels = large.Commands.OfType<DrawStringEx>().Select(c => c.Text).ToList();
|
||||
|
||||
Assert.Contains("September 2026", labels);
|
||||
Assert.Contains("Oktober 2026", labels);
|
||||
Assert.Contains("November 2026", labels);
|
||||
Assert.True(large.ContentHeight > small.ContentHeight);
|
||||
}
|
||||
|
||||
// Regression: Breite und Höhe dürfen nur mit EINEM gemeinsamen Faktor skaliert werden (a =
|
||||
// min(a_x, a_y)), nicht unabhängig voneinander - sonst verzerren die Tageskacheln, wenn das
|
||||
// Seitenverhältnis der realen Box vom Referenzentwurf abweicht (z.B. eine sehr breite, aber
|
||||
// niedrige DRAWBOX). Das Breiten-/Höhenverhältnis einer Kachel muss unabhängig von contentWidth
|
||||
// gleich bleiben, solange die Höhe der begrenzende Faktor ist.
|
||||
[Fact]
|
||||
public void ElternbriefKalender_SkaliertKachelnGleichmaessigOhneVerzerrung()
|
||||
{
|
||||
var options = new AttendanceCalendarOptions(new DateOnly(2026, 9, 18), 3, AttendanceCalendarSize.Large);
|
||||
var schmaleBox = StudentAttendanceCalendarDrawingBuilder.Build("Ada Müller", options, [], [],
|
||||
contentWidth: 170, contentHeight: 60);
|
||||
var sehrBreiteBox = StudentAttendanceCalendarDrawingBuilder.Build("Ada Müller", options, [], [],
|
||||
contentWidth: 1000, contentHeight: 60);
|
||||
|
||||
var schmaleKachel = schmaleBox.Commands.OfType<DrawRoundedRectangle>().First();
|
||||
var breiteKachel = sehrBreiteBox.Commands.OfType<DrawRoundedRectangle>().First();
|
||||
var schmalesVerhaeltnis = schmaleKachel.Width / schmaleKachel.Height;
|
||||
var breitesVerhaeltnis = breiteKachel.Width / breiteKachel.Height;
|
||||
|
||||
Assert.Equal(schmalesVerhaeltnis, breitesVerhaeltnis, 0.001f);
|
||||
// Bei gleicher (begrenzender) Höhe muss die Kachelgröße selbst identisch sein - die
|
||||
// zusätzliche Breite der zweiten Box bleibt ungenutzt (kein Verzerren, kein Zwang zum
|
||||
// vollständigen Ausfüllen), statt die Kacheln künstlich in die Breite zu ziehen.
|
||||
Assert.Equal(schmaleKachel.Width, breiteKachel.Width, 0.01f);
|
||||
Assert.Equal(schmaleKachel.Height, breiteKachel.Height, 0.01f);
|
||||
}
|
||||
|
||||
// Regression: DRAWBOX bricht anders als FLOWDRAWBOX nicht automatisch um - Inhalt, der die von
|
||||
// der Vorlage deklarierte Höhe überschreitet, wird von QuestTemplateRenderer stillschweigend am
|
||||
// unteren Rand abgeschnitten (kein Fehler, keine Warnung). "Größe" muss deshalb automatisch so
|
||||
// weit verkleinert werden, dass alle gewählten Monate innerhalb von contentHeight Platz finden.
|
||||
[Fact]
|
||||
public void ElternbriefKalender_VerkleinertGroesseAutomatischUmDieVorlagenHoeheEinzuhalten()
|
||||
{
|
||||
var start = new DateOnly(2026, 9, 18);
|
||||
var uneingeschraenkt = StudentAttendanceCalendarDrawingBuilder.Build("Ada Müller",
|
||||
new AttendanceCalendarOptions(start, 3, AttendanceCalendarSize.Large), [], []);
|
||||
var engeBox = StudentAttendanceCalendarDrawingBuilder.Build("Ada Müller",
|
||||
new AttendanceCalendarOptions(start, 3, AttendanceCalendarSize.Large), [], [],
|
||||
contentHeight: 60);
|
||||
|
||||
Assert.True(uneingeschraenkt.ContentHeight > 60,
|
||||
"Testvoraussetzung: 3 Monate in 'Groß' brauchen ohne Deckelung mehr als 60 Einheiten Höhe.");
|
||||
Assert.True(engeBox.ContentHeight <= 60 + 0.01f);
|
||||
}
|
||||
|
||||
// Samstage/Sonntage ohne Eintrag sind normalerweise keine Schultage - "keine Fehlzeit" dort ist
|
||||
// keine Leistung und soll dezent ausgegraut statt gleichwertig mit echten Schultagen erscheinen.
|
||||
// Ein tatsächlicher Eintrag an einem Wochenendtag bleibt dagegen unverändert farbig.
|
||||
[Fact]
|
||||
public void ElternbriefKalender_GrautWochenendtageOhneEintragAus()
|
||||
{
|
||||
var month = new DateOnly(2026, 9, 1);
|
||||
var drawing = StudentAttendanceCalendarDrawingBuilder.Build("Ada Müller", month, [], []);
|
||||
|
||||
var dayCells = drawing.Commands
|
||||
.Zip(drawing.Commands.Skip(1), (first, second) => (first, second))
|
||||
.Where(pair => pair.first is DrawRoundedRectangle && pair.second is DrawStringEx text
|
||||
&& int.TryParse(text.Text, out _))
|
||||
.Select(pair => ((DrawRoundedRectangle)pair.first, int.Parse(((DrawStringEx)pair.second).Text)))
|
||||
.ToList();
|
||||
|
||||
Assert.NotEmpty(dayCells);
|
||||
foreach (var (rectangle, day) in dayCells)
|
||||
{
|
||||
var isWeekend = new DateOnly(2026, 9, day).DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday;
|
||||
Assert.Equal(isWeekend ? "#F3F4F6" : "#FFFFFF", rectangle.FillColor);
|
||||
}
|
||||
}
|
||||
|
||||
// Ein Eintrag (z.B. ein dokumentiertes Ereignis) an einem Wochenendtag trägt echte Information
|
||||
// und darf deshalb nicht vom "ausgrauen" betroffen sein.
|
||||
[Fact]
|
||||
public void ElternbriefKalender_GrautWochenendtagMitEintragNichtAus()
|
||||
{
|
||||
var month = new DateOnly(2026, 9, 1);
|
||||
var samstag = Enumerable.Range(1, 30)
|
||||
.Select(day => new DateOnly(2026, 9, day))
|
||||
.First(d => d.DayOfWeek == DayOfWeek.Saturday);
|
||||
var absences = new[]
|
||||
{
|
||||
new ClassAbsenceDaySummaryRow(samstag, "Ada Müller", 1, 6, 270,
|
||||
["Deu"], [1, 2, 3, 4, 5, 6], ["nicht entsch."], ["Absent"], null, null, true),
|
||||
};
|
||||
|
||||
var drawing = StudentAttendanceCalendarDrawingBuilder.Build("Ada Müller", month, absences, []);
|
||||
|
||||
var samstagsZelle = drawing.Commands
|
||||
.Zip(drawing.Commands.Skip(1), (first, second) => (first, second))
|
||||
.Where(pair => pair.first is DrawRoundedRectangle && pair.second is DrawStringEx text
|
||||
&& text.Text == "U")
|
||||
.Select(pair => (DrawRoundedRectangle)pair.first)
|
||||
.Single();
|
||||
Assert.NotEqual("#F3F4F6", samstagsZelle.FillColor);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ElternbriefFehltage_ListetDatumUmfangUndEntschuldigungsstatus()
|
||||
{
|
||||
var options = new AttendanceCalendarOptions(new DateOnly(2026, 9, 1), 1);
|
||||
var absences = new[]
|
||||
{
|
||||
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 9, 3), "Müller Ada", 1, 6, 270,
|
||||
["Deu"], [1, 2, 3, 4, 5, 6], ["entsch."], ["Krank"], null, null, true),
|
||||
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 9, 8), "Müller Ada", 1, 2, 90,
|
||||
["Mathe"], [1, 2], ["nicht entsch."], ["Absent"], null, null, false),
|
||||
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 9, 9), "Schmidt Ben", 2, 4, 180,
|
||||
["Eng"], [1, 2, 3, 4], ["entsch."], ["Krank"], null, null, true),
|
||||
};
|
||||
|
||||
var drawing = StudentAbsenceDayListDrawingBuilder.Build("Ada Müller", options, absences);
|
||||
var labels = drawing.Commands.OfType<DrawStringEx>().Select(c => c.Text).ToList();
|
||||
|
||||
Assert.Contains("03.09.2026", labels);
|
||||
Assert.Contains("Ganzer Fehltag", labels);
|
||||
Assert.Contains("08.09.2026", labels);
|
||||
Assert.Contains("Fehlzeit · 2 Std.", labels);
|
||||
Assert.Contains("Entschuldigt", labels);
|
||||
Assert.Contains("Unentschuldigt", labels);
|
||||
Assert.DoesNotContain("09.09.2026", labels);
|
||||
}
|
||||
|
||||
// Regression: Die Spaltenpositionen wurden versehentlich zusätzlich mit millimeterScale
|
||||
// multipliziert (analog zu echten mm-Maßen wie der Zeilenhöhe) - bei einer in "pt" statt "mm"
|
||||
// deklarierten Vorlage (millimeterScale ≈ 2.83) lag die Status-Spalte dadurch weit außerhalb der
|
||||
// tatsächlichen Box (x≈323 in einer nur 170 Einheiten breiten Box), statt nur ein Anteil von
|
||||
// contentWidth zu sein.
|
||||
[Fact]
|
||||
public void ElternbriefFehltage_SpaltenBleibenInnerhalbDerBoxbreiteAuchBeiPunktBasierterVorlage()
|
||||
{
|
||||
var options = new AttendanceCalendarOptions(new DateOnly(2026, 9, 1), 1);
|
||||
var absences = new[]
|
||||
{
|
||||
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 9, 3), "Ada Müller", 1, 6, 270,
|
||||
["Deu"], [1, 2, 3, 4, 5, 6], ["entsch."], ["Krank"], null, null, true),
|
||||
};
|
||||
const float contentWidth = 170f; const float millimeterScale = 2.8346f;
|
||||
|
||||
var drawing = StudentAbsenceDayListDrawingBuilder.Build("Ada Müller", options, absences,
|
||||
contentWidth, millimeterScale);
|
||||
var textBoxes = drawing.Commands.OfType<DrawStringEx>().ToList();
|
||||
var rectangles = drawing.Commands.OfType<DrawRectangle>().ToList();
|
||||
|
||||
Assert.NotEmpty(textBoxes);
|
||||
Assert.All(textBoxes, c => Assert.True(c.X + c.Width <= contentWidth + 0.01f,
|
||||
$"'{c.Text}' reicht bis x={c.X + c.Width}, Box ist aber nur {contentWidth} breit."));
|
||||
Assert.All(rectangles, c => Assert.True(c.X + c.Width <= contentWidth + 0.01f));
|
||||
}
|
||||
|
||||
private static ClassAbsenceDaySummaryRow[] BuildFehltage(int count) =>
|
||||
[.. Enumerable.Range(1, count).Select(day => new ClassAbsenceDaySummaryRow(
|
||||
new DateOnly(2026, 9, day), "Ada Müller", 1, 0, 0,
|
||||
["Deu"], [1], ["nicht entsch."], ["Absent"], null, null, true))];
|
||||
|
||||
// Regression: eine sehr lange einspaltige Fehlzeitenliste (FLOWDRAWBOX ohne automatischen
|
||||
// Seitenumbruch-Schutz) konnte in der echten Vorlage zu einer unerklärlichen Leerseite führen.
|
||||
// Ab ausreichend Zeilen UND ausreichend breiter Box wird deshalb zweispaltig (chronologisch:
|
||||
// erste Hälfte links, Rest rechts) gerendert - das halbiert die benötigte Höhe ungefähr.
|
||||
[Fact]
|
||||
public void ElternbriefFehltage_RendertZweispaltigWennBoxBreitGenugIst()
|
||||
{
|
||||
var options = new AttendanceCalendarOptions(new DateOnly(2026, 9, 1), 1);
|
||||
var absences = BuildFehltage(10);
|
||||
|
||||
var einspaltig = StudentAbsenceDayListDrawingBuilder.Build("Ada Müller", options, absences,
|
||||
contentWidth: 170);
|
||||
var zweispaltig = StudentAbsenceDayListDrawingBuilder.Build("Ada Müller", options, absences,
|
||||
contentWidth: 400);
|
||||
|
||||
// Zweispaltig braucht ungefähr die Hälfte der Höhe der einspaltigen Variante für dieselben
|
||||
// Daten (5 Zeilen je Spalte statt 10 Zeilen in einer Spalte, jeweils plus eine Kopfzeile).
|
||||
Assert.True(zweispaltig.ContentHeight < einspaltig.ContentHeight * .7f,
|
||||
$"Zweispaltig ({zweispaltig.ContentHeight}) sollte deutlich niedriger sein als einspaltig ({einspaltig.ContentHeight}).");
|
||||
var texte = zweispaltig.Commands.OfType<DrawStringEx>().Select(c => c.Text).ToList();
|
||||
Assert.Equal(2, texte.Count(t => t == "Datum")); // eine Kopfzeile je Spalte
|
||||
Assert.Contains("01.09.2026", texte);
|
||||
Assert.Contains("10.09.2026", texte);
|
||||
var rechteckeUndTexte = zweispaltig.Commands.Select(c => c switch
|
||||
{
|
||||
DrawRectangle r => (float?)(r.X + r.Width), DrawStringEx s => s.X + s.Width, _ => null,
|
||||
}).Where(x => x is not null);
|
||||
Assert.All(rechteckeUndTexte, x => Assert.True(x <= 400.01f));
|
||||
}
|
||||
|
||||
// Regression: bei einer zu schmalen Box (wie der echten Vorlage dieses Nutzers, deren
|
||||
// FLOWDRAWBOX für die Fehltagesliste aktuell nur 170 Einheiten breit ist) müssen zwei
|
||||
// nebeneinanderliegende Spalten zu schmal für Datum/Umfang/Status werden - deshalb bleibt es
|
||||
// dort bewusst einspaltig, auch bei vielen Zeilen.
|
||||
[Fact]
|
||||
public void ElternbriefFehltage_BleibtEinspaltigWennBoxZuSchmalFuerZweiSpaltenIst()
|
||||
{
|
||||
var options = new AttendanceCalendarOptions(new DateOnly(2026, 9, 1), 1);
|
||||
var absences = BuildFehltage(10);
|
||||
|
||||
var drawing = StudentAbsenceDayListDrawingBuilder.Build("Ada Müller", options, absences,
|
||||
contentWidth: 170);
|
||||
var texte = drawing.Commands.OfType<DrawStringEx>().Select(c => c.Text).ToList();
|
||||
|
||||
Assert.Equal(1, texte.Count(t => t == "Datum"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GroupByStudentAndDay_FasstFehlstundenProSchuelerUndTagZusammen()
|
||||
{
|
||||
@@ -228,6 +549,198 @@ public sealed class ClassTeacherViewModelsTests
|
||||
Assert.Null(row.YearSummaryTooltip);
|
||||
}
|
||||
|
||||
// ── Fehlquote behandelt Verspätung nicht mehr wie einen ganzen Fehltag (Nutzer-Feedback) ────
|
||||
|
||||
[Fact]
|
||||
public void RosterBuild_ReineVerspaetungZaehltNichtInDieFehlquote()
|
||||
{
|
||||
// Nutzer-Feedback: "10× 5 Min. verspätet" wurde bisher exakt wie "10× unentschuldigt
|
||||
// gefehlt" behandelt. Reine (nicht unentschuldigte) Verspätung darf die Quote nicht mehr
|
||||
// treiben, taucht aber weiterhin als eigene Zahl auf.
|
||||
var students = new[] { Student(1001, "Ada Müller") };
|
||||
var yearAbsences = Enumerable.Range(0, 3)
|
||||
.Select(i => new ClassAbsenceDaySummaryRow(new DateOnly(2026, 8, 10 + i), "Müller Ada", 1001, 0, 5,
|
||||
["Deu"], [1], ["entsch."], ["Verspätung"], null, null, false))
|
||||
.ToArray();
|
||||
|
||||
var row = Assert.Single(ClassTeacherRosterRow.Build(students, [], [],
|
||||
new DateOnly(2026, 8, 26), yearAbsences, schoolDaysElapsed: 20, termStart: new DateOnly(2026, 8, 1)));
|
||||
|
||||
Assert.Equal(0, row.YearAbsenceDayCount);
|
||||
Assert.Equal(3, row.YearLateDayCount);
|
||||
Assert.Equal(0, row.YearAbsenceRatePercent);
|
||||
Assert.True(row.HasYearSummary);
|
||||
Assert.Contains("verspätet", row.YearSummaryLabel);
|
||||
Assert.DoesNotContain("%", row.YearSummaryLabel);
|
||||
Assert.Contains("3 Tage verspätet", row.YearSummaryTooltip);
|
||||
Assert.Contains("zählt nicht zur Quote", row.YearSummaryTooltip);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RosterBuild_UnentschuldigtUndVerspaetetZaehltAlsUnentschuldigtNichtAlsVerspaetung()
|
||||
{
|
||||
// Wer unentschuldigt UND verspätet ist, bleibt der schwerwiegendere Fall (dieselbe
|
||||
// Rangfolge wie AttentionRank/StatusKind/BuildTrend: Unentschuldigt vor Verspätet) — zählt
|
||||
// deshalb weiter voll in die Quote statt in YearLateDayCount zu verschwinden.
|
||||
var students = new[] { Student(1001, "Ada Müller") };
|
||||
var yearAbsences = new[]
|
||||
{
|
||||
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 8, 10), "Müller Ada", 1001, 0, 60,
|
||||
["Deu"], [1], ["nicht entsch."], ["Verspätung"], null, null, false),
|
||||
};
|
||||
|
||||
var row = Assert.Single(ClassTeacherRosterRow.Build(students, [], [],
|
||||
new DateOnly(2026, 8, 26), yearAbsences, schoolDaysElapsed: 20, termStart: new DateOnly(2026, 8, 1)));
|
||||
|
||||
Assert.Equal(1, row.YearAbsenceDayCount);
|
||||
Assert.Equal(1, row.YearUnexcusedDayCount);
|
||||
Assert.Equal(0, row.YearLateDayCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PatternScore_GewichtetUnentschuldigtDeutlichStaerkerAlsVerspaetung()
|
||||
{
|
||||
// Kernfall aus dem Nutzer-Feedback: 10× 5 Minuten verspätet darf nicht denselben Score
|
||||
// ergeben wie 10× ganztägig unentschuldigt gefehlt.
|
||||
var lateStudent = Student(1001, "Verpennt Timo");
|
||||
var truantStudent = Student(1002, "Geschwaenzt Cem");
|
||||
var yearAbsences = Enumerable.Range(0, 10)
|
||||
.SelectMany(i => new[]
|
||||
{
|
||||
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 8, 3 + i), "Verpennt Timo", 1001, 0, 5,
|
||||
["Deu"], [1], ["entsch."], ["Verspätung"], null, null, false),
|
||||
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 8, 3 + i), "Geschwaenzt Cem", 1002, 6, 270,
|
||||
["Deu"], [1, 2, 3, 4, 5, 6], ["nicht entsch."], ["Absent"], null, null, true),
|
||||
})
|
||||
.ToArray();
|
||||
|
||||
var roster = ClassTeacherRosterRow.Build([lateStudent, truantStudent], [], [],
|
||||
new DateOnly(2026, 8, 26), yearAbsences, schoolDaysElapsed: 20, termStart: new DateOnly(2026, 8, 1));
|
||||
|
||||
var timo = Assert.Single(roster, r => r.StudentName == "Verpennt Timo");
|
||||
var cem = Assert.Single(roster, r => r.StudentName == "Geschwaenzt Cem");
|
||||
Assert.Equal(5.0, timo.PatternScore);
|
||||
Assert.Equal(30.0, cem.PatternScore);
|
||||
Assert.True(cem.PatternScore > timo.PatternScore * 5);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PatternScore_ErfasstMusterAuchWennHeuteAnwesend()
|
||||
{
|
||||
// Nutzer-Feedback: ein/e Schüler*in, die/der heute da ist, aber zuvor mehrfach unentschuldigt
|
||||
// fehlte, soll nicht spurlos aus der Musterauswertung verschwinden — anders als bei der
|
||||
// reinen "heute auffällig"-Sortierung (HasAbsenceToday).
|
||||
var student = Student(1001, "Ada Müller");
|
||||
var yearAbsences = Enumerable.Range(0, 5)
|
||||
.Select(i => new ClassAbsenceDaySummaryRow(new DateOnly(2026, 8, 10 + i), "Müller Ada", 1001, 6, 270,
|
||||
["Deu"], [1, 2, 3, 4, 5, 6], ["nicht entsch."], ["Absent"], null, null, true))
|
||||
.ToArray();
|
||||
|
||||
// Kein todayAbsences-Eintrag: heute anwesend.
|
||||
var row = Assert.Single(ClassTeacherRosterRow.Build([student], [], [],
|
||||
new DateOnly(2026, 8, 26), yearAbsences, schoolDaysElapsed: 20, termStart: new DateOnly(2026, 8, 1)));
|
||||
|
||||
Assert.False(row.HasAbsenceToday);
|
||||
Assert.True(row.PatternScore > 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PatternScore_IstNullOhneJahresdaten()
|
||||
{
|
||||
var students = new[] { Student(1001, "Ada Müller") };
|
||||
|
||||
var row = Assert.Single(ClassTeacherRosterRow.Build(students, [], [], new DateOnly(2026, 8, 26)));
|
||||
|
||||
Assert.Equal(0.0, row.PatternScore);
|
||||
}
|
||||
|
||||
// ── Klassenbucheinträge anderer Lehrkräfte fließen ebenfalls in den Score ein ────────────────
|
||||
|
||||
[Fact]
|
||||
public void PatternScore_NegativeKlassenbucheintraegeErhoehenDenScoreAuchOhneFehlzeiten()
|
||||
{
|
||||
var student = Student(1001, "Ada Müller");
|
||||
var yearRegister = Enumerable.Range(0, 4)
|
||||
.Select(i => new UntisForeignClassRegisterEventDto("6a", 20260810 + i, "Deu", "Müller Ada", "test",
|
||||
"Unterrichtsstörung", "Negativ", "Gestört"))
|
||||
.ToArray();
|
||||
|
||||
var row = Assert.Single(ClassTeacherRosterRow.Build([student], [], [],
|
||||
new DateOnly(2026, 8, 26), schoolDaysElapsed: 20, termStart: new DateOnly(2026, 8, 1),
|
||||
yearClassRegisterEntries: yearRegister));
|
||||
|
||||
Assert.Equal(4, row.YearNegativeClassRegisterCount);
|
||||
Assert.Equal(4.0, row.PatternScore);
|
||||
Assert.True(row.HasYearSummary);
|
||||
Assert.Contains("negative Klassenbucheinträge", row.YearSummaryLabel);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PatternScore_HausaufgabenUndMitarbeitSchluesselwoerterZaehlenStaerkerAlsPlainNegativ()
|
||||
{
|
||||
var withKeyword = Student(1001, "Keyword Kim");
|
||||
var plain = Student(1002, "Plain Priya");
|
||||
var yearRegister = new[]
|
||||
{
|
||||
new UntisForeignClassRegisterEventDto("6a", 20260810, "Deu", "Keyword Kim", "test",
|
||||
"Hausaufgaben fehlen", "Negativ", "HA nicht dabei"),
|
||||
new UntisForeignClassRegisterEventDto("6a", 20260810, "Deu", "Plain Priya", "test",
|
||||
"Sonstiges", "Negativ", "Gestört"),
|
||||
};
|
||||
|
||||
var roster = ClassTeacherRosterRow.Build([withKeyword, plain], [], [],
|
||||
new DateOnly(2026, 8, 26), schoolDaysElapsed: 20, termStart: new DateOnly(2026, 8, 1),
|
||||
yearClassRegisterEntries: yearRegister);
|
||||
|
||||
var kim = Assert.Single(roster, r => r.StudentName == "Keyword Kim");
|
||||
var priya = Assert.Single(roster, r => r.StudentName == "Plain Priya");
|
||||
Assert.True(kim.PatternScore > priya.PatternScore);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PatternScore_SuspendiertSchiesstDenScoreWeitUeberVieleAndereEintraegeHinaus()
|
||||
{
|
||||
var suspended = Student(1001, "Suspendiert Sam");
|
||||
var chronic = Student(1002, "Viele Vera");
|
||||
var yearRegister = new List<UntisForeignClassRegisterEventDto>
|
||||
{
|
||||
new("6a", 20260810, "Deu", "Suspendiert Sam", "test", "Ordnungsmaßnahme", "Negativ",
|
||||
"Vom Unterricht suspendiert"),
|
||||
};
|
||||
yearRegister.AddRange(Enumerable.Range(0, 6)
|
||||
.Select(i => new UntisForeignClassRegisterEventDto("6a", 20260810 + i, "Deu", "Viele Vera", "test",
|
||||
"Sonstiges", "Negativ", "Gestört")));
|
||||
|
||||
var roster = ClassTeacherRosterRow.Build([suspended, chronic], [], [],
|
||||
new DateOnly(2026, 8, 26), schoolDaysElapsed: 20, termStart: new DateOnly(2026, 8, 1),
|
||||
yearClassRegisterEntries: yearRegister);
|
||||
|
||||
var sam = Assert.Single(roster, r => r.StudentName == "Suspendiert Sam");
|
||||
var vera = Assert.Single(roster, r => r.StudentName == "Viele Vera");
|
||||
Assert.True(sam.HasSuspensionEntry);
|
||||
Assert.True(sam.PatternScore > vera.PatternScore);
|
||||
Assert.Contains("Suspendierung vermerkt", sam.YearSummaryTooltip);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PatternScore_OhneEigeneJahresklassenbuchlisteFaelltAufDenUebergebenenParameterZurueck()
|
||||
{
|
||||
// Rückwärtskompatibilität: Aufrufer, die (wie die bestehenden Tests) nur den ursprünglichen
|
||||
// recentClassRegisterEntries-Parameter befüllen, sollen trotzdem einen Score aus diesen
|
||||
// Einträgen bekommen statt stillschweigend leer auszugehen.
|
||||
var student = Student(1001, "Ada Müller");
|
||||
var entries = new[]
|
||||
{
|
||||
new UntisForeignClassRegisterEventDto("6a", 20260810, "Deu", "Müller Ada", "test",
|
||||
"Sonstiges", "Negativ", "Gestört"),
|
||||
};
|
||||
|
||||
var row = Assert.Single(ClassTeacherRosterRow.Build([student], [], entries,
|
||||
new DateOnly(2026, 8, 26)));
|
||||
|
||||
Assert.True(row.PatternScore > 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RosterBuild_OrdnetJahresfehlzeitenAuchOhneExternKeyUeberNamenZu()
|
||||
{
|
||||
@@ -584,4 +1097,325 @@ public sealed class ClassTeacherViewModelsTests
|
||||
|
||||
private static UntisStudentRosterCacheEntry Student(int? externKey, string displayName) =>
|
||||
new() { ClassName = "6a", ExternKey = externKey, DisplayName = displayName };
|
||||
|
||||
// ── Klassenbuch-Tab als Dokumentations-Hub: eigene Dokumentation neben WebUntis ─────────────
|
||||
|
||||
[Fact]
|
||||
public void FilterOwnDocumentation_ZeigtNurEintraegeZugeordneterSchuelerImZeitraum()
|
||||
{
|
||||
var ada = Guid.NewGuid();
|
||||
var fremd = Guid.NewGuid();
|
||||
var rosterMatches = new List<(Guid StudentId, string DisplayName)> { (ada, "Ada Müller") };
|
||||
var docs = new List<Documentation>
|
||||
{
|
||||
new() { StudentId = ada, Date = new DateOnly(2026, 8, 20), Title = "Im Zeitraum" },
|
||||
new() { StudentId = ada, Date = new DateOnly(2026, 7, 1), Title = "Vor dem Zeitraum" },
|
||||
new() { StudentId = fremd, Date = new DateOnly(2026, 8, 20), Title = "Anderer Schüler" },
|
||||
new() { StudentId = ada, Date = new DateOnly(2026, 8, 21), Title = "Gelöscht", IsDeleted = true },
|
||||
};
|
||||
|
||||
var result = ClassTeacherDetailsViewModel.FilterOwnDocumentation(docs, rosterMatches,
|
||||
new DateOnly(2026, 8, 1), new DateOnly(2026, 8, 31), "");
|
||||
|
||||
Assert.Equal(["Im Zeitraum"], result.Select(d => d.Title));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FilterOwnDocumentation_SortiertEntwuerfeVorNeuestenZuerst()
|
||||
{
|
||||
var id = Guid.NewGuid();
|
||||
var rosterMatches = new List<(Guid StudentId, string DisplayName)> { (id, "Ada Müller") };
|
||||
var docs = new List<Documentation>
|
||||
{
|
||||
new() { StudentId = id, Date = new DateOnly(2026, 8, 25), Title = "Neu, fertig" },
|
||||
new() { StudentId = id, Date = new DateOnly(2026, 8, 10), Title = "Alt, Entwurf", IsDraft = true },
|
||||
new() { StudentId = id, Date = new DateOnly(2026, 8, 20), Title = "Mittel, fertig" },
|
||||
};
|
||||
|
||||
var result = ClassTeacherDetailsViewModel.FilterOwnDocumentation(docs, rosterMatches,
|
||||
new DateOnly(2026, 8, 1), new DateOnly(2026, 8, 31), "");
|
||||
|
||||
Assert.Equal(["Alt, Entwurf", "Neu, fertig", "Mittel, fertig"], result.Select(d => d.Title));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FilterOwnDocumentation_SchuelerfilterErkenntVertauschteReihenfolge()
|
||||
{
|
||||
// Derselbe Namensabgleich wie bei den WebUntis-Klassenbuchzeilen (siehe
|
||||
// RosterBuild_ErkenntNamenAuchInVertauschterReihenfolge) - der Filter kommt aus der
|
||||
// Übersicht als "Nachname Vorname" oder "Vorname Nachname" je nach Bericht.
|
||||
var ada = Guid.NewGuid();
|
||||
var ben = Guid.NewGuid();
|
||||
var rosterMatches = new List<(Guid StudentId, string DisplayName)>
|
||||
{
|
||||
(ada, "Ada Müller"), (ben, "Ben Schmidt"),
|
||||
};
|
||||
var docs = new List<Documentation>
|
||||
{
|
||||
new() { StudentId = ada, Date = new DateOnly(2026, 8, 20), Title = "Ada" },
|
||||
new() { StudentId = ben, Date = new DateOnly(2026, 8, 20), Title = "Ben" },
|
||||
};
|
||||
|
||||
var result = ClassTeacherDetailsViewModel.FilterOwnDocumentation(docs, rosterMatches,
|
||||
new DateOnly(2026, 8, 1), new DateOnly(2026, 8, 31), "Müller Ada");
|
||||
|
||||
Assert.Equal(["Ada"], result.Select(d => d.Title));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FilterOwnDocumentation_ZeigtVerwaistenKlassenEintragUndFindetTeilnehmerPerVorname()
|
||||
{
|
||||
var rosterMatches = new List<(Guid StudentId, string DisplayName)>
|
||||
{
|
||||
(Guid.NewGuid(), "Karim Alshurbaji"), (Guid.NewGuid(), "Saleh Al-Anezi"),
|
||||
};
|
||||
var orphan = new Documentation
|
||||
{
|
||||
StudentId = Guid.Empty, GroupId = null, Date = new DateOnly(2026, 9, 7),
|
||||
Title = "Vorfall", Participants = ["Karim", "Saleh"],
|
||||
};
|
||||
|
||||
var result = ClassTeacherDetailsViewModel.FilterOwnDocumentation([orphan], rosterMatches,
|
||||
new DateOnly(2026, 9, 1), new DateOnly(2026, 9, 30), "Karim");
|
||||
|
||||
Assert.Same(orphan, Assert.Single(result));
|
||||
}
|
||||
|
||||
// ── Vorgang: Fallmappe für Klassenbuch- und Dokumentationseinträge ───────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void BuildClassRegisterSnapshot_KopiertAlleFelderDerZeile()
|
||||
{
|
||||
var row = new ClassTeacherClassRegisterRow(new DateOnly(2026, 8, 20), "Deu", "Schmidt Ben",
|
||||
"mueller", "Fehlende HA", "Negativ", "Buch vergessen");
|
||||
|
||||
var snapshot = ClassTeacherDetailsViewModel.BuildClassRegisterSnapshot(row);
|
||||
|
||||
Assert.Equal(new DateOnly(2026, 8, 20), snapshot.Date);
|
||||
Assert.Equal("Schmidt Ben", snapshot.StudentName);
|
||||
Assert.Equal("Deu", snapshot.Subject);
|
||||
Assert.Equal("mueller", snapshot.TeacherUsername);
|
||||
Assert.Equal("Fehlende HA", snapshot.CategoryName);
|
||||
Assert.Equal("Negativ", snapshot.CategoryGroup);
|
||||
Assert.Equal("Buch vergessen", snapshot.Text);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FilterAvailableDocumentation_ZeigtNurUnverknuepfteDokumentationDerVorgangsSchueler()
|
||||
{
|
||||
var ada = Guid.NewGuid();
|
||||
var ben = Guid.NewGuid();
|
||||
var fremd = Guid.NewGuid();
|
||||
var linked = new Documentation { StudentId = ada, Title = "Schon verknüpft" };
|
||||
var unlinked = new Documentation { StudentId = ada, Title = "Noch offen" };
|
||||
var otherStudentInCase = new Documentation { StudentId = ben, Title = "Ben, offen" };
|
||||
var unrelated = new Documentation { StudentId = fremd, Title = "Anderer Schüler" };
|
||||
var vorgang = new Vorgang { StudentIds = [ada, ben], DocumentationIds = [linked.Id] };
|
||||
var allDocs = new List<Documentation> { linked, unlinked, otherStudentInCase, unrelated };
|
||||
|
||||
var result = ClassTeacherCasesViewModel.FilterAvailableDocumentation(allDocs, vorgang);
|
||||
|
||||
Assert.Equal(["Noch offen", "Ben, offen"], result.Select(d => d.Title));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FilterAvailableDocumentation_LeerOhneUnverknuepfteEintraege()
|
||||
{
|
||||
var ada = Guid.NewGuid();
|
||||
var doc = new Documentation { StudentId = ada, Title = "Verknüpft" };
|
||||
var vorgang = new Vorgang { StudentIds = [ada], DocumentationIds = [doc.Id] };
|
||||
|
||||
var result = ClassTeacherCasesViewModel.FilterAvailableDocumentation([doc], vorgang);
|
||||
|
||||
Assert.Empty(result);
|
||||
}
|
||||
|
||||
// ── Konfigurierbare Gewichtung + Dämpfung/Rückfall-Warnung nach geschlossenem Vorgang ─────────
|
||||
|
||||
[Fact]
|
||||
public void MatchDomains_ErkenntBereicheAnSchluesselwoertern()
|
||||
{
|
||||
Assert.Equal([VorgangScoreDomain.Attendance], ClassTeacherRosterRow.MatchDomains(["Absentismus"]));
|
||||
Assert.Equal([VorgangScoreDomain.Lateness], ClassTeacherRosterRow.MatchDomains(["Verspätungen"]));
|
||||
Assert.Equal([VorgangScoreDomain.Classbook], ClassTeacherRosterRow.MatchDomains(["Konflikte"]));
|
||||
Assert.Equal([VorgangScoreDomain.Classbook], ClassTeacherRosterRow.MatchDomains(["Mitarbeit"]));
|
||||
Assert.Equal([VorgangScoreDomain.Classbook], ClassTeacherRosterRow.MatchDomains(["Hausaufgaben"]));
|
||||
Assert.Equal([VorgangScoreDomain.Classbook], ClassTeacherRosterRow.MatchDomains(["Eskalation"]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MatchDomains_OhneErkanntesSchlagwortDaemptAlleBereiche()
|
||||
{
|
||||
// Nutzer-Entscheidung: ein Vorgang darf beim Schließen nie folgenlos bleiben, auch wenn sein
|
||||
// Schlagwort (z.B. "Elternkontakt") keinem bekannten Score-Bereich zugeordnet werden kann.
|
||||
var domains = ClassTeacherRosterRow.MatchDomains(["Elternkontakt"]);
|
||||
|
||||
Assert.Equal(3, domains.Count);
|
||||
Assert.Contains(VorgangScoreDomain.Attendance, domains);
|
||||
Assert.Contains(VorgangScoreDomain.Lateness, domains);
|
||||
Assert.Contains(VorgangScoreDomain.Classbook, domains);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ComputeDampeningCutoffs_NimmtJeBereichDasJuengsteSchliessDatum()
|
||||
{
|
||||
var closed = new List<Vorgang>
|
||||
{
|
||||
new() { Tags = ["Absentismus"], Status = VorgangStatus.Closed, ClosedAt = new DateTime(2026, 8, 10) },
|
||||
new() { Tags = ["Absentismus"], Status = VorgangStatus.Closed, ClosedAt = new DateTime(2026, 8, 20) },
|
||||
new() { Tags = ["Verspätungen"], Status = VorgangStatus.Closed, ClosedAt = new DateTime(2026, 8, 5) },
|
||||
};
|
||||
|
||||
var cutoffs = ClassTeacherRosterRow.ComputeDampeningCutoffs(closed);
|
||||
|
||||
Assert.Equal(new DateOnly(2026, 8, 20), cutoffs[VorgangScoreDomain.Attendance]);
|
||||
Assert.Equal(new DateOnly(2026, 8, 5), cutoffs[VorgangScoreDomain.Lateness]);
|
||||
Assert.False(cutoffs.ContainsKey(VorgangScoreDomain.Classbook));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ComputeDampeningCutoffs_IgnoriertVorgaengeOhneSchliessDatum()
|
||||
{
|
||||
var closed = new List<Vorgang> { new() { Tags = ["Absentismus"], Status = VorgangStatus.Open } };
|
||||
|
||||
var cutoffs = ClassTeacherRosterRow.ComputeDampeningCutoffs(closed);
|
||||
|
||||
Assert.Empty(cutoffs);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PatternScore_BenutztUebergebeneGewichteStattFesterKonstanten()
|
||||
{
|
||||
var student = Student(1001, "Ada Müller");
|
||||
var yearAbsences = new[]
|
||||
{
|
||||
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 8, 10), "Müller Ada", 1001, 6, 270,
|
||||
["Deu"], [1, 2, 3, 4, 5, 6], ["nicht entsch."], ["Absent"], null, null, true),
|
||||
};
|
||||
var customWeights = new PatternScoreWeights { UnexcusedDayWeight = 10.0 };
|
||||
|
||||
var row = Assert.Single(ClassTeacherRosterRow.Build([student], [], [],
|
||||
new DateOnly(2026, 8, 26), yearAbsences, schoolDaysElapsed: 20, termStart: new DateOnly(2026, 8, 1),
|
||||
weights: customWeights));
|
||||
|
||||
Assert.Equal(10.0, row.PatternScore);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PatternScore_DaempftNurDenZumVorgangPassendenBereichNachAbschluss()
|
||||
{
|
||||
var student = Student(1001, "Ada Müller");
|
||||
var yearAbsences = new[]
|
||||
{
|
||||
// Vor dem Abschluss: darf für den Score nicht mehr zählen.
|
||||
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 8, 5), "Müller Ada", 1001, 6, 270,
|
||||
["Deu"], [1, 2, 3, 4, 5, 6], ["nicht entsch."], ["Absent"], null, null, true),
|
||||
// Nach dem Abschluss: zählt weiter.
|
||||
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 8, 20), "Müller Ada", 1001, 6, 270,
|
||||
["Deu"], [1, 2, 3, 4, 5, 6], ["nicht entsch."], ["Absent"], null, null, true),
|
||||
// Verspätung, anderer Bereich: bleibt von der auf "Absentismus" beschränkten Dämpfung unberührt.
|
||||
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 8, 1), "Müller Ada", 1001, 0, 5,
|
||||
["Deu"], [1], ["entsch."], ["Verspätung"], null, null, false),
|
||||
};
|
||||
var closedVorgaengeByNameKey = new Dictionary<string, IReadOnlyList<Vorgang>>
|
||||
{
|
||||
[UntisNameMatching.NameKey("Ada Müller")] = [new Vorgang
|
||||
{
|
||||
Title = "Schuleschwänzen", Tags = ["Absentismus"], Status = VorgangStatus.Closed,
|
||||
ClosedAt = new DateTime(2026, 8, 12),
|
||||
}],
|
||||
};
|
||||
|
||||
var row = Assert.Single(ClassTeacherRosterRow.Build([student], [], [],
|
||||
new DateOnly(2026, 8, 26), yearAbsences, schoolDaysElapsed: 20, termStart: new DateOnly(2026, 8, 1),
|
||||
closedVorgaengeByNameKey: closedVorgaengeByNameKey));
|
||||
|
||||
// 1 unentschuldigter Tag nach Abschluss (3,0) + 1 unbeeinflusster Verspätungstag (0,5) = 3,5.
|
||||
Assert.Equal(3.5, row.PatternScore);
|
||||
// Die Quote bleibt von der Dämpfung unberührt: beide unentschuldigten Tage zählen weiter.
|
||||
Assert.Equal(2, row.YearUnexcusedDayCount);
|
||||
Assert.Equal(2, row.YearAbsenceDayCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PatternScore_VorgangOhneErkennbaresSchlagwortDaemptAlleBereiche()
|
||||
{
|
||||
var student = Student(1001, "Ada Müller");
|
||||
var yearAbsences = new[]
|
||||
{
|
||||
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 8, 5), "Müller Ada", 1001, 0, 5,
|
||||
["Deu"], [1], ["entsch."], ["Verspätung"], null, null, false),
|
||||
};
|
||||
var closedVorgaengeByNameKey = new Dictionary<string, IReadOnlyList<Vorgang>>
|
||||
{
|
||||
[UntisNameMatching.NameKey("Ada Müller")] = [new Vorgang
|
||||
{
|
||||
Title = "Elterngespräch", Tags = ["Elternkontakt"], Status = VorgangStatus.Closed,
|
||||
ClosedAt = new DateTime(2026, 8, 12),
|
||||
}],
|
||||
};
|
||||
|
||||
var row = Assert.Single(ClassTeacherRosterRow.Build([student], [], [],
|
||||
new DateOnly(2026, 8, 26), yearAbsences, schoolDaysElapsed: 20, termStart: new DateOnly(2026, 8, 1),
|
||||
closedVorgaengeByNameKey: closedVorgaengeByNameKey));
|
||||
|
||||
Assert.Equal(0.0, row.PatternScore);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RegressionScore_IstNullOhneNeueEreignisseNachAbschluss()
|
||||
{
|
||||
var student = Student(1001, "Ada Müller");
|
||||
var yearAbsences = new[]
|
||||
{
|
||||
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 8, 5), "Müller Ada", 1001, 6, 270,
|
||||
["Deu"], [1, 2, 3, 4, 5, 6], ["nicht entsch."], ["Absent"], null, null, true),
|
||||
};
|
||||
var closedVorgaengeByNameKey = new Dictionary<string, IReadOnlyList<Vorgang>>
|
||||
{
|
||||
[UntisNameMatching.NameKey("Ada Müller")] = [new Vorgang
|
||||
{
|
||||
Title = "Schuleschwänzen", Tags = ["Absentismus"], Status = VorgangStatus.Closed,
|
||||
ClosedAt = new DateTime(2026, 8, 12),
|
||||
}],
|
||||
};
|
||||
|
||||
var row = Assert.Single(ClassTeacherRosterRow.Build([student], [], [],
|
||||
new DateOnly(2026, 8, 26), yearAbsences, schoolDaysElapsed: 20, termStart: new DateOnly(2026, 8, 1),
|
||||
closedVorgaengeByNameKey: closedVorgaengeByNameKey));
|
||||
|
||||
Assert.Equal(0.0, row.RegressionScore);
|
||||
Assert.Equal("Schuleschwänzen", row.RegressionVorgangTitle);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RegressionScore_ErkenntNeueUnentschuldigteTageNachAbschluss()
|
||||
{
|
||||
var student = Student(1001, "Ada Müller");
|
||||
var yearAbsences = new[]
|
||||
{
|
||||
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 8, 5), "Müller Ada", 1001, 6, 270,
|
||||
["Deu"], [1, 2, 3, 4, 5, 6], ["nicht entsch."], ["Absent"], null, null, true),
|
||||
// Nach Abschluss erneut unentschuldigt gefehlt.
|
||||
new ClassAbsenceDaySummaryRow(new DateOnly(2026, 8, 20), "Müller Ada", 1001, 6, 270,
|
||||
["Deu"], [1, 2, 3, 4, 5, 6], ["nicht entsch."], ["Absent"], null, null, true),
|
||||
};
|
||||
var closedVorgaengeByNameKey = new Dictionary<string, IReadOnlyList<Vorgang>>
|
||||
{
|
||||
[UntisNameMatching.NameKey("Ada Müller")] = [new Vorgang
|
||||
{
|
||||
Title = "Schuleschwänzen", Tags = ["Absentismus"], Status = VorgangStatus.Closed,
|
||||
ClosedAt = new DateTime(2026, 8, 12),
|
||||
}],
|
||||
};
|
||||
|
||||
var row = Assert.Single(ClassTeacherRosterRow.Build([student], [], [],
|
||||
new DateOnly(2026, 8, 26), yearAbsences, schoolDaysElapsed: 20, termStart: new DateOnly(2026, 8, 1),
|
||||
closedVorgaengeByNameKey: closedVorgaengeByNameKey));
|
||||
|
||||
Assert.Equal(3.0, row.RegressionScore);
|
||||
Assert.Equal("Schuleschwänzen", row.RegressionVorgangTitle);
|
||||
// Quote weiterhin unangetastet.
|
||||
Assert.Equal(2, row.YearUnexcusedDayCount);
|
||||
}
|
||||
}
|
||||
@@ -13,29 +13,34 @@ public sealed class CompetencyOverviewViewModelTests
|
||||
var subjectId = Guid.NewGuid();
|
||||
var group = new LearningGroup { SubjectId = subjectId, GradeLevel = 8 };
|
||||
var student = new Student { FirstName = "Ada", LastName = "Lovelace" };
|
||||
var k1 = new CompetencyItem { Code = "K1", Description = "Kompetenz" };
|
||||
var units = new FakeUnits();
|
||||
units.Add(new Unit
|
||||
{
|
||||
GroupId = group.Id, Status = UnitStatus.Completed, Competencies = ["K1"],
|
||||
GroupId = group.Id, Status = UnitStatus.Completed,
|
||||
Competencies = [new CompetencyReference { ItemId = k1.Id, Code = k1.Code, Description = k1.Description }],
|
||||
});
|
||||
var exam = new Exam
|
||||
{
|
||||
GroupId = group.Id,
|
||||
Status = ExamStatus.Graded,
|
||||
Tasks = [new ExamTask { MaxPoints = 10, CompetencyCodes = ["K1"] }],
|
||||
Tasks = [new ExamTask { MaxPoints = 10, Competencies = [new CompetencyReference { ItemId = k1.Id, Code = k1.Code, Description = k1.Description }] }],
|
||||
};
|
||||
var results = new FakeResults();
|
||||
results.Add(new ExamResult { ExamId = exam.Id, StudentId = student.Id, Points = [5] });
|
||||
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 = [new CompetencyItem { Code = "K1", Description = "Kompetenz" }],
|
||||
Items = [k1],
|
||||
});
|
||||
var vm = new CompetencyOverviewTabViewModel(units, new FakeExams([exam]), results,
|
||||
catalog, new FakeStudents([student]), new CompetencyAnalysisService());
|
||||
catalog, versions, new FakeStudents([student]), new CompetencyAnalysisService());
|
||||
|
||||
vm.Initialize(group);
|
||||
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Desktop.ViewModels.Groups;
|
||||
using Xunit;
|
||||
|
||||
namespace LehrerApp.Desktop.Tests;
|
||||
|
||||
public sealed class CompetencyTagGroupBuilderTests
|
||||
{
|
||||
[Fact]
|
||||
public void Build_MarkiertAusgewaehlteItemsAlsSelected()
|
||||
{
|
||||
var item = new CompetencyItem { Code = "K1", Description = "Erste Kompetenz" };
|
||||
var catalog = new List<CompetencyDomain> { new() { Name = "Bereich", Items = [item] } };
|
||||
var selected = new List<CompetencyReference> { new() { ItemId = item.Id, Code = item.Code, Description = item.Description } };
|
||||
|
||||
var groups = CompetencyTagGroupBuilder.Build(catalog, selected, _ => { });
|
||||
|
||||
var group = Assert.Single(groups);
|
||||
var tag = Assert.Single(group.Items);
|
||||
Assert.True(tag.IsSelected);
|
||||
Assert.Equal(item.Id, tag.ItemId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Build_ReferenzOhneKatalogTreffer_LandetInEigenerGruppeMitMomentaufnahme()
|
||||
{
|
||||
var catalog = new List<CompetencyDomain>
|
||||
{
|
||||
new() { Name = "Bereich", Items = [new CompetencyItem { Code = "K1", Description = "Erste Kompetenz" }] },
|
||||
};
|
||||
var orphaned = new CompetencyReference
|
||||
{
|
||||
ItemId = Guid.NewGuid(), Code = "ALT1", Description = "Alte, gelöschte Kompetenz",
|
||||
};
|
||||
var selected = new List<CompetencyReference> { orphaned };
|
||||
|
||||
var groups = CompetencyTagGroupBuilder.Build(catalog, selected, _ => { });
|
||||
|
||||
Assert.Equal(2, groups.Count);
|
||||
var fallbackGroup = groups.Single(g => g.Name == "Nicht mehr im Katalog");
|
||||
var tag = Assert.Single(fallbackGroup.Items);
|
||||
Assert.True(tag.IsSelected);
|
||||
Assert.Equal("ALT1", tag.Code);
|
||||
Assert.Equal("Alte, gelöschte Kompetenz", tag.Description);
|
||||
// Der reguläre Katalog-Bereich bleibt unberührt und zeigt sein einziges Item als abwählbar.
|
||||
var catalogGroup = groups.Single(g => g.Name == "Bereich");
|
||||
Assert.False(Assert.Single(catalogGroup.Items).IsSelected);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Build_ToggleAufTag_RuftOnChangedMitDerTagInstanzAuf()
|
||||
{
|
||||
var item = new CompetencyItem { Code = "K1", Description = "Erste Kompetenz" };
|
||||
var catalog = new List<CompetencyDomain> { new() { Name = "Bereich", Items = [item] } };
|
||||
CompetencyTag? changed = null;
|
||||
|
||||
var groups = CompetencyTagGroupBuilder.Build(catalog, [], tag => changed = tag);
|
||||
var tag = Assert.Single(Assert.Single(groups).Items);
|
||||
tag.IsSelected = true;
|
||||
|
||||
Assert.Same(tag, changed);
|
||||
Assert.Equal(item.Id, changed!.ItemId);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Desktop.Services;
|
||||
using LehrerApp.Desktop.ViewModels.Students;
|
||||
using LehrerApp.Templating;
|
||||
using Xunit;
|
||||
@@ -54,6 +55,246 @@ public sealed class CreateLetterDialogViewModelTests : IDisposable
|
||||
Assert.Equal("%PDF", System.Text.Encoding.ASCII.GetString(File.ReadAllBytes(output), 0, 4));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AdvancedContent_Anwesenheitskalender_WirdAlsDrawingGerendert()
|
||||
{
|
||||
var store = StoreWithTemplate(new PlaceholderDefinition(
|
||||
StudentAttendanceCalendarDrawingBuilder.PlaceholderName, PlaceholderType.Drawing, true));
|
||||
var drawing = StudentAttendanceCalendarDrawingBuilder.Build("Lena Beispiel", new DateOnly(2026, 9, 1), [], []);
|
||||
var vm = new CreateLetterDialogViewModel(StudentWithContact("Sehr geehrte Frau Muster,"), store,
|
||||
new QuestTemplateRenderer(), new FakeMemberships([]), new FakeGroups([]), (_, _, _, _) => drawing);
|
||||
var output = Path.Combine(_directory, "Kalender.pdf");
|
||||
|
||||
Assert.True(vm.UsesAttendanceCalendar);
|
||||
await vm.SetAttendanceCalendarOptionsAsync(new AttendanceCalendarOptions(
|
||||
new DateOnly(2026, 8, 19), 3, AttendanceCalendarSize.Large));
|
||||
Assert.True(vm.AttendanceCalendarConfigured);
|
||||
Assert.Contains("August 2026", vm.AttendanceCalendarSummary);
|
||||
Assert.Contains("3 Monate", vm.AttendanceCalendarSummary);
|
||||
Assert.Contains("Groß", vm.AttendanceCalendarSummary);
|
||||
Assert.True(vm.Generate(output));
|
||||
Assert.Equal("%PDF", System.Text.Encoding.ASCII.GetString(File.ReadAllBytes(output), 0, 4));
|
||||
}
|
||||
|
||||
// Regression: Der DrawingValue-Builder hat früher immer eine feste Breite (170) angenommen,
|
||||
// unabhängig davon, wie breit die DRAWBOX in der jeweiligen Vorlage tatsächlich deklariert war -
|
||||
// bei breiteren (oder in "pt" statt "mm" deklarierten) Boxen blieb dadurch ein Großteil der
|
||||
// eigentlich verfügbaren Fläche ungenutzt leer (sichtbar in echten Elternbriefen als "Luft"
|
||||
// rechts/unterhalb des Kalenders). Der Dialog muss die real deklarierte Breite ermitteln und an
|
||||
// den Builder weiterreichen.
|
||||
[Fact]
|
||||
public void AdvancedContent_Anwesenheitskalender_NutztDieImLayoutDeklarierteBoxbreite()
|
||||
{
|
||||
var manifest = new TemplateManifest
|
||||
{
|
||||
Id = $"brief-{Guid.NewGuid():N}", Name = "Elternbrief",
|
||||
Placeholders = [new(StudentAttendanceCalendarDrawingBuilder.PlaceholderName, PlaceholderType.Drawing, true)],
|
||||
};
|
||||
var source = Path.Combine(_directory, $"{Guid.NewGuid():N}.lavorlage");
|
||||
TemplatePackage.Create(source, manifest,
|
||||
$"PAGE 210 297 mm\nDRAWBOX 20 20 250 80 ${StudentAttendanceCalendarDrawingBuilder.PlaceholderName}",
|
||||
new Dictionary<string, byte[]>());
|
||||
var store = new TemplateStore(Path.Combine(_directory, $"store-{Guid.NewGuid():N}"));
|
||||
store.Import(source);
|
||||
float? receivedWidth = null; float? receivedMillimeterScale = null;
|
||||
|
||||
var vm = new CreateLetterDialogViewModel(StudentWithContact("Sehr geehrte Frau Muster,"), store,
|
||||
new QuestTemplateRenderer(), new FakeMemberships([]), new FakeGroups([]),
|
||||
(_, width, millimeterScale, _) => { receivedWidth = width; receivedMillimeterScale = millimeterScale; return new DrawingValue([], 0); });
|
||||
|
||||
Assert.True(vm.UsesAttendanceCalendar);
|
||||
Assert.Equal(250, receivedWidth);
|
||||
Assert.Equal(1, receivedMillimeterScale);
|
||||
}
|
||||
|
||||
// Regression: Eine reale, aus einem Word-Dokument übernommene Vorlage deklariert die Seite in
|
||||
// "pt" statt "mm" (PAGE ... pt). Ohne Umrechnung würde das mm-entworfene Kalenderraster dort nur
|
||||
// rund ein Drittel der vorgesehenen physischen Größe erreichen (1 "mm-Einheit" würde als 1pt statt
|
||||
// als ~2.83pt gerendert).
|
||||
[Fact]
|
||||
public void AdvancedContent_Anwesenheitskalender_RechnetBoxbreiteBeiPunktBasierterVorlageUm()
|
||||
{
|
||||
var manifest = new TemplateManifest
|
||||
{
|
||||
Id = $"brief-{Guid.NewGuid():N}", Name = "Elternbrief",
|
||||
Placeholders = [new(StudentAttendanceCalendarDrawingBuilder.PlaceholderName, PlaceholderType.Drawing, true)],
|
||||
};
|
||||
var source = Path.Combine(_directory, $"{Guid.NewGuid():N}.lavorlage");
|
||||
TemplatePackage.Create(source, manifest,
|
||||
$"PAGE 595.32 841.92 pt\nDRAWBOX 71 350 487 177 ${StudentAttendanceCalendarDrawingBuilder.PlaceholderName}",
|
||||
new Dictionary<string, byte[]>());
|
||||
var store = new TemplateStore(Path.Combine(_directory, $"store-{Guid.NewGuid():N}"));
|
||||
store.Import(source);
|
||||
float? receivedWidth = null; float? receivedMillimeterScale = null;
|
||||
|
||||
var vm = new CreateLetterDialogViewModel(StudentWithContact("Sehr geehrte Frau Muster,"), store,
|
||||
new QuestTemplateRenderer(), new FakeMemberships([]), new FakeGroups([]),
|
||||
(_, width, millimeterScale, _) => { receivedWidth = width; receivedMillimeterScale = millimeterScale; return new DrawingValue([], 0); });
|
||||
|
||||
Assert.True(vm.UsesAttendanceCalendar);
|
||||
Assert.Equal(487, receivedWidth);
|
||||
Assert.NotNull(receivedMillimeterScale);
|
||||
Assert.Equal(2.8346f, receivedMillimeterScale!.Value, 0.001f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AttendanceKalenderKonfigurieren_LoestGezieltenDatenAbrufFuerDenZeitraumAus()
|
||||
{
|
||||
var store = StoreWithTemplate(new PlaceholderDefinition(
|
||||
StudentAttendanceCalendarDrawingBuilder.PlaceholderName, PlaceholderType.Drawing, true));
|
||||
AttendanceCalendarOptions? requested = null;
|
||||
var vm = new CreateLetterDialogViewModel(StudentWithContact("Sehr geehrte Frau Muster,"), store,
|
||||
new QuestTemplateRenderer(), new FakeMemberships([]), new FakeGroups([]),
|
||||
(_, _, _, _) => new DrawingValue([], 0), attendanceDataRefresher: (options, _) =>
|
||||
{ requested = options; return Task.CompletedTask; });
|
||||
|
||||
await vm.SetAttendanceCalendarOptionsAsync(new AttendanceCalendarOptions(
|
||||
new DateOnly(2026, 9, 1), 2, AttendanceCalendarSize.Medium));
|
||||
|
||||
Assert.NotNull(requested);
|
||||
Assert.Equal(new DateOnly(2026, 9, 1), requested!.NormalizedStartMonth);
|
||||
Assert.Equal(2, requested.NormalizedMonthCount);
|
||||
Assert.False(vm.IsRefreshingAttendanceData);
|
||||
Assert.Equal("", vm.AttendanceRefreshError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AttendanceKalenderKonfigurieren_ZeigtFehlerBeiFehlgeschlagenemAbrufAnStattZuBlockieren()
|
||||
{
|
||||
var store = StoreWithTemplate(new PlaceholderDefinition(
|
||||
StudentAttendanceCalendarDrawingBuilder.PlaceholderName, PlaceholderType.Drawing, true));
|
||||
var vm = new CreateLetterDialogViewModel(StudentWithContact("Sehr geehrte Frau Muster,"), store,
|
||||
new QuestTemplateRenderer(), new FakeMemberships([]), new FakeGroups([]),
|
||||
(_, _, _, _) => new DrawingValue([], 0),
|
||||
attendanceDataRefresher: (_, _) => throw new WebUntisIntegrationException("Keine Verbindung."));
|
||||
|
||||
await vm.SetAttendanceCalendarOptionsAsync(new AttendanceCalendarOptions(
|
||||
new DateOnly(2026, 9, 1), 1, AttendanceCalendarSize.Medium));
|
||||
|
||||
Assert.True(vm.AttendanceCalendarConfigured);
|
||||
Assert.Contains("Keine Verbindung.", vm.AttendanceRefreshError);
|
||||
Assert.False(vm.IsRefreshingAttendanceData);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AdvancedContent_Fehlzeitenliste_AktiviertKonfigurationsschritt()
|
||||
{
|
||||
var store = StoreWithTemplate(new PlaceholderDefinition(
|
||||
StudentAbsenceDayListDrawingBuilder.PlaceholderName, PlaceholderType.Drawing, true));
|
||||
var drawing = StudentAbsenceDayListDrawingBuilder.Build("Lena Beispiel",
|
||||
new AttendanceCalendarOptions(new DateOnly(2026, 9, 1), 1), []);
|
||||
var vm = new CreateLetterDialogViewModel(StudentWithContact("Sehr geehrte Frau Muster,"), store,
|
||||
new QuestTemplateRenderer(), new FakeMemberships([]), new FakeGroups([]),
|
||||
attendanceCalendarFactory: null, absenceDayListFactory: (_, _, _, _) => drawing);
|
||||
|
||||
Assert.False(vm.UsesAttendanceCalendar);
|
||||
Assert.True(vm.UsesAbsenceDayList);
|
||||
Assert.True(vm.UsesAttendanceAdvancedContent);
|
||||
Assert.True(vm.CanGenerate);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EigenerPlatzhalter_KannImDialogEingegebenWerden()
|
||||
{
|
||||
var store = StoreWithTemplate(new PlaceholderDefinition("Anrede", PlaceholderType.Text, true),
|
||||
new PlaceholderDefinition("Datum", PlaceholderType.Date, true),
|
||||
new PlaceholderDefinition("Brieftext", PlaceholderType.Multiline, true),
|
||||
new PlaceholderDefinition("Betreff", PlaceholderType.Text, true));
|
||||
var vm = Build(StudentWithContact("Sehr geehrte Frau Muster,"), store);
|
||||
vm.LetterText = "Dies ist der Inhalt.";
|
||||
|
||||
var betreff = Assert.Single(vm.CustomPlaceholders);
|
||||
Assert.Equal("Betreff", betreff.Name);
|
||||
Assert.False(vm.CanGenerate);
|
||||
Assert.Contains(vm.Issues, i => i.Message.Contains("Betreff", StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
betreff.TextValue = "Wichtiger Termin";
|
||||
var output = Path.Combine(_directory, "MitBetreff.pdf");
|
||||
|
||||
Assert.True(vm.CanGenerate);
|
||||
Assert.True(vm.Generate(output));
|
||||
Assert.Equal("%PDF", System.Text.Encoding.ASCII.GetString(File.ReadAllBytes(output), 0, 4));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StudentName_WirdAutomatischMitVollemNamenBefuellt()
|
||||
{
|
||||
var store = StoreWithTemplate(new PlaceholderDefinition("Anrede", PlaceholderType.Text, true),
|
||||
new PlaceholderDefinition("Datum", PlaceholderType.Date, true),
|
||||
new PlaceholderDefinition("Brieftext", PlaceholderType.Multiline, true),
|
||||
new PlaceholderDefinition("Student.Name", PlaceholderType.Text, true));
|
||||
var vm = Build(StudentWithContact("Sehr geehrte Frau Muster,"), store);
|
||||
vm.LetterText = "Dies ist der Inhalt.";
|
||||
|
||||
Assert.Empty(vm.CustomPlaceholders);
|
||||
Assert.True(vm.CanGenerate);
|
||||
var output = Path.Combine(_directory, "StudentName.pdf");
|
||||
Assert.True(vm.Generate(output));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Anrede_WirdAusKontaktVorbelegtUndBleibtEditierbar()
|
||||
{
|
||||
var store = StoreWithTemplate(new PlaceholderDefinition("Anrede", PlaceholderType.Text, true),
|
||||
new PlaceholderDefinition("Datum", PlaceholderType.Date, true),
|
||||
new PlaceholderDefinition("Brieftext", PlaceholderType.Multiline, true));
|
||||
var vm = Build(StudentWithContact(null), store);
|
||||
vm.LetterText = "Dies ist der Inhalt.";
|
||||
|
||||
Assert.Equal("", vm.Anrede);
|
||||
Assert.False(vm.CanGenerate);
|
||||
Assert.Contains(vm.Issues, i => i.Message.Contains("Anrede", StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
vm.Anrede = "Sehr geehrte Familie Beispiel,";
|
||||
var output = Path.Combine(_directory, "AnredeManuell.pdf");
|
||||
|
||||
Assert.True(vm.CanGenerate);
|
||||
Assert.True(vm.Generate(output));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddressPreview_FolgtDemGewaehltenKontaktUndAktualisiertSichBeimWechsel()
|
||||
{
|
||||
var student = new Student
|
||||
{
|
||||
FirstName = "Lena", LastName = "Beispiel",
|
||||
Contacts =
|
||||
[
|
||||
new Contact { Name = "Frau Beispiel", Relation = "Mutter", Street = "Erste Str. 1", PostalCode = "11111", City = "Erststadt" },
|
||||
new Contact { Name = "Herr Beispiel", Relation = "Vater", Street = "Zweite Str. 2", PostalCode = "22222", City = "Zweitstadt" },
|
||||
],
|
||||
};
|
||||
var vm = Build(student, StoreWithTemplate(new PlaceholderDefinition("Anrede", PlaceholderType.Text, true)));
|
||||
|
||||
Assert.Equal(2, vm.Contacts.Count);
|
||||
Assert.Contains("Frau Beispiel", vm.AddressPreview);
|
||||
Assert.Contains("Erste Str. 1", vm.AddressPreview);
|
||||
|
||||
vm.SelectedContact = vm.Contacts.Single(c => c.Model.Name == "Herr Beispiel");
|
||||
|
||||
Assert.Contains("Herr Beispiel", vm.AddressPreview);
|
||||
Assert.Contains("Zweite Str. 2", vm.AddressPreview);
|
||||
Assert.DoesNotContain("Frau Beispiel", vm.AddressPreview);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SelectContactDialog_StartetBeimAktuellenKontaktUndAktualisiertVorschau()
|
||||
{
|
||||
var contacts = new List<LetterContactChoice>
|
||||
{
|
||||
new(new Contact { Name = "Frau Beispiel", Street = "Erste Str. 1", PostalCode = "11111", City = "Erststadt" }),
|
||||
new(new Contact { Name = "Herr Beispiel", Street = "Zweite Str. 2", PostalCode = "22222", City = "Zweitstadt" }),
|
||||
};
|
||||
var dialogVm = new SelectContactDialogViewModel(contacts, contacts[1]);
|
||||
|
||||
Assert.Same(contacts[1], dialogVm.SelectedContact);
|
||||
Assert.Contains("Zweite Str. 2", dialogVm.AddressPreview);
|
||||
|
||||
dialogVm.SelectedContact = contacts[0];
|
||||
|
||||
Assert.Contains("Erste Str. 1", dialogVm.AddressPreview);
|
||||
}
|
||||
|
||||
private CreateLetterDialogViewModel Build(Student student, TemplateStore store) =>
|
||||
new(student, store, new QuestTemplateRenderer(), new FakeMemberships([]), new FakeGroups([]));
|
||||
|
||||
@@ -65,8 +306,18 @@ public sealed class CreateLetterDialogViewModelTests : IDisposable
|
||||
var y = 20;
|
||||
foreach (var definition in definitions)
|
||||
{
|
||||
var element = definition.Type == PlaceholderType.Multiline ? "TEXTBOX" : "TEXT";
|
||||
lines.Add(element == "TEXTBOX" ? $"TEXTBOX 20 {y} 170 80 ${definition.Name}" : $"TEXT 20 {y} ${definition.Name}");
|
||||
var element = definition.Type switch
|
||||
{
|
||||
PlaceholderType.Multiline => "TEXTBOX",
|
||||
PlaceholderType.Drawing => "DRAWBOX",
|
||||
_ => "TEXT",
|
||||
};
|
||||
lines.Add(element switch
|
||||
{
|
||||
"TEXTBOX" => $"TEXTBOX 20 {y} 170 80 ${definition.Name}",
|
||||
"DRAWBOX" => $"DRAWBOX 20 {y} 170 80 ${definition.Name}",
|
||||
_ => $"TEXT 20 {y} ${definition.Name}",
|
||||
});
|
||||
y += 20;
|
||||
}
|
||||
TemplatePackage.Create(source, manifest, string.Join('\n', lines), new Dictionary<string, byte[]>());
|
||||
|
||||
@@ -20,14 +20,75 @@ public sealed class DashboardViewModelTests
|
||||
|
||||
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today });
|
||||
|
||||
Assert.False(vm.ExcusesCard.EffectiveIsVisible);
|
||||
Assert.False(vm.CorrectionsCard.EffectiveIsVisible);
|
||||
Assert.False(vm.AlertsCard.EffectiveIsVisible);
|
||||
Assert.False(vm.AttentionCard.EffectiveIsVisible);
|
||||
Assert.Equal("0 offene Punkte", vm.AttentionSummary);
|
||||
Assert.True(vm.TodayCard.EffectiveIsVisible);
|
||||
Assert.True(vm.CalendarCard.EffectiveIsVisible);
|
||||
}
|
||||
|
||||
/// Regression: ApplyCardLayout zaehlte frueher IsVisible statt EffectiveIsVisible. Eine
|
||||
/// eingeschaltete, aber leere HideWhenEmpty-Kachel belegte damit einen Rasterplatz, den das
|
||||
/// Grid nie fuellt — im Alltag der Normalfall, weil meist mehrere Hinweiskacheln leer sind.
|
||||
[Fact]
|
||||
public void Kachelraster_LeereAusgeblendeteKacheln_HinterlassenKeineLuecke()
|
||||
{
|
||||
var group = new LearningGroup { Name = "9c" };
|
||||
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||
|
||||
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today });
|
||||
|
||||
// Ohne mindestens eine leer ausgeblendete Kachel wuerde der Test nichts pruefen.
|
||||
Assert.False(vm.AttentionCard.EffectiveIsVisible);
|
||||
|
||||
var belegtePlaetze = vm.DashboardCards.Where(c => c.EffectiveIsVisible)
|
||||
.Select(c => c.Row * 2 + c.Column).OrderBy(slot => slot).ToList();
|
||||
Assert.Equal(Enumerable.Range(0, belegtePlaetze.Count), belegtePlaetze);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void KachelMargin_FolgtDerBerechnetenSpalte()
|
||||
{
|
||||
var group = new LearningGroup { Name = "9c" };
|
||||
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||
|
||||
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today });
|
||||
|
||||
foreach (var card in vm.DashboardCards.Where(c => c.EffectiveIsVisible))
|
||||
Assert.Equal(card.Column == 0
|
||||
? new Avalonia.Thickness(0, 0, 8, 8)
|
||||
: new Avalonia.Thickness(8, 0, 0, 8), card.Margin);
|
||||
}
|
||||
|
||||
/// Regression: der Margin hing fest im XAML an der Kachel. Wandert sie durch Aus-/Einblenden
|
||||
/// einer vorherigen Kachel in die andere Spalte, sass der Rinnstein auf der falschen Seite.
|
||||
[Fact]
|
||||
public void KachelAusblenden_DrehtDenMarginDerNachfolgendenKachel()
|
||||
{
|
||||
var group = new LearningGroup { Name = "9c" };
|
||||
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||
|
||||
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today });
|
||||
Assert.Equal(1, vm.TasksCard.Column);
|
||||
Assert.Equal(new Avalonia.Thickness(8, 0, 0, 8), vm.TasksCard.Margin);
|
||||
|
||||
vm.TodayCard.IsVisible = false;
|
||||
|
||||
Assert.Equal(0, vm.TasksCard.Column);
|
||||
Assert.Equal(new Avalonia.Thickness(0, 0, 8, 8), vm.TasksCard.Margin);
|
||||
}
|
||||
|
||||
/// Die frueheren sieben eigenen Listen (OpenExcuses, AttendanceWarnings, ...) sind zur
|
||||
/// zusammengefassten Attention-Karte verschmolzen (siehe AttentionItem.cs) — Tests greifen
|
||||
/// seither ueber Kind gefiltert zu statt ueber eine eigene Collection je Art.
|
||||
private static IEnumerable<AttentionItem> Items(DashboardViewModel vm, AttentionKind kind) =>
|
||||
vm.Attention.Where(g => g.Kind == kind).SelectMany(g => g.Items);
|
||||
|
||||
/// AttentionItem traegt fuer MissingTeachingTime kein eigenes Date-Feld (Title ist bereits der
|
||||
/// formatierte Anzeigetext) — das genaue Datum steckt im mitgegebenen Action-Parameter
|
||||
/// (derselbe MissingTeachingTimeItem, den auch der "Erfassen"-Dialog erhaelt).
|
||||
private static DateOnly MissingTimeDate(AttentionItem item) =>
|
||||
((MissingTeachingTimeItem)item.Actions.Single().Parameter!).Date;
|
||||
|
||||
private static PeriodScheduleService NewPeriodSchedule()
|
||||
{
|
||||
var tempPath = System.IO.Path.Combine(
|
||||
@@ -61,7 +122,7 @@ public sealed class DashboardViewModelTests
|
||||
FakeLessons? lessons = null, FakeSubstitutionEntries? substitutions = null,
|
||||
FakeSessions? sessions = null, FakeEntries? entries = null,
|
||||
FakeAnnualPlanEvents? annualPlanEvents = null, List<LearningGroup>? allGroups = null,
|
||||
FakeTimeEntries? timeEntries = null)
|
||||
FakeTimeEntries? timeEntries = null, Func<DateTime>? now = null)
|
||||
{
|
||||
lessons ??= new FakeLessons();
|
||||
lessons.Add(lesson);
|
||||
@@ -74,7 +135,9 @@ public sealed class DashboardViewModelTests
|
||||
slots ?? new FakeTimetableSlots(), periodSchedule ?? NewPeriodSchedule(),
|
||||
new AttendanceBalanceService(), new SchoolYearService(), dashboardSettings ?? NewDashboardSettings(),
|
||||
schoolHolidays ?? new FakeSchoolHolidays(), new PublicHolidayService(), NewCalendarSettings(),
|
||||
substitutions ?? new FakeSubstitutionEntries(), timeEntries ?? new FakeTimeEntries(), annualPlanEvents);
|
||||
substitutions ?? new FakeSubstitutionEntries(), timeEntries ?? new FakeTimeEntries(),
|
||||
TestSupport.BuildUntisHubService(), TestSupport.BuildWebUntisIntegrationService(), annualPlanEvents,
|
||||
annualPlanSync: null, schoolWeather: null, now: now);
|
||||
}
|
||||
|
||||
/// Montag einer Woche, die garantiert in der Zukunft liegt und innerhalb der
|
||||
@@ -152,8 +215,8 @@ public sealed class DashboardViewModelTests
|
||||
|
||||
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today }, slots: slots, periodSchedule: periodSchedule);
|
||||
|
||||
Assert.Contains(vm.MissingTeachingTimeEntries, i => i.Date == pastDay);
|
||||
Assert.True(vm.MissingTeachingTimeCard.EffectiveIsVisible);
|
||||
Assert.Contains(Items(vm, AttentionKind.MissingTeachingTime), i => MissingTimeDate(i) == pastDay);
|
||||
Assert.True(vm.AttentionCard.EffectiveIsVisible);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -173,7 +236,7 @@ public sealed class DashboardViewModelTests
|
||||
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||
slots: slots, periodSchedule: periodSchedule, timeEntries: timeEntries);
|
||||
|
||||
Assert.DoesNotContain(vm.MissingTeachingTimeEntries, i => i.Date == pastDay);
|
||||
Assert.DoesNotContain(Items(vm, AttentionKind.MissingTeachingTime), i => MissingTimeDate(i) == pastDay);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -193,7 +256,7 @@ public sealed class DashboardViewModelTests
|
||||
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||
slots: slots, periodSchedule: periodSchedule, substitutions: substitutions);
|
||||
|
||||
Assert.DoesNotContain(vm.MissingTeachingTimeEntries, i => i.Date == pastDay);
|
||||
Assert.DoesNotContain(Items(vm, AttentionKind.MissingTeachingTime), i => MissingTimeDate(i) == pastDay);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -213,43 +276,55 @@ public sealed class DashboardViewModelTests
|
||||
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||
slots: slots, periodSchedule: periodSchedule, schoolHolidays: schoolHolidays);
|
||||
|
||||
Assert.DoesNotContain(vm.MissingTeachingTimeEntries, i => i.Date == pastDay);
|
||||
Assert.DoesNotContain(Items(vm, AttentionKind.MissingTeachingTime), i => MissingTimeDate(i) == pastDay);
|
||||
}
|
||||
|
||||
/// Fixer Referenzzeitpunkt fuer die beiden "heute, kurz vor/nach Ablauf der Wartezeit"-Tests
|
||||
/// unten. Regression: die Tests bauten "Unterrichtsende" bisher aus TimeOnly.FromDateTime(
|
||||
/// DateTime.Now).AddHours(±2) — TimeOnly wickelt bei Mitternacht um, ausgefuehrt zwischen ca.
|
||||
/// 22:00 und 02:00 Uhr wurde dadurch aus "+2h" ein Ende VOR "jetzt" (oder umgekehrt), je nach
|
||||
/// Tageszeit zufaellig rot. September ist bewusst gewaehlt: keiner der bundesweiten oder
|
||||
/// laenderspezifischen Feiertage (PublicHolidayService) faellt in diesen Monat, ein Dienstag
|
||||
/// ist garantiert kein Wochenende — die injizierte Uhr (DashboardViewModel now:-Parameter)
|
||||
/// macht "jetzt" fuer den Test unabhaengig von der tatsaechlichen Ausfuehrungsuhrzeit.
|
||||
private static readonly DateTime FixedNow = new(2026, 9, 8, 10, 0, 0);
|
||||
|
||||
[Fact]
|
||||
public void MissingTeachingTime_HeuteVorAblaufDerWartezeit_WirdNichtGemeldet()
|
||||
{
|
||||
var group = new LearningGroup { Name = "9c" };
|
||||
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||
var today = DateOnly.FromDateTime(FixedNow);
|
||||
var slots = new FakeTimetableSlots();
|
||||
slots.Add(new TimetableSlot { GroupId = group.Id, Weekday = today.DayOfWeek, PeriodNumber = 1 });
|
||||
var periodSchedule = NewPeriodSchedule();
|
||||
// Unterrichtsende liegt garantiert noch keine 30 Minuten zurück.
|
||||
var futureEnd = TimeOnly.FromDateTime(DateTime.Now).AddHours(2);
|
||||
// Unterrichtsende liegt (relativ zur fixen Uhr FixedNow) noch keine 30 Minuten zurück.
|
||||
var futureEnd = TimeOnly.FromDateTime(FixedNow).AddHours(2);
|
||||
periodSchedule.SetPeriods([new PeriodTimeEntry
|
||||
{ PeriodNumber = 1, Start = futureEnd.AddHours(-1), End = futureEnd }]);
|
||||
|
||||
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today }, slots: slots, periodSchedule: periodSchedule);
|
||||
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today }, slots: slots,
|
||||
periodSchedule: periodSchedule, now: () => FixedNow);
|
||||
|
||||
Assert.DoesNotContain(vm.MissingTeachingTimeEntries, i => i.Date == today);
|
||||
Assert.DoesNotContain(Items(vm, AttentionKind.MissingTeachingTime), i => MissingTimeDate(i) == today);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MissingTeachingTime_HeuteNachAblaufDerWartezeit_WirdGemeldet()
|
||||
{
|
||||
var group = new LearningGroup { Name = "9c" };
|
||||
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||
var today = DateOnly.FromDateTime(FixedNow);
|
||||
var slots = new FakeTimetableSlots();
|
||||
slots.Add(new TimetableSlot { GroupId = group.Id, Weekday = today.DayOfWeek, PeriodNumber = 1 });
|
||||
var periodSchedule = NewPeriodSchedule();
|
||||
// Unterrichtsende liegt garantiert mehr als 30 Minuten zurück.
|
||||
var pastEnd = TimeOnly.FromDateTime(DateTime.Now).AddHours(-2);
|
||||
// Unterrichtsende liegt (relativ zur fixen Uhr FixedNow) mehr als 30 Minuten zurück.
|
||||
var pastEnd = TimeOnly.FromDateTime(FixedNow).AddHours(-2);
|
||||
periodSchedule.SetPeriods([new PeriodTimeEntry
|
||||
{ PeriodNumber = 1, Start = pastEnd.AddHours(-1), End = pastEnd }]);
|
||||
|
||||
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today }, slots: slots, periodSchedule: periodSchedule);
|
||||
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today }, slots: slots,
|
||||
periodSchedule: periodSchedule, now: () => FixedNow);
|
||||
|
||||
Assert.Contains(vm.MissingTeachingTimeEntries, i => i.Date == today);
|
||||
Assert.Contains(Items(vm, AttentionKind.MissingTeachingTime), i => MissingTimeDate(i) == today);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -376,10 +451,9 @@ public sealed class DashboardViewModelTests
|
||||
exams: new FakeExams([exam]), results: results, memberships: memberships,
|
||||
students: new FakeStudents([anna, ben]));
|
||||
|
||||
var correction = Assert.Single(vm.OpenCorrections);
|
||||
Assert.Equal(1, correction.Completed);
|
||||
Assert.Equal(2, correction.Total);
|
||||
Assert.Equal(50, correction.Percent);
|
||||
var correction = Assert.Single(Items(vm, AttentionKind.Correction));
|
||||
Assert.Equal(50, correction.ProgressPercent);
|
||||
Assert.Equal("1 von 2 Arbeiten bewertet", correction.ProgressLabel);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -400,7 +474,7 @@ public sealed class DashboardViewModelTests
|
||||
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today }, grades: grades,
|
||||
memberships: memberships, students: new FakeStudents([student]));
|
||||
|
||||
Assert.Contains(vm.Alerts, a => a.StudentId == student.Id && a.KindLabel == "Notenabfall");
|
||||
Assert.Contains(Items(vm, AttentionKind.Alert), a => a.Title == student.FullName && a.TrailingText == "Notenabfall");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -559,9 +633,8 @@ public sealed class DashboardViewModelTests
|
||||
|
||||
var vm = BuildVm(group, pastLesson, slots: slots);
|
||||
|
||||
var item = Assert.Single(vm.UnplannedLessons);
|
||||
Assert.Equal(group.Id, item.GroupId);
|
||||
Assert.Equal(1, item.PeriodNumber);
|
||||
var item = Assert.Single(Items(vm, AttentionKind.Unplanned));
|
||||
Assert.Equal($"{group.Name} · 1. Stunde", item.Title);
|
||||
Assert.Equal("Heute", item.DateDisplay);
|
||||
}
|
||||
|
||||
@@ -576,7 +649,7 @@ public sealed class DashboardViewModelTests
|
||||
|
||||
var vm = BuildVm(group, lesson, slots: slots);
|
||||
|
||||
Assert.Empty(vm.UnplannedLessons);
|
||||
Assert.Empty(Items(vm, AttentionKind.Unplanned));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -590,7 +663,7 @@ public sealed class DashboardViewModelTests
|
||||
|
||||
var vm = BuildVm(group, pastLesson, slots: slots);
|
||||
|
||||
Assert.Empty(vm.UnplannedLessons);
|
||||
Assert.Empty(Items(vm, AttentionKind.Unplanned));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -606,7 +679,7 @@ public sealed class DashboardViewModelTests
|
||||
|
||||
var vm = BuildVm(group, pastLesson, slots: slots, schoolHolidays: schoolHolidays);
|
||||
|
||||
Assert.Empty(vm.UnplannedLessons);
|
||||
Assert.Empty(Items(vm, AttentionKind.Unplanned));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -621,7 +694,7 @@ public sealed class DashboardViewModelTests
|
||||
|
||||
var vm = BuildVm(group, lesson, slots: slots);
|
||||
|
||||
Assert.Empty(vm.UnplannedLessons);
|
||||
Assert.Empty(Items(vm, AttentionKind.Unplanned));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -636,9 +709,10 @@ public sealed class DashboardViewModelTests
|
||||
|
||||
var vm = BuildVm(group, lesson, slots: slots);
|
||||
|
||||
Assert.Equal(2, vm.UnplannedLessons.Count);
|
||||
Assert.Contains(vm.UnplannedLessons, i => i.PeriodNumber == 3);
|
||||
Assert.Contains(vm.UnplannedLessons, i => i.PeriodNumber == 4);
|
||||
var unplanned = Items(vm, AttentionKind.Unplanned).ToList();
|
||||
Assert.Equal(2, unplanned.Count);
|
||||
Assert.Contains(unplanned, i => i.Title.Contains("3. Stunde"));
|
||||
Assert.Contains(unplanned, i => i.Title.Contains("4. Stunde"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -656,7 +730,7 @@ public sealed class DashboardViewModelTests
|
||||
|
||||
var vm = BuildVm(group, pastLesson, slots: slots, substitutions: substitutions);
|
||||
|
||||
Assert.Empty(vm.UnplannedLessons);
|
||||
Assert.Empty(Items(vm, AttentionKind.Unplanned));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -679,7 +753,7 @@ public sealed class DashboardViewModelTests
|
||||
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||
students: new FakeStudents([student]), sessions: sessions, entries: entries);
|
||||
|
||||
Assert.Empty(vm.AttendanceWarnings);
|
||||
Assert.Empty(Items(vm, AttentionKind.Attendance));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -703,9 +777,9 @@ public sealed class DashboardViewModelTests
|
||||
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||
students: new FakeStudents([student]), sessions: sessions, entries: entries);
|
||||
|
||||
var item = Assert.Single(vm.AttendanceWarnings);
|
||||
Assert.Equal(student.FullName, item.StudentName);
|
||||
Assert.Equal(30.0, item.AbsenceRatePercent);
|
||||
var item = Assert.Single(Items(vm, AttentionKind.Attendance));
|
||||
Assert.Equal(student.FullName, item.Title);
|
||||
Assert.Equal("30 %", item.TrailingText);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -228,6 +228,20 @@ public sealed class DocumentationDialogViewModelTests
|
||||
Assert.NotEqual("", vm.StudentError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OhneGeladeneSchuelerlisteUndOhneKontext_SaveErzeugtKeinenVerwaistenEintrag()
|
||||
{
|
||||
var vm = new DocumentationDialogViewModel(Guid.Empty, null, new FakeAttachmentStorage())
|
||||
{
|
||||
Title = "Vorfall", TypeName = "Vorkommnis",
|
||||
};
|
||||
|
||||
vm.SaveCommand.Execute(null);
|
||||
|
||||
Assert.Null(vm.Result);
|
||||
Assert.Contains("noch nicht geladen", vm.StudentError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MitStudentOptions_AuswahlGetroffen_SaveUebernimmtSchuelerUndGruppe()
|
||||
{
|
||||
|
||||
@@ -2,6 +2,7 @@ using LehrerApp.Core.Interfaces;
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Core.Services;
|
||||
using LehrerApp.Desktop.Services;
|
||||
using LehrerApp.Desktop.Services.Mcp;
|
||||
using LehrerApp.Desktop.ViewModels.Settings;
|
||||
using LehrerApp.Sync;
|
||||
using LehrerApp.Sync.Crypto;
|
||||
@@ -29,7 +30,18 @@ public static class TestSupport
|
||||
/// solange AiSettingsService.IsLoggedIn false ist.
|
||||
public static AiPlanningService BuildAiPlanningService() => new(
|
||||
new HttpClient(), new FakeLessons(), new FakeGroups([]), new FakeSubjects([]),
|
||||
new FakeCompetencyDomains(), new FakeAlternativeLessonPaths([]));
|
||||
new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions(), new FakeAlternativeLessonPaths([]));
|
||||
|
||||
/// Analog zu <see cref="BuildAiSettingsService"/>, eigenes Temp-Verzeichnis je Aufruf.
|
||||
public static McpSettingsService BuildMcpSettingsService()
|
||||
{
|
||||
var tempPath = Path.Combine(Path.GetTempPath(), $"lehrerapp-mcpsettings-tests-{Guid.NewGuid():N}");
|
||||
Directory.CreateDirectory(tempPath);
|
||||
return new McpSettingsService(tempPath);
|
||||
}
|
||||
|
||||
/// Kein Konstruktorparameter - Pfade werden intern über Environment.SpecialFolder aufgelöst.
|
||||
public static McpClientRegistrationService BuildMcpClientRegistrationService() => new();
|
||||
|
||||
/// Analog zu <see cref="BuildAiSettingsService"/>, eigenes Temp-Verzeichnis je Aufruf.
|
||||
public static WebUntisSettingsService BuildWebUntisSettingsService()
|
||||
@@ -39,6 +51,14 @@ public static class TestSupport
|
||||
return new WebUntisSettingsService(tempPath);
|
||||
}
|
||||
|
||||
/// Nicht konfiguriert (kein API-Login hinterlegt) - genügt für Tests, die nur den Konstruktor
|
||||
/// bedienen müssen und keinen echten WebUntis-Zugriff auslösen.
|
||||
public static WebUntisIntegrationService BuildWebUntisIntegrationService() =>
|
||||
new(new HttpClient(), BuildWebUntisSettingsService());
|
||||
|
||||
public static UntisHubService BuildUntisHubService(List<LearningGroup>? groups = null) =>
|
||||
new(new FakeGroups(groups ?? []), new FakeUntisHubJobStates(), new SchoolYearService());
|
||||
|
||||
/// Analog zu den übrigen dateibasierten Feed-Einstellungen: eigenes Temp-Verzeichnis.
|
||||
public static AnnualPlanSettingsService BuildAnnualPlanSettingsService()
|
||||
{
|
||||
@@ -338,6 +358,7 @@ public class FakeLessons : ILessonRepository
|
||||
{
|
||||
private readonly List<Lesson> _all = [];
|
||||
public void Add(Lesson l) => _all.Add(l);
|
||||
public Lesson? GetById(Guid id) => _all.FirstOrDefault(l => l.Id == id);
|
||||
public List<Lesson> GetByUnit(Guid unitId) =>
|
||||
_all.Where(l => l.UnitId == unitId).OrderBy(l => l.Date).ThenBy(l => l.LessonNumber).ToList();
|
||||
public List<Lesson> GetByGroupAndDate(Guid groupId, DateOnly date) =>
|
||||
@@ -352,30 +373,76 @@ public class FakeSubjects(List<Subject> all) : ISubjectRepository
|
||||
{
|
||||
public List<Subject> GetAll() => all;
|
||||
public Subject? GetById(Guid id) => all.FirstOrDefault(s => s.Id == id);
|
||||
public Subject? GetByName(string name) => all.FirstOrDefault(s => s.Name == name);
|
||||
public void Save(Subject subject) { }
|
||||
public void Delete(Guid id) { }
|
||||
public Subject? GetByName(string name) => all.FirstOrDefault(s =>
|
||||
string.Equals(s.Name.Trim(), name.Trim(), StringComparison.OrdinalIgnoreCase));
|
||||
public void Save(Subject subject)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(subject.Name)) throw new ArgumentException("Der Fachname darf nicht leer sein.");
|
||||
var duplicate = GetByName(subject.Name);
|
||||
if (duplicate is not null && duplicate.Id != subject.Id)
|
||||
throw new InvalidOperationException("Ein Fach mit diesem Namen existiert bereits.");
|
||||
all.RemoveAll(s => s.Id == subject.Id);
|
||||
all.Add(subject);
|
||||
}
|
||||
public void Delete(Guid id) => all.RemoveAll(s => s.Id == id);
|
||||
}
|
||||
|
||||
public class FakeCompetencyDomains : ICompetencyDomainRepository
|
||||
{
|
||||
private readonly List<CompetencyDomain> _all = [];
|
||||
public void Add(CompetencyDomain d) => _all.Add(d);
|
||||
public List<CompetencyDomain> GetBySubjectAndGrade(Guid subjectId, int gradeLevel) =>
|
||||
_all.Where(d => d.SubjectId == subjectId && d.GradeLevel == gradeLevel)
|
||||
public List<CompetencyDomain> GetBySubjectAndGrade(Guid subjectId, int gradeLevel, Guid versionId) =>
|
||||
_all.Where(d => d.SubjectId == subjectId && d.GradeLevel == gradeLevel && d.VersionId == versionId)
|
||||
.OrderBy(d => d.SortOrder).ToList();
|
||||
public List<CompetencyDomain> GetBySubjectAndVersion(Guid subjectId, Guid versionId) =>
|
||||
_all.Where(d => d.SubjectId == subjectId && d.VersionId == versionId)
|
||||
.OrderBy(d => d.GradeLevel).ThenBy(d => d.SortOrder).ToList();
|
||||
public List<CompetencyDomain> GetAll() => _all.ToList();
|
||||
public CompetencyDomain? GetById(Guid id) => _all.FirstOrDefault(d => d.Id == id);
|
||||
public void Save(CompetencyDomain domain) { _all.RemoveAll(d => d.Id == domain.Id); _all.Add(domain); }
|
||||
public void Delete(Guid id) => _all.RemoveAll(d => d.Id == id);
|
||||
public void DeleteBySubjectAndGrade(Guid subjectId, int gradeLevel) =>
|
||||
_all.RemoveAll(d => d.SubjectId == subjectId && d.GradeLevel == gradeLevel);
|
||||
public void ReplaceForSubjectAndGrade(Guid subjectId, int gradeLevel, List<CompetencyDomain> domains)
|
||||
public void DeleteBySubjectGradeAndVersion(Guid subjectId, int gradeLevel, Guid versionId) =>
|
||||
_all.RemoveAll(d => d.SubjectId == subjectId && d.GradeLevel == gradeLevel && d.VersionId == versionId);
|
||||
public void ReplaceForSubjectGradeAndVersion(Guid subjectId, int gradeLevel, Guid versionId, List<CompetencyDomain> domains)
|
||||
{
|
||||
DeleteBySubjectAndGrade(subjectId, gradeLevel);
|
||||
DeleteBySubjectGradeAndVersion(subjectId, gradeLevel, versionId);
|
||||
foreach (var d in domains) { d.SubjectId = subjectId; d.GradeLevel = gradeLevel; d.VersionId = versionId; }
|
||||
_all.AddRange(domains);
|
||||
}
|
||||
}
|
||||
|
||||
public class FakeCompetencyCatalogVersions : ICompetencyCatalogVersionRepository
|
||||
{
|
||||
private readonly List<CompetencyCatalogVersion> _all = [];
|
||||
public void Add(CompetencyCatalogVersion v) => _all.Add(v);
|
||||
public List<CompetencyCatalogVersion> GetBySubject(Guid subjectId) =>
|
||||
_all.Where(v => v.SubjectId == subjectId).OrderBy(v => v.SortOrder).ToList();
|
||||
public CompetencyCatalogVersion? GetById(Guid id) => _all.FirstOrDefault(v => v.Id == id);
|
||||
public CompetencyCatalogVersion GetOrCreateDefault(Guid subjectId)
|
||||
{
|
||||
var existing = GetBySubject(subjectId).FirstOrDefault(v => v.IsDefault);
|
||||
if (existing is not null) return existing;
|
||||
var version = new CompetencyCatalogVersion { SubjectId = subjectId, Name = "Bestehender Kompetenzkatalog", IsDefault = true };
|
||||
Save(version);
|
||||
return version;
|
||||
}
|
||||
public void Save(CompetencyCatalogVersion version)
|
||||
{
|
||||
if (version.IsDefault)
|
||||
foreach (var other in _all.Where(v => v.SubjectId == version.SubjectId && v.Id != version.Id)) other.IsDefault = false;
|
||||
_all.RemoveAll(v => v.Id == version.Id);
|
||||
_all.Add(version);
|
||||
}
|
||||
public void Delete(Guid id)
|
||||
{
|
||||
var version = _all.FirstOrDefault(v => v.Id == id);
|
||||
if (version is null) return;
|
||||
if (version.IsDefault)
|
||||
throw new InvalidOperationException("Die Standardversion eines Fachs kann nicht gelöscht werden. Erst eine andere Version als Standard setzen.");
|
||||
_all.RemoveAll(v => v.Id == id);
|
||||
}
|
||||
}
|
||||
|
||||
public class FakeShorthandCodes(List<ShorthandCode> all) : IShorthandCodeRepository
|
||||
{
|
||||
public List<ShorthandCode> GetAll() => all;
|
||||
@@ -525,6 +592,19 @@ public class FakeUntisCacheFetchStates : IUntisCacheFetchStateRepository
|
||||
}
|
||||
}
|
||||
|
||||
public class FakeUntisHubJobStates : IUntisHubJobStateRepository
|
||||
{
|
||||
private readonly List<UntisHubJobState> _all = [];
|
||||
public UntisHubJobState? Get(UntisHubJobKind kind, Guid? groupId) =>
|
||||
_all.FirstOrDefault(s => s.Kind == kind && s.GroupId == groupId);
|
||||
public List<UntisHubJobState> GetAll() => _all.ToList();
|
||||
public void Save(UntisHubJobState state)
|
||||
{
|
||||
_all.RemoveAll(s => s.Kind == state.Kind && s.GroupId == state.GroupId);
|
||||
_all.Add(state);
|
||||
}
|
||||
}
|
||||
|
||||
public class FakeWorkTasks : IWorkTaskRepository
|
||||
{
|
||||
private readonly List<WorkTask> _all = [];
|
||||
@@ -565,3 +645,28 @@ public class FakeReportGrades : IReportGradeRepository
|
||||
}
|
||||
public void Delete(Guid id) => _all.RemoveAll(r => r.Id == id);
|
||||
}
|
||||
|
||||
/// <summary>Fake für MCP-Write-Tool-Tests (Phase 2): antwortet ohne echtes UI, konfigurierbar über
|
||||
/// <see cref="Response"/>, merkt sich Titel/Nachricht des letzten Aufrufs zur Prüfung, dass der
|
||||
/// Bestätigungstext tatsächlich menschenlesbar ist (kein rohes JSON/GUID-Dump).</summary>
|
||||
public class FakeMcpConfirmation : IMcpConfirmationService
|
||||
{
|
||||
public bool Response { get; set; } = true;
|
||||
public string? LastTitle { get; private set; }
|
||||
public string? LastMessage { get; private set; }
|
||||
public int CallCount { get; private set; }
|
||||
|
||||
public string? LastOperationKey { get; private set; }
|
||||
public bool? LastAllowSessionTrust { get; private set; }
|
||||
|
||||
public Task<bool> ConfirmAsync(string title, string message, CancellationToken ct,
|
||||
[System.Runtime.CompilerServices.CallerMemberName] string operationKey = "", bool allowSessionTrust = true)
|
||||
{
|
||||
CallCount++;
|
||||
LastTitle = title;
|
||||
LastMessage = message;
|
||||
LastOperationKey = operationKey;
|
||||
LastAllowSessionTrust = allowSessionTrust;
|
||||
return Task.FromResult(Response);
|
||||
}
|
||||
}
|
||||
@@ -21,12 +21,12 @@ public sealed class GroupDetailViewModelTests
|
||||
new GroupOverviewViewModel(new FakeLessons(), exams, new FakeResults(), new FakeSessions([]), new FakeEntries(), students,
|
||||
new FakeDocumentation(), tasks, groups, new AttendanceBalanceService(), new GradingService(), new SchoolYearService()),
|
||||
new ParticipationTabViewModel(new FakeSessions([]), new FakeEntries(), new FakeAspects(),
|
||||
students, memberships, groups, new FakeCompetencyDomains()),
|
||||
students, memberships, groups, new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions()),
|
||||
new GradeOverviewTabViewModel(grades, exams, new FakeResults(), students, memberships, new GradingService()),
|
||||
new PlanningTabViewModel(new FakeUnits(), new FakeLessons(), groups, subjects,
|
||||
new FakeCompetencyDomains(), TestSupport.BuildAiSettingsService(), new FakeSessions([])),
|
||||
new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions(), TestSupport.BuildAiSettingsService(), new FakeSessions([])),
|
||||
new CompetencyOverviewTabViewModel(new FakeUnits(), exams, new FakeResults(),
|
||||
new FakeCompetencyDomains(), students, new CompetencyAnalysisService()),
|
||||
new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions(), students, new CompetencyAnalysisService()),
|
||||
new SeatingPlanTabViewModel(new FakeSeatingPlans(), students, memberships,
|
||||
new FakeSessions([]), new FakeEntries(), new FakeAspects()),
|
||||
new GroupDocumentationTabViewModel(new FakeDocumentation(), students, groups));
|
||||
|
||||
@@ -10,6 +10,33 @@ namespace LehrerApp.Desktop.Tests;
|
||||
/// zusammen, was Planung/Klausuren/Mitarbeit/Dokumentation ohnehin schon verwalten.
|
||||
public sealed class GroupOverviewViewModelTests
|
||||
{
|
||||
[Fact]
|
||||
public void UnterrichtHeute_BietetNurHeutigeNichtAusgefalleneStundenUndOeffnetAuswahl()
|
||||
{
|
||||
var group = new LearningGroup { IsActive = true };
|
||||
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||
var lessons = new FakeLessons();
|
||||
var first = new Lesson { GroupId = group.Id, Date = today, Topic = "Erste Stunde" };
|
||||
var second = new Lesson { GroupId = group.Id, Date = today, Topic = "Zweite Stunde" };
|
||||
lessons.Add(first);
|
||||
lessons.Add(second);
|
||||
lessons.Add(new Lesson { GroupId = group.Id, Date = today, Status = LessonStatus.Cancelled });
|
||||
lessons.Add(new Lesson { GroupId = group.Id, Date = today.AddDays(1) });
|
||||
lessons.Add(new Lesson { GroupId = Guid.NewGuid(), Date = today });
|
||||
var vm = NewVm(lessons: lessons, groups: new FakeGroups([group]));
|
||||
vm.Initialize(group.Id, group.Name);
|
||||
Assert.True(vm.HasTodayLessons);
|
||||
Assert.Equal(2, vm.TodayLessons.Count);
|
||||
Lesson? opened = null;
|
||||
vm.OnOpenTeachingMode = lesson => opened = lesson;
|
||||
vm.SelectedTeachingLesson = second;
|
||||
vm.StartTeachingModeCommand.Execute(null);
|
||||
Assert.Same(second, opened);
|
||||
group.IsActive = false;
|
||||
vm.Refresh();
|
||||
Assert.False(vm.HasTodayLessons);
|
||||
}
|
||||
|
||||
private static GroupOverviewViewModel NewVm(FakeLessons? lessons = null, FakeExams? exams = null,
|
||||
FakeSessions? sessions = null, FakeEntries? entries = null, FakeStudents? students = null,
|
||||
FakeDocumentation? documentation = null, FakeWorkTasks? tasks = null,
|
||||
|
||||
@@ -254,7 +254,7 @@ public sealed class HazardAssessmentWizardViewModelTests
|
||||
aiSettings.SetEnabled(true);
|
||||
aiSettings.SetCredentialsAndToken("sebastian", "token-abc");
|
||||
var ai = new AiPlanningService(new HttpClient(), new FakeLessons(), new FakeGroups([]),
|
||||
new FakeSubjects([]), new FakeCompetencyDomains(), new FakeAlternativeLessonPaths([]));
|
||||
new FakeSubjects([]), new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions(), new FakeAlternativeLessonPaths([]));
|
||||
var unit = new Unit { Title = "Redoxreaktionen" };
|
||||
var lesson = new Lesson { Topic = "Natrium in Wasser" };
|
||||
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Desktop.ViewModels.Groups;
|
||||
using Xunit;
|
||||
|
||||
namespace LehrerApp.Desktop.Tests;
|
||||
|
||||
/// Deckt die Kandidatensuche für den "Vorhandene Stunde verknüpfen"-Button im Stunden-anlegen-
|
||||
/// Dialog ab (Nutzer-Feedback: per JSON-Import/KI ohne Stundennummer angelegte Stunden tauchen im
|
||||
/// Stundenplan nicht auf, da der dort verwendete FindLessonForSlot per Datum+Stundennummer sucht).
|
||||
public class LessonFixItSearchTests
|
||||
{
|
||||
[Fact]
|
||||
public void FindCandidates_FindetVerwaisteStundeOhneStundennummerAmSelbenTag()
|
||||
{
|
||||
var lessons = new FakeLessons();
|
||||
var groupId = Guid.NewGuid();
|
||||
var unitId = Guid.NewGuid();
|
||||
var date = new DateOnly(2026, 9, 8);
|
||||
var orphan = new Lesson { UnitId = unitId, GroupId = groupId, Date = date, LessonNumber = null, Topic = "Reflexionsgesetz" };
|
||||
lessons.Add(orphan);
|
||||
|
||||
var candidates = LessonFixItSearch.FindCandidates(lessons, groupId, date);
|
||||
|
||||
var found = Assert.Single(candidates);
|
||||
Assert.Equal(orphan.Id, found.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FindCandidates_FindetStundeAmSelbenTagMitAbweichenderStundennummer()
|
||||
{
|
||||
var lessons = new FakeLessons();
|
||||
var groupId = Guid.NewGuid();
|
||||
var unitId = Guid.NewGuid();
|
||||
var date = new DateOnly(2026, 9, 8);
|
||||
var wrongPeriod = new Lesson { UnitId = unitId, GroupId = groupId, Date = date, LessonNumber = 7, Topic = "Reflexionsgesetz" };
|
||||
lessons.Add(wrongPeriod);
|
||||
|
||||
var candidates = LessonFixItSearch.FindCandidates(lessons, groupId, date);
|
||||
|
||||
var found = Assert.Single(candidates);
|
||||
Assert.Equal(wrongPeriod.Id, found.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FindCandidates_SortiertExaktesDatumVorNahenTerminenOhneStundennummer()
|
||||
{
|
||||
var lessons = new FakeLessons();
|
||||
var groupId = Guid.NewGuid();
|
||||
var unitId = Guid.NewGuid();
|
||||
var date = new DateOnly(2026, 9, 8);
|
||||
var near = new Lesson { UnitId = unitId, GroupId = groupId, Date = date.AddDays(-2), LessonNumber = null, Topic = "Nah" };
|
||||
var exact = new Lesson { UnitId = unitId, GroupId = groupId, Date = date, LessonNumber = null, Topic = "Exakt" };
|
||||
lessons.Add(near); lessons.Add(exact);
|
||||
|
||||
var candidates = LessonFixItSearch.FindCandidates(lessons, groupId, date);
|
||||
|
||||
Assert.Equal(2, candidates.Count);
|
||||
Assert.Equal(exact.Id, candidates[0].Id);
|
||||
Assert.Equal(near.Id, candidates[1].Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FindCandidates_IgnoriertStundenAusserhalbDesZeitfenstersUndAnderenGruppen()
|
||||
{
|
||||
var lessons = new FakeLessons();
|
||||
var groupId = Guid.NewGuid();
|
||||
var otherGroupId = Guid.NewGuid();
|
||||
var unitId = Guid.NewGuid();
|
||||
var date = new DateOnly(2026, 9, 8);
|
||||
lessons.Add(new Lesson { UnitId = unitId, GroupId = groupId, Date = date.AddDays(-30), LessonNumber = null, Topic = "Zu weit weg" });
|
||||
lessons.Add(new Lesson { UnitId = unitId, GroupId = otherGroupId, Date = date, LessonNumber = null, Topic = "Andere Gruppe" });
|
||||
// Gesetzte Stundennummer, aber exakt am gesuchten Datum — bewusst als Kandidat enthalten
|
||||
// (z.B. falsch nummerierter Import); der Nutzer entscheidet im Bestätigungs-/
|
||||
// Auswahldialog, ob sie passt.
|
||||
lessons.Add(new Lesson { UnitId = unitId, GroupId = groupId, Date = date, LessonNumber = 3, Topic = "Falsch nummeriert, aber am gesuchten Tag" });
|
||||
|
||||
var candidates = LessonFixItSearch.FindCandidates(lessons, groupId, date);
|
||||
|
||||
var found = Assert.Single(candidates);
|
||||
Assert.Equal("Falsch nummeriert, aber am gesuchten Tag", found.Topic);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FindCandidates_LeerOhnePassendeStunde()
|
||||
{
|
||||
var lessons = new FakeLessons();
|
||||
var groupId = Guid.NewGuid();
|
||||
var date = new DateOnly(2026, 9, 8);
|
||||
|
||||
var candidates = LessonFixItSearch.FindCandidates(lessons, groupId, date);
|
||||
|
||||
Assert.Empty(candidates);
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,39 @@ public sealed class LessonSchedulingServiceTests
|
||||
Assert.Equal(new DateOnly(2026, 9, 4), conducted.Date);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Move_RuecktAuchAusgefalleneFolgestundenNichtNach()
|
||||
{
|
||||
var unitId = Guid.NewGuid();
|
||||
var groupId = Guid.NewGuid();
|
||||
var moved = new Lesson { UnitId = unitId, GroupId = groupId, Date = new(2026, 9, 1) };
|
||||
var cancelledFollowing = new Lesson { UnitId = unitId, GroupId = groupId, Date = new(2026, 9, 4), Status = LessonStatus.Cancelled };
|
||||
var repo = new FakeLessons();
|
||||
repo.Add(moved); repo.Add(cancelledFollowing);
|
||||
|
||||
new LessonSchedulingService(repo).Move(moved, new(2026, 9, 8), null, shiftFollowing: true);
|
||||
|
||||
Assert.Equal(new DateOnly(2026, 9, 4), cancelledFollowing.Date);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SplitAndMoveSecondPart_AusgefalleneQuellstundeSetztFortsetzungAufEntwurfZurueck()
|
||||
{
|
||||
var source = new Lesson
|
||||
{
|
||||
UnitId = Guid.NewGuid(), GroupId = Guid.NewGuid(), Date = new(2026, 9, 1),
|
||||
Status = LessonStatus.Cancelled,
|
||||
Phases = [new LessonPhaseStep { Name = "Einstieg", DurationMinutes = 60 }],
|
||||
};
|
||||
var repo = new FakeLessons();
|
||||
repo.Add(source);
|
||||
|
||||
var continuation = new LessonSchedulingService(repo).SplitAndMoveSecondPart(source, 30,
|
||||
new(2026, 9, 3), 1, null);
|
||||
|
||||
Assert.Equal(LessonStatus.Draft, continuation.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SplitAndMoveSecondPart_TeiltAuchEineUeberDieGrenzeLaufendePhase()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Desktop.ViewModels.Groups;
|
||||
using Xunit;
|
||||
|
||||
namespace LehrerApp.Desktop.Tests;
|
||||
|
||||
public sealed class LessonStatusDisplayTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(LessonStatus.Draft, "Entwurf")]
|
||||
[InlineData(LessonStatus.Ready, "Bereit")]
|
||||
[InlineData(LessonStatus.Conducted, "Durchgeführt")]
|
||||
[InlineData(LessonStatus.Cancelled, "Ausgefallen")]
|
||||
[InlineData(LessonStatus.Planned, "Geplant")]
|
||||
public void ToName_FromName_RoundTrip(LessonStatus status, string expectedName)
|
||||
{
|
||||
Assert.Equal(expectedName, LessonStatusDisplay.ToName(status));
|
||||
Assert.Equal(status, LessonStatusDisplay.FromName(expectedName));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UnitSummary_AusgefalleneStundenZaehlenWederAlsGehaltenNochAlsPensum()
|
||||
{
|
||||
var unit = new Unit { Title = "Optik" };
|
||||
var lessons = new List<Lesson>
|
||||
{
|
||||
new() { Status = LessonStatus.Conducted },
|
||||
new() { Status = LessonStatus.Cancelled },
|
||||
new() { Status = LessonStatus.Ready },
|
||||
};
|
||||
|
||||
var summary = new UnitSummary(unit, lessons);
|
||||
|
||||
Assert.Equal(2, summary.TotalCount);
|
||||
Assert.Equal(1, summary.ConductedCount);
|
||||
Assert.Equal(0.5, summary.ProgressFraction);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Desktop.Services.Mcp.Tools;
|
||||
using LehrerApp.Templating;
|
||||
using Xunit;
|
||||
|
||||
namespace LehrerApp.Desktop.Tests;
|
||||
|
||||
public sealed class LetterTemplateToolsTests : IDisposable
|
||||
{
|
||||
private readonly string _directory = Path.Combine(Path.GetTempPath(), $"lehrerapp-lettertools-tests-{Guid.NewGuid():N}");
|
||||
public LetterTemplateToolsTests() => Directory.CreateDirectory(_directory);
|
||||
public void Dispose() { if (Directory.Exists(_directory)) Directory.Delete(_directory, true); }
|
||||
|
||||
private LetterTemplateTools BuildTool(TemplateStore store, FakeStudents? students = null, FakeGroups? groups = null) =>
|
||||
new(store, new TemplateLoader(), new QuestTemplateRenderer(), students ?? new FakeStudents([]), groups ?? new FakeGroups([]));
|
||||
|
||||
private TemplateStore StoreWithTemplate(string name, params PlaceholderDefinition[] definitions)
|
||||
{
|
||||
var source = Path.Combine(_directory, $"{Guid.NewGuid():N}.lavorlage");
|
||||
var manifest = new TemplateManifest { Id = $"brief-{Guid.NewGuid():N}", Name = name, Placeholders = [.. definitions] };
|
||||
var lines = new List<string> { "PAGE 210 297 mm" };
|
||||
var y = 20;
|
||||
foreach (var definition in definitions)
|
||||
{
|
||||
var element = definition.Type == PlaceholderType.Multiline ? "TEXTBOX" : "TEXT";
|
||||
lines.Add(element == "TEXTBOX" ? $"TEXTBOX 20 {y} 170 80 ${definition.Name}" : $"TEXT 20 {y} ${definition.Name}");
|
||||
y += 20;
|
||||
}
|
||||
TemplatePackage.Create(source, manifest, string.Join('\n', lines), new Dictionary<string, byte[]>());
|
||||
var store = new TemplateStore(Path.Combine(_directory, $"store-{Guid.NewGuid():N}"));
|
||||
store.Import(source);
|
||||
return store;
|
||||
}
|
||||
|
||||
private static Student StudentWithContact(string? salutation = "Sehr geehrte Frau Muster,") => new()
|
||||
{
|
||||
FirstName = "Lena", LastName = "Beispiel",
|
||||
Contacts = [new Contact
|
||||
{
|
||||
Name = "Frau Muster", Relation = "Mutter", LetterSalutation = salutation,
|
||||
Street = "Hauptstraße 1", PostalCode = "12345", City = "Musterstadt",
|
||||
}],
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void ListLetterTemplates_ListetVorlageMitPlatzhaltern()
|
||||
{
|
||||
var store = StoreWithTemplate("Elternbrief", new PlaceholderDefinition("Anrede", PlaceholderType.Text, true));
|
||||
var tool = BuildTool(store);
|
||||
|
||||
var result = Assert.Single(tool.ListLetterTemplates());
|
||||
|
||||
Assert.Equal("Elternbrief", result.Name);
|
||||
Assert.Contains(result.Placeholders, p => p.Name == "Anrede" && p.Required);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderLetter_UnbekannteVorlage_LiefertFehler()
|
||||
{
|
||||
var student = StudentWithContact();
|
||||
var tool = BuildTool(new TemplateStore(_directory), new FakeStudents([student]));
|
||||
|
||||
var result = tool.RenderLetter("nicht-vorhanden", student.Id, "Text", "Frau Lehrer");
|
||||
|
||||
Assert.False(result.Success);
|
||||
Assert.Null(result.Base64Pdf);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderLetter_UnbekannterSchueler_LiefertFehler()
|
||||
{
|
||||
var store = StoreWithTemplate("Elternbrief", new PlaceholderDefinition("Anrede", PlaceholderType.Text, true));
|
||||
var installed = Assert.Single(store.GetTemplates());
|
||||
var tool = BuildTool(store);
|
||||
|
||||
var result = tool.RenderLetter(installed.Id, Guid.NewGuid(), "Text", "Frau Lehrer");
|
||||
|
||||
Assert.False(result.Success);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderLetter_PflichtplatzhalterFehlt_LiefertFehlerOhnePdf()
|
||||
{
|
||||
var store = StoreWithTemplate("Elternbrief", new PlaceholderDefinition("Anrede", PlaceholderType.Text, true));
|
||||
var installed = Assert.Single(store.GetTemplates());
|
||||
var student = StudentWithContact(salutation: null); // keine Anrede hinterlegt
|
||||
var tool = BuildTool(store, new FakeStudents([student]));
|
||||
|
||||
var result = tool.RenderLetter(installed.Id, student.Id, "Text", "Frau Lehrer");
|
||||
|
||||
Assert.False(result.Success);
|
||||
Assert.Contains("Anrede", result.Message);
|
||||
Assert.Null(result.Base64Pdf);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderLetter_VollstaendigeDaten_LiefertBase64Pdf()
|
||||
{
|
||||
var store = StoreWithTemplate("Elternbrief",
|
||||
new PlaceholderDefinition("Anrede", PlaceholderType.Text, true),
|
||||
new PlaceholderDefinition("Datum", PlaceholderType.Date, true),
|
||||
new PlaceholderDefinition("Brieftext", PlaceholderType.Multiline, true));
|
||||
var installed = Assert.Single(store.GetTemplates());
|
||||
var student = StudentWithContact();
|
||||
var tool = BuildTool(store, new FakeStudents([student]));
|
||||
|
||||
var result = tool.RenderLetter(installed.Id, student.Id, "Dies ist der Inhalt.", "Frau Lehrer");
|
||||
|
||||
Assert.True(result.Success);
|
||||
Assert.NotNull(result.Base64Pdf);
|
||||
var bytes = Convert.FromBase64String(result.Base64Pdf!);
|
||||
Assert.Equal("%PDF", System.Text.Encoding.ASCII.GetString(bytes, 0, 4));
|
||||
Assert.Equal("Elternbrief_Beispiel_Lena.pdf", result.SuggestedFileName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderLetter_ExtraValues_FuelltZusaetzlichenPlatzhalter()
|
||||
{
|
||||
var store = StoreWithTemplate("Elternbrief",
|
||||
new PlaceholderDefinition("Anrede", PlaceholderType.Text, true),
|
||||
new PlaceholderDefinition("Betreff", PlaceholderType.Text, true));
|
||||
var installed = Assert.Single(store.GetTemplates());
|
||||
var student = StudentWithContact();
|
||||
var tool = BuildTool(store, new FakeStudents([student]));
|
||||
|
||||
var result = tool.RenderLetter(installed.Id, student.Id, "Text", "Frau Lehrer",
|
||||
extraValues: new Dictionary<string, string> { ["Betreff"] = "Elternabend" });
|
||||
|
||||
Assert.True(result.Success);
|
||||
Assert.NotNull(result.Base64Pdf);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
using System.Text.Json.Nodes;
|
||||
using LehrerApp.Desktop.Services.Mcp;
|
||||
using Xunit;
|
||||
|
||||
namespace LehrerApp.Desktop.Tests;
|
||||
|
||||
public sealed class McpClientRegistrationServiceTests : IDisposable
|
||||
{
|
||||
private readonly string _directory = Path.Combine(Path.GetTempPath(), $"lehrerapp-mcpreg-tests-{Guid.NewGuid():N}");
|
||||
public McpClientRegistrationServiceTests() => Directory.CreateDirectory(_directory);
|
||||
public void Dispose() { if (Directory.Exists(_directory)) Directory.Delete(_directory, true); }
|
||||
|
||||
private string ConfigPath => Path.Combine(_directory, "claude_desktop_config.json");
|
||||
|
||||
private string BuildFakeBridge()
|
||||
{
|
||||
var bridgePath = Path.Combine(_directory, "LehrerApp.McpBridge.exe");
|
||||
File.WriteAllText(bridgePath, "fake");
|
||||
return bridgePath;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Register_OhneBridgeDatei_LiefertFehlerUndSchreibtNichts()
|
||||
{
|
||||
var service = new McpClientRegistrationService(ConfigPath, Path.Combine(_directory, "fehlt.exe"));
|
||||
|
||||
var result = service.Register();
|
||||
|
||||
Assert.False(result.Success);
|
||||
Assert.False(File.Exists(ConfigPath));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Register_OhneBestehendeKonfiguration_LegtDateiMitEintragAn()
|
||||
{
|
||||
var bridgePath = BuildFakeBridge();
|
||||
var service = new McpClientRegistrationService(ConfigPath, bridgePath);
|
||||
|
||||
var result = service.Register();
|
||||
|
||||
Assert.True(result.Success);
|
||||
Assert.True(service.IsRegistered());
|
||||
var root = JsonNode.Parse(File.ReadAllText(ConfigPath))!;
|
||||
Assert.Equal(bridgePath, root["mcpServers"]!["lehrerapp"]!["command"]!.GetValue<string>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Register_BestehendeKonfigurationMitAnderenServern_BleibtErhalten()
|
||||
{
|
||||
File.WriteAllText(ConfigPath, """{"mcpServers":{"andererServer":{"command":"foo"}},"globalShortcut":"Ctrl+X"}""");
|
||||
var bridgePath = BuildFakeBridge();
|
||||
var service = new McpClientRegistrationService(ConfigPath, bridgePath);
|
||||
|
||||
var result = service.Register();
|
||||
|
||||
Assert.True(result.Success);
|
||||
var root = JsonNode.Parse(File.ReadAllText(ConfigPath))!;
|
||||
Assert.Equal("foo", root["mcpServers"]!["andererServer"]!["command"]!.GetValue<string>());
|
||||
Assert.Equal("Ctrl+X", root["globalShortcut"]!.GetValue<string>());
|
||||
Assert.Equal(bridgePath, root["mcpServers"]!["lehrerapp"]!["command"]!.GetValue<string>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Register_KaputteBestehendeKonfiguration_WirdNichtUeberschrieben()
|
||||
{
|
||||
File.WriteAllText(ConfigPath, "{ das ist kein json");
|
||||
var bridgePath = BuildFakeBridge();
|
||||
var service = new McpClientRegistrationService(ConfigPath, bridgePath);
|
||||
|
||||
var result = service.Register();
|
||||
|
||||
Assert.False(result.Success);
|
||||
Assert.Equal("{ das ist kein json", File.ReadAllText(ConfigPath));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Unregister_EntferntNurEigenenEintrag()
|
||||
{
|
||||
File.WriteAllText(ConfigPath, """{"mcpServers":{"andererServer":{"command":"foo"},"lehrerapp":{"command":"bar"}}}""");
|
||||
var service = new McpClientRegistrationService(ConfigPath, BuildFakeBridge());
|
||||
|
||||
var result = service.Unregister();
|
||||
|
||||
Assert.True(result.Success);
|
||||
Assert.False(service.IsRegistered());
|
||||
Assert.Contains("andererServer", File.ReadAllText(ConfigPath));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsRegistered_OhneDatei_IstFalse()
|
||||
{
|
||||
var service = new McpClientRegistrationService(ConfigPath, BuildFakeBridge());
|
||||
|
||||
Assert.False(service.IsRegistered());
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,7 @@ public sealed class ParticipationSessionEditingTests
|
||||
Date = new DateOnly(2026, 8, 19),
|
||||
Comment = "Sitzplan",
|
||||
LessonId = Guid.NewGuid(),
|
||||
CompetencyCodes = ["K1"],
|
||||
Competencies = [new CompetencyReference { ItemId = Guid.NewGuid(), Code = "K1", Description = "Kompetenz" }],
|
||||
};
|
||||
var vm = new AddSessionDialogViewModel(session)
|
||||
{
|
||||
@@ -29,7 +29,7 @@ public sealed class ParticipationSessionEditingTests
|
||||
Assert.Equal(new DateOnly(2026, 8, 20), session.Date);
|
||||
Assert.Equal("Elektrische Stromkreise", session.Comment);
|
||||
Assert.NotNull(session.LessonId);
|
||||
Assert.Equal(["K1"], session.CompetencyCodes);
|
||||
Assert.Equal(["K1"], session.Competencies.Select(c => c.Code));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -45,7 +45,7 @@ public sealed class ParticipationSessionEditingTests
|
||||
var sessions = new FakeSessions([session]);
|
||||
var vm = new ParticipationTabViewModel(
|
||||
sessions, new FakeEntries(), new FakeAspects(), new FakeStudents([]),
|
||||
new FakeMemberships([]), new FakeGroups([group]), new FakeCompetencyDomains());
|
||||
new FakeMemberships([]), new FakeGroups([group]), new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions());
|
||||
vm.OnEditSession = existing =>
|
||||
{
|
||||
existing.Comment = "Nachbesprechung Elektrizität";
|
||||
@@ -70,7 +70,7 @@ public sealed class ParticipationSessionEditingTests
|
||||
entries.Add(new ParticipationEntry { SessionId = session.Id, StudentId = Guid.NewGuid() });
|
||||
var vm = new ParticipationTabViewModel(
|
||||
sessions, entries, new FakeAspects(), new FakeStudents([]),
|
||||
new FakeMemberships([]), new FakeGroups([group]), new FakeCompetencyDomains());
|
||||
new FakeMemberships([]), new FakeGroups([group]), new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions());
|
||||
vm.Initialize(group.Id, group.SchoolYear);
|
||||
vm.SelectedSession = vm.Sessions.Single(s => s.Id == session.Id);
|
||||
|
||||
@@ -87,6 +87,49 @@ public sealed class ParticipationSessionEditingTests
|
||||
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]
|
||||
public async Task LoeschenBefehl_BrichtBeiAbgelehnterBestaetigungAb()
|
||||
{
|
||||
@@ -95,7 +138,7 @@ public sealed class ParticipationSessionEditingTests
|
||||
var sessions = new FakeSessions([session]);
|
||||
var vm = new ParticipationTabViewModel(
|
||||
sessions, new FakeEntries(), new FakeAspects(), new FakeStudents([]),
|
||||
new FakeMemberships([]), new FakeGroups([group]), new FakeCompetencyDomains());
|
||||
new FakeMemberships([]), new FakeGroups([group]), new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions());
|
||||
vm.Initialize(group.Id, group.SchoolYear);
|
||||
vm.SelectedSession = vm.Sessions.Single(s => s.Id == session.Id);
|
||||
vm.OnConfirmDeleteSession = (_, _) => Task.FromResult(false);
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Desktop.ViewModels.Groups;
|
||||
using LehrerApp.Templating;
|
||||
using Xunit;
|
||||
|
||||
namespace LehrerApp.Desktop.Tests;
|
||||
|
||||
public sealed class PersonalizeWorksheetDialogViewModelTests : IDisposable
|
||||
{
|
||||
private readonly string _directory = Path.Combine(Path.GetTempPath(), $"lehrerapp-worksheet-vm-tests-{Guid.NewGuid():N}");
|
||||
public PersonalizeWorksheetDialogViewModelTests() => Directory.CreateDirectory(_directory);
|
||||
|
||||
[Fact]
|
||||
public void Generate_ErzeugtEinePdfJeAusgewaehltemSchueler()
|
||||
{
|
||||
var group = new LearningGroup { Name = "8a", SchoolYear = "2025/26" };
|
||||
var anna = new Student { FirstName = "Anna", LastName = "Adler" };
|
||||
var ben = new Student { FirstName = "Ben", LastName = "Bauer" };
|
||||
var vm = Build(group, [anna, ben], StoreWithTemplate());
|
||||
var output = Path.Combine(_directory, "output");
|
||||
|
||||
vm.Generate(output);
|
||||
|
||||
Assert.Equal(2, vm.Results.Count);
|
||||
Assert.All(vm.Results, r => Assert.True(r.Success));
|
||||
Assert.Equal(2, Directory.GetFiles(output, "*.pdf").Length);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Generate_AbgewaehlterSchueler_WirdUebersprungen()
|
||||
{
|
||||
var group = new LearningGroup { Name = "8a", SchoolYear = "2025/26" };
|
||||
var anna = new Student { FirstName = "Anna", LastName = "Adler" };
|
||||
var ben = new Student { FirstName = "Ben", LastName = "Bauer" };
|
||||
var vm = Build(group, [anna, ben], StoreWithTemplate());
|
||||
vm.Students.Single(s => s.Model.Id == ben.Id).IsIncluded = false;
|
||||
var output = Path.Combine(_directory, "output");
|
||||
|
||||
vm.Generate(output);
|
||||
|
||||
Assert.Single(vm.Results);
|
||||
Assert.Equal(anna.FullName, vm.Results[0].StudentName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OhneVorlage_GenerateTutNichts()
|
||||
{
|
||||
var group = new LearningGroup { Name = "8a", SchoolYear = "2025/26" };
|
||||
var anna = new Student { FirstName = "Anna", LastName = "Adler" };
|
||||
var vm = Build(group, [anna], new WorksheetTemplateStore(new TemplateStore(Path.Combine(_directory, "empty-store"))));
|
||||
var output = Path.Combine(_directory, "output");
|
||||
|
||||
vm.Generate(output);
|
||||
|
||||
Assert.Empty(vm.Results);
|
||||
}
|
||||
|
||||
private static PersonalizeWorksheetDialogViewModel Build(LearningGroup group, List<Student> students, WorksheetTemplateStore store) =>
|
||||
new(group, [.. students.Select(s => s.Id)], new FakeStudents(students), store, new QuestTemplateRenderer());
|
||||
|
||||
private WorksheetTemplateStore StoreWithTemplate()
|
||||
{
|
||||
var source = Path.Combine(_directory, $"{Guid.NewGuid():N}.lavorlage");
|
||||
var manifest = new TemplateManifest
|
||||
{
|
||||
Id = $"arbeitsblatt-{Guid.NewGuid():N}", Name = "Arbeitsblatt",
|
||||
Placeholders = [new PlaceholderDefinition("Student.FirstName", PlaceholderType.Text)],
|
||||
};
|
||||
TemplatePackage.Create(source, manifest, "PAGE 210 297 mm\nTEXT 20 20 $Student.FirstName", new Dictionary<string, byte[]>());
|
||||
var store = new WorksheetTemplateStore(new TemplateStore(Path.Combine(_directory, $"store-{Guid.NewGuid():N}")));
|
||||
store.Store.Import(source);
|
||||
return store;
|
||||
}
|
||||
|
||||
public void Dispose() { if (Directory.Exists(_directory)) Directory.Delete(_directory, true); }
|
||||
}
|
||||
@@ -23,7 +23,11 @@ public sealed class PlanningExchangeServiceTests
|
||||
Title = "Optik",
|
||||
StartDate = new DateOnly(2026, 9, 1),
|
||||
EndDate = new DateOnly(2026, 10, 1),
|
||||
Competencies = ["UF1", "E4"],
|
||||
Competencies =
|
||||
[
|
||||
new CompetencyReference { ItemId = Guid.NewGuid(), Code = "UF1", Description = "" },
|
||||
new CompetencyReference { ItemId = Guid.NewGuid(), Code = "E4", Description = "" },
|
||||
],
|
||||
Status = UnitStatus.Active,
|
||||
Notes = "Experimente",
|
||||
};
|
||||
@@ -61,7 +65,11 @@ public sealed class PlanningExchangeServiceTests
|
||||
Assert.Equal(targetGroupId, result.Unit.GroupId);
|
||||
Assert.Equal("Optik", result.Unit.Title);
|
||||
Assert.Equal(UnitStatus.Active, result.Unit.Status);
|
||||
Assert.Equal(["UF1", "E4"], result.Unit.Competencies);
|
||||
// Codes werden exportiert/importiert (Momentaufnahme-Text), aber bewusst NICHT gegen den
|
||||
// Katalog der Zielinstallation aufgelöst - jede importierte Referenz bleibt ItemId=Guid.Empty
|
||||
// (siehe PlanningExchangeService-Klassenkommentar: nie interne IDs übertragen).
|
||||
Assert.Equal(["UF1", "E4"], result.Unit.Competencies.Select(c => c.Code));
|
||||
Assert.All(result.Unit.Competencies, c => Assert.Equal(Guid.Empty, c.ItemId));
|
||||
var importedLesson = Assert.Single(result.Lessons);
|
||||
Assert.NotEqual(sourceLesson.Id, importedLesson.Id);
|
||||
Assert.Equal(result.Unit.Id, importedLesson.UnitId);
|
||||
|
||||
@@ -20,7 +20,7 @@ public class PlanningTabViewModelTests
|
||||
var lessons = new FakeLessons();
|
||||
|
||||
var vm = new PlanningTabViewModel(units, lessons, groups, subjects, competencyDomains,
|
||||
TestSupport.BuildAiSettingsService(), new FakeSessions([]));
|
||||
new FakeCompetencyCatalogVersions(), TestSupport.BuildAiSettingsService(), new FakeSessions([]));
|
||||
vm.Initialize(groupId);
|
||||
|
||||
return (vm, units, lessons, groupId);
|
||||
@@ -45,6 +45,21 @@ public class PlanningTabViewModelTests
|
||||
Assert.Contains("2 / 3", summary.ProgressText);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Initialize_WaehltLaufendeEinheitAlsArbeitskontext()
|
||||
{
|
||||
var (vm, units, _, groupId) = BuildScenario();
|
||||
units.Add(new Unit { GroupId = groupId, Title = "Früher", Status = UnitStatus.Completed,
|
||||
StartDate = new DateOnly(2025, 8, 1) });
|
||||
var active = new Unit { GroupId = groupId, Title = "Aktuell", Status = UnitStatus.Active,
|
||||
StartDate = new DateOnly(2025, 9, 1) };
|
||||
units.Add(active);
|
||||
|
||||
vm.Initialize(groupId);
|
||||
|
||||
Assert.Equal(active.Id, vm.SelectedUnit?.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MoveLesson_MitNachrueckenVerschiebtNurGeplanteFolgestundenNachDemStichtag()
|
||||
{
|
||||
@@ -93,6 +108,30 @@ public class PlanningTabViewModelTests
|
||||
Assert.Equal(new DateOnly(2025, 9, 8), byUnit[l2.Id].Date); // unverändert
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangeLessonUnit_OrdnetStundeDerZieleinheitZuUndWaehltSieAus()
|
||||
{
|
||||
var (vm, units, lessons, groupId) = BuildScenario();
|
||||
var unitA = new Unit { GroupId = groupId, Title = "Mechanik" };
|
||||
var unitB = new Unit { GroupId = groupId, Title = "Optik" };
|
||||
units.Add(unitA); units.Add(unitB);
|
||||
var l1 = new Lesson { UnitId = unitA.Id, GroupId = groupId, Date = new DateOnly(2025, 9, 1), Status = LessonStatus.Planned, Topic = "1" };
|
||||
lessons.Add(l1);
|
||||
|
||||
vm.Initialize(groupId);
|
||||
vm.SelectedUnit = vm.Units.Single(u => u.Id == unitA.Id);
|
||||
vm.SelectedLesson = vm.Lessons.Single(l => l.Id == l1.Id);
|
||||
vm.OnPickUnitChange = _ => Task.FromResult<Unit?>(unitB);
|
||||
|
||||
await vm.ChangeLessonUnitCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.Empty(lessons.GetByUnit(unitA.Id));
|
||||
var moved = Assert.Single(lessons.GetByUnit(unitB.Id));
|
||||
Assert.Equal(l1.Id, moved.Id);
|
||||
Assert.Equal(unitB.Id, vm.SelectedUnit?.Id);
|
||||
Assert.Equal(l1.Id, vm.SelectedLesson?.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CopyUnit_ErhaeltAbstaendeUndSetztGroupIdAufZielgruppe()
|
||||
{
|
||||
@@ -238,7 +277,7 @@ public class PlanningTabViewModelTests
|
||||
var lessons = new FakeLessons();
|
||||
var sessions = new FakeSessions([]);
|
||||
var vm = new PlanningTabViewModel(units, lessons, groups, new FakeSubjects([]),
|
||||
new FakeCompetencyDomains(), TestSupport.BuildAiSettingsService(), sessions);
|
||||
new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions(), TestSupport.BuildAiSettingsService(), sessions);
|
||||
vm.Initialize(groupId);
|
||||
|
||||
var unit = new Unit { GroupId = groupId, Title = "Optik" };
|
||||
@@ -273,7 +312,7 @@ public class PlanningTabViewModelTests
|
||||
var lessons = new FakeLessons();
|
||||
var sessions = new FakeSessions([]);
|
||||
var vm = new PlanningTabViewModel(units, lessons, groups, new FakeSubjects([]),
|
||||
new FakeCompetencyDomains(), TestSupport.BuildAiSettingsService(), sessions);
|
||||
new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions(), TestSupport.BuildAiSettingsService(), sessions);
|
||||
vm.Initialize(groupId);
|
||||
|
||||
var unit = new Unit { GroupId = groupId, Title = "Optik" };
|
||||
@@ -294,4 +333,44 @@ public class PlanningTabViewModelTests
|
||||
Assert.Single(sessions.GetByGroup(groupId));
|
||||
Assert.Equal("Für diese Stunde existiert bereits eine Sitzung.", notified);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateParticipationSession_AndereStundeAmSelbenTagBereitsVerknuepft_LegtKeineZweiteSitzungAn()
|
||||
{
|
||||
// Nutzer-Feedback: eine dritte Stunde am selben Tag (z.B. Vertretung) soll die bereits
|
||||
// bestehende Sitzung des Tages weiterverwenden statt eine zweite anzulegen.
|
||||
var groupId = Guid.NewGuid();
|
||||
var group = new LearningGroup { Id = groupId, Name = "Testgruppe" };
|
||||
var groups = new FakeGroups([group]);
|
||||
var units = new FakeUnits();
|
||||
var lessons = new FakeLessons();
|
||||
var sessions = new FakeSessions([]);
|
||||
var vm = new PlanningTabViewModel(units, lessons, groups, new FakeSubjects([]),
|
||||
new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions(), TestSupport.BuildAiSettingsService(), sessions);
|
||||
vm.Initialize(groupId);
|
||||
|
||||
var unit = new Unit { GroupId = groupId, Title = "Optik" };
|
||||
units.Add(unit);
|
||||
var date = new DateOnly(2025, 9, 1);
|
||||
var doubleLesson = new Lesson
|
||||
{ UnitId = unit.Id, GroupId = groupId, Date = date, Topic = "Brechung" };
|
||||
var thirdLesson = new Lesson
|
||||
{ UnitId = unit.Id, GroupId = groupId, Date = date, Topic = "Vertretung" };
|
||||
lessons.Add(doubleLesson);
|
||||
lessons.Add(thirdLesson);
|
||||
|
||||
vm.RefreshPlanning(unit.Id, doubleLesson.Id);
|
||||
vm.SelectedLesson = vm.Lessons.Single(l => l.Id == doubleLesson.Id);
|
||||
vm.CreateParticipationSessionCommand.Execute(null);
|
||||
|
||||
string? notified = null;
|
||||
vm.OnNotify = m => notified = m;
|
||||
vm.RefreshPlanning(unit.Id, thirdLesson.Id);
|
||||
vm.SelectedLesson = vm.Lessons.Single(l => l.Id == thirdLesson.Id);
|
||||
vm.CreateParticipationSessionCommand.Execute(null);
|
||||
|
||||
var created = Assert.Single(sessions.GetByGroup(groupId));
|
||||
Assert.Equal(doubleLesson.Id, created.LessonId);
|
||||
Assert.Equal("Für diesen Tag existiert bereits eine Sitzung.", notified);
|
||||
}
|
||||
}
|
||||
@@ -78,4 +78,16 @@ public sealed class RatingCellTests
|
||||
var cell = new RatingCell(Guid.NewGuid(), "k", 2);
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -256,6 +256,30 @@ public sealed class SeatingPlanViewModelTests
|
||||
Assert.Single(sessions.GetByGroup(groupId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SelectOrCreateSessionForLesson_AndereStundeAmSelbenTagBereitsVerknuepft_LegtKeineZweiteSitzungAn()
|
||||
{
|
||||
// Nutzer-Feedback: eine dritte Stunde am selben Tag (z.B. durch Vertretung, eigene Lesson-
|
||||
// Id) soll die bereits bestehende Sitzung der Doppelstunde weiterverwenden statt eine
|
||||
// zweite, unabhängige Sitzung für denselben Tag anzulegen.
|
||||
var groupId = Guid.NewGuid();
|
||||
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||
var doubleLesson = new Lesson { GroupId = groupId, Date = today, Topic = "Redox" };
|
||||
var thirdLesson = new Lesson { GroupId = groupId, Date = today, Topic = "Vertretung" };
|
||||
var existingSession = new ParticipationSession
|
||||
{ GroupId = groupId, Date = today, LessonId = doubleLesson.Id, Comment = "Redox" };
|
||||
var sessions = new FakeSessions([existingSession]);
|
||||
var plan = new SeatingPlan { GroupId = groupId, Name = "Standard", Rows = 1, Columns = 1 };
|
||||
var vm = new SeatingPlanTabViewModel(new FakeSeatingPlans([plan]), new FakeStudents([]),
|
||||
new FakeMemberships([]), sessions, new FakeEntries(), new FakeAspects());
|
||||
vm.Initialize(groupId, isReadOnly: false);
|
||||
|
||||
vm.SelectOrCreateSessionForLesson(thirdLesson);
|
||||
|
||||
Assert.Equal(existingSession.Id, vm.SelectedSession?.Id);
|
||||
Assert.Single(sessions.GetByGroup(groupId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SelectOrCreateSessionForLesson_KeineSitzungVorhanden_LegtVerknuepfteAnUndWaehltSieAus()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Desktop.ViewModels.Groups;
|
||||
using Xunit;
|
||||
|
||||
namespace LehrerApp.Desktop.Tests;
|
||||
|
||||
public sealed class SeatingQuickCheckTests
|
||||
{
|
||||
private static (SeatingPlanTabViewModel Vm, FakeEntries Entries, ParticipationSession Session, Student Student) Build(bool readOnly = false)
|
||||
{
|
||||
var group = Guid.NewGuid();
|
||||
var student = new Student { FirstName = "Anna", LastName = "Beispiel" };
|
||||
var session = new ParticipationSession { GroupId = group, Date = DateOnly.FromDateTime(DateTime.Today) };
|
||||
var entries = new FakeEntries();
|
||||
var plan = new SeatingPlan { GroupId = group, Rows = 1, Columns = 2,
|
||||
Assignments = [new SeatAssignment { Row = 0, Column = 0, StudentId = student.Id }] };
|
||||
var vm = new SeatingPlanTabViewModel(new FakeSeatingPlans([plan]), new FakeStudents([student]),
|
||||
new FakeMemberships([new GroupMembership { GroupId = group, StudentId = student.Id }]),
|
||||
new FakeSessions([session]), entries, new FakeAspects());
|
||||
vm.Initialize(group, readOnly);
|
||||
return (vm, entries, session, student);
|
||||
}
|
||||
|
||||
[Fact] public void Attendance_UsesSeatAndPreservesExistingHomeworkAndCounters()
|
||||
{
|
||||
var (vm, entries, session, student) = Build();
|
||||
entries.Save(new ParticipationEntry { SessionId = session.Id, StudentId = student.Id,
|
||||
Homework = HomeworkStatus.Completed, RaisedHandCount = 3, CalledOnCount = 2 });
|
||||
vm.CheckAttendanceCommand.Execute(null);
|
||||
var seat = vm.Seats[0];
|
||||
Assert.True(seat.ShowQuickCheck);
|
||||
Assert.False(vm.Seats[1].ShowQuickCheck);
|
||||
seat.QuickNegativeCommand.Execute(null);
|
||||
var entry = entries.GetBySessionAndStudent(session.Id, student.Id)!;
|
||||
Assert.Equal(AttendanceStatus.ExcusePending, entry.Attendance);
|
||||
Assert.Equal(HomeworkStatus.Completed, entry.Homework);
|
||||
Assert.Equal(3, entry.RaisedHandCount);
|
||||
Assert.Equal(2, entry.CalledOnCount);
|
||||
Assert.Equal(1, seat.DisplayOpacity);
|
||||
seat.QuickPositiveCommand.Execute(null);
|
||||
Assert.Equal(AttendanceStatus.Present, entry.Attendance);
|
||||
}
|
||||
|
||||
[Fact] public void Homework_UpdatesLegacyFlagAndPreservesAttendance()
|
||||
{
|
||||
var (vm, entries, session, student) = Build();
|
||||
entries.Save(new ParticipationEntry { SessionId = session.Id, StudentId = student.Id, Attendance = AttendanceStatus.Late });
|
||||
vm.CheckHomeworkCommand.Execute(null);
|
||||
vm.Seats[0].QuickNegativeCommand.Execute(null);
|
||||
var entry = entries.GetBySessionAndStudent(session.Id, student.Id)!;
|
||||
Assert.Equal(HomeworkStatus.MissingOpen, entry.Homework);
|
||||
Assert.True(entry.HomeworkMissing);
|
||||
Assert.Equal(AttendanceStatus.Late, entry.Attendance);
|
||||
vm.Seats[0].QuickPositiveCommand.Execute(null);
|
||||
Assert.Equal(HomeworkStatus.Completed, entry.Homework);
|
||||
Assert.False(entry.HomeworkMissing);
|
||||
vm.EndQuickCheckCommand.Execute(null);
|
||||
Assert.False(vm.Seats[0].ShowQuickCheck);
|
||||
Assert.True(vm.Seats[0].ShowNormalActions);
|
||||
}
|
||||
|
||||
[Fact] public async Task SpecialCases_OpenAssessmentForClickedStudentAndSession()
|
||||
{
|
||||
var (vm, _, _, _) = Build();
|
||||
var calls = 0;
|
||||
vm.OnAssessStudent = _ => { calls++; return Task.CompletedTask; };
|
||||
vm.CheckAttendanceCommand.Execute(null);
|
||||
await vm.Seats[0].QuickSpecialCommand.ExecuteAsync(null);
|
||||
Assert.Equal(1, calls);
|
||||
}
|
||||
|
||||
[Fact] public void ReadOnlyAndEmptySeats_CannotWriteQuickChecks()
|
||||
{
|
||||
var (vm, entries, session, _) = Build(readOnly: true);
|
||||
vm.CheckHomeworkCommand.Execute(null);
|
||||
vm.Seats[0].QuickNegativeCommand.Execute(null);
|
||||
vm.Seats[1].QuickPositiveCommand.Execute(null);
|
||||
Assert.False(vm.Seats[0].ShowQuickCheck);
|
||||
Assert.Empty(entries.GetBySession(session.Id));
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ public sealed class SettingsViewModelTests
|
||||
private static SettingsViewModel BuildViewModel(FakeSchoolHolidays? holidays = null,
|
||||
FakeSupervisionDuties? supervisionDuties = null,
|
||||
FakeSubjects? subjects = null, FakeCompetencyDomains? competencyDomains = null,
|
||||
FakeCompetencyCatalogVersions? competencyVersions = null,
|
||||
EventQueue? eventQueue = null, SyncKeyStatus? syncKeyStatus = null,
|
||||
SyncKeyRecoveryService? syncKeyRecovery = null, AppearanceSettingsService? appearance = null,
|
||||
TrashViewModel? trashTab = null)
|
||||
@@ -27,7 +28,8 @@ public sealed class SettingsViewModelTests
|
||||
Directory.CreateDirectory(tempPath);
|
||||
|
||||
return new SettingsViewModel(
|
||||
subjects ?? new FakeSubjects([]), competencyDomains ?? new FakeCompetencyDomains(), new FakeGradingKeyTemplates(),
|
||||
subjects ?? new FakeSubjects([]), competencyDomains ?? new FakeCompetencyDomains(),
|
||||
competencyVersions ?? new FakeCompetencyCatalogVersions(), new FakeGradingKeyTemplates(),
|
||||
new FakeSchemes(), new GradingService(), new BackupService(tempPath),
|
||||
new BackupSettingsService(tempPath),
|
||||
new DatabaseEncryptionService(), new AppLockService(tempPath),
|
||||
@@ -35,7 +37,9 @@ public sealed class SettingsViewModelTests
|
||||
new FakeDocumentation(), new FakeStudents([]), new FakeShorthandCodes([]),
|
||||
holidays ?? new FakeSchoolHolidays(), new SchoolCalendarSettingsService(tempPath),
|
||||
new PeriodScheduleService(tempPath), supervisionDuties ?? new FakeSupervisionDuties(),
|
||||
new TemplateStore(tempPath), TestSupport.BuildAiSettingsService(), TestSupport.BuildAiPlanningService(),
|
||||
new TemplateStore(tempPath), new WorksheetTemplateStore(new TemplateStore(tempPath, subfolder: "worksheet-template-packages")), TestSupport.BuildAiSettingsService(), TestSupport.BuildAiPlanningService(),
|
||||
TestSupport.BuildMcpSettingsService(),
|
||||
TestSupport.BuildMcpClientRegistrationService(),
|
||||
TestSupport.BuildWebUntisSettingsService(),
|
||||
TestSupport.BuildAnnualPlanSettingsService(),
|
||||
TestSupport.BuildSyncSettingsService(), TestSupport.BuildSyncAuthService(),
|
||||
@@ -219,6 +223,25 @@ public sealed class SettingsViewModelTests
|
||||
Assert.Empty(queue.GetUnreviewed());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ClearSyncConflicts_LeertProtokollUndQueue()
|
||||
{
|
||||
var queue = TestSupport.BuildEventQueue();
|
||||
foreach (var resolution in new[] { "LocalWon", "RemoteWon" })
|
||||
queue.AddConflict(new ConflictEntry
|
||||
{
|
||||
LocalEvent = new SyncEvent { EntityType = "Student", EntityId = Guid.NewGuid().ToString() },
|
||||
RemoteEvent = new SyncEvent { EntityType = "Student", EntityId = Guid.NewGuid().ToString() },
|
||||
Resolution = resolution,
|
||||
});
|
||||
var vm = BuildViewModel(eventQueue: queue);
|
||||
|
||||
vm.ClearSyncConflictsCommand.Execute(null);
|
||||
|
||||
Assert.Empty(vm.SyncConflicts);
|
||||
Assert.Empty(queue.GetUnreviewed());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddSchoolHoliday_GueltigeEingabe_WirdGespeichertUndInListeAngezeigt()
|
||||
{
|
||||
@@ -314,14 +337,16 @@ public sealed class SettingsViewModelTests
|
||||
var calendarSettings = new SchoolCalendarSettingsService(tempPath);
|
||||
|
||||
var vm = new SettingsViewModel(
|
||||
new FakeSubjects([]), new FakeCompetencyDomains(), new FakeGradingKeyTemplates(),
|
||||
new FakeSubjects([]), new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions(), new FakeGradingKeyTemplates(),
|
||||
new FakeSchemes(), new GradingService(), new BackupService(tempPath),
|
||||
new BackupSettingsService(tempPath),
|
||||
new DatabaseEncryptionService(), new AppLockService(tempPath),
|
||||
new LiteDbContext(new MemoryStream()), new PrivacySettingsService(tempPath),
|
||||
new FakeDocumentation(), new FakeStudents([]), new FakeShorthandCodes([]),
|
||||
new FakeSchoolHolidays(), calendarSettings, new PeriodScheduleService(tempPath),
|
||||
new FakeSupervisionDuties(), new TemplateStore(tempPath), TestSupport.BuildAiSettingsService(), TestSupport.BuildAiPlanningService(),
|
||||
new FakeSupervisionDuties(), new TemplateStore(tempPath), new WorksheetTemplateStore(new TemplateStore(tempPath, subfolder: "worksheet-template-packages")), TestSupport.BuildAiSettingsService(), TestSupport.BuildAiPlanningService(),
|
||||
TestSupport.BuildMcpSettingsService(),
|
||||
TestSupport.BuildMcpClientRegistrationService(),
|
||||
TestSupport.BuildWebUntisSettingsService(),
|
||||
TestSupport.BuildAnnualPlanSettingsService(),
|
||||
TestSupport.BuildSyncSettingsService(), TestSupport.BuildSyncAuthService(), TestSupport.BuildEventQueue(),
|
||||
@@ -342,14 +367,16 @@ public sealed class SettingsViewModelTests
|
||||
var periodSchedule = new PeriodScheduleService(tempPath);
|
||||
|
||||
var vm = new SettingsViewModel(
|
||||
new FakeSubjects([]), new FakeCompetencyDomains(), new FakeGradingKeyTemplates(),
|
||||
new FakeSubjects([]), new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions(), new FakeGradingKeyTemplates(),
|
||||
new FakeSchemes(), new GradingService(), new BackupService(tempPath),
|
||||
new BackupSettingsService(tempPath),
|
||||
new DatabaseEncryptionService(), new AppLockService(tempPath),
|
||||
new LiteDbContext(new MemoryStream()), new PrivacySettingsService(tempPath),
|
||||
new FakeDocumentation(), new FakeStudents([]), new FakeShorthandCodes([]),
|
||||
new FakeSchoolHolidays(), new SchoolCalendarSettingsService(tempPath), periodSchedule,
|
||||
new FakeSupervisionDuties(), new TemplateStore(tempPath), TestSupport.BuildAiSettingsService(), TestSupport.BuildAiPlanningService(),
|
||||
new FakeSupervisionDuties(), new TemplateStore(tempPath), new WorksheetTemplateStore(new TemplateStore(tempPath, subfolder: "worksheet-template-packages")), TestSupport.BuildAiSettingsService(), TestSupport.BuildAiPlanningService(),
|
||||
TestSupport.BuildMcpSettingsService(),
|
||||
TestSupport.BuildMcpClientRegistrationService(),
|
||||
TestSupport.BuildWebUntisSettingsService(),
|
||||
TestSupport.BuildAnnualPlanSettingsService(),
|
||||
TestSupport.BuildSyncSettingsService(), TestSupport.BuildSyncAuthService(), TestSupport.BuildEventQueue(),
|
||||
@@ -374,14 +401,16 @@ public sealed class SettingsViewModelTests
|
||||
var periodSchedule = new PeriodScheduleService(tempPath);
|
||||
|
||||
var vm = new SettingsViewModel(
|
||||
new FakeSubjects([]), new FakeCompetencyDomains(), new FakeGradingKeyTemplates(),
|
||||
new FakeSubjects([]), new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions(), new FakeGradingKeyTemplates(),
|
||||
new FakeSchemes(), new GradingService(), new BackupService(tempPath),
|
||||
new BackupSettingsService(tempPath),
|
||||
new DatabaseEncryptionService(), new AppLockService(tempPath),
|
||||
new LiteDbContext(new MemoryStream()), new PrivacySettingsService(tempPath),
|
||||
new FakeDocumentation(), new FakeStudents([]), new FakeShorthandCodes([]),
|
||||
new FakeSchoolHolidays(), new SchoolCalendarSettingsService(tempPath), periodSchedule,
|
||||
new FakeSupervisionDuties(), new TemplateStore(tempPath), TestSupport.BuildAiSettingsService(), TestSupport.BuildAiPlanningService(),
|
||||
new FakeSupervisionDuties(), new TemplateStore(tempPath), new WorksheetTemplateStore(new TemplateStore(tempPath, subfolder: "worksheet-template-packages")), TestSupport.BuildAiSettingsService(), TestSupport.BuildAiPlanningService(),
|
||||
TestSupport.BuildMcpSettingsService(),
|
||||
TestSupport.BuildMcpClientRegistrationService(),
|
||||
TestSupport.BuildWebUntisSettingsService(),
|
||||
TestSupport.BuildAnnualPlanSettingsService(),
|
||||
TestSupport.BuildSyncSettingsService(), TestSupport.BuildSyncAuthService(), TestSupport.BuildEventQueue(),
|
||||
@@ -462,21 +491,24 @@ public sealed class SettingsViewModelTests
|
||||
{
|
||||
var subject = new Subject { Name = "Biologie", ShortName = "Bio" };
|
||||
var repository = new FakeCompetencyDomains();
|
||||
var versions = new FakeCompetencyCatalogVersions();
|
||||
var version = versions.GetOrCreateDefault(subject.Id);
|
||||
repository.Add(new CompetencyDomain
|
||||
{
|
||||
SubjectId = subject.Id, GradeLevel = 10, Name = "Erster Bereich", SortOrder = 0,
|
||||
SubjectId = subject.Id, GradeLevel = 10, VersionId = version.Id, Name = "Erster Bereich", SortOrder = 0,
|
||||
});
|
||||
repository.Add(new CompetencyDomain
|
||||
{
|
||||
SubjectId = subject.Id, GradeLevel = 10, Name = "Zweiter Bereich", SortOrder = 1,
|
||||
SubjectId = subject.Id, GradeLevel = 10, VersionId = version.Id, Name = "Zweiter Bereich", SortOrder = 1,
|
||||
});
|
||||
var vm = BuildViewModel(subjects: new FakeSubjects([subject]), competencyDomains: repository);
|
||||
var vm = BuildViewModel(subjects: new FakeSubjects([subject]), competencyDomains: repository,
|
||||
competencyVersions: versions);
|
||||
vm.CatalogSubject = vm.Subjects.Single();
|
||||
|
||||
vm.Domains[1].MoveUpCommand.Execute(null);
|
||||
|
||||
Assert.Equal(["Zweiter Bereich", "Erster Bereich"], vm.Domains.Select(x => x.Name));
|
||||
var stored = repository.GetBySubjectAndGrade(subject.Id, 10);
|
||||
var stored = repository.GetBySubjectAndGrade(subject.Id, 10, version.Id);
|
||||
Assert.Equal(["Zweiter Bereich", "Erster Bereich"], stored.Select(x => x.Name));
|
||||
Assert.Equal([0, 1], stored.Select(x => x.SortOrder));
|
||||
}
|
||||
@@ -510,15 +542,19 @@ public sealed class SettingsViewModelTests
|
||||
{
|
||||
var subject = new Subject { Name = "Biologie", ShortName = "Bio" };
|
||||
var repository = new FakeCompetencyDomains();
|
||||
var versions = new FakeCompetencyCatalogVersions();
|
||||
var version = versions.GetOrCreateDefault(subject.Id);
|
||||
repository.Add(new CompetencyDomain
|
||||
{
|
||||
SubjectId = subject.Id,
|
||||
GradeLevel = 10,
|
||||
VersionId = version.Id,
|
||||
Name = "Erkenntnisgewinnung",
|
||||
Code = "EG",
|
||||
Items = [new CompetencyItem { Code = "EG1", Description = "Modelle verwenden" }],
|
||||
});
|
||||
var vm = BuildViewModel(subjects: new FakeSubjects([subject]), competencyDomains: repository);
|
||||
var vm = BuildViewModel(subjects: new FakeSubjects([subject]), competencyDomains: repository,
|
||||
competencyVersions: versions);
|
||||
vm.CatalogSubject = vm.Subjects.Single();
|
||||
|
||||
var preview = vm.PrepareCatalogCopy(11);
|
||||
@@ -529,9 +565,9 @@ public sealed class SettingsViewModelTests
|
||||
Assert.Equal(1, preview.NewCompetencies);
|
||||
|
||||
vm.ApplyCatalogImport(preview, CompetencyCatalogImportMode.Merge, new HashSet<string>());
|
||||
var copied = repository.GetBySubjectAndGrade(subject.Id, 11);
|
||||
var copied = repository.GetBySubjectAndGrade(subject.Id, 11, version.Id);
|
||||
Assert.Single(copied);
|
||||
Assert.NotEqual(repository.GetBySubjectAndGrade(subject.Id, 10)[0].Id, copied[0].Id);
|
||||
Assert.NotEqual(repository.GetBySubjectAndGrade(subject.Id, 10, version.Id)[0].Id, copied[0].Id);
|
||||
Assert.Equal("EG1", copied[0].Items.Single().Code);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Desktop.ViewModels.Students;
|
||||
using Xunit;
|
||||
|
||||
namespace LehrerApp.Desktop.Tests;
|
||||
|
||||
public sealed class StudentPickerDialogViewModelTests
|
||||
{
|
||||
private static (StudentPickerDialogViewModel Vm, Student Anna, Student Ben) Build()
|
||||
{
|
||||
var anna = new Student { FirstName = "Anna", LastName = "Adler" };
|
||||
var ben = new Student { FirstName = "Ben", LastName = "Bauer" };
|
||||
var vm = new StudentPickerDialogViewModel(new FakeStudents([anna, ben]));
|
||||
return (vm, anna, ben);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SearchText_FiltertNachTeilstring()
|
||||
{
|
||||
var (vm, anna, _) = Build();
|
||||
|
||||
vm.SearchText = "ann";
|
||||
|
||||
Assert.Single(vm.Students);
|
||||
Assert.Equal(anna.FullName, vm.Students[0].FullName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Select_OhneAuswahl_SetztValidationMessage()
|
||||
{
|
||||
var (vm, _, _) = Build();
|
||||
|
||||
vm.SelectCommand.Execute(null);
|
||||
|
||||
Assert.Null(vm.Result);
|
||||
Assert.NotEqual("", vm.ValidationMessage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Select_MitAuswahl_LiefertVollenSchueler()
|
||||
{
|
||||
var (vm, anna, _) = Build();
|
||||
vm.SelectedStudent = vm.Students.Single(s => s.Id == anna.Id);
|
||||
|
||||
vm.SelectCommand.Execute(null);
|
||||
|
||||
Assert.Equal(anna.Id, vm.Result?.Id);
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,7 @@ public sealed class TeachingModeViewModelTests
|
||||
FakeSessions? sessions = null) =>
|
||||
new(sessions ?? new FakeSessions([]), new FakeEntries(), new FakeAspects(),
|
||||
new FakeStudents([]), new FakeMemberships([]), new FakeGroups([group]),
|
||||
new FakeCompetencyDomains());
|
||||
new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions());
|
||||
|
||||
[Fact]
|
||||
public void Konstruktor_LaedtVerlaufsplanUndInitialisiertSitzplanFuerDieGruppe()
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Desktop.ViewModels.Groups;
|
||||
using Xunit;
|
||||
|
||||
namespace LehrerApp.Desktop.Tests;
|
||||
|
||||
public sealed class TeachingTimelineViewModelTests
|
||||
{
|
||||
private readonly DateTime _start = new(2026, 9, 14, 8, 0, 0, DateTimeKind.Utc);
|
||||
private DateTime _now;
|
||||
private readonly FakeLessons _lessons = new();
|
||||
|
||||
private (Lesson Lesson, TeachingTimelineViewModel Vm) Build(bool scheduled = true)
|
||||
{
|
||||
_now = _start.AddMinutes(5);
|
||||
var local = _start.ToLocalTime();
|
||||
var lesson = new Lesson
|
||||
{
|
||||
Date = DateOnly.FromDateTime(local),
|
||||
StartTime = scheduled ? TimeOnly.FromDateTime(local) : null,
|
||||
Phases = [new() { Name = "Einstieg", DurationMinutes = 10 },
|
||||
new() { Name = "Arbeit", DurationMinutes = 10 },
|
||||
new() { Name = "Sicherung", DurationMinutes = 10 }]
|
||||
};
|
||||
_lessons.Add(lesson);
|
||||
return (lesson, new TeachingTimelineViewModel(lesson, _lessons, utcNow: () => _now));
|
||||
}
|
||||
|
||||
[Fact] public void Clock_HighlightsExactlyOnePhaseAtBoundary()
|
||||
{
|
||||
var (_, vm) = Build();
|
||||
Assert.True(vm.Phases[0].IsActive);
|
||||
Assert.Equal(50, vm.Phases[0].Progress);
|
||||
_now = _start.AddMinutes(10);
|
||||
vm.Refresh();
|
||||
Assert.True(vm.Phases[0].IsCompleted);
|
||||
Assert.True(vm.Phases[1].IsActive);
|
||||
Assert.Single(vm.Phases, p => p.IsActive);
|
||||
}
|
||||
|
||||
[Fact] public void NoStartTime_RequiresExplicitStart()
|
||||
{
|
||||
var (_, vm) = Build(scheduled: false);
|
||||
Assert.True(vm.NeedsStart);
|
||||
Assert.DoesNotContain(vm.Phases, p => p.IsActive);
|
||||
vm.StartNowCommand.Execute(null);
|
||||
Assert.False(vm.NeedsStart);
|
||||
Assert.True(vm.Phases[0].IsActive);
|
||||
Assert.Equal(_now, vm.Phases[0].StartUtc);
|
||||
}
|
||||
|
||||
[Fact] public void Extend_ShiftsLaterPhasesAndPreservesOriginalPlan()
|
||||
{
|
||||
var (lesson, vm) = Build();
|
||||
vm.Phases[0].ExtendTenCommand.Execute(null);
|
||||
Assert.Equal(_start.AddMinutes(20), vm.Phases[1].StartUtc);
|
||||
Assert.True(vm.Phases[2].IsOverflow);
|
||||
Assert.Equal(10, lesson.Phases[0].DurationMinutes);
|
||||
Assert.NotNull(_lessons.GetById(lesson.Id)!.TeachingTimeline);
|
||||
}
|
||||
|
||||
[Fact] public void FinishEarly_StartsNextPhaseNow()
|
||||
{
|
||||
var (_, vm) = Build();
|
||||
vm.Phases[0].FinishCommand.Execute(null);
|
||||
Assert.True(vm.Phases[0].IsCompleted);
|
||||
Assert.True(vm.Phases[1].IsActive);
|
||||
Assert.Equal(_now, vm.Phases[1].StartUtc);
|
||||
}
|
||||
|
||||
[Fact] public void Hold_SurvivesReopenAndContinuesOnlyOnNext()
|
||||
{
|
||||
var (lesson, vm) = Build();
|
||||
vm.Phases[0].HoldCommand.Execute(null);
|
||||
_now = _start.AddMinutes(65);
|
||||
var reopened = new TeachingTimelineViewModel(lesson, _lessons, utcNow: () => _now);
|
||||
Assert.True(reopened.Phases[0].IsHeld);
|
||||
Assert.True(reopened.Phases[0].IsActive);
|
||||
Assert.Single(reopened.Phases, p => p.IsActive);
|
||||
reopened.Phases[0].FinishCommand.Execute(null);
|
||||
Assert.True(reopened.Phases[1].IsActive);
|
||||
Assert.False(reopened.Phases[0].IsHeld);
|
||||
Assert.Equal(_now, reopened.Phases[1].StartUtc);
|
||||
}
|
||||
|
||||
[Fact] public void BringForward_KeepsSkippedPendingPhasesBelowChosenPhase()
|
||||
{
|
||||
var (_, vm) = Build();
|
||||
var chosen = vm.Phases[2];
|
||||
chosen.BringForwardCommand.Execute(null);
|
||||
Assert.Equal(new[] { "Einstieg", "Sicherung", "Arbeit" }, vm.Phases.Select(p => p.Source.Name));
|
||||
Assert.True(chosen.IsActive);
|
||||
Assert.Equal(_now, chosen.StartUtc);
|
||||
Assert.False(vm.Phases[2].IsCompleted);
|
||||
}
|
||||
|
||||
[Fact] public void Overflow_RemainsPendingTheNextDayAndCanBeStartedNow()
|
||||
{
|
||||
var (lesson, vm) = Build();
|
||||
vm.Phases[0].ExtendTenCommand.Execute(null);
|
||||
_now = _start.AddDays(1);
|
||||
var reopened = new TeachingTimelineViewModel(lesson, _lessons, utcNow: () => _now);
|
||||
var remainder = reopened.Phases[2];
|
||||
Assert.True(remainder.IsOverflow);
|
||||
Assert.False(remainder.IsCompleted);
|
||||
Assert.False(remainder.IsActive);
|
||||
Assert.True(reopened.HasRemainder);
|
||||
remainder.BringForwardCommand.Execute(null);
|
||||
Assert.True(remainder.IsActive);
|
||||
Assert.Equal(_now, remainder.StartUtc);
|
||||
}
|
||||
|
||||
[Fact] public void Transfer_CopiesIntoSelectedLessonOnlyOnceAndKeepsSource()
|
||||
{
|
||||
var (lesson, _) = Build();
|
||||
var target = new Lesson { GroupId = lesson.GroupId, Date = lesson.Date.AddDays(1), Topic = "Folgestunde" };
|
||||
_lessons.Add(target);
|
||||
var vm = new TeachingTimelineViewModel(lesson, _lessons, utcNow: () => _now);
|
||||
vm.Phases[0].ExtendTenCommand.Execute(null);
|
||||
vm.TransferRemainderCommand.Execute(null);
|
||||
vm.TransferRemainderCommand.Execute(null);
|
||||
var copy = Assert.Single(target.Phases);
|
||||
Assert.Equal("Sicherung", copy.Name);
|
||||
Assert.NotEqual(lesson.Phases[2].Id, copy.Id);
|
||||
Assert.Equal(3, lesson.Phases.Count);
|
||||
Assert.True(vm.Phases[2].IsTransferred);
|
||||
}
|
||||
|
||||
[Fact] public void PartiallyOverflowingPhase_PreservesOnlyUnfinishedMinutesAfterLessonEnds()
|
||||
{
|
||||
var (lesson, vm) = Build();
|
||||
vm.Phases[0].ExtendFiveCommand.Execute(null);
|
||||
_now = _start.AddMinutes(28);
|
||||
vm.Refresh();
|
||||
Assert.True(vm.Phases[2].IsActive);
|
||||
_now = _start.AddDays(1);
|
||||
var reopened = new TeachingTimelineViewModel(lesson, _lessons, utcNow: () => _now);
|
||||
var remainder = reopened.Phases[2];
|
||||
Assert.False(remainder.IsCompleted);
|
||||
Assert.False(remainder.IsActive);
|
||||
Assert.True(reopened.HasRemainder);
|
||||
Assert.Equal(5, remainder.RemainingMinutes);
|
||||
remainder.BringForwardCommand.Execute(null);
|
||||
Assert.True(remainder.IsActive);
|
||||
Assert.Equal(_now.AddMinutes(5), remainder.EndUtc);
|
||||
}
|
||||
|
||||
[Fact] public void ReadOnly_DoesNotChangeTimingOrStartClock()
|
||||
{
|
||||
var (lesson, _) = Build(scheduled: false);
|
||||
var vm = new TeachingTimelineViewModel(lesson, _lessons, readOnly: true, utcNow: () => _now);
|
||||
vm.StartNowCommand.Execute(null);
|
||||
Assert.Null(lesson.TeachingTimeline);
|
||||
Assert.True(vm.NeedsStart);
|
||||
}
|
||||
|
||||
[Fact] public void AlternativePhases_AreNotRunAlongsideMainPath()
|
||||
{
|
||||
var (lesson, _) = Build();
|
||||
lesson.Phases.Add(new LessonPhaseStep { AlternativePathId = Guid.NewGuid(), DurationMinutes = 30 });
|
||||
var vm = new TeachingTimelineViewModel(lesson, _lessons, utcNow: () => _now);
|
||||
Assert.Equal(3, vm.Phases.Count);
|
||||
Assert.Equal(_start.AddMinutes(30), vm.Phases[^1].EndUtc);
|
||||
}
|
||||
|
||||
[Fact] public void HeldTiming_RoundTripsThroughLiteDbWithoutTimezoneShift()
|
||||
{
|
||||
using var stream = new MemoryStream();
|
||||
using var db = new LehrerApp.Data.LiteDbContext(stream);
|
||||
var repository = new LehrerApp.Data.Repositories.LessonRepository(db);
|
||||
var (lesson, _) = Build();
|
||||
repository.Save(lesson);
|
||||
var vm = new TeachingTimelineViewModel(lesson, repository, utcNow: () => _now);
|
||||
vm.Phases[0].HoldCommand.Execute(null);
|
||||
_now = _start.AddMinutes(40);
|
||||
var loaded = repository.GetById(lesson.Id)!;
|
||||
var reopened = new TeachingTimelineViewModel(loaded, repository, utcNow: () => _now);
|
||||
Assert.True(reopened.Phases[0].IsActive);
|
||||
Assert.True(reopened.Phases[0].IsHeld);
|
||||
Assert.Equal(_start, reopened.Phases[0].StartUtc);
|
||||
Assert.Equal(_start.AddMinutes(45), reopened.Phases[0].EndUtc);
|
||||
}
|
||||
}
|
||||
@@ -25,4 +25,28 @@ public sealed class UnitDialogViewModelTests
|
||||
|
||||
Assert.Equal("10c · kein Fach hinterlegt (siehe Lerngruppe)", vm.GroupSubjectDisplay);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Laufend_SetztBisherigeLaufendeEinheitAufAbgeschlossenUndWarntVorher()
|
||||
{
|
||||
var groupId = Guid.NewGuid();
|
||||
var units = new FakeUnits();
|
||||
var previous = new LehrerApp.Core.Models.Unit
|
||||
{
|
||||
GroupId = groupId, Title = "Bruchrechnung", Status = LehrerApp.Core.Models.UnitStatus.Active,
|
||||
};
|
||||
units.Add(previous);
|
||||
var vm = new UnitDialogViewModel(units, new FakeCompetencyDomains(),
|
||||
groupId, null, 6, "6a", "Mathematik", editingUnit: null)
|
||||
{
|
||||
Title = "Prozentrechnung",
|
||||
StatusName = "Laufend",
|
||||
};
|
||||
|
||||
Assert.Contains("Bruchrechnung", vm.StatusNotice);
|
||||
vm.SaveCommand.Execute(null);
|
||||
|
||||
Assert.Equal(LehrerApp.Core.Models.UnitStatus.Completed, previous.Status);
|
||||
Assert.Single(units.GetByGroup(groupId), u => u.Status == LehrerApp.Core.Models.UnitStatus.Active);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Desktop.Services;
|
||||
using LehrerApp.Desktop.Services.Mcp.Tools;
|
||||
using Xunit;
|
||||
|
||||
namespace LehrerApp.Desktop.Tests;
|
||||
|
||||
/// Aus Konsistenz mit den drei bestehenden WebUntis-Abgleichs-ViewModels bewusst ohne Tests für
|
||||
/// GetUntisAbsenceRows/GetNamedUntisAbsencePattern gelassen (siehe TODO.md) - beide rufen
|
||||
/// WebUntisIntegrationService.GetLessonAbsencesAsync auf, was einen echten WebUntis-JSON-RPC-
|
||||
/// Handshake voraussetzt. Getestet werden die Teile, die keinen WebUntis-Zugriff brauchen:
|
||||
/// GetUntisHubStatus (reine Delegation an UntisHubService) und die Validierungspfade von
|
||||
/// ApplyUntisAbsenceStatus, die vor jedem WebUntis-/Datenbankzugriff greifen.
|
||||
public sealed class UntisComparisonToolsTests
|
||||
{
|
||||
private static UntisComparisonTools Build(
|
||||
List<LearningGroup>? groups = null, List<Student>? students = null,
|
||||
List<ParticipationSession>? sessions = null, FakeMcpConfirmation? confirmation = null) =>
|
||||
new(new FakeGroups(groups ?? []), new FakeStudents(students ?? []), new FakeSessions(sessions ?? []),
|
||||
new FakeEntries(), TestSupport.BuildWebUntisIntegrationService(),
|
||||
TestSupport.BuildUntisHubService(groups ?? []), confirmation ?? new FakeMcpConfirmation());
|
||||
|
||||
[Fact]
|
||||
public void GetUntisHubStatus_DelegiertAnUntisHubServiceUndMapptKindUndDueStateAlsText()
|
||||
{
|
||||
var group = new LearningGroup { Name = "9a", WebUntisLessonId = 42 };
|
||||
var tool = Build([group]);
|
||||
|
||||
var rows = tool.GetUntisHubStatus();
|
||||
|
||||
Assert.Contains(rows, r => r.Kind == nameof(UntisHubJobKind.FehlzeitenKurz) && r.GroupName == "9a"
|
||||
&& r.DueState == nameof(UntisHubDueState.Overdue));
|
||||
Assert.Contains(rows, r => r.Kind == nameof(UntisHubJobKind.OffenePeriods) && r.GroupName == "Offene Stunden");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApplyUntisAbsenceStatus_UnbekannterStatus_WirdOhneRowIdPruefungAbgelehnt()
|
||||
{
|
||||
var tool = Build();
|
||||
|
||||
var result = await tool.ApplyUntisAbsenceStatus("irgendeine-id", "Suspendiert");
|
||||
|
||||
Assert.False(result.Applied);
|
||||
Assert.Contains("Status", result.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApplyUntisAbsenceStatus_NichtSelektierbarerAberGueltigerEnumWert_WirdAbgelehnt()
|
||||
{
|
||||
// "Truant"/"Suspended" etc. sind gültige AttendanceStatus-Werte, aber keine, die WebUntis
|
||||
// hier je melden würde (siehe SelectableStatuses) - müssen trotzdem abgelehnt werden, damit
|
||||
// ein KI-Client nicht versehentlich einen fachlich unpassenden Status setzen kann.
|
||||
var tool = Build();
|
||||
|
||||
var result = await tool.ApplyUntisAbsenceStatus("irgendeine-id", nameof(AttendanceStatus.Truant));
|
||||
|
||||
Assert.False(result.Applied);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApplyUntisAbsenceStatus_UnbekannteRowId_WirdAbgelehntOhneBestaetigung()
|
||||
{
|
||||
var confirmation = new FakeMcpConfirmation();
|
||||
var tool = Build(confirmation: confirmation);
|
||||
|
||||
var result = await tool.ApplyUntisAbsenceStatus("nie-vergeben", nameof(AttendanceStatus.Excused));
|
||||
|
||||
Assert.False(result.Applied);
|
||||
Assert.Contains("row-id", result.Message);
|
||||
Assert.Equal(0, confirmation.CallCount); // erst gar nicht bis zur Bestätigung vorgedrungen
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Core.Services;
|
||||
using LehrerApp.Desktop.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace LehrerApp.Desktop.Tests;
|
||||
|
||||
public sealed class UntisHubServiceTests
|
||||
{
|
||||
private static readonly DateTime UtcNow = new(2026, 9, 10, 8, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private static LearningGroup Group(string name, int? webUntisLessonId, bool isActive = true) =>
|
||||
new() { Name = name, WebUntisLessonId = webUntisLessonId, IsActive = isActive };
|
||||
|
||||
[Fact]
|
||||
public void BuildRows_ProGruppeMitLessonId_ZweiFehlzeitenzeilenPlusDreiGlobaleZeilen()
|
||||
{
|
||||
var group = Group("9a", 42);
|
||||
|
||||
var rows = UntisHubService.BuildRows([group], [], UtcNow);
|
||||
|
||||
Assert.Equal(5, rows.Count);
|
||||
Assert.Equal(2, rows.Count(r => r.GroupId == group.Id));
|
||||
Assert.Contains(rows, r => r.Kind == UntisHubJobKind.FehlzeitenKurz && r.GroupId == group.Id);
|
||||
Assert.Contains(rows, r => r.Kind == UntisHubJobKind.FehlzeitenLang && r.GroupId == group.Id);
|
||||
Assert.Contains(rows, r => r.Kind == UntisHubJobKind.OffenePeriods && r.GroupId == null);
|
||||
Assert.Contains(rows, r => r.Kind == UntisHubJobKind.Klassenbuchabgleich && r.GroupId == null);
|
||||
Assert.Contains(rows, r => r.Kind == UntisHubJobKind.Hausaufgabenabgleich && r.GroupId == null);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildRows_NieGeprueft_GiltAlsUeberfaellig()
|
||||
{
|
||||
var rows = UntisHubService.BuildRows([], [], UtcNow);
|
||||
|
||||
Assert.All(rows, r => Assert.Equal(UntisHubDueState.Overdue, r.DueState));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildRows_FehlzeitenKurzVorSechsTagen_GiltAlsOk()
|
||||
{
|
||||
var group = Group("9a", 42);
|
||||
var state = new UntisHubJobState
|
||||
{
|
||||
Kind = UntisHubJobKind.FehlzeitenKurz, GroupId = group.Id, LastRunAt = UtcNow.AddDays(-6),
|
||||
};
|
||||
|
||||
var rows = UntisHubService.BuildRows([group], [state], UtcNow);
|
||||
|
||||
var row = rows.Single(r => r.Kind == UntisHubJobKind.FehlzeitenKurz);
|
||||
Assert.Equal(UntisHubDueState.Ok, row.DueState);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildRows_FehlzeitenKurzVorSechzehnTagen_GiltAlsFaellig()
|
||||
{
|
||||
var group = Group("9a", 42);
|
||||
var state = new UntisHubJobState
|
||||
{
|
||||
Kind = UntisHubJobKind.FehlzeitenKurz, GroupId = group.Id, LastRunAt = UtcNow.AddDays(-16),
|
||||
};
|
||||
|
||||
var rows = UntisHubService.BuildRows([group], [state], UtcNow);
|
||||
|
||||
var row = rows.Single(r => r.Kind == UntisHubJobKind.FehlzeitenKurz);
|
||||
Assert.Equal(UntisHubDueState.Due, row.DueState);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildRows_FehlzeitenKurzVorZweiundzwanzigTagen_GiltAlsUeberfaellig()
|
||||
{
|
||||
var group = Group("9a", 42);
|
||||
var state = new UntisHubJobState
|
||||
{
|
||||
Kind = UntisHubJobKind.FehlzeitenKurz, GroupId = group.Id, LastRunAt = UtcNow.AddDays(-22),
|
||||
};
|
||||
|
||||
var rows = UntisHubService.BuildRows([group], [state], UtcNow);
|
||||
|
||||
var row = rows.Single(r => r.Kind == UntisHubJobKind.FehlzeitenKurz);
|
||||
Assert.Equal(UntisHubDueState.Overdue, row.DueState);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildRows_FehlzeitenLangHatDeutlichLaengereKadenzAlsKurz()
|
||||
{
|
||||
var group = Group("9a", 42);
|
||||
var lastRunAt = UtcNow.AddDays(-40);
|
||||
var states = new List<UntisHubJobState>
|
||||
{
|
||||
new() { Kind = UntisHubJobKind.FehlzeitenKurz, GroupId = group.Id, LastRunAt = lastRunAt },
|
||||
new() { Kind = UntisHubJobKind.FehlzeitenLang, GroupId = group.Id, LastRunAt = lastRunAt },
|
||||
};
|
||||
|
||||
var rows = UntisHubService.BuildRows([group], states, UtcNow);
|
||||
|
||||
Assert.Equal(UntisHubDueState.Overdue, rows.Single(r => r.Kind == UntisHubJobKind.FehlzeitenKurz).DueState);
|
||||
Assert.Equal(UntisHubDueState.Ok, rows.Single(r => r.Kind == UntisHubJobKind.FehlzeitenLang).DueState);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildRows_GruppeOhneWebUntisLessonId_WirdVonAufrufseiteAusgeschlossen()
|
||||
{
|
||||
// GetRows() filtert vorab auf WebUntisLessonId != null (siehe UntisHubService.GetRows) -
|
||||
// BuildRows selbst bekommt bereits nur die eligible-Gruppen übergeben.
|
||||
var eligible = new List<LearningGroup> { Group("9a", 42) };
|
||||
|
||||
var rows = UntisHubService.BuildRows(eligible, [], UtcNow);
|
||||
|
||||
Assert.Equal(2, rows.Count(r => r.GroupId != null));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RecordRun_FehlzeitenLang_SchliesstAuchFehlzeitenKurzDerselbenGruppeAb()
|
||||
{
|
||||
// Nutzer-Feedback: der Langzeit-Abgleich deckt das kurzfristige Zeitfenster als Teilmenge mit
|
||||
// ab - ohne diese Kopplung bliebe die kurzfristige Kadenz trotz erledigtem Langzeit-Abgleich
|
||||
// als fällig stehen.
|
||||
var group = Group("9a", 42);
|
||||
var jobStates = new FakeUntisHubJobStates();
|
||||
var hub = new UntisHubService(new FakeGroups([group]), jobStates, new SchoolYearService());
|
||||
|
||||
hub.RecordRun(UntisHubJobKind.FehlzeitenLang, group.Id, "3 Fehlzeiten übernommen");
|
||||
|
||||
var kurzState = jobStates.Get(UntisHubJobKind.FehlzeitenKurz, group.Id);
|
||||
var langState = jobStates.Get(UntisHubJobKind.FehlzeitenLang, group.Id);
|
||||
Assert.NotNull(kurzState?.LastRunAt);
|
||||
Assert.Equal(langState!.LastRunAt, kurzState!.LastRunAt);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RecordRun_FehlzeitenKurz_LaesstFehlzeitenLangUnangetastet()
|
||||
{
|
||||
var group = Group("9a", 42);
|
||||
var jobStates = new FakeUntisHubJobStates();
|
||||
var hub = new UntisHubService(new FakeGroups([group]), jobStates, new SchoolYearService());
|
||||
|
||||
hub.RecordRun(UntisHubJobKind.FehlzeitenKurz, group.Id, "keine Abweichungen");
|
||||
|
||||
Assert.Null(jobStates.Get(UntisHubJobKind.FehlzeitenLang, group.Id));
|
||||
}
|
||||
}
|
||||
@@ -18,4 +18,18 @@ public sealed class UntisNameMatchingTests
|
||||
[InlineData("Ben Schmidt", "")]
|
||||
public void NamesMatch_LehntUnterschiedlicheOderFehlendeNamenAb(string? a, string b) =>
|
||||
Assert.False(UntisNameMatching.NamesMatch(a, b));
|
||||
|
||||
// Regression: Student.FullName liefert "Nachname, Vorname" (mit Komma) für Anzeigezwecke.
|
||||
// Wird dieser String direkt an NamesMatch übergeben, bleibt das Komma am Wort kleben
|
||||
// ("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]
|
||||
public void NamesMatch_KommaGetrennterAnzeigename_PasstNichtOhneUmformung()
|
||||
{
|
||||
Assert.False(UntisNameMatching.NamesMatch("Gerste, Amelia", "Gerste Amelia"));
|
||||
Assert.True(UntisNameMatching.NamesMatch("Amelia Gerste", "Gerste Amelia"));
|
||||
}
|
||||
}
|
||||
@@ -61,7 +61,7 @@ public sealed class UntisSyncServiceTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ProcessIcsText_AbweichendesFach_SchreibtVertretungUndAktualisiertBeiWiederholung()
|
||||
public void ProcessIcsText_AbweichendesFach_SchreibtVertretungUndUeberspringtUnveraenderteWiederholung()
|
||||
{
|
||||
var mappings = new FakeUntisSlotMappings();
|
||||
mappings.Add(new UntisSlotMapping
|
||||
@@ -81,7 +81,7 @@ public sealed class UntisSyncServiceTests
|
||||
// Eintrag erzeugen - Idempotenz über SubstitutionEntry.ExternalId.
|
||||
var second = service.ProcessIcsText(BuildIcs("1", "20260817T075000", "NAT", "10c HED"));
|
||||
|
||||
Assert.Equal(1, second.SubstitutionCount);
|
||||
Assert.Equal(0, second.SubstitutionCount);
|
||||
Assert.Single(substitutions.GetAll());
|
||||
}
|
||||
|
||||
@@ -278,7 +278,7 @@ public sealed class UntisSyncServiceTests
|
||||
// Erneuter Poll mit demselben, weiterhin unverändert vorhandenen Termin darf keinen
|
||||
// zweiten Eintrag erzeugen (Idempotenz über ExternalId=Uid).
|
||||
var second = service.ProcessIcsText(BuildIcs("v1", dtstart, null, "HED"));
|
||||
Assert.Equal(1, second.SubstitutionCount);
|
||||
Assert.Equal(0, second.SubstitutionCount);
|
||||
Assert.Single(substitutions.GetAll());
|
||||
}
|
||||
|
||||
|
||||
@@ -572,6 +572,51 @@ public sealed class TimeTrackingViewModelTests
|
||||
|
||||
Assert.False(called);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MissingTeachingTime_VergangenerUnterrichtstag_WirdInZeiterfassungAngezeigt()
|
||||
{
|
||||
var pastDay = DateOnly.FromDateTime(DateTime.Today).AddDays(-1);
|
||||
var slots = new FakeTimetableSlots();
|
||||
slots.Add(new TimetableSlot { Weekday = pastDay.DayOfWeek, PeriodNumber = 1 });
|
||||
var periodSchedule = TestSupport.BuildPeriodScheduleService();
|
||||
periodSchedule.SetPeriods([new PeriodTimeEntry
|
||||
{ PeriodNumber = 1, Start = new TimeOnly(8, 0), End = new TimeOnly(8, 45) }]);
|
||||
|
||||
var vm = new TimeTrackingViewModel(
|
||||
new FakeTimeEntries(), new FakeWorkTasks(), slots, periodSchedule);
|
||||
|
||||
var gap = Assert.Single(vm.MissingTeachingTimeEntries, i => i.Date == pastDay);
|
||||
Assert.Equal(new TimeOnly(7, 45), gap.WindowStart);
|
||||
Assert.Equal(new TimeOnly(8, 55), gap.WindowEnd);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddMissingTeachingTime_SpeichertVorgefuelltenTagUndEntferntIhnAusOffenerListe()
|
||||
{
|
||||
var pastDay = DateOnly.FromDateTime(DateTime.Today).AddDays(-1);
|
||||
var slots = new FakeTimetableSlots();
|
||||
slots.Add(new TimetableSlot { Weekday = pastDay.DayOfWeek, PeriodNumber = 1 });
|
||||
var periodSchedule = TestSupport.BuildPeriodScheduleService();
|
||||
periodSchedule.SetPeriods([new PeriodTimeEntry
|
||||
{ PeriodNumber = 1, Start = new TimeOnly(8, 0), End = new TimeOnly(8, 45) }]);
|
||||
var entries = new FakeTimeEntries();
|
||||
var vm = new TimeTrackingViewModel(entries, new FakeWorkTasks(), slots, periodSchedule);
|
||||
var gap = Assert.Single(vm.MissingTeachingTimeEntries, i => i.Date == pastDay);
|
||||
vm.OnAddMissingTeachingTime = item => Task.FromResult<TimeEntry?>(new TimeEntry
|
||||
{
|
||||
Date = item.Date,
|
||||
Category = TaskCategoryDisplay.Label(TaskCategory.Teaching),
|
||||
StartTime = item.WindowStart,
|
||||
EndTime = item.WindowEnd,
|
||||
DurationMinutes = (int)(item.WindowEnd - item.WindowStart).TotalMinutes,
|
||||
});
|
||||
|
||||
await vm.AddMissingTeachingTimeCommand.ExecuteAsync(gap);
|
||||
|
||||
Assert.Single(entries.GetByDate(pastDay));
|
||||
Assert.DoesNotContain(vm.MissingTeachingTimeEntries, i => i.Date == pastDay);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class AddTimeEntryDialogViewModelTests
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
using LehrerApp.Templating;
|
||||
using Xunit;
|
||||
|
||||
namespace LehrerApp.Desktop.Tests;
|
||||
|
||||
public sealed class _TempFlowCheck2
|
||||
{
|
||||
[Fact]
|
||||
public void MarkerTest()
|
||||
{
|
||||
var outDir = @"C:\Users\SHedt\AppData\Local\Temp\claude\d--source-LehrerApp\fb3681df-caaf-4f2d-9996-e343e44f5554\scratchpad";
|
||||
Directory.CreateDirectory(outDir);
|
||||
|
||||
var commands = new List<DrawingCommand>
|
||||
{
|
||||
new DrawStringEx(0, 0, 12, 170, "TOP-0", DrawingTextAlignment.AlignLeft, 10, Color: "#000000"),
|
||||
new DrawStringEx(0, 90, 12, 170, "NEARBOTTOM-90", DrawingTextAlignment.AlignLeft, 10, Color: "#000000"),
|
||||
new DrawStringEx(0, 105, 12, 170, "AFTERBOUNDARY-105", DrawingTextAlignment.AlignLeft, 10, Color: "#000000"),
|
||||
new DrawStringEx(0, 190, 12, 170, "BOTTOM-190", DrawingTextAlignment.AlignLeft, 10, Color: "#000000"),
|
||||
};
|
||||
var drawing = new DrawingValue(commands, 200);
|
||||
|
||||
var manifest = new TemplateManifest
|
||||
{
|
||||
Id = "marker", Name = "Marker",
|
||||
Placeholders = [new("Marker", PlaceholderType.Drawing, true)],
|
||||
};
|
||||
var layout = "PAGE 210 297 mm\nFLOWDRAWBOX 20 20 170 100 $Marker\n";
|
||||
var loadedLayout = new LayoutParser().Parse(layout);
|
||||
var loaded = new LoadedTemplate(manifest, loadedLayout, new Dictionary<string, byte[]>());
|
||||
var provider = new FakeProvider(new Dictionary<string, PlaceholderValue> { ["Marker"] = drawing });
|
||||
|
||||
var pngs = new QuestTemplateRenderer().RenderPagesToPng(loaded, provider, dpi: 150);
|
||||
for (var i = 0; i < pngs.Count; i++)
|
||||
File.WriteAllBytes(Path.Combine(outDir, $"marker2-{i}.png"), pngs[i]);
|
||||
}
|
||||
|
||||
private sealed class FakeProvider(IReadOnlyDictionary<string, PlaceholderValue> values) : ITemplateDataProvider
|
||||
{ public IReadOnlyDictionary<string, PlaceholderValue> GetValues() => values; }
|
||||
}
|
||||
@@ -16,6 +16,8 @@
|
||||
<StreamGeometry x:Key="IconCalendar">M3,4 H21 V22 H3 Z M5,10 V20 H19 V10 Z M7,2 H9 V7 H7 Z M15,2 H17 V7 H15 Z M7,12 H10 V15 H7 Z M12,12 H15 V15 H12 Z M7,17 H10 V19 H7 Z M12,17 H15 V19 H12 Z</StreamGeometry>
|
||||
<StreamGeometry x:Key="IconClock">M12,2 A10,10 0 1 0 12,22 A10,10 0 1 0 12,2 M12,5 A7,7 0 1 1 12,19 A7,7 0 1 1 12,5 M11,7 H13 V12 L17,14 L16,16 L11,13 Z</StreamGeometry>
|
||||
<StreamGeometry x:Key="IconClassTeacher">M2,8 L12,3 L22,8 L12,13 Z M6,11 V16 C9,19 15,19 18,16 V11 M22,8 V15</StreamGeometry>
|
||||
<!-- Klassenbuch mit Ausrufezeichen für noch offene Einträge. -->
|
||||
<StreamGeometry x:Key="IconOpenPeriods">M5,2 H19 A2,2 0 0 1 21,4 V20 A2,2 0 0 1 19,22 H5 A2,2 0 0 1 3,20 V4 A2,2 0 0 1 5,2 Z M7,4 V20 H19 V4 Z M11,7 H14 V13 H11 Z M11,15 H14 V18 H11 Z</StreamGeometry>
|
||||
<StreamGeometry x:Key="IconSettings">M3,5 H21 V7 H3 Z M8,3 A3,3 0 1 0 8,9 A3,3 0 1 0 8,3 M3,11 H21 V13 H3 Z M16,9 A3,3 0 1 0 16,15 A3,3 0 1 0 16,9 M3,17 H21 V19 H3 Z M10,15 A3,3 0 1 0 10,21 A3,3 0 1 0 10,15</StreamGeometry>
|
||||
<StreamGeometry x:Key="IconRefresh">M12,3 A9,9 0 0 1 21,12 H18 A6,6 0 0 0 8,7 L11,10 H3 V2 L6,5 A9,9 0 0 1 12,3 M12,21 A9,9 0 0 1 3,12 H6 A6,6 0 0 0 16,17 L13,14 H21 V22 L18,19 A9,9 0 0 1 12,21</StreamGeometry>
|
||||
</ResourceDictionary>
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Markup.Xaml;
|
||||
using Avalonia.Styling;
|
||||
using Avalonia.Threading;
|
||||
using LehrerApp.Core.Interfaces;
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Core.Services;
|
||||
@@ -24,6 +26,8 @@ public class App : Application
|
||||
public static IServiceProvider Services { get; private set; } = null!;
|
||||
private static ServiceProvider? _serviceProvider;
|
||||
private static bool _exitHandlerAttached;
|
||||
private static Task _initialPolls = Task.CompletedTask;
|
||||
private static readonly CancellationTokenSource StartupCancellation = new();
|
||||
|
||||
public override void Initialize() => AvaloniaXamlLoader.Load(this);
|
||||
|
||||
@@ -37,6 +41,21 @@ public class App : Application
|
||||
ApplyTheme(new AppearanceSettingsService(AppBootstrapper.ResolveAppDataPath()).Load());
|
||||
|
||||
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||||
{
|
||||
// Erst den Splashscreen anzeigen und die synchrone Initialisierung in den ersten
|
||||
// Dispatcher-Durchlauf verschieben, damit das Ladebild vorher gezeichnet wird.
|
||||
var splash = new SplashWindow();
|
||||
desktop.MainWindow = splash;
|
||||
Dispatcher.UIThread.Post(
|
||||
() => ContinueStartup(desktop, splash),
|
||||
DispatcherPriority.Background);
|
||||
}
|
||||
|
||||
base.OnFrameworkInitializationCompleted();
|
||||
}
|
||||
|
||||
private static async void ContinueStartup(
|
||||
IClassicDesktopStyleApplicationLifetime desktop, SplashWindow splash)
|
||||
{
|
||||
// Verschlüsselte Datenbank (13.3.4): Passwort abfragen, bevor die Datenbank
|
||||
// (und damit BuildServices, das sie öffnet) angefasst wird.
|
||||
@@ -45,34 +64,42 @@ public class App : Application
|
||||
var promptVm = new DbPasswordPromptViewModel(
|
||||
new DatabaseEncryptionService(), AppBootstrapper.ResolveDbPath());
|
||||
var promptWindow = new DbPasswordPromptWindow { DataContext = promptVm };
|
||||
promptVm.OnUnlocked = password =>
|
||||
promptVm.OnUnlocked = async password =>
|
||||
{
|
||||
AppBootstrapper.DbPassword = password;
|
||||
StartMainApp(desktop, showImmediately: true);
|
||||
var unlockedSplash = new SplashWindow();
|
||||
desktop.MainWindow = unlockedSplash;
|
||||
unlockedSplash.Show();
|
||||
promptWindow.Close();
|
||||
await StartMainAppAsync(desktop, unlockedSplash);
|
||||
};
|
||||
desktop.MainWindow = promptWindow;
|
||||
}
|
||||
else
|
||||
{
|
||||
StartMainApp(desktop, showImmediately: false);
|
||||
}
|
||||
promptWindow.Show();
|
||||
splash.Close();
|
||||
return;
|
||||
}
|
||||
|
||||
base.OnFrameworkInitializationCompleted();
|
||||
await StartMainAppAsync(desktop, splash);
|
||||
}
|
||||
|
||||
private static void StartMainApp(
|
||||
IClassicDesktopStyleApplicationLifetime desktop, bool showImmediately)
|
||||
private static async Task StartMainAppAsync(
|
||||
IClassicDesktopStyleApplicationLifetime desktop, Window? windowToClose = null)
|
||||
{
|
||||
_serviceProvider = AppBootstrapper.BuildServices();
|
||||
var splash = windowToClose as SplashWindow;
|
||||
var timer = System.Diagnostics.Stopwatch.StartNew();
|
||||
var progress = new Progress<(int Value, string Text)>(step =>
|
||||
splash?.SetProgress(step.Value, step.Text));
|
||||
_serviceProvider = await Task.Run(() => AppBootstrapper.BuildServices(
|
||||
(value, text) => ((IProgress<(int, string)>)progress).Report((value, text))));
|
||||
Services = _serviceProvider;
|
||||
Services.GetRequiredService<AppLogger>().Info("Anwendung gestartet.");
|
||||
GlobalExceptionHandler.AttachNotifications(Services.GetRequiredService<NotificationService>());
|
||||
// Papierkorb (14.3): Einträge älter als 30 Tage endgültig entfernen. Beim Start statt per
|
||||
// Timer - reicht für ein Werkzeug, das ohnehin nur "Fehlklick eben rückgängig machen" sein
|
||||
// soll, kein dauerhaftes Archiv.
|
||||
Services.GetRequiredService<ITrashRepository>().PurgeOlderThan(DateTime.UtcNow.AddDays(-30));
|
||||
splash?.SetProgress(60, "Papierkorb aufräumen …");
|
||||
await Task.Run(() => Services.GetRequiredService<ITrashRepository>()
|
||||
.PurgeOlderThan(DateTime.UtcNow.AddDays(-30)));
|
||||
|
||||
if (!_exitHandlerAttached)
|
||||
{
|
||||
@@ -80,23 +107,49 @@ public class App : Application
|
||||
_exitHandlerAttached = true;
|
||||
}
|
||||
|
||||
// MCP-Server (lokal, Phase 1): Start ist ohne Wirkung, falls in den Einstellungen nicht
|
||||
// aktiviert (siehe McpServerHostedService.Start). Kein Live-Reload beim Umschalten des
|
||||
// Opt-in - ein Neustart der App richtet den Pipe-Listener neu ein.
|
||||
Services.GetRequiredService<Services.Mcp.McpServerHostedService>().Start();
|
||||
|
||||
splash?.SetProgress(75, "Übersicht vorbereiten …");
|
||||
await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.Background);
|
||||
var mainVm = Services.GetRequiredService<MainWindowViewModel>();
|
||||
WireCallbacks(mainVm);
|
||||
|
||||
// DI-Singletons werden erst beim ersten Auflösen erzeugt. Ohne dieses explizite
|
||||
// Auflösen entstand der Timer des optionalen WebUntis-Abgleichs erst, wenn die
|
||||
// Einstellungen geöffnet oder ein manueller Abruf gestartet wurde. Den Dienst beim
|
||||
// Anwendungsstart aktivieren und wie den Jahresplan sofort einmal abgleichen; danach
|
||||
// übernimmt sein stündlicher Timer.
|
||||
if (Services.GetService<UntisSyncService>() is { } untisSync)
|
||||
_ = untisSync.PollAsync();
|
||||
splash?.SetProgress(90, "Hauptfenster öffnen …");
|
||||
await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.Background);
|
||||
|
||||
var main = new MainWindow { DataContext = mainVm };
|
||||
main.EnableWindowSizePersistence(Services.GetRequiredService<WindowSettingsService>());
|
||||
if (Services.GetService<SyncEngine>() is { } syncEngine)
|
||||
main.EnableFinalSync(syncEngine);
|
||||
desktop.MainWindow = main;
|
||||
if (showImmediately) main.Show();
|
||||
main.Show();
|
||||
splash?.SetProgress(100, "Bereit");
|
||||
windowToClose?.Close();
|
||||
AppBootstrapper.Logger.Info($"Start: Hauptfenster nach {timer.ElapsedMilliseconds} ms geöffnet.");
|
||||
|
||||
// Vorhandene lokale Daten sind sofort nutzbar; Netzwerkzugriffe blockieren den Start nicht.
|
||||
var untis = Services.GetService<UntisSyncService>();
|
||||
var annualPlan = Services.GetService<AnnualPlanSyncService>();
|
||||
if (untis is not null)
|
||||
untis.DataChanged += () => Dispatcher.UIThread.Post(() =>
|
||||
{
|
||||
Services.GetRequiredService<TimetableViewModel>().Load();
|
||||
Services.GetRequiredService<DashboardViewModel>().RefreshCommand.Execute(null);
|
||||
});
|
||||
_initialPolls = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.WhenAll(
|
||||
untis?.PollAsync(StartupCancellation.Token) ?? Task.CompletedTask,
|
||||
annualPlan?.PollAsync(StartupCancellation.Token) ?? Task.CompletedTask);
|
||||
}
|
||||
catch (OperationCanceledException) when (StartupCancellation.IsCancellationRequested) { }
|
||||
catch (Exception ex) { AppBootstrapper.Logger.Error("Erstabgleich fehlgeschlagen.", ex); }
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>Wechselt die Darstellung sofort, ohne Neustart (12.4) — Avalonia stylt den
|
||||
@@ -117,6 +170,8 @@ public class App : Application
|
||||
|
||||
try
|
||||
{
|
||||
StartupCancellation.Cancel();
|
||||
_initialPolls.GetAwaiter().GetResult();
|
||||
serviceProvider.GetService<LiteDbContext>()?.Checkpoint();
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
@@ -4,6 +4,8 @@ using LehrerApp.Core.Services;
|
||||
using LehrerApp.Data;
|
||||
using LehrerApp.Data.Repositories;
|
||||
using LehrerApp.Desktop.Services;
|
||||
using LehrerApp.Desktop.Services.Mcp;
|
||||
using LehrerApp.Desktop.Services.Mcp.Tools;
|
||||
using LehrerApp.Desktop.ViewModels;
|
||||
using LehrerApp.Desktop.ViewModels.ClassTeacher;
|
||||
using LehrerApp.Desktop.ViewModels.Exams;
|
||||
@@ -99,7 +101,7 @@ public static class AppBootstrapper
|
||||
Environment.Exit(0);
|
||||
}
|
||||
|
||||
public static ServiceProvider BuildServices()
|
||||
public static ServiceProvider BuildServices(Action<int, string>? reportProgress = null)
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
|
||||
@@ -121,13 +123,16 @@ public static class AppBootstrapper
|
||||
services.AddSingleton<ITemplateLoader, TemplateLoader>();
|
||||
services.AddSingleton<ITemplateRenderer, QuestTemplateRenderer>();
|
||||
services.AddSingleton(_ => new TemplateStore(appData));
|
||||
services.AddSingleton(_ => new WorksheetTemplateStore(new TemplateStore(appData, subfolder: "worksheet-template-packages")));
|
||||
|
||||
// ── Datensicherheit (13.3) ───────────────────────────────────────────
|
||||
// Backup läuft vor dem Öffnen der Datenbank, rein dateibasiert (unabhängig von
|
||||
// Verschlüsselung) — reine Datei-Kopie, kein offener LiteDB-Handle nötig.
|
||||
var backupSettings = new BackupSettingsService(appData);
|
||||
var backup = new BackupService(appData) { SecondaryBackupDirectory = backupSettings.LoadSecondaryDirectory() };
|
||||
reportProgress?.Invoke(10, "Sicherung erstellen …");
|
||||
var backupPath = backup.CreateBackup(DbPath);
|
||||
reportProgress?.Invoke(25, "Sicherung prüfen …");
|
||||
// Best-effort-Prüfung des automatischen Startbackups: nur geloggt, kein Blocker für den
|
||||
// Programmstart — ein beschädigtes Backup soll auffallen, nicht den Nutzer aufhalten.
|
||||
if (backupPath is not null && !new DatabaseEncryptionService().CanOpenAndRead(backupPath, DbPassword))
|
||||
@@ -162,6 +167,7 @@ public static class AppBootstrapper
|
||||
services.AddSingleton<IUnitRepository, UnitRepository>();
|
||||
services.AddSingleton<ILessonRepository, LessonRepository>();
|
||||
services.AddSingleton<IDocumentationRepository, DocumentationRepository>();
|
||||
services.AddSingleton<IVorgangRepository, VorgangRepository>();
|
||||
services.AddSingleton<IWorkTaskRepository, WorkTaskRepository>();
|
||||
services.AddSingleton<ITimeEntryRepository, TimeEntryRepository>();
|
||||
services.AddSingleton<IParticipationSessionRepository, ParticipationSessionRepository>();
|
||||
@@ -170,6 +176,7 @@ public static class AppBootstrapper
|
||||
services.AddSingleton<IParticipationSectionRepository, ParticipationSectionRepository>();
|
||||
services.AddSingleton<ISubjectRepository, SubjectRepository>();
|
||||
services.AddSingleton<ICompetencyDomainRepository, CompetencyDomainRepository>();
|
||||
services.AddSingleton<ICompetencyCatalogVersionRepository, CompetencyCatalogVersionRepository>();
|
||||
services.AddSingleton<IShorthandCodeRepository, ShorthandCodeRepository>();
|
||||
services.AddSingleton<IAlternativeLessonPathRepository, AlternativeLessonPathRepository>();
|
||||
services.AddSingleton<IAttachmentStorage, LiteAttachmentStorage>();
|
||||
@@ -184,6 +191,7 @@ public static class AppBootstrapper
|
||||
services.AddSingleton<IUntisClassRegisterCacheRepository, UntisClassRegisterCacheRepository>();
|
||||
services.AddSingleton<IUntisCacheFetchStateRepository, UntisCacheFetchStateRepository>();
|
||||
services.AddSingleton<IUntisStudentRosterCacheRepository, UntisStudentRosterCacheRepository>();
|
||||
services.AddSingleton<IUntisHubJobStateRepository, UntisHubJobStateRepository>();
|
||||
|
||||
// ── Services ──────────────────────────────────────────────────────────
|
||||
services.AddSingleton<GradingService>();
|
||||
@@ -195,15 +203,41 @@ public static class AppBootstrapper
|
||||
services.AddSingleton(_ => new PeriodScheduleService(appData));
|
||||
services.AddSingleton(_ => new WorkloadSettingsService(appData));
|
||||
services.AddSingleton(_ => new DashboardSettingsService(appData));
|
||||
services.AddSingleton(_ => new PatternScoreSettingsService(appData));
|
||||
services.AddSingleton(_ => new WindowSettingsService(appData));
|
||||
services.AddSingleton(_ => new AppearanceSettingsService(appData));
|
||||
services.AddSingleton<PlanningExchangeService>();
|
||||
|
||||
// ── KI-Unterstützung (4.5.9, optional – nur wenn in den Einstellungen aktiviert) ──────
|
||||
services.AddSingleton(_ => new AiSettingsService(appData));
|
||||
services.AddSingleton(_ => new HttpClient { BaseAddress = new Uri(AiBackendUrl) });
|
||||
services.AddSingleton(_ => new HttpClient
|
||||
{
|
||||
BaseAddress = new Uri(AiBackendUrl),
|
||||
// Das PHP-Backend wartet höchstens 180 s auf umfangreiche KI-Antworten. Der Client
|
||||
// bleibt bewusst etwas länger offen, damit dessen konkrete Fehlermeldung noch ankommt.
|
||||
Timeout = TimeSpan.FromSeconds(210),
|
||||
});
|
||||
services.AddSingleton<AiPlanningService>();
|
||||
|
||||
// ── MCP-Server (lokal, Phase 1 – siehe Planungsdokument, optional per Opt-in) ─────────
|
||||
services.AddSingleton(_ => new McpSettingsService(appData));
|
||||
services.AddSingleton<IMcpConfirmationService, AvaloniaMcpConfirmationService>();
|
||||
services.AddSingleton<StudentTools>();
|
||||
services.AddSingleton<ExamTools>();
|
||||
services.AddSingleton<GradeTools>();
|
||||
services.AddSingleton<ScheduleTools>();
|
||||
services.AddSingleton<TimeEntryTools>();
|
||||
services.AddSingleton<LessonPlanTools>();
|
||||
services.AddSingleton<GroupMembershipTools>();
|
||||
services.AddSingleton<LetterTemplateTools>();
|
||||
services.AddSingleton<StudentAttendanceCalendarService>();
|
||||
services.AddSingleton<CompetencyTools>();
|
||||
services.AddSingleton<GroupTools>();
|
||||
services.AddSingleton<ParticipationTools>();
|
||||
services.AddSingleton<UntisComparisonTools>();
|
||||
services.AddSingleton<McpServerHostedService>();
|
||||
services.AddSingleton<McpClientRegistrationService>();
|
||||
|
||||
// ── WebUntis-iCal-Abgleich (optional – nur wenn URL hinterlegt und aktiviert) ─────────
|
||||
var untisSettings = new WebUntisSettingsService(appData);
|
||||
services.AddSingleton(untisSettings);
|
||||
@@ -240,6 +274,7 @@ public static class AppBootstrapper
|
||||
services.AddSingleton(sp => new SchoolWeatherService(new HttpClient(), syncSettings));
|
||||
services.AddSingleton(sp => new WebUntisIntegrationService(new HttpClient(), untisSettings));
|
||||
services.AddSingleton<UntisReportCacheService>();
|
||||
services.AddSingleton<UntisHubService>();
|
||||
// War dieses Gerät schon eingeloggt, aber sync.key fehlt(e), wurde gerade eben (unten)
|
||||
// stillschweigend ein neuer, unabhängiger Schlüssel erzeugt - bisher unter dem ALTEN
|
||||
// Schlüssel synchronisierte Server-Daten sind für dieses Gerät dann nicht mehr lesbar.
|
||||
@@ -315,6 +350,7 @@ public static class AppBootstrapper
|
||||
services.AddSingleton<WorkloadEvaluationViewModel>();
|
||||
services.AddSingleton<WorkloadViewModel>();
|
||||
services.AddSingleton<ClassTeacherDetailsViewModel>();
|
||||
services.AddSingleton<ClassTeacherCasesViewModel>();
|
||||
services.AddSingleton<ClassTeacherOverviewViewModel>();
|
||||
services.AddSingleton<ExamsOverviewViewModel>();
|
||||
|
||||
@@ -332,7 +368,9 @@ public static class AppBootstrapper
|
||||
services.AddTransient<TrashViewModel>();
|
||||
services.AddTransient<SettingsViewModel>();
|
||||
|
||||
reportProgress?.Invoke(40, "Datenbank öffnen und aktualisieren …");
|
||||
var provider = services.BuildServiceProvider();
|
||||
provider.GetRequiredService<LiteDbContext>();
|
||||
|
||||
// Sync-agnostischer Hook auf LiteDbContext (siehe LiteDbContext.OnChange) wird erst hier,
|
||||
// außerhalb der Repository-Registrierung, mit der tatsächlichen Sync-Logik verbunden.
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.2 MiB |
@@ -0,0 +1,22 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using Avalonia.Data.Converters;
|
||||
|
||||
namespace LehrerApp.Desktop.Converters;
|
||||
|
||||
/// <summary>`CalendarDatePicker.SelectedDate` ist (anders als der eingebaute `DatePicker`) vom
|
||||
/// WPF-Toolkit übernommenes `DateTime?`, während Datumsfelder in dieser Codebasis durchgängig
|
||||
/// `DateTimeOffset`(?) sind. Avalonia bietet dafür keine automatische Konvertierung
|
||||
/// (`TypeUtilities.TryConvert`/`TryConvertImplicit` unterstützen `DateTime`↔`DateTimeOffset`
|
||||
/// nicht) — ohne diesen Converter bleibt die Bindung beim Anzeigen stumm leer und wirft beim
|
||||
/// Zurückschreiben eine `InvalidCastException`.</summary>
|
||||
public sealed class DateTimeOffsetToDateTimeConverter : IValueConverter
|
||||
{
|
||||
public static readonly DateTimeOffsetToDateTimeConverter Instance = new();
|
||||
|
||||
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
value is DateTimeOffset offset ? offset.DateTime : null;
|
||||
|
||||
public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
value is DateTime dateTime ? new DateTimeOffset(DateTime.SpecifyKind(dateTime, DateTimeKind.Local)) : null;
|
||||
}
|
||||
@@ -21,6 +21,7 @@
|
||||
<PackageReference Include="CommunityToolkit.Mvvm" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
|
||||
<PackageReference Include="QuestPDF" />
|
||||
<PackageReference Include="ModelContextProtocol.Core" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<AvaloniaResource Include="Assets\**" />
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Avalonia;
|
||||
using LehrerApp.Core.Mcp;
|
||||
using LehrerApp.Desktop.Services;
|
||||
|
||||
namespace LehrerApp.Desktop;
|
||||
@@ -8,6 +9,10 @@ class Program
|
||||
[STAThread]
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
// Muss vor der ersten NamedPipeServerStream-Instanz laufen (siehe
|
||||
// McpServerHostedService), sonst löst TMPDIR-Auseinanderdriften zwischen diesem Prozess
|
||||
// und LehrerApp.McpBridge auf macOS/Linux "MCP nicht erreichbar" aus - siehe Doku dort.
|
||||
McpPipeConstants.EnsureStableUnixSocketDirectory();
|
||||
var logger = AppBootstrapper.EnsureLogger();
|
||||
GlobalExceptionHandler.Install(logger);
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using LehrerApp.Core.AiPlanning;
|
||||
using LehrerApp.Core.Interfaces;
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Core.Services;
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
@@ -10,7 +11,14 @@ using System.Text.Json.Serialization;
|
||||
namespace LehrerApp.Desktop.Services;
|
||||
|
||||
/// <summary>Fehler beim Aufruf des KI-Backends, Message ist bereits deutsch und nutzergerichtet.</summary>
|
||||
public class AiBackendException(string userMessage) : Exception(userMessage);
|
||||
public class AiBackendException(string userMessage, string? rawResponse = null) : Exception(userMessage)
|
||||
{
|
||||
/// <summary>
|
||||
/// Unveränderte Modellantwort, sofern der Fehler beim Lesen einer Planungsantwort entstand.
|
||||
/// Sie wird ausschließlich für den ausdrücklich vom Nutzer gestarteten Rettungsdialog gehalten.
|
||||
/// </summary>
|
||||
public string? RawResponse { get; } = rawResponse;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Der KI-Wire-Vertrag verwendet deutsches Datumsformat (siehe ai-backend/plan.php Systemprompt,
|
||||
@@ -65,7 +73,8 @@ public class GermanTimeOnlyJsonConverter : JsonConverter<TimeOnly>
|
||||
/// </summary>
|
||||
public class AiPlanningService(HttpClient http, ILessonRepository lessons,
|
||||
IGroupRepository groups, ISubjectRepository subjects,
|
||||
ICompetencyDomainRepository competencyDomains, IAlternativeLessonPathRepository altPaths)
|
||||
ICompetencyDomainRepository competencyDomains, ICompetencyCatalogVersionRepository competencyVersions,
|
||||
IAlternativeLessonPathRepository altPaths)
|
||||
{
|
||||
// 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.
|
||||
@@ -87,16 +96,19 @@ public class AiPlanningService(HttpClient http, ILessonRepository lessons,
|
||||
private static async Task<AiBackendException> BuildRequestFailedExceptionAsync(HttpResponseMessage resp)
|
||||
{
|
||||
string? backendReason = null;
|
||||
string? rawResponse = null;
|
||||
try
|
||||
{
|
||||
var body = await resp.Content.ReadFromJsonAsync<BackendErrorResult>(JsonOptions);
|
||||
var responseText = await resp.Content.ReadAsStringAsync();
|
||||
var body = JsonSerializer.Deserialize<BackendErrorResult>(responseText, JsonOptions);
|
||||
backendReason = string.IsNullOrWhiteSpace(body?.Error) ? null : body!.Error;
|
||||
rawResponse = string.IsNullOrWhiteSpace(body?.RawResponse) ? null : body!.RawResponse;
|
||||
}
|
||||
catch { /* Antwortkörper war kein valides {"error": "..."}-JSON - Fallback unten greift. */ }
|
||||
|
||||
return new AiBackendException(backendReason is null
|
||||
? "Die Anfrage an den KI-Dienst ist fehlgeschlagen."
|
||||
: $"Die Anfrage an den KI-Dienst ist fehlgeschlagen: {backendReason}");
|
||||
: $"Die Anfrage an den KI-Dienst ist fehlgeschlagen: {backendReason}", rawResponse);
|
||||
}
|
||||
|
||||
public async Task<string> LoginAsync(string username, string password)
|
||||
@@ -155,7 +167,8 @@ public class AiPlanningService(HttpClient http, ILessonRepository lessons,
|
||||
|
||||
var competencyCatalog = subject is null
|
||||
? []
|
||||
: competencyDomains.GetBySubjectAndGrade(subject.Id, gradeLevel)
|
||||
: competencyDomains.GetBySubjectAndGrade(subject.Id, gradeLevel,
|
||||
CompetencyCatalogVersionResolver.Resolve(competencyVersions, subject.Id, group?.CompetencyCatalogVersionId))
|
||||
.Select(d => new AiCompetencyDomain
|
||||
{
|
||||
Name = d.Name,
|
||||
@@ -178,6 +191,7 @@ public class AiPlanningService(HttpClient http, ILessonRepository lessons,
|
||||
StartTime = l.StartTime,
|
||||
Homework = l.Homework,
|
||||
Reflection = l.Reflection,
|
||||
PlanningIdeas = l.PlanningIdeas,
|
||||
Phases = ToAiPhases(l.Phases, pathNames),
|
||||
})
|
||||
.ToList();
|
||||
@@ -191,7 +205,7 @@ public class AiPlanningService(HttpClient http, ILessonRepository lessons,
|
||||
Title = unit.Title,
|
||||
StartDate = unit.StartDate,
|
||||
EndDate = unit.EndDate,
|
||||
Competencies = unit.Competencies,
|
||||
Competencies = unit.Competencies.Select(c => c.Code).ToList(),
|
||||
Notes = unit.Notes,
|
||||
SubjectName = subject?.Name ?? "",
|
||||
GradeLevel = gradeLevel,
|
||||
@@ -260,6 +274,9 @@ public class AiPlanningService(HttpClient http, ILessonRepository lessons,
|
||||
if (!string.Equals(existing.Reflection, proposed.Reflection, StringComparison.Ordinal))
|
||||
diffs.Add("Reflexion geändert");
|
||||
|
||||
if (!string.Equals(existing.PlanningIdeas, proposed.PlanningIdeas, StringComparison.Ordinal))
|
||||
diffs.Add("Planungsideen geändert");
|
||||
|
||||
var pathNames = altPaths.GetAll().ToDictionary(p => p.Id, p => p.Name);
|
||||
var existingPhases = ToAiPhases(existing.Phases, pathNames);
|
||||
if (!PhasesEqual(existingPhases, proposed.Phases))
|
||||
@@ -340,6 +357,12 @@ public class AiPlanningService(HttpClient http, ILessonRepository lessons,
|
||||
|
||||
HttpResponseMessage resp;
|
||||
try { resp = await http.SendAsync(req); }
|
||||
catch (TaskCanceledException)
|
||||
{
|
||||
throw new AiBackendException(
|
||||
"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.");
|
||||
}
|
||||
catch (HttpRequestException)
|
||||
{
|
||||
throw new AiBackendException("Der KI-Dienst ist nicht erreichbar. Bitte Internetverbindung prüfen.");
|
||||
@@ -352,14 +375,64 @@ public class AiPlanningService(HttpClient http, ILessonRepository lessons,
|
||||
if (!resp.IsSuccessStatusCode)
|
||||
throw await BuildRequestFailedExceptionAsync(resp);
|
||||
|
||||
var responseText = await resp.Content.ReadAsStringAsync();
|
||||
try
|
||||
{
|
||||
var result = await resp.Content.ReadFromJsonAsync<AiPlanningResponse>(JsonOptions);
|
||||
var result = JsonSerializer.Deserialize<AiPlanningResponse>(responseText, JsonOptions);
|
||||
return result ?? throw new AiBackendException("Die Antwort der KI konnte nicht verarbeitet werden.");
|
||||
}
|
||||
catch (Exception ex) when (ex is not AiBackendException)
|
||||
{
|
||||
throw new AiBackendException("Die Antwort der KI konnte nicht verarbeitet werden. Bitte erneut versuchen.");
|
||||
string? rawModelResponse = null;
|
||||
try
|
||||
{
|
||||
using var envelope = JsonDocument.Parse(responseText);
|
||||
if (envelope.RootElement.TryGetProperty("rawResponse", out var rawElement)
|
||||
&& rawElement.ValueKind == JsonValueKind.String)
|
||||
rawModelResponse = rawElement.GetString();
|
||||
}
|
||||
catch (JsonException) { /* Die HTTP-Antwort selbst war ungültig; unten komplett zeigen. */ }
|
||||
|
||||
throw new AiBackendException(
|
||||
"Die Antwort der KI konnte nicht verarbeitet werden. Du kannst die Antwort manuell retten.",
|
||||
string.IsNullOrWhiteSpace(rawModelResponse) ? responseText : rawModelResponse);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Liest eine von Hand markierte Modellantwort. Akzeptiert die normale Antwort-Hülle, ein
|
||||
/// einzelnes Lesson-Objekt oder ein Array von Lessons, damit auch nur der relevante Ausschnitt
|
||||
/// der Rohantwort markiert werden kann.
|
||||
/// </summary>
|
||||
public static List<AiLesson> ParsePlanningLessons(string json)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(json))
|
||||
throw new AiBackendException("Bitte markiere zuerst den JSON-Abschnitt der Antwort.");
|
||||
|
||||
try
|
||||
{
|
||||
using var document = JsonDocument.Parse(json);
|
||||
var root = document.RootElement;
|
||||
List<AiLesson>? parsed = root.ValueKind switch
|
||||
{
|
||||
JsonValueKind.Object when root.TryGetProperty("lessons", out _) =>
|
||||
JsonSerializer.Deserialize<AiPlanningResponse>(json, JsonOptions)?.Lessons,
|
||||
JsonValueKind.Object =>
|
||||
[JsonSerializer.Deserialize<AiLesson>(json, JsonOptions)
|
||||
?? throw new JsonException("Leere Stunde")],
|
||||
JsonValueKind.Array => JsonSerializer.Deserialize<List<AiLesson>>(json, JsonOptions),
|
||||
_ => null,
|
||||
};
|
||||
|
||||
if (parsed is null || parsed.Count == 0)
|
||||
throw new JsonException("Keine Stunde enthalten");
|
||||
if (parsed.Any(l => string.IsNullOrWhiteSpace(l.Topic)))
|
||||
throw new JsonException("Mindestens einer Stunde fehlt das Feld topic");
|
||||
return parsed;
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
throw new AiBackendException($"Der markierte Text ist noch kein gültiges Stunden-JSON: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -520,6 +593,7 @@ public class AiPlanningService(HttpClient http, ILessonRepository lessons,
|
||||
StartTime = ai.StartTime,
|
||||
Homework = ai.Homework,
|
||||
Reflection = ai.Reflection,
|
||||
PlanningIdeas = ai.PlanningIdeas,
|
||||
// Status bleibt bei einer Änderung erhalten — sonst würde eine bereits
|
||||
// durchgeführte Stunde durch eine KI-Anpassung stillschweigend auf "Geplant"
|
||||
// zurückgesetzt (die KI kennt/liefert diesen Status gar nicht).
|
||||
@@ -531,6 +605,10 @@ public class AiPlanningService(HttpClient http, ILessonRepository lessons,
|
||||
Activity = p.Activity,
|
||||
Material = p.Material,
|
||||
Shorthand = p.Shorthand,
|
||||
// Persistiert den Prompt (4.5.20/4.5.36), damit er nach dem Übernehmen weiterhin
|
||||
// im Stundeneditor kopierbar bleibt statt nur einmalig im Review-Dialog.
|
||||
MaterialPrompt = string.IsNullOrWhiteSpace(p.MaterialSuggestion)
|
||||
? null : BuildMaterialPrompt(unit, ai, p),
|
||||
AlternativePathId = p.AlternativePathName is { } name && pathIdsByName.TryGetValue(name, out var pathId)
|
||||
? pathId : null,
|
||||
}).ToList(),
|
||||
@@ -539,7 +617,64 @@ public class AiPlanningService(HttpClient http, ILessonRepository lessons,
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fragt für eine Charge anonymisierter Fehlzeitenzeilen (ai-backend/untis-status.php,
|
||||
/// Nutzer-Feedback zum Untis-Hub) einen Statusvorschlag ab - eine Anfrage für alle fraglichen
|
||||
/// Zeilen eines Abgleichslaufs statt einer je Zeile (Kosten/Latenz-Überlegung aus der
|
||||
/// Nutzerdiskussion). Liefert nur dann Vorschläge zurück, wenn die vom Backend gemeldete
|
||||
/// Id-Menge exakt der gesendeten entspricht (keine fehlenden, zusätzlichen oder doppelten Ids) -
|
||||
/// andernfalls eine leere Zuordnung, statt sich auf eine möglicherweise vermischte Reihenfolge
|
||||
/// zu verlassen. Der Aufrufer behält für jede nicht zurückgelieferte Id den bisherigen
|
||||
/// regelbasierten Status bei.
|
||||
/// </summary>
|
||||
public async Task<IReadOnlyDictionary<string, string>> RequestUntisStatusSuggestionsAsync(
|
||||
IReadOnlyList<AiUntisStatusRow> rows, string token)
|
||||
{
|
||||
if (rows.Count == 0) return new Dictionary<string, string>();
|
||||
|
||||
using var req = new HttpRequestMessage(HttpMethod.Post, "untis-status.php")
|
||||
{
|
||||
Content = JsonContent.Create(new AiUntisStatusRequest { Rows = rows.ToList() }, options: JsonOptions),
|
||||
};
|
||||
req.Headers.Authorization = new("Bearer", token);
|
||||
|
||||
HttpResponseMessage resp;
|
||||
try { resp = await http.SendAsync(req); }
|
||||
catch (HttpRequestException)
|
||||
{
|
||||
throw new AiBackendException("Der KI-Dienst ist nicht erreichbar. Bitte Internetverbindung prüfen.");
|
||||
}
|
||||
|
||||
if (resp.StatusCode == HttpStatusCode.Unauthorized)
|
||||
throw new AiBackendException("Anmeldung abgelaufen. Bitte in den Einstellungen erneut anmelden.");
|
||||
if (resp.StatusCode == (HttpStatusCode)402)
|
||||
throw new AiBackendException("Nicht genügend KI-Guthaben. Bitte Guthaben aufladen.");
|
||||
if (!resp.IsSuccessStatusCode)
|
||||
throw await BuildRequestFailedExceptionAsync(resp);
|
||||
|
||||
AiUntisStatusResponse? result;
|
||||
try { result = await resp.Content.ReadFromJsonAsync<AiUntisStatusResponse>(JsonOptions); }
|
||||
catch (Exception ex) when (ex is not AiBackendException)
|
||||
{
|
||||
throw new AiBackendException("Die Antwort der KI konnte nicht verarbeitet werden. Bitte erneut versuchen.");
|
||||
}
|
||||
if (result is null)
|
||||
throw new AiBackendException("Die Antwort der KI konnte nicht verarbeitet werden.");
|
||||
|
||||
var sentIds = rows.Select(r => r.Id).ToHashSet();
|
||||
var receivedIds = result.Suggestions.Select(s => s.Id).ToList();
|
||||
if (receivedIds.Count != sentIds.Count || receivedIds.Distinct().Count() != receivedIds.Count
|
||||
|| !sentIds.SetEquals(receivedIds))
|
||||
return new Dictionary<string, string>();
|
||||
|
||||
return result.Suggestions.ToDictionary(s => s.Id, s => s.Status);
|
||||
}
|
||||
|
||||
private class LoginResult { public string Token { get; set; } = ""; }
|
||||
private class BalanceResult { public decimal BalanceUsd { get; set; } }
|
||||
private class BackendErrorResult { public string? Error { get; set; } }
|
||||
private class BackendErrorResult
|
||||
{
|
||||
public string? Error { get; set; }
|
||||
public string? RawResponse { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -36,9 +36,9 @@ public sealed class AnnualPlanSyncService : IDisposable
|
||||
_timer = new Timer(async _ => await PollAsync(), null, PollInterval, PollInterval);
|
||||
}
|
||||
|
||||
public async Task PollAsync()
|
||||
public async Task PollAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!await _gate.WaitAsync(0)) return;
|
||||
if (!await _gate.WaitAsync(0).ConfigureAwait(false)) return;
|
||||
try
|
||||
{
|
||||
var url = _settings.GetIcalUrl();
|
||||
@@ -47,7 +47,7 @@ public sealed class AnnualPlanSyncService : IDisposable
|
||||
string icsText;
|
||||
try
|
||||
{
|
||||
icsText = await _http.GetStringAsync(url);
|
||||
icsText = await _http.GetStringAsync(url, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -59,7 +59,7 @@ public sealed class AnnualPlanSyncService : IDisposable
|
||||
AnnualPlanPollResult result;
|
||||
try
|
||||
{
|
||||
result = ProcessIcsText(icsText);
|
||||
result = await Task.Run(() => ProcessIcsText(icsText)).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
using Avalonia.Controls;
|
||||
using LehrerApp.Core.Interfaces;
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Desktop.ViewModels.Students;
|
||||
using LehrerApp.Desktop.Views.Students;
|
||||
using LehrerApp.Templating;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace LehrerApp.Desktop.Services;
|
||||
|
||||
/// <summary>Öffnet den bestehenden Elternbrief-Dialog für einen Schüler, egal ob der Aufruf aus
|
||||
/// der Schülerdetailansicht (Student schon im DataContext) oder aus dem Formulare-Menü (Student
|
||||
/// erst per Picker gewählt) kommt.</summary>
|
||||
public static class LetterDialogs
|
||||
{
|
||||
public static async Task ShowCreateLetterDialogAsync(Window owner, Student student)
|
||||
{
|
||||
var vm = new CreateLetterDialogViewModel(student,
|
||||
App.Services.GetRequiredService<TemplateStore>(),
|
||||
App.Services.GetRequiredService<ITemplateRenderer>(),
|
||||
App.Services.GetRequiredService<IGroupMembershipRepository>(),
|
||||
App.Services.GetRequiredService<IGroupRepository>(),
|
||||
(options, contentWidth, millimeterScale, contentHeight) => App.Services.GetRequiredService<StudentAttendanceCalendarService>()
|
||||
.Build(student, options, contentWidth, millimeterScale, contentHeight),
|
||||
(options, contentWidth, millimeterScale, contentHeight) => App.Services.GetRequiredService<StudentAttendanceCalendarService>()
|
||||
.BuildAbsenceDayList(student, options, contentWidth, millimeterScale),
|
||||
RefreshAttendanceDataAsync);
|
||||
var dialog = new CreateLetterDialog { DataContext = vm };
|
||||
var path = await dialog.ShowDialog<string?>(owner);
|
||||
if (!string.IsNullOrEmpty(path) && File.Exists(path))
|
||||
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(path) { UseShellExecute = true });
|
||||
}
|
||||
|
||||
/// <summary>Holt genau den im Anwesenheitskalender-Dialog gewählten Zeitraum gezielt per
|
||||
/// WebUntis nach (ausgelöst durch den expliziten "Konfigurieren…"-Klick, kein Hintergrundabruf
|
||||
/// beim bloßen Öffnen des Briefdialogs). Damit sieht <see cref="StudentAttendanceCalendarService"/>
|
||||
/// anschließend frische Daten im lokalen Cache, statt stillschweigend "keine Fehltage" zu
|
||||
/// melden, nur weil die Klassenlehrer-Übersicht für diesen Zeitraum noch nie geöffnet wurde.</summary>
|
||||
private static async Task RefreshAttendanceDataAsync(AttendanceCalendarOptions options, CancellationToken token)
|
||||
{
|
||||
var className = App.Services.GetRequiredService<WebUntisSettingsService>().HomeroomClassName;
|
||||
if (string.IsNullOrWhiteSpace(className)) return;
|
||||
var cache = App.Services.GetRequiredService<UntisReportCacheService>();
|
||||
var start = options.NormalizedStartMonth;
|
||||
var end = start.AddMonths(options.NormalizedMonthCount).AddDays(-1);
|
||||
await cache.GetAbsencesAsync(className, start, end, token: token);
|
||||
await cache.GetClassRegisterEventsAsync(className, start, end, token: token);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Templating;
|
||||
|
||||
namespace LehrerApp.Desktop.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Baut die Standard-Platzhalterwerte für Elternbrief-Vorlagen (Datum, Anrede, Kontaktadresse,
|
||||
/// Schülerdaten, Brieftext, ...). Ursprünglich Teil von
|
||||
/// <see cref="ViewModels.Students.CreateLetterDialogViewModel"/>, hierher extrahiert, damit
|
||||
/// <c>LetterTemplateTools</c> (MCP, siehe Planungsdokument) dieselbe Logik nutzt statt sie zu
|
||||
/// duplizieren — beide Aufrufer müssen exakt dieselben Platzhalternamen befüllen, sonst driften
|
||||
/// Dialog-generierte und KI-generierte Briefe unbemerkt auseinander.
|
||||
/// </summary>
|
||||
public static class LetterPlaceholderBuilder
|
||||
{
|
||||
public static Dictionary<string, PlaceholderValue> BuildStandardValues(
|
||||
Student student, Contact? contact, LearningGroup? group, DateOnly date,
|
||||
string letterText, string teacherName, DrawingValue? attendanceCalendar = null,
|
||||
DrawingValue? absenceDays = null)
|
||||
{
|
||||
var address = FormatAddress(contact);
|
||||
return new Dictionary<string, PlaceholderValue>(StringComparer.Ordinal)
|
||||
{
|
||||
["Datum"] = new DateValue(date), ["CurrentDate"] = new DateValue(date),
|
||||
["Empfaenger"] = new TextValue(contact?.Name ?? ""), ["Anrede"] = new TextValue(contact?.LetterSalutation ?? ""),
|
||||
["Brieftext"] = new MultilineValue(letterText), ["LehrerName"] = new TextValue(teacherName),
|
||||
["Student.FirstName"] = new TextValue(student.FirstName), ["Student.LastName"] = new TextValue(student.LastName),
|
||||
["Student.Name"] = new TextValue(student.FullName),
|
||||
["Contact.Name"] = new TextValue(contact?.Name ?? ""), ["Contact.Address"] = new MultilineValue(address),
|
||||
["Contact.Street"] = new TextValue(contact?.Street ?? ""), ["Contact.PostalCode"] = new TextValue(contact?.PostalCode ?? ""),
|
||||
["Contact.City"] = new TextValue(contact?.City ?? ""), ["Letter.Salutation"] = new TextValue(contact?.LetterSalutation ?? ""),
|
||||
["Group.Name"] = new TextValue(group?.Name ?? ""), ["SchoolYear"] = new TextValue(group?.SchoolYear ?? ""),
|
||||
[StudentAttendanceCalendarDrawingBuilder.PlaceholderName] = attendanceCalendar ?? new DrawingValue([], 0),
|
||||
[StudentAbsenceDayListDrawingBuilder.PlaceholderName] = absenceDays ?? new DrawingValue([], 0),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Mehrzeilige Anschrift (Name/Straße/PLZ Ort) für Adressvorschau im Dialog und
|
||||
/// den <c>Contact.Address</c>-Platzhalter - eine Formatierung für beide Verwendungen.</summary>
|
||||
public static string FormatAddress(Contact? contact)
|
||||
{
|
||||
var cityLine = string.Join(" ", new[] { contact?.PostalCode, contact?.City }.Where(x => !string.IsNullOrWhiteSpace(x)));
|
||||
return string.Join(Environment.NewLine, new[] { contact?.Name, contact?.Street, cityLine }.Where(x => !string.IsNullOrWhiteSpace(x)));
|
||||
}
|
||||
|
||||
public static bool IsEmpty(PlaceholderValue value) => value switch
|
||||
{
|
||||
TextValue x => string.IsNullOrWhiteSpace(x.Value),
|
||||
MultilineValue x => string.IsNullOrWhiteSpace(x.Value),
|
||||
DrawingValue x => x.ContentHeight <= 0 || x.Commands.Count == 0,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
/// <summary>Tatsächliche DRAWBOX/FLOWDRAWBOX-Größe eines Platzhalters (in der Maßeinheit der
|
||||
/// Vorlage) plus dem Umrechnungsfaktor "1mm in dieser Maßeinheit". DrawingValue-Builder wie
|
||||
/// <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) =>
|
||||
FindDeclaredDrawingBox(template.Layout, 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Threading;
|
||||
using LehrerApp.Core.Services;
|
||||
using LehrerApp.Desktop.Views.Mcp;
|
||||
|
||||
namespace LehrerApp.Desktop.Services.Mcp;
|
||||
|
||||
/// <summary>
|
||||
/// Produktive <see cref="IMcpConfirmationService"/>-Implementierung: zeigt <see cref="McpConfirmDialog"/>
|
||||
/// über dem Hauptfenster an. Der aufrufende Tool-Handler läuft auf einem Hintergrund-Thread
|
||||
/// (MCP-Pipe-Session in <see cref="McpServerHostedService"/>), deshalb Marshalling über
|
||||
/// <see cref="Dispatcher.UIThread"/>.
|
||||
///
|
||||
/// Nutzer-Feedback: der Dialog fiel zu wenig auf, wenn LehrerApp im Hintergrund lief (naheliegend,
|
||||
/// da der Anstoß von einem KI-Client in einem anderen Fenster kommt) — deshalb wird das Hauptfenster
|
||||
/// vor dem Anzeigen aus einer möglichen Minimierung geholt und aktiviert, und der Dialog selbst
|
||||
/// läuft `Topmost`.
|
||||
///
|
||||
/// Nutzer-Feedback (Nachtrag): bei vielen gleichartigen Vorschlägen in Folge (z.B. 17x
|
||||
/// "add_lesson_phase" für eine neu generierte Unterrichtseinheit) einzeln nachfragen zu müssen, ist
|
||||
/// unzumutbar. Der Dialog bietet deshalb zwei Sitzungsfreigaben an ("diese Aktion" / "alle
|
||||
/// Aktionen"), die als reines In-Memory-Bookkeeping auf dieser Singleton-Instanz leben — sie gelten
|
||||
/// bis zum Beenden der App (neuer Prozess = neue Instanz = wieder alles ungetraut) und werden nie
|
||||
/// persistiert. <paramref name="operationKey"/> ist der Name der aufrufenden Tool-Methode (siehe
|
||||
/// <see cref="IMcpConfirmationService.ConfirmAsync"/>), nicht der MCP-Wire-Name.
|
||||
///
|
||||
/// Ohne Reaktion des Nutzers würde die Pipe-Session (und damit der wartende KI-Client) unbegrenzt
|
||||
/// hängen bleiben — nach <see cref="Timeout"/> wird der Dialog automatisch geschlossen und die
|
||||
/// Änderung als abgelehnt gewertet.
|
||||
/// </summary>
|
||||
public sealed class AvaloniaMcpConfirmationService(AppLogger logger) : IMcpConfirmationService
|
||||
{
|
||||
private static readonly TimeSpan Timeout = TimeSpan.FromMinutes(2);
|
||||
|
||||
private readonly object _trustLock = new();
|
||||
private readonly HashSet<string> _trustedOperations = [];
|
||||
private bool _trustAll;
|
||||
|
||||
public async Task<bool> ConfirmAsync(string title, string message, CancellationToken ct,
|
||||
[CallerMemberName] string operationKey = "", bool allowSessionTrust = true)
|
||||
{
|
||||
if (allowSessionTrust)
|
||||
{
|
||||
bool alreadyTrusted;
|
||||
lock (_trustLock) alreadyTrusted = _trustAll || _trustedOperations.Contains(operationKey);
|
||||
if (alreadyTrusted)
|
||||
{
|
||||
logger.Info($"MCP: „{title}“ automatisch bestätigt (Sitzungsfreigabe für " +
|
||||
$"{(_trustAll ? "alle Aktionen" : operationKey)}).");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (Application.Current?.ApplicationLifetime is not IClassicDesktopStyleApplicationLifetime { MainWindow: { } owner })
|
||||
return false;
|
||||
|
||||
// Die gesamte Warte-/Timeout-Logik läuft als ein Stück innerhalb des UI-Thread-Callbacks:
|
||||
// Avalonias Dispatcher-Synchronisationskontext sorgt dafür, dass die Fortsetzung nach
|
||||
// "await Task.WhenAny(...)" wieder auf dem UI-Thread läuft, sodass dialog.Close() dort
|
||||
// sicher aufgerufen werden kann.
|
||||
var result = await Dispatcher.UIThread.InvokeAsync(async () =>
|
||||
{
|
||||
if (owner.WindowState == WindowState.Minimized) owner.WindowState = WindowState.Normal;
|
||||
owner.Activate();
|
||||
|
||||
var dialog = new McpConfirmDialog
|
||||
{
|
||||
DataContext = new McpConfirmDialogInfo
|
||||
{
|
||||
Title = title, Message = message, ConfirmText = "Übernehmen",
|
||||
AllowSessionTrust = allowSessionTrust,
|
||||
},
|
||||
};
|
||||
var dialogTask = dialog.ShowDialog<McpConfirmDialogResult>(owner);
|
||||
var timeoutTask = Task.Delay(Timeout, ct);
|
||||
var completed = await Task.WhenAny(dialogTask, timeoutTask);
|
||||
if (completed != dialogTask)
|
||||
{
|
||||
dialog.Close(McpConfirmDialogResult.Rejected);
|
||||
return McpConfirmDialogResult.Rejected;
|
||||
}
|
||||
return await dialogTask;
|
||||
});
|
||||
|
||||
if (result.Approved && allowSessionTrust)
|
||||
{
|
||||
lock (_trustLock)
|
||||
{
|
||||
if (result.TrustAll) _trustAll = true;
|
||||
else if (result.TrustOperation) _trustedOperations.Add(operationKey);
|
||||
}
|
||||
}
|
||||
return result.Approved;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace LehrerApp.Desktop.Services.Mcp;
|
||||
|
||||
/// <summary>
|
||||
/// Zeigt dem Nutzer eine über MCP vorgeschlagene Änderung an, bevor sie tatsächlich geschrieben
|
||||
/// wird — Sicherheitsmodell aus dem Planungsdokument: "Tool-Aufruf erzeugt einen Vorschlag/Diff,
|
||||
/// der im Avalonia-Client als Bestätigungsdialog angezeigt wird, [...] kein 'silent write' durch
|
||||
/// das Modell." Als Interface gehalten, damit Write-Tool-Tests ohne echtes UI laufen können (siehe
|
||||
/// <see cref="AvaloniaMcpConfirmationService"/> für die produktive Implementierung).
|
||||
/// </summary>
|
||||
public interface IMcpConfirmationService
|
||||
{
|
||||
/// <param name="operationKey">Identifiziert die Art der Operation für eine mögliche
|
||||
/// Sitzungsfreigabe ("diese Aktion für den Rest der Sitzung nicht mehr nachfragen") — bewusst
|
||||
/// per <see cref="CallerMemberNameAttribute"/> automatisch befüllt (der Name der aufrufenden
|
||||
/// Tool-Methode, z.B. "AddLessonPhase"), damit kein Aufrufer diesen Parameter selbst pflegen
|
||||
/// muss. Nicht Teil des MCP-Wire-Protokolls, rein internes Bestätigungs-Bookkeeping.</param>
|
||||
/// <param name="allowSessionTrust">False für die eine bewusste Ausnahme, bei der eine
|
||||
/// Sitzungsfreigabe nicht angeboten werden soll (Nutzer-Entscheidung zu
|
||||
/// <c>get_named_untis_absence_pattern</c>: eine namentliche Fehlzeitenauskunft muss JEDES MAL
|
||||
/// einzeln bestätigt werden, nie pauschal für die restliche Sitzung) — weder die vorherige
|
||||
/// Prüfung auf eine bereits bestehende Freigabe noch das Setzen einer neuen finden dann statt,
|
||||
/// unabhängig davon, ob zuvor schon "alle Aktionen" freigegeben wurde.</param>
|
||||
/// <returns>true, wenn der Nutzer bestätigt hat (direkt oder über eine bereits erteilte
|
||||
/// Sitzungsfreigabe); false bei Ablehnung, Timeout oder falls kein Hauptfenster verfügbar ist
|
||||
/// (z.B. während des DB-Passwort-Prompts beim Start).</returns>
|
||||
Task<bool> ConfirmAsync(string title, string message, CancellationToken ct,
|
||||
[CallerMemberName] string operationKey = "", bool allowSessionTrust = true);
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace LehrerApp.Desktop.Services.Mcp;
|
||||
|
||||
public record McpRegistrationResult(bool Success, string Message);
|
||||
|
||||
/// <summary>
|
||||
/// Trägt LehrerApp.McpBridge in die MCP-Server-Konfiguration von Claude Desktop ein (siehe
|
||||
/// Planungsdokument, "Registrierungs-Workflow"). Bewusst nur für Claude Desktop: das ist der einzige
|
||||
/// KI-Client, den die Spec konkret benennt und der eine dokumentierte, stabile Config-Datei-Konvention
|
||||
/// hat (<c>mcpServers</c>-Objekt in <c>claude_desktop_config.json</c>) — andere lokale Clients
|
||||
/// (Ollama, LM Studio, ...) haben keine einheitliche Konvention, die sich hier ohne Rätselraten
|
||||
/// unterstützen ließe.
|
||||
///
|
||||
/// Läuft nur auf explizite Nutzeraktion (Button in den Einstellungen), nie automatisch beim
|
||||
/// App-Start — das Schreiben in die Konfigurationsdatei eines fremden Programms ist ein sichtbarer
|
||||
/// externer Seiteneffekt und gehört nicht in den normalen Startpfad.
|
||||
///
|
||||
/// Setzt eine gepackte Installation voraus (Bridge liegt neben der Hauptapp-Executable, siehe
|
||||
/// build-macos-app.sh) — bei einem lokalen "dotnet build/run" liegt die Bridge in ihrem eigenen
|
||||
/// separaten bin-Ordner, <see cref="ResolveBridgePath"/> findet sie dann nicht.
|
||||
/// </summary>
|
||||
public class McpClientRegistrationService
|
||||
{
|
||||
private const string ServerName = "lehrerapp";
|
||||
private static readonly JsonSerializerOptions WriteOptions = new() { WriteIndented = true };
|
||||
private readonly string? _bridgePath;
|
||||
|
||||
public McpClientRegistrationService() : this(ResolveConfigPath(), ResolveBridgePath()) { }
|
||||
|
||||
/// <summary>Test-Seam: erlaubt, Konfigurations- und Bridge-Pfad ohne echte
|
||||
/// Sonderordner/Installation vorzugeben (siehe <see cref="ResolveConfigPath"/>/
|
||||
/// <see cref="ResolveBridgePath"/> für das produktive Verhalten).</summary>
|
||||
public McpClientRegistrationService(string? configPath, string? bridgePath)
|
||||
{
|
||||
ConfigPath = configPath;
|
||||
_bridgePath = bridgePath;
|
||||
}
|
||||
|
||||
public string? ConfigPath { get; }
|
||||
|
||||
/// <summary>Ob überhaupt ein Claude-Desktop-Konfigurationsordner existiert — ein Hinweis, ob die
|
||||
/// Anwendung installiert ist, unabhängig davon, ob LehrerApp dort schon eingetragen ist.</summary>
|
||||
public bool IsClaudeDesktopDetected => ConfigPath is not null && File.Exists(ConfigPath);
|
||||
|
||||
public bool IsRegistered() =>
|
||||
TryLoadRoot(out var root, out _) && root["mcpServers"]?[ServerName] is not null;
|
||||
|
||||
public McpRegistrationResult Register()
|
||||
{
|
||||
if (ConfigPath is null)
|
||||
return new(false, "Claude Desktop wird auf diesem Betriebssystem nicht unterstützt.");
|
||||
|
||||
var bridgePath = _bridgePath;
|
||||
if (bridgePath is null || !File.Exists(bridgePath))
|
||||
return new(false,
|
||||
$"Bridge-Programm nicht gefunden ({bridgePath ?? "unbekannter Pfad"}). " +
|
||||
"Diese Funktion setzt eine gepackte Installation voraus, nicht einen lokalen Entwicklungs-Build.");
|
||||
|
||||
if (!TryLoadRoot(out var root, out var error))
|
||||
return new(false, error!);
|
||||
|
||||
if (root["mcpServers"] is not JsonObject servers)
|
||||
{
|
||||
servers = new JsonObject();
|
||||
root["mcpServers"] = servers;
|
||||
}
|
||||
servers[ServerName] = new JsonObject
|
||||
{
|
||||
["command"] = bridgePath,
|
||||
["args"] = new JsonArray(),
|
||||
};
|
||||
|
||||
var detectedBefore = IsClaudeDesktopDetected;
|
||||
var result = WriteRoot(root, "In Claude Desktop eingetragen. Claude Desktop neu starten, damit die Änderung wirkt.");
|
||||
if (result.Success && !detectedBefore)
|
||||
return result with
|
||||
{
|
||||
Message = result.Message +
|
||||
" Hinweis: Es wurde keine bestehende Claude-Desktop-Installation erkannt — die Konfiguration " +
|
||||
"greift erst, sobald Claude Desktop installiert ist.",
|
||||
};
|
||||
return result;
|
||||
}
|
||||
|
||||
public McpRegistrationResult Unregister()
|
||||
{
|
||||
if (ConfigPath is null || !File.Exists(ConfigPath))
|
||||
return new(true, "Nichts einzutragen gefunden.");
|
||||
if (!TryLoadRoot(out var root, out var error))
|
||||
return new(false, error!);
|
||||
if (root["mcpServers"] is not JsonObject servers || !servers.Remove(ServerName))
|
||||
return new(true, "War nicht eingetragen.");
|
||||
return WriteRoot(root, "Eintrag entfernt.");
|
||||
}
|
||||
|
||||
private bool TryLoadRoot(out JsonObject root, out string? error)
|
||||
{
|
||||
error = null;
|
||||
if (ConfigPath is null || !File.Exists(ConfigPath)) { root = new JsonObject(); return true; }
|
||||
try
|
||||
{
|
||||
root = JsonNode.Parse(File.ReadAllText(ConfigPath)) as JsonObject ?? new JsonObject();
|
||||
return true;
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
// Nicht raten und überschreiben - eine kaputte fremde Konfigurationsdatei bleibt unangetastet,
|
||||
// der Nutzer bekommt stattdessen eine klare Fehlermeldung mit Pfad.
|
||||
root = new JsonObject();
|
||||
error = $"Bestehende Claude-Desktop-Konfiguration ist kein gültiges JSON ({ex.Message}). " +
|
||||
$"Bitte manuell prüfen: {ConfigPath}";
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// Z.B. gesperrt, weil Claude Desktop selbst gerade schreibt - ebenfalls nicht überschreiben.
|
||||
root = new JsonObject();
|
||||
error = $"Bestehende Claude-Desktop-Konfiguration konnte nicht gelesen werden: {ex.Message}";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private McpRegistrationResult WriteRoot(JsonObject root, string successMessage)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(ConfigPath!)!);
|
||||
File.WriteAllText(ConfigPath!, root.ToJsonString(WriteOptions));
|
||||
return new(true, successMessage);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return new(false, $"Konfiguration konnte nicht geschrieben werden: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static string? ResolveBridgePath()
|
||||
{
|
||||
var bridgeFile = OperatingSystem.IsWindows() ? "LehrerApp.McpBridge.exe" : "LehrerApp.McpBridge";
|
||||
return Path.Combine(AppContext.BaseDirectory, bridgeFile);
|
||||
}
|
||||
|
||||
private static string? ResolveConfigPath()
|
||||
{
|
||||
if (OperatingSystem.IsWindows())
|
||||
return Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
||||
"Claude", "claude_desktop_config.json");
|
||||
if (OperatingSystem.IsMacOS())
|
||||
return Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
|
||||
"Library", "Application Support", "Claude", "claude_desktop_config.json");
|
||||
return null; // Linux: kein offizieller Claude-Desktop-Client bekannt.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
using System.IO.Pipes;
|
||||
using LehrerApp.Core.Mcp;
|
||||
using LehrerApp.Core.Services;
|
||||
using LehrerApp.Desktop.Services.Mcp.Tools;
|
||||
using ModelContextProtocol.Protocol;
|
||||
using ModelContextProtocol.Server;
|
||||
|
||||
namespace LehrerApp.Desktop.Services.Mcp;
|
||||
|
||||
/// <summary>
|
||||
/// In-Process-MCP-Server (siehe Planungsdokument und TODO.md 4.5.25ff.). Lauscht auf der Named Pipe
|
||||
/// <see cref="McpPipeConstants.PipeName"/> und bedient jede eingehende Verbindung (eine je
|
||||
/// LehrerApp.McpBridge-Instanz) als eigene MCP-Session über <see cref="StreamServerTransport"/> —
|
||||
/// ein <see cref="NamedPipeServerStream"/> ist ein normaler <see cref="Stream"/> und kann direkt
|
||||
/// als Ein-/Ausgabe der Session übergeben werden, ohne eigenes JSON-RPC-Parsing.
|
||||
///
|
||||
/// Nur aktiv, wenn <see cref="McpSettingsService.Enabled"/> — sonst tut <see cref="Start"/> nichts.
|
||||
/// Repositories sind im DI-Container Singletons (siehe AppBootstrapper), deshalb reicht es, die
|
||||
/// Tool-Instanzen und die daraus gebaute <see cref="McpServerOptions"/> einmalig zu bauen und für
|
||||
/// alle Sessions zu teilen.
|
||||
/// </summary>
|
||||
public sealed class McpServerHostedService : IAsyncDisposable
|
||||
{
|
||||
private readonly McpSettingsService _settings;
|
||||
private readonly AppLogger _logger;
|
||||
private readonly McpServerOptions _serverOptions;
|
||||
private CancellationTokenSource? _cts;
|
||||
private Task? _acceptLoop;
|
||||
|
||||
public McpServerHostedService(
|
||||
McpSettingsService settings, AppLogger logger,
|
||||
StudentTools studentTools, ExamTools examTools, GradeTools gradeTools,
|
||||
ScheduleTools scheduleTools, TimeEntryTools timeEntryTools, LessonPlanTools lessonPlanTools,
|
||||
GroupMembershipTools groupMembershipTools, LetterTemplateTools letterTemplateTools,
|
||||
CompetencyTools competencyTools, UntisComparisonTools untisComparisonTools, GroupTools groupTools,
|
||||
ParticipationTools participationTools)
|
||||
{
|
||||
_settings = settings;
|
||||
_logger = logger;
|
||||
_serverOptions = BuildServerOptions(
|
||||
studentTools, examTools, gradeTools, scheduleTools, timeEntryTools, lessonPlanTools,
|
||||
groupMembershipTools, letterTemplateTools, competencyTools, untisComparisonTools, groupTools,
|
||||
participationTools);
|
||||
}
|
||||
|
||||
/// <summary>Setzt die Pipe-Server-Accept-Loop auf, falls aktiviert. Ohne Wirkung, falls
|
||||
/// bereits gestartet oder in den Einstellungen deaktiviert (dann bleibt keine Pipe offen).</summary>
|
||||
public void Start()
|
||||
{
|
||||
if (!_settings.Enabled || _cts is not null) return;
|
||||
_cts = new CancellationTokenSource();
|
||||
_acceptLoop = Task.Run(() => AcceptLoopAsync(_cts.Token));
|
||||
_logger.Info("MCP-Server gestartet, lauscht auf Pipe '" + McpPipeConstants.PipeName + "'.");
|
||||
}
|
||||
|
||||
private async Task AcceptLoopAsync(CancellationToken ct)
|
||||
{
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
var pipe = new NamedPipeServerStream(
|
||||
McpPipeConstants.PipeName, PipeDirection.InOut,
|
||||
NamedPipeServerStream.MaxAllowedServerInstances,
|
||||
PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
|
||||
try
|
||||
{
|
||||
await pipe.WaitForConnectionAsync(ct);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
await pipe.DisposeAsync();
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.Error("MCP: Fehler beim Warten auf eine Bridge-Verbindung.", ex);
|
||||
await pipe.DisposeAsync();
|
||||
continue;
|
||||
}
|
||||
|
||||
// Nicht awaiten: die Accept-Loop muss sofort weiterlaufen, damit mehrere gleichzeitige
|
||||
// Bridge-Instanzen (mehrere KI-Client-Sitzungen) unabhängig bedient werden.
|
||||
_ = RunSessionAsync(pipe, ct);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RunSessionAsync(NamedPipeServerStream pipe, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var transport = new StreamServerTransport(pipe, pipe, "LehrerApp");
|
||||
await using var server = McpServer.Create(transport, _serverOptions, loggerFactory: null, serviceProvider: null);
|
||||
await server.RunAsync(ct);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.Warn($"MCP: Session beendet ({ex.Message}).");
|
||||
}
|
||||
finally
|
||||
{
|
||||
await pipe.DisposeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_cts is null) return;
|
||||
await _cts.CancelAsync();
|
||||
if (_acceptLoop is not null)
|
||||
{
|
||||
try { await _acceptLoop; }
|
||||
catch { /* Beenden über Cancellation ist der Normalfall hier */ }
|
||||
}
|
||||
_cts.Dispose();
|
||||
}
|
||||
|
||||
private static McpServerOptions BuildServerOptions(
|
||||
StudentTools studentTools, ExamTools examTools, GradeTools gradeTools,
|
||||
ScheduleTools scheduleTools, TimeEntryTools timeEntryTools, LessonPlanTools lessonPlanTools,
|
||||
GroupMembershipTools groupMembershipTools, LetterTemplateTools letterTemplateTools,
|
||||
CompetencyTools competencyTools, UntisComparisonTools untisComparisonTools, GroupTools groupTools,
|
||||
ParticipationTools participationTools)
|
||||
{
|
||||
var toolCollection = new McpServerPrimitiveCollection<McpServerTool>();
|
||||
|
||||
void AddReadTool(Delegate handler, string name, string description)
|
||||
{
|
||||
toolCollection.Add(McpServerTool.Create(handler, new McpServerToolCreateOptions
|
||||
{
|
||||
Name = name,
|
||||
Description = description,
|
||||
ReadOnly = true,
|
||||
}));
|
||||
}
|
||||
|
||||
// Write-Tools schreiben nie direkt - jede Handler-Methode ruft selbst erst
|
||||
// IMcpConfirmationService auf (siehe die jeweilige Tool-Klasse). ReadOnly bewusst false,
|
||||
// Destructive bewusst false (keine dieser Schreiboperationen löscht etwas) - für die
|
||||
// Ausnahme siehe AddDestructiveWriteTool/McpToolScope.AllowedDestructiveWriteTools.
|
||||
void AddWriteTool(Delegate handler, string name, string description)
|
||||
{
|
||||
toolCollection.Add(McpServerTool.Create(handler, new McpServerToolCreateOptions
|
||||
{
|
||||
Name = name,
|
||||
Description = description,
|
||||
ReadOnly = false,
|
||||
Destructive = false,
|
||||
}));
|
||||
}
|
||||
|
||||
void AddDestructiveWriteTool(Delegate handler, string name, string description)
|
||||
{
|
||||
toolCollection.Add(McpServerTool.Create(handler, new McpServerToolCreateOptions
|
||||
{
|
||||
Name = name,
|
||||
Description = description,
|
||||
ReadOnly = false,
|
||||
Destructive = true,
|
||||
}));
|
||||
}
|
||||
|
||||
AddReadTool(studentTools.GetStudents, "get_students",
|
||||
"Listet Schüler, optional gefiltert nach Lerngruppe.");
|
||||
AddReadTool(groupTools.GetGroups, "get_groups",
|
||||
"Listet Lerngruppen (Klassen/Kurse) mit ihrer Id, optional gefiltert nach Schuljahr.");
|
||||
AddReadTool(examTools.GetExams, "get_exams",
|
||||
"Listet Klausuren, optional gefiltert nach Lerngruppe.");
|
||||
AddReadTool(gradeTools.GetGrades, "get_grades",
|
||||
"Listet Noten einer Lerngruppe, optional gefiltert auf einen Schüler.");
|
||||
AddReadTool(scheduleTools.GetSchedule, "get_schedule",
|
||||
"Listet Stundenplan-Einträge, optional gefiltert nach Lerngruppe.");
|
||||
AddReadTool(timeEntryTools.GetTimeEntries, "get_time_entries",
|
||||
"Listet eigene Zeiterfassungs-Einträge in einem Datumsbereich.");
|
||||
AddReadTool(lessonPlanTools.GetLessonPlans, "get_lesson_plans",
|
||||
"Listet Unterrichtseinheiten und -stunden einer Lerngruppe in einem Zeitraum.");
|
||||
AddReadTool(lessonPlanTools.DownloadLessonAttachment, "download_lesson_attachment",
|
||||
"Lädt den Inhalt eines an eine Einzelstunde angehängten Materials Base64-kodiert herunter.");
|
||||
AddReadTool(letterTemplateTools.ListLetterTemplates, "list_letter_templates",
|
||||
"Listet importierte Elternbrief-Vorlagen mit ihren Platzhaltern.");
|
||||
AddReadTool(letterTemplateTools.RenderLetter, "render_letter",
|
||||
"Erzeugt einen Elternbrief aus einer Vorlage für einen Schüler als Base64-PDF.");
|
||||
AddReadTool(competencyTools.GetSubjects, "get_subjects",
|
||||
"Listet alle Fächer.");
|
||||
AddReadTool(competencyTools.GetCompetencyPlanVersions, "get_competency_plan_versions",
|
||||
"Listet die Bildungsplan-Versionen eines Fachs.");
|
||||
AddReadTool(competencyTools.GetCompetencyCatalog, "get_competency_catalog",
|
||||
"Listet den Kompetenzkatalog eines Fachs für eine Bildungsplan-Version, optional gefiltert auf eine Klassenstufe.");
|
||||
AddReadTool(untisComparisonTools.GetUntisHubStatus, "get_untis_hub_status",
|
||||
"Listet die Fälligkeit der Untis-Hub-Abgleiche, ohne selbst WebUntis anzufragen.");
|
||||
AddReadTool(untisComparisonTools.GetUntisAbsenceRows, "get_untis_absence_rows",
|
||||
"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",
|
||||
"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",
|
||||
"Schlägt einen neuen Zeiterfassungs-Eintrag vor (Bestätigung durch den Nutzer nötig).");
|
||||
AddWriteTool(gradeTools.CreateGradeEntry, "create_grade_entry",
|
||||
"Schlägt eine neue Note für einen Schüler vor (Bestätigung durch den Nutzer nötig).");
|
||||
AddWriteTool(groupMembershipTools.UpdateStudentGroupAssignment, "update_student_group_assignment",
|
||||
"Legt eine Gruppenmitgliedschaft an oder ändert Niveau/Zeitraum (Bestätigung durch den Nutzer nötig).");
|
||||
AddWriteTool(lessonPlanTools.CreateUnit, "create_unit",
|
||||
"Legt eine neue Unterrichtseinheit an (Bestätigung durch den Nutzer nötig).");
|
||||
AddWriteTool(lessonPlanTools.UpdateUnit, "update_unit",
|
||||
"Ändert Titel/Zeitraum/Status einer Unterrichtseinheit (Bestätigung durch den Nutzer nötig).");
|
||||
AddWriteTool(lessonPlanTools.CreateLesson, "create_lesson",
|
||||
"Legt eine neue Einzelstunde ohne Verlaufsplan an (Bestätigung durch den Nutzer nötig).");
|
||||
AddWriteTool(lessonPlanTools.UpdateLesson, "update_lesson",
|
||||
"Ändert Metadaten einer Einzelstunde, ohne den Verlaufsplan anzufassen (Bestätigung durch den Nutzer nötig).");
|
||||
AddWriteTool(lessonPlanTools.AddLessonPhase, "add_lesson_phase",
|
||||
"Fügt einer Einzelstunde eine Verlaufsplan-Phase hinzu (Bestätigung durch den Nutzer nötig).");
|
||||
AddWriteTool(lessonPlanTools.UpdateLessonPhase, "update_lesson_phase",
|
||||
"Ändert eine Verlaufsplan-Phase einer Einzelstunde (Bestätigung durch den Nutzer nötig).");
|
||||
AddWriteTool(lessonPlanTools.RemoveLessonPhase, "remove_lesson_phase",
|
||||
"Entfernt eine Verlaufsplan-Phase aus einer Einzelstunde (Bestätigung durch den Nutzer nötig).");
|
||||
AddWriteTool(lessonPlanTools.AddLessonAttachment, "add_lesson_attachment",
|
||||
"Fügt einer Einzelstunde ein neues Material als Base64-kodierten Anhang hinzu (Bestätigung durch den Nutzer nötig).");
|
||||
AddWriteTool(lessonPlanTools.MoveLesson, "move_lesson",
|
||||
"Verschiebt eine Einzelstunde auf ein neues Datum, optional mit Mitverschieben späterer Stunden derselben Einheit (Bestätigung durch den Nutzer nötig).");
|
||||
AddWriteTool(lessonPlanTools.AddLessonCompetency, "add_lesson_competency",
|
||||
"Ordnet einer Einzelstunde einen Kompetenzcode zu (Bestätigung durch den Nutzer nötig).");
|
||||
AddWriteTool(lessonPlanTools.RemoveLessonCompetency, "remove_lesson_competency",
|
||||
"Entfernt einen Kompetenzcode von einer Einzelstunde (Bestätigung durch den Nutzer nötig).");
|
||||
AddWriteTool(competencyTools.CreateSubject, "create_subject",
|
||||
"Legt ein neues Fach an (Bestätigung durch den Nutzer nötig).");
|
||||
AddWriteTool(competencyTools.UpdateSubject, "update_subject",
|
||||
"Ändert Name/Kurzform eines Fachs (Bestätigung durch den Nutzer nötig).");
|
||||
AddWriteTool(competencyTools.CreateCompetencyDomain, "create_competency_domain",
|
||||
"Legt einen neuen Kompetenzbereich für ein Fach/eine Klassenstufe an (Bestätigung durch den Nutzer nötig).");
|
||||
AddWriteTool(competencyTools.UpdateCompetencyDomain, "update_competency_domain",
|
||||
"Ändert Name/Kürzel eines Kompetenzbereichs (Bestätigung durch den Nutzer nötig).");
|
||||
AddWriteTool(competencyTools.AddCompetencyItem, "add_competency_item",
|
||||
"Fügt einem Kompetenzbereich eine Einzelkompetenz hinzu (Bestätigung durch den Nutzer nötig).");
|
||||
AddWriteTool(competencyTools.UpdateCompetencyItem, "update_competency_item",
|
||||
"Ändert Code/Beschreibung einer Einzelkompetenz (Bestätigung durch den Nutzer nötig).");
|
||||
AddWriteTool(competencyTools.RemoveCompetencyItem, "remove_competency_item",
|
||||
"Entfernt eine Einzelkompetenz aus einem Kompetenzbereich (Bestätigung durch den Nutzer nötig).");
|
||||
AddWriteTool(competencyTools.CreateCompetencyPlanVersion, "create_competency_plan_version",
|
||||
"Legt eine neue Bildungsplan-Version für ein Fach an (Bestätigung durch den Nutzer nötig).");
|
||||
AddWriteTool(competencyTools.UpdateCompetencyPlanVersion, "update_competency_plan_version",
|
||||
"Ändert Name/Standardstatus einer Bildungsplan-Version (Bestätigung durch den Nutzer nötig).");
|
||||
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).");
|
||||
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",
|
||||
"Ü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).");
|
||||
|
||||
AddDestructiveWriteTool(lessonPlanTools.DeleteLesson, "delete_lesson",
|
||||
"Löscht eine Einzelstunde endgültig, ohne Papierkorb (Bestätigung durch den Nutzer nötig).");
|
||||
AddDestructiveWriteTool(competencyTools.DeleteSubject, "delete_subject",
|
||||
"Löscht ein Fach endgültig, ohne Papierkorb (Bestätigung durch den Nutzer nötig).");
|
||||
AddDestructiveWriteTool(competencyTools.DeleteCompetencyDomain, "delete_competency_domain",
|
||||
"Löscht einen Kompetenzbereich endgültig samt Einzelkompetenzen, ohne Papierkorb (Bestätigung durch den Nutzer nötig).");
|
||||
AddDestructiveWriteTool(competencyTools.DeleteCompetencyPlanVersion, "delete_competency_plan_version",
|
||||
"Löscht eine Bildungsplan-Version endgültig, ohne Papierkorb (Bestätigung durch den Nutzer nötig).");
|
||||
|
||||
System.Diagnostics.Debug.Assert(
|
||||
toolCollection.Select(t => t.ProtocolTool.Name).OrderBy(n => n)
|
||||
.SequenceEqual(McpToolScope.AllowedReadTools.Concat(McpToolScope.AllowedWriteTools)
|
||||
.Concat(McpToolScope.AllowedDestructiveWriteTools).OrderBy(n => n)),
|
||||
"Registrierte MCP-Tools weichen von McpToolScope ab.");
|
||||
|
||||
return new McpServerOptions
|
||||
{
|
||||
ServerInfo = new Implementation { Name = "LehrerApp", Version = "1.0.0" },
|
||||
Capabilities = new ServerCapabilities { Tools = new ToolsCapability() },
|
||||
ToolCollection = toolCollection,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
namespace LehrerApp.Desktop.Services.Mcp;
|
||||
|
||||
/// <summary>
|
||||
/// Allowlist der über MCP exponierten Tool-Namen. Dieselbe Absicherung wie
|
||||
/// LehrerApp.Api/PlainEventStore.cs (dort für den Klartext-Sync-Kanal): Gesprächsnotizen, Vorfälle
|
||||
/// und Förderpläne (Documentation/Vorgang) sind hier bewusst nie aufgeführt und werden von keiner
|
||||
/// Tool-Klasse referenziert — ein KI-Client kann diese Daten technisch nicht erreichen, unabhängig
|
||||
/// davon, wie vertrauenswürdig der lokale Modell-Client erscheint oder wie die Tool-Liste künftig
|
||||
/// wächst. <see cref="McpServerHostedService"/> registriert nur exakt diese Namen.
|
||||
///
|
||||
/// "get_named_untis_absence_pattern" ist die eine bewusste, eng begrenzte Ausnahme von der oben
|
||||
/// beschriebenen Regel (Nutzer-Entscheidung, siehe TODO.md): es verknüpft Schülername mit
|
||||
/// Fehlzeitendaten, aber nur für explizit angegebene Schüler-IDs und nur nach jedes Mal gesonderter,
|
||||
/// prominenter Bestätigung ohne Sitzungsfreigabe (siehe UntisComparisonTools). Documentation/
|
||||
/// Vorgang bleibt davon unberührt weiterhin vollständig ausgeschlossen.
|
||||
/// </summary>
|
||||
public static class McpToolScope
|
||||
{
|
||||
public static readonly IReadOnlyCollection<string> AllowedReadTools =
|
||||
[
|
||||
"get_students",
|
||||
"get_groups",
|
||||
"get_exams",
|
||||
"get_grades",
|
||||
"get_schedule",
|
||||
"get_time_entries",
|
||||
"get_lesson_plans",
|
||||
"download_lesson_attachment",
|
||||
"list_letter_templates",
|
||||
"render_letter",
|
||||
"get_subjects",
|
||||
"get_competency_plan_versions",
|
||||
"get_competency_catalog",
|
||||
"get_untis_hub_status",
|
||||
"get_untis_absence_rows",
|
||||
"get_named_untis_absence_pattern",
|
||||
"get_participation_sessions",
|
||||
];
|
||||
|
||||
/// <summary>Write-Tools (Phase 2+3) — jeder Aufruf läuft über <see cref="IMcpConfirmationService"/>,
|
||||
/// bevor irgendetwas geschrieben wird (siehe die jeweilige Tool-Klasse). Absichtlich kleinteilig
|
||||
/// bei Unit/Lesson (create/update_unit, create/update_lesson, add/update/remove_lesson_phase)
|
||||
/// statt eines einzelnen "update_lesson" für die ganze Stunde inkl. Verlaufsplan — siehe
|
||||
/// Begründung in LessonPlanTools.</summary>
|
||||
public static readonly IReadOnlyCollection<string> AllowedWriteTools =
|
||||
[
|
||||
"create_time_entry",
|
||||
"create_grade_entry",
|
||||
"update_student_group_assignment",
|
||||
"create_unit",
|
||||
"update_unit",
|
||||
"create_lesson",
|
||||
"update_lesson",
|
||||
"add_lesson_phase",
|
||||
"update_lesson_phase",
|
||||
"remove_lesson_phase",
|
||||
"add_lesson_attachment",
|
||||
"move_lesson",
|
||||
"add_lesson_competency",
|
||||
"remove_lesson_competency",
|
||||
"create_subject",
|
||||
"update_subject",
|
||||
"create_competency_domain",
|
||||
"update_competency_domain",
|
||||
"add_competency_item",
|
||||
"update_competency_item",
|
||||
"remove_competency_item",
|
||||
"create_competency_plan_version",
|
||||
"update_competency_plan_version",
|
||||
"update_group_competency_version",
|
||||
"add_session_competency",
|
||||
"remove_session_competency",
|
||||
"apply_untis_absence_status",
|
||||
];
|
||||
|
||||
/// <summary>Löschende Write-Tools — ursprünglich eine bewusste, gezielte Ausnahme von der sonst
|
||||
/// geltenden "v1 ohne Lösch-Tools"-Regel für "delete_lesson" (siehe Planungsdokument), inzwischen
|
||||
/// (Nutzer-Nachtrag) um die endgültigen Löschungen für Fächer/Kompetenzbereiche erweitert — beide
|
||||
/// ohne Papierkorb, wie delete_lesson. Getrennt von <see cref="AllowedWriteTools"/> aufgeführt,
|
||||
/// damit diese Ausnahme beim Lesen sofort auffällt. <see cref="McpServerHostedService"/>
|
||||
/// registriert diese Tools zusätzlich mit <c>Destructive = true</c>.</summary>
|
||||
public static readonly IReadOnlyCollection<string> AllowedDestructiveWriteTools =
|
||||
[
|
||||
"delete_lesson",
|
||||
"delete_subject",
|
||||
"delete_competency_domain",
|
||||
"delete_competency_plan_version",
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
using System.ComponentModel;
|
||||
using System.Text;
|
||||
using LehrerApp.Core.Interfaces;
|
||||
using LehrerApp.Core.Models;
|
||||
|
||||
namespace LehrerApp.Desktop.Services.Mcp.Tools;
|
||||
|
||||
/// <summary>MCP-Tools für die Fach- und Kompetenzkatalog-Verwaltung (Nutzer-Nachtrag zu 4.5.28ff.,
|
||||
/// später um Bildungsplan-Versionierung erweitert): <see cref="Subject"/>,
|
||||
/// <see cref="CompetencyCatalogVersion"/> und <see cref="CompetencyDomain"/>/<see cref="CompetencyItem"/>
|
||||
/// vollständig anlegen/ändern/löschen. Die Zuordnung von Kompetenzcodes zu einzelnen Stunden lebt
|
||||
/// bewusst in <see cref="LessonPlanTools"/> (AddLessonCompetency/RemoveLessonCompetency), nicht hier -
|
||||
/// sie gehört fachlich zur Stundenverwaltung, nicht zum Katalog selbst.
|
||||
///
|
||||
/// "delete_subject", "delete_competency_domain" und "delete_competency_plan_version" sind wie
|
||||
/// "delete_lesson" (LessonPlanTools) endgültige Löschungen ohne Papierkorb (die
|
||||
/// Repository-Implementierungen löschen direkt in der LiteDB-Collection statt über MoveToTrash) -
|
||||
/// deshalb als Destructive registriert (siehe McpServerHostedService) und mit entsprechend
|
||||
/// deutlicher Bestätigungsnachricht.</summary>
|
||||
public class CompetencyTools(
|
||||
ISubjectRepository subjects, ICompetencyDomainRepository domains,
|
||||
ICompetencyCatalogVersionRepository versions, IMcpConfirmationService confirmation)
|
||||
{
|
||||
// ── Lesen ────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
[Description("Listet alle Fächer.")]
|
||||
public List<SubjectDto> GetSubjects() =>
|
||||
subjects.GetAll().Select(s => new SubjectDto(s.Id, s.Name, s.ShortName)).ToList();
|
||||
|
||||
[Description("Listet die Bildungsplan-Versionen eines Fachs (z.B. \"Bildungsplan 2016\" vs. \"Bildungsplan 2026\", während ein neuer Plan klassenstufenweise hochwächst). Genau eine Version je Fach ist die Standardversion.")]
|
||||
public List<CompetencyPlanVersionDto> GetCompetencyPlanVersions(
|
||||
[Description("Fach-ID, aus get_subjects.")] Guid subjectId) =>
|
||||
versions.GetBySubject(subjectId)
|
||||
.Select(v => new CompetencyPlanVersionDto(v.Id, v.SubjectId, v.Name, v.IsDefault, v.SortOrder))
|
||||
.ToList();
|
||||
|
||||
[Description("Listet den Kompetenzkatalog (Bereiche mit Einzelkompetenzen) eines Fachs für eine Bildungsplan-Version, optional gefiltert auf eine Klassenstufe.")]
|
||||
public List<CompetencyDomainDto> GetCompetencyCatalog(
|
||||
[Description("Fach-ID, aus get_subjects.")] Guid subjectId,
|
||||
[Description("Optionale Klassenstufe. Weglassen: alle Klassenstufen dieser Version.")] int? gradeLevel = null,
|
||||
[Description("Bildungsplan-Version, aus get_competency_plan_versions. Weglassen: Standardversion des Fachs.")] Guid? versionId = null)
|
||||
{
|
||||
var effectiveVersionId = versionId ?? versions.GetOrCreateDefault(subjectId).Id;
|
||||
var result = gradeLevel is not null
|
||||
? domains.GetBySubjectAndGrade(subjectId, gradeLevel.Value, effectiveVersionId)
|
||||
: domains.GetBySubjectAndVersion(subjectId, effectiveVersionId);
|
||||
return result.Select(ToDto).ToList();
|
||||
}
|
||||
|
||||
// ── Bildungsplan-Versionen (CompetencyCatalogVersion) ────────────────────────────────────
|
||||
|
||||
[Description("Legt eine neue Bildungsplan-Version für ein Fach an (z.B. \"Bildungsplan 2026\"), um einen neuen, parallel gültigen Kompetenzkatalog zu pflegen. Muss der Nutzer erst bestätigen.")]
|
||||
public async Task<WriteResultDto> CreateCompetencyPlanVersion(
|
||||
[Description("Fach-ID, aus get_subjects.")] Guid subjectId,
|
||||
[Description("Name der Version, z.B. \"Bildungsplan 2026\".")] string name,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var subject = subjects.GetById(subjectId);
|
||||
if (subject is null) return new WriteResultDto(false, null, "Unbekannte Fach-ID.");
|
||||
if (string.IsNullOrWhiteSpace(name)) return new WriteResultDto(false, null, "Name der Version darf nicht leer sein.");
|
||||
|
||||
var message = $"Neue Bildungsplan-Version „{name.Trim()}“ für {subject.Name} anlegen?";
|
||||
if (!await confirmation.ConfirmAsync("Version anlegen?", message, ct))
|
||||
return new WriteResultDto(false, null, "Vom Nutzer abgelehnt oder nicht bestätigt.");
|
||||
|
||||
var version = new CompetencyCatalogVersion
|
||||
{
|
||||
SubjectId = subjectId, Name = name, SortOrder = versions.GetBySubject(subjectId).Count,
|
||||
};
|
||||
try { versions.Save(version); }
|
||||
catch (ArgumentException ex) { return new WriteResultDto(false, null, ex.Message); }
|
||||
return new WriteResultDto(true, version.Id, "Version gespeichert.");
|
||||
}
|
||||
|
||||
[Description("Ändert Name/Standardstatus einer bestehenden Bildungsplan-Version. Nur angegebene Felder werden geändert.")]
|
||||
public async Task<WriteResultDto> UpdateCompetencyPlanVersion(
|
||||
[Description("ID der Version, aus get_competency_plan_versions.")] Guid versionId,
|
||||
[Description("Neuer Name. Unverändert lassen: weglassen.")] string? name = null,
|
||||
[Description("Auf true setzen, um diese Version zur Standardversion ihres Fachs zu machen (bisherige Standardversion wird automatisch zurückgenommen).")] bool? setAsDefault = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var version = versions.GetById(versionId);
|
||||
if (version is null) return new WriteResultDto(false, null, "Unbekannte Versions-ID.");
|
||||
|
||||
var changes = new StringBuilder();
|
||||
if (name is not null && name != version.Name) { changes.AppendLine($"Name: „{version.Name}“ → „{name}“"); version.Name = name; }
|
||||
if (setAsDefault is true && !version.IsDefault) { changes.AppendLine("wird Standardversion des Fachs"); version.IsDefault = true; }
|
||||
|
||||
if (changes.Length == 0)
|
||||
return new WriteResultDto(true, version.Id, "Keine Änderung nötig.");
|
||||
|
||||
if (!await confirmation.ConfirmAsync("Version ändern?", $"„{version.Name}“\n{changes}".TrimEnd(), ct))
|
||||
return new WriteResultDto(false, null, "Vom Nutzer abgelehnt oder nicht bestätigt.");
|
||||
|
||||
try { versions.Save(version); }
|
||||
catch (ArgumentException ex) { return new WriteResultDto(false, null, ex.Message); }
|
||||
return new WriteResultDto(true, version.Id, "Version gespeichert.");
|
||||
}
|
||||
|
||||
[Description("Löscht eine Bildungsplan-Version endgültig. Schlägt fehl, wenn sie noch Kompetenzbereiche oder Kurse referenziert, oder wenn sie die Standardversion ihres Fachs ist. Kein Papierkorb - nicht rückgängig zu machen. Muss der Nutzer erst bestätigen.")]
|
||||
public async Task<WriteResultDto> DeleteCompetencyPlanVersion(
|
||||
[Description("ID der Version.")] Guid versionId,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var version = versions.GetById(versionId);
|
||||
if (version is null) return new WriteResultDto(false, null, "Unbekannte Versions-ID.");
|
||||
|
||||
var message = $"Die Bildungsplan-Version „{version.Name}“ wird endgültig gelöscht. Das kann NICHT rückgängig gemacht werden (kein Papierkorb für Versionen). Schlägt fehl, falls noch Kompetenzbereiche oder Kurse diese Version nutzen.";
|
||||
if (!await confirmation.ConfirmAsync("Version endgültig löschen?", message, ct))
|
||||
return new WriteResultDto(false, null, "Vom Nutzer abgelehnt oder nicht bestätigt.");
|
||||
|
||||
try { versions.Delete(versionId); }
|
||||
catch (InvalidOperationException ex) { return new WriteResultDto(false, null, ex.Message); }
|
||||
return new WriteResultDto(true, versionId, "Version gelöscht.");
|
||||
}
|
||||
|
||||
// ── Fächer (Subject) ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
[Description("Legt ein neues Fach an. Muss der Nutzer erst bestätigen.")]
|
||||
public async Task<WriteResultDto> CreateSubject(
|
||||
[Description("Name des Fachs, z.B. \"Mathematik\".")] string name,
|
||||
[Description("Kurzform, z.B. \"Ma\".")] string shortName = "",
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(name)) return new WriteResultDto(false, null, "Fachname darf nicht leer sein.");
|
||||
|
||||
var message = $"Neues Fach „{name.Trim()}“" +
|
||||
(string.IsNullOrWhiteSpace(shortName) ? "" : $" ({shortName.Trim()})") + " anlegen?";
|
||||
if (!await confirmation.ConfirmAsync("Fach anlegen?", message, ct))
|
||||
return new WriteResultDto(false, null, "Vom Nutzer abgelehnt oder nicht bestätigt.");
|
||||
|
||||
var subject = new Subject { Name = name, ShortName = shortName };
|
||||
try { subjects.Save(subject); }
|
||||
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException)
|
||||
{
|
||||
return new WriteResultDto(false, null, ex.Message);
|
||||
}
|
||||
return new WriteResultDto(true, subject.Id, "Fach gespeichert.");
|
||||
}
|
||||
|
||||
[Description("Ändert Name/Kurzform eines bestehenden Fachs. Nur angegebene Felder werden geändert.")]
|
||||
public async Task<WriteResultDto> UpdateSubject(
|
||||
[Description("Fach-ID.")] Guid subjectId,
|
||||
[Description("Neuer Name. Unverändert lassen: weglassen.")] string? name = null,
|
||||
[Description("Neue Kurzform. Unverändert lassen: weglassen.")] string? shortName = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var subject = subjects.GetById(subjectId);
|
||||
if (subject is null) return new WriteResultDto(false, null, "Unbekannte Fach-ID.");
|
||||
|
||||
var changes = new StringBuilder();
|
||||
if (name is not null && name != subject.Name) { changes.AppendLine($"Name: „{subject.Name}“ → „{name}“"); subject.Name = name; }
|
||||
if (shortName is not null && shortName != subject.ShortName) { changes.AppendLine($"Kurzform: „{subject.ShortName}“ → „{shortName}“"); subject.ShortName = shortName; }
|
||||
|
||||
if (changes.Length == 0)
|
||||
return new WriteResultDto(true, subject.Id, "Keine Änderung nötig.");
|
||||
|
||||
if (!await confirmation.ConfirmAsync("Fach ändern?", $"„{subject.Name}“\n{changes}".TrimEnd(), ct))
|
||||
return new WriteResultDto(false, null, "Vom Nutzer abgelehnt oder nicht bestätigt.");
|
||||
|
||||
try { subjects.Save(subject); }
|
||||
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException)
|
||||
{
|
||||
return new WriteResultDto(false, null, ex.Message);
|
||||
}
|
||||
return new WriteResultDto(true, subject.Id, "Fach gespeichert.");
|
||||
}
|
||||
|
||||
[Description("Löscht ein Fach endgültig. Schlägt fehl, wenn noch eine Lerngruppe oder ein Kompetenzkatalog dieses Fach referenziert. Kein Papierkorb - nicht rückgängig zu machen. Muss der Nutzer erst bestätigen.")]
|
||||
public async Task<WriteResultDto> DeleteSubject(
|
||||
[Description("Fach-ID.")] Guid subjectId,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var subject = subjects.GetById(subjectId);
|
||||
if (subject is null) return new WriteResultDto(false, null, "Unbekannte Fach-ID.");
|
||||
|
||||
var message = $"Das Fach „{subject.Name}“ wird endgültig gelöscht. Das kann NICHT rückgängig gemacht werden (kein Papierkorb für Fächer).";
|
||||
if (!await confirmation.ConfirmAsync("Fach endgültig löschen?", message, ct))
|
||||
return new WriteResultDto(false, null, "Vom Nutzer abgelehnt oder nicht bestätigt.");
|
||||
|
||||
try { subjects.Delete(subjectId); }
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
return new WriteResultDto(false, null, ex.Message);
|
||||
}
|
||||
return new WriteResultDto(true, subjectId, "Fach gelöscht.");
|
||||
}
|
||||
|
||||
// ── Kompetenzbereiche (CompetencyDomain) ────────────────────────────────────────────────
|
||||
|
||||
[Description("Legt einen neuen Kompetenzbereich (z.B. \"Zahlen und Operationen\") für ein Fach, eine Klassenstufe und eine Bildungsplan-Version an, zunächst ohne Einzelkompetenzen. Muss der Nutzer erst bestätigen.")]
|
||||
public async Task<WriteResultDto> CreateCompetencyDomain(
|
||||
[Description("Fach-ID, aus get_subjects.")] Guid subjectId,
|
||||
[Description("Klassenstufe.")] int gradeLevel,
|
||||
[Description("Name des Bereichs.")] string name,
|
||||
[Description("Optionales Kürzel, z.B. \"ZO\".")] string code = "",
|
||||
[Description("Bildungsplan-Version, aus get_competency_plan_versions. Weglassen: Standardversion des Fachs.")] Guid? versionId = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var subject = subjects.GetById(subjectId);
|
||||
if (subject is null) return new WriteResultDto(false, null, "Unbekannte Fach-ID.");
|
||||
if (string.IsNullOrWhiteSpace(name)) return new WriteResultDto(false, null, "Bereichsname darf nicht leer sein.");
|
||||
|
||||
var effectiveVersionId = versionId ?? versions.GetOrCreateDefault(subjectId).Id;
|
||||
var versionName = versions.GetById(effectiveVersionId)?.Name ?? "";
|
||||
var sortOrder = domains.GetBySubjectAndGrade(subjectId, gradeLevel, effectiveVersionId).Count;
|
||||
var message = $"Neuen Kompetenzbereich „{name.Trim()}“ für {subject.Name}, Klasse {gradeLevel} ({versionName}), anlegen?";
|
||||
if (!await confirmation.ConfirmAsync("Kompetenzbereich anlegen?", message, ct))
|
||||
return new WriteResultDto(false, null, "Vom Nutzer abgelehnt oder nicht bestätigt.");
|
||||
|
||||
var domain = new CompetencyDomain
|
||||
{
|
||||
SubjectId = subjectId, GradeLevel = gradeLevel, VersionId = effectiveVersionId,
|
||||
Name = name, Code = code, SortOrder = sortOrder,
|
||||
};
|
||||
domains.Save(domain);
|
||||
return new WriteResultDto(true, domain.Id, "Kompetenzbereich gespeichert.");
|
||||
}
|
||||
|
||||
[Description("Ändert Name/Kürzel eines bestehenden Kompetenzbereichs. Nur angegebene Felder werden geändert.")]
|
||||
public async Task<WriteResultDto> UpdateCompetencyDomain(
|
||||
[Description("ID des Kompetenzbereichs, aus get_competency_catalog.")] Guid domainId,
|
||||
[Description("Neuer Name. Unverändert lassen: weglassen.")] string? name = null,
|
||||
[Description("Neues Kürzel. Unverändert lassen: weglassen.")] string? code = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var domain = domains.GetById(domainId);
|
||||
if (domain is null) return new WriteResultDto(false, null, "Unbekannte Bereichs-ID.");
|
||||
|
||||
var changes = new StringBuilder();
|
||||
if (name is not null && name != domain.Name) { changes.AppendLine($"Name: „{domain.Name}“ → „{name}“"); domain.Name = name; }
|
||||
if (code is not null && code != domain.Code) { changes.AppendLine($"Kürzel: „{domain.Code}“ → „{code}“"); domain.Code = code; }
|
||||
|
||||
if (changes.Length == 0)
|
||||
return new WriteResultDto(true, domain.Id, "Keine Änderung nötig.");
|
||||
|
||||
if (!await confirmation.ConfirmAsync("Kompetenzbereich ändern?", $"„{domain.Name}“\n{changes}".TrimEnd(), ct))
|
||||
return new WriteResultDto(false, null, "Vom Nutzer abgelehnt oder nicht bestätigt.");
|
||||
|
||||
domains.Save(domain);
|
||||
return new WriteResultDto(true, domain.Id, "Kompetenzbereich gespeichert.");
|
||||
}
|
||||
|
||||
[Description("Löscht einen Kompetenzbereich endgültig, inklusive aller darin enthaltenen Einzelkompetenzen. Bereits vergebene Kompetenzcodes an Einheiten/Stunden/Klausuraufgaben bleiben als Freitext bestehen, gelten aber danach als \"nicht im Katalog\". Kein Papierkorb - nicht rückgängig zu machen. Muss der Nutzer erst bestätigen.")]
|
||||
public async Task<WriteResultDto> DeleteCompetencyDomain(
|
||||
[Description("ID des Kompetenzbereichs.")] Guid domainId,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var domain = domains.GetById(domainId);
|
||||
if (domain is null) return new WriteResultDto(false, null, "Unbekannte Bereichs-ID.");
|
||||
|
||||
var message = $"Der Kompetenzbereich „{domain.Name}“ mit {domain.Items.Count} Einzelkompetenz(en) wird endgültig gelöscht. " +
|
||||
"Das kann NICHT rückgängig gemacht werden (kein Papierkorb für Kompetenzbereiche).";
|
||||
if (!await confirmation.ConfirmAsync("Kompetenzbereich endgültig löschen?", message, ct))
|
||||
return new WriteResultDto(false, null, "Vom Nutzer abgelehnt oder nicht bestätigt.");
|
||||
|
||||
domains.Delete(domainId);
|
||||
return new WriteResultDto(true, domainId, "Kompetenzbereich gelöscht.");
|
||||
}
|
||||
|
||||
// ── Einzelkompetenzen (CompetencyItem) ──────────────────────────────────────────────────
|
||||
|
||||
[Description("Fügt einem Kompetenzbereich eine neue Einzelkompetenz hinzu (ans Ende). Muss der Nutzer erst bestätigen.")]
|
||||
public async Task<WriteResultDto> AddCompetencyItem(
|
||||
[Description("ID des Kompetenzbereichs, aus get_competency_catalog.")] Guid domainId,
|
||||
[Description("Kompetenzcode, z.B. \"M.5.1\".")] string code,
|
||||
[Description("Beschreibung der Kompetenz.")] string description,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var domain = domains.GetById(domainId);
|
||||
if (domain is null) return new WriteResultDto(false, null, "Unbekannte Bereichs-ID.");
|
||||
if (string.IsNullOrWhiteSpace(description)) return new WriteResultDto(false, null, "Beschreibung darf nicht leer sein.");
|
||||
|
||||
var message = $"Neue Kompetenz „{code}“ zu Bereich „{domain.Name}“ hinzufügen?\n{description}";
|
||||
if (!await confirmation.ConfirmAsync("Kompetenz hinzufügen?", message, ct))
|
||||
return new WriteResultDto(false, null, "Vom Nutzer abgelehnt oder nicht bestätigt.");
|
||||
|
||||
var item = new CompetencyItem { Code = code.Trim(), Description = description.Trim(), SortOrder = domain.Items.Count };
|
||||
domain.Items.Add(item);
|
||||
domains.Save(domain);
|
||||
return new WriteResultDto(true, item.Id, "Kompetenz hinzugefügt.");
|
||||
}
|
||||
|
||||
[Description("Ändert Code/Beschreibung einer bestehenden Einzelkompetenz. Nur angegebene Felder werden geändert.")]
|
||||
public async Task<WriteResultDto> UpdateCompetencyItem(
|
||||
[Description("ID des Kompetenzbereichs.")] Guid domainId,
|
||||
[Description("ID der Einzelkompetenz, aus get_competency_catalog.")] Guid itemId,
|
||||
[Description("Neuer Kompetenzcode. Unverändert lassen: weglassen.")] string? code = null,
|
||||
[Description("Neue Beschreibung. Unverändert lassen: weglassen.")] string? description = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var domain = domains.GetById(domainId);
|
||||
if (domain is null) return new WriteResultDto(false, null, "Unbekannte Bereichs-ID.");
|
||||
var item = domain.Items.FirstOrDefault(i => i.Id == itemId);
|
||||
if (item is null) return new WriteResultDto(false, null, "Unbekannte Kompetenz-ID in diesem Bereich.");
|
||||
|
||||
var changes = new StringBuilder();
|
||||
if (code is not null && code != item.Code) { changes.AppendLine($"Code: „{item.Code}“ → „{code}“"); item.Code = code; }
|
||||
if (description is not null && description != item.Description) { changes.AppendLine($"Beschreibung: „{item.Description}“ → „{description}“"); item.Description = description; }
|
||||
|
||||
if (changes.Length == 0)
|
||||
return new WriteResultDto(true, item.Id, "Keine Änderung nötig.");
|
||||
|
||||
if (!await confirmation.ConfirmAsync("Kompetenz ändern?", $"Kompetenz „{item.Code}“ in Bereich „{domain.Name}“\n{changes}".TrimEnd(), ct))
|
||||
return new WriteResultDto(false, null, "Vom Nutzer abgelehnt oder nicht bestätigt.");
|
||||
|
||||
domains.Save(domain);
|
||||
return new WriteResultDto(true, item.Id, "Kompetenz gespeichert.");
|
||||
}
|
||||
|
||||
[Description("Entfernt eine Einzelkompetenz aus einem Kompetenzbereich. Muss der Nutzer erst bestätigen.")]
|
||||
public async Task<WriteResultDto> RemoveCompetencyItem(
|
||||
[Description("ID des Kompetenzbereichs.")] Guid domainId,
|
||||
[Description("ID der Einzelkompetenz, aus get_competency_catalog.")] Guid itemId,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var domain = domains.GetById(domainId);
|
||||
if (domain is null) return new WriteResultDto(false, null, "Unbekannte Bereichs-ID.");
|
||||
var item = domain.Items.FirstOrDefault(i => i.Id == itemId);
|
||||
if (item is null) return new WriteResultDto(false, null, "Unbekannte Kompetenz-ID in diesem Bereich.");
|
||||
|
||||
var message = $"Kompetenz „{item.Code}“ ({item.Description}) aus Bereich „{domain.Name}“ entfernen?";
|
||||
if (!await confirmation.ConfirmAsync("Kompetenz entfernen?", message, ct))
|
||||
return new WriteResultDto(false, null, "Vom Nutzer abgelehnt oder nicht bestätigt.");
|
||||
|
||||
domain.Items.Remove(item);
|
||||
domains.Save(domain);
|
||||
return new WriteResultDto(true, item.Id, "Kompetenz entfernt.");
|
||||
}
|
||||
|
||||
private static CompetencyDomainDto ToDto(CompetencyDomain d) => new(
|
||||
d.Id, d.SubjectId, d.GradeLevel, d.VersionId, d.Name, d.Code, d.SortOrder,
|
||||
d.Items.OrderBy(i => i.SortOrder)
|
||||
.Select(i => new CompetencyItemDto(i.Id, i.Code, i.Description, i.SortOrder)).ToList());
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
using LehrerApp.Core.Models;
|
||||
|
||||
namespace LehrerApp.Desktop.Services.Mcp.Tools;
|
||||
|
||||
// Schlanke, bewusst nicht 1:1 zu den LiteDB-Entities gehaltene Rückgabetypen: verhindert, dass ein
|
||||
// später zum Modell hinzugefügtes Feld (z.B. ein neues personenbezogenes Attribut) unbeabsichtigt
|
||||
// über ein MCP-Tool nach außen dringt, nur weil es Teil der Entity-Klasse ist.
|
||||
|
||||
public record StudentDto(Guid Id, string FirstName, string LastName, bool IsActive);
|
||||
|
||||
public record ExamResultDto(Guid StudentId, double TotalPoints, string? Grade, bool Absent);
|
||||
|
||||
public record ExamDto(
|
||||
Guid Id, Guid GroupId, string Title, DateOnly Date, ExamStatus Status, Niveau? Niveau,
|
||||
List<ExamResultDto>? Results);
|
||||
|
||||
public record GradeDto(
|
||||
Guid Id, Guid StudentId, Guid GroupId, GradeCategory Category, string Value, DateOnly Date,
|
||||
double Weight, string? Note);
|
||||
|
||||
public record TimetableSlotDto(Guid Id, Guid GroupId, DayOfWeek Weekday, int PeriodNumber, string? Room);
|
||||
|
||||
public record TimeEntryDto(
|
||||
Guid Id, Guid? TaskId, string Category, Guid? GroupId, DateOnly Date,
|
||||
TimeOnly? StartTime, TimeOnly? EndTime, int DurationMinutes, string? Description);
|
||||
|
||||
/// <summary><see cref="MaterialPrompt"/> ist der beim letzten KI-"Übernehmen" gespeicherte
|
||||
/// Materialerstellungs-Prompt (4.5.20/4.5.36) — nur gesetzt, wenn die KI für diese Phase einen
|
||||
/// Medienvorschlag gemacht hatte. Ein MCP-Client kann ihn direkt zur Materialerzeugung nutzen, ohne
|
||||
/// erst den Desktop-Dialog öffnen zu müssen.</summary>
|
||||
public record LessonPhaseDto(
|
||||
Guid Id, string Name, int DurationMinutes, string Activity, string Material, string Shorthand,
|
||||
string? MaterialPrompt);
|
||||
|
||||
public record LessonAttachmentDto(string StorageId, string FileName, long SizeBytes);
|
||||
|
||||
/// <summary>Eine über MCP zugeordnete Kompetenz - Id + zum Zuordnungszeitpunkt gespeicherte
|
||||
/// Momentaufnahme aus Code/Description (siehe CompetencyReference), damit ein KI-Client sie ohne
|
||||
/// Zusatzabfrage lesen kann, auch wenn das Katalog-Item inzwischen gelöscht wurde.</summary>
|
||||
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(
|
||||
Guid Id, Guid UnitId, Guid GroupId, DateOnly Date, int? LessonNumber, string Topic,
|
||||
string? Homework, string? PlanningIdeas, LessonStatus Status, List<CompetencyReferenceDto> Competencies,
|
||||
List<LessonPhaseDto> Phases, List<LessonAttachmentDto> Attachments);
|
||||
|
||||
/// <summary>Ergebnis von "download_lesson_attachment": Inhalt Base64-kodiert, weil MCP-Tool-Antworten
|
||||
/// als JSON/Text übertragen werden. Bewusst kein Ressourcen-URI-Mechanismus (siehe Planungsdokument) -
|
||||
/// dafür müsste der Server MCP-Resources anbieten, was über den Rahmen dieses Tools hinausgeht;
|
||||
/// stattdessen deckelt <see cref="LessonPlanTools.MaxInlineAttachmentBytes"/> die Größe.</summary>
|
||||
public record AttachmentContentDto(string FileName, long SizeBytes, string Base64Content);
|
||||
|
||||
public record UnitDto(
|
||||
Guid Id, Guid GroupId, string Title, DateOnly? StartDate, DateOnly? EndDate,
|
||||
UnitStatus Status, List<CompetencyReferenceDto> Competencies);
|
||||
|
||||
public record LessonPlanResultDto(List<UnitDto> Units, List<LessonDto> Lessons);
|
||||
|
||||
public record SubjectDto(Guid Id, string Name, string ShortName);
|
||||
|
||||
public record CompetencyItemDto(Guid Id, string Code, string Description, int SortOrder);
|
||||
|
||||
public record CompetencyDomainDto(
|
||||
Guid Id, Guid SubjectId, int GradeLevel, Guid VersionId, string Name, string Code, int SortOrder,
|
||||
List<CompetencyItemDto> Items);
|
||||
|
||||
/// <summary>Eine Bildungsplan-Version eines Fachs, siehe CompetencyTools.GetCompetencyPlanVersions.</summary>
|
||||
public record CompetencyPlanVersionDto(Guid Id, Guid SubjectId, string Name, bool IsDefault, int SortOrder);
|
||||
|
||||
public record GroupMembershipDto(
|
||||
Guid Id, Guid StudentId, Guid GroupId, MembershipPeriod Period,
|
||||
DateOnly? JoinedAt, DateOnly? LeftAt, Niveau? Niveau);
|
||||
|
||||
/// <summary>Ergebnis eines Write-Tools (Phase 2, siehe Planungsdokument): <see cref="Applied"/> ist
|
||||
/// nur dann true, wenn der Nutzer die Änderung im Bestätigungsdialog angenommen hat.</summary>
|
||||
public record WriteResultDto(bool Applied, Guid? Id, string Message);
|
||||
|
||||
public record PlaceholderInfoDto(string Name, string Type, bool Required, bool IsConstant);
|
||||
|
||||
/// <summary>"Worksheets" aus der ursprünglichen Spec entsprechen im tatsächlichen Datenmodell den
|
||||
/// importierten Elternbrief-Vorlagen (<c>.lavorlage</c>, <c>LehrerApp.Templating</c>) — es gibt kein
|
||||
/// separates "Arbeitsblatt"-Konzept mit Fach/Klassenstufe-Metadaten. Siehe LetterTemplateTools.</summary>
|
||||
public record LetterTemplateDto(string Id, string Name, string Description, List<PlaceholderInfoDto> Placeholders);
|
||||
|
||||
public record LetterRenderResultDto(bool Success, string Message, string? Base64Pdf, string? SuggestedFileName);
|
||||
|
||||
/// <summary>Eine Zeile des Untis-Hub (siehe UntisHubService) - "Kind"/"DueState" als Text statt
|
||||
/// Enum-Wert, damit ein KI-Client sie ohne Kenntnis des internen Enums lesen kann. GroupId ist bei
|
||||
/// den drei dashboard-weiten Zeilen (offene Stunden, Klassenbuch-/Hausaufgabenabgleich) null - siehe
|
||||
/// UntisHubJobRow. Enthalten, damit ein KI-Client die Id nicht erst über get_groups nachschlagen
|
||||
/// muss, um get_untis_absence_rows/get_named_untis_absence_pattern für eine hier gelistete Gruppe
|
||||
/// aufzurufen (Nutzer-Feedback: die GroupId war nirgends exponiert).</summary>
|
||||
public record UntisHubStatusRowDto(
|
||||
string Kind, Guid? GroupId, string GroupName, string DueState, string DueLabel,
|
||||
DateTime? LastRunAt, string? LastResultSummary);
|
||||
|
||||
/// <summary>Lerngruppe (Klasse oder Kurs) - siehe GroupTools.GetGroups. Bewusst kein Verweis auf
|
||||
/// SubjectId->Name aufgelöst (dafür get_subjects), um nicht bei jeder Gruppe implizit einen ganzen
|
||||
/// Fach-Datensatz mitzuschleppen.</summary>
|
||||
public record GroupDto(
|
||||
Guid Id, string Name, GroupType Type, string SchoolYear, int GradeLevel,
|
||||
Guid? SubjectId, bool IsActive, Guid? CompetencyPlanVersionId);
|
||||
|
||||
/// <summary>Anonymisierte Fehlzeiten-Diskrepanz (siehe UntisComparisonTools.GetUntisAbsenceRows):
|
||||
/// bewusst KEIN Schülername/keine Klasse - <see cref="RowId"/> ist die einzige Kennung, über die
|
||||
/// UntisComparisonTools.ApplyUntisAbsenceStatus später zurückordnet.</summary>
|
||||
public record UntisAbsenceRowDto(
|
||||
string RowId, DateOnly Date, string ReasonText, int AbsentMinutes, bool HandledOn,
|
||||
bool? ExternKeyInParentheses, string CurrentLocalStatus, string CurrentGuessStatus);
|
||||
|
||||
/// <summary>Eine Zeile aus dem namentlichen Ausnahmeweg (get_named_untis_absence_pattern) - im
|
||||
/// Unterschied zu <see cref="UntisAbsenceRowDto"/> bewusst MIT Schülername, da genau diese
|
||||
/// Zusammenführung von Name und Fehlzeitendaten der Zweck des Aufrufs ist (z.B. Fehlmuster-Vergleich
|
||||
/// zwischen zwei Schülern) und der Nutzer sie je Anfrage einzeln freigegeben hat.</summary>
|
||||
public record NamedUntisAbsenceRowDto(
|
||||
Guid StudentId, string StudentFullName, DateOnly Date, string ReasonText,
|
||||
string CurrentLocalStatus, string CurrentGuessStatus);
|
||||
|
||||
/// <summary><see cref="Granted"/> ist false bei Ablehnung/Timeout oder wenn keine der angegebenen
|
||||
/// Schüler-IDs bekannt war - <see cref="Rows"/> ist dann null, nicht nur leer, damit ein KI-Client
|
||||
/// "abgelehnt" nicht mit "keine Fehlzeiten gefunden" verwechselt.</summary>
|
||||
public record NamedUntisAbsenceResultDto(bool Granted, string Message, List<NamedUntisAbsenceRowDto>? Rows);
|
||||
@@ -0,0 +1,23 @@
|
||||
using System.ComponentModel;
|
||||
using LehrerApp.Core.Interfaces;
|
||||
|
||||
namespace LehrerApp.Desktop.Services.Mcp.Tools;
|
||||
|
||||
/// <summary>MCP-Read-Tool "get_exams" (Phase 1, siehe Planungsdokument).</summary>
|
||||
public class ExamTools(IExamRepository exams, IExamResultRepository examResults)
|
||||
{
|
||||
[Description("Listet Klausuren, optional gefiltert nach Lerngruppe.")]
|
||||
public List<ExamDto> GetExams(
|
||||
[Description("Optionale Lerngruppen-ID zum Filtern.")] Guid? groupId = null,
|
||||
[Description("Ergebnisse je Schüler mitliefern (Standard: nein, hält die Antwort klein).")] bool includeResults = false)
|
||||
{
|
||||
var list = groupId is { } id ? exams.GetByGroup(id) : exams.GetAll();
|
||||
return list.Select(e => new ExamDto(
|
||||
e.Id, e.GroupId, e.Title, e.Date, e.Status, e.Niveau,
|
||||
includeResults
|
||||
? examResults.GetByExam(e.Id)
|
||||
.Select(r => new ExamResultDto(r.StudentId, r.TotalPoints, r.Grade, r.Absent))
|
||||
.ToList()
|
||||
: null)).ToList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using System.ComponentModel;
|
||||
using LehrerApp.Core.Interfaces;
|
||||
using LehrerApp.Core.Models;
|
||||
|
||||
namespace LehrerApp.Desktop.Services.Mcp.Tools;
|
||||
|
||||
/// <summary>MCP-Tools "get_grades" (Phase 1) und "create_grade_entry" (Phase 2), siehe
|
||||
/// Planungsdokument.</summary>
|
||||
public class GradeTools(IGradeRepository grades, IStudentRepository students, IMcpConfirmationService confirmation)
|
||||
{
|
||||
[Description("Listet Noten einer Lerngruppe, optional gefiltert auf einen einzelnen Schüler.")]
|
||||
public List<GradeDto> GetGrades(
|
||||
[Description("Lerngruppen-ID.")] Guid groupId,
|
||||
[Description("Optionale Schüler-ID zum Filtern auf einen einzelnen Schüler.")] Guid? studentId = null)
|
||||
{
|
||||
var list = studentId is { } sid ? grades.GetByStudentAndGroup(sid, groupId) : grades.GetByGroup(groupId);
|
||||
return list.Select(g => new GradeDto(
|
||||
g.Id, g.StudentId, g.GroupId, g.Category, g.Value, g.Date, g.Weight, g.Note)).ToList();
|
||||
}
|
||||
|
||||
[Description("Schlägt eine neue Note für einen Schüler vor. Muss der Nutzer erst in einem Dialog in LehrerApp bestätigen, bevor sie gespeichert wird.")]
|
||||
public async Task<WriteResultDto> CreateGradeEntry(
|
||||
[Description("Schüler-ID.")] Guid studentId,
|
||||
[Description("Lerngruppen-ID.")] Guid groupId,
|
||||
[Description("Kategorie: Oral, Homework, Participation, Project oder Other.")] GradeCategory category,
|
||||
[Description("Notenwert als Text, z.B. \"2+\" oder \"gut\".")] string value,
|
||||
[Description("Datum, Format YYYY-MM-DD.")] DateOnly date,
|
||||
[Description("Gewichtung, Standard 1.0.")] double weight = 1.0,
|
||||
[Description("Optionale Notiz.")] string? note = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var student = students.GetById(studentId);
|
||||
if (student is null)
|
||||
return new WriteResultDto(false, null, "Unbekannte Schüler-ID.");
|
||||
|
||||
var message =
|
||||
$"Neue Note für {student.FullName}: {GradeCategoryDisplayName(category)} = {value}" +
|
||||
(weight != 1.0 ? $" (Gewichtung {weight:0.##})" : "") +
|
||||
$", am {date:dd.MM.yyyy}" +
|
||||
(string.IsNullOrWhiteSpace(note) ? "" : $"\n„{note}“");
|
||||
|
||||
if (!await confirmation.ConfirmAsync("Note anlegen?", message, ct))
|
||||
return new WriteResultDto(false, null, "Vom Nutzer abgelehnt oder nicht bestätigt.");
|
||||
|
||||
var grade = new Grade
|
||||
{
|
||||
StudentId = studentId,
|
||||
GroupId = groupId,
|
||||
Category = category,
|
||||
Value = value,
|
||||
Date = date,
|
||||
Weight = weight,
|
||||
Note = note,
|
||||
};
|
||||
grades.Save(grade);
|
||||
return new WriteResultDto(true, grade.Id, "Note gespeichert.");
|
||||
}
|
||||
|
||||
// Eigene, schlanke Beschriftung statt Wiederverwendung von ViewModels.Groups.GradeCategoryDisplay:
|
||||
// Tool-Klassen unter Services/Mcp sollen nicht von ViewModel-Klassen abhängen.
|
||||
private static string GradeCategoryDisplayName(GradeCategory c) => c switch
|
||||
{
|
||||
GradeCategory.Oral => "Mündlich",
|
||||
GradeCategory.Homework => "Hausaufgaben",
|
||||
GradeCategory.Participation => "Mitarbeit",
|
||||
GradeCategory.Project => "Projekt",
|
||||
GradeCategory.Other => "Sonstiges",
|
||||
_ => c.ToString(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
using System.ComponentModel;
|
||||
using System.Text;
|
||||
using LehrerApp.Core.Interfaces;
|
||||
using LehrerApp.Core.Models;
|
||||
|
||||
namespace LehrerApp.Desktop.Services.Mcp.Tools;
|
||||
|
||||
/// <summary>MCP-Write-Tool "update_student_group_assignment" (Phase 2, siehe Planungsdokument).
|
||||
/// Legt eine <see cref="GroupMembership"/> an, falls noch keine für Schüler+Gruppe existiert, sonst
|
||||
/// werden nur die übergebenen (nicht-null) Felder überschrieben.</summary>
|
||||
public class GroupMembershipTools(
|
||||
IGroupMembershipRepository memberships, IStudentRepository students, IGroupRepository groups,
|
||||
IMcpConfirmationService confirmation)
|
||||
{
|
||||
[Description("Legt eine Gruppenmitgliedschaft eines Schülers an oder ändert Niveau/Zeitraum einer bestehenden. Muss der Nutzer erst in einem Dialog in LehrerApp bestätigen.")]
|
||||
public async Task<WriteResultDto> UpdateStudentGroupAssignment(
|
||||
[Description("Schüler-ID.")] Guid studentId,
|
||||
[Description("Lerngruppen-ID.")] Guid groupId,
|
||||
[Description("Niveau: E, G oder Foerder. Unverändert lassen: weglassen.")] Niveau? niveau = 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("Austrittsdatum bei Custom-Zeitraum, Format YYYY-MM-DD.")] DateOnly? leftAt = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var student = students.GetById(studentId);
|
||||
var group = groups.GetById(groupId);
|
||||
if (student is null || group is null)
|
||||
return new WriteResultDto(false, null, "Unbekannte Schüler- oder Gruppen-ID.");
|
||||
|
||||
var existing = memberships.GetByStudentAndGroup(studentId, groupId);
|
||||
var target = existing is null
|
||||
? new GroupMembership { StudentId = studentId, GroupId = groupId }
|
||||
: Clone(existing);
|
||||
|
||||
var changes = new StringBuilder();
|
||||
if (niveau is not null && niveau != target.Niveau) { changes.AppendLine($"Niveau: {NiveauName(target.Niveau)} → {NiveauName(niveau)}"); target.Niveau = niveau; }
|
||||
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 (leftAt is not null && leftAt != target.LeftAt) { changes.AppendLine($"Austritt: {target.LeftAt:dd.MM.yyyy} → {leftAt:dd.MM.yyyy}"); target.LeftAt = leftAt; }
|
||||
|
||||
if (existing is not null && changes.Length == 0)
|
||||
return new WriteResultDto(true, existing.Id, "Keine Änderung nötig, Mitgliedschaft besteht bereits unverändert.");
|
||||
|
||||
var title = existing is null ? "Gruppenmitgliedschaft anlegen?" : "Gruppenmitgliedschaft ändern?";
|
||||
var message = $"{student.FullName} — {group.Name}" +
|
||||
(existing is null ? "\nNeue Mitgliedschaft anlegen." : "") +
|
||||
(changes.Length > 0 ? "\n" + changes.ToString().TrimEnd() : "");
|
||||
|
||||
if (!await confirmation.ConfirmAsync(title, message, ct))
|
||||
return new WriteResultDto(false, null, "Vom Nutzer abgelehnt oder nicht bestätigt.");
|
||||
|
||||
memberships.Save(target);
|
||||
return new WriteResultDto(true, target.Id, "Gruppenmitgliedschaft gespeichert.");
|
||||
}
|
||||
|
||||
private static GroupMembership Clone(GroupMembership m) => new()
|
||||
{
|
||||
Id = m.Id, StudentId = m.StudentId, GroupId = m.GroupId, AddedOn = m.AddedOn,
|
||||
Period = m.Period, JoinedAt = m.JoinedAt, LeftAt = m.LeftAt, Niveau = m.Niveau,
|
||||
};
|
||||
|
||||
private static string NiveauName(Niveau? n) => n switch
|
||||
{
|
||||
Core.Models.Niveau.E => "E-Niveau",
|
||||
Core.Models.Niveau.G => "G-Niveau",
|
||||
Core.Models.Niveau.Foerder => "Förderniveau",
|
||||
_ => "–",
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
using System.ComponentModel;
|
||||
using System.Text;
|
||||
using LehrerApp.Core.Interfaces;
|
||||
|
||||
namespace LehrerApp.Desktop.Services.Mcp.Tools;
|
||||
|
||||
/// <summary>MCP-Tools für Lerngruppen (Klassen/Kurse). "get_groups" (Nutzer-Nachtrag: die GroupId,
|
||||
/// die praktisch jedes andere Tool als Pflichtparameter verlangt - get_grades, get_schedule,
|
||||
/// get_lesson_plans, get_untis_absence_rows usw. - war nirgends über MCP auflösbar; ein KI-Client
|
||||
/// kannte bestenfalls den Klarnamen einer Lerngruppe aus dem Gespräch, nie ihre Id) ist reiner
|
||||
/// Lesezugriff. "update_group_competency_version" ist das erste Schreib-Tool auf einem
|
||||
/// LearningGroup-Feld selbst (Nutzer-Nachtrag zur Bildungsplan-Versionierung) - deshalb bewusst eng
|
||||
/// auf genau dieses eine Feld geschnitten statt eines allgemeinen "update_group".</summary>
|
||||
public class GroupTools(IGroupRepository groups, ICompetencyCatalogVersionRepository versions,
|
||||
IMcpConfirmationService confirmation)
|
||||
{
|
||||
[Description("Listet Lerngruppen (Klassen/Kurse) mit ihrer Id - Voraussetzung, um andere Tools (z.B. get_grades, get_schedule, get_untis_absence_rows) für eine bestimmte Gruppe aufzurufen, wenn nur ihr Name bekannt ist. Ohne schoolYear werden alle Schuljahre zurückgegeben.")]
|
||||
public List<GroupDto> GetGroups(
|
||||
[Description("Optionales Schuljahr zum Filtern, Format \"2025/26\". Ohne Angabe alle Schuljahre.")] string? schoolYear = null,
|
||||
[Description("Auch inaktive/archivierte Gruppen einbeziehen.")] bool includeInactive = false)
|
||||
{
|
||||
var list = schoolYear is null
|
||||
? groups.GetAll(includeInactive)
|
||||
: groups.GetBySchoolYear(schoolYear, includeInactive);
|
||||
return list.Select(g => new GroupDto(g.Id, g.Name, g.Type, g.SchoolYear, g.GradeLevel,
|
||||
g.SubjectId, g.IsActive, g.CompetencyCatalogVersionId)).ToList();
|
||||
}
|
||||
|
||||
[Description("Setzt oder löscht die Bildungsplan-Version eines Kurses/einer Klasse (welcher Kompetenzkatalog für diese Gruppe gilt). Muss der Nutzer erst bestätigen.")]
|
||||
public async Task<WriteResultDto> UpdateGroupCompetencyVersion(
|
||||
[Description("Gruppen-ID, aus get_groups.")] Guid groupId,
|
||||
[Description("Bildungsplan-Version, aus get_competency_plan_versions. Weglassen: zurück auf die Standardversion des Fachs.")] Guid? versionId = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var group = groups.GetById(groupId);
|
||||
if (group is null) return new WriteResultDto(false, null, "Unbekannte Gruppen-ID.");
|
||||
if (versionId is Guid vid && versions.GetById(vid) is null)
|
||||
return new WriteResultDto(false, null, "Unbekannte Versions-ID.");
|
||||
|
||||
var oldName = group.CompetencyCatalogVersionId is Guid oldId ? versions.GetById(oldId)?.Name ?? "unbekannt" : "Standardversion";
|
||||
var newName = versionId is Guid newId ? versions.GetById(newId)?.Name ?? "unbekannt" : "Standardversion";
|
||||
if (oldName == newName && group.CompetencyCatalogVersionId == versionId)
|
||||
return new WriteResultDto(true, group.Id, "Keine Änderung nötig.");
|
||||
|
||||
var message = new StringBuilder($"Bildungsplan-Version von „{group.Name}“ ändern:\n{oldName} → {newName}");
|
||||
if (!await confirmation.ConfirmAsync("Bildungsplan-Version ändern?", message.ToString(), ct))
|
||||
return new WriteResultDto(false, null, "Vom Nutzer abgelehnt oder nicht bestätigt.");
|
||||
|
||||
group.CompetencyCatalogVersionId = versionId;
|
||||
groups.Save(group);
|
||||
return new WriteResultDto(true, group.Id, "Bildungsplan-Version gespeichert.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,427 @@
|
||||
using System.ComponentModel;
|
||||
using System.Text;
|
||||
using LehrerApp.Core.Interfaces;
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Core.Services;
|
||||
|
||||
namespace LehrerApp.Desktop.Services.Mcp.Tools;
|
||||
|
||||
/// <summary>MCP-Tools rund um Unterrichtseinheiten (<see cref="Unit"/>) und Einzelstunden
|
||||
/// (<see cref="Lesson"/>) — Phase 1 (get_lesson_plans) und Phase 3 (siehe Planungsdokument).
|
||||
///
|
||||
/// Bewusst kleinteilig statt eines einzelnen "update_lesson", das die komplette Stunde inkl.
|
||||
/// Verlaufsplan als ein großes JSON-Objekt tauscht: <see cref="Lesson.Phases"/> ist zwar technisch
|
||||
/// eine eingebettete Liste im selben LiteDB-Dokument (keine echte Sub-Collection, also kein
|
||||
/// Zeilen-Locking auf DB-Ebene) — kleinteilige Tools verkürzen aber das Zeitfenster zwischen Lesen
|
||||
/// und Schreiben je Operation drastisch (ein Tool-Aufruf ändert nur eine Phase, nicht die ganze
|
||||
/// Stunde) und liefern einen für den Bestätigungsdialog tatsächlich lesbaren Diff statt eines
|
||||
/// kompletten Objekt-Dumps. Ein Tool, das die ganze Stunde überschreibt, ist bewusst NICHT
|
||||
/// vorgesehen; wo es fehlt, ist die Kombination aus update_lesson (Metadaten) +
|
||||
/// add/update/remove_lesson_phase (je eine Phase) der vorgesehene Weg.
|
||||
///
|
||||
/// "delete_lesson" ist (Stand Nutzer-Nachtrag) das einzige Lösch-Tool im gesamten MCP-Katalog —
|
||||
/// eine bewusste, gezielte Ausnahme von der sonst geltenden "v1 ohne Lösch-Tools"-Regel (siehe
|
||||
/// Planungsdokument), nicht deren Aufhebung. Entsprechend als "Destructive" annotiert
|
||||
/// (siehe McpServerHostedService) und mit besonders deutlicher Bestätigungsnachricht.</summary>
|
||||
public class LessonPlanTools(
|
||||
IUnitRepository units, ILessonRepository lessons, IGroupRepository groups,
|
||||
IAttachmentStorage attachments, ICompetencyDomainRepository competencyDomains,
|
||||
IMcpConfirmationService confirmation)
|
||||
{
|
||||
/// <summary>Deckelt die Antwortgröße von "download_lesson_attachment" (Base64 bläht ca. um
|
||||
/// Faktor 1,33 auf). Kleiner als <see cref="IAttachmentStorage.MaxSizeBytes"/> (App-weites
|
||||
/// Limit), damit ein einzelner MCP-Tool-Aufruf nicht unnötig groß wird — siehe Planungsdokument
|
||||
/// zum offenen Punkt "Ressourcen statt Inline-Base64 für große Dateien".</summary>
|
||||
public const long MaxInlineAttachmentBytes = 3 * 1024 * 1024;
|
||||
|
||||
// ── Lesen ────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
[Description("Listet Unterrichtseinheiten und -stunden einer Lerngruppe; die Einzelstunden werden auf den angegebenen Zeitraum gefiltert.")]
|
||||
public LessonPlanResultDto GetLessonPlans(
|
||||
[Description("Lerngruppen-ID.")] Guid groupId,
|
||||
[Description("Startdatum (einschließlich) für die Einzelstunden, Format YYYY-MM-DD.")] DateOnly from,
|
||||
[Description("Enddatum (einschließlich) für die Einzelstunden, Format YYYY-MM-DD.")] DateOnly to)
|
||||
{
|
||||
var unitDtos = units.GetByGroup(groupId)
|
||||
.Select(u => new UnitDto(u.Id, u.GroupId, u.Title, u.StartDate, u.EndDate, u.Status, ToDto(u.Competencies)))
|
||||
.ToList();
|
||||
var lessonDtos = lessons.GetByGroupAndRange(groupId, from, to)
|
||||
.Select(ToDto)
|
||||
.ToList();
|
||||
return new LessonPlanResultDto(unitDtos, lessonDtos);
|
||||
}
|
||||
|
||||
[Description("Lädt den Inhalt eines an eine Einzelstunde angehängten Materials (z.B. Arbeitsblatt) Base64-kodiert herunter. Für die storageId siehe get_lesson_plans.")]
|
||||
public AttachmentContentDto DownloadLessonAttachment(
|
||||
[Description("ID der Einzelstunde.")] Guid lessonId,
|
||||
[Description("Speicher-ID des Anhangs, aus get_lesson_plans.")] string storageId)
|
||||
{
|
||||
var lesson = lessons.GetById(lessonId) ?? throw new InvalidOperationException("Unbekannte Stunden-ID.");
|
||||
var attachment = lesson.Attachments.FirstOrDefault(a => a.StorageId == storageId)
|
||||
?? throw new InvalidOperationException("Kein Anhang mit dieser Speicher-ID an dieser Stunde.");
|
||||
if (attachment.SizeBytes > MaxInlineAttachmentBytes)
|
||||
throw new InvalidOperationException(
|
||||
$"Anhang ist mit {attachment.SizeBytes / 1024 / 1024} MB zu groß für eine Inline-Antwort (Limit {MaxInlineAttachmentBytes / 1024 / 1024} MB).");
|
||||
|
||||
using var stream = attachments.OpenRead(storageId)
|
||||
?? throw new InvalidOperationException("Anhang-Inhalt nicht auffindbar (Speicher inkonsistent).");
|
||||
using var buffer = new MemoryStream();
|
||||
stream.CopyTo(buffer);
|
||||
return new AttachmentContentDto(attachment.FileName, attachment.SizeBytes, Convert.ToBase64String(buffer.ToArray()));
|
||||
}
|
||||
|
||||
[Description("Fügt einer Einzelstunde ein neues Material (z.B. ein von der KI erzeugtes Arbeitsblatt) als Anhang hinzu, Base64-kodiert. Muss der Nutzer erst bestätigen.")]
|
||||
public async Task<WriteResultDto> AddLessonAttachment(
|
||||
[Description("ID der Einzelstunde.")] Guid lessonId,
|
||||
[Description("Dateiname inkl. Endung, z.B. \"arbeitsblatt.pdf\".")] string fileName,
|
||||
[Description("Dateiinhalt, Base64-kodiert.")] string base64Content,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var lesson = lessons.GetById(lessonId);
|
||||
if (lesson is null) return new WriteResultDto(false, null, "Unbekannte Stunden-ID.");
|
||||
|
||||
byte[] bytes;
|
||||
try { bytes = Convert.FromBase64String(base64Content); }
|
||||
catch (FormatException) { return new WriteResultDto(false, null, "Ungültiger Base64-Inhalt."); }
|
||||
|
||||
if (bytes.Length == 0) return new WriteResultDto(false, null, "Leerer Dateiinhalt.");
|
||||
if (bytes.Length > IAttachmentStorage.MaxSizeBytes)
|
||||
return new WriteResultDto(false, null,
|
||||
$"Datei ist mit {bytes.Length / 1024 / 1024} MB zu groß (Limit {IAttachmentStorage.MaxSizeBytes / 1024 / 1024} MB).");
|
||||
|
||||
var sizeDisplay = bytes.Length >= 1024 * 1024
|
||||
? $"{bytes.Length / 1024 / 1024} MB" : $"{Math.Max(1, bytes.Length / 1024)} KB";
|
||||
var message = $"„{fileName}“ ({sizeDisplay}) zu „{lesson.Topic}“ am {lesson.Date:dd.MM.yyyy} hinzufügen?";
|
||||
if (!await confirmation.ConfirmAsync("Material anhängen?", message, ct))
|
||||
return new WriteResultDto(false, null, "Vom Nutzer abgelehnt oder nicht bestätigt.");
|
||||
|
||||
string storageId;
|
||||
using (var stream = new MemoryStream(bytes)) storageId = attachments.Upload(fileName, stream);
|
||||
|
||||
lesson.Attachments.Add(new DocumentAttachment { StorageId = storageId, FileName = fileName, SizeBytes = bytes.Length });
|
||||
lessons.Save(lesson);
|
||||
// DocumentAttachment hat keine eigene Guid-Id (nur StorageId, ein string) - deshalb Id hier
|
||||
// null, storageId steht stattdessen in der Nachricht (für einen unmittelbaren Folgeaufruf,
|
||||
// z.B. download_lesson_attachment zur Bestätigung, ohne erst get_lesson_plans erneut aufzurufen).
|
||||
return new WriteResultDto(true, null, $"Anhang gespeichert (storageId={storageId}).");
|
||||
}
|
||||
|
||||
// ── Unterrichtseinheiten (Unit) ──────────────────────────────────────────────────────────
|
||||
|
||||
[Description("Legt eine neue Unterrichtseinheit an. Muss der Nutzer erst in einem Dialog in LehrerApp bestätigen.")]
|
||||
public async Task<WriteResultDto> CreateUnit(
|
||||
[Description("Lerngruppen-ID.")] Guid groupId,
|
||||
[Description("Titel der Einheit.")] string title,
|
||||
[Description("Optionales Startdatum, Format YYYY-MM-DD.")] DateOnly? startDate = null,
|
||||
[Description("Optionales Enddatum, Format YYYY-MM-DD.")] DateOnly? endDate = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var group = groups.GetById(groupId);
|
||||
if (group is null) return new WriteResultDto(false, null, "Unbekannte Gruppen-ID.");
|
||||
|
||||
var message = $"Neue Unterrichtseinheit „{title}“ für {group.Name} anlegen?" +
|
||||
(startDate is not null || endDate is not null
|
||||
? $"\nZeitraum: {startDate:dd.MM.yyyy} – {endDate:dd.MM.yyyy}" : "");
|
||||
if (!await confirmation.ConfirmAsync("Unterrichtseinheit anlegen?", message, ct))
|
||||
return new WriteResultDto(false, null, "Vom Nutzer abgelehnt oder nicht bestätigt.");
|
||||
|
||||
var unit = new Unit { GroupId = groupId, Title = title, StartDate = startDate, EndDate = endDate };
|
||||
units.Save(unit);
|
||||
return new WriteResultDto(true, unit.Id, "Unterrichtseinheit gespeichert.");
|
||||
}
|
||||
|
||||
[Description("Ändert Titel/Zeitraum/Status einer bestehenden Unterrichtseinheit. Nur angegebene Felder werden geändert.")]
|
||||
public async Task<WriteResultDto> UpdateUnit(
|
||||
[Description("ID der Unterrichtseinheit.")] Guid unitId,
|
||||
[Description("Neuer Titel. Unverändert lassen: weglassen.")] string? title = null,
|
||||
[Description("Neues Startdatum, Format YYYY-MM-DD. Unverändert lassen: weglassen.")] DateOnly? startDate = null,
|
||||
[Description("Neues Enddatum, Format YYYY-MM-DD. Unverändert lassen: weglassen.")] DateOnly? endDate = null,
|
||||
[Description("Neuer Status: Planned, Active oder Completed. Unverändert lassen: weglassen.")] UnitStatus? status = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var unit = units.GetById(unitId);
|
||||
if (unit is null) return new WriteResultDto(false, null, "Unbekannte Einheiten-ID.");
|
||||
|
||||
var changes = new StringBuilder();
|
||||
if (title is not null && title != unit.Title) { changes.AppendLine($"Titel: „{unit.Title}“ → „{title}“"); unit.Title = title; }
|
||||
if (startDate is not null && startDate != unit.StartDate) { changes.AppendLine($"Start: {unit.StartDate:dd.MM.yyyy} → {startDate:dd.MM.yyyy}"); unit.StartDate = startDate; }
|
||||
if (endDate is not null && endDate != unit.EndDate) { changes.AppendLine($"Ende: {unit.EndDate:dd.MM.yyyy} → {endDate:dd.MM.yyyy}"); unit.EndDate = endDate; }
|
||||
if (status is not null && status != unit.Status) { changes.AppendLine($"Status: {unit.Status} → {status}"); unit.Status = status.Value; }
|
||||
|
||||
if (changes.Length == 0)
|
||||
return new WriteResultDto(true, unit.Id, "Keine Änderung nötig.");
|
||||
|
||||
if (!await confirmation.ConfirmAsync("Unterrichtseinheit ändern?", $"„{unit.Title}“\n{changes}".TrimEnd(), ct))
|
||||
return new WriteResultDto(false, null, "Vom Nutzer abgelehnt oder nicht bestätigt.");
|
||||
|
||||
units.Save(unit);
|
||||
return new WriteResultDto(true, unit.Id, "Unterrichtseinheit gespeichert.");
|
||||
}
|
||||
|
||||
// ── Einzelstunden (Lesson) — Metadaten ───────────────────────────────────────────────────
|
||||
|
||||
[Description("Legt eine neue Einzelstunde ohne Verlaufsplan-Phasen an. Phasen danach einzeln über add_lesson_phase hinzufügen. Muss der Nutzer erst bestätigen.")]
|
||||
public async Task<WriteResultDto> CreateLesson(
|
||||
[Description("ID der übergeordneten Unterrichtseinheit.")] Guid unitId,
|
||||
[Description("Datum, Format YYYY-MM-DD.")] DateOnly date,
|
||||
[Description("Thema der Stunde.")] string topic,
|
||||
[Description("Optionale Stundennummer im Tagesraster.")] int? lessonNumber = null,
|
||||
[Description("Optionaler Stundenbeginn, Format HH:mm.")] TimeOnly? startTime = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var unit = units.GetById(unitId);
|
||||
if (unit is null) return new WriteResultDto(false, null, "Unbekannte Einheiten-ID.");
|
||||
|
||||
var message = $"Neue Stunde „{topic}“ am {date:dd.MM.yyyy} in Einheit „{unit.Title}“ anlegen?";
|
||||
if (!await confirmation.ConfirmAsync("Einzelstunde anlegen?", message, ct))
|
||||
return new WriteResultDto(false, null, "Vom Nutzer abgelehnt oder nicht bestätigt.");
|
||||
|
||||
var lesson = new Lesson
|
||||
{
|
||||
UnitId = unitId,
|
||||
GroupId = unit.GroupId,
|
||||
Date = date,
|
||||
Topic = topic,
|
||||
LessonNumber = lessonNumber,
|
||||
StartTime = startTime,
|
||||
};
|
||||
lessons.Save(lesson);
|
||||
return new WriteResultDto(true, lesson.Id, "Einzelstunde gespeichert.");
|
||||
}
|
||||
|
||||
[Description("Ändert Metadaten einer bestehenden Einzelstunde (Thema, Hausaufgabe, Planungsideen, Status, Beginn, Stundennummer) — der Verlaufsplan (Phasen) bleibt unverändert. Nur angegebene Felder werden geändert.")]
|
||||
public async Task<WriteResultDto> UpdateLesson(
|
||||
[Description("ID der Einzelstunde.")] Guid lessonId,
|
||||
[Description("Neues Thema. Unverändert lassen: weglassen.")] string? topic = null,
|
||||
[Description("Neue Hausaufgabe. Unverändert lassen: weglassen.")] string? homework = null,
|
||||
[Description("Neue Planungsideen (grober Entwurf vor der Feinplanung). Unverändert lassen: weglassen.")] string? planningIdeas = null,
|
||||
[Description("Neuer Status: Planned, Conducted, Draft, Ready oder Cancelled (ausgefallen, z.B. Exkursion/Feiertag - Alternative zu delete_lesson, wenn die Stunde als Ereignis dokumentiert bleiben soll). Unverändert lassen: weglassen.")] LessonStatus? status = null,
|
||||
[Description("Neuer Stundenbeginn, Format HH:mm. Unverändert lassen: weglassen.")] TimeOnly? startTime = null,
|
||||
[Description("Neue Stundennummer. Unverändert lassen: weglassen.")] int? lessonNumber = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var lesson = lessons.GetById(lessonId);
|
||||
if (lesson is null) return new WriteResultDto(false, null, "Unbekannte Stunden-ID.");
|
||||
|
||||
var changes = new StringBuilder();
|
||||
if (topic is not null && topic != lesson.Topic) { changes.AppendLine($"Thema: „{lesson.Topic}“ → „{topic}“"); lesson.Topic = topic; }
|
||||
if (homework is not null && homework != lesson.Homework) { changes.AppendLine($"Hausaufgabe: „{lesson.Homework}“ → „{homework}“"); lesson.Homework = homework; }
|
||||
if (planningIdeas is not null && planningIdeas != lesson.PlanningIdeas) { changes.AppendLine($"Planungsideen: „{lesson.PlanningIdeas}“ → „{planningIdeas}“"); lesson.PlanningIdeas = planningIdeas; }
|
||||
if (status is not null && status != lesson.Status) { changes.AppendLine($"Status: {lesson.Status} → {status}"); lesson.Status = status.Value; }
|
||||
if (startTime is not null && startTime != lesson.StartTime) { changes.AppendLine($"Beginn: {lesson.StartTime:HH\\:mm} → {startTime:HH\\:mm}"); lesson.StartTime = startTime; }
|
||||
if (lessonNumber is not null && lessonNumber != lesson.LessonNumber) { changes.AppendLine($"Nr.: {lesson.LessonNumber} → {lessonNumber}"); lesson.LessonNumber = lessonNumber; }
|
||||
|
||||
if (changes.Length == 0)
|
||||
return new WriteResultDto(true, lesson.Id, "Keine Änderung nötig.");
|
||||
|
||||
if (!await confirmation.ConfirmAsync("Einzelstunde ändern?", $"„{lesson.Topic}“ am {lesson.Date:dd.MM.yyyy}\n{changes}".TrimEnd(), ct))
|
||||
return new WriteResultDto(false, null, "Vom Nutzer abgelehnt oder nicht bestätigt.");
|
||||
|
||||
lessons.Save(lesson);
|
||||
return new WriteResultDto(true, lesson.Id, "Einzelstunde gespeichert.");
|
||||
}
|
||||
|
||||
// ── Einzelstunden (Lesson) — Verlaufsplan-Phasen ─────────────────────────────────────────
|
||||
|
||||
[Description("Fügt einer Einzelstunde eine neue Verlaufsplan-Phase hinzu (ans Ende). Muss der Nutzer erst bestätigen.")]
|
||||
public async Task<WriteResultDto> AddLessonPhase(
|
||||
[Description("ID der Einzelstunde.")] Guid lessonId,
|
||||
[Description("Name der Phase, z.B. \"Einstieg\", \"Erarbeitung\".")] string name,
|
||||
[Description("Dauer in Minuten.")] int durationMinutes,
|
||||
[Description("Tätigkeit/Sozialform.")] string activity = "",
|
||||
[Description("Material.")] string material = "",
|
||||
[Description("Kurzsymbol, z.B. \"AB001->S\".")] string shorthand = "",
|
||||
[Description("Optionaler, vollständiger Prompt zur Materialerstellung für diese Phase (siehe get_lesson_plans, LessonPhaseDto.MaterialPrompt) - z.B. wenn eine externe KI-Sitzung ihn selbst formuliert hat und er zur Wiederverwendung gespeichert werden soll.")] string? materialPrompt = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var lesson = lessons.GetById(lessonId);
|
||||
if (lesson is null) return new WriteResultDto(false, null, "Unbekannte Stunden-ID.");
|
||||
|
||||
var message = $"Neue Phase „{name}“ ({durationMinutes} Min.) zu „{lesson.Topic}“ am {lesson.Date:dd.MM.yyyy} hinzufügen?";
|
||||
if (!await confirmation.ConfirmAsync("Phase hinzufügen?", message, ct))
|
||||
return new WriteResultDto(false, null, "Vom Nutzer abgelehnt oder nicht bestätigt.");
|
||||
|
||||
var phase = new LessonPhaseStep
|
||||
{
|
||||
Name = name, DurationMinutes = durationMinutes, Activity = activity,
|
||||
Material = material, Shorthand = shorthand, MaterialPrompt = materialPrompt,
|
||||
};
|
||||
lesson.Phases.Add(phase);
|
||||
lessons.Save(lesson);
|
||||
return new WriteResultDto(true, phase.Id, "Phase hinzugefügt.");
|
||||
}
|
||||
|
||||
[Description("Ändert eine bestehende Verlaufsplan-Phase einer Einzelstunde. Nur angegebene Felder werden geändert.")]
|
||||
public async Task<WriteResultDto> UpdateLessonPhase(
|
||||
[Description("ID der Einzelstunde.")] Guid lessonId,
|
||||
[Description("ID der Phase, aus get_lesson_plans.")] Guid phaseId,
|
||||
[Description("Neuer Name. Unverändert lassen: weglassen.")] string? name = null,
|
||||
[Description("Neue Dauer in Minuten. Unverändert lassen: weglassen.")] int? durationMinutes = null,
|
||||
[Description("Neue Tätigkeit. Unverändert lassen: weglassen.")] string? activity = null,
|
||||
[Description("Neues Material. Unverändert lassen: weglassen.")] string? material = null,
|
||||
[Description("Neues Kurzsymbol. Unverändert lassen: weglassen.")] string? shorthand = null,
|
||||
[Description("Neuer Prompt zur Materialerstellung (siehe get_lesson_plans, LessonPhaseDto.MaterialPrompt). Unverändert lassen: weglassen.")] string? materialPrompt = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var lesson = lessons.GetById(lessonId);
|
||||
if (lesson is null) return new WriteResultDto(false, null, "Unbekannte Stunden-ID.");
|
||||
var phase = lesson.Phases.FirstOrDefault(p => p.Id == phaseId);
|
||||
if (phase is null) return new WriteResultDto(false, null, "Unbekannte Phasen-ID an dieser Stunde.");
|
||||
|
||||
var changes = new StringBuilder();
|
||||
if (name is not null && name != phase.Name) { changes.AppendLine($"Name: „{phase.Name}“ → „{name}“"); phase.Name = name; }
|
||||
if (durationMinutes is not null && durationMinutes != phase.DurationMinutes) { changes.AppendLine($"Dauer: {phase.DurationMinutes} → {durationMinutes} Min."); phase.DurationMinutes = durationMinutes.Value; }
|
||||
if (activity is not null && activity != phase.Activity) { changes.AppendLine($"Tätigkeit: „{phase.Activity}“ → „{activity}“"); phase.Activity = activity; }
|
||||
if (material is not null && material != phase.Material) { changes.AppendLine($"Material: „{phase.Material}“ → „{material}“"); phase.Material = material; }
|
||||
if (shorthand is not null && shorthand != phase.Shorthand) { changes.AppendLine($"Kürzel: „{phase.Shorthand}“ → „{shorthand}“"); phase.Shorthand = shorthand; }
|
||||
if (materialPrompt is not null && materialPrompt != phase.MaterialPrompt) { changes.AppendLine("Materialerstellungs-Prompt geändert."); phase.MaterialPrompt = materialPrompt; }
|
||||
|
||||
if (changes.Length == 0)
|
||||
return new WriteResultDto(true, phase.Id, "Keine Änderung nötig.");
|
||||
|
||||
if (!await confirmation.ConfirmAsync("Phase ändern?", $"Phase „{phase.Name}“ in „{lesson.Topic}“ am {lesson.Date:dd.MM.yyyy}\n{changes}".TrimEnd(), ct))
|
||||
return new WriteResultDto(false, null, "Vom Nutzer abgelehnt oder nicht bestätigt.");
|
||||
|
||||
lessons.Save(lesson);
|
||||
return new WriteResultDto(true, phase.Id, "Phase gespeichert.");
|
||||
}
|
||||
|
||||
[Description("Entfernt eine Verlaufsplan-Phase aus einer Einzelstunde. Muss der Nutzer erst bestätigen.")]
|
||||
public async Task<WriteResultDto> RemoveLessonPhase(
|
||||
[Description("ID der Einzelstunde.")] Guid lessonId,
|
||||
[Description("ID der Phase, aus get_lesson_plans.")] Guid phaseId,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var lesson = lessons.GetById(lessonId);
|
||||
if (lesson is null) return new WriteResultDto(false, null, "Unbekannte Stunden-ID.");
|
||||
var phase = lesson.Phases.FirstOrDefault(p => p.Id == phaseId);
|
||||
if (phase is null) return new WriteResultDto(false, null, "Unbekannte Phasen-ID an dieser Stunde.");
|
||||
|
||||
var message = $"Phase „{phase.Name}“ ({phase.DurationMinutes} Min.) aus „{lesson.Topic}“ am {lesson.Date:dd.MM.yyyy} entfernen?";
|
||||
if (!await confirmation.ConfirmAsync("Phase entfernen?", message, ct))
|
||||
return new WriteResultDto(false, null, "Vom Nutzer abgelehnt oder nicht bestätigt.");
|
||||
|
||||
lesson.Phases.Remove(phase);
|
||||
lessons.Save(lesson);
|
||||
return new WriteResultDto(true, phase.Id, "Phase entfernt.");
|
||||
}
|
||||
|
||||
// ── Einzelstunden (Lesson) — Kompetenzzuordnung ──────────────────────────────────────────
|
||||
// Auf Stundenebene (Lesson.Competencies), noch nicht je Phase - siehe TODO.md 4.5.8. Getrennte
|
||||
// add/remove-Tools statt eines "set_lesson_competencies", das die ganze Liste ersetzt: dieselbe
|
||||
// Race-Condition-Überlegung wie bei den Verlaufsplan-Phasen (add/update/remove_lesson_phase) -
|
||||
// ein Tool-Aufruf ändert nur einen Code, kein "letzter Schreiber gewinnt" über die ganze Liste.
|
||||
|
||||
[Description("Ordnet einer Einzelstunde eine Kompetenz aus dem Katalog zu (siehe get_competency_catalog). Muss der Nutzer erst bestätigen.")]
|
||||
public async Task<WriteResultDto> AddLessonCompetency(
|
||||
[Description("ID der Einzelstunde.")] Guid lessonId,
|
||||
[Description("ID der Einzelkompetenz, aus get_competency_catalog.")] Guid itemId,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var lesson = lessons.GetById(lessonId);
|
||||
if (lesson is null) return new WriteResultDto(false, null, "Unbekannte Stunden-ID.");
|
||||
var item = FindCompetencyItem(itemId);
|
||||
if (item is null) return new WriteResultDto(false, null, "Unbekannte Kompetenz-ID.");
|
||||
if (lesson.Competencies.Any(c => c.ItemId == itemId))
|
||||
return new WriteResultDto(true, lesson.Id, "Kompetenz ist bereits zugeordnet.");
|
||||
|
||||
var message = $"Kompetenz „{item.Code}“ zu „{lesson.Topic}“ am {lesson.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.");
|
||||
|
||||
lesson.Competencies.Add(new CompetencyReference { ItemId = item.Id, Code = item.Code, Description = item.Description });
|
||||
lessons.Save(lesson);
|
||||
return new WriteResultDto(true, lesson.Id, "Kompetenz zugeordnet.");
|
||||
}
|
||||
|
||||
[Description("Entfernt eine Kompetenz von einer Einzelstunde. Muss der Nutzer erst bestätigen.")]
|
||||
public async Task<WriteResultDto> RemoveLessonCompetency(
|
||||
[Description("ID der Einzelstunde.")] Guid lessonId,
|
||||
[Description("ID der Einzelkompetenz, wie in get_lesson_plans hinterlegt.")] Guid itemId,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var lesson = lessons.GetById(lessonId);
|
||||
if (lesson is null) return new WriteResultDto(false, null, "Unbekannte Stunden-ID.");
|
||||
var existing = lesson.Competencies.FirstOrDefault(c => c.ItemId == itemId);
|
||||
if (existing is null) return new WriteResultDto(false, null, "Diese Kompetenz ist dieser Stunde nicht zugeordnet.");
|
||||
|
||||
var message = $"Kompetenz „{existing.Code}“ von „{lesson.Topic}“ am {lesson.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.");
|
||||
|
||||
lesson.Competencies.Remove(existing);
|
||||
lessons.Save(lesson);
|
||||
return new WriteResultDto(true, lesson.Id, "Kompetenz entfernt.");
|
||||
}
|
||||
|
||||
private CompetencyItem? FindCompetencyItem(Guid itemId) =>
|
||||
competencyDomains.GetAll().SelectMany(d => d.Items).FirstOrDefault(i => i.Id == itemId);
|
||||
|
||||
// ── Einzelstunden (Lesson) — Verschieben & Löschen ───────────────────────────────────────
|
||||
|
||||
[Description("Verschiebt eine Einzelstunde auf ein neues Datum (und optional eine neue Stundennummer). Mit shiftFollowingLessons=true verschieben sich alle noch nicht durchgeführten, späteren Stunden derselben Einheit um denselben Tages-Versatz mit — so lässt sich eine Lücke für eine neue Stunde öffnen: diese Stunde auf den Termin der übernächsten verschieben (mit shiftFollowingLessons), dann create_lesson auf das dadurch freigewordene ursprüngliche Datum. Muss der Nutzer erst bestätigen.")]
|
||||
public async Task<WriteResultDto> MoveLesson(
|
||||
[Description("ID der zu verschiebenden Einzelstunde.")] Guid lessonId,
|
||||
[Description("Neues Datum, Format YYYY-MM-DD.")] DateOnly newDate,
|
||||
[Description("Neue Stundennummer im Tagesraster. Unverändert lassen: weglassen.")] int? newPeriod = null,
|
||||
[Description("Alle späteren, noch nicht durchgeführten Stunden derselben Einheit um denselben Tages-Versatz mitverschieben.")] bool shiftFollowingLessons = false,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var lesson = lessons.GetById(lessonId);
|
||||
if (lesson is null) return new WriteResultDto(false, null, "Unbekannte Stunden-ID.");
|
||||
|
||||
var oldDate = lesson.Date;
|
||||
// Muss exakt dieselbe Schutzbedingung wie LessonSchedulingService.Move verwenden, sonst
|
||||
// weicht die Vorschau-Zahl im Bestätigungstext von dem ab, was tatsächlich verschoben wird.
|
||||
var affectedCount = shiftFollowingLessons
|
||||
? lessons.GetByUnit(lesson.UnitId).Count(l =>
|
||||
l.Id != lesson.Id && l.Status is not (LessonStatus.Conducted or LessonStatus.Cancelled) && l.Date > oldDate)
|
||||
: 0;
|
||||
|
||||
var message = $"„{lesson.Topic}“ von {oldDate:dd.MM.yyyy} auf {newDate:dd.MM.yyyy} verschieben?" +
|
||||
(newPeriod is not null ? $"\nNeue Stundennummer: {newPeriod}." : "") +
|
||||
(shiftFollowingLessons
|
||||
? affectedCount > 0
|
||||
? $"\n{affectedCount} spätere Stunde(n) derselben Einheit verschieben sich um denselben Versatz mit."
|
||||
: "\nKeine späteren, noch offenen Stunden derselben Einheit betroffen."
|
||||
: "");
|
||||
|
||||
if (!await confirmation.ConfirmAsync("Stunde verschieben?", message, ct))
|
||||
return new WriteResultDto(false, null, "Vom Nutzer abgelehnt oder nicht bestätigt.");
|
||||
|
||||
try
|
||||
{
|
||||
new LessonSchedulingService(lessons).Move(lesson, newDate, newPeriod, shiftFollowingLessons);
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
return new WriteResultDto(false, null, ex.Message);
|
||||
}
|
||||
return new WriteResultDto(true, lesson.Id, "Stunde verschoben.");
|
||||
}
|
||||
|
||||
[Description("Löscht eine Einzelstunde endgültig, inklusive ihrer Anhänge. Anders als die meisten anderen Löschvorgänge in LehrerApp landet eine gelöschte Stunde NICHT im Papierkorb — nicht rückgängig zu machen. Für eine Stunde, die nur ausgefallen ist (Exkursion, Feiertag, Vertretung ohne Ersatztermin) aber als Ereignis dokumentiert bleiben soll, ist update_lesson mit status=Cancelled meist die bessere Wahl. Muss der Nutzer erst bestätigen.")]
|
||||
public async Task<WriteResultDto> DeleteLesson(
|
||||
[Description("ID der zu löschenden Einzelstunde.")] Guid lessonId,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var lesson = lessons.GetById(lessonId);
|
||||
if (lesson is null) return new WriteResultDto(false, null, "Unbekannte Stunden-ID.");
|
||||
|
||||
var message = $"Die Stunde „{lesson.Topic}“ vom {lesson.Date:dd.MM.yyyy} wird endgültig gelöscht. " +
|
||||
"Das kann NICHT rückgängig gemacht werden (kein Papierkorb für Stunden).";
|
||||
if (!await confirmation.ConfirmAsync("Stunde endgültig löschen?", message, ct))
|
||||
return new WriteResultDto(false, null, "Vom Nutzer abgelehnt oder nicht bestätigt.");
|
||||
|
||||
lessons.Delete(lessonId);
|
||||
return new WriteResultDto(true, lessonId, "Stunde gelöscht.");
|
||||
}
|
||||
|
||||
private static LessonDto ToDto(Lesson l) => new(
|
||||
l.Id, l.UnitId, l.GroupId, l.Date, l.LessonNumber, l.Topic, l.Homework, l.PlanningIdeas, l.Status, ToDto(l.Competencies),
|
||||
l.Phases.Select(p => new LessonPhaseDto(p.Id, p.Name, p.DurationMinutes, p.Activity, p.Material, p.Shorthand, p.MaterialPrompt)).ToList(),
|
||||
l.Attachments.Select(a => new LessonAttachmentDto(a.StorageId, a.FileName, a.SizeBytes)).ToList());
|
||||
|
||||
private static List<CompetencyReferenceDto> ToDto(List<CompetencyReference> competencies) =>
|
||||
competencies.Select(c => new CompetencyReferenceDto(c.ItemId, c.Code, c.Description)).ToList();
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
using System.ComponentModel;
|
||||
using System.Globalization;
|
||||
using LehrerApp.Core.Interfaces;
|
||||
using LehrerApp.Desktop.Services;
|
||||
using LehrerApp.Templating;
|
||||
|
||||
namespace LehrerApp.Desktop.Services.Mcp.Tools;
|
||||
|
||||
/// <summary>MCP-Tools "list_letter_templates"/"render_letter" (siehe Planungsdokument, Abschnitt
|
||||
/// "Worksheets"). Die ursprüngliche Spec sah "Arbeitsblätter" mit Fach-/Klassenstufe-Metadaten vor —
|
||||
/// das existiert im Datenmodell nicht. Was tatsächlich existiert: importierte
|
||||
/// <c>.lavorlage</c>-Elternbrief-Vorlagen (<see cref="TemplateStore"/>), an Schüler+Kontakt
|
||||
/// gebunden, exakt wie im bestehenden "Elternbrief"-Dialog
|
||||
/// (<c>CreateLetterDialogViewModel</c>). Bewusst NICHT umgesetzt: "upload_worksheet"/
|
||||
/// "update_worksheet" im Sinne von "eine neue Vorlage per KI entwerfen" — das Seitenlayout ist eine
|
||||
/// eigene, positionsbasierte DSL (siehe LehrerApp.Templating/LayoutParser.cs), für die es absichtlich
|
||||
/// einen eigenen visuellen Editor (LehrerApp.TemplateDesigner) gibt; ein LLM würde diese DSL blind
|
||||
/// erzeugen müssen, mit hohem Risiko für unbrauchbare/kaputte Layouts. "render_letter" deckt den
|
||||
/// tatsächlich nützlichen Fall ab: eine bestehende, vom Nutzer gestaltete Vorlage mit Werten füllen.</summary>
|
||||
public class LetterTemplateTools(
|
||||
TemplateStore templates, ITemplateLoader loader, ITemplateRenderer renderer,
|
||||
IStudentRepository students, IGroupRepository groups,
|
||||
StudentAttendanceCalendarService? attendanceCalendars = null)
|
||||
{
|
||||
[Description("Listet importierte Elternbrief-Vorlagen mit ihren deklarierten Platzhaltern (Name, Typ, Pflichtfeld, konstant).")]
|
||||
public List<LetterTemplateDto> ListLetterTemplates()
|
||||
{
|
||||
var result = new List<LetterTemplateDto>();
|
||||
foreach (var installed in templates.GetTemplates())
|
||||
{
|
||||
try
|
||||
{
|
||||
var loaded = templates.Load(installed);
|
||||
result.Add(new LetterTemplateDto(installed.Id, installed.Name, installed.Description,
|
||||
loaded.Manifest.Placeholders
|
||||
.Select(p => new PlaceholderInfoDto(p.Name, p.Type.ToString(), p.Required, p.IsConstant))
|
||||
.ToList()));
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or InvalidDataException or TemplateValidationException)
|
||||
{
|
||||
// Beschädigtes/ungültiges Paket - wie TemplateStore.GetTemplates() selbst überspringt
|
||||
// auch diese Auflistung es kommentarlos, statt die ganze Liste scheitern zu lassen.
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
[Description("Erzeugt einen Elternbrief aus einer importierten Vorlage für einen Schüler und liefert ihn als Base64-PDF. Reiner Lesezugriff (kein Datenbank-Schreibzugriff), deshalb ohne Bestätigungsdialog.")]
|
||||
public LetterRenderResultDto RenderLetter(
|
||||
[Description("Vorlagen-ID, aus list_letter_templates.")] string templateId,
|
||||
[Description("Schüler-ID.")] Guid studentId,
|
||||
[Description("Brieftext (Fließtext).")] string letterText,
|
||||
[Description("Name der unterschreibenden Lehrkraft.")] string teacherName,
|
||||
[Description("Optionale Kontakt-ID des Schülers. Ohne Angabe wird der erste gültige Kontakt verwendet.")] Guid? contactId = null,
|
||||
[Description("Optionale Lerngruppen-ID für Group.Name/SchoolYear-Platzhalter.")] Guid? groupId = null,
|
||||
[Description("Briefdatum, Format YYYY-MM-DD. Standard: heute.")] DateOnly? letterDate = null,
|
||||
[Description("Zusätzliche, von der Vorlage deklarierte Platzhalterwerte über die Standardfelder hinaus (Name -> Text/Zahl/Datum als Text).")]
|
||||
Dictionary<string, string>? extraValues = null)
|
||||
{
|
||||
var student = students.GetById(studentId);
|
||||
if (student is null) return new LetterRenderResultDto(false, "Unbekannte Schüler-ID.", null, null);
|
||||
|
||||
var installed = templates.GetTemplates().FirstOrDefault(t => t.Id == templateId);
|
||||
if (installed is null) return new LetterRenderResultDto(false, "Unbekannte Vorlagen-ID.", null, null);
|
||||
|
||||
LoadedTemplate loaded;
|
||||
try { loaded = templates.Load(installed); }
|
||||
catch (Exception ex) when (ex is IOException or InvalidDataException or TemplateValidationException)
|
||||
{ return new LetterRenderResultDto(false, $"Vorlage ist ungültig: {ex.Message}", null, null); }
|
||||
|
||||
var contact = contactId is { } cid
|
||||
? student.Contacts.FirstOrDefault(c => c.Id == cid)
|
||||
: student.Contacts.FirstOrDefault(c => !c.InvalidSince.HasValue);
|
||||
var group = groupId is { } gid ? groups.GetById(gid) : null;
|
||||
var date = letterDate ?? DateOnly.FromDateTime(DateTime.Today);
|
||||
|
||||
var calendarBox = LetterPlaceholderBuilder.FindDeclaredDrawingBox(loaded,
|
||||
StudentAttendanceCalendarDrawingBuilder.PlaceholderName) ?? new(170, float.PositiveInfinity, 1, false);
|
||||
var absenceDayListBox = LetterPlaceholderBuilder.FindDeclaredDrawingBox(loaded,
|
||||
StudentAbsenceDayListDrawingBuilder.PlaceholderName) ?? new(170, float.PositiveInfinity, 1, false);
|
||||
var values = LetterPlaceholderBuilder.BuildStandardValues(student, contact, group, date, letterText,
|
||||
teacherName, attendanceCalendars?.Build(student, new AttendanceCalendarOptions(date, 1),
|
||||
calendarBox.Width, calendarBox.MillimeterScale,
|
||||
calendarBox.IsFixed ? calendarBox.Height : float.PositiveInfinity),
|
||||
attendanceCalendars?.BuildAbsenceDayList(student, new AttendanceCalendarOptions(date, 1),
|
||||
absenceDayListBox.Width, absenceDayListBox.MillimeterScale));
|
||||
foreach (var (name, raw) in extraValues ?? [])
|
||||
{
|
||||
var definition = loaded.Manifest.Placeholders.FirstOrDefault(p => p.Name == name);
|
||||
if (definition is null || definition.IsConstant) continue;
|
||||
if (TryConvert(definition.Type, raw) is { } converted) values[name] = converted;
|
||||
}
|
||||
var resolved = TemplateDataResolver.Resolve(loaded.Manifest, values);
|
||||
|
||||
var validation = loader.Validate(loaded, resolved.ToDictionary(x => x.Key, x => x.Value.Type));
|
||||
var missing = loaded.Manifest.Placeholders
|
||||
.Where(p => !p.IsConstant && p.Required &&
|
||||
(!resolved.TryGetValue(p.Name, out var v) || LetterPlaceholderBuilder.IsEmpty(v)))
|
||||
.Select(p => p.Name).ToList();
|
||||
if (!validation.IsValid || missing.Count > 0)
|
||||
{
|
||||
var issues = validation.Issues.Select(i => i.Message)
|
||||
.Concat(missing.Select(m => $"Pflichtfeld „{m}“ fehlt."));
|
||||
return new LetterRenderResultDto(false,
|
||||
"Vorlage kann mit diesen Werten nicht gefüllt werden: " + string.Join(" ", issues), null, null);
|
||||
}
|
||||
|
||||
byte[] pdf;
|
||||
try { pdf = renderer.RenderToPdf(loaded, new DictionaryDataProvider(resolved)); }
|
||||
catch (Exception ex) when (ex is InvalidDataException or TemplateValidationException)
|
||||
{ return new LetterRenderResultDto(false, $"Brief konnte nicht erzeugt werden: {ex.Message}", null, null); }
|
||||
|
||||
var fileName = SanitizeFileName($"{installed.Name}_{student.LastName}_{student.FirstName}.pdf");
|
||||
return new LetterRenderResultDto(true, "Brief erzeugt.", Convert.ToBase64String(pdf), fileName);
|
||||
}
|
||||
|
||||
private static PlaceholderValue? TryConvert(PlaceholderType type, string raw) => type switch
|
||||
{
|
||||
PlaceholderType.Text => new TextValue(raw),
|
||||
PlaceholderType.Multiline => new MultilineValue(raw),
|
||||
PlaceholderType.Date => TryParseDate(raw) is { } date ? new DateValue(date) : null,
|
||||
PlaceholderType.Number => TryParseNumber(raw) is { } number ? new NumberValue(number) : null,
|
||||
// Image/Table/Chart/Drawing sind über MCP-Textparameter nicht sinnvoll setzbar.
|
||||
_ => null,
|
||||
};
|
||||
|
||||
private static DateOnly? TryParseDate(string raw) =>
|
||||
DateOnly.TryParse(raw, CultureInfo.InvariantCulture, DateTimeStyles.None, out var d) ||
|
||||
DateOnly.TryParse(raw, CultureInfo.GetCultureInfo("de-DE"), DateTimeStyles.None, out d) ? d : null;
|
||||
|
||||
private static decimal? TryParseNumber(string raw) =>
|
||||
decimal.TryParse(raw, NumberStyles.Number, CultureInfo.InvariantCulture, out var n) ||
|
||||
decimal.TryParse(raw, NumberStyles.Number, CultureInfo.GetCultureInfo("de-DE"), out n) ? n : null;
|
||||
|
||||
private static string SanitizeFileName(string value)
|
||||
{
|
||||
foreach (var character in Path.GetInvalidFileNameChars()) value = value.Replace(character, '_');
|
||||
return value;
|
||||
}
|
||||
|
||||
private sealed class DictionaryDataProvider(IReadOnlyDictionary<string, PlaceholderValue> values) : ITemplateDataProvider
|
||||
{
|
||||
public IReadOnlyDictionary<string, PlaceholderValue> GetValues() => values;
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using System.ComponentModel;
|
||||
using LehrerApp.Core.Interfaces;
|
||||
|
||||
namespace LehrerApp.Desktop.Services.Mcp.Tools;
|
||||
|
||||
/// <summary>MCP-Read-Tool "get_schedule" (Phase 1, siehe Planungsdokument).</summary>
|
||||
public class ScheduleTools(ITimetableSlotRepository slots)
|
||||
{
|
||||
[Description("Listet Stundenplan-Einträge (Wochenraster), optional gefiltert nach Lerngruppe.")]
|
||||
public List<TimetableSlotDto> GetSchedule(
|
||||
[Description("Optionale Lerngruppen-ID zum Filtern.")] Guid? groupId = null)
|
||||
{
|
||||
var list = groupId is { } id ? slots.GetByGroup(id) : slots.GetAll();
|
||||
return list.Select(s => new TimetableSlotDto(s.Id, s.GroupId, s.Weekday, s.PeriodNumber, s.Room)).ToList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using System.ComponentModel;
|
||||
using LehrerApp.Core.Interfaces;
|
||||
|
||||
namespace LehrerApp.Desktop.Services.Mcp.Tools;
|
||||
|
||||
/// <summary>MCP-Read-Tool "get_students" (Phase 1, siehe Planungsdokument). Reine Lesezugriffe auf
|
||||
/// die bestehenden Repositories, keine eigene Datenzugriffslogik.</summary>
|
||||
public class StudentTools(IStudentRepository students)
|
||||
{
|
||||
[Description("Listet Schüler, optional gefiltert nach Lerngruppe. Enthält standardmäßig nur aktive Schüler.")]
|
||||
public List<StudentDto> GetStudents(
|
||||
[Description("Optionale Lerngruppen-ID zum Filtern.")] Guid? groupId = null,
|
||||
[Description("Auch inaktive/ausgeschiedene Schüler einbeziehen.")] bool includeInactive = false)
|
||||
{
|
||||
var list = groupId is { } id ? students.GetByGroup(id) : students.GetAll(includeInactive);
|
||||
if (groupId is not null && !includeInactive)
|
||||
list = list.Where(s => s.IsActive).ToList();
|
||||
return list.Select(s => new StudentDto(s.Id, s.FirstName, s.LastName, s.IsActive)).ToList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using System.ComponentModel;
|
||||
using LehrerApp.Core.Interfaces;
|
||||
using LehrerApp.Core.Models;
|
||||
|
||||
namespace LehrerApp.Desktop.Services.Mcp.Tools;
|
||||
|
||||
/// <summary>MCP-Tools "get_time_entries" (Phase 1) und "create_time_entry" (Phase 2), siehe
|
||||
/// Planungsdokument. Der Zeitraum bei "get_time_entries" ist Pflicht (nicht optional), damit eine
|
||||
/// unbedachte Anfrage nicht die gesamte Zeiterfassungshistorie zurückgibt.</summary>
|
||||
public class TimeEntryTools(ITimeEntryRepository timeEntries, IGroupRepository groups, IMcpConfirmationService confirmation)
|
||||
{
|
||||
[Description("Listet eigene Zeiterfassungs-Einträge in einem Datumsbereich.")]
|
||||
public List<TimeEntryDto> GetTimeEntries(
|
||||
[Description("Startdatum (einschließlich), Format YYYY-MM-DD.")] DateOnly from,
|
||||
[Description("Enddatum (einschließlich), Format YYYY-MM-DD.")] DateOnly to) =>
|
||||
timeEntries.GetByDateRange(from, to).Select(t => new TimeEntryDto(
|
||||
t.Id, t.TaskId, t.Category, t.GroupId, t.Date, t.StartTime, t.EndTime,
|
||||
t.DurationMinutes, t.Description)).ToList();
|
||||
|
||||
[Description("Schlägt einen neuen Zeiterfassungs-Eintrag vor. Muss der Nutzer erst in einem Dialog in LehrerApp bestätigen, bevor er gespeichert wird.")]
|
||||
public async Task<WriteResultDto> CreateTimeEntry(
|
||||
[Description("Kategorie, z.B. \"Unterricht\", \"Korrektur\", \"Vorbereitung\".")] string category,
|
||||
[Description("Datum, Format YYYY-MM-DD.")] DateOnly date,
|
||||
[Description("Dauer in Minuten.")] int durationMinutes,
|
||||
[Description("Optionale Lerngruppen-ID.")] Guid? groupId = null,
|
||||
[Description("Optionale Beschreibung.")] string? description = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var groupName = groupId is { } gid ? groups.GetById(gid)?.Name : null;
|
||||
var message =
|
||||
$"Neuer Zeiteintrag: {category}, {durationMinutes} Min. am {date:dd.MM.yyyy}" +
|
||||
(groupName is not null ? $", Gruppe {groupName}" : "") +
|
||||
(string.IsNullOrWhiteSpace(description) ? "" : $"\n„{description}“");
|
||||
|
||||
if (!await confirmation.ConfirmAsync("Zeiteintrag anlegen?", message, ct))
|
||||
return new WriteResultDto(false, null, "Vom Nutzer abgelehnt oder nicht bestätigt.");
|
||||
|
||||
var entry = new TimeEntry
|
||||
{
|
||||
Category = category,
|
||||
Date = date,
|
||||
DurationMinutes = durationMinutes,
|
||||
GroupId = groupId,
|
||||
Description = description,
|
||||
};
|
||||
timeEntries.Save(entry);
|
||||
return new WriteResultDto(true, entry.Id, "Zeiteintrag gespeichert.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.ComponentModel;
|
||||
using LehrerApp.Core.Interfaces;
|
||||
using LehrerApp.Core.Models;
|
||||
|
||||
namespace LehrerApp.Desktop.Services.Mcp.Tools;
|
||||
|
||||
/// <summary>
|
||||
/// MCP-Tools für die WebUntis-Abgleiche (Nutzer-Nachtrag zum Untis-Hub, siehe TODO.md), zweigleisig
|
||||
/// wie vom Nutzer entschieden:
|
||||
///
|
||||
/// - <see cref="GetUntisAbsenceRows"/>/<see cref="ApplyUntisAbsenceStatus"/> (bevorzugter Weg): eine
|
||||
/// rein technische <c>row-id</c> ordnet zurück, nie ein Schülername - nur Zeilen, die WebUntis
|
||||
/// selbst eindeutig über die externe Schülernummer (ENr) einem Kursmitglied zuordnet, werden
|
||||
/// überhaupt gelistet (unklare, nur namensbasiert auflösbare Fälle fließen bewusst NICHT hier
|
||||
/// hinein, siehe <see cref="GetUntisAbsenceRows"/>).
|
||||
/// - <see cref="GetNamedUntisAbsencePattern"/> (bewusste, eng begrenzte Ausnahme von der sonst in
|
||||
/// <see cref="McpToolScope"/> geltenden Regel, dass personenbezogene Verhaltens-/Anwesenheitsdaten
|
||||
/// nie mit einem Namen verknüpft nach außen gehen): exponiert Name UND Fehlzeiten gemeinsam, aber
|
||||
/// nur für explizit angegebene Schüler-IDs und nur nach JEDES MAL gesonderter, prominenter
|
||||
/// Bestätigung ohne Sitzungsfreigabe (<c>allowSessionTrust: false</c>).
|
||||
///
|
||||
/// <see cref="GetUntisHubStatus"/> ergänzt beide Wege um einen Überblick, welche Abgleiche laut
|
||||
/// <see cref="UntisHubService"/> überhaupt fällig sind, ohne selbst WebUntis anzufragen.
|
||||
/// </summary>
|
||||
public class UntisComparisonTools(
|
||||
IGroupRepository groups, IStudentRepository students, IParticipationSessionRepository sessions,
|
||||
IParticipationRepository participation, WebUntisIntegrationService untis, UntisHubService hub,
|
||||
IMcpConfirmationService confirmation)
|
||||
{
|
||||
// Statuswerte, die ApplyUntisAbsenceStatus akzeptiert - dieselbe Einschränkung wie
|
||||
// WebUntisLessonAbsenceRow.SelectableStatuses im interaktiven Dialog (nicht z.B. "Geschwänzt"
|
||||
// oder "Suspendiert", die WebUntis hier nie meldet). Eigenständig gehalten statt der Row-Klasse
|
||||
// referenziert, da Tool-Klassen unter Services/Mcp nicht von ViewModel-Klassen abhängen sollen
|
||||
// (siehe GradeTools).
|
||||
private static readonly AttendanceStatus[] SelectableStatuses =
|
||||
[
|
||||
AttendanceStatus.ExcusePending, AttendanceStatus.Excused, AttendanceStatus.Unexcused,
|
||||
AttendanceStatus.Late, AttendanceStatus.LeftDuringClass, AttendanceStatus.Present,
|
||||
];
|
||||
|
||||
// In-Memory, pro Prozesslaufzeit - eine row-id aus GetUntisAbsenceRows ist nur bis zum nächsten
|
||||
// Neustart von LehrerApp gültig; danach muss der KI-Client die Liste erneut abrufen. Bewusst
|
||||
// keine Ablauf-/Größenbegrenzung (siehe Nutzerdiskussion: geringe Nutzungsfrequenz, winzige
|
||||
// Einträge) - ein v1-Kompromiss, kein Deployment-Risiko wie bei den ai-backend-Endpunkten.
|
||||
private readonly ConcurrentDictionary<string, PendingAbsenceRow> _pendingRows = new();
|
||||
|
||||
private sealed record PendingAbsenceRow(Guid StudentId, Guid SessionId, Guid GroupId, DateOnly Date);
|
||||
|
||||
[Description("Listet die Fälligkeit der Untis-Hub-Abgleiche (Fehlzeiten je Lerngruppe, offene Stunden, Klassenbuch-/Hausaufgabenabgleich) - reine Lesefunktion aus der lokalen Fälligkeits-Historie, kein eigener WebUntis-Zugriff.")]
|
||||
public List<UntisHubStatusRowDto> GetUntisHubStatus() =>
|
||||
hub.GetRows().Select(r => new UntisHubStatusRowDto(
|
||||
r.Kind.ToString(), r.GroupId, r.GroupName, r.DueState.ToString(), r.DueLabel,
|
||||
r.LastRunAt, r.LastResultSummary)).ToList();
|
||||
|
||||
[Description("""
|
||||
Listet Fehlzeiten-Diskrepanzen einer Lerngruppe gegenüber WebUntis in einem Zeitraum, ANONYMISIERT:
|
||||
enthält keinen Schülernamen, nur eine technische row-id je Zeile (für apply_untis_absence_status).
|
||||
Enthält nur Zeilen, die WebUntis über die externe Schülernummer eindeutig einem Kursmitglied zuordnen
|
||||
konnte - Zeilen, die nur über den Namen auflösbar wären, fehlen hier bewusst; für die braucht es
|
||||
get_named_untis_absence_pattern (Namen exponierend, gesondert bestätigungspflichtig).
|
||||
""")]
|
||||
public async Task<List<UntisAbsenceRowDto>> GetUntisAbsenceRows(
|
||||
[Description("Lerngruppen-ID.")] Guid groupId,
|
||||
[Description("Startdatum, Format YYYY-MM-DD.")] DateOnly startDate,
|
||||
[Description("Enddatum, Format YYYY-MM-DD.")] DateOnly endDate,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var group = groups.GetById(groupId);
|
||||
if (group?.WebUntisLessonId is not { } lessonId) return [];
|
||||
|
||||
var courseStudents = students.GetByGroup(groupId);
|
||||
var byExternKey = courseStudents
|
||||
.Select(s => (Student: s, Key: UntisLessonAbsenceHelper.StudentExternKey(s)))
|
||||
.Where(x => x.Key is not null)
|
||||
.ToDictionary(x => x.Key!.Value, x => x.Student);
|
||||
var localSessions = sessions.GetByGroup(groupId)
|
||||
.Where(s => s.Date >= startDate && s.Date <= endDate)
|
||||
.GroupBy(s => s.Date).ToDictionary(g => g.Key, g => g.First());
|
||||
|
||||
var absences = await untis.GetLessonAbsencesAsync(lessonId, startDate, endDate, ct);
|
||||
var rows = new List<UntisAbsenceRowDto>();
|
||||
foreach (var absence in absences)
|
||||
{
|
||||
if (absence.ExternKey is not { } key || !byExternKey.TryGetValue(key, out var student)) continue;
|
||||
if (!TryParseDate(absence.Date, out var date) || !localSessions.TryGetValue(date, out var session)) continue;
|
||||
|
||||
var rowId = Guid.NewGuid().ToString("N");
|
||||
_pendingRows[rowId] = new PendingAbsenceRow(student.Id, session.Id, groupId, date);
|
||||
|
||||
var entry = participation.GetBySessionAndStudent(session.Id, student.Id);
|
||||
var guess = UntisLessonAbsenceHelper.MapStatus(absence);
|
||||
rows.Add(new UntisAbsenceRowDto(
|
||||
rowId, date, absence.Reason ?? "", absence.AbsentMinutes,
|
||||
!string.IsNullOrWhiteSpace(absence.HandledOn),
|
||||
absence.ExternKey is null ? null : absence.ExternKeyInParentheses,
|
||||
LocalStatusLabel(entry?.Attendance), guess.ToString()));
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
[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(
|
||||
[Description("row-id aus get_untis_absence_rows.")] string rowId,
|
||||
[Description("Zielstatus: Present, Late, LeftDuringClass, ExcusePending, Excused oder Unexcused.")] string status,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
if (!Enum.TryParse<AttendanceStatus>(status, out var target) || !SelectableStatuses.Contains(target))
|
||||
return new WriteResultDto(false, null, "Unbekannter oder nicht zulässiger Status.");
|
||||
if (!_pendingRows.TryGetValue(rowId, out var row))
|
||||
return new WriteResultDto(false, null, "Unbekannte oder abgelaufene row-id - zuerst get_untis_absence_rows erneut aufrufen.");
|
||||
|
||||
var groupName = groups.GetById(row.GroupId)?.Name ?? "?";
|
||||
var message = $"Fehlzeile vom {row.Date:dd.MM.yyyy} in Lerngruppe „{groupName}“: " +
|
||||
$"Anwesenheitsstatus auf „{LocalStatusLabel(target)}“ setzen?";
|
||||
if (!await confirmation.ConfirmAsync("Fehlzeiten-Status übernehmen?", message, ct))
|
||||
return new WriteResultDto(false, null, "Vom Nutzer abgelehnt oder nicht bestätigt.");
|
||||
|
||||
var entry = participation.GetBySessionAndStudent(row.SessionId, row.StudentId)
|
||||
?? new ParticipationEntry { SessionId = row.SessionId, StudentId = row.StudentId };
|
||||
entry.Attendance = target;
|
||||
entry.UpdatedAt = DateTime.UtcNow;
|
||||
participation.Save(entry);
|
||||
_pendingRows.TryRemove(rowId, out _);
|
||||
return new WriteResultDto(true, entry.Id, "Status übernommen.");
|
||||
}
|
||||
|
||||
[Description("""
|
||||
Liefert Fehlzeiten für EXPLIZIT angegebene Schüler-IDs MIT Namen (z.B. für einen Bericht oder einen
|
||||
Fehlmuster-Vergleich zwischen zwei Schülern) - bewusste, eng begrenzte Ausnahme von der sonst
|
||||
geltenden Anonymisierung (siehe get_untis_absence_rows). So wenige studentIds wie für die Anfrage
|
||||
nötig angeben, nicht den ganzen Kurs. Erfordert JEDES MAL eine gesonderte, prominente
|
||||
Nutzerbestätigung ohne Sitzungsfreigabe - liefert bei Ablehnung granted:false und keine Zeilen.
|
||||
""")]
|
||||
public async Task<NamedUntisAbsenceResultDto> GetNamedUntisAbsencePattern(
|
||||
[Description("Lerngruppen-ID.")] Guid groupId,
|
||||
[Description("Ids der Schüler, für die Name UND Fehlzeiten gemeinsam offengelegt werden sollen.")] List<Guid> studentIds,
|
||||
[Description("Startdatum, Format YYYY-MM-DD.")] DateOnly startDate,
|
||||
[Description("Enddatum, Format YYYY-MM-DD.")] DateOnly endDate,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var group = groups.GetById(groupId);
|
||||
if (group?.WebUntisLessonId is not { } lessonId)
|
||||
return new NamedUntisAbsenceResultDto(false, "Für diese Lerngruppe ist keine WebUntis-Unterrichtsnummer hinterlegt.", null);
|
||||
|
||||
var resolvedStudents = studentIds.Distinct()
|
||||
.Select(students.GetById).Where(s => s is not null).Cast<Student>().ToList();
|
||||
if (resolvedStudents.Count == 0)
|
||||
return new NamedUntisAbsenceResultDto(false, "Keine der angegebenen Schüler-IDs ist bekannt.", null);
|
||||
|
||||
var names = string.Join(", ", resolvedStudents.Select(s => s.FullName));
|
||||
var message = $"Name UND Fehlzeiten gemeinsam an den KI-Assistenten weitergeben für:\n{names}\n\n" +
|
||||
$"Zeitraum: {startDate:dd.MM.yyyy}–{endDate:dd.MM.yyyy}, Lerngruppe „{group.Name}“.";
|
||||
if (!await confirmation.ConfirmAsync("Namentliche Fehlzeitenauskunft freigeben?", message, ct, allowSessionTrust: false))
|
||||
return new NamedUntisAbsenceResultDto(false, "Vom Nutzer abgelehnt oder nicht bestätigt.", null);
|
||||
|
||||
var byExternKey = resolvedStudents
|
||||
.Select(s => (Student: s, Key: UntisLessonAbsenceHelper.StudentExternKey(s)))
|
||||
.Where(x => x.Key is not null)
|
||||
.ToDictionary(x => x.Key!.Value, x => x.Student);
|
||||
var byName = resolvedStudents
|
||||
.SelectMany(s => new[]
|
||||
{
|
||||
NameKey($"{s.LastName} {s.FirstName}"), NameKey($"{s.FirstName} {s.LastName}"),
|
||||
}.Select(key => (Key: key, Student: s)))
|
||||
.GroupBy(x => x.Key).Where(g => g.Select(x => x.Student).Distinct().Count() == 1)
|
||||
.ToDictionary(g => g.Key, g => g.First().Student);
|
||||
var localSessions = sessions.GetByGroup(groupId)
|
||||
.Where(s => s.Date >= startDate && s.Date <= endDate)
|
||||
.GroupBy(s => s.Date).ToDictionary(g => g.Key, g => g.First());
|
||||
|
||||
var absences = await untis.GetLessonAbsencesAsync(lessonId, startDate, endDate, ct);
|
||||
var rows = new List<NamedUntisAbsenceRowDto>();
|
||||
foreach (var absence in absences)
|
||||
{
|
||||
var match = absence.ExternKey is { } key && byExternKey.TryGetValue(key, out var byKeyStudent)
|
||||
? byKeyStudent
|
||||
: byName.GetValueOrDefault(NameKey(absence.StudentName));
|
||||
if (match is null) continue; // nur die explizit freigegebenen Schüler, nie "geraten"
|
||||
if (!TryParseDate(absence.Date, out var date)) continue;
|
||||
|
||||
var entry = localSessions.TryGetValue(date, out var session)
|
||||
? participation.GetBySessionAndStudent(session.Id, match.Id) : null;
|
||||
rows.Add(new NamedUntisAbsenceRowDto(
|
||||
match.Id, match.FullName, date, absence.Reason ?? "",
|
||||
LocalStatusLabel(entry?.Attendance), UntisLessonAbsenceHelper.MapStatus(absence).ToString()));
|
||||
}
|
||||
return new NamedUntisAbsenceResultDto(true, $"{rows.Count} Fehlzeile(n) für {resolvedStudents.Count} Schüler.", rows);
|
||||
}
|
||||
|
||||
private static string NameKey(string value) => value.Trim().ToLowerInvariant();
|
||||
private static bool TryParseDate(int value, out DateOnly date) =>
|
||||
DateOnly.TryParseExact(value.ToString(), "yyyyMMdd", out date);
|
||||
|
||||
// Eigene, schlanke Beschriftung statt AttendanceDisplay (Views-/ViewModel-Bezug) - Tool-Klassen
|
||||
// unter Services/Mcp sollen nicht von ViewModel-Klassen abhängen (siehe GradeTools).
|
||||
private static string LocalStatusLabel(AttendanceStatus? s) => s switch
|
||||
{
|
||||
null => "kein Status erfasst",
|
||||
AttendanceStatus.Present => "Anwesend",
|
||||
AttendanceStatus.ExcusePending => "Krank (Entschuldigung offen)",
|
||||
AttendanceStatus.Excused => "Krank, entschuldigt",
|
||||
AttendanceStatus.Unexcused => "Krank, unentschuldigt",
|
||||
AttendanceStatus.Late => "Verspätet",
|
||||
AttendanceStatus.LeftDuringClass => "Während des Unterrichts abgängig",
|
||||
_ => s.ToString()!,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace LehrerApp.Desktop.Services;
|
||||
|
||||
internal class McpSettingsConfig
|
||||
{
|
||||
public bool Enabled { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opt-in-Schalter für den lokalen MCP-Server (siehe Planungsdokument, Phase 1). Anders als
|
||||
/// <see cref="AiSettingsService"/> braucht Phase 1 kein Login/Token — die Named Pipe selbst ist die
|
||||
/// Vertrauensgrenze (lokaler Prozess, gleiche Windows-Session bzw. Unix-Dateirechte), siehe
|
||||
/// Begründung im Planungsdokument.
|
||||
/// </summary>
|
||||
public class McpSettingsService
|
||||
{
|
||||
private readonly string _configPath;
|
||||
private McpSettingsConfig _config;
|
||||
|
||||
public bool Enabled => _config.Enabled;
|
||||
|
||||
public McpSettingsService(string appDataPath)
|
||||
{
|
||||
_configPath = Path.Combine(appDataPath, "mcp-settings.json");
|
||||
_config = Load();
|
||||
}
|
||||
|
||||
public void SetEnabled(bool enabled)
|
||||
{
|
||||
_config.Enabled = enabled;
|
||||
Save();
|
||||
}
|
||||
|
||||
private void Save() => File.WriteAllText(_configPath, JsonSerializer.Serialize(_config));
|
||||
|
||||
private McpSettingsConfig Load()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(_configPath))
|
||||
return JsonSerializer.Deserialize<McpSettingsConfig>(File.ReadAllText(_configPath))
|
||||
?? new McpSettingsConfig();
|
||||
}
|
||||
catch { /* beschädigte Konfiguration -> Standardwert */ }
|
||||
return new McpSettingsConfig();
|
||||
}
|
||||
}
|
||||
@@ -62,9 +62,16 @@ public sealed class PlanningExchangeService(IUnitRepository units, ILessonReposi
|
||||
Title = document.Unit.Title.Trim(),
|
||||
StartDate = document.Unit.StartDate,
|
||||
EndDate = document.Unit.EndDate,
|
||||
// Das Austauschformat überträgt bewusst nie interne DB-IDs ("jeder Import legt neue
|
||||
// Objekte an", siehe Klassenkommentar) - jeder importierte Code wird deshalb als NICHT
|
||||
// aufgelöste Referenz gespeichert (kein Matching gegen den Katalog der Zielinstallation,
|
||||
// das wäre wieder dasselbe fragile Code-Matching, das TODO 16.5 vermeiden soll, nur
|
||||
// installationsübergreifend). Die Tag-UI zeigt sie ehrlich als "Nicht mehr im Katalog";
|
||||
// der Nutzer kann sie bei Bedarf manuell dem echten Katalogeintrag neu zuordnen.
|
||||
Competencies = document.Unit.Competencies
|
||||
.Where(c => !string.IsNullOrWhiteSpace(c)).Select(c => c.Trim())
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase).ToList(),
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.Select(c => new CompetencyReference { ItemId = Guid.Empty, Code = c }).ToList(),
|
||||
Status = document.Unit.Status,
|
||||
Notes = Clean(document.Unit.Notes),
|
||||
};
|
||||
@@ -94,7 +101,7 @@ public sealed class PlanningExchangeService(IUnitRepository units, ILessonReposi
|
||||
Title = unit.Title,
|
||||
StartDate = unit.StartDate,
|
||||
EndDate = unit.EndDate,
|
||||
Competencies = [.. unit.Competencies],
|
||||
Competencies = [.. unit.Competencies.Select(c => c.Code)],
|
||||
Status = unit.Status,
|
||||
Notes = unit.Notes,
|
||||
Lessons = [.. unitLessons.Select(ToPayload)],
|
||||
|
||||
@@ -0,0 +1,374 @@
|
||||
using System.Globalization;
|
||||
using LehrerApp.Core.Interfaces;
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Desktop.ViewModels.ClassTeacher;
|
||||
using LehrerApp.Templating;
|
||||
|
||||
namespace LehrerApp.Desktop.Services;
|
||||
|
||||
public enum AttendanceCalendarSize { Small, Medium, Large }
|
||||
|
||||
public sealed record AttendanceCalendarOptions(DateOnly StartMonth, int MonthCount,
|
||||
AttendanceCalendarSize Size = AttendanceCalendarSize.Medium)
|
||||
{
|
||||
public DateOnly NormalizedStartMonth => new(StartMonth.Year, StartMonth.Month, 1);
|
||||
public int NormalizedMonthCount => Math.Clamp(MonthCount, 1, 3);
|
||||
}
|
||||
|
||||
/// <summary>Erzeugt den portablen Advanced-Content-Platzhalter für Elternbriefe aus derselben
|
||||
/// priorisierten Monatsansicht, die im Klassenlehrer-Sidebar-Widget verwendet wird.</summary>
|
||||
public static class StudentAttendanceCalendarDrawingBuilder
|
||||
{
|
||||
public const string PlaceholderName = "Student.AttendanceCalendar";
|
||||
|
||||
public static DrawingValue Build(string studentName, DateOnly month,
|
||||
IReadOnlyList<ClassAbsenceDaySummaryRow> absences,
|
||||
IReadOnlyList<UntisForeignClassRegisterEventDto> registerEntries) =>
|
||||
Build(studentName, new AttendanceCalendarOptions(month, 1), absences, registerEntries);
|
||||
|
||||
public static DrawingValue Build(string studentName, AttendanceCalendarOptions options,
|
||||
IReadOnlyList<ClassAbsenceDaySummaryRow> absences,
|
||||
IReadOnlyList<UntisForeignClassRegisterEventDto> registerEntries, float contentWidth = 170,
|
||||
float millimeterScale = 1, float contentHeight = float.PositiveInfinity)
|
||||
{
|
||||
var requestedScale = options.Size switch
|
||||
{
|
||||
AttendanceCalendarSize.Small => .7f,
|
||||
AttendanceCalendarSize.Large => 1f,
|
||||
_ => .85f,
|
||||
};
|
||||
// contentWidth/contentHeight/millimeterScale kommen aus der tatsächlichen DRAWBOX/
|
||||
// FLOWDRAWBOX-Deklaration der jeweiligen Vorlage (siehe
|
||||
// LetterPlaceholderBuilder.FindDeclaredDrawingBox). Das gesamte Raster wird in einem festen
|
||||
// Millimeter-Referenzentwurf (designWidth 170mm) gezeichnet und dann mit EINEM einzigen,
|
||||
// gemeinsamen Faktor "k" in die Koordinaten-Einheit der Vorlage skaliert - k ist bewusst für
|
||||
// X- und Y-Richtung identisch (kein separates a_x/a_y), sonst verzerren die Tageskacheln je
|
||||
// nachdem, ob Breite oder Höhe der realen Box stärker vom Referenzentwurf abweicht.
|
||||
var designWidth = 170f;
|
||||
var designMonthGapX = 6f;
|
||||
// Eigener (kleinerer) Y-Abstand vor der Legende, getrennt von designMonthGapX (das misst den
|
||||
// horizontalen Abstand zwischen den Monatsblöcken und soll davon unberührt bleiben).
|
||||
var designTrailingGapY = 2f;
|
||||
var first = options.NormalizedStartMonth;
|
||||
var monthCount = options.NormalizedMonthCount;
|
||||
|
||||
// Wochenanzahl je Monat vorab ermitteln, unabhängig von "Größe" - nötig, um VOR dem
|
||||
// eigentlichen Zeichnen zu wissen, wie viel Höhe das Raster im Referenzentwurf braucht.
|
||||
var maxWeeks = 0;
|
||||
for (var monthIndex = 0; monthIndex < monthCount; monthIndex++)
|
||||
{
|
||||
var current = first.AddMonths(monthIndex);
|
||||
var days = ClassTeacherOverviewViewModel.BuildCompactMonthDays(current, absences, registerEntries,
|
||||
DateOnly.FromDateTime(DateTime.Today), studentName);
|
||||
var offset = ((int)current.DayOfWeek + 6) % 7;
|
||||
maxWeeks = Math.Max(maxWeeks, (int)Math.Ceiling((offset + days.Count) / 7d));
|
||||
}
|
||||
// Höhe des Referenzentwurfs bei k=1 (mm): Name+Abstand (5.5, siehe unten - keine eigene
|
||||
// "Anwesenheit"-Überschrift mehr, die Monatsnamen darunter machen bereits klar, worum es
|
||||
// geht; der Name bleibt klein/grau nur zur Kontrolle "ist das das richtige Kind") + Monats-/
|
||||
// Wochentagskopf (20) + maxWeeks Wochenzeilen (10 je Woche) + Trailing-Gap (2) + Legende/
|
||||
// Nachlauf (9). Muss mit der Höhenberechnung am Ende dieser Methode ("y") übereinstimmen. Je
|
||||
// kleiner dieser "Overhead" ausfällt, desto größer kann k (und damit das ganze Raster inkl.
|
||||
// der Tageskacheln) werden, wenn contentHeight der begrenzende Faktor ist.
|
||||
var designHeight = 5.5f + 20f + 10f * maxWeeks + designTrailingGapY + 9f;
|
||||
|
||||
// a_x/a_y: wie viel größer/kleiner als der Referenzentwurf die reale Box in jeweils einer
|
||||
// Richtung ist. Eine DRAWBOX bricht anders als FLOWDRAWBOX nicht automatisch auf Folgeseiten
|
||||
// um (siehe DrawingElementRenderer.RenderFixed/Slice) - Inhalt, der contentHeight
|
||||
// überschreitet, wird von QuestTemplateRenderer am unteren Rand stillschweigend
|
||||
// abgeschnitten. a = min(a_x, a_y, "Größe") verkleinert nötigenfalls gleichmäßig, statt die
|
||||
// Boxgrenzen zu verletzen oder die Kacheln durch getrenntes Skalieren zu verzerren.
|
||||
var scaleForWidth = contentWidth / (designWidth * millimeterScale);
|
||||
var scaleForHeight = float.IsFinite(contentHeight)
|
||||
? contentHeight / (designHeight * millimeterScale)
|
||||
: float.PositiveInfinity;
|
||||
var finalScale = Math.Max(.35f, Math.Min(requestedScale, Math.Min(scaleForWidth, scaleForHeight)));
|
||||
var k = finalScale * millimeterScale;
|
||||
|
||||
var cellHeight = 10 * k;
|
||||
// War 10mm im Referenzentwurf - bei 3 Monaten nebeneinander größer als eine einzelne
|
||||
// Tageskachel und zog damit spürbar Platz von den Kacheln ab, ohne selbst als Inhalt
|
||||
// wahrgenommen zu werden.
|
||||
var monthGapX = designMonthGapX * k;
|
||||
var monthWidth = (designWidth * k - monthGapX * (monthCount - 1)) / monthCount;
|
||||
var cellWidth = monthWidth / 7;
|
||||
// Kachel-Zwischenraum (Trennung zu Nachbarzellen) deutlich knapper als vorher (war 1mm im
|
||||
// Referenzentwurf - bei einer ~7mm breiten Zelle ein gutes Viertel reiner Leerraum). Die
|
||||
// Kachel selbst füllt dadurch ihren Rasterplatz sichtbar besser aus.
|
||||
var cellInset = .4f * k;
|
||||
var cellCornerRadius = Math.Min(cellWidth, cellHeight) * .2f;
|
||||
var commands = new List<DrawingCommand>();
|
||||
var contentWidthDesign = designWidth * k;
|
||||
var y = 0f;
|
||||
// Keine eigene "Anwesenheit"-Überschrift mehr - die Monatsnamen im Raster machen bereits
|
||||
// klar, worum es geht. Der Name bleibt klein und in hellem Grau: er dient nur der Kontrolle,
|
||||
// dass der Kalender zum richtigen Kind gehört, nicht als gestalterischer Blickfang - der
|
||||
// eingesparte Platz kommt stattdessen den Tageskacheln zugute (siehe designHeight oben).
|
||||
commands.Add(new DrawStringEx(0, y, 5 * k, contentWidthDesign, studentName,
|
||||
DrawingTextAlignment.AlignLeft, 6.5f * finalScale, Color: "#9CA3AF"));
|
||||
y += 5 * k + .5f * k;
|
||||
var weekdays = new[] { "Mo", "Di", "Mi", "Do", "Fr", "Sa", "So" };
|
||||
var gridStartY = y;
|
||||
for (var monthIndex = 0; monthIndex < monthCount; monthIndex++)
|
||||
{
|
||||
var current = first.AddMonths(monthIndex);
|
||||
var days = ClassTeacherOverviewViewModel.BuildCompactMonthDays(current, absences, registerEntries,
|
||||
DateOnly.FromDateTime(DateTime.Today), studentName);
|
||||
var offset = ((int)current.DayOfWeek + 6) % 7;
|
||||
var xOffset = monthIndex * (monthWidth + monthGapX);
|
||||
var monthY = gridStartY;
|
||||
commands.Add(new DrawStringEx(xOffset, monthY, 11 * k, monthWidth,
|
||||
current.ToString("MMMM yyyy", CultureInfo.GetCultureInfo("de-DE")),
|
||||
DrawingTextAlignment.AlignLeft, 9 * finalScale, Color: "#374151", Bold: true));
|
||||
monthY += 11 * k;
|
||||
for (var column = 0; column < 7; column++)
|
||||
commands.Add(new DrawStringEx(xOffset + column * cellWidth, monthY, 9 * k,
|
||||
cellWidth, weekdays[column], DrawingTextAlignment.AlignCenter, 7 * finalScale, Color: "#6B7280",
|
||||
Bold: true));
|
||||
monthY += 9 * k;
|
||||
|
||||
foreach (var day in days)
|
||||
{
|
||||
var index = offset + day.Date.Day - 1;
|
||||
var column = index % 7;
|
||||
var row = index / 7;
|
||||
var x = xOffset + column * cellWidth;
|
||||
var cellY = monthY + row * cellHeight;
|
||||
// Sa/So (Spalten 5/6, siehe weekdays-Array oben) ohne Eintrag dezent ausgrauen - das
|
||||
// sind normalerweise keine Schultage, "keine Fehlzeit" dort ist keine Leistung und
|
||||
// soll nicht optisch gleichwertig neben echten schulfreien-Tage-Einträgen stehen. Ein
|
||||
// tatsächlicher Eintrag an einem Wochenendtag (day.HasSignal) bleibt unverändert
|
||||
// farbig, da er echte Information trägt.
|
||||
var isMutedWeekend = column is 5 or 6 && !day.HasSignal;
|
||||
commands.Add(new DrawRoundedRectangle(x + cellInset, cellY, cellWidth - 2 * cellInset,
|
||||
cellHeight - cellInset, cellCornerRadius, isMutedWeekend ? "#E5E7EB" : "#D1D5DB", .35f,
|
||||
day.HasSignal ? day.SignalColorHex : isMutedWeekend ? "#F3F4F6" : "#FFFFFF"));
|
||||
commands.Add(new DrawStringEx(x, cellY + k, cellHeight - 2 * k, cellWidth,
|
||||
day.HasSignal ? day.SignalCode : day.DayNumber, DrawingTextAlignment.AlignCenter, 7 * finalScale,
|
||||
Color: day.HasSignal ? "#FFFFFF" : isMutedWeekend ? "#B0B7C0" : "#374151", Bold: day.HasSignal));
|
||||
}
|
||||
}
|
||||
y = gridStartY + 11 * k + 9 * k + maxWeeks * cellHeight + designTrailingGapY * k;
|
||||
|
||||
commands.Add(new DrawStringEx(0, y, 8 * k, contentWidthDesign,
|
||||
"U unentschuldigt · A abwesend · V verspätet · E entschuldigt · ! Klassenbuch",
|
||||
DrawingTextAlignment.AlignLeft, 6.5f * finalScale, Color: "#6B7280"));
|
||||
return new DrawingValue(commands, y + 9 * k);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Chronologische, portable Fehlzeitenliste für Elternbriefvorlagen.</summary>
|
||||
public static class StudentAbsenceDayListDrawingBuilder
|
||||
{
|
||||
public const string PlaceholderName = "Student.AbsenceDays";
|
||||
|
||||
public static DrawingValue Build(string studentName, AttendanceCalendarOptions options,
|
||||
IReadOnlyList<ClassAbsenceDaySummaryRow> absences, float contentWidth = 170,
|
||||
float millimeterScale = 1)
|
||||
{
|
||||
var scale = options.Size switch
|
||||
{
|
||||
AttendanceCalendarSize.Small => .75f,
|
||||
AttendanceCalendarSize.Large => 1f,
|
||||
_ => .88f,
|
||||
};
|
||||
// contentWidth ist die reale DRAWBOX/FLOWDRAWBOX-Breite (bereits in der Koordinaten-Einheit
|
||||
// der Vorlage) und wird für die Spalten NICHT zusätzlich mit millimeterScale multipliziert -
|
||||
// die Spaltenpositionen sind Anteile von contentWidth (proportional, unitless), nicht eigene
|
||||
// mm-Maße. Nur echte mm-Maße wie Zeilenhöhe/Abstände (Y-Richtung) brauchen millimeterScale,
|
||||
// um bei einer in "pt" deklarierten Vorlage die richtige physische Größe zu erreichen (siehe
|
||||
// StudentAttendanceCalendarDrawingBuilder). Eine frühere Version multiplizierte auch die
|
||||
// Spalten mit millimeterScale, wodurch sie bei "pt"-Vorlagen weit über contentWidth
|
||||
// hinausliefen (z.B. Status-Spalte bei x≈323 in einer nur 170 Einheiten breiten Box).
|
||||
var rowHeight = 12 * scale * millimeterScale;
|
||||
var start = options.NormalizedStartMonth;
|
||||
var end = start.AddMonths(options.NormalizedMonthCount).AddDays(-1);
|
||||
var rows = absences
|
||||
.Where(a => a.Date >= start && a.Date <= end &&
|
||||
UntisNameMatching.NamesMatch(a.StudentName, studentName))
|
||||
.OrderBy(a => a.Date)
|
||||
.ToList();
|
||||
var commands = new List<DrawingCommand>();
|
||||
var y = 0f;
|
||||
// Kein eigener "Fehltage"-Titel mehr - analog zum Anwesenheitskalender dient der (klein und
|
||||
// hellgrau gehaltene) Name nur der Kontrolle, dass die Liste zum richtigen Kind gehört.
|
||||
commands.Add(new DrawStringEx(0, y, 5 * millimeterScale, contentWidth, studentName,
|
||||
DrawingTextAlignment.AlignLeft, 6.5f * scale, Color: "#9CA3AF"));
|
||||
y += 5 * millimeterScale + .5f * millimeterScale;
|
||||
// Spaltenbreiten als Anteile von contentWidth (gegen eine 170-Einheiten-Referenz austariert),
|
||||
// damit auch die Datenzeilen (nicht nur die kurzen Kopfzeilen-Labels) hineinpassen - "Datum"
|
||||
// als Kopfzeile ist kürzer als "dd.MM.yyyy" und wurde bei 31 zu schmal bemessen, wodurch das
|
||||
// Datum am rechten Rand abgeschnitten wurde.
|
||||
const float referenceWidth = 170f;
|
||||
var dateColumnX = contentWidth * (2f / referenceWidth);
|
||||
var dateColumnWidth = contentWidth * (38f / referenceWidth);
|
||||
var extentColumnX = contentWidth * (44f / referenceWidth);
|
||||
var extentColumnWidth = contentWidth * (66f / referenceWidth);
|
||||
var statusColumnX = contentWidth * (114f / referenceWidth);
|
||||
var statusColumnWidth = contentWidth * (54f / referenceWidth);
|
||||
|
||||
(string Extent, string Status, string StatusColor) Format(ClassAbsenceDaySummaryRow row)
|
||||
{
|
||||
var extent = row.CountsAsFullDay
|
||||
? "Ganzer Fehltag"
|
||||
: row.TotalAbsentPeriods > 0
|
||||
? $"Fehlzeit · {row.TotalAbsentPeriods} Std."
|
||||
: $"Fehlzeit · {row.TotalAbsentMinutes} Min.";
|
||||
var status = row.IsUnexcused
|
||||
? "Unentschuldigt"
|
||||
: row.FriendlyStatusLabel.Contains("Entschuldigt", StringComparison.OrdinalIgnoreCase)
|
||||
? "Entschuldigt"
|
||||
: row.FriendlyStatusLabel;
|
||||
return (extent, status, row.IsUnexcused ? "#C62828" : "#2E7D32");
|
||||
}
|
||||
|
||||
void DrawRows(float columnX, float columnWidth, float dColumnX, float dColumnWidth, float eColumnX,
|
||||
float eColumnWidth, float sColumnX, float sColumnWidth,
|
||||
IReadOnlyList<ClassAbsenceDaySummaryRow> columnRows)
|
||||
{
|
||||
var rowY = y;
|
||||
commands.Add(new DrawRectangle(columnX, rowY, columnWidth, rowHeight, "#CBD5E1", .4f, "#F3F4F6"));
|
||||
commands.Add(new DrawStringEx(dColumnX, rowY + scale * millimeterScale, rowHeight - scale * millimeterScale,
|
||||
dColumnWidth, "Datum", DrawingTextAlignment.AlignLeft, 7.5f * scale, Color: "#374151", Bold: true));
|
||||
commands.Add(new DrawStringEx(eColumnX, rowY + scale * millimeterScale, rowHeight - scale * millimeterScale,
|
||||
eColumnWidth, "Umfang", DrawingTextAlignment.AlignLeft, 7.5f * scale, Color: "#374151", Bold: true));
|
||||
commands.Add(new DrawStringEx(sColumnX, rowY + scale * millimeterScale, rowHeight - scale * millimeterScale,
|
||||
sColumnWidth, "Status", DrawingTextAlignment.AlignLeft, 7.5f * scale, Color: "#374151", Bold: true));
|
||||
rowY += rowHeight;
|
||||
for (var index = 0; index < columnRows.Count; index++)
|
||||
{
|
||||
var row = columnRows[index];
|
||||
var (extent, status, statusColor) = Format(row);
|
||||
var fill = index % 2 == 0 ? "#FFFFFF" : "#F9FAFB";
|
||||
commands.Add(new DrawRectangle(columnX, rowY, columnWidth, rowHeight, "#E5E7EB", .3f, fill));
|
||||
commands.Add(new DrawStringEx(dColumnX, rowY + scale * millimeterScale,
|
||||
rowHeight - scale * millimeterScale, dColumnWidth,
|
||||
row.Date.ToString("dd.MM.yyyy"), DrawingTextAlignment.AlignLeft, 7.5f * scale, Color: "#374151"));
|
||||
commands.Add(new DrawStringEx(eColumnX, rowY + scale * millimeterScale,
|
||||
rowHeight - scale * millimeterScale, eColumnWidth,
|
||||
extent, DrawingTextAlignment.AlignLeft, 7.5f * scale, Color: "#374151"));
|
||||
commands.Add(new DrawStringEx(sColumnX, rowY + scale * millimeterScale,
|
||||
rowHeight - scale * millimeterScale, sColumnWidth,
|
||||
status, DrawingTextAlignment.AlignLeft, 7.5f * scale, Color: statusColor, Bold: row.IsUnexcused));
|
||||
rowY += rowHeight;
|
||||
}
|
||||
}
|
||||
|
||||
if (rows.Count == 0)
|
||||
{
|
||||
DrawRows(0, contentWidth, dateColumnX, dateColumnWidth, extentColumnX, extentColumnWidth,
|
||||
statusColumnX, statusColumnWidth, []);
|
||||
y += rowHeight;
|
||||
commands.Add(new DrawStringEx(dateColumnX, y + 2 * scale * millimeterScale, rowHeight,
|
||||
contentWidth - 2 * dateColumnX, "Keine Fehltage im gewählten Zeitraum",
|
||||
DrawingTextAlignment.AlignLeft, 8 * scale, Color: "#6B7280", Italic: true));
|
||||
y += rowHeight + 3 * scale * millimeterScale;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Ab genug Zeilen zweispaltig (chronologisch: erste Hälfte links, Rest rechts) - spart bei
|
||||
// längeren Listen spürbar Höhe. Nur wenn die Box auch wirklich breit genug für zwei volle
|
||||
// Spalten ist (>= 2x die Einspalten-Referenzbreite + Zwischenraum) - sonst blieben Datum/
|
||||
// Umfang/Status in jeder Hälfte zu schmal und würden abgeschnitten, siehe die reale
|
||||
// Vorlage dieses Nutzers, deren FLOWDRAWBOX für diesen Platzhalter aktuell nur 170 statt
|
||||
// z.B. 400+ Einheiten breit ist (dort bleibt es also bewusst einspaltig).
|
||||
const float columnGapDesign = 8f;
|
||||
var minTwoColumnWidth = 2 * referenceWidth + columnGapDesign;
|
||||
if (rows.Count >= 4 && contentWidth >= minTwoColumnWidth)
|
||||
{
|
||||
var columnGap = contentWidth * (columnGapDesign / referenceWidth);
|
||||
var columnWidth = (contentWidth - columnGap) / 2;
|
||||
var leftCount = (rows.Count + 1) / 2;
|
||||
var left = rows.Take(leftCount).ToList();
|
||||
var right = rows.Skip(leftCount).ToList();
|
||||
// Spaltenanteile innerhalb EINER Hälfte, gegen eine 81-Einheiten-Referenz austariert:
|
||||
// 81 + columnGapDesign(8) + 81 = 170 = referenceWidth, dieselbe Gesamtbreite wie das
|
||||
// einspaltige Layout, nur eben in zwei Hälften aufgeteilt.
|
||||
const float halfReferenceWidth = 81f;
|
||||
(float X, float Width) Fraction(float leftEdge, float x, float width) =>
|
||||
(leftEdge + columnWidth * (x / halfReferenceWidth), columnWidth * (width / halfReferenceWidth));
|
||||
var (leftDateX, leftDateWidth) = Fraction(0, 1, 19);
|
||||
var (leftExtentX, leftExtentWidth) = Fraction(0, 21, 32);
|
||||
var (leftStatusX, leftStatusWidth) = Fraction(0, 54, 26);
|
||||
var rightEdge = columnWidth + columnGap;
|
||||
var (rightDateX, rightDateWidth) = Fraction(rightEdge, 1, 19);
|
||||
var (rightExtentX, rightExtentWidth) = Fraction(rightEdge, 21, 32);
|
||||
var (rightStatusX, rightStatusWidth) = Fraction(rightEdge, 54, 26);
|
||||
DrawRows(0, columnWidth, leftDateX, leftDateWidth, leftExtentX, leftExtentWidth, leftStatusX,
|
||||
leftStatusWidth, left);
|
||||
DrawRows(rightEdge, columnWidth, rightDateX, rightDateWidth, rightExtentX, rightExtentWidth,
|
||||
rightStatusX, rightStatusWidth, right);
|
||||
y += rowHeight * (1 + Math.Max(left.Count, right.Count));
|
||||
}
|
||||
else
|
||||
{
|
||||
DrawRows(0, contentWidth, dateColumnX, dateColumnWidth, extentColumnX, extentColumnWidth,
|
||||
statusColumnX, statusColumnWidth, rows);
|
||||
y += rowHeight * (1 + rows.Count);
|
||||
}
|
||||
}
|
||||
return new DrawingValue(commands, y);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Liest ausschließlich den lokalen WebUntis-Cache. Das Öffnen oder Rendern eines
|
||||
/// Elternbriefs löst dadurch keinen unerwarteten Netzwerkabruf aus.</summary>
|
||||
public sealed class StudentAttendanceCalendarService(
|
||||
WebUntisSettingsService settings,
|
||||
IUntisAbsenceCacheRepository absenceCache,
|
||||
IUntisClassRegisterCacheRepository registerCache,
|
||||
IUntisStudentRosterCacheRepository rosterCache)
|
||||
{
|
||||
public DrawingValue Build(Student student, DateOnly month) =>
|
||||
Build(student, new AttendanceCalendarOptions(month, 1));
|
||||
|
||||
public DrawingValue Build(Student student, AttendanceCalendarOptions options, float contentWidth = 170,
|
||||
float millimeterScale = 1, float contentHeight = float.PositiveInfinity)
|
||||
{
|
||||
var className = settings.HomeroomClassName;
|
||||
if (string.IsNullOrWhiteSpace(className)) return new DrawingValue([], 0);
|
||||
|
||||
var first = options.NormalizedStartMonth;
|
||||
var last = first.AddMonths(options.NormalizedMonthCount).AddDays(-1);
|
||||
var matchName = $"{student.FirstName} {student.LastName}";
|
||||
var rosterName = rosterCache.GetByClass(className)
|
||||
.FirstOrDefault(r => UntisNameMatching.NamesMatch(r.DisplayName, matchName))?.DisplayName
|
||||
?? matchName;
|
||||
var start = first.Year * 10000 + first.Month * 100 + first.Day;
|
||||
var end = last.Year * 10000 + last.Month * 100 + last.Day;
|
||||
var absences = absenceCache.GetByClassAndRange(className, start, end)
|
||||
.Select(e => new UntisClassAbsenceEntryDto(e.StudentName, e.ExternKey, e.ClassName, e.Date,
|
||||
e.AbsentPeriods, e.AbsentMinutes, e.TeacherUsernames, e.Subject, e.AbsenceReason, e.Note,
|
||||
e.EntryId, e.HandledOn, e.Counts, e.ExcuseNote, e.PeriodNumber, e.Status, e.CountsAsFullDay))
|
||||
.ToList();
|
||||
var register = registerCache.GetByClassAndRange(className, start, end)
|
||||
.Select(e => new UntisForeignClassRegisterEventDto(e.ClassName, e.Date, e.Subject, e.StudentName,
|
||||
e.TeacherUsername, e.CategoryName, e.CategoryGroup, e.Text))
|
||||
.ToList();
|
||||
return StudentAttendanceCalendarDrawingBuilder.Build(rosterName, options,
|
||||
ClassAbsenceDaySummaryRow.GroupByStudentAndDay(absences), register, contentWidth, millimeterScale,
|
||||
contentHeight);
|
||||
}
|
||||
|
||||
public DrawingValue BuildAbsenceDayList(Student student, AttendanceCalendarOptions options, float contentWidth = 170,
|
||||
float millimeterScale = 1)
|
||||
{
|
||||
var className = settings.HomeroomClassName;
|
||||
if (string.IsNullOrWhiteSpace(className)) return new DrawingValue([], 0);
|
||||
|
||||
var first = options.NormalizedStartMonth;
|
||||
var last = first.AddMonths(options.NormalizedMonthCount).AddDays(-1);
|
||||
var matchName = $"{student.FirstName} {student.LastName}";
|
||||
var rosterName = rosterCache.GetByClass(className)
|
||||
.FirstOrDefault(r => UntisNameMatching.NamesMatch(r.DisplayName, matchName))?.DisplayName
|
||||
?? matchName;
|
||||
var start = first.Year * 10000 + first.Month * 100 + first.Day;
|
||||
var end = last.Year * 10000 + last.Month * 100 + last.Day;
|
||||
var absences = absenceCache.GetByClassAndRange(className, start, end)
|
||||
.Select(e => new UntisClassAbsenceEntryDto(e.StudentName, e.ExternKey, e.ClassName, e.Date,
|
||||
e.AbsentPeriods, e.AbsentMinutes, e.TeacherUsernames, e.Subject, e.AbsenceReason, e.Note,
|
||||
e.EntryId, e.HandledOn, e.Counts, e.ExcuseNote, e.PeriodNumber, e.Status, e.CountsAsFullDay));
|
||||
return StudentAbsenceDayListDrawingBuilder.Build(rosterName, options,
|
||||
ClassAbsenceDaySummaryRow.GroupByStudentAndDay(absences), contentWidth, millimeterScale);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
using Avalonia.Controls;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using LehrerApp.Core.Interfaces;
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Core.Services;
|
||||
using LehrerApp.Desktop.ViewModels.Groups;
|
||||
using LehrerApp.Desktop.ViewModels.Students;
|
||||
using LehrerApp.Desktop.Views;
|
||||
using LehrerApp.Desktop.Views.Groups;
|
||||
using LehrerApp.Desktop.Views.Students;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace LehrerApp.Desktop.Services;
|
||||
|
||||
/// <summary>Führt einen der vier bestehenden WebUntis-Abgleiche (unverändert, über ihre bestehenden
|
||||
/// Dialoge) aus und vermerkt das Ergebnis im <see cref="UntisHubService"/> - genutzt sowohl vom
|
||||
/// Untis-Hub-Dialog ("Jetzt prüfen" je Zeile) als auch von den WebUntis-Menüpunkten in
|
||||
/// <c>MainWindow</c>, damit beide Einstiegspunkte denselben Fälligkeitsstand pflegen.</summary>
|
||||
public static class UntisHubActions
|
||||
{
|
||||
public static async Task RunFehlzeitenAsync(Window owner, LearningGroup group, UntisHubJobKind kind,
|
||||
DateOnly start, DateOnly end, UntisHubService hub)
|
||||
{
|
||||
var vm = new WebUntisLessonAbsenceComparisonViewModel(group,
|
||||
App.Services.GetRequiredService<WebUntisIntegrationService>(),
|
||||
App.Services.GetRequiredService<IStudentRepository>(),
|
||||
App.Services.GetRequiredService<IParticipationSessionRepository>(),
|
||||
App.Services.GetRequiredService<IParticipationRepository>(),
|
||||
App.Services.GetRequiredService<AiPlanningService>(),
|
||||
App.Services.GetRequiredService<AiSettingsService>())
|
||||
{ StartDate = start.ToDateTime(TimeOnly.MinValue), EndDate = end.ToDateTime(TimeOnly.MinValue) };
|
||||
var loaded = TrackLoad(vm, v => v.Busy);
|
||||
await new WebUntisLessonAbsenceComparisonDialog { DataContext = vm }.ShowDialog(owner);
|
||||
if (loaded()) hub.RecordRun(kind, group.Id, vm.Status);
|
||||
}
|
||||
|
||||
public static async Task RunKlassenbuchAsync(Window owner, UntisHubService hub)
|
||||
{
|
||||
var vm = new WebUntisDocumentationComparisonViewModel(
|
||||
App.Services.GetRequiredService<WebUntisIntegrationService>(),
|
||||
App.Services.GetRequiredService<IStudentRepository>(),
|
||||
App.Services.GetRequiredService<IGroupRepository>(),
|
||||
App.Services.GetRequiredService<IDocumentationRepository>(),
|
||||
App.Services.GetRequiredService<SchoolYearService>());
|
||||
var loaded = TrackLoad(vm, v => v.Busy);
|
||||
await new WebUntisDocumentationComparisonDialog { DataContext = vm }.ShowDialog(owner);
|
||||
if (loaded()) hub.RecordRun(UntisHubJobKind.Klassenbuchabgleich, null, vm.Status);
|
||||
}
|
||||
|
||||
public static async Task RunHausaufgabenAsync(Window owner, UntisHubService hub)
|
||||
{
|
||||
var vm = new WebUntisHomeworkComparisonViewModel(
|
||||
App.Services.GetRequiredService<WebUntisIntegrationService>(),
|
||||
App.Services.GetRequiredService<IStudentRepository>(),
|
||||
App.Services.GetRequiredService<IGroupRepository>(),
|
||||
App.Services.GetRequiredService<ISubjectRepository>(),
|
||||
App.Services.GetRequiredService<IGroupMembershipRepository>(),
|
||||
App.Services.GetRequiredService<IParticipationSessionRepository>(),
|
||||
App.Services.GetRequiredService<IParticipationRepository>(),
|
||||
App.Services.GetRequiredService<SchoolYearService>());
|
||||
var loaded = TrackLoad(vm, v => v.Busy);
|
||||
await new WebUntisHomeworkComparisonDialog { DataContext = vm }.ShowDialog(owner);
|
||||
if (loaded()) hub.RecordRun(UntisHubJobKind.Hausaufgabenabgleich, null, vm.Status);
|
||||
}
|
||||
|
||||
public static async Task RunOffenePeriodsAsync(Window owner, UntisHubService hub)
|
||||
{
|
||||
var dialog = new OpenUntisPeriodsDialog();
|
||||
await dialog.ShowDialog(owner);
|
||||
hub.RecordRun(UntisHubJobKind.OffenePeriods, null, dialog.LastStatus);
|
||||
}
|
||||
|
||||
/// <summary>Erkennt nicht-invasiv (ohne die Vergleichs-ViewModels zu ändern), ob im Dialog
|
||||
/// tatsächlich ein Ladeversuch stattfand: <c>Busy</c> wechselt in <c>Load()</c> immer erst auf
|
||||
/// true und im <c>finally</c>-Block zurück auf false, egal ob erfolgreich oder mit Fehler
|
||||
/// abgebrochen - genau dieser Übergang wird hier beobachtet.</summary>
|
||||
private static Func<bool> TrackLoad<T>(T vm, Func<T, bool> isBusy) where T : ObservableObject
|
||||
{
|
||||
var loaded = false;
|
||||
var wasBusy = false;
|
||||
vm.PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.PropertyName != "Busy") return;
|
||||
var busy = isBusy(vm);
|
||||
if (wasBusy && !busy) loaded = true;
|
||||
wasBusy = busy;
|
||||
};
|
||||
return () => loaded;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
using LehrerApp.Core.Interfaces;
|
||||
using LehrerApp.Core.Models;
|
||||
using LehrerApp.Core.Services;
|
||||
|
||||
namespace LehrerApp.Desktop.Services;
|
||||
|
||||
public enum UntisHubDueState { Ok, Due, Overdue }
|
||||
|
||||
/// <summary>Eine Zeile im Untis-Hub: eine Job-Instanz (Fehlzeiten-Kadenz je Lerngruppe, oder einer
|
||||
/// der drei dashboard-weiten Jobs) mit ihrer aktuellen Fälligkeit.</summary>
|
||||
public sealed record UntisHubJobRow(
|
||||
UntisHubJobKind Kind, Guid? GroupId, string GroupName,
|
||||
DateTime? LastRunAt, string? LastResultSummary, UntisHubDueState DueState, string DueLabel);
|
||||
|
||||
/// <summary>
|
||||
/// Zeigt, welche der bestehenden, rein manuell ausgelösten WebUntis-Abgleiche (Fehlzeiten pro
|
||||
/// Lerngruppe, offene Stunden, Klassenbuch-/Hausaufgabenabgleich) fällig sind - ohne selbst
|
||||
/// WebUntis anzufragen (Nutzer-Feedback: "nicht bei WebUntis auffallen", siehe
|
||||
/// <see cref="UntisReportCacheService"/>). Die eigentlichen Abgleiche laufen weiterhin über die
|
||||
/// bestehenden Vergleichsdialoge (siehe <see cref="UntisHubActions"/>); dieser Service verwaltet
|
||||
/// nur die Fälligkeits-Zeitstempel dazu.
|
||||
/// </summary>
|
||||
public sealed class UntisHubService(
|
||||
IGroupRepository groups, IUntisHubJobStateRepository jobStates, SchoolYearService schoolYears)
|
||||
{
|
||||
private static readonly TimeSpan FehlzeitenKurzDue = TimeSpan.FromDays(14);
|
||||
private static readonly TimeSpan FehlzeitenKurzOverdue = TimeSpan.FromDays(21);
|
||||
private static readonly TimeSpan FehlzeitenLangDue = TimeSpan.FromDays(60);
|
||||
private static readonly TimeSpan FehlzeitenLangOverdue = TimeSpan.FromDays(90);
|
||||
private static readonly TimeSpan GlobalDue = TimeSpan.FromDays(14);
|
||||
private static readonly TimeSpan GlobalOverdue = TimeSpan.FromDays(21);
|
||||
|
||||
private static readonly (UntisHubJobKind Kind, string Label)[] GlobalJobs =
|
||||
[
|
||||
(UntisHubJobKind.OffenePeriods, "Offene Stunden"),
|
||||
(UntisHubJobKind.Klassenbuchabgleich, "Klassenbuchabgleich"),
|
||||
(UntisHubJobKind.Hausaufgabenabgleich, "Hausaufgabenabgleich"),
|
||||
];
|
||||
|
||||
public List<UntisHubJobRow> GetRows()
|
||||
{
|
||||
var eligibleGroups = groups.GetBySchoolYear(schoolYears.CurrentSchoolYear())
|
||||
.Where(g => g.WebUntisLessonId is not null && !g.ExcludedFromUntisHub)
|
||||
.OrderBy(g => g.Name)
|
||||
.ToList();
|
||||
return BuildRows(eligibleGroups, jobStates.GetAll(), DateTime.UtcNow);
|
||||
}
|
||||
|
||||
/// <summary>Der Langzeit-Fehlzeitenabgleich deckt seit Schuljahresbeginn ein Zeitfenster ab, das
|
||||
/// das kurzfristige vollständig einschließt - ohne das hier mitzuziehen bliebe die kurzfristige
|
||||
/// Kadenz trotz erledigtem Langzeit-Abgleich als fällig stehen (Nutzer-Feedback). Umgekehrt deckt
|
||||
/// ein Kurz-Lauf das lange Fenster nicht ab, bleibt also einseitig.
|
||||
public void RecordRun(UntisHubJobKind kind, Guid? groupId, string? summary)
|
||||
{
|
||||
var now = DateTime.UtcNow;
|
||||
Save(kind, groupId, now, summary);
|
||||
if (kind == UntisHubJobKind.FehlzeitenLang)
|
||||
Save(UntisHubJobKind.FehlzeitenKurz, groupId, now, "durch Abgleich seit Schuljahresbeginn mit erledigt");
|
||||
}
|
||||
|
||||
private void Save(UntisHubJobKind kind, Guid? groupId, DateTime at, string? summary) =>
|
||||
jobStates.Save(new UntisHubJobState
|
||||
{
|
||||
Id = jobStates.Get(kind, groupId)?.Id ?? Guid.NewGuid(),
|
||||
Kind = kind, GroupId = groupId, LastRunAt = at, LastResultSummary = summary,
|
||||
});
|
||||
|
||||
/// Reine Entscheidungslogik ohne Repository-Zugriff (gleiches Muster wie
|
||||
/// <see cref="UntisReportCacheService.Plan"/>): aus den fälligkeitsrelevanten Lerngruppen und den
|
||||
/// zuletzt gespeicherten Job-Zuständen wird die vollständige Hub-Zeilenliste gebaut - zwei
|
||||
/// Fehlzeiten-Zeilen je Gruppe plus die drei dashboard-weiten Zeilen.
|
||||
public static List<UntisHubJobRow> BuildRows(
|
||||
IReadOnlyList<LearningGroup> eligibleGroups, IReadOnlyList<UntisHubJobState> states, DateTime utcNow)
|
||||
{
|
||||
// Nach Sync-Aktivierung von UntisHubJobState (siehe TODO.md) können zwei Geräte, die
|
||||
// denselben, noch nie gelaufenen Job unabhängig voneinander zum ersten Mal ausführen,
|
||||
// bevor sie sich gegenseitig gesehen haben, kurzzeitig zwei Datensätze für dasselbe
|
||||
// (Kind, GroupId) anlegen - hier den zuletzt gelaufenen wählen statt einen beliebigen.
|
||||
UntisHubJobState? State(UntisHubJobKind kind, Guid? groupId) =>
|
||||
states.Where(s => s.Kind == kind && s.GroupId == groupId)
|
||||
.OrderByDescending(s => s.LastRunAt)
|
||||
.FirstOrDefault();
|
||||
|
||||
var rows = new List<UntisHubJobRow>();
|
||||
foreach (var group in eligibleGroups)
|
||||
{
|
||||
rows.Add(Row(UntisHubJobKind.FehlzeitenKurz, group.Id, group.Name,
|
||||
State(UntisHubJobKind.FehlzeitenKurz, group.Id), FehlzeitenKurzDue, FehlzeitenKurzOverdue, utcNow));
|
||||
rows.Add(Row(UntisHubJobKind.FehlzeitenLang, group.Id, group.Name,
|
||||
State(UntisHubJobKind.FehlzeitenLang, group.Id), FehlzeitenLangDue, FehlzeitenLangOverdue, utcNow));
|
||||
}
|
||||
foreach (var (kind, label) in GlobalJobs)
|
||||
rows.Add(Row(kind, null, label, State(kind, null), GlobalDue, GlobalOverdue, utcNow));
|
||||
return rows;
|
||||
}
|
||||
|
||||
private static UntisHubJobRow Row(UntisHubJobKind kind, Guid? groupId, string groupName,
|
||||
UntisHubJobState? state, TimeSpan due, TimeSpan overdue, DateTime utcNow)
|
||||
{
|
||||
var (dueState, dueLabel) = DueStatus(state?.LastRunAt, due, overdue, utcNow);
|
||||
return new UntisHubJobRow(kind, groupId, groupName, state?.LastRunAt, state?.LastResultSummary,
|
||||
dueState, dueLabel);
|
||||
}
|
||||
|
||||
private static (UntisHubDueState, string) DueStatus(
|
||||
DateTime? lastRunAt, TimeSpan due, TimeSpan overdue, DateTime utcNow)
|
||||
{
|
||||
if (lastRunAt is null) return (UntisHubDueState.Overdue, "noch nie geprüft");
|
||||
var age = utcNow - lastRunAt.Value;
|
||||
var days = (int)age.TotalDays;
|
||||
if (age >= overdue) return (UntisHubDueState.Overdue, $"fällig seit {days} Tagen");
|
||||
if (age >= due) return (UntisHubDueState.Due, $"fällig seit {days} Tagen");
|
||||
return (UntisHubDueState.Ok, days == 0 ? "gerade eben geprüft" : $"vor {days} Tag(en) geprüft");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using LehrerApp.Core.Importing;
|
||||
using LehrerApp.Core.Models;
|
||||
|
||||
namespace LehrerApp.Desktop.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Aus <c>WebUntisLessonAbsenceComparisonViewModel</c> herausgelöst (Nachtrag: die MCP-Tools in
|
||||
/// <c>UntisComparisonTools</c> brauchen exakt dieselbe Regel für dieselbe Fehlzeile, siehe TODO.md) -
|
||||
/// framework-frei (kein ObservableObject/Avalonia-Bezug), damit beide Aufrufer ohne Duplikat
|
||||
/// garantiert denselben Statusvorschlag berechnen. Eine Abweichung zwischen Dialog und MCP-Tool für
|
||||
/// dieselbe WebUntis-Zeile wäre verwirrender als die eine zusätzliche Indirektion hier.
|
||||
/// </summary>
|
||||
public static class UntisLessonAbsenceHelper
|
||||
{
|
||||
private const int FullLessonMinutes = 45;
|
||||
|
||||
// Der Bericht liefert keinen Entschuldigungstext, nur Minutenwerte, ein Bearbeitet-Datum und die
|
||||
// (laut Schule) über Klammerung der ENr codierte Entscheidung des Klassenlehrers - ENr in
|
||||
// Klammern bedeutet unentschuldigt, ohne Klammern abgeschlossen/entschuldigt. Reihenfolge ist
|
||||
// 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
|
||||
// oder sonstiger Teilverlust, nie als komplette Abwesenheit - der Text "Verspätung" allein ist
|
||||
// laut Schule nicht zuverlässig genug, deshalb primär über die Minutenschwelle erkannt.
|
||||
public static AttendanceStatus MapStatus(UntisLessonAbsenceDto absence)
|
||||
{
|
||||
if (IsEarlyRelease(absence)) return AttendanceStatus.LeftDuringClass;
|
||||
if (absence.AbsentMinutes < FullLessonMinutes) return AttendanceStatus.Late;
|
||||
if (string.IsNullOrWhiteSpace(absence.HandledOn)) return AttendanceStatus.ExcusePending;
|
||||
if (absence.ExternKey is null) return AttendanceStatus.ExcusePending;
|
||||
return absence.ExternKeyInParentheses ? AttendanceStatus.Unexcused : AttendanceStatus.Excused;
|
||||
}
|
||||
|
||||
private static bool IsEarlyRelease(UntisLessonAbsenceDto absence) =>
|
||||
absence.Reason?.Contains("entlassen", StringComparison.OrdinalIgnoreCase) == true;
|
||||
|
||||
/// Erste Wahl zum Zuordnen einer WebUntis-Fehlzeile: die externe Schülernummer (ENr), sofern der
|
||||
/// Schüler eine hat (z.B. nicht bei manuell statt per WebUntis-Import angelegten Schülern).
|
||||
public static int? StudentExternKey(Student student)
|
||||
{
|
||||
student.ExternalIds ??= [];
|
||||
return student.ExternalIds.TryGetValue(StudentImportFormats.MasterDataCsv.Value, out var value)
|
||||
&& int.TryParse(value, out var key) ? key : null;
|
||||
}
|
||||
}
|
||||
@@ -65,9 +65,9 @@ public class UntisSyncService : IDisposable
|
||||
TimeSpan.FromMinutes(PollIntervalMinutes), TimeSpan.FromMinutes(PollIntervalMinutes));
|
||||
}
|
||||
|
||||
public async Task PollAsync()
|
||||
public async Task PollAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!await _gate.WaitAsync(0)) return;
|
||||
if (!await _gate.WaitAsync(0).ConfigureAwait(false)) return;
|
||||
try
|
||||
{
|
||||
var url = _settings.GetIcalUrl();
|
||||
@@ -76,7 +76,7 @@ public class UntisSyncService : IDisposable
|
||||
string icsText;
|
||||
try
|
||||
{
|
||||
icsText = await _http.GetStringAsync(url);
|
||||
icsText = await _http.GetStringAsync(url, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -88,7 +88,7 @@ public class UntisSyncService : IDisposable
|
||||
UntisPollResult result;
|
||||
try
|
||||
{
|
||||
result = ProcessIcsText(icsText);
|
||||
result = await Task.Run(() => ProcessIcsText(icsText)).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -118,11 +118,20 @@ public class UntisSyncService : IDisposable
|
||||
var diffResult = _diffService.Diff(events, previousSnapshot, confirmedMappings, today,
|
||||
existingSupervisionDuties: _supervisionDuties.GetAll(), freeDates: BuildFreeDates(today));
|
||||
|
||||
var savedSubstitutionCount = 0;
|
||||
foreach (var candidate in diffResult.SubstitutionsToSave)
|
||||
{
|
||||
var existing = candidate.ExternalId is not null ? _substitutions.GetByExternalId(candidate.ExternalId) : null;
|
||||
if (existing is not null) candidate.Id = existing.Id;
|
||||
// Der Diff liefert auch weiterhin bestehende WebUntis-Abweichungen als Kandidaten.
|
||||
// Ein unverändertes Upsert würde über Repository.OnChange bei jedem Poll erneut ein
|
||||
// Sync-Ereignis erzeugen und bei vielen aktiven Abweichungen das Protokoll fluten.
|
||||
if (existing is not null)
|
||||
{
|
||||
candidate.Id = existing.Id;
|
||||
if (SubstitutionContentEquals(existing, candidate)) continue;
|
||||
}
|
||||
_substitutions.Save(candidate);
|
||||
savedSubstitutionCount++;
|
||||
}
|
||||
// Zuvor automatisch erzeugte Einträge, die jetzt nicht (mehr) gebraucht werden (siehe
|
||||
// UntisDiffResult.SubstitutionExternalIdsToDelete) - existiert keiner mit dieser
|
||||
@@ -135,9 +144,17 @@ public class UntisSyncService : IDisposable
|
||||
foreach (var snapshot in diffResult.SnapshotToSave) _snapshots.Save(snapshot);
|
||||
foreach (var id in diffResult.SnapshotIdsToDelete) _snapshots.Delete(id);
|
||||
|
||||
return new UntisPollResult(events.Count, diffResult.SubstitutionsToSave.Count);
|
||||
return new UntisPollResult(events.Count, savedSubstitutionCount);
|
||||
}
|
||||
|
||||
private static bool SubstitutionContentEquals(SubstitutionEntry left, SubstitutionEntry right) =>
|
||||
left.Date == right.Date && left.Kind == right.Kind &&
|
||||
left.PeriodNumber == right.PeriodNumber && left.AfterPeriod == right.AfterPeriod &&
|
||||
left.FromPeriod == right.FromPeriod && left.ToPeriod == right.ToPeriod &&
|
||||
left.IsAllDay == right.IsAllDay && left.GroupId == right.GroupId &&
|
||||
left.GroupLabel == right.GroupLabel && left.Description == right.Description &&
|
||||
left.Notes == right.Notes && left.ExternalId == right.ExternalId;
|
||||
|
||||
// Ferien-/Feiertagstage im relevanten Zeitfenster (deutlich über das Lookahead-Fenster
|
||||
// hinaus, kostet bei kleinen Ferienlisten nichts) - verhindert, dass die aktive
|
||||
// "fehlt komplett im Feed"-Prüfung in UntisDiffService Ferientage fälschlich als Ausfall
|
||||
|
||||
@@ -205,6 +205,13 @@ public sealed class WebUntisIntegrationService(HttpClient http, WebUntisSettings
|
||||
};
|
||||
}
|
||||
|
||||
public Task<UntisOpenPeriodsMeta> GetOpenPeriodsMetaAsync(int schoolYearId, CancellationToken token = default) =>
|
||||
ExecuteAsync(client => client.GetOpenPeriodsMetaAsync(schoolYearId, token), token);
|
||||
|
||||
public Task<IReadOnlyList<UntisOpenPeriod>> GetOpenPeriodsAsync(int schoolYearId, int? teacherId,
|
||||
int? classId, DateOnly start, DateOnly end, CancellationToken token = default) =>
|
||||
ExecuteAsync(client => client.GetOpenPeriodsAsync(schoolYearId, teacherId, classId, start, end, token), token);
|
||||
|
||||
private async Task<T> ExecuteAsync<T>(Func<WebUntisClient, Task<T>> operation, CancellationToken token)
|
||||
{
|
||||
try { return await operation(await GetClientAsync(token)); }
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using System.Windows.Input;
|
||||
|
||||
namespace LehrerApp.Desktop.ViewModels;
|
||||
|
||||
/// <summary>Die sieben Dashboard-Kacheln, die tatsächlich "wo muss ich reagieren" beantworten
|
||||
/// (siehe <see cref="DashboardViewModel.AttentionCount"/>), zusammengefasst zu einer Karte mit
|
||||
/// Filter-Chips statt sieben eigenen Sichtbarkeits-Schaltern. Reihenfolge hier ist die Reihenfolge
|
||||
/// der Gruppen in der zusammengefassten Ansicht (siehe DashboardViewModel.RebuildAttention) — sie
|
||||
/// übernimmt bewusst die frühere Sortierung aus DashboardSettingsService.DefaultCardOrder, damit
|
||||
/// sich nichts, was Nutzer bereits kennen, unvorhersehbar umsortiert.
|
||||
/// "Klausurwochen" (examload) bleibt bewusst außen vor: die Einträge dort sind Wochen-Aggregate,
|
||||
/// keine Einzelvorgänge, die sich abhaken oder anklicken lassen — sie passen nicht ins Item-Modell.</summary>
|
||||
public enum AttentionKind { MissingTeachingTime, Excuse, Correction, Unplanned, Alert, Attendance, SupportPlan }
|
||||
|
||||
/// <summary>Eine Inline-Aktion auf einem Handlungsbedarf-Eintrag (z.B. "Entschuldigt"/"Unentschuldigt",
|
||||
/// "Erfassen"). Verwendet ICommand statt Action, damit die bereits vorhandenen generierten
|
||||
/// RelayCommands (OpenExcuseItem.MarkExcusedCommand, DashboardViewModel.AddMissingTeachingTimeCommand)
|
||||
/// direkt weiterverwendet werden können, statt sie in einen zweiten Delegate-Typ zu verpacken.</summary>
|
||||
public sealed record AttentionAction(string Label, ICommand Command, object? Parameter = null);
|
||||
|
||||
/// <summary>Gemeinsame Projektion für die sieben Handlungsbedarf-Arten. Trägt nur Anzeigedaten —
|
||||
/// die eigentliche Beschaffung bleibt unverändert in den jeweiligen DashboardViewModel.LoadXxx-
|
||||
/// Methoden; sie erzeugen am Ende ein AttentionItem statt (wie vorher) ihre eigene Item-Klasse in
|
||||
/// ihre eigene ObservableCollection einzutragen.</summary>
|
||||
public sealed class AttentionItem
|
||||
{
|
||||
public AttentionKind Kind { get; }
|
||||
public string Title { get; }
|
||||
public string Subtitle { get; }
|
||||
/// <summary>Kurztext rechts neben dem Titel — Fehlzeitenquote, Alert-Kind-Label. Meist leer.</summary>
|
||||
public string TrailingText { get; }
|
||||
public string DateDisplay { get; }
|
||||
public bool IsOverdue { get; }
|
||||
public AlertSeverity? Severity { get; }
|
||||
/// <summary>Nur bei Korrekturen gesetzt (0–100); steuert die ProgressBar. Eigenes HasProgress statt
|
||||
/// Nullability, damit die ProgressBar-Bindung ein einfaches int (kompatibel mit Value:double) bleibt.</summary>
|
||||
public int ProgressPercent { get; }
|
||||
public bool HasProgress { get; }
|
||||
/// <summary>Text unter der ProgressBar, z.B. "3 von 5 Arbeiten bewertet". Nur bei Korrekturen gesetzt.</summary>
|
||||
public string ProgressLabel { get; }
|
||||
/// <summary>Färbt TrailingText wie die frühere Fehlzeiten-Warnung (fest "Foreground=Red") ein —
|
||||
/// nur bei Attendance gesetzt, weil ein AttentionItem dieser Art per Konstruktion nur entsteht,
|
||||
/// wenn die Fehlzeitenquote den Schwellenwert bereits überschreitet.</summary>
|
||||
public bool IsWarningTrailing { get; }
|
||||
public IReadOnlyList<AttentionAction> Actions { get; }
|
||||
public Action? Navigate { get; }
|
||||
|
||||
public AttentionItem(AttentionKind kind, string title, string subtitle = "", string trailingText = "",
|
||||
string dateDisplay = "", bool isOverdue = false, AlertSeverity? severity = null,
|
||||
int progressPercent = 0, string progressLabel = "", bool hasProgress = false,
|
||||
bool isWarningTrailing = false, IReadOnlyList<AttentionAction>? actions = null, Action? navigate = null)
|
||||
{
|
||||
Kind = kind;
|
||||
Title = title;
|
||||
Subtitle = subtitle;
|
||||
TrailingText = trailingText;
|
||||
DateDisplay = dateDisplay;
|
||||
IsOverdue = isOverdue;
|
||||
Severity = severity;
|
||||
ProgressPercent = progressPercent;
|
||||
ProgressLabel = progressLabel;
|
||||
HasProgress = hasProgress;
|
||||
IsWarningTrailing = isWarningTrailing;
|
||||
Actions = actions ?? [];
|
||||
Navigate = navigate;
|
||||
}
|
||||
|
||||
public bool HasSubtitle => !string.IsNullOrWhiteSpace(Subtitle);
|
||||
public bool HasTrailingText => !string.IsNullOrWhiteSpace(TrailingText);
|
||||
public bool HasDate => !string.IsNullOrWhiteSpace(DateDisplay);
|
||||
public bool HasActions => Actions.Count > 0;
|
||||
public bool HasSeverity => Severity is not null;
|
||||
public bool IsHighSeverity => Severity == AlertSeverity.High;
|
||||
public bool IsMediumSeverity => Severity == AlertSeverity.Medium;
|
||||
}
|
||||
|
||||
/// <summary>Eine Kind-Gruppe innerhalb der zusammengefassten Handlungsbedarf-Liste. Items behalten
|
||||
/// die Sortierung, die ihre jeweilige LoadXxx-Methode schon immer produziert hat (z.B. Fehlzeiten
|
||||
/// nach Quote absteigend, Korrekturen nach Datum) — ein zweites, generisches "Importance"-Sortieren
|
||||
/// quer über alle Arten würde diese bewusst gewählten Reihenfolgen wieder zerstören.</summary>
|
||||
public sealed class AttentionGroup(AttentionKind kind, string header, IReadOnlyList<AttentionItem> items)
|
||||
{
|
||||
public AttentionKind Kind { get; } = kind;
|
||||
public string Header { get; } = header;
|
||||
public IReadOnlyList<AttentionItem> Items { get; } = items;
|
||||
public int Count => Items.Count;
|
||||
}
|
||||
|
||||
/// <summary>Ein Filter-Chip für eine Handlungsbedarf-Art in der zusammengefassten Karte — ersetzt
|
||||
/// die frühere Sichtbarkeit je Einzelkachel (siehe DashboardViewModel.LoadAttentionFilters).</summary>
|
||||
public partial class AttentionFilterOption : ObservableObject
|
||||
{
|
||||
[ObservableProperty] private bool _isActive = true;
|
||||
public AttentionKind Kind { get; }
|
||||
public string Label { get; }
|
||||
public Action? OnChanged { get; set; }
|
||||
|
||||
public AttentionFilterOption(AttentionKind kind, string label)
|
||||
{
|
||||
Kind = kind;
|
||||
Label = label;
|
||||
}
|
||||
|
||||
partial void OnIsActiveChanged(bool value) => OnChanged?.Invoke();
|
||||
}
|
||||
Loaded 100 of 244 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user