Compare commits
116
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4b73d2bea2 | ||
|
|
f3e23ad207 | ||
|
|
1291b24478 | ||
|
|
960d52686a | ||
|
|
45b7a2b7e6 | ||
|
|
30f0fee0b2 | ||
|
|
f0c0479bcb | ||
|
|
cdb4637c65 | ||
|
|
ecf64fff88 | ||
|
|
22eceb3ac1 | ||
|
|
0f2a25feb5 | ||
|
|
0942a8ebcf | ||
|
|
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 | ||
|
|
2ccc3201d2 | ||
|
|
ab1feba0f0 | ||
|
|
b2d0ccd30d | ||
|
|
c6efdab9ef | ||
|
|
11ef73ab1f | ||
|
|
4b4a746e17 | ||
|
|
e2e2bfb854 | ||
|
|
3e5f197bdb | ||
|
|
95e3f677e4 | ||
|
|
cdbed69d8b | ||
|
|
527c186090 | ||
|
|
28469bf547 | ||
|
|
9dce6576e2 | ||
|
|
9f28081931 | ||
|
|
6468596bf3 | ||
|
|
23abe7af63 | ||
|
|
3f71f7f371 | ||
|
|
2f2761caf8 | ||
|
|
a088823b30 | ||
|
|
1215d4ac22 | ||
|
|
84c03962ef | ||
|
|
b7c7d46ee4 | ||
|
|
da4b88c93d | ||
|
|
538ad65a3a | ||
|
|
dade41ee8d | ||
|
|
2b299fc940 | ||
|
|
dbd8777e64 | ||
|
|
89a6376fb6 | ||
|
|
b7a105af73 |
No files matched your search
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"permissions": {
|
||||||
|
"allow": [
|
||||||
|
"Bash(git commit -m ' *)"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
name: CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
pull_request:
|
||||||
|
branches: [main]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build-and-test:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
container:
|
||||||
|
image: mcr.microsoft.com/dotnet/sdk:10.0
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Restore
|
||||||
|
run: dotnet restore LehrerApp.sln
|
||||||
|
|
||||||
|
- name: Build
|
||||||
|
run: dotnet build LehrerApp.sln --no-restore --configuration Release
|
||||||
|
|
||||||
|
- name: Test
|
||||||
|
run: dotnet test LehrerApp.sln --no-build --configuration Release --logger "console;verbosity=normal"
|
||||||
Vendored
+21
-6
@@ -5,7 +5,7 @@
|
|||||||
"name": "Desktop App starten",
|
"name": "Desktop App starten",
|
||||||
"type": "coreclr",
|
"type": "coreclr",
|
||||||
"request": "launch",
|
"request": "launch",
|
||||||
"preLaunchTask": "Desktop bauen",
|
"preLaunchTask": "TemplateDesigner bauen",
|
||||||
"program": "${workspaceFolder}/LehrerApp.Desktop/bin/Debug/net10.0/LehrerApp.Desktop.dll",
|
"program": "${workspaceFolder}/LehrerApp.Desktop/bin/Debug/net10.0/LehrerApp.Desktop.dll",
|
||||||
"args": [],
|
"args": [],
|
||||||
"cwd": "${workspaceFolder}/LehrerApp.Desktop",
|
"cwd": "${workspaceFolder}/LehrerApp.Desktop",
|
||||||
@@ -15,6 +15,20 @@
|
|||||||
"DOTNET_ENVIRONMENT": "Development"
|
"DOTNET_ENVIRONMENT": "Development"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"name": "TemplateDesigner App starten",
|
||||||
|
"type": "coreclr",
|
||||||
|
"request": "launch",
|
||||||
|
"preLaunchTask": "Desktop bauen",
|
||||||
|
"program": "${workspaceFolder}/LehrerApp.TemplateDesigner/bin/Debug/net10.0/LehrerApp.TemplateDesigner.dll",
|
||||||
|
"args": [],
|
||||||
|
"cwd": "${workspaceFolder}/LehrerApp.TemplateDesigner",
|
||||||
|
"stopAtEntry": false,
|
||||||
|
"console": "internalConsole",
|
||||||
|
"env": {
|
||||||
|
"DOTNET_ENVIRONMENT": "Development"
|
||||||
|
}
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"name": "API Server starten",
|
"name": "API Server starten",
|
||||||
"type": "coreclr",
|
"type": "coreclr",
|
||||||
@@ -33,11 +47,12 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "Desktop + API (gleichzeitig)",
|
"name": "API Tests starten",
|
||||||
"configurations": [
|
"type": "coreclr",
|
||||||
"Desktop App starten",
|
"request": "launch",
|
||||||
"API Server starten"
|
"preLaunchTask": "API bauen",
|
||||||
]
|
"program": "${workspaceFolder}/LehrerApp.Api.Tests/bin/Debug/net10.0/LehrerApp.Api.Tests.dll",
|
||||||
|
"args": [],
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"compounds": [
|
"compounds": [
|
||||||
|
|||||||
Vendored
+13
@@ -27,6 +27,19 @@
|
|||||||
"problemMatcher": "$msCompile",
|
"problemMatcher": "$msCompile",
|
||||||
"group": "build"
|
"group": "build"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"label": "TemplateDesigner bauen",
|
||||||
|
"command": "dotnet",
|
||||||
|
"type": "process",
|
||||||
|
"args": [
|
||||||
|
"build",
|
||||||
|
"${workspaceFolder}/LehrerApp.TemplateDesigner/LehrerApp.TemplateDesigner.csproj",
|
||||||
|
"--configuration", "Debug",
|
||||||
|
"--verbosity", "minimal"
|
||||||
|
],
|
||||||
|
"problemMatcher": "$msCompile",
|
||||||
|
"group": "build"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"label": "Solution bauen",
|
"label": "Solution bauen",
|
||||||
"command": "dotnet",
|
"command": "dotnet",
|
||||||
|
|||||||
@@ -123,6 +123,11 @@ The API can also run via `docker/docker-compose.yml` (reads `JWT_SECRET` from th
|
|||||||
idempotency forever.
|
idempotency forever.
|
||||||
- `new LiteDbContext(stream)` opens an in-memory database from a `MemoryStream` — used pervasively
|
- `new LiteDbContext(stream)` opens an in-memory database from a `MemoryStream` — used pervasively
|
||||||
in tests for a fast, disk-free `LiteDbContext`.
|
in tests for a fast, disk-free `LiteDbContext`.
|
||||||
|
- `LehrerApp.Api`'s `Cli.cs` (`create-user`/`set-password`) opens `users.db` as a second, separate
|
||||||
|
`LiteDatabase` instance in a short-lived process next to the already-running server's own
|
||||||
|
instance. The write lands on disk correctly, but the running server process keeps serving logins
|
||||||
|
against its own in-memory state and never picks up the external change — `docker restart` on the
|
||||||
|
API container after running the CLI is required for the new password to actually take effect.
|
||||||
|
|
||||||
### Central Package Management
|
### Central Package Management
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<LangVersion>latest</LangVersion>
|
<LangVersion>latest</LangVersion>
|
||||||
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
|
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||||
<!-- CS8618: falsch-positiv durch [ObservableProperty] Source Generator -->
|
<!-- CS8618: falsch-positiv durch [ObservableProperty] Source Generator -->
|
||||||
<NoWarn>CS8618</NoWarn>
|
<NoWarn>CS8618</NoWarn>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|||||||
@@ -17,13 +17,17 @@
|
|||||||
<!-- Datenbank -->
|
<!-- Datenbank -->
|
||||||
<PackageVersion Include="LiteDB" Version="5.0.21" />
|
<PackageVersion Include="LiteDB" Version="5.0.21" />
|
||||||
|
|
||||||
<!-- PDF-Erzeugung (11.3) - nur LehrerApp.Desktop: zieht SkiaSharp-Native-Binaries mit,
|
<!-- PDF-Erzeugung: Desktop-Exporte und die unabhängige Templating-Library. -->
|
||||||
die im Server-Image (LehrerApp.Api) nichts verloren haben. -->
|
|
||||||
<PackageVersion Include="QuestPDF" Version="2025.7.0" />
|
<PackageVersion Include="QuestPDF" Version="2025.7.0" />
|
||||||
|
<PackageVersion Include="PDFtoImage" Version="5.4.0" />
|
||||||
|
<PackageVersion Include="PdfPig" Version="0.1.13" />
|
||||||
|
|
||||||
<!-- API -->
|
<!-- API -->
|
||||||
<PackageVersion Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.0" />
|
<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 -->
|
<!-- Tests -->
|
||||||
<PackageVersion Include="xunit" Version="2.9.3" />
|
<PackageVersion Include="xunit" Version="2.9.3" />
|
||||||
<PackageVersion Include="xunit.runner.visualstudio" Version="2.8.2" />
|
<PackageVersion Include="xunit.runner.visualstudio" Version="2.8.2" />
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ internal static class Cli
|
|||||||
}
|
}
|
||||||
|
|
||||||
Console.WriteLine($"Nutzer '{username}' angelegt.");
|
Console.WriteLine($"Nutzer '{username}' angelegt.");
|
||||||
|
Console.WriteLine("Hinweis: Server-Container neu starten, damit die Änderung wirksam wird (LiteDB im laufenden Serverprozess sieht externe Schreibzugriffe sonst nicht).");
|
||||||
return Task.FromResult(0);
|
return Task.FromResult(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -47,6 +48,7 @@ internal static class Cli
|
|||||||
}
|
}
|
||||||
|
|
||||||
Console.WriteLine($"Passwort für '{username}' aktualisiert.");
|
Console.WriteLine($"Passwort für '{username}' aktualisiert.");
|
||||||
|
Console.WriteLine("Hinweis: Server-Container neu starten, damit die Änderung wirksam wird (LiteDB im laufenden Serverprozess sieht externe Schreibzugriffe sonst nicht).");
|
||||||
return Task.FromResult(0);
|
return Task.FromResult(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -76,6 +76,9 @@ public class AiLesson
|
|||||||
public List<AiPhaseStep> Phases { get; set; } = [];
|
public List<AiPhaseStep> Phases { get; set; } = [];
|
||||||
public string? Homework { get; set; }
|
public string? Homework { get; set; }
|
||||||
public string? Reflection { 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
|
public class AiPhaseStep
|
||||||
@@ -100,6 +103,10 @@ public class AiPlanningResponse
|
|||||||
{
|
{
|
||||||
public List<AiLesson> Lessons { get; set; } = [];
|
public List<AiLesson> Lessons { get; set; } = [];
|
||||||
public string? Summary { 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>
|
/// <summary>
|
||||||
@@ -174,3 +181,55 @@ public class AiSubstanceResearchResponse
|
|||||||
public string ActivityRestriction { get; set; } = "";
|
public string ActivityRestriction { get; set; } = "";
|
||||||
public string Source { 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"/"SignificantlyLate"/"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
|
public interface ILessonRepository
|
||||||
{
|
{
|
||||||
|
Lesson? GetById(Guid id);
|
||||||
List<Lesson> GetByUnit(Guid unitId);
|
List<Lesson> GetByUnit(Guid unitId);
|
||||||
List<Lesson> GetByGroupAndDate(Guid groupId, DateOnly date);
|
List<Lesson> GetByGroupAndDate(Guid groupId, DateOnly date);
|
||||||
List<Lesson> GetByGroupAndRange(Guid groupId, DateOnly from, DateOnly to);
|
List<Lesson> GetByGroupAndRange(Guid groupId, DateOnly from, DateOnly to);
|
||||||
@@ -170,6 +171,14 @@ public interface IUntisCacheFetchStateRepository
|
|||||||
UntisCacheFetchState? Get(string className, UntisCacheKind kind);
|
UntisCacheFetchState? Get(string className, UntisCacheKind kind);
|
||||||
void Save(UntisCacheFetchState state);
|
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.
|
/// Vom Nutzer bestätigte Zuordnungen WebUntis-Wochenmuster → LearningGroup.
|
||||||
public interface IUntisSlotMappingRepository
|
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).
|
/// Entfernt den Eintrag endgültig — nur für die Löschfristen-Bereinigung (5.4.2).
|
||||||
void HardDelete(Guid id);
|
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
|
public interface IWorkTaskRepository
|
||||||
{
|
{
|
||||||
List<WorkTask> GetByStatus(WorkTaskStatus status);
|
List<WorkTask> GetByStatus(WorkTaskStatus status);
|
||||||
@@ -225,6 +243,9 @@ public interface IParticipationSessionRepository
|
|||||||
{
|
{
|
||||||
List<ParticipationSession> GetByGroup(Guid groupId);
|
List<ParticipationSession> GetByGroup(Guid groupId);
|
||||||
ParticipationSession? GetById(Guid id);
|
ParticipationSession? GetById(Guid id);
|
||||||
|
// Für Aggregationen über alle Gruppen (z.B. Dashboard-Fehlzeiten-Warnung), die sonst pro
|
||||||
|
// Eintrag einzeln GetById aufrufen müssten — ein Bulk-Laden vermeidet dieses N+1-Muster.
|
||||||
|
List<ParticipationSession> GetAll();
|
||||||
void Save(ParticipationSession session);
|
void Save(ParticipationSession session);
|
||||||
void Delete(Guid id);
|
void Delete(Guid id);
|
||||||
}
|
}
|
||||||
@@ -263,12 +284,34 @@ public interface ISubjectRepository
|
|||||||
}
|
}
|
||||||
public interface ICompetencyDomainRepository
|
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);
|
CompetencyDomain? GetById(Guid id);
|
||||||
void Save(CompetencyDomain domain);
|
void Save(CompetencyDomain domain);
|
||||||
void Delete(Guid id);
|
void Delete(Guid id);
|
||||||
void DeleteBySubjectAndGrade(Guid subjectId, int gradeLevel);
|
void DeleteBySubjectGradeAndVersion(Guid subjectId, int gradeLevel, Guid versionId);
|
||||||
void ReplaceForSubjectAndGrade(Guid subjectId, int gradeLevel, List<CompetencyDomain> domains);
|
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
|
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 Id { get; set; } = Guid.NewGuid();
|
||||||
public Guid SubjectId { get; set; }
|
public Guid SubjectId { get; set; }
|
||||||
public int GradeLevel { 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 Name { get; set; } = "";
|
||||||
public string Code { get; set; } = "";
|
public string Code { get; set; } = "";
|
||||||
public int SortOrder { get; set; }
|
public int SortOrder { get; set; }
|
||||||
@@ -12,6 +17,22 @@ public class CompetencyDomain
|
|||||||
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
|
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 class CompetencyItem
|
||||||
{
|
{
|
||||||
public Guid Id { get; set; } = Guid.NewGuid();
|
public Guid Id { get; set; } = Guid.NewGuid();
|
||||||
@@ -19,3 +40,17 @@ public class CompetencyItem
|
|||||||
public string Description { get; set; } = "";
|
public string Description { get; set; } = "";
|
||||||
public int SortOrder { 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; } = "";
|
||||||
|
}
|
||||||
@@ -15,6 +15,9 @@ public class Exam
|
|||||||
public string? Notes { get; set; }
|
public string? Notes { get; set; }
|
||||||
public DateOnly? ApprovalGrantedAt { get; set; }
|
public DateOnly? ApprovalGrantedAt { get; set; }
|
||||||
public DateOnly? AnnouncedAt { get; set; }
|
public DateOnly? AnnouncedAt { get; set; }
|
||||||
|
/// <summary>Stabile Kennung einer automatisch importierten Arbeit. Bleibt bei manuell
|
||||||
|
/// angelegten Klausuren null; aktuell wird der Präfix "webuntis-rest-exam:" verwendet.</summary>
|
||||||
|
public string? ExternalId { get; set; }
|
||||||
/// Verknüpft Parallelklausuren (gleiche Arbeit, mehrere Kurse) für den Kurs-Umschalter
|
/// Verknüpft Parallelklausuren (gleiche Arbeit, mehrere Kurse) für den Kurs-Umschalter
|
||||||
/// auf der Klausuren-Hauptseite — Id der "Ursprungs"-Klausur, gesetzt beim Duplizieren
|
/// auf der Klausuren-Hauptseite — Id der "Ursprungs"-Klausur, gesetzt beim Duplizieren
|
||||||
/// (siehe ExamDialogViewModel.Save).
|
/// (siehe ExamDialogViewModel.Save).
|
||||||
@@ -28,7 +31,7 @@ public class ExamTask
|
|||||||
public string? Title { get; set; }
|
public string? Title { get; set; }
|
||||||
public double MaxPoints { get; set; }
|
public double MaxPoints { get; set; }
|
||||||
public double Weight { get; set; } = 1.0;
|
public double Weight { get; set; } = 1.0;
|
||||||
public List<string> CompetencyCodes { get; set; } = [];
|
public List<CompetencyReference> Competencies { get; set; } = [];
|
||||||
}
|
}
|
||||||
public class GradingKeyEntry
|
public class GradingKeyEntry
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -8,6 +8,14 @@ public class LearningGroup
|
|||||||
public Guid? SubjectId { get; set; }
|
public Guid? SubjectId { get; set; }
|
||||||
public string SchoolYear { get; set; } = "";
|
public string SchoolYear { get; set; } = "";
|
||||||
public int GradeLevel { 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 GradingSystem GradingSystem { get; set; }
|
||||||
public int? HoursPerWeek { get; set; }
|
public int? HoursPerWeek { get; set; }
|
||||||
public bool IsActive { get; set; } = true;
|
public bool IsActive { get; set; } = true;
|
||||||
@@ -26,6 +34,21 @@ public class LearningGroup
|
|||||||
/// deshalb händisch je Lerngruppe/Schuljahr gepflegt werden - keine JSON-RPC-Methode liefert sie.
|
/// deshalb händisch je Lerngruppe/Schuljahr gepflegt werden - keine JSON-RPC-Methode liefert sie.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public int? WebUntisLessonId { get; set; }
|
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
|
||||||
|
/// hochgestufte Gruppen bleiben unverknüpft (kein rückwirkendes Verknüpfen vorgesehen).
|
||||||
|
/// </summary>
|
||||||
|
public Guid? PreviousGroupId { get; set; }
|
||||||
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||||
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
|
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ public class ParticipationSession
|
|||||||
public DateOnly Date { get; set; } = DateOnly.FromDateTime(DateTime.Today);
|
public DateOnly Date { get; set; } = DateOnly.FromDateTime(DateTime.Today);
|
||||||
public Guid? LessonId { get; set; }
|
public Guid? LessonId { get; set; }
|
||||||
public string? Comment { 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 CreatedAt { get; set; } = DateTime.UtcNow;
|
||||||
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
|
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
|
||||||
}
|
}
|
||||||
@@ -24,9 +24,26 @@ public class ParticipationEntry
|
|||||||
// Bleibt für bereits gespeicherte Daten erhalten. Neue Schreibvorgänge setzen beide Felder.
|
// Bleibt für bereits gespeicherte Daten erhalten. Neue Schreibvorgänge setzen beide Felder.
|
||||||
public bool HomeworkMissing { get; set; }
|
public bool HomeworkMissing { get; set; }
|
||||||
public AttendanceStatus? Attendance { get; set; }
|
public AttendanceStatus? Attendance { get; set; }
|
||||||
|
// Strichliste im Sitzplan (Nutzer-Feedback): RaisedHandCount zählt jede beobachtete Meldung,
|
||||||
|
// CalledOnCount die Teilmenge davon, bei der der Schüler auch drangekommen ist —
|
||||||
|
// "drangekommen" ist immer auch eine Meldung und erhöht daher immer beide Zähler zugleich,
|
||||||
|
// nie CalledOnCount allein. Ergibt nebenbei eine Aufrufgerechtigkeits-Quote
|
||||||
|
// (CalledOnCount / RaisedHandCount) und schlägt die Quantitätsbewertung vor, siehe
|
||||||
|
// ParticipationCountSuggestion.
|
||||||
|
public int RaisedHandCount { get; set; }
|
||||||
|
public int CalledOnCount { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Tagesflagge (Nutzer-Feedback): markiert eine session-bezogene Bewertung als besonders
|
||||||
|
/// herausragend oder besonders schwach, unabhängig von der Richtung ("egal in welche
|
||||||
|
/// Richtung, herausragend festhalten"). Rein deskriptiv — fließt nirgends in eine Berechnung
|
||||||
|
/// (Mitarbeitsnote 3.2, Aufrufgerechtigkeit) ein, nur zur Erinnerung/Dokumentation.
|
||||||
|
/// </summary>
|
||||||
|
public DayHighlightKind? DayHighlight { get; set; }
|
||||||
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
|
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public enum DayHighlightKind { Standout, Sleepy, Rough }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Hausaufgabenstatus einer Sitzung; null bedeutet, dass für diesen Termin keine
|
/// Hausaufgabenstatus einer Sitzung; null bedeutet, dass für diesen Termin keine
|
||||||
/// Hausaufgabe erfasst wurde. MissingOpen kann später in MissingOverdue oder SubmittedLate
|
/// Hausaufgabe erfasst wurde. MissingOpen kann später in MissingOverdue oder SubmittedLate
|
||||||
@@ -84,7 +101,7 @@ public class ParticipationSection
|
|||||||
|
|
||||||
public class CompetencyRating
|
public class CompetencyRating
|
||||||
{
|
{
|
||||||
public string Code { get; set; } = "";
|
public Guid ItemId { get; set; }
|
||||||
public int Value { get; set; }
|
public int Value { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -160,3 +177,27 @@ public static class ParticipationRatingScale
|
|||||||
_ => value,
|
_ => value,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Nutzer-Feedback: die Strichliste im Sitzplan (<see cref="ParticipationEntry.RaisedHandCount"/>)
|
||||||
|
/// schlägt direkt eine Quantitätsbewertung vor — wie oft sich jemand meldet, ist ja bereits die
|
||||||
|
/// Quantität. Nur ein Richtwert, kein fester Automatismus: die Lehrkraft übernimmt den Vorschlag
|
||||||
|
/// per Klick oder ignoriert ihn. Bewusst nur für <see cref="AspectValueType.Scale5"/> (der
|
||||||
|
/// Standardtyp des "quantity"-Aspekts) — für individuell umkonfigurierte Aspekttypen gäbe es keine
|
||||||
|
/// sinnvolle, unmissverständliche Abbildung.
|
||||||
|
/// </summary>
|
||||||
|
public static class ParticipationCountSuggestion
|
||||||
|
{
|
||||||
|
public static int? SuggestQuantity(AspectValueType type, int raisedHandCount)
|
||||||
|
{
|
||||||
|
if (type != AspectValueType.Scale5) return null;
|
||||||
|
return raisedHandCount switch
|
||||||
|
{
|
||||||
|
0 => -2,
|
||||||
|
1 => -1,
|
||||||
|
2 or 3 => 0,
|
||||||
|
4 or 5 => 1,
|
||||||
|
_ => 2,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -37,7 +37,7 @@ public class Unit
|
|||||||
public string Title { get; set; } = "";
|
public string Title { get; set; } = "";
|
||||||
public DateOnly? StartDate { get; set; }
|
public DateOnly? StartDate { get; set; }
|
||||||
public DateOnly? EndDate { 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 UnitStatus Status { get; set; } = UnitStatus.Planned;
|
||||||
public string? Notes { get; set; }
|
public string? Notes { get; set; }
|
||||||
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
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
|
/// Optionaler Stundenbeginn — solange kein Stundenplan (Kapitel 4.3) existiert, manuell
|
||||||
/// gepflegt. Dient nur der abgeleiteten Uhrzeit-Anzeige je Phase in <see cref="Phases"/>.
|
/// gepflegt. Dient nur der abgeleiteten Uhrzeit-Anzeige je Phase in <see cref="Phases"/>.
|
||||||
public TimeOnly? StartTime { get; set; }
|
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 List<LessonPhaseStep> Phases { get; set; } = [];
|
||||||
|
public TeachingTimelineState? TeachingTimeline { get; set; }
|
||||||
public string? Homework { get; set; }
|
public string? Homework { get; set; }
|
||||||
/// Markiert, dass die hier eingetragene Hausaufgabe in einer Folgestunde besprochen/kontrolliert
|
/// Markiert, dass die hier eingetragene Hausaufgabe in einer Folgestunde besprochen/kontrolliert
|
||||||
/// wurde — treibt das Stundenplan-Badge "Hausaufgabe kontrollieren" (4.5.4).
|
/// 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).
|
/// wenn die Hausaufgabe absichtlich nicht mehr kontrolliert wird).
|
||||||
public bool HomeworkCheckDismissed { get; set; }
|
public bool HomeworkCheckDismissed { get; set; }
|
||||||
public string? Reflection { 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;
|
public LessonStatus Status { get; set; } = LessonStatus.Planned;
|
||||||
/// Material/Arbeitsblätter sowie fachspezifische Anhänge (z.B. Experiment- und
|
/// Material/Arbeitsblätter sowie fachspezifische Anhänge (z.B. Experiment- und
|
||||||
/// Gefährdungsbeurteilungs-Dokumente im Chemieunterricht) — dieselbe Anhang-Infrastruktur wie
|
/// Gefährdungsbeurteilungs-Dokumente im Chemieunterricht) — dieselbe Anhang-Infrastruktur wie
|
||||||
@@ -89,6 +102,14 @@ public class LessonPhaseStep
|
|||||||
public string Activity { get; set; } = "";
|
public string Activity { get; set; } = "";
|
||||||
public string Material { get; set; } = "";
|
public string Material { get; set; } = "";
|
||||||
public string Shorthand { 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>
|
/// <summary>
|
||||||
/// null = Hauptweg. Sonst Verweis auf einen benannten <see cref="AlternativeLessonPath"/> aus
|
/// null = Hauptweg. Sonst Verweis auf einen benannten <see cref="AlternativeLessonPath"/> aus
|
||||||
/// dem Katalog, über den Phasen alternativer Unterrichtsverläufe zusammengehören —
|
/// dem Katalog, über den Phasen alternativer Unterrichtsverläufe zusammengehören —
|
||||||
@@ -100,7 +121,10 @@ public class LessonPhaseStep
|
|||||||
}
|
}
|
||||||
|
|
||||||
public enum UnitStatus { Planned, Active, Completed }
|
public enum UnitStatus { Planned, Active, Completed }
|
||||||
public enum LessonStatus { Planned, Conducted }
|
// 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, Cancelled = 4 }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Katalogeintrag für einen wiederverwendbaren "alternativen Ablauf" (z.B. "Kurzversion" bei
|
/// Katalogeintrag für einen wiederverwendbaren "alternativen Ablauf" (z.B. "Kurzversion" bei
|
||||||
@@ -236,3 +260,21 @@ public class ReportGrade
|
|||||||
public bool IsLocked { get; set; }
|
public bool IsLocked { get; set; }
|
||||||
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
|
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;
|
||||||
|
}
|
||||||
@@ -93,7 +93,7 @@ public interface IHasAttachments
|
|||||||
List<DocumentAttachment> Attachments { get; }
|
List<DocumentAttachment> Attachments { get; }
|
||||||
}
|
}
|
||||||
// Hinten angefügt, damit die numerischen Werte bereits gespeicherter LiteDB-Einträge stabil bleiben.
|
// Hinten angefügt, damit die numerischen Werte bereits gespeicherter LiteDB-Einträge stabil bleiben.
|
||||||
public enum DocumentationType { Conversation, Incident, SupportPlan, Absence, ParentCall, ParentLetter }
|
public enum DocumentationType { Conversation, Incident, SupportPlan, Absence, ParentCall, ParentLetter, Planning }
|
||||||
public enum SupportStatus { Active, Completed, Paused }
|
public enum SupportStatus { Active, Completed, Paused }
|
||||||
|
|
||||||
public class WorkTask
|
public class WorkTask
|
||||||
|
|||||||
@@ -14,6 +14,13 @@ public class BackupService
|
|||||||
|
|
||||||
public string BackupDirectory => _backupDirectory;
|
public string BackupDirectory => _backupDirectory;
|
||||||
|
|
||||||
|
/// Optionales zweites Sicherungsziel (z.B. USB-Stick, Netzlaufwerk) — Backups liegen sonst
|
||||||
|
/// ausschließlich neben der Live-Datenbank und sind bei einem Plattenausfall oder einem
|
||||||
|
/// versehentlich gelöschten Profilverzeichnis wertlos. Wird von außen gesetzt (Desktop-Settings,
|
||||||
|
/// siehe BackupSettingsService); bewusst best-effort — ist das Ziel beim Sichern nicht
|
||||||
|
/// erreichbar (Stick nicht eingesteckt, Freigabe offline), bleibt nur das Hauptbackup bestehen.
|
||||||
|
public string? SecondaryBackupDirectory { get; set; }
|
||||||
|
|
||||||
public BackupService(string appDataPath)
|
public BackupService(string appDataPath)
|
||||||
{
|
{
|
||||||
_backupDirectory = Path.Combine(appDataPath, "backups");
|
_backupDirectory = Path.Combine(appDataPath, "backups");
|
||||||
@@ -34,9 +41,36 @@ public class BackupService
|
|||||||
File.Copy(databasePath, target, overwrite: true);
|
File.Copy(databasePath, target, overwrite: true);
|
||||||
|
|
||||||
PruneOldBackups(keepCount);
|
PruneOldBackups(keepCount);
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(SecondaryBackupDirectory))
|
||||||
|
TryMirrorToSecondary(target, fileName, keepCount);
|
||||||
|
|
||||||
return target;
|
return target;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void TryMirrorToSecondary(string sourcePath, string fileName, int keepCount)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(SecondaryBackupDirectory!);
|
||||||
|
File.Copy(sourcePath, Path.Combine(SecondaryBackupDirectory!, fileName), overwrite: true);
|
||||||
|
|
||||||
|
foreach (var stale in Directory.GetFiles(SecondaryBackupDirectory!, "lehrerapp-*.db")
|
||||||
|
.Select(p => new FileInfo(p))
|
||||||
|
.OrderByDescending(f => f.LastWriteTime)
|
||||||
|
.Skip(keepCount))
|
||||||
|
{
|
||||||
|
try { stale.Delete(); }
|
||||||
|
catch { /* nächster Lauf versucht es erneut */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// Sicherungsziel nicht erreichbar — das Hauptbackup (_backupDirectory) ist davon
|
||||||
|
// unberührt, ein manuelles/automatisches Backup soll daran nicht scheitern.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public List<BackupInfo> ListBackups() =>
|
public List<BackupInfo> ListBackups() =>
|
||||||
Directory.GetFiles(_backupDirectory, "lehrerapp-*.db")
|
Directory.GetFiles(_backupDirectory, "lehrerapp-*.db")
|
||||||
.Select(p => new BackupInfo(p, File.GetLastWriteTime(p), new FileInfo(p).Length))
|
.Select(p => new BackupInfo(p, File.GetLastWriteTime(p), new FileInfo(p).Length))
|
||||||
|
|||||||
@@ -3,7 +3,8 @@ using LehrerApp.Core.Models;
|
|||||||
namespace LehrerApp.Core.Services;
|
namespace LehrerApp.Core.Services;
|
||||||
|
|
||||||
public sealed record CompetencyScore(
|
public sealed record CompetencyScore(
|
||||||
double AchievedPoints, double MaxPoints, int EvidenceCount, int ParticipantCount)
|
double AchievedPoints, double MaxPoints, int EvidenceCount, int ParticipantCount,
|
||||||
|
int ExamEvidenceCount = 0, int ParticipationEvidenceCount = 0)
|
||||||
{
|
{
|
||||||
public double Percent => MaxPoints <= 0 ? 0 : AchievedPoints / MaxPoints * 100.0;
|
public double Percent => MaxPoints <= 0 ? 0 : AchievedPoints / MaxPoints * 100.0;
|
||||||
}
|
}
|
||||||
@@ -18,6 +19,7 @@ public sealed class CompetencyAnalysisItem
|
|||||||
public int TaughtUnitCount { get; init; }
|
public int TaughtUnitCount { get; init; }
|
||||||
public int PlannedExamCount { get; init; }
|
public int PlannedExamCount { get; init; }
|
||||||
public int AssessedExamCount { get; init; }
|
public int AssessedExamCount { get; init; }
|
||||||
|
public int ParticipationSessionCount { get; init; }
|
||||||
public CompetencyScore? GroupScore { get; init; }
|
public CompetencyScore? GroupScore { get; init; }
|
||||||
public IReadOnlyDictionary<Guid, CompetencyScore> StudentScores { get; init; } =
|
public IReadOnlyDictionary<Guid, CompetencyScore> StudentScores { get; init; } =
|
||||||
new Dictionary<Guid, CompetencyScore>();
|
new Dictionary<Guid, CompetencyScore>();
|
||||||
@@ -29,34 +31,60 @@ public sealed class CompetencyAnalysisService
|
|||||||
IReadOnlyList<CompetencyDomain> catalog,
|
IReadOnlyList<CompetencyDomain> catalog,
|
||||||
IReadOnlyList<Unit> units,
|
IReadOnlyList<Unit> units,
|
||||||
IReadOnlyList<Exam> exams,
|
IReadOnlyList<Exam> exams,
|
||||||
IReadOnlyList<ExamResult> results)
|
IReadOnlyList<ExamResult> results,
|
||||||
|
IReadOnlyList<ParticipationSession>? participationSessions = null,
|
||||||
|
IReadOnlyList<ParticipationEntry>? participationEntries = null,
|
||||||
|
IReadOnlyList<ParticipationAspect>? participationAspects = null)
|
||||||
{
|
{
|
||||||
var builders = new List<ItemBuilder>();
|
var builders = new List<ItemBuilder>();
|
||||||
var 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 domain in catalog.OrderBy(x => x.SortOrder))
|
||||||
foreach (var item in domain.Items.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);
|
var builder = new ItemBuilder(domain.Name, domain.Code, item.Code, item.Description);
|
||||||
builders.Add(builder);
|
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();
|
var description = string.IsNullOrWhiteSpace(reference.Description)
|
||||||
if (byCode.TryGetValue(code, out var existing)) return existing;
|
? "Diese Kompetenz wird noch verwendet, ist aber nicht (mehr) im aktuellen Katalog enthalten."
|
||||||
var added = new ItemBuilder("Nicht im Katalog", "", code,
|
: reference.Description;
|
||||||
"Dieser Kompetenzcode wird noch verwendet, ist aber nicht im aktuellen Katalog enthalten.");
|
|
||||||
byCode[code] = added;
|
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);
|
builders.Add(added);
|
||||||
return added;
|
return added;
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach (var unit in units)
|
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++;
|
if (unit.Status == UnitStatus.Planned) builder.PlannedUnits++;
|
||||||
else builder.TaughtUnits++;
|
else builder.TaughtUnits++;
|
||||||
}
|
}
|
||||||
@@ -64,10 +92,10 @@ public sealed class CompetencyAnalysisService
|
|||||||
var resultsByExam = results.GroupBy(x => x.ExamId).ToDictionary(x => x.Key, x => x.ToList());
|
var resultsByExam = results.GroupBy(x => x.ExamId).ToDictionary(x => x.Key, x => x.ToList());
|
||||||
foreach (var exam in exams)
|
foreach (var exam in exams)
|
||||||
{
|
{
|
||||||
var examCodes = NormalizeCodes(exam.Tasks.SelectMany(x => x.CompetencyCodes));
|
var examReferences = NormalizeReferences(exam.Tasks.SelectMany(x => x.Competencies));
|
||||||
foreach (var code in examCodes)
|
foreach (var reference in examReferences)
|
||||||
{
|
{
|
||||||
var builder = GetOrAdd(code);
|
var builder = GetOrAdd(reference);
|
||||||
if (exam.Status == ExamStatus.Planned) builder.PlannedExams++;
|
if (exam.Status == ExamStatus.Planned) builder.PlannedExams++;
|
||||||
else builder.AssessedExams++;
|
else builder.AssessedExams++;
|
||||||
}
|
}
|
||||||
@@ -81,17 +109,45 @@ public sealed class CompetencyAnalysisService
|
|||||||
var task = exam.Tasks[taskIndex];
|
var task = exam.Tasks[taskIndex];
|
||||||
if (task.MaxPoints <= 0) continue;
|
if (task.MaxPoints <= 0) continue;
|
||||||
var achieved = Math.Clamp(result.Points[taskIndex], 0, task.MaxPoints);
|
var achieved = Math.Clamp(result.Points[taskIndex], 0, task.MaxPoints);
|
||||||
foreach (var code in NormalizeCodes(task.CompetencyCodes))
|
foreach (var reference in NormalizeReferences(task.Competencies))
|
||||||
GetOrAdd(code).AddScore(result.StudentId, achieved, task.MaxPoints);
|
GetOrAdd(reference).AddExamScore(result.StudentId, achieved, task.MaxPoints);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var entriesBySession = (participationEntries ?? [])
|
||||||
|
.GroupBy(x => x.SessionId)
|
||||||
|
.ToDictionary(x => x.Key, x => x.ToList());
|
||||||
|
var aspects = participationAspects ?? [];
|
||||||
|
|
||||||
|
foreach (var session in participationSessions ?? [])
|
||||||
|
{
|
||||||
|
var references = NormalizeReferences(session.Competencies).ToList();
|
||||||
|
foreach (var reference in references)
|
||||||
|
GetOrAdd(reference).ParticipationSessions++;
|
||||||
|
|
||||||
|
if (references.Count == 0 || !entriesBySession.TryGetValue(session.Id, out var entries))
|
||||||
|
continue;
|
||||||
|
|
||||||
|
foreach (var entry in entries)
|
||||||
|
{
|
||||||
|
var estimated = ParticipationCompetencyEstimate.Estimate(
|
||||||
|
entry.Ratings, aspects, entry.DayHighlight);
|
||||||
|
foreach (var reference in references)
|
||||||
|
{
|
||||||
|
var explicitRating = entry.CompetencyRatings
|
||||||
|
.FirstOrDefault(x => x.ItemId == reference.ItemId)?.Value;
|
||||||
|
var rating = explicitRating ?? estimated;
|
||||||
|
if (rating is not null)
|
||||||
|
GetOrAdd(reference).AddParticipationScore(entry.StudentId, rating.Value);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return builders.Select(x => x.Build()).ToList();
|
return builders.Select(x => x.Build()).ToList();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static bool HasCode(string? value) => !string.IsNullOrWhiteSpace(value);
|
private static IEnumerable<CompetencyReference> NormalizeReferences(IEnumerable<CompetencyReference> references) =>
|
||||||
private static IEnumerable<string> NormalizeCodes(IEnumerable<string> codes) =>
|
references.DistinctBy(x => x.ItemId);
|
||||||
codes.Where(HasCode).Select(x => x.Trim()).Distinct(StringComparer.OrdinalIgnoreCase);
|
|
||||||
|
|
||||||
private sealed class ItemBuilder(
|
private sealed class ItemBuilder(
|
||||||
string domainName, string domainCode, string code, string description)
|
string domainName, string domainCode, string code, string description)
|
||||||
@@ -102,14 +158,23 @@ public sealed class CompetencyAnalysisService
|
|||||||
public int TaughtUnits { get; set; }
|
public int TaughtUnits { get; set; }
|
||||||
public int PlannedExams { get; set; }
|
public int PlannedExams { get; set; }
|
||||||
public int AssessedExams { get; set; }
|
public int AssessedExams { get; set; }
|
||||||
|
public int ParticipationSessions { get; set; }
|
||||||
|
|
||||||
public void AddScore(Guid studentId, double achieved, double maximum)
|
public void AddExamScore(Guid studentId, double achieved, double maximum) =>
|
||||||
|
AddScore(studentId, achieved, maximum, isParticipation: false);
|
||||||
|
|
||||||
|
public void AddParticipationScore(Guid studentId, int rating) =>
|
||||||
|
AddScore(studentId, Math.Clamp(rating, -2, 2) + 2, 4, isParticipation: true);
|
||||||
|
|
||||||
|
private void AddScore(Guid studentId, double achieved, double maximum, bool isParticipation)
|
||||||
{
|
{
|
||||||
if (!_scores.TryGetValue(studentId, out var score))
|
if (!_scores.TryGetValue(studentId, out var score))
|
||||||
_scores[studentId] = score = new MutableScore();
|
_scores[studentId] = score = new MutableScore();
|
||||||
score.Achieved += achieved;
|
score.Achieved += achieved;
|
||||||
score.Maximum += maximum;
|
score.Maximum += maximum;
|
||||||
score.EvidenceCount++;
|
score.EvidenceCount++;
|
||||||
|
if (isParticipation) score.ParticipationEvidenceCount++;
|
||||||
|
else score.ExamEvidenceCount++;
|
||||||
}
|
}
|
||||||
|
|
||||||
public CompetencyAnalysisItem Build()
|
public CompetencyAnalysisItem Build()
|
||||||
@@ -118,6 +183,8 @@ public sealed class CompetencyAnalysisService
|
|||||||
var achieved = _scores.Values.Sum(x => x.Achieved);
|
var achieved = _scores.Values.Sum(x => x.Achieved);
|
||||||
var maximum = _scores.Values.Sum(x => x.Maximum);
|
var maximum = _scores.Values.Sum(x => x.Maximum);
|
||||||
var evidence = _scores.Values.Sum(x => x.EvidenceCount);
|
var evidence = _scores.Values.Sum(x => x.EvidenceCount);
|
||||||
|
var examEvidence = _scores.Values.Sum(x => x.ExamEvidenceCount);
|
||||||
|
var participationEvidence = _scores.Values.Sum(x => x.ParticipationEvidenceCount);
|
||||||
return new CompetencyAnalysisItem
|
return new CompetencyAnalysisItem
|
||||||
{
|
{
|
||||||
DomainName = domainName,
|
DomainName = domainName,
|
||||||
@@ -128,8 +195,10 @@ public sealed class CompetencyAnalysisService
|
|||||||
TaughtUnitCount = TaughtUnits,
|
TaughtUnitCount = TaughtUnits,
|
||||||
PlannedExamCount = PlannedExams,
|
PlannedExamCount = PlannedExams,
|
||||||
AssessedExamCount = AssessedExams,
|
AssessedExamCount = AssessedExams,
|
||||||
|
ParticipationSessionCount = ParticipationSessions,
|
||||||
GroupScore = maximum > 0
|
GroupScore = maximum > 0
|
||||||
? new CompetencyScore(achieved, maximum, evidence, _scores.Count)
|
? new CompetencyScore(achieved, maximum, evidence, _scores.Count,
|
||||||
|
examEvidence, participationEvidence)
|
||||||
: null,
|
: null,
|
||||||
StudentScores = studentScores,
|
StudentScores = studentScores,
|
||||||
};
|
};
|
||||||
@@ -141,7 +210,10 @@ public sealed class CompetencyAnalysisService
|
|||||||
public double Achieved { get; set; }
|
public double Achieved { get; set; }
|
||||||
public double Maximum { get; set; }
|
public double Maximum { get; set; }
|
||||||
public int EvidenceCount { get; set; }
|
public int EvidenceCount { get; set; }
|
||||||
|
public int ExamEvidenceCount { get; set; }
|
||||||
|
public int ParticipationEvidenceCount { get; set; }
|
||||||
public CompetencyScore ToScore(int participantCount) =>
|
public CompetencyScore ToScore(int participantCount) =>
|
||||||
new(Achieved, Maximum, EvidenceCount, participantCount);
|
new(Achieved, Maximum, EvidenceCount, participantCount,
|
||||||
|
ExamEvidenceCount, ParticipationEvidenceCount);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -15,6 +15,7 @@ public sealed class CompetencyCatalogImportPreview
|
|||||||
public required Guid SubjectId { get; init; }
|
public required Guid SubjectId { get; init; }
|
||||||
public required string SubjectName { get; init; }
|
public required string SubjectName { get; init; }
|
||||||
public required int GradeLevel { get; init; }
|
public required int GradeLevel { get; init; }
|
||||||
|
public required Guid VersionId { get; init; }
|
||||||
public required List<CompetencyDomain> ImportedDomains { get; init; }
|
public required List<CompetencyDomain> ImportedDomains { get; init; }
|
||||||
public required string ExistingFingerprint { get; init; }
|
public required string ExistingFingerprint { get; init; }
|
||||||
public List<string> Warnings { get; init; } = [];
|
public List<string> Warnings { get; init; } = [];
|
||||||
@@ -28,7 +29,7 @@ public sealed class CompetencyCatalogImportPreview
|
|||||||
public sealed class CompetencyCatalogImportService(ICompetencyDomainRepository repository)
|
public sealed class CompetencyCatalogImportService(ICompetencyDomainRepository repository)
|
||||||
{
|
{
|
||||||
public CompetencyCatalogImportPreview Analyze(
|
public CompetencyCatalogImportPreview Analyze(
|
||||||
string json, Guid subjectId, string subjectName, int gradeLevel)
|
string json, Guid subjectId, string subjectName, int gradeLevel, Guid versionId)
|
||||||
{
|
{
|
||||||
CatalogDto dto;
|
CatalogDto dto;
|
||||||
try
|
try
|
||||||
@@ -100,7 +101,7 @@ public sealed class CompetencyCatalogImportService(ICompetencyDomainRepository r
|
|||||||
if (dto.GradeLevel is > 0 and <= 13 && dto.GradeLevel != gradeLevel)
|
if (dto.GradeLevel is > 0 and <= 13 && dto.GradeLevel != gradeLevel)
|
||||||
warnings.Add($"Die Datei nennt Klassenstufe {dto.GradeLevel}, ausgewählt ist Klassenstufe {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 conflicts = new List<CompetencyCatalogImportConflict>();
|
||||||
var newDomains = 0;
|
var newDomains = 0;
|
||||||
var newItems = 0;
|
var newItems = 0;
|
||||||
@@ -147,6 +148,7 @@ public sealed class CompetencyCatalogImportService(ICompetencyDomainRepository r
|
|||||||
SubjectId = subjectId,
|
SubjectId = subjectId,
|
||||||
SubjectName = subjectName,
|
SubjectName = subjectName,
|
||||||
GradeLevel = gradeLevel,
|
GradeLevel = gradeLevel,
|
||||||
|
VersionId = versionId,
|
||||||
ImportedDomains = imported,
|
ImportedDomains = imported,
|
||||||
ExistingFingerprint = Fingerprint(existing),
|
ExistingFingerprint = Fingerprint(existing),
|
||||||
Warnings = warnings,
|
Warnings = warnings,
|
||||||
@@ -160,7 +162,7 @@ public sealed class CompetencyCatalogImportService(ICompetencyDomainRepository r
|
|||||||
public void Apply(CompetencyCatalogImportPreview preview, CompetencyCatalogImportMode mode,
|
public void Apply(CompetencyCatalogImportPreview preview, CompetencyCatalogImportMode mode,
|
||||||
IReadOnlySet<string>? useImportedConflicts = null)
|
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)
|
if (Fingerprint(current) != preview.ExistingFingerprint)
|
||||||
throw new InvalidOperationException(
|
throw new InvalidOperationException(
|
||||||
"Der Kompetenzkatalog wurde seit der Vorschau verändert. Bitte öffne den Import erneut.");
|
"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()
|
? preview.ImportedDomains.Select((d, index) => CloneAsNew(d, preview.SubjectId, preview.GradeLevel, index)).ToList()
|
||||||
: Merge(current, preview, useImportedConflicts ?? new HashSet<string>());
|
: 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,
|
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,10 +12,13 @@ public sealed class DashboardCardSetting
|
|||||||
/// <summary>Speichert Sichtbarkeit und Reihenfolge der Dashboard-Kacheln lokal.</summary>
|
/// <summary>Speichert Sichtbarkeit und Reihenfolge der Dashboard-Kacheln lokal.</summary>
|
||||||
public sealed class DashboardSettingsService
|
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 =
|
public static readonly string[] DefaultCardOrder =
|
||||||
[
|
[
|
||||||
"today", "tasks", "calendar", "excuses", "upcoming",
|
"today", "tasks", "attention", "calendar", "upcoming", "groups", "examload",
|
||||||
"corrections", "unplanned", "alerts", "attendance", "support", "groups",
|
|
||||||
];
|
];
|
||||||
|
|
||||||
private readonly string _configPath;
|
private readonly string _configPath;
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using LehrerApp.Core.Models;
|
||||||
|
|
||||||
|
namespace LehrerApp.Core.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Zählt eigene Klausuren pro ISO-Kalenderwoche über alle Lerngruppen hinweg. Nutzer-Feedback:
|
||||||
|
/// die klassenbezogene Kollisionsprüfung (mehrere Klausuren einer einzelnen Klasse in einer
|
||||||
|
/// Woche) übernimmt bereits der schulische Klausurplaner (externes Klassenbuch) — was dort
|
||||||
|
/// fehlt, ist die persönliche Belastung der Lehrkraft: mehr eigene Klausuren in derselben Woche
|
||||||
|
/// bedeuten unabhängig von der Klasse mehr Erstellungsaufwand vorher und mehr Korrekturaufwand
|
||||||
|
/// danach. Da eine LiteDB-Datei genau einem Nutzer gehört (siehe CLAUDE.md), sind "alle
|
||||||
|
/// Klausuren in der Datenbank" bereits gleichbedeutend mit "meine Klausuren".
|
||||||
|
/// </summary>
|
||||||
|
public static class ExamWeekLoadService
|
||||||
|
{
|
||||||
|
/// Ab dieser Anzahl eigener Klausuren in derselben Woche gilt die Woche als spürbar belastet.
|
||||||
|
/// Nutzer-Feedback: zwei Klausuren aus zwei unterrichteten Fächern in derselben Woche sind
|
||||||
|
/// normal, eine dritte ist die eigentliche Häufung.
|
||||||
|
public const int WarningThreshold = 3;
|
||||||
|
|
||||||
|
/// Anzahl Klausuren (ohne <paramref name="excludeExamId"/>, z.B. die gerade im Dialog
|
||||||
|
/// bearbeitete), die in dieselbe ISO-Kalenderwoche wie <paramref name="date"/> fallen.
|
||||||
|
public static int CountInSameWeek(IEnumerable<Exam> allExams, DateOnly date, Guid? excludeExamId = null)
|
||||||
|
{
|
||||||
|
var (year, week) = IsoWeek(date);
|
||||||
|
return allExams.Count(e => e.Id != excludeExamId && IsoWeek(e.Date) == (year, week));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Gruppiert die übergebenen Klausuren nach ISO-Kalenderwoche und liefert nur die Wochen mit
|
||||||
|
/// mindestens <see cref="WarningThreshold"/> Klausuren, chronologisch sortiert — für einen
|
||||||
|
/// vorausschauenden Überblick (z.B. Dashboard), nicht für die Einzelprüfung beim Anlegen.
|
||||||
|
public static List<ExamWeekLoad> FindOverloadedWeeks(IEnumerable<Exam> exams) =>
|
||||||
|
exams
|
||||||
|
.GroupBy(e => IsoWeek(e.Date))
|
||||||
|
.Where(g => g.Count() >= WarningThreshold)
|
||||||
|
.Select(g => new ExamWeekLoad(g.Key.Year, g.Key.Week, WeekStart(g.Key.Year, g.Key.Week), g.Count()))
|
||||||
|
.OrderBy(w => w.WeekStart)
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
private static (int Year, int Week) IsoWeek(DateOnly date)
|
||||||
|
{
|
||||||
|
var dt = date.ToDateTime(TimeOnly.MinValue);
|
||||||
|
return (ISOWeek.GetYear(dt), ISOWeek.GetWeekOfYear(dt));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static DateOnly WeekStart(int isoYear, int isoWeek) =>
|
||||||
|
DateOnly.FromDateTime(ISOWeek.ToDateTime(isoYear, isoWeek, DayOfWeek.Monday));
|
||||||
|
}
|
||||||
|
|
||||||
|
public readonly record struct ExamWeekLoad(int IsoYear, int IsoWeek, DateOnly WeekStart, int ExamCount)
|
||||||
|
{
|
||||||
|
public DateOnly WeekEnd => WeekStart.AddDays(6);
|
||||||
|
}
|
||||||
@@ -77,13 +77,29 @@ public class GradingService
|
|||||||
public double WeightedAverage(List<(string Grade, double Weight)> grades)
|
public double WeightedAverage(List<(string Grade, double Weight)> grades)
|
||||||
{
|
{
|
||||||
var numeric = grades
|
var numeric = grades
|
||||||
.Select(g => (Value: int.TryParse(g.Grade, out var n) ? (int?)n : null, g.Weight))
|
.Select(g => (Value: ParseGradeValue(g.Grade), g.Weight))
|
||||||
.Where(g => g.Value.HasValue).ToList();
|
.Where(g => g.Value.HasValue).ToList();
|
||||||
if (numeric.Count == 0) return 0;
|
if (numeric.Count == 0) return 0;
|
||||||
var total = numeric.Sum(g => g.Weight);
|
var total = numeric.Sum(g => g.Weight);
|
||||||
return total == 0 ? 0 : numeric.Sum(g => g.Value!.Value * g.Weight) / total;
|
return total == 0 ? 0 : numeric.Sum(g => g.Value!.Value * g.Weight) / total;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Wandelt eine Notenangabe mit optionaler Tendenz ("3+", "2-") in einen rechnerischen
|
||||||
|
/// Notenwert um. Tendenzen verschieben um ein Drittel in Richtung der besseren Note
|
||||||
|
/// (z.B. "3+" → 2,67, "2-" → 2,33) — der in deutschen Notensystemen übliche Drittelabstand.
|
||||||
|
private static double? ParseGradeValue(string grade)
|
||||||
|
{
|
||||||
|
var trimmed = grade.Trim();
|
||||||
|
if (trimmed.Length == 0) return null;
|
||||||
|
|
||||||
|
var tendency = 0.0;
|
||||||
|
var core = trimmed;
|
||||||
|
if (core.EndsWith('+')) { tendency = -1.0 / 3.0; core = core[..^1].TrimEnd(); }
|
||||||
|
else if (core.EndsWith('-')) { tendency = 1.0 / 3.0; core = core[..^1].TrimEnd(); }
|
||||||
|
|
||||||
|
return int.TryParse(core, out var n) ? n + tendency : null;
|
||||||
|
}
|
||||||
|
|
||||||
/// Rundet einen rechnerischen Notenwert auf eine ganze Note/Punktzahl.
|
/// Rundet einen rechnerischen Notenwert auf eine ganze Note/Punktzahl.
|
||||||
/// "Kaufmännisch" rundet bei genau 0,5 immer vom Nullpunkt weg (Standard).
|
/// "Kaufmännisch" rundet bei genau 0,5 immer vom Nullpunkt weg (Standard).
|
||||||
/// "Pädagogisch" rundet bei genau 0,5 in Richtung der besseren Note
|
/// "Pädagogisch" rundet bei genau 0,5 in Richtung der besseren Note
|
||||||
|
|||||||
@@ -60,6 +60,7 @@ public sealed class GroupRolloverService(
|
|||||||
IsActive = true,
|
IsActive = true,
|
||||||
IsOwnClass = source.IsOwnClass,
|
IsOwnClass = source.IsOwnClass,
|
||||||
IsDifferentiated = source.IsDifferentiated,
|
IsDifferentiated = source.IsDifferentiated,
|
||||||
|
PreviousGroupId = source.Id,
|
||||||
// WebUntisLessonId bewusst nicht übernommen: WebUntis vergibt sie pro Schuljahr neu,
|
// WebUntisLessonId bewusst nicht übernommen: WebUntis vergibt sie pro Schuljahr neu,
|
||||||
// eine übernommene alte lsid würde in der Folgegruppe stumm falsche Fehlzeiten liefern.
|
// eine übernommene alte lsid würde in der Folgegruppe stumm falsche Fehlzeiten liefern.
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,99 @@
|
|||||||
|
using LehrerApp.Core.Interfaces;
|
||||||
|
using LehrerApp.Core.Models;
|
||||||
|
|
||||||
|
namespace LehrerApp.Core.Services;
|
||||||
|
|
||||||
|
/// <summary>Gemeinsame Terminlogik für Verschieben und Trennen von Stunden.</summary>
|
||||||
|
public sealed class LessonSchedulingService(ILessonRepository lessons)
|
||||||
|
{
|
||||||
|
public void Move(Lesson lesson, DateOnly newDate, int? newPeriod, bool shiftFollowing)
|
||||||
|
{
|
||||||
|
EnsureTargetIsFree(lesson, newDate, newPeriod);
|
||||||
|
var oldDate = lesson.Date;
|
||||||
|
var delta = newDate.DayNumber - oldDate.DayNumber;
|
||||||
|
|
||||||
|
if (shiftFollowing && delta != 0)
|
||||||
|
{
|
||||||
|
foreach (var other in lessons.GetByUnit(lesson.UnitId))
|
||||||
|
{
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
lesson.Date = newDate;
|
||||||
|
if (newPeriod.HasValue) lesson.LessonNumber = newPeriod;
|
||||||
|
lessons.Save(lesson);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Lesson SplitAndMoveSecondPart(Lesson source, int splitAfterMinutes, DateOnly newDate,
|
||||||
|
int newPeriod, TimeOnly? newStartTime)
|
||||||
|
{
|
||||||
|
if (splitAfterMinutes <= 0 || source.Phases.Sum(p => p.DurationMinutes) <= splitAfterMinutes)
|
||||||
|
throw new InvalidOperationException("Der Verlauf reicht nicht über die erste Stunde hinaus.");
|
||||||
|
EnsureTargetIsFree(source, newDate, newPeriod);
|
||||||
|
|
||||||
|
var first = new List<LessonPhaseStep>();
|
||||||
|
var second = new List<LessonPhaseStep>();
|
||||||
|
var elapsed = 0;
|
||||||
|
foreach (var phase in source.Phases)
|
||||||
|
{
|
||||||
|
var remainingInFirst = splitAfterMinutes - elapsed;
|
||||||
|
if (remainingInFirst <= 0)
|
||||||
|
second.Add(Clone(phase, phase.DurationMinutes));
|
||||||
|
else if (phase.DurationMinutes <= remainingInFirst)
|
||||||
|
first.Add(Clone(phase, phase.DurationMinutes));
|
||||||
|
else
|
||||||
|
{
|
||||||
|
first.Add(Clone(phase, remainingInFirst));
|
||||||
|
second.Add(Clone(phase, phase.DurationMinutes - remainingInFirst));
|
||||||
|
}
|
||||||
|
elapsed += phase.DurationMinutes;
|
||||||
|
}
|
||||||
|
|
||||||
|
source.Phases = first;
|
||||||
|
var continuation = new Lesson
|
||||||
|
{
|
||||||
|
UnitId = source.UnitId,
|
||||||
|
GroupId = source.GroupId,
|
||||||
|
Date = newDate,
|
||||||
|
LessonNumber = newPeriod,
|
||||||
|
StartTime = newStartTime,
|
||||||
|
Topic = string.IsNullOrWhiteSpace(source.Topic) ? "Fortsetzung" : $"{source.Topic} – Fortsetzung",
|
||||||
|
Phases = second,
|
||||||
|
Homework = source.Homework,
|
||||||
|
HomeworkChecked = source.HomeworkChecked,
|
||||||
|
HomeworkCheckDismissed = source.HomeworkCheckDismissed,
|
||||||
|
Reflection = source.Reflection,
|
||||||
|
Status = source.Status is LessonStatus.Conducted or LessonStatus.Cancelled ? LessonStatus.Draft : source.Status,
|
||||||
|
};
|
||||||
|
source.Homework = null;
|
||||||
|
source.HomeworkChecked = false;
|
||||||
|
source.HomeworkCheckDismissed = false;
|
||||||
|
source.Reflection = null;
|
||||||
|
lessons.Save(source);
|
||||||
|
lessons.Save(continuation);
|
||||||
|
return continuation;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void EnsureTargetIsFree(Lesson source, DateOnly date, int? period)
|
||||||
|
{
|
||||||
|
if (period is null) return;
|
||||||
|
var occupied = lessons.GetByGroupAndDate(source.GroupId, date)
|
||||||
|
.Any(l => l.Id != source.Id && l.LessonNumber == period);
|
||||||
|
if (occupied)
|
||||||
|
throw new InvalidOperationException($"Für die Lerngruppe existiert am {date:dd.MM.yyyy} in der {period}. Stunde bereits eine Planung.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LessonPhaseStep Clone(LessonPhaseStep source, int duration) => new()
|
||||||
|
{
|
||||||
|
Name = source.Name,
|
||||||
|
DurationMinutes = duration,
|
||||||
|
Activity = source.Activity,
|
||||||
|
Material = source.Material,
|
||||||
|
Shorthand = source.Shorthand,
|
||||||
|
AlternativePathId = source.AlternativePathId,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,316 +0,0 @@
|
|||||||
using System.IO.Compression;
|
|
||||||
using System.Text.Json;
|
|
||||||
using System.Xml.Linq;
|
|
||||||
|
|
||||||
namespace LehrerApp.Core.Services;
|
|
||||||
|
|
||||||
public enum TemplateIssueSeverity
|
|
||||||
{
|
|
||||||
Warning,
|
|
||||||
StrongWarning,
|
|
||||||
Error,
|
|
||||||
}
|
|
||||||
|
|
||||||
public sealed record LetterPlaceholder(string Tag, string Description);
|
|
||||||
|
|
||||||
public sealed record TemplateValidationIssue(
|
|
||||||
TemplateIssueSeverity Severity,
|
|
||||||
string Message,
|
|
||||||
string? Tag = null,
|
|
||||||
string? SuggestedTag = null);
|
|
||||||
|
|
||||||
public sealed record TemplateValidationResult(
|
|
||||||
IReadOnlyList<string> Tags,
|
|
||||||
IReadOnlyList<TemplateValidationIssue> Issues)
|
|
||||||
{
|
|
||||||
public bool CanGenerate => Issues.All(i => i.Severity != TemplateIssueSeverity.Error);
|
|
||||||
public bool HasStrongWarnings => Issues.Any(i => i.Severity == TemplateIssueSeverity.StrongWarning);
|
|
||||||
}
|
|
||||||
|
|
||||||
public sealed class LetterTemplateInfo
|
|
||||||
{
|
|
||||||
public Guid Id { get; set; } = Guid.NewGuid();
|
|
||||||
public string Name { get; set; } = "";
|
|
||||||
public string StoredFileName { get; set; } = "";
|
|
||||||
public string OriginalFileName { get; set; } = "";
|
|
||||||
public DateTime ImportedAt { get; set; } = DateTime.UtcNow;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Verwaltet DOCX-Briefvorlagen und befüllt Word-Inhaltssteuerelemente anhand ihres Tags.
|
|
||||||
/// Die Originalvorlage wird nie verändert.
|
|
||||||
/// </summary>
|
|
||||||
public sealed class LetterTemplateService
|
|
||||||
{
|
|
||||||
private static readonly XNamespace W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
|
|
||||||
private static readonly JsonSerializerOptions JsonOptions = new() { WriteIndented = true };
|
|
||||||
|
|
||||||
public static IReadOnlyList<LetterPlaceholder> SupportedPlaceholders { get; } =
|
|
||||||
[
|
|
||||||
new("Student.FirstName", "Vorname des Schülers"),
|
|
||||||
new("Student.LastName", "Nachname des Schülers"),
|
|
||||||
new("Contact.Name", "Name des ausgewählten Kontakts"),
|
|
||||||
new("Contact.Address", "Vollständige Anschrift (mehrzeilig)"),
|
|
||||||
new("Contact.Street", "Straße und Hausnummer"),
|
|
||||||
new("Contact.PostalCode", "Postleitzahl"),
|
|
||||||
new("Contact.City", "Ort"),
|
|
||||||
new("Letter.Salutation", "Gespeicherte Briefanrede des Kontakts"),
|
|
||||||
new("Group.Name", "Ausgewählte Lerngruppe"),
|
|
||||||
new("SchoolYear", "Schuljahr der ausgewählten Gruppe"),
|
|
||||||
new("CurrentDate", "Gewähltes Briefdatum"),
|
|
||||||
];
|
|
||||||
|
|
||||||
private readonly string _templateDirectory;
|
|
||||||
private readonly string _indexPath;
|
|
||||||
|
|
||||||
public LetterTemplateService(string appDataPath)
|
|
||||||
{
|
|
||||||
_templateDirectory = Path.Combine(appDataPath, "letter-templates");
|
|
||||||
_indexPath = Path.Combine(_templateDirectory, "templates.json");
|
|
||||||
Directory.CreateDirectory(_templateDirectory);
|
|
||||||
}
|
|
||||||
|
|
||||||
public IReadOnlyList<LetterTemplateInfo> GetTemplates() => LoadIndex()
|
|
||||||
.OrderBy(t => t.Name, StringComparer.CurrentCultureIgnoreCase)
|
|
||||||
.ToList();
|
|
||||||
|
|
||||||
public string GetTemplatePath(LetterTemplateInfo template) =>
|
|
||||||
Path.Combine(_templateDirectory, template.StoredFileName);
|
|
||||||
|
|
||||||
public LetterTemplateInfo Import(string sourcePath, string? displayName = null)
|
|
||||||
{
|
|
||||||
var validation = Validate(sourcePath);
|
|
||||||
if (!validation.CanGenerate)
|
|
||||||
throw new InvalidDataException(validation.Issues.First(i => i.Severity == TemplateIssueSeverity.Error).Message);
|
|
||||||
|
|
||||||
var templates = LoadIndex();
|
|
||||||
var info = new LetterTemplateInfo
|
|
||||||
{
|
|
||||||
Name = string.IsNullOrWhiteSpace(displayName)
|
|
||||||
? Path.GetFileNameWithoutExtension(sourcePath)
|
|
||||||
: displayName.Trim(),
|
|
||||||
OriginalFileName = Path.GetFileName(sourcePath),
|
|
||||||
};
|
|
||||||
info.StoredFileName = $"{info.Id:N}.docx";
|
|
||||||
File.Copy(sourcePath, GetTemplatePath(info), overwrite: false);
|
|
||||||
templates.Add(info);
|
|
||||||
SaveIndex(templates);
|
|
||||||
return info;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Delete(Guid id)
|
|
||||||
{
|
|
||||||
var templates = LoadIndex();
|
|
||||||
var template = templates.FirstOrDefault(t => t.Id == id);
|
|
||||||
if (template is null) return;
|
|
||||||
var path = GetTemplatePath(template);
|
|
||||||
if (File.Exists(path)) File.Delete(path);
|
|
||||||
templates.Remove(template);
|
|
||||||
SaveIndex(templates);
|
|
||||||
}
|
|
||||||
|
|
||||||
public TemplateValidationResult Validate(LetterTemplateInfo template) =>
|
|
||||||
Validate(GetTemplatePath(template));
|
|
||||||
|
|
||||||
public TemplateValidationResult Validate(string path)
|
|
||||||
{
|
|
||||||
var tags = new List<string>();
|
|
||||||
var issues = new List<TemplateValidationIssue>();
|
|
||||||
|
|
||||||
if (!File.Exists(path))
|
|
||||||
return Error("Die Vorlagendatei wurde nicht gefunden.");
|
|
||||||
if (!string.Equals(Path.GetExtension(path), ".docx", StringComparison.OrdinalIgnoreCase))
|
|
||||||
return Error("Die Vorlage muss eine DOCX-Datei sein.");
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
using var archive = ZipFile.OpenRead(path);
|
|
||||||
var xmlEntries = WordXmlEntries(archive).ToList();
|
|
||||||
if (xmlEntries.All(e => !string.Equals(e.FullName, "word/document.xml", StringComparison.OrdinalIgnoreCase)))
|
|
||||||
return Error("Die Datei ist kein gültiges Word-DOCX-Dokument.");
|
|
||||||
|
|
||||||
foreach (var entry in xmlEntries)
|
|
||||||
{
|
|
||||||
using var stream = entry.Open();
|
|
||||||
var document = XDocument.Load(stream, LoadOptions.PreserveWhitespace);
|
|
||||||
foreach (var control in document.Descendants(W + "sdt"))
|
|
||||||
{
|
|
||||||
var tag = control.Element(W + "sdtPr")?.Element(W + "tag")?.Attribute(W + "val")?.Value?.Trim();
|
|
||||||
if (string.IsNullOrWhiteSpace(tag))
|
|
||||||
{
|
|
||||||
issues.Add(new(TemplateIssueSeverity.StrongWarning,
|
|
||||||
$"Ein Inhaltssteuerelement in {PartLabel(entry.FullName)} besitzt keinen Tag und kann nicht befüllt werden."));
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
tags.Add(tag);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (InvalidDataException)
|
|
||||||
{
|
|
||||||
return Error("Die Datei ist beschädigt oder kein gültiges DOCX-Dokument.");
|
|
||||||
}
|
|
||||||
catch (System.Xml.XmlException)
|
|
||||||
{
|
|
||||||
return Error("Die Word-Vorlage enthält ungültiges XML und kann nicht gelesen werden.");
|
|
||||||
}
|
|
||||||
catch (IOException ex)
|
|
||||||
{
|
|
||||||
return Error($"Die Vorlage konnte nicht geöffnet werden: {ex.Message}");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (tags.Count == 0 && issues.Count == 0)
|
|
||||||
issues.Add(new(TemplateIssueSeverity.Warning,
|
|
||||||
"Die Vorlage enthält keine Inhaltssteuerelemente. Es werden keine Felder befüllt."));
|
|
||||||
|
|
||||||
foreach (var tag in tags.Distinct(StringComparer.Ordinal))
|
|
||||||
{
|
|
||||||
if (SupportedPlaceholders.Any(p => p.Tag == tag)) continue;
|
|
||||||
var suggestion = FindSuggestion(tag);
|
|
||||||
issues.Add(suggestion is null
|
|
||||||
? new(TemplateIssueSeverity.Warning,
|
|
||||||
$"Der unbekannte Tag „{tag}“ wird nicht befüllt.", tag)
|
|
||||||
: new(TemplateIssueSeverity.StrongWarning,
|
|
||||||
$"Wahrscheinlicher Schreibfehler: „{tag}“. Meinten Sie „{suggestion}“?", tag, suggestion));
|
|
||||||
}
|
|
||||||
|
|
||||||
return new(tags.Distinct(StringComparer.Ordinal).OrderBy(t => t).ToList(), issues);
|
|
||||||
|
|
||||||
TemplateValidationResult Error(string message) =>
|
|
||||||
new([], [new(TemplateIssueSeverity.Error, message)]);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Generate(string templatePath, string outputPath,
|
|
||||||
IReadOnlyDictionary<string, string?> values)
|
|
||||||
{
|
|
||||||
var validation = Validate(templatePath);
|
|
||||||
if (!validation.CanGenerate)
|
|
||||||
throw new InvalidDataException(validation.Issues.First(i => i.Severity == TemplateIssueSeverity.Error).Message);
|
|
||||||
|
|
||||||
var outputDirectory = Path.GetDirectoryName(outputPath);
|
|
||||||
if (!string.IsNullOrEmpty(outputDirectory)) Directory.CreateDirectory(outputDirectory);
|
|
||||||
|
|
||||||
using var source = ZipFile.OpenRead(templatePath);
|
|
||||||
using var target = ZipFile.Open(outputPath, ZipArchiveMode.Create);
|
|
||||||
foreach (var entry in source.Entries)
|
|
||||||
{
|
|
||||||
var targetEntry = target.CreateEntry(entry.FullName, CompressionLevel.Optimal);
|
|
||||||
targetEntry.LastWriteTime = entry.LastWriteTime;
|
|
||||||
using var input = entry.Open();
|
|
||||||
using var output = targetEntry.Open();
|
|
||||||
|
|
||||||
if (!IsWordXmlEntry(entry))
|
|
||||||
{
|
|
||||||
input.CopyTo(output);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
var document = XDocument.Load(input, LoadOptions.PreserveWhitespace);
|
|
||||||
foreach (var control in document.Descendants(W + "sdt").ToList())
|
|
||||||
{
|
|
||||||
var tag = control.Element(W + "sdtPr")?.Element(W + "tag")?.Attribute(W + "val")?.Value?.Trim();
|
|
||||||
if (tag is null || !values.TryGetValue(tag, out var value)) continue;
|
|
||||||
ReplaceContent(control.Element(W + "sdtContent"), value ?? "");
|
|
||||||
}
|
|
||||||
document.Save(output, SaveOptions.DisableFormatting);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void ReplaceContent(XElement? content, string value)
|
|
||||||
{
|
|
||||||
if (content is null) return;
|
|
||||||
var paragraph = content.Elements(W + "p").FirstOrDefault();
|
|
||||||
XElement run;
|
|
||||||
|
|
||||||
if (paragraph is not null)
|
|
||||||
{
|
|
||||||
run = paragraph.Descendants(W + "r").FirstOrDefault() ?? new XElement(W + "r");
|
|
||||||
var paragraphProperties = paragraph.Element(W + "pPr");
|
|
||||||
var runProperties = run.Element(W + "rPr") is { } rp ? new XElement(rp) : null;
|
|
||||||
paragraph.RemoveNodes();
|
|
||||||
if (paragraphProperties is not null) paragraph.Add(paragraphProperties);
|
|
||||||
run = new XElement(W + "r");
|
|
||||||
if (runProperties is not null) run.Add(runProperties);
|
|
||||||
paragraph.Add(run);
|
|
||||||
foreach (var extra in content.Elements(W + "p").Skip(1).ToList()) extra.Remove();
|
|
||||||
foreach (var node in content.Nodes().Where(n => n is XElement e && e.Name != W + "p").ToList()) node.Remove();
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
var firstRun = content.Descendants(W + "r").FirstOrDefault();
|
|
||||||
var runProperties = firstRun?.Element(W + "rPr") is { } rp ? new XElement(rp) : null;
|
|
||||||
content.RemoveNodes();
|
|
||||||
run = new XElement(W + "r");
|
|
||||||
if (runProperties is not null) run.Add(runProperties);
|
|
||||||
content.Add(run);
|
|
||||||
}
|
|
||||||
|
|
||||||
var lines = value.Replace("\r\n", "\n", StringComparison.Ordinal).Replace('\r', '\n').Split('\n');
|
|
||||||
for (var i = 0; i < lines.Length; i++)
|
|
||||||
{
|
|
||||||
if (i > 0) run.Add(new XElement(W + "br"));
|
|
||||||
run.Add(new XElement(W + "t", new XAttribute(XNamespace.Xml + "space", "preserve"), lines[i]));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static IEnumerable<ZipArchiveEntry> WordXmlEntries(ZipArchive archive) =>
|
|
||||||
archive.Entries.Where(IsWordXmlEntry);
|
|
||||||
|
|
||||||
private static bool IsWordXmlEntry(ZipArchiveEntry entry) =>
|
|
||||||
entry.FullName.StartsWith("word/", StringComparison.OrdinalIgnoreCase)
|
|
||||||
&& entry.FullName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase);
|
|
||||||
|
|
||||||
private static string PartLabel(string path) => path switch
|
|
||||||
{
|
|
||||||
"word/document.xml" => "Dokumenttext",
|
|
||||||
var p when p.StartsWith("word/header", StringComparison.OrdinalIgnoreCase) => "einer Kopfzeile",
|
|
||||||
var p when p.StartsWith("word/footer", StringComparison.OrdinalIgnoreCase) => "einer Fußzeile",
|
|
||||||
_ => $"dem Dokumentteil „{Path.GetFileName(path)}“",
|
|
||||||
};
|
|
||||||
|
|
||||||
private static string? FindSuggestion(string unknown)
|
|
||||||
{
|
|
||||||
var candidate = SupportedPlaceholders
|
|
||||||
.Select(p => (p.Tag, Distance: Levenshtein(unknown.ToLowerInvariant(), p.Tag.ToLowerInvariant())))
|
|
||||||
.OrderBy(x => x.Distance)
|
|
||||||
.ThenBy(x => x.Tag)
|
|
||||||
.First();
|
|
||||||
var threshold = candidate.Tag.Length >= 12 ? 3 : 2;
|
|
||||||
return candidate.Distance <= threshold ? candidate.Tag : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static int Levenshtein(string left, string right)
|
|
||||||
{
|
|
||||||
var previous = Enumerable.Range(0, right.Length + 1).ToArray();
|
|
||||||
for (var i = 1; i <= left.Length; i++)
|
|
||||||
{
|
|
||||||
var current = new int[right.Length + 1];
|
|
||||||
current[0] = i;
|
|
||||||
for (var j = 1; j <= right.Length; j++)
|
|
||||||
current[j] = Math.Min(Math.Min(current[j - 1] + 1, previous[j] + 1),
|
|
||||||
previous[j - 1] + (left[i - 1] == right[j - 1] ? 0 : 1));
|
|
||||||
previous = current;
|
|
||||||
}
|
|
||||||
return previous[right.Length];
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<LetterTemplateInfo> LoadIndex()
|
|
||||||
{
|
|
||||||
if (!File.Exists(_indexPath)) return [];
|
|
||||||
try
|
|
||||||
{
|
|
||||||
return JsonSerializer.Deserialize<List<LetterTemplateInfo>>(File.ReadAllText(_indexPath), JsonOptions) ?? [];
|
|
||||||
}
|
|
||||||
catch (JsonException)
|
|
||||||
{
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void SaveIndex(List<LetterTemplateInfo> templates)
|
|
||||||
{
|
|
||||||
var temporaryPath = _indexPath + ".tmp";
|
|
||||||
File.WriteAllText(temporaryPath, JsonSerializer.Serialize(templates, JsonOptions));
|
|
||||||
File.Move(temporaryPath, _indexPath, overwrite: true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
using LehrerApp.Core.Models;
|
||||||
|
|
||||||
|
namespace LehrerApp.Core.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Leitet aus den allgemeinen Mitarbeitsaspekten einen Kompetenzwert auf der gemeinsamen
|
||||||
|
/// Skala von -2 bis +2 ab. Explizite Kompetenzbewertungen werden vom Aufrufer bevorzugt.
|
||||||
|
/// </summary>
|
||||||
|
public static class ParticipationCompetencyEstimate
|
||||||
|
{
|
||||||
|
public static int? Estimate(IEnumerable<AspectRating> ratings,
|
||||||
|
IReadOnlyCollection<ParticipationAspect> aspects, DayHighlightKind? dayHighlight)
|
||||||
|
{
|
||||||
|
var aspectsByKey = aspects
|
||||||
|
.GroupBy(x => x.Key, StringComparer.OrdinalIgnoreCase)
|
||||||
|
.ToDictionary(x => x.Key, x => x.Last(), StringComparer.OrdinalIgnoreCase);
|
||||||
|
var normalized = ratings
|
||||||
|
.Where(x => aspectsByKey.ContainsKey(x.Key))
|
||||||
|
.Select(x =>
|
||||||
|
{
|
||||||
|
var aspect = aspectsByKey[x.Key];
|
||||||
|
return ParticipationRatingScale.Normalize(aspect.ValueType, x.Value, aspect.MaxPoints);
|
||||||
|
})
|
||||||
|
.ToList();
|
||||||
|
if (normalized.Count == 0) return null;
|
||||||
|
|
||||||
|
var adjustment = dayHighlight switch
|
||||||
|
{
|
||||||
|
DayHighlightKind.Standout => 1.0,
|
||||||
|
DayHighlightKind.Sleepy or DayHighlightKind.Rough => -1.0,
|
||||||
|
_ => 0.0,
|
||||||
|
};
|
||||||
|
return Math.Clamp((int)Math.Round(normalized.Average() + adjustment,
|
||||||
|
MidpointRounding.AwayFromZero), -2, 2);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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));
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
using LehrerApp.Core.Models;
|
||||||
|
|
||||||
|
namespace LehrerApp.Core.Services;
|
||||||
|
|
||||||
|
/// Welcher der drei Leistungsbereiche (siehe GradingScheme) bei der Zielnoten-Frage der
|
||||||
|
/// gesuchte/unbekannte ist.
|
||||||
|
public enum GradeBucketKind { Exams, Participation, Other }
|
||||||
|
|
||||||
|
public readonly record struct TargetGradeResult(double RequiredAverage, bool IsAchievable);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Beantwortet die Zielnoten-Frage "Was brauche ich noch, um Zeugnisnote X zu erreichen?"
|
||||||
|
/// (Nutzer-Feedback) — kehrt <see cref="GradingService.CalculateReportGrade"/> um: löst nach
|
||||||
|
/// dem Durchschnitt eines gewählten Bereichs auf, der zusammen mit den bekannten Durchschnitten
|
||||||
|
/// der übrigen Bereiche (gewichtet nach <see cref="GradingScheme"/>) genau die Zielnote ergibt.
|
||||||
|
/// Bereiche ohne bekannten Durchschnitt (z.B. noch keine Mitarbeitsnote im Halbjahr) fließen
|
||||||
|
/// nicht in die bekannte Seite der Gleichung ein — exakt dieselbe Normierung wie
|
||||||
|
/// <see cref="GradingService.CalculateReportGrade"/> bei fehlenden Bereichen.
|
||||||
|
/// </summary>
|
||||||
|
public static class ReportGradeTargetCalculator
|
||||||
|
{
|
||||||
|
public static TargetGradeResult? SolveRequiredAverage(double target, GradeBucketKind solveFor,
|
||||||
|
double? examsAverage, double? participationAverage, double? otherAverage,
|
||||||
|
GradingScheme scheme, GradingSystem system)
|
||||||
|
{
|
||||||
|
var solvePercent = solveFor switch
|
||||||
|
{
|
||||||
|
GradeBucketKind.Exams => scheme.ExamsPercent,
|
||||||
|
GradeBucketKind.Participation => scheme.ParticipationPercent,
|
||||||
|
_ => scheme.OtherPercent,
|
||||||
|
};
|
||||||
|
// Dieser Bereich fließt laut Gewichtungsschema gar nicht in die Zeugnisnote ein —
|
||||||
|
// keine Zielnoten-Frage für ihn beantwortbar.
|
||||||
|
if (solvePercent <= 0) return null;
|
||||||
|
|
||||||
|
var known = new List<(double Avg, double Percent)>();
|
||||||
|
if (solveFor != GradeBucketKind.Exams && examsAverage is { } e) known.Add((e, scheme.ExamsPercent));
|
||||||
|
if (solveFor != GradeBucketKind.Participation && participationAverage is { } p) known.Add((p, scheme.ParticipationPercent));
|
||||||
|
if (solveFor != GradeBucketKind.Other && otherAverage is { } o) known.Add((o, scheme.OtherPercent));
|
||||||
|
|
||||||
|
var totalPercent = known.Sum(k => k.Percent) + solvePercent;
|
||||||
|
var knownContribution = known.Sum(k => k.Avg * k.Percent);
|
||||||
|
var required = (target * totalPercent - knownContribution) / solvePercent;
|
||||||
|
|
||||||
|
var (min, max) = system == GradingSystem.Grades1To6 ? (1.0, 6.0) : (0.0, 15.0);
|
||||||
|
return new TargetGradeResult(required, required >= min && required <= max);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -72,18 +72,19 @@ public class UntisDiffService
|
|||||||
|
|
||||||
if (string.Equals(evt.Status, "CANCELLED", StringComparison.OrdinalIgnoreCase))
|
if (string.Equals(evt.Status, "CANCELLED", StringComparison.OrdinalIgnoreCase))
|
||||||
{
|
{
|
||||||
substitutions.Add(mapping.Kind == SubstitutionKind.Lesson
|
if (mapping.Kind == SubstitutionKind.Lesson)
|
||||||
? BuildCancelledLesson(evt.Date, mapping, evt.Uid)
|
substitutions.AddRange(BuildCancelledLessons(evt.Date, mapping, evt.Uid));
|
||||||
: BuildSupervisionNote(evt.Date, mapping, evt.Uid, "Laut WebUntis abgesagt."));
|
else
|
||||||
|
substitutions.Add(BuildSupervisionNote(evt.Date, mapping, evt.Uid, "Laut WebUntis abgesagt."));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (mapping.Kind == SubstitutionKind.Lesson)
|
if (mapping.Kind == SubstitutionKind.Lesson)
|
||||||
{
|
{
|
||||||
if (DeviationReason(evt, mapping) is { } reason)
|
if (DeviationReason(evt, mapping) is { } reason)
|
||||||
substitutions.Add(BuildChangedLesson(evt, mapping, reason));
|
substitutions.AddRange(BuildChangedLessons(evt, mapping, reason));
|
||||||
else
|
else
|
||||||
externalIdsToDelete.Add(evt.Uid); // war ggf. vorher fälschlich als Vertretung erkannt
|
externalIdsToDelete.AddRange(ExternalIdsForPeriods(evt.Uid, mapping)); // ggf. frühere Vertretung entfernen
|
||||||
}
|
}
|
||||||
else if (!regularDutyKeys.Contains((mapping.Weekday, mapping.AfterPeriod!.Value)))
|
else if (!regularDutyKeys.Contains((mapping.Weekday, mapping.AfterPeriod!.Value)))
|
||||||
{
|
{
|
||||||
@@ -143,11 +144,11 @@ public class UntisDiffService
|
|||||||
{
|
{
|
||||||
// War evtl. an einem früheren Poll (noch) als fehlend gemeldet - jetzt
|
// War evtl. an einem früheren Poll (noch) als fehlend gemeldet - jetzt
|
||||||
// wieder im Feed vorhanden, die alte Meldung räumt sich damit selbst ab.
|
// wieder im Feed vorhanden, die alte Meldung räumt sich damit selbst ab.
|
||||||
externalIdsToDelete.Add(BuildMissingExternalId(date, mapping));
|
externalIdsToDelete.AddRange(ExternalIdsForPeriods(BuildMissingExternalId(date, mapping), mapping));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
substitutions.Add(BuildCancelledLesson(date, mapping, BuildMissingExternalId(date, mapping)));
|
substitutions.AddRange(BuildCancelledLessons(date, mapping, BuildMissingExternalId(date, mapping)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -192,19 +193,32 @@ public class UntisDiffService
|
|||||||
private static string RemoveWhitespace(string value) =>
|
private static string RemoveWhitespace(string value) =>
|
||||||
new(value.Where(c => !char.IsWhiteSpace(c)).ToArray());
|
new(value.Where(c => !char.IsWhiteSpace(c)).ToArray());
|
||||||
|
|
||||||
private static SubstitutionEntry BuildCancelledLesson(DateOnly date, UntisSlotMapping mapping, string externalId) => new()
|
private static IEnumerable<SubstitutionEntry> BuildCancelledLessons(DateOnly date, UntisSlotMapping mapping,
|
||||||
|
string externalId) => Periods(mapping).Select((period, index) => new SubstitutionEntry
|
||||||
{
|
{
|
||||||
Date = date, Kind = SubstitutionKind.Cancelled, PeriodNumber = mapping.PeriodNumber,
|
Date = date, Kind = SubstitutionKind.Cancelled, PeriodNumber = period,
|
||||||
Description = "Automatisch über WebUntis-Abgleich erkannt.", ExternalId = externalId,
|
Description = "Automatisch über WebUntis-Abgleich erkannt.",
|
||||||
};
|
ExternalId = PeriodExternalId(externalId, period, index),
|
||||||
|
});
|
||||||
|
|
||||||
private static SubstitutionEntry BuildChangedLesson(UntisIcsEvent evt, UntisSlotMapping mapping, string reason) => new()
|
private static IEnumerable<SubstitutionEntry> BuildChangedLessons(UntisIcsEvent evt, UntisSlotMapping mapping,
|
||||||
|
string reason) => Periods(mapping).Select((period, index) => new SubstitutionEntry
|
||||||
{
|
{
|
||||||
Date = evt.Date, Kind = SubstitutionKind.Lesson, PeriodNumber = mapping.PeriodNumber,
|
Date = evt.Date, Kind = SubstitutionKind.Lesson, PeriodNumber = period,
|
||||||
GroupId = mapping.GroupId, GroupLabel = mapping.ClassToken,
|
GroupId = mapping.GroupId, GroupLabel = mapping.ClassToken,
|
||||||
Description = $"WebUntis: {evt.Summary ?? "?"} · {evt.Location} (regulär: {mapping.Summary ?? "?"}) — {reason}",
|
Description = $"WebUntis: {evt.Summary ?? "?"} · {evt.Location} (regulär: {mapping.Summary ?? "?"}) — {reason}",
|
||||||
ExternalId = evt.Uid,
|
ExternalId = PeriodExternalId(evt.Uid, period, index),
|
||||||
};
|
});
|
||||||
|
|
||||||
|
private static List<int> Periods(UntisSlotMapping mapping) => mapping.CoveredPeriods.Count > 0
|
||||||
|
? mapping.CoveredPeriods.Distinct().Order().ToList()
|
||||||
|
: mapping.PeriodNumber is { } period ? [period] : [];
|
||||||
|
|
||||||
|
private static IEnumerable<string> ExternalIdsForPeriods(string externalId, UntisSlotMapping mapping) =>
|
||||||
|
Periods(mapping).Select((period, index) => PeriodExternalId(externalId, period, index));
|
||||||
|
|
||||||
|
private static string PeriodExternalId(string externalId, int period, int index) =>
|
||||||
|
index == 0 ? externalId : $"{externalId}-period-{period}";
|
||||||
|
|
||||||
// Aufsichten haben keinen TimetableSlot im Hintergrund (siehe SubstitutionEntry.Kind-Doc) -
|
// Aufsichten haben keinen TimetableSlot im Hintergrund (siehe SubstitutionEntry.Kind-Doc) -
|
||||||
// deshalb Kind=Supervision statt Cancelled, auch wenn der Termin verschwunden ist.
|
// deshalb Kind=Supervision statt Cancelled, auch wenn der Termin verschwunden ist.
|
||||||
|
|||||||
@@ -123,7 +123,7 @@ public sealed class ChangeHookCascadeTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void CompetencyDomainRepository_ReplaceForSubjectAndGrade_LoestDeleteFuerAlteUndSaveFuerNeueAus()
|
public void CompetencyDomainRepository_ReplaceForSubjectGradeAndVersion_LoestDeleteFuerAlteUndSaveFuerNeueAus()
|
||||||
{
|
{
|
||||||
using var db = NewInMemoryContext();
|
using var db = NewInMemoryContext();
|
||||||
var repo = new CompetencyDomainRepository(db);
|
var repo = new CompetencyDomainRepository(db);
|
||||||
@@ -132,7 +132,7 @@ public sealed class ChangeHookCascadeTests
|
|||||||
var calls = new List<(string EntityType, string Operation)>();
|
var calls = new List<(string EntityType, string Operation)>();
|
||||||
db.OnChange = (type, id, op, payload) => calls.Add((type, op));
|
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 1" },
|
||||||
new CompetencyDomain { Name = "Neu 2" },
|
new CompetencyDomain { Name = "Neu 2" },
|
||||||
@@ -145,7 +145,7 @@ public sealed class ChangeHookCascadeTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void CompetencyDomainRepository_DeleteBySubjectAndGrade_LoestEinEreignisProDomaenAus()
|
public void CompetencyDomainRepository_DeleteBySubjectGradeAndVersion_LoestEinEreignisProDomaenAus()
|
||||||
{
|
{
|
||||||
using var db = NewInMemoryContext();
|
using var db = NewInMemoryContext();
|
||||||
var repo = new CompetencyDomainRepository(db);
|
var repo = new CompetencyDomainRepository(db);
|
||||||
@@ -155,7 +155,7 @@ public sealed class ChangeHookCascadeTests
|
|||||||
var calls = new List<(string EntityType, string Operation)>();
|
var calls = new List<(string EntityType, string Operation)>();
|
||||||
db.OnChange = (type, id, op, payload) => calls.Add((type, op));
|
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.Equal(2, calls.Count);
|
||||||
Assert.All(calls, c => Assert.Equal((nameof(CompetencyDomain), "Delete"), c));
|
Assert.All(calls, c => Assert.Equal((nameof(CompetencyDomain), "Delete"), c));
|
||||||
@@ -193,4 +193,21 @@ public sealed class ChangeHookCascadeTests
|
|||||||
var call = Assert.Single(calls);
|
var call = Assert.Single(calls);
|
||||||
Assert.Equal((nameof(Documentation), "Delete"), call);
|
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));
|
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 =>
|
yield return Case("ShorthandCode", nameof(ShorthandCode), db =>
|
||||||
{
|
{
|
||||||
var repo = new ShorthandCodeRepository(db);
|
var repo = new ShorthandCodeRepository(db);
|
||||||
|
|||||||
@@ -57,4 +57,24 @@ public sealed class ChangeHookTests
|
|||||||
|
|
||||||
Assert.Null(exception);
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -26,6 +26,38 @@ public sealed class DatabaseEncryptionServiceTests
|
|||||||
Assert.False(service.IsEncrypted(temp.Path));
|
Assert.False(service.IsEncrypted(temp.Path));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Regression: SettingsViewModel ruft IsEncrypted/VerifyPassword mit dem Pfad der bereits
|
||||||
|
/// laufenden Datenbank auf, während LiteDbContext deren Shared-Verbindung noch offen hält
|
||||||
|
/// (z.B. bei jedem Öffnen der Einstellungen). Eine zweite Verbindung im Standard-Modus
|
||||||
|
/// (Direct) würde das mit "The process cannot access the file" quittieren.
|
||||||
|
[Fact]
|
||||||
|
public void IsEncrypted_WaehrendAndereSharedVerbindungOffenIst_WirftNicht()
|
||||||
|
{
|
||||||
|
using var temp = new TempDatabase();
|
||||||
|
using (var db = new LiteDatabase(temp.Path))
|
||||||
|
db.GetCollection<BsonDocument>("t").Insert(new BsonDocument { ["x"] = 1 });
|
||||||
|
using var open = new LiteDatabase(new ConnectionString(temp.Path) { Connection = ConnectionType.Shared });
|
||||||
|
|
||||||
|
var service = new DatabaseEncryptionService();
|
||||||
|
|
||||||
|
Assert.False(service.IsEncrypted(temp.Path));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void VerifyPassword_WaehrendAndereSharedVerbindungOffenIst_WirftNicht()
|
||||||
|
{
|
||||||
|
using var temp = new TempDatabase();
|
||||||
|
using (var db = new LiteDatabase(temp.Path))
|
||||||
|
db.GetCollection<BsonDocument>("t").Insert(new BsonDocument { ["x"] = 1 });
|
||||||
|
var service = new DatabaseEncryptionService();
|
||||||
|
service.SetPassword(temp.Path, currentPassword: null, newPassword: "geheim123");
|
||||||
|
using var open = new LiteDatabase(new ConnectionString(temp.Path)
|
||||||
|
{ Password = "geheim123", Connection = ConnectionType.Shared });
|
||||||
|
|
||||||
|
Assert.True(service.VerifyPassword(temp.Path, "geheim123"));
|
||||||
|
Assert.False(service.VerifyPassword(temp.Path, "falsch"));
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void SetPassword_VerschluesseltDieDatenbankUndBehaeltDieDaten()
|
public void SetPassword_VerschluesseltDieDatenbankUndBehaeltDieDaten()
|
||||||
{
|
{
|
||||||
@@ -60,6 +92,65 @@ public sealed class DatabaseEncryptionServiceTests
|
|||||||
Assert.Single(reopened.GetCollection<BsonDocument>("t").FindAll());
|
Assert.Single(reopened.GetCollection<BsonDocument>("t").FindAll());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void CanOpenAndRead_OhneVorhandeneDatei_GibtFalseZurueck()
|
||||||
|
{
|
||||||
|
using var temp = new TempDatabase();
|
||||||
|
var service = new DatabaseEncryptionService();
|
||||||
|
|
||||||
|
Assert.False(service.CanOpenAndRead(temp.Path, null));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void CanOpenAndRead_GueltigeUnverschluesselteDatenbank_GibtTrueZurueck()
|
||||||
|
{
|
||||||
|
using var temp = new TempDatabase();
|
||||||
|
using (var db = new LiteDatabase(temp.Path))
|
||||||
|
db.GetCollection<BsonDocument>("t").Insert(new BsonDocument { ["x"] = 1 });
|
||||||
|
|
||||||
|
var service = new DatabaseEncryptionService();
|
||||||
|
|
||||||
|
Assert.True(service.CanOpenAndRead(temp.Path, null));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void CanOpenAndRead_GueltigeVerschluesselteDatenbankMitRichtigemPasswort_GibtTrueZurueck()
|
||||||
|
{
|
||||||
|
using var temp = new TempDatabase();
|
||||||
|
using (var db = new LiteDatabase(new ConnectionString(temp.Path) { Password = "geheim123" }))
|
||||||
|
db.GetCollection<BsonDocument>("t").Insert(new BsonDocument { ["x"] = 1 });
|
||||||
|
|
||||||
|
var service = new DatabaseEncryptionService();
|
||||||
|
|
||||||
|
Assert.True(service.CanOpenAndRead(temp.Path, "geheim123"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void CanOpenAndRead_FalschesPasswort_GibtFalseZurueck()
|
||||||
|
{
|
||||||
|
using var temp = new TempDatabase();
|
||||||
|
using (var db = new LiteDatabase(new ConnectionString(temp.Path) { Password = "geheim123" }))
|
||||||
|
db.GetCollection<BsonDocument>("t").Insert(new BsonDocument { ["x"] = 1 });
|
||||||
|
|
||||||
|
var service = new DatabaseEncryptionService();
|
||||||
|
|
||||||
|
Assert.False(service.CanOpenAndRead(temp.Path, "falsch"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void CanOpenAndRead_BeschaedigteDatei_GibtFalseZurueck()
|
||||||
|
{
|
||||||
|
using var temp = new TempDatabase();
|
||||||
|
// Eine kurze Textdatei initialisiert LiteDB stillschweigend als neue, leere Datenbank
|
||||||
|
// (kleiner als eine Seite) — erst genug Datenmüll jenseits der Seitengröße lässt das
|
||||||
|
// Datei-Layout tatsächlich fehlschlagen und simuliert eine echte Beschädigung
|
||||||
|
// (z.B. durch einen vollen Datenträger während der Backup-Kopie).
|
||||||
|
File.WriteAllBytes(temp.Path, Enumerable.Repeat((byte)0x42, 32_768).ToArray());
|
||||||
|
var service = new DatabaseEncryptionService();
|
||||||
|
|
||||||
|
Assert.False(service.CanOpenAndRead(temp.Path, null));
|
||||||
|
}
|
||||||
|
|
||||||
private sealed class TempDatabase : IDisposable
|
private sealed class TempDatabase : IDisposable
|
||||||
{
|
{
|
||||||
private readonly string _directory = System.IO.Path.Combine(
|
private readonly string _directory = System.IO.Path.Combine(
|
||||||
|
|||||||
@@ -121,7 +121,7 @@ public sealed class LiteDbContextTests
|
|||||||
using var temp = new TempDatabase();
|
using var temp = new TempDatabase();
|
||||||
using var context = new LiteDbContext(temp.Path);
|
using var context = new LiteDbContext(temp.Path);
|
||||||
|
|
||||||
Assert.Equal(4, context.SchemaVersion);
|
Assert.Equal(6, context.SchemaVersion);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -132,7 +132,139 @@ public sealed class LiteDbContextTests
|
|||||||
|
|
||||||
using var second = new LiteDbContext(temp.Path);
|
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]
|
[Fact]
|
||||||
|
|||||||
@@ -715,6 +715,67 @@ public sealed class RepositoryTests
|
|||||||
Assert.Null(storage.OpenRead(attachmentId));
|
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 ──────────────────────────────────────────────────────
|
// ── LessonRepository ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -1188,4 +1249,93 @@ public sealed class RepositoryTests
|
|||||||
Assert.Equal(studentId, item.StudentId);
|
Assert.Equal(studentId, item.StudentId);
|
||||||
Assert.True(item.IsDone);
|
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));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -10,12 +10,21 @@ namespace LehrerApp.Data;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public class DatabaseEncryptionService
|
public class DatabaseEncryptionService
|
||||||
{
|
{
|
||||||
|
// Beide Methoden werden auch gegen den Pfad der laufenden, bereits geöffneten Datenbank
|
||||||
|
// aufgerufen (z.B. bei jedem Öffnen der Einstellungen bzw. vor einer Passwort-Änderung) -
|
||||||
|
// LiteDbContext hält dafür längst eine ConnectionType.Shared-Verbindung offen. Ohne Shared
|
||||||
|
// hier ebenfalls zu setzen, würde die zweite Verbindung im Standard-Modus (Direct) einen
|
||||||
|
// exklusiven Dateizugriff verlangen und mit "The process cannot access the file" scheitern.
|
||||||
public bool IsEncrypted(string dbPath)
|
public bool IsEncrypted(string dbPath)
|
||||||
{
|
{
|
||||||
if (!File.Exists(dbPath)) return false;
|
if (!File.Exists(dbPath)) return false;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
using var db = new LiteDatabase(dbPath);
|
// Shared-Verbindungen öffnen die Datei lazy - anders als Direct wirft der Konstruktor
|
||||||
|
// bei falschem/fehlendem Passwort noch nicht, erst ein tatsächlicher Zugriff liest den
|
||||||
|
// (ggf. verschlüsselten) Header.
|
||||||
|
using var db = new LiteDatabase(new ConnectionString(dbPath) { Connection = ConnectionType.Shared });
|
||||||
|
_ = db.GetCollectionNames().ToList();
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
catch (LiteException)
|
catch (LiteException)
|
||||||
@@ -28,7 +37,9 @@ public class DatabaseEncryptionService
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
using var db = new LiteDatabase(new ConnectionString(dbPath) { Password = password });
|
using var db = new LiteDatabase(new ConnectionString(dbPath)
|
||||||
|
{ Password = password, Connection = ConnectionType.Shared });
|
||||||
|
_ = db.GetCollectionNames().ToList();
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
catch (LiteException)
|
catch (LiteException)
|
||||||
@@ -37,6 +48,29 @@ public class DatabaseEncryptionService
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Öffnet die Datei probeweise und liest die Sammlungsliste, um eine strukturell gültige
|
||||||
|
/// (nicht nur vorhandene) LiteDB-Datei zu bestätigen — z.B. direkt nach dem Anlegen eines
|
||||||
|
/// Backups, das durch einen vollen Datenträger oder einen vorzeitig entfernten USB-Stick
|
||||||
|
/// beschädigt worden sein könnte. Bewusst breites Catch: jede Art von Fehlschlag beim Öffnen
|
||||||
|
/// oder Lesen bedeutet hier "Backup nicht verifizierbar", nicht nur ein falsches Passwort.
|
||||||
|
public bool CanOpenAndRead(string dbPath, string? password)
|
||||||
|
{
|
||||||
|
if (!File.Exists(dbPath)) return false;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var connection = password is null
|
||||||
|
? new ConnectionString(dbPath)
|
||||||
|
: new ConnectionString(dbPath) { Password = password };
|
||||||
|
using var db = new LiteDatabase(connection);
|
||||||
|
_ = db.GetCollectionNames().ToList();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Setzt (newPassword != null), ändert oder entfernt (newPassword == null) das
|
/// Setzt (newPassword != null), ändert oder entfernt (newPassword == null) das
|
||||||
/// Passwort der Datenbank. Der Aufrufer muss sicherstellen, dass keine andere
|
/// Passwort der Datenbank. Der Aufrufer muss sicherstellen, dass keine andere
|
||||||
/// Verbindung (z.B. der laufende <see cref="LiteDbContext"/>) die Datei offen hält.
|
/// Verbindung (z.B. der laufende <see cref="LiteDbContext"/>) die Datei offen hält.
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ public class LiteDbContext : IDisposable
|
|||||||
/// Aktuelle Schema-Version. Migrationsschritte werden versioniert unter
|
/// Aktuelle Schema-Version. Migrationsschritte werden versioniert unter
|
||||||
/// <see cref="RunVersionedMigrations"/> ergänzt, statt bei jedem Start erneut
|
/// <see cref="RunVersionedMigrations"/> ergänzt, statt bei jedem Start erneut
|
||||||
/// (idempotent, aber unnötig) über alle Daten zu laufen.
|
/// (idempotent, aber unnötig) über alle Daten zu laufen.
|
||||||
private const int CurrentSchemaVersion = 4;
|
private const int CurrentSchemaVersion = 6;
|
||||||
|
|
||||||
private readonly LiteDatabase _db;
|
private readonly LiteDatabase _db;
|
||||||
|
|
||||||
@@ -51,6 +51,7 @@ public class LiteDbContext : IDisposable
|
|||||||
public ILiteCollection<Unit> Units => _db.GetCollection<Unit>("units");
|
public ILiteCollection<Unit> Units => _db.GetCollection<Unit>("units");
|
||||||
public ILiteCollection<Lesson> Lessons => _db.GetCollection<Lesson>("lessons");
|
public ILiteCollection<Lesson> Lessons => _db.GetCollection<Lesson>("lessons");
|
||||||
public ILiteCollection<Documentation> Documentation => _db.GetCollection<Documentation>("documentation");
|
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 ILiteStorage<string> Attachments => _db.GetStorage<string>("attachments", "attachments_chunks");
|
||||||
public ILiteCollection<WorkTask> Tasks => _db.GetCollection<WorkTask>("tasks");
|
public ILiteCollection<WorkTask> Tasks => _db.GetCollection<WorkTask>("tasks");
|
||||||
public ILiteCollection<TimeEntry> TimeEntries => _db.GetCollection<TimeEntry>("time_entries");
|
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<ParticipationSection> ParticipationSections => _db.GetCollection<ParticipationSection>("participation_sections");
|
||||||
public ILiteCollection<Subject> Subjects => _db.GetCollection<Subject>("subjects");
|
public ILiteCollection<Subject> Subjects => _db.GetCollection<Subject>("subjects");
|
||||||
public ILiteCollection<CompetencyDomain> CompetencyDomains => _db.GetCollection<CompetencyDomain>("competency_domains");
|
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<ShorthandCode> ShorthandCodes => _db.GetCollection<ShorthandCode>("shorthand_codes");
|
||||||
public ILiteCollection<AlternativeLessonPath> AlternativeLessonPaths => _db.GetCollection<AlternativeLessonPath>("alternative_lesson_paths");
|
public ILiteCollection<AlternativeLessonPath> AlternativeLessonPaths => _db.GetCollection<AlternativeLessonPath>("alternative_lesson_paths");
|
||||||
public ILiteCollection<TimetableSlot> TimetableSlots => _db.GetCollection<TimetableSlot>("timetable_slots");
|
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<UntisAbsenceCacheEntry> UntisAbsenceCache => _db.GetCollection<UntisAbsenceCacheEntry>("untis_absence_cache");
|
||||||
public ILiteCollection<UntisClassRegisterCacheEntry> UntisClassRegisterCache => _db.GetCollection<UntisClassRegisterCacheEntry>("untis_classregister_cache");
|
public ILiteCollection<UntisClassRegisterCacheEntry> UntisClassRegisterCache => _db.GetCollection<UntisClassRegisterCacheEntry>("untis_classregister_cache");
|
||||||
public ILiteCollection<UntisCacheFetchState> UntisCacheFetchStates => _db.GetCollection<UntisCacheFetchState>("untis_cache_fetch_state");
|
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<UntisStudentRosterCacheEntry> UntisStudentRosterCache => _db.GetCollection<UntisStudentRosterCacheEntry>("untis_student_roster_cache");
|
||||||
public ILiteCollection<AnnualPlanEvent> AnnualPlanEvents => _db.GetCollection<AnnualPlanEvent>("annual_plan_events");
|
public ILiteCollection<AnnualPlanEvent> AnnualPlanEvents => _db.GetCollection<AnnualPlanEvent>("annual_plan_events");
|
||||||
public ILiteCollection<TrashedItem> TrashedItems => _db.GetCollection<TrashedItem>("trash");
|
public ILiteCollection<TrashedItem> TrashedItems => _db.GetCollection<TrashedItem>("trash");
|
||||||
@@ -260,6 +263,16 @@ public class LiteDbContext : IDisposable
|
|||||||
MigrateLessonAlternativePaths();
|
MigrateLessonAlternativePaths();
|
||||||
version = 4;
|
version = 4;
|
||||||
}
|
}
|
||||||
|
if (version < 5)
|
||||||
|
{
|
||||||
|
MigrateCompetencyCatalogVersions();
|
||||||
|
version = 5;
|
||||||
|
}
|
||||||
|
if (version < 6)
|
||||||
|
{
|
||||||
|
MigrateCompetencyReferences();
|
||||||
|
version = 6;
|
||||||
|
}
|
||||||
WriteSchemaVersion(version);
|
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()
|
private void EnsureIndexes()
|
||||||
{
|
{
|
||||||
Students.EnsureIndex(x => x.LastName);
|
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);
|
Subjects.EnsureIndex("ux_subject_name", BsonExpression.Create("LOWER(TRIM($.Name))"), unique: true);
|
||||||
CompetencyDomains.EnsureIndex(x => x.SubjectId);
|
CompetencyDomains.EnsureIndex(x => x.SubjectId);
|
||||||
CompetencyDomains.EnsureIndex(x => x.GradeLevel);
|
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);
|
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);
|
AlternativeLessonPaths.EnsureIndex("ux_alt_lesson_path_name", BsonExpression.Create("LOWER(TRIM($.Name))"), unique: true);
|
||||||
TimetableSlots.EnsureIndex(x => x.GroupId);
|
TimetableSlots.EnsureIndex(x => x.GroupId);
|
||||||
|
|||||||
@@ -357,6 +357,20 @@ public class UnitRepository(LiteDbContext db) : IUnitRepository
|
|||||||
public void Save(Unit u)
|
public void Save(Unit u)
|
||||||
{
|
{
|
||||||
ArchivedGroupWriteGuard.EnsureActive(db, u.GroupId);
|
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;
|
u.UpdatedAt = DateTime.UtcNow;
|
||||||
db.Units.Upsert(u);
|
db.Units.Upsert(u);
|
||||||
db.OnChange?.Invoke(nameof(Unit), u.Id.ToString(), "Save", 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 class LessonRepository(LiteDbContext db) : ILessonRepository
|
||||||
{
|
{
|
||||||
|
public Lesson? GetById(Guid id) => db.Lessons.FindById(id);
|
||||||
public List<Lesson> GetByUnit(Guid id) =>
|
public List<Lesson> GetByUnit(Guid id) =>
|
||||||
db.Lessons.Find(l => l.UnitId == id).OrderBy(l => l.Date).ThenBy(l => l.LessonNumber).ToList();
|
db.Lessons.Find(l => l.UnitId == id).OrderBy(l => l.Date).ThenBy(l => l.LessonNumber).ToList();
|
||||||
public List<Lesson> GetByGroupAndDate(Guid gid, DateOnly date) =>
|
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 class WorkTaskRepository(LiteDbContext db) : IWorkTaskRepository
|
||||||
{
|
{
|
||||||
public List<WorkTask> GetByStatus(WorkTaskStatus s) =>
|
public List<WorkTask> GetByStatus(WorkTaskStatus s) =>
|
||||||
@@ -492,6 +538,7 @@ public class ParticipationSessionRepository(LiteDbContext db) : IParticipationSe
|
|||||||
public List<ParticipationSession> GetByGroup(Guid groupId) =>
|
public List<ParticipationSession> GetByGroup(Guid groupId) =>
|
||||||
db.ParticipationSessions.Find(s => s.GroupId == groupId).OrderByDescending(s => s.Date).ToList();
|
db.ParticipationSessions.Find(s => s.GroupId == groupId).OrderByDescending(s => s.Date).ToList();
|
||||||
public ParticipationSession? GetById(Guid id) => db.ParticipationSessions.FindById(id);
|
public ParticipationSession? GetById(Guid id) => db.ParticipationSessions.FindById(id);
|
||||||
|
public List<ParticipationSession> GetAll() => db.ParticipationSessions.FindAll().ToList();
|
||||||
public void Save(ParticipationSession s)
|
public void Save(ParticipationSession s)
|
||||||
{
|
{
|
||||||
ArchivedGroupWriteGuard.EnsureActive(db, s.GroupId);
|
ArchivedGroupWriteGuard.EnsureActive(db, s.GroupId);
|
||||||
@@ -623,8 +670,9 @@ public class SubjectRepository(LiteDbContext db) : ISubjectRepository
|
|||||||
}
|
}
|
||||||
public void Delete(Guid id)
|
public void Delete(Guid id)
|
||||||
{
|
{
|
||||||
if (db.Groups.Exists(g => g.SubjectId == id) || db.CompetencyDomains.Exists(d => d.SubjectId == 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.");
|
|| 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.Subjects.Delete(id);
|
||||||
db.OnChange?.Invoke(nameof(Subject), id.ToString(), "Delete", null);
|
db.OnChange?.Invoke(nameof(Subject), id.ToString(), "Delete", null);
|
||||||
}
|
}
|
||||||
@@ -853,13 +901,33 @@ public class UntisCacheFetchStateRepository(LiteDbContext db) : IUntisCacheFetch
|
|||||||
public void Save(UntisCacheFetchState state) => db.UntisCacheFetchStates.Upsert(state);
|
public void Save(UntisCacheFetchState state) => db.UntisCacheFetchStates.Upsert(state);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public class 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 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
|
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)
|
.OrderBy(d => d.SortOrder)
|
||||||
.ToList();
|
.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 CompetencyDomain? GetById(Guid id) => db.CompetencyDomains.FindById(id);
|
||||||
public void Save(CompetencyDomain d)
|
public void Save(CompetencyDomain d)
|
||||||
{
|
{
|
||||||
@@ -872,22 +940,22 @@ public class CompetencyDomainRepository(LiteDbContext db) : ICompetencyDomainRep
|
|||||||
db.CompetencyDomains.Delete(id);
|
db.CompetencyDomains.Delete(id);
|
||||||
db.OnChange?.Invoke(nameof(CompetencyDomain), id.ToString(), "Delete", null);
|
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
|
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())
|
.ToList())
|
||||||
{
|
{
|
||||||
db.CompetencyDomains.Delete(d.Id);
|
db.CompetencyDomains.Delete(d.Id);
|
||||||
db.OnChange?.Invoke(nameof(CompetencyDomain), d.Id.ToString(), "Delete", null);
|
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(() =>
|
db.ExecuteInTransaction(() =>
|
||||||
{
|
{
|
||||||
foreach (var domain in db.CompetencyDomains
|
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.CompetencyDomains.Delete(domain.Id);
|
||||||
db.OnChange?.Invoke(nameof(CompetencyDomain), domain.Id.ToString(), "Delete", null);
|
db.OnChange?.Invoke(nameof(CompetencyDomain), domain.Id.ToString(), "Delete", null);
|
||||||
@@ -897,6 +965,7 @@ public class CompetencyDomainRepository(LiteDbContext db) : ICompetencyDomainRep
|
|||||||
{
|
{
|
||||||
domain.SubjectId = subjectId;
|
domain.SubjectId = subjectId;
|
||||||
domain.GradeLevel = gradeLevel;
|
domain.GradeLevel = gradeLevel;
|
||||||
|
domain.VersionId = versionId;
|
||||||
domain.UpdatedAt = now;
|
domain.UpdatedAt = now;
|
||||||
db.CompetencyDomains.Upsert(domain);
|
db.CompetencyDomains.Upsert(domain);
|
||||||
db.OnChange?.Invoke(nameof(CompetencyDomain), domain.Id.ToString(), "Save", domain);
|
db.OnChange?.Invoke(nameof(CompetencyDomain), domain.Id.ToString(), "Save", domain);
|
||||||
@@ -905,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
|
/// <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
|
/// 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>
|
/// "Fehlklick sofort rückgängig machen"-Werkzeug, kein geräteübergreifendes Archiv.</summary>
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
using LehrerApp.Core.AiPlanning;
|
using LehrerApp.Core.AiPlanning;
|
||||||
using LehrerApp.Core.Models;
|
using LehrerApp.Core.Models;
|
||||||
using LehrerApp.Desktop.Services;
|
using LehrerApp.Desktop.Services;
|
||||||
|
using LehrerApp.Desktop.ViewModels.Groups;
|
||||||
|
using System.Net;
|
||||||
|
using System.Text;
|
||||||
using Xunit;
|
using Xunit;
|
||||||
|
|
||||||
namespace LehrerApp.Desktop.Tests;
|
namespace LehrerApp.Desktop.Tests;
|
||||||
@@ -12,8 +15,202 @@ namespace LehrerApp.Desktop.Tests;
|
|||||||
public sealed class AiPlanningServiceTests
|
public sealed class AiPlanningServiceTests
|
||||||
{
|
{
|
||||||
private static AiPlanningService Build(FakeLessons lessons, FakeGroups groups, FakeSubjects subjects,
|
private static AiPlanningService Build(FakeLessons lessons, FakeGroups groups, FakeSubjects subjects,
|
||||||
FakeCompetencyDomains competencyDomains, FakeAlternativeLessonPaths altPaths) =>
|
FakeCompetencyDomains competencyDomains, FakeAlternativeLessonPaths altPaths,
|
||||||
new(new HttpClient(), lessons, groups, subjects, competencyDomains, altPaths);
|
FakeCompetencyCatalogVersions? competencyVersions = null) =>
|
||||||
|
new(new HttpClient(), lessons, groups, subjects, competencyDomains,
|
||||||
|
competencyVersions ?? new FakeCompetencyCatalogVersions(), altPaths, TestSupport.BuildAppLogger());
|
||||||
|
|
||||||
|
[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([]),
|
||||||
|
TestSupport.BuildAppLogger());
|
||||||
|
|
||||||
|
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([]),
|
||||||
|
TestSupport.BuildAppLogger());
|
||||||
|
}
|
||||||
|
|
||||||
|
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]
|
[Fact]
|
||||||
public void BuildContext_FuelltGruppenUndFachKontext()
|
public void BuildContext_FuelltGruppenUndFachKontext()
|
||||||
@@ -42,14 +239,16 @@ public sealed class AiPlanningServiceTests
|
|||||||
var unit = new Unit { GroupId = group.Id, Title = "T" };
|
var unit = new Unit { GroupId = group.Id, Title = "T" };
|
||||||
|
|
||||||
var domains = new FakeCompetencyDomains();
|
var domains = new FakeCompetencyDomains();
|
||||||
|
var versions = new FakeCompetencyCatalogVersions();
|
||||||
|
var version = versions.GetOrCreateDefault(subject.Id);
|
||||||
domains.Add(new CompetencyDomain
|
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" }],
|
Items = [new CompetencyItem { Code = "C1", Description = "Redoxreaktionen erklären" }],
|
||||||
});
|
});
|
||||||
|
|
||||||
var service = Build(new FakeLessons(), new FakeGroups([group]), new FakeSubjects([subject]),
|
var service = Build(new FakeLessons(), new FakeGroups([group]), new FakeSubjects([subject]),
|
||||||
domains, new FakeAlternativeLessonPaths([]));
|
domains, new FakeAlternativeLessonPaths([]), versions);
|
||||||
|
|
||||||
var context = service.BuildContext(unit, "");
|
var context = service.BuildContext(unit, "");
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -13,29 +13,35 @@ public sealed class CompetencyOverviewViewModelTests
|
|||||||
var subjectId = Guid.NewGuid();
|
var subjectId = Guid.NewGuid();
|
||||||
var group = new LearningGroup { SubjectId = subjectId, GradeLevel = 8 };
|
var group = new LearningGroup { SubjectId = subjectId, GradeLevel = 8 };
|
||||||
var student = new Student { FirstName = "Ada", LastName = "Lovelace" };
|
var student = new Student { FirstName = "Ada", LastName = "Lovelace" };
|
||||||
|
var k1 = new CompetencyItem { Code = "K1", Description = "Kompetenz" };
|
||||||
var units = new FakeUnits();
|
var units = new FakeUnits();
|
||||||
units.Add(new Unit
|
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
|
var exam = new Exam
|
||||||
{
|
{
|
||||||
GroupId = group.Id,
|
GroupId = group.Id,
|
||||||
Status = ExamStatus.Graded,
|
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();
|
var results = new FakeResults();
|
||||||
results.Add(new ExamResult { ExamId = exam.Id, StudentId = student.Id, Points = [5] });
|
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();
|
var catalog = new FakeCompetencyDomains();
|
||||||
catalog.Add(new CompetencyDomain
|
catalog.Add(new CompetencyDomain
|
||||||
{
|
{
|
||||||
SubjectId = subjectId,
|
SubjectId = subjectId,
|
||||||
GradeLevel = 8,
|
GradeLevel = 8,
|
||||||
|
VersionId = version.Id,
|
||||||
Name = "Bereich",
|
Name = "Bereich",
|
||||||
Items = [new CompetencyItem { Code = "K1", Description = "Kompetenz" }],
|
Items = [k1],
|
||||||
});
|
});
|
||||||
var vm = new CompetencyOverviewTabViewModel(units, new FakeExams([exam]), results,
|
var vm = new CompetencyOverviewTabViewModel(units, new FakeExams([exam]), results,
|
||||||
catalog, new FakeStudents([student]), new CompetencyAnalysisService());
|
catalog, versions, new FakeStudents([student]), new FakeSessions([]), new FakeEntries(),
|
||||||
|
new FakeAspects(), new CompetencyAnalysisService());
|
||||||
|
|
||||||
vm.Initialize(group);
|
vm.Initialize(group);
|
||||||
|
|
||||||
@@ -65,4 +71,52 @@ public sealed class CompetencyOverviewViewModelTests
|
|||||||
|
|
||||||
Assert.Equal("Stand solide", row.Recommendation);
|
Assert.Equal("Stand solide", row.Recommendation);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Initialize_AutomatischeMitarbeitsschaetzung_FuelltKompetenzprofil()
|
||||||
|
{
|
||||||
|
var subjectId = Guid.NewGuid();
|
||||||
|
var group = new LearningGroup { SubjectId = subjectId, GradeLevel = 8 };
|
||||||
|
var student = new Student { FirstName = "Ada", LastName = "Lovelace" };
|
||||||
|
var competency = new CompetencyItem { Code = "K1", Description = "Kompetenz" };
|
||||||
|
var versions = new FakeCompetencyCatalogVersions();
|
||||||
|
var version = versions.GetOrCreateDefault(subjectId);
|
||||||
|
var catalog = new FakeCompetencyDomains();
|
||||||
|
catalog.Add(new CompetencyDomain
|
||||||
|
{
|
||||||
|
SubjectId = subjectId,
|
||||||
|
GradeLevel = 8,
|
||||||
|
VersionId = version.Id,
|
||||||
|
Name = "Bereich",
|
||||||
|
Items = [competency],
|
||||||
|
});
|
||||||
|
var session = new ParticipationSession
|
||||||
|
{
|
||||||
|
GroupId = group.Id,
|
||||||
|
Competencies = [new CompetencyReference
|
||||||
|
{
|
||||||
|
ItemId = competency.Id,
|
||||||
|
Code = competency.Code,
|
||||||
|
Description = competency.Description,
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
var entries = new FakeEntries();
|
||||||
|
entries.Add(new ParticipationEntry
|
||||||
|
{
|
||||||
|
SessionId = session.Id,
|
||||||
|
StudentId = student.Id,
|
||||||
|
Ratings = [new AspectRating { Key = "quality", Value = 1 }],
|
||||||
|
});
|
||||||
|
|
||||||
|
var vm = new CompetencyOverviewTabViewModel(new FakeUnits(), new FakeExams([]),
|
||||||
|
new FakeResults(), catalog, versions, new FakeStudents([student]),
|
||||||
|
new FakeSessions([session]), entries, new FakeAspects(), new CompetencyAnalysisService());
|
||||||
|
|
||||||
|
vm.Initialize(group);
|
||||||
|
|
||||||
|
var row = Assert.Single(vm.Rows);
|
||||||
|
Assert.Equal("1× bewertet", row.ParticipationCoverage);
|
||||||
|
Assert.Contains("75 %", row.GroupResult);
|
||||||
|
Assert.Contains("1 Mitarbeitswert", row.StudentResult);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -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,7 +1,7 @@
|
|||||||
using System.IO.Compression;
|
|
||||||
using LehrerApp.Core.Models;
|
using LehrerApp.Core.Models;
|
||||||
using LehrerApp.Core.Services;
|
using LehrerApp.Desktop.Services;
|
||||||
using LehrerApp.Desktop.ViewModels.Students;
|
using LehrerApp.Desktop.ViewModels.Students;
|
||||||
|
using LehrerApp.Templating;
|
||||||
using Xunit;
|
using Xunit;
|
||||||
|
|
||||||
namespace LehrerApp.Desktop.Tests;
|
namespace LehrerApp.Desktop.Tests;
|
||||||
@@ -9,16 +9,12 @@ namespace LehrerApp.Desktop.Tests;
|
|||||||
public sealed class CreateLetterDialogViewModelTests : IDisposable
|
public sealed class CreateLetterDialogViewModelTests : IDisposable
|
||||||
{
|
{
|
||||||
private readonly string _directory = Path.Combine(Path.GetTempPath(), $"lehrerapp-letter-vm-tests-{Guid.NewGuid():N}");
|
private readonly string _directory = Path.Combine(Path.GetTempPath(), $"lehrerapp-letter-vm-tests-{Guid.NewGuid():N}");
|
||||||
|
|
||||||
public CreateLetterDialogViewModelTests() => Directory.CreateDirectory(_directory);
|
public CreateLetterDialogViewModelTests() => Directory.CreateDirectory(_directory);
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void OhneVorlage_KannKeinenBriefErzeugen()
|
public void OhneVorlage_KannKeinenBriefErzeugen()
|
||||||
{
|
{
|
||||||
var student = StudentWithContact("Sehr geehrte Frau Muster,");
|
var vm = Build(StudentWithContact("Sehr geehrte Frau Muster,"), new TemplateStore(_directory));
|
||||||
|
|
||||||
var vm = Build(student, new LetterTemplateService(_directory));
|
|
||||||
|
|
||||||
Assert.False(vm.CanGenerate);
|
Assert.False(vm.CanGenerate);
|
||||||
Assert.Contains(vm.Issues, i => i.Message.Contains("Vorlage", StringComparison.OrdinalIgnoreCase));
|
Assert.Contains(vm.Issues, i => i.Message.Contains("Vorlage", StringComparison.OrdinalIgnoreCase));
|
||||||
}
|
}
|
||||||
@@ -26,83 +22,313 @@ public sealed class CreateLetterDialogViewModelTests : IDisposable
|
|||||||
[Fact]
|
[Fact]
|
||||||
public void VerwendeteBriefanredeFehlt_BlockiertErzeugung()
|
public void VerwendeteBriefanredeFehlt_BlockiertErzeugung()
|
||||||
{
|
{
|
||||||
var service = ServiceWithTemplate("Letter.Salutation");
|
var vm = Build(StudentWithContact(null), StoreWithTemplate(
|
||||||
var vm = Build(StudentWithContact(null), service);
|
new PlaceholderDefinition("Anrede", PlaceholderType.Text, true)));
|
||||||
|
|
||||||
Assert.False(vm.CanGenerate);
|
Assert.False(vm.CanGenerate);
|
||||||
Assert.Contains(vm.Issues, i => i.Message.Contains("Briefanrede"));
|
Assert.Contains(vm.Issues, i => i.Message.Contains("Anrede", StringComparison.OrdinalIgnoreCase));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void VollstaendigeDaten_ErzeugenEditierbareDocxKopie()
|
public void VollstaendigeDaten_ErzeugenFlachesPdf()
|
||||||
{
|
{
|
||||||
var service = ServiceWithTemplate("Letter.Salutation", "Student.FirstName", "CurrentDate");
|
var store = StoreWithTemplate(new PlaceholderDefinition("Anrede", PlaceholderType.Text, true),
|
||||||
var vm = Build(StudentWithContact("Sehr geehrte Frau Muster,"), service);
|
new PlaceholderDefinition("Datum", PlaceholderType.Date, true),
|
||||||
var output = Path.Combine(_directory, "Brief.docx");
|
new PlaceholderDefinition("Brieftext", PlaceholderType.Multiline, true));
|
||||||
|
var vm = Build(StudentWithContact("Sehr geehrte Frau Muster,"), store);
|
||||||
|
vm.LetterText = "Dies ist der Inhalt.";
|
||||||
|
var output = Path.Combine(_directory, "Brief.pdf");
|
||||||
|
|
||||||
var generated = vm.Generate(output);
|
Assert.True(vm.Generate(output));
|
||||||
|
Assert.Equal("%PDF", System.Text.Encoding.ASCII.GetString(File.ReadAllBytes(output), 0, 4));
|
||||||
Assert.True(generated);
|
|
||||||
Assert.True(File.Exists(output));
|
|
||||||
using var archive = ZipFile.OpenRead(output);
|
|
||||||
using var reader = new StreamReader(archive.GetEntry("word/document.xml")!.Open());
|
|
||||||
var xml = reader.ReadToEnd();
|
|
||||||
Assert.Contains("Sehr geehrte Frau Muster,", xml);
|
|
||||||
Assert.Contains("Lena", xml);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void KontaktBearbeiten_SpeichertExpliziteBriefanrede()
|
public void KonstanterPflichttext_BenoetigtKeineExterneEingabe()
|
||||||
{
|
{
|
||||||
var vm = new ContactEditDialogViewModel(new Contact { Name = "Frau Muster" });
|
var store = StoreWithTemplate(new PlaceholderDefinition("Brieftext", PlaceholderType.Multiline,
|
||||||
vm.LetterSalutation = "Sehr geehrte Frau Muster,";
|
Required: true, IsConstant: true, ConstantValue: "Fest im Vorlagenpaket"));
|
||||||
|
var vm = Build(StudentWithContact("Sehr geehrte Frau Muster,"), store);
|
||||||
|
var output = Path.Combine(_directory, "Konstant.pdf");
|
||||||
|
|
||||||
vm.SaveCommand.Execute(null);
|
Assert.True(vm.CanGenerate);
|
||||||
|
Assert.True(vm.Generate(output));
|
||||||
Assert.Equal("Sehr geehrte Frau Muster,", vm.Result!.LetterSalutation);
|
Assert.Equal("%PDF", System.Text.Encoding.ASCII.GetString(File.ReadAllBytes(output), 0, 4));
|
||||||
}
|
}
|
||||||
|
|
||||||
private CreateLetterDialogViewModel Build(Student student, LetterTemplateService service) =>
|
[Fact]
|
||||||
new(student, service, new FakeMemberships([]), new FakeGroups([]));
|
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");
|
||||||
|
|
||||||
private LetterTemplateService ServiceWithTemplate(params string[] tags)
|
Assert.True(vm.UsesAttendanceCalendar);
|
||||||
{
|
await vm.SetAttendanceCalendarOptionsAsync(new AttendanceCalendarOptions(
|
||||||
var source = Path.Combine(_directory, $"{Guid.NewGuid():N}.docx");
|
new DateOnly(2026, 8, 19), 3, AttendanceCalendarSize.Large));
|
||||||
using (var archive = ZipFile.Open(source, ZipArchiveMode.Create))
|
Assert.True(vm.AttendanceCalendarConfigured);
|
||||||
{
|
Assert.Contains("August 2026", vm.AttendanceCalendarSummary);
|
||||||
var entry = archive.CreateEntry("word/document.xml");
|
Assert.Contains("3 Monate", vm.AttendanceCalendarSummary);
|
||||||
using var writer = new StreamWriter(entry.Open());
|
Assert.Contains("Groß", vm.AttendanceCalendarSummary);
|
||||||
var controls = string.Join("", tags.Select(tag =>
|
Assert.True(vm.Generate(output));
|
||||||
$"<w:sdt><w:sdtPr><w:tag w:val=\"{tag}\"/></w:sdtPr><w:sdtContent>" +
|
Assert.Equal("%PDF", System.Text.Encoding.ASCII.GetString(File.ReadAllBytes(output), 0, 4));
|
||||||
"<w:p><w:r><w:t>Platzhalter</w:t></w:r></w:p></w:sdtContent></w:sdt>"));
|
|
||||||
writer.Write("<w:document xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">" +
|
|
||||||
$"<w:body>{controls}</w:body></w:document>");
|
|
||||||
}
|
}
|
||||||
var service = new LetterTemplateService(Path.Combine(_directory, $"service-{Guid.NewGuid():N}"));
|
|
||||||
service.Import(source, "Elternbrief");
|
// Regression: Der DrawingValue-Builder hat früher immer eine feste Breite (170) angenommen,
|
||||||
return service;
|
// 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([]));
|
||||||
|
|
||||||
|
private TemplateStore StoreWithTemplate(params PlaceholderDefinition[] definitions)
|
||||||
|
{
|
||||||
|
var source = Path.Combine(_directory, $"{Guid.NewGuid():N}.lavorlage");
|
||||||
|
var manifest = new TemplateManifest { Id = $"brief-{Guid.NewGuid():N}", Name = "Elternbrief", Placeholders = [.. definitions] };
|
||||||
|
var lines = new List<string> { "PAGE 210 297 mm" };
|
||||||
|
var y = 20;
|
||||||
|
foreach (var definition in definitions)
|
||||||
|
{
|
||||||
|
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[]>());
|
||||||
|
var store = new TemplateStore(Path.Combine(_directory, $"store-{Guid.NewGuid():N}")); store.Import(source); return store;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static Student StudentWithContact(string? salutation) => new()
|
private static Student StudentWithContact(string? salutation) => new()
|
||||||
{
|
{
|
||||||
FirstName = "Lena",
|
FirstName = "Lena", LastName = "Beispiel",
|
||||||
LastName = "Beispiel",
|
Contacts = [new Contact { Name = "Frau Muster", Relation = "Mutter", LetterSalutation = salutation,
|
||||||
Contacts =
|
Street = "Hauptstraße 1", PostalCode = "12345", City = "Musterstadt" }],
|
||||||
[
|
|
||||||
new Contact
|
|
||||||
{
|
|
||||||
Name = "Frau Muster",
|
|
||||||
Relation = "Mutter",
|
|
||||||
LetterSalutation = salutation,
|
|
||||||
Street = "Hauptstraße 1",
|
|
||||||
PostalCode = "12345",
|
|
||||||
City = "Musterstadt",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
};
|
||||||
|
public void Dispose() { if (Directory.Exists(_directory)) Directory.Delete(_directory, true); }
|
||||||
public void Dispose()
|
|
||||||
{
|
|
||||||
if (Directory.Exists(_directory)) Directory.Delete(_directory, recursive: true);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
using LehrerApp.Core.Models;
|
using LehrerApp.Core.Models;
|
||||||
using LehrerApp.Core.Services;
|
using LehrerApp.Core.Services;
|
||||||
using LehrerApp.Desktop.ViewModels;
|
using LehrerApp.Desktop.ViewModels;
|
||||||
|
using System.Globalization;
|
||||||
using Xunit;
|
using Xunit;
|
||||||
|
|
||||||
namespace LehrerApp.Desktop.Tests;
|
namespace LehrerApp.Desktop.Tests;
|
||||||
@@ -19,14 +20,100 @@ public sealed class DashboardViewModelTests
|
|||||||
|
|
||||||
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today });
|
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today });
|
||||||
|
|
||||||
Assert.False(vm.ExcusesCard.EffectiveIsVisible);
|
Assert.False(vm.AttentionCard.EffectiveIsVisible);
|
||||||
Assert.False(vm.CorrectionsCard.EffectiveIsVisible);
|
|
||||||
Assert.False(vm.AlertsCard.EffectiveIsVisible);
|
|
||||||
Assert.Equal("0 offene Punkte", vm.AttentionSummary);
|
Assert.Equal("0 offene Punkte", vm.AttentionSummary);
|
||||||
Assert.True(vm.TodayCard.EffectiveIsVisible);
|
Assert.True(vm.TodayCard.EffectiveIsVisible);
|
||||||
Assert.True(vm.CalendarCard.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;
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void OpenExcuses_ZeigtNurSchuelerAusEigenerKlasse()
|
||||||
|
{
|
||||||
|
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||||
|
var ownClass = new LearningGroup { Name = "Meine 9c", IsOwnClass = true };
|
||||||
|
var otherClass = new LearningGroup { Name = "Fremde 8a", IsOwnClass = false };
|
||||||
|
var ownStudent = new Student { FirstName = "Anna", LastName = "Eigen" };
|
||||||
|
var otherStudent = new Student { FirstName = "Ben", LastName = "Fremd" };
|
||||||
|
var ownSession = new ParticipationSession { GroupId = ownClass.Id, Date = today.AddDays(-1) };
|
||||||
|
var otherSession = new ParticipationSession { GroupId = otherClass.Id, Date = today.AddDays(-1) };
|
||||||
|
var entries = new FakeEntries();
|
||||||
|
entries.Add(new ParticipationEntry
|
||||||
|
{ SessionId = ownSession.Id, StudentId = ownStudent.Id, Attendance = AttendanceStatus.ExcusePending });
|
||||||
|
entries.Add(new ParticipationEntry
|
||||||
|
{ SessionId = otherSession.Id, StudentId = otherStudent.Id, Attendance = AttendanceStatus.ExcusePending });
|
||||||
|
|
||||||
|
var vm = BuildVm(ownClass, new Lesson { GroupId = ownClass.Id, Date = today },
|
||||||
|
allGroups: [ownClass, otherClass], students: new FakeStudents([ownStudent, otherStudent]),
|
||||||
|
sessions: new FakeSessions([ownSession, otherSession]), entries: entries);
|
||||||
|
|
||||||
|
var excuse = Assert.Single(Items(vm, AttentionKind.Excuse));
|
||||||
|
Assert.Equal(ownStudent.FullName, excuse.Title);
|
||||||
|
Assert.DoesNotContain(Items(vm, AttentionKind.Excuse), item => item.Title == otherStudent.FullName);
|
||||||
|
}
|
||||||
|
|
||||||
private static PeriodScheduleService NewPeriodSchedule()
|
private static PeriodScheduleService NewPeriodSchedule()
|
||||||
{
|
{
|
||||||
var tempPath = System.IO.Path.Combine(
|
var tempPath = System.IO.Path.Combine(
|
||||||
@@ -59,12 +146,13 @@ public sealed class DashboardViewModelTests
|
|||||||
DashboardSettingsService? dashboardSettings = null, FakeSchoolHolidays? schoolHolidays = null,
|
DashboardSettingsService? dashboardSettings = null, FakeSchoolHolidays? schoolHolidays = null,
|
||||||
FakeLessons? lessons = null, FakeSubstitutionEntries? substitutions = null,
|
FakeLessons? lessons = null, FakeSubstitutionEntries? substitutions = null,
|
||||||
FakeSessions? sessions = null, FakeEntries? entries = null,
|
FakeSessions? sessions = null, FakeEntries? entries = null,
|
||||||
FakeAnnualPlanEvents? annualPlanEvents = null)
|
FakeAnnualPlanEvents? annualPlanEvents = null, List<LearningGroup>? allGroups = null,
|
||||||
|
FakeTimeEntries? timeEntries = null, Func<DateTime>? now = null)
|
||||||
{
|
{
|
||||||
lessons ??= new FakeLessons();
|
lessons ??= new FakeLessons();
|
||||||
lessons.Add(lesson);
|
lessons.Add(lesson);
|
||||||
return new DashboardViewModel(
|
return new DashboardViewModel(
|
||||||
new FakeGroups([group]), new FakeSubjects([]), lessons,
|
new FakeGroups(allGroups ?? [group]), new FakeSubjects([]), lessons,
|
||||||
exams ?? new FakeExams([]), results ?? new FakeResults(), grades ?? new FakeGrades(),
|
exams ?? new FakeExams([]), results ?? new FakeResults(), grades ?? new FakeGrades(),
|
||||||
reportGrades ?? new FakeReportGrades(), memberships ?? new FakeMemberships([]),
|
reportGrades ?? new FakeReportGrades(), memberships ?? new FakeMemberships([]),
|
||||||
tasks ?? new FakeWorkTasks(), sessions ?? new FakeSessions([]), entries ?? new FakeEntries(),
|
tasks ?? new FakeWorkTasks(), sessions ?? new FakeSessions([]), entries ?? new FakeEntries(),
|
||||||
@@ -72,7 +160,196 @@ public sealed class DashboardViewModelTests
|
|||||||
slots ?? new FakeTimetableSlots(), periodSchedule ?? NewPeriodSchedule(),
|
slots ?? new FakeTimetableSlots(), periodSchedule ?? NewPeriodSchedule(),
|
||||||
new AttendanceBalanceService(), new SchoolYearService(), dashboardSettings ?? NewDashboardSettings(),
|
new AttendanceBalanceService(), new SchoolYearService(), dashboardSettings ?? NewDashboardSettings(),
|
||||||
schoolHolidays ?? new FakeSchoolHolidays(), new PublicHolidayService(), NewCalendarSettings(),
|
schoolHolidays ?? new FakeSchoolHolidays(), new PublicHolidayService(), NewCalendarSettings(),
|
||||||
substitutions ?? new FakeSubstitutionEntries(), 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
|
||||||
|
/// Klausurwochen-Vorausschau — unabhängig davon, welcher Wochentag "heute" gerade ist.
|
||||||
|
private static DateOnly NextIsoWeekMonday()
|
||||||
|
{
|
||||||
|
var reference = DateTime.Today.AddDays(7);
|
||||||
|
return DateOnly.FromDateTime(
|
||||||
|
ISOWeek.ToDateTime(ISOWeek.GetYear(reference), ISOWeek.GetWeekOfYear(reference), DayOfWeek.Monday));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ExamWeekLoads_DreiGeplanteKlausurenInDerselbenWoche_ErzeugtEintrag()
|
||||||
|
{
|
||||||
|
var group = new LearningGroup { Name = "9c" };
|
||||||
|
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||||
|
var monday = NextIsoWeekMonday();
|
||||||
|
var exams = new FakeExams([
|
||||||
|
new Exam { GroupId = group.Id, Title = "a", Date = monday, Status = ExamStatus.Planned },
|
||||||
|
new Exam { GroupId = group.Id, Title = "b", Date = monday.AddDays(1), Status = ExamStatus.Planned },
|
||||||
|
new Exam { GroupId = group.Id, Title = "c", Date = monday.AddDays(2), Status = ExamStatus.Planned },
|
||||||
|
]);
|
||||||
|
|
||||||
|
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today }, exams: exams);
|
||||||
|
|
||||||
|
var entry = Assert.Single(vm.ExamWeekLoads);
|
||||||
|
Assert.Equal(3, entry.ExamCount);
|
||||||
|
Assert.True(vm.ExamLoadCard.EffectiveIsVisible);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ExamWeekLoads_WenigeKlausurenProWoche_BleibtLeer()
|
||||||
|
{
|
||||||
|
var group = new LearningGroup { Name = "9c" };
|
||||||
|
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||||
|
var monday = NextIsoWeekMonday();
|
||||||
|
var exams = new FakeExams([
|
||||||
|
new Exam { GroupId = group.Id, Title = "a", Date = monday, Status = ExamStatus.Planned },
|
||||||
|
new Exam { GroupId = group.Id, Title = "b", Date = monday.AddDays(1), Status = ExamStatus.Planned },
|
||||||
|
]);
|
||||||
|
|
||||||
|
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today }, exams: exams);
|
||||||
|
|
||||||
|
Assert.Empty(vm.ExamWeekLoads);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ExamWeekLoads_BereitsDurchgefuehrteKlausurenZaehlenNicht()
|
||||||
|
{
|
||||||
|
var group = new LearningGroup { Name = "9c" };
|
||||||
|
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||||
|
var monday = NextIsoWeekMonday();
|
||||||
|
var exams = new FakeExams([
|
||||||
|
new Exam { GroupId = group.Id, Title = "a", Date = monday, Status = ExamStatus.Conducted },
|
||||||
|
new Exam { GroupId = group.Id, Title = "b", Date = monday.AddDays(1), Status = ExamStatus.Graded },
|
||||||
|
new Exam { GroupId = group.Id, Title = "c", Date = monday.AddDays(2), Status = ExamStatus.Planned },
|
||||||
|
]);
|
||||||
|
|
||||||
|
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today }, exams: exams);
|
||||||
|
|
||||||
|
Assert.Empty(vm.ExamWeekLoads);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void MissingTeachingTime_VergangenerUnterrichtstagOhneErfassung_WirdGemeldet()
|
||||||
|
{
|
||||||
|
var group = new LearningGroup { Name = "9c" };
|
||||||
|
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||||
|
var pastDay = today.AddDays(-1);
|
||||||
|
var slots = new FakeTimetableSlots();
|
||||||
|
slots.Add(new TimetableSlot { GroupId = group.Id, Weekday = pastDay.DayOfWeek, PeriodNumber = 1 });
|
||||||
|
var periodSchedule = NewPeriodSchedule();
|
||||||
|
periodSchedule.SetPeriods([new PeriodTimeEntry
|
||||||
|
{ PeriodNumber = 1, Start = new TimeOnly(8, 0), End = new TimeOnly(8, 45) }]);
|
||||||
|
|
||||||
|
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today }, slots: slots, periodSchedule: periodSchedule);
|
||||||
|
|
||||||
|
Assert.Contains(Items(vm, AttentionKind.MissingTeachingTime), i => MissingTimeDate(i) == pastDay);
|
||||||
|
Assert.True(vm.AttentionCard.EffectiveIsVisible);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void MissingTeachingTime_BereitsErfassterTag_WirdNichtGemeldet()
|
||||||
|
{
|
||||||
|
var group = new LearningGroup { Name = "9c" };
|
||||||
|
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||||
|
var pastDay = today.AddDays(-1);
|
||||||
|
var slots = new FakeTimetableSlots();
|
||||||
|
slots.Add(new TimetableSlot { GroupId = group.Id, Weekday = pastDay.DayOfWeek, PeriodNumber = 1 });
|
||||||
|
var periodSchedule = NewPeriodSchedule();
|
||||||
|
periodSchedule.SetPeriods([new PeriodTimeEntry
|
||||||
|
{ PeriodNumber = 1, Start = new TimeOnly(8, 0), End = new TimeOnly(8, 45) }]);
|
||||||
|
var timeEntries = new FakeTimeEntries();
|
||||||
|
timeEntries.Add(new TimeEntry { Date = pastDay, Category = "Unterricht", DurationMinutes = 45 });
|
||||||
|
|
||||||
|
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||||
|
slots: slots, periodSchedule: periodSchedule, timeEntries: timeEntries);
|
||||||
|
|
||||||
|
Assert.DoesNotContain(Items(vm, AttentionKind.MissingTeachingTime), i => MissingTimeDate(i) == pastDay);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void MissingTeachingTime_KomplettAusgefallenerTag_WirdNichtGemeldet()
|
||||||
|
{
|
||||||
|
var group = new LearningGroup { Name = "9c" };
|
||||||
|
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||||
|
var pastDay = today.AddDays(-1);
|
||||||
|
var slots = new FakeTimetableSlots();
|
||||||
|
slots.Add(new TimetableSlot { GroupId = group.Id, Weekday = pastDay.DayOfWeek, PeriodNumber = 1 });
|
||||||
|
var periodSchedule = NewPeriodSchedule();
|
||||||
|
periodSchedule.SetPeriods([new PeriodTimeEntry
|
||||||
|
{ PeriodNumber = 1, Start = new TimeOnly(8, 0), End = new TimeOnly(8, 45) }]);
|
||||||
|
var substitutions = new FakeSubstitutionEntries();
|
||||||
|
substitutions.Add(new SubstitutionEntry { Date = pastDay, Kind = SubstitutionKind.Cancelled, PeriodNumber = 1 });
|
||||||
|
|
||||||
|
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||||
|
slots: slots, periodSchedule: periodSchedule, substitutions: substitutions);
|
||||||
|
|
||||||
|
Assert.DoesNotContain(Items(vm, AttentionKind.MissingTeachingTime), i => MissingTimeDate(i) == pastDay);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void MissingTeachingTime_SchulferienTagWirdNichtGemeldet()
|
||||||
|
{
|
||||||
|
var group = new LearningGroup { Name = "9c" };
|
||||||
|
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||||
|
var pastDay = today.AddDays(-1);
|
||||||
|
var slots = new FakeTimetableSlots();
|
||||||
|
slots.Add(new TimetableSlot { GroupId = group.Id, Weekday = pastDay.DayOfWeek, PeriodNumber = 1 });
|
||||||
|
var periodSchedule = NewPeriodSchedule();
|
||||||
|
periodSchedule.SetPeriods([new PeriodTimeEntry
|
||||||
|
{ PeriodNumber = 1, Start = new TimeOnly(8, 0), End = new TimeOnly(8, 45) }]);
|
||||||
|
var schoolHolidays = new FakeSchoolHolidays();
|
||||||
|
schoolHolidays.Add(new SchoolHoliday { Name = "Ferien", StartDate = pastDay, EndDate = pastDay });
|
||||||
|
|
||||||
|
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||||
|
slots: slots, periodSchedule: periodSchedule, schoolHolidays: schoolHolidays);
|
||||||
|
|
||||||
|
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(FixedNow);
|
||||||
|
var slots = new FakeTimetableSlots();
|
||||||
|
slots.Add(new TimetableSlot { GroupId = group.Id, Weekday = today.DayOfWeek, PeriodNumber = 1 });
|
||||||
|
var periodSchedule = NewPeriodSchedule();
|
||||||
|
// 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, now: () => FixedNow);
|
||||||
|
|
||||||
|
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(FixedNow);
|
||||||
|
var slots = new FakeTimetableSlots();
|
||||||
|
slots.Add(new TimetableSlot { GroupId = group.Id, Weekday = today.DayOfWeek, PeriodNumber = 1 });
|
||||||
|
var periodSchedule = NewPeriodSchedule();
|
||||||
|
// 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, now: () => FixedNow);
|
||||||
|
|
||||||
|
Assert.Contains(Items(vm, AttentionKind.MissingTeachingTime), i => MissingTimeDate(i) == today);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -199,10 +476,9 @@ public sealed class DashboardViewModelTests
|
|||||||
exams: new FakeExams([exam]), results: results, memberships: memberships,
|
exams: new FakeExams([exam]), results: results, memberships: memberships,
|
||||||
students: new FakeStudents([anna, ben]));
|
students: new FakeStudents([anna, ben]));
|
||||||
|
|
||||||
var correction = Assert.Single(vm.OpenCorrections);
|
var correction = Assert.Single(Items(vm, AttentionKind.Correction));
|
||||||
Assert.Equal(1, correction.Completed);
|
Assert.Equal(50, correction.ProgressPercent);
|
||||||
Assert.Equal(2, correction.Total);
|
Assert.Equal("1 von 2 Arbeiten bewertet", correction.ProgressLabel);
|
||||||
Assert.Equal(50, correction.Percent);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -223,7 +499,7 @@ public sealed class DashboardViewModelTests
|
|||||||
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today }, grades: grades,
|
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today }, grades: grades,
|
||||||
memberships: memberships, students: new FakeStudents([student]));
|
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]
|
[Fact]
|
||||||
@@ -242,6 +518,26 @@ public sealed class DashboardViewModelTests
|
|||||||
Assert.Contains(vm.SelectedDayEvents, e => e.Kind == CalendarEventKind.Exam && e.Title == "Test");
|
Assert.Contains(vm.SelectedDayEvents, e => e.Kind == CalendarEventKind.Exam && e.Title == "Test");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Kalenderauswahl_SortiertKurseDesTagesVorDenAlphabetischenRest()
|
||||||
|
{
|
||||||
|
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||||
|
var selectedDate = today.AddDays(1);
|
||||||
|
var alphabeticallyFirst = new LearningGroup { Name = "10a" };
|
||||||
|
var selectedDayGroup = new LearningGroup { Name = "WAT 10c" };
|
||||||
|
var lessons = new FakeLessons();
|
||||||
|
lessons.Add(new Lesson { GroupId = selectedDayGroup.Id, Date = selectedDate });
|
||||||
|
var vm = BuildVm(alphabeticallyFirst,
|
||||||
|
new Lesson { GroupId = alphabeticallyFirst.Id, Date = today }, lessons: lessons,
|
||||||
|
allGroups: [alphabeticallyFirst, selectedDayGroup]);
|
||||||
|
|
||||||
|
vm.SelectCalendarDayCommand.Execute(vm.CalendarDays.Single(d => d.Date == selectedDate));
|
||||||
|
|
||||||
|
Assert.Equal(selectedDayGroup.Id, vm.CurrentGroups[0].GroupId);
|
||||||
|
Assert.True(vm.CurrentGroups[0].IsOnSelectedDay);
|
||||||
|
Assert.Equal(alphabeticallyFirst.Id, vm.CurrentGroups[1].GroupId);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void Kalender_ZeigtMitarbeitssitzungenAlsEigenenTermintyp()
|
public void Kalender_ZeigtMitarbeitssitzungenAlsEigenenTermintyp()
|
||||||
{
|
{
|
||||||
@@ -362,9 +658,8 @@ public sealed class DashboardViewModelTests
|
|||||||
|
|
||||||
var vm = BuildVm(group, pastLesson, slots: slots);
|
var vm = BuildVm(group, pastLesson, slots: slots);
|
||||||
|
|
||||||
var item = Assert.Single(vm.UnplannedLessons);
|
var item = Assert.Single(Items(vm, AttentionKind.Unplanned));
|
||||||
Assert.Equal(group.Id, item.GroupId);
|
Assert.Equal($"{group.Name} · 1. Stunde", item.Title);
|
||||||
Assert.Equal(1, item.PeriodNumber);
|
|
||||||
Assert.Equal("Heute", item.DateDisplay);
|
Assert.Equal("Heute", item.DateDisplay);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -379,7 +674,7 @@ public sealed class DashboardViewModelTests
|
|||||||
|
|
||||||
var vm = BuildVm(group, lesson, slots: slots);
|
var vm = BuildVm(group, lesson, slots: slots);
|
||||||
|
|
||||||
Assert.Empty(vm.UnplannedLessons);
|
Assert.Empty(Items(vm, AttentionKind.Unplanned));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -393,7 +688,7 @@ public sealed class DashboardViewModelTests
|
|||||||
|
|
||||||
var vm = BuildVm(group, pastLesson, slots: slots);
|
var vm = BuildVm(group, pastLesson, slots: slots);
|
||||||
|
|
||||||
Assert.Empty(vm.UnplannedLessons);
|
Assert.Empty(Items(vm, AttentionKind.Unplanned));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -409,7 +704,7 @@ public sealed class DashboardViewModelTests
|
|||||||
|
|
||||||
var vm = BuildVm(group, pastLesson, slots: slots, schoolHolidays: schoolHolidays);
|
var vm = BuildVm(group, pastLesson, slots: slots, schoolHolidays: schoolHolidays);
|
||||||
|
|
||||||
Assert.Empty(vm.UnplannedLessons);
|
Assert.Empty(Items(vm, AttentionKind.Unplanned));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -424,7 +719,7 @@ public sealed class DashboardViewModelTests
|
|||||||
|
|
||||||
var vm = BuildVm(group, lesson, slots: slots);
|
var vm = BuildVm(group, lesson, slots: slots);
|
||||||
|
|
||||||
Assert.Empty(vm.UnplannedLessons);
|
Assert.Empty(Items(vm, AttentionKind.Unplanned));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -439,9 +734,10 @@ public sealed class DashboardViewModelTests
|
|||||||
|
|
||||||
var vm = BuildVm(group, lesson, slots: slots);
|
var vm = BuildVm(group, lesson, slots: slots);
|
||||||
|
|
||||||
Assert.Equal(2, vm.UnplannedLessons.Count);
|
var unplanned = Items(vm, AttentionKind.Unplanned).ToList();
|
||||||
Assert.Contains(vm.UnplannedLessons, i => i.PeriodNumber == 3);
|
Assert.Equal(2, unplanned.Count);
|
||||||
Assert.Contains(vm.UnplannedLessons, i => i.PeriodNumber == 4);
|
Assert.Contains(unplanned, i => i.Title.Contains("3. Stunde"));
|
||||||
|
Assert.Contains(unplanned, i => i.Title.Contains("4. Stunde"));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -459,7 +755,7 @@ public sealed class DashboardViewModelTests
|
|||||||
|
|
||||||
var vm = BuildVm(group, pastLesson, slots: slots, substitutions: substitutions);
|
var vm = BuildVm(group, pastLesson, slots: slots, substitutions: substitutions);
|
||||||
|
|
||||||
Assert.Empty(vm.UnplannedLessons);
|
Assert.Empty(Items(vm, AttentionKind.Unplanned));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -482,7 +778,7 @@ public sealed class DashboardViewModelTests
|
|||||||
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||||
students: new FakeStudents([student]), sessions: sessions, entries: entries);
|
students: new FakeStudents([student]), sessions: sessions, entries: entries);
|
||||||
|
|
||||||
Assert.Empty(vm.AttendanceWarnings);
|
Assert.Empty(Items(vm, AttentionKind.Attendance));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -506,9 +802,11 @@ public sealed class DashboardViewModelTests
|
|||||||
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
var vm = BuildVm(group, new Lesson { GroupId = group.Id, Date = today },
|
||||||
students: new FakeStudents([student]), sessions: sessions, entries: entries);
|
students: new FakeStudents([student]), sessions: sessions, entries: entries);
|
||||||
|
|
||||||
var item = Assert.Single(vm.AttendanceWarnings);
|
var item = Assert.Single(Items(vm, AttentionKind.Attendance));
|
||||||
Assert.Equal(student.FullName, item.StudentName);
|
Assert.Equal(student.FullName, item.Title);
|
||||||
Assert.Equal(30.0, item.AbsenceRatePercent);
|
Assert.Equal("30 %", item.TrailingText);
|
||||||
|
Assert.True(item.IsAttendanceWarning);
|
||||||
|
Assert.Equal(AttentionKind.Attendance, vm.Attention.First().Kind);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
|
|||||||
@@ -228,6 +228,20 @@ public sealed class DocumentationDialogViewModelTests
|
|||||||
Assert.NotEqual("", vm.StudentError);
|
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]
|
[Fact]
|
||||||
public void MitStudentOptions_AuswahlGetroffen_SaveUebernimmtSchuelerUndGruppe()
|
public void MitStudentOptions_AuswahlGetroffen_SaveUebernimmtSchuelerUndGruppe()
|
||||||
{
|
{
|
||||||
@@ -247,6 +261,25 @@ public sealed class DocumentationDialogViewModelTests
|
|||||||
Assert.Equal(groupId, vm.Result.GroupId);
|
Assert.Equal(groupId, vm.Result.GroupId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GesamteLerngruppe_SaveSpeichertOhneSchuelerbezug()
|
||||||
|
{
|
||||||
|
var groupId = Guid.NewGuid();
|
||||||
|
var wholeGroup = new StudentOption(Guid.Empty, "Gesamte Lerngruppe");
|
||||||
|
var vm = new DocumentationDialogViewModel(Guid.Empty, null, new FakeAttachmentStorage(),
|
||||||
|
[wholeGroup], groupId)
|
||||||
|
{
|
||||||
|
SelectedStudent = wholeGroup, Title = "Klausur planen", TypeName = "Planung / Erinnerung",
|
||||||
|
};
|
||||||
|
|
||||||
|
vm.SaveCommand.Execute(null);
|
||||||
|
|
||||||
|
Assert.NotNull(vm.Result);
|
||||||
|
Assert.Equal(Guid.Empty, vm.Result!.StudentId);
|
||||||
|
Assert.Equal(groupId, vm.Result.GroupId);
|
||||||
|
Assert.Equal(DocumentationType.Planning, vm.Result.Type);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void MitStudentOptions_Bearbeiten_SchuelerIstVorausgewaehlt()
|
public void MitStudentOptions_Bearbeiten_SchuelerIstVorausgewaehlt()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Core.Services;
|
||||||
|
using LehrerApp.Desktop.ViewModels.Groups;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.Tests;
|
||||||
|
|
||||||
|
public sealed class ExamDialogViewModelTests
|
||||||
|
{
|
||||||
|
private static ExamDialogViewModel BuildViewModel(List<Exam> existingExams, string dateText,
|
||||||
|
Exam? editingExam = null)
|
||||||
|
{
|
||||||
|
var vm = new ExamDialogViewModel(new FakeExams(existingExams), new FakeCompetencyDomains(),
|
||||||
|
new FakeGradingKeyTemplates(), new GradingService(), Guid.NewGuid(), null, 9,
|
||||||
|
GradingSystem.Grades1To6, "Chemie", isDifferentiated: false, editingExam, null);
|
||||||
|
vm.DateText = dateText;
|
||||||
|
return vm;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Exam MakeExam(DateOnly date) => new() { GroupId = Guid.NewGuid(), Title = "x", Date = date };
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void WeekLoadHint_WenigeKlausurenInDerWoche_BleibtLeer()
|
||||||
|
{
|
||||||
|
var monday = new DateOnly(2026, 3, 16);
|
||||||
|
var existing = new List<Exam> { MakeExam(monday) };
|
||||||
|
|
||||||
|
var vm = BuildViewModel(existing, monday.AddDays(1).ToString("dd.MM.yyyy"));
|
||||||
|
|
||||||
|
Assert.Equal("", vm.WeekLoadHint);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void WeekLoadHint_DritteKlausurInDerWoche_ZeigtHinweis()
|
||||||
|
{
|
||||||
|
var monday = new DateOnly(2026, 3, 16);
|
||||||
|
var existing = new List<Exam> { MakeExam(monday), MakeExam(monday.AddDays(1)) };
|
||||||
|
|
||||||
|
var vm = BuildViewModel(existing, monday.AddDays(2).ToString("dd.MM.yyyy"));
|
||||||
|
|
||||||
|
Assert.Contains("3 Klausuren", vm.WeekLoadHint);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void WeekLoadHint_BearbeiteteKlausurZaehltNichtDoppelt()
|
||||||
|
{
|
||||||
|
var monday = new DateOnly(2026, 3, 16);
|
||||||
|
var editing = MakeExam(monday);
|
||||||
|
var existing = new List<Exam> { editing, MakeExam(monday.AddDays(1)) };
|
||||||
|
|
||||||
|
// Nur die eigene Klausur (editing) + eine weitere -> 2 insgesamt, kein Hinweis.
|
||||||
|
var vm = BuildViewModel(existing, monday.ToString("dd.MM.yyyy"), editing);
|
||||||
|
|
||||||
|
Assert.Equal("", vm.WeekLoadHint);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void WeekLoadHint_UngueltigesDatum_BleibtLeer()
|
||||||
|
{
|
||||||
|
var vm = BuildViewModel([], "keindatum");
|
||||||
|
|
||||||
|
Assert.Equal("", vm.WeekLoadHint);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -29,6 +29,20 @@ public sealed class ExamsOverviewViewModelTests
|
|||||||
Assert.Equal("Neue Klausur", vm.Rows[1].Title);
|
Assert.Equal("Neue Klausur", vm.Rows[1].Title);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void LeereListe_BietetAbsprungZuLerngruppen()
|
||||||
|
{
|
||||||
|
var vm = BuildVm([], []);
|
||||||
|
var navigated = false;
|
||||||
|
vm.OnNavigateToGroups = () => navigated = true;
|
||||||
|
|
||||||
|
vm.LoadCommand.Execute(null);
|
||||||
|
vm.GoToGroupsCommand.Execute(null);
|
||||||
|
|
||||||
|
Assert.True(vm.HasNoExams);
|
||||||
|
Assert.True(navigated);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void Load_ParallelkurseWerdenAlsGeschwisterErkannt()
|
public void Load_ParallelkurseWerdenAlsGeschwisterErkannt()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ using LehrerApp.Core.Interfaces;
|
|||||||
using LehrerApp.Core.Models;
|
using LehrerApp.Core.Models;
|
||||||
using LehrerApp.Core.Services;
|
using LehrerApp.Core.Services;
|
||||||
using LehrerApp.Desktop.Services;
|
using LehrerApp.Desktop.Services;
|
||||||
|
using LehrerApp.Desktop.Services.Mcp;
|
||||||
using LehrerApp.Desktop.ViewModels.Settings;
|
using LehrerApp.Desktop.ViewModels.Settings;
|
||||||
using LehrerApp.Sync;
|
using LehrerApp.Sync;
|
||||||
using LehrerApp.Sync.Crypto;
|
using LehrerApp.Sync.Crypto;
|
||||||
@@ -29,7 +30,19 @@ public static class TestSupport
|
|||||||
/// solange AiSettingsService.IsLoggedIn false ist.
|
/// solange AiSettingsService.IsLoggedIn false ist.
|
||||||
public static AiPlanningService BuildAiPlanningService() => new(
|
public static AiPlanningService BuildAiPlanningService() => new(
|
||||||
new HttpClient(), new FakeLessons(), new FakeGroups([]), new FakeSubjects([]),
|
new HttpClient(), new FakeLessons(), new FakeGroups([]), new FakeSubjects([]),
|
||||||
new FakeCompetencyDomains(), new FakeAlternativeLessonPaths([]));
|
new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions(), new FakeAlternativeLessonPaths([]),
|
||||||
|
BuildAppLogger());
|
||||||
|
|
||||||
|
/// 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.
|
/// Analog zu <see cref="BuildAiSettingsService"/>, eigenes Temp-Verzeichnis je Aufruf.
|
||||||
public static WebUntisSettingsService BuildWebUntisSettingsService()
|
public static WebUntisSettingsService BuildWebUntisSettingsService()
|
||||||
@@ -39,6 +52,14 @@ public static class TestSupport
|
|||||||
return new WebUntisSettingsService(tempPath);
|
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.
|
/// Analog zu den übrigen dateibasierten Feed-Einstellungen: eigenes Temp-Verzeichnis.
|
||||||
public static AnnualPlanSettingsService BuildAnnualPlanSettingsService()
|
public static AnnualPlanSettingsService BuildAnnualPlanSettingsService()
|
||||||
{
|
{
|
||||||
@@ -170,6 +191,7 @@ public class FakeSessions(List<ParticipationSession> all) : IParticipationSessio
|
|||||||
{
|
{
|
||||||
public List<ParticipationSession> GetByGroup(Guid groupId) => all.Where(s => s.GroupId == groupId).ToList();
|
public List<ParticipationSession> GetByGroup(Guid groupId) => all.Where(s => s.GroupId == groupId).ToList();
|
||||||
public ParticipationSession? GetById(Guid id) => all.FirstOrDefault(s => s.Id == id);
|
public ParticipationSession? GetById(Guid id) => all.FirstOrDefault(s => s.Id == id);
|
||||||
|
public List<ParticipationSession> GetAll() => all.ToList();
|
||||||
public void Save(ParticipationSession session)
|
public void Save(ParticipationSession session)
|
||||||
{
|
{
|
||||||
all.RemoveAll(s => s.Id == session.Id);
|
all.RemoveAll(s => s.Id == session.Id);
|
||||||
@@ -337,6 +359,7 @@ public class FakeLessons : ILessonRepository
|
|||||||
{
|
{
|
||||||
private readonly List<Lesson> _all = [];
|
private readonly List<Lesson> _all = [];
|
||||||
public void Add(Lesson l) => _all.Add(l);
|
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) =>
|
public List<Lesson> GetByUnit(Guid unitId) =>
|
||||||
_all.Where(l => l.UnitId == unitId).OrderBy(l => l.Date).ThenBy(l => l.LessonNumber).ToList();
|
_all.Where(l => l.UnitId == unitId).OrderBy(l => l.Date).ThenBy(l => l.LessonNumber).ToList();
|
||||||
public List<Lesson> GetByGroupAndDate(Guid groupId, DateOnly date) =>
|
public List<Lesson> GetByGroupAndDate(Guid groupId, DateOnly date) =>
|
||||||
@@ -351,30 +374,76 @@ public class FakeSubjects(List<Subject> all) : ISubjectRepository
|
|||||||
{
|
{
|
||||||
public List<Subject> GetAll() => all;
|
public List<Subject> GetAll() => all;
|
||||||
public Subject? GetById(Guid id) => all.FirstOrDefault(s => s.Id == id);
|
public Subject? GetById(Guid id) => all.FirstOrDefault(s => s.Id == id);
|
||||||
public Subject? GetByName(string name) => all.FirstOrDefault(s => s.Name == name);
|
public Subject? GetByName(string name) => all.FirstOrDefault(s =>
|
||||||
public void Save(Subject subject) { }
|
string.Equals(s.Name.Trim(), name.Trim(), StringComparison.OrdinalIgnoreCase));
|
||||||
public void Delete(Guid id) { }
|
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
|
public class FakeCompetencyDomains : ICompetencyDomainRepository
|
||||||
{
|
{
|
||||||
private readonly List<CompetencyDomain> _all = [];
|
private readonly List<CompetencyDomain> _all = [];
|
||||||
public void Add(CompetencyDomain d) => _all.Add(d);
|
public void Add(CompetencyDomain d) => _all.Add(d);
|
||||||
public List<CompetencyDomain> GetBySubjectAndGrade(Guid subjectId, int gradeLevel) =>
|
public List<CompetencyDomain> GetBySubjectAndGrade(Guid subjectId, int gradeLevel, Guid versionId) =>
|
||||||
_all.Where(d => d.SubjectId == subjectId && d.GradeLevel == gradeLevel)
|
_all.Where(d => d.SubjectId == subjectId && d.GradeLevel == gradeLevel && d.VersionId == versionId)
|
||||||
.OrderBy(d => d.SortOrder).ToList();
|
.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 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 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 Delete(Guid id) => _all.RemoveAll(d => d.Id == id);
|
||||||
public void DeleteBySubjectAndGrade(Guid subjectId, int gradeLevel) =>
|
public void DeleteBySubjectGradeAndVersion(Guid subjectId, int gradeLevel, Guid versionId) =>
|
||||||
_all.RemoveAll(d => d.SubjectId == subjectId && d.GradeLevel == gradeLevel);
|
_all.RemoveAll(d => d.SubjectId == subjectId && d.GradeLevel == gradeLevel && d.VersionId == versionId);
|
||||||
public void ReplaceForSubjectAndGrade(Guid subjectId, int gradeLevel, List<CompetencyDomain> domains)
|
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);
|
_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 class FakeShorthandCodes(List<ShorthandCode> all) : IShorthandCodeRepository
|
||||||
{
|
{
|
||||||
public List<ShorthandCode> GetAll() => all;
|
public List<ShorthandCode> GetAll() => all;
|
||||||
@@ -524,6 +593,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
|
public class FakeWorkTasks : IWorkTaskRepository
|
||||||
{
|
{
|
||||||
private readonly List<WorkTask> _all = [];
|
private readonly List<WorkTask> _all = [];
|
||||||
@@ -564,3 +646,28 @@ public class FakeReportGrades : IReportGradeRepository
|
|||||||
}
|
}
|
||||||
public void Delete(Guid id) => _all.RemoveAll(r => r.Id == id);
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,7 +14,8 @@ public sealed class GlobalSearchViewModelTests
|
|||||||
Assert.Collection(vm.Results,
|
Assert.Collection(vm.Results,
|
||||||
item => Assert.Equal(GlobalSearchAction.NewTask, item.Action),
|
item => Assert.Equal(GlobalSearchAction.NewTask, item.Action),
|
||||||
item => Assert.Equal(GlobalSearchAction.NewReminder, item.Action),
|
item => Assert.Equal(GlobalSearchAction.NewReminder, item.Action),
|
||||||
item => Assert.Equal(GlobalSearchAction.NewStudent, item.Action));
|
item => Assert.Equal(GlobalSearchAction.NewStudent, item.Action),
|
||||||
|
item => Assert.Equal(GlobalSearchAction.NewGroupDocumentation, item.Action));
|
||||||
Assert.Same(vm.Results[0], vm.SelectedResult);
|
Assert.Same(vm.Results[0], vm.SelectedResult);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -67,8 +68,36 @@ public sealed class GlobalSearchViewModelTests
|
|||||||
Assert.True(reminder);
|
Assert.True(reminder);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Suche_FindetAktiveGruppeUeberFachUndZeigtFachImUntertitel()
|
||||||
|
{
|
||||||
|
var subject = new Subject { Name = "Wirtschaft-Arbeit-Technik", ShortName = "WAT" };
|
||||||
|
var group = new LearningGroup { Name = "10c", SubjectId = subject.Id, SchoolYear = "2026/27", GradeLevel = 10 };
|
||||||
|
var vm = BuildVm(groups: [group], subjects: [subject]);
|
||||||
|
|
||||||
|
vm.Query = "wat";
|
||||||
|
|
||||||
|
var result = Assert.Single(vm.Results, x => x.Kind == GlobalSearchResultKind.Group);
|
||||||
|
Assert.Contains("WAT", result.Subtitle);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Suche_UeberspringtArchivierteSchuelerUndGruppenSamtDerenKlausuren()
|
||||||
|
{
|
||||||
|
var archivedGroup = new LearningGroup { Name = "Testkurs Vorjahr", IsActive = false };
|
||||||
|
var archivedStudent = new Student { FirstName = "Test", LastName = "Archiv", IsActive = false };
|
||||||
|
var exam = new Exam { GroupId = archivedGroup.Id, Title = "Testklausur" };
|
||||||
|
var vm = BuildVm([archivedStudent], [archivedGroup], [exam]);
|
||||||
|
|
||||||
|
vm.Query = "Test";
|
||||||
|
|
||||||
|
Assert.DoesNotContain(vm.Results, x => x.Kind is GlobalSearchResultKind.Student
|
||||||
|
or GlobalSearchResultKind.Group or GlobalSearchResultKind.Exam);
|
||||||
|
}
|
||||||
|
|
||||||
private static GlobalSearchViewModel BuildVm(List<Student>? students = null,
|
private static GlobalSearchViewModel BuildVm(List<Student>? students = null,
|
||||||
List<LearningGroup>? groups = null, List<Exam>? exams = null, FakeWorkTasks? tasks = null) =>
|
List<LearningGroup>? groups = null, List<Exam>? exams = null, FakeWorkTasks? tasks = null,
|
||||||
|
List<Subject>? subjects = null) =>
|
||||||
new(new FakeStudents(students ?? []), new FakeGroups(groups ?? []),
|
new(new FakeStudents(students ?? []), new FakeGroups(groups ?? []),
|
||||||
new FakeExams(exams ?? []), tasks ?? new FakeWorkTasks());
|
new FakeSubjects(subjects ?? []), new FakeExams(exams ?? []), tasks ?? new FakeWorkTasks());
|
||||||
}
|
}
|
||||||
@@ -18,15 +18,16 @@ public sealed class GroupDetailViewModelTests
|
|||||||
var grades = new FakeGrades();
|
var grades = new FakeGrades();
|
||||||
|
|
||||||
var vm = new GroupDetailViewModel(groups, students, memberships, subjects, exams, grades, tasks,
|
var vm = new GroupDetailViewModel(groups, students, memberships, subjects, exams, grades, tasks,
|
||||||
new GroupOverviewViewModel(new FakeLessons(), exams, new FakeSessions([]), new FakeEntries(), students,
|
new GroupOverviewViewModel(new FakeLessons(), exams, new FakeResults(), new FakeSessions([]), new FakeEntries(), students,
|
||||||
new FakeDocumentation(), tasks, new AttendanceBalanceService(), new SchoolYearService()),
|
new FakeDocumentation(), tasks, groups, new AttendanceBalanceService(), new GradingService(), new SchoolYearService()),
|
||||||
new ParticipationTabViewModel(new FakeSessions([]), new FakeEntries(), new FakeAspects(),
|
new ParticipationTabViewModel(new FakeSessions([]), new FakeEntries(), new FakeAspects(),
|
||||||
students, memberships, groups, new FakeCompetencyDomains()),
|
students, memberships, groups, new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions()),
|
||||||
new GradeOverviewTabViewModel(grades, exams, new FakeResults(), students, memberships, new GradingService()),
|
new GradeOverviewTabViewModel(grades, exams, new FakeResults(), students, memberships, new GradingService()),
|
||||||
new PlanningTabViewModel(new FakeUnits(), new FakeLessons(), groups, subjects,
|
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 CompetencyOverviewTabViewModel(new FakeUnits(), exams, new FakeResults(),
|
||||||
new FakeCompetencyDomains(), students, new CompetencyAnalysisService()),
|
new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions(), students,
|
||||||
|
new FakeSessions([]), new FakeEntries(), new FakeAspects(), new CompetencyAnalysisService()),
|
||||||
new SeatingPlanTabViewModel(new FakeSeatingPlans(), students, memberships,
|
new SeatingPlanTabViewModel(new FakeSeatingPlans(), students, memberships,
|
||||||
new FakeSessions([]), new FakeEntries(), new FakeAspects()),
|
new FakeSessions([]), new FakeEntries(), new FakeAspects()),
|
||||||
new GroupDocumentationTabViewModel(new FakeDocumentation(), students, groups));
|
new GroupDocumentationTabViewModel(new FakeDocumentation(), students, groups));
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Desktop.ViewModels.Students;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.Tests;
|
||||||
|
|
||||||
|
public sealed class GroupDocumentationQuickViewModelTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void Save_ErstelltPlanungFuerGesamteLerngruppe()
|
||||||
|
{
|
||||||
|
var group = new GroupDocumentationOption(Guid.NewGuid(), "10c · WAT");
|
||||||
|
var vm = new GroupDocumentationQuickViewModel([group])
|
||||||
|
{
|
||||||
|
SelectedGroup = group, Title = "Klausur ankündigen", Content = "Termin abstimmen",
|
||||||
|
};
|
||||||
|
|
||||||
|
vm.SaveCommand.Execute(null);
|
||||||
|
|
||||||
|
Assert.NotNull(vm.Result);
|
||||||
|
Assert.Equal(Guid.Empty, vm.Result!.StudentId);
|
||||||
|
Assert.Equal(group.Id, vm.Result.GroupId);
|
||||||
|
Assert.Equal(DocumentationType.Planning, vm.Result.Type);
|
||||||
|
Assert.True(vm.Result.ExcludeFromWebUntisSync);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -36,6 +36,25 @@ public sealed class GroupDocumentationTabViewModelTests
|
|||||||
Assert.Equal("Alt", vm.Entries[1].Model.Title);
|
Assert.Equal("Alt", vm.Entries[1].Model.Title);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Initialize_ZeigtGruppenweitenEintragAuchOhneSchueler()
|
||||||
|
{
|
||||||
|
var group = new LearningGroup { Name = "10c" };
|
||||||
|
var docs = new FakeDocumentation();
|
||||||
|
docs.Add(new Documentation
|
||||||
|
{
|
||||||
|
StudentId = Guid.Empty, GroupId = group.Id, Type = DocumentationType.Planning,
|
||||||
|
Title = "Klausur planen", Date = new DateOnly(2026, 9, 1),
|
||||||
|
});
|
||||||
|
|
||||||
|
var vm = BuildVm([], [group], docs);
|
||||||
|
vm.Initialize(group.Id);
|
||||||
|
|
||||||
|
var entry = Assert.Single(vm.Entries);
|
||||||
|
Assert.Equal("Gesamte Lerngruppe", entry.StudentName);
|
||||||
|
Assert.Equal("Planung / Erinnerung", entry.TypeLabel);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void Initialize_EintragAusAndererGruppe_WirdMitangezeigtAberAlsFremdMarkiert()
|
public void Initialize_EintragAusAndererGruppe_WirdMitangezeigtAberAlsFremdMarkiert()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -10,12 +10,42 @@ namespace LehrerApp.Desktop.Tests;
|
|||||||
/// zusammen, was Planung/Klausuren/Mitarbeit/Dokumentation ohnehin schon verwalten.
|
/// zusammen, was Planung/Klausuren/Mitarbeit/Dokumentation ohnehin schon verwalten.
|
||||||
public sealed class GroupOverviewViewModelTests
|
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,
|
private static GroupOverviewViewModel NewVm(FakeLessons? lessons = null, FakeExams? exams = null,
|
||||||
FakeSessions? sessions = null, FakeEntries? entries = null, FakeStudents? students = null,
|
FakeSessions? sessions = null, FakeEntries? entries = null, FakeStudents? students = null,
|
||||||
FakeDocumentation? documentation = null, FakeWorkTasks? tasks = null) =>
|
FakeDocumentation? documentation = null, FakeWorkTasks? tasks = null,
|
||||||
new(lessons ?? new FakeLessons(), exams ?? new FakeExams([]), sessions ?? new FakeSessions([]),
|
FakeResults? results = null, FakeGroups? groups = null) =>
|
||||||
|
new(lessons ?? new FakeLessons(), exams ?? new FakeExams([]), results ?? new FakeResults(),
|
||||||
|
sessions ?? new FakeSessions([]),
|
||||||
entries ?? new FakeEntries(), students ?? new FakeStudents([]), documentation ?? new FakeDocumentation(),
|
entries ?? new FakeEntries(), students ?? new FakeStudents([]), documentation ?? new FakeDocumentation(),
|
||||||
tasks ?? new FakeWorkTasks(), new AttendanceBalanceService(), new SchoolYearService());
|
tasks ?? new FakeWorkTasks(), groups ?? new FakeGroups([]), new AttendanceBalanceService(),
|
||||||
|
new GradingService(), new SchoolYearService());
|
||||||
|
|
||||||
private static (GroupOverviewViewModel Vm, FakeLessons Lessons, FakeExams Exams,
|
private static (GroupOverviewViewModel Vm, FakeLessons Lessons, FakeExams Exams,
|
||||||
FakeSessions Sessions, FakeEntries Entries, FakeStudents Students, Guid GroupId) BuildScenario(
|
FakeSessions Sessions, FakeEntries Entries, FakeStudents Students, Guid GroupId) BuildScenario(
|
||||||
@@ -76,6 +106,86 @@ public sealed class GroupOverviewViewModelTests
|
|||||||
Assert.Contains("Klassenarbeit 2", vm.NextExamLabel);
|
Assert.Contains("Klassenarbeit 2", vm.NextExamLabel);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Vorjahresvergleich_OhneVerknuepfteVorgaengergruppe_BleibtVerborgen()
|
||||||
|
{
|
||||||
|
var groupId = Guid.NewGuid();
|
||||||
|
var groups = new FakeGroups([new LearningGroup { Id = groupId, GradingSystem = GradingSystem.Grades1To6 }]);
|
||||||
|
var vm = NewVm(groups: groups);
|
||||||
|
|
||||||
|
vm.Initialize(groupId, "Testkurs");
|
||||||
|
|
||||||
|
Assert.False(vm.HasYearComparison);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Vorjahresvergleich_VorgaengerOhneKlausurergebnisse_BleibtVerborgen()
|
||||||
|
{
|
||||||
|
var previousId = Guid.NewGuid();
|
||||||
|
var groupId = Guid.NewGuid();
|
||||||
|
var groups = new FakeGroups([
|
||||||
|
new LearningGroup { Id = groupId, GradingSystem = GradingSystem.Grades1To6, PreviousGroupId = previousId },
|
||||||
|
new LearningGroup { Id = previousId, GradingSystem = GradingSystem.Grades1To6 },
|
||||||
|
]);
|
||||||
|
var vm = NewVm(groups: groups);
|
||||||
|
|
||||||
|
vm.Initialize(groupId, "Testkurs");
|
||||||
|
|
||||||
|
Assert.False(vm.HasYearComparison);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Vorjahresvergleich_ZeigtDurchschnitteBeiderJahreAn()
|
||||||
|
{
|
||||||
|
var previousId = Guid.NewGuid();
|
||||||
|
var groupId = Guid.NewGuid();
|
||||||
|
var groups = new FakeGroups([
|
||||||
|
new LearningGroup { Id = groupId, GradingSystem = GradingSystem.Grades1To6, PreviousGroupId = previousId },
|
||||||
|
new LearningGroup { Id = previousId, GradingSystem = GradingSystem.Grades1To6 },
|
||||||
|
]);
|
||||||
|
|
||||||
|
var previousExam = new Exam { Id = Guid.NewGuid(), GroupId = previousId };
|
||||||
|
var currentExam = new Exam { Id = Guid.NewGuid(), GroupId = groupId };
|
||||||
|
var exams = new FakeExams([previousExam, currentExam]);
|
||||||
|
|
||||||
|
var results = new FakeResults();
|
||||||
|
results.Add(new ExamResult { ExamId = previousExam.Id, StudentId = Guid.NewGuid(), Grade = "2" });
|
||||||
|
results.Add(new ExamResult { ExamId = previousExam.Id, StudentId = Guid.NewGuid(), Grade = "4" });
|
||||||
|
results.Add(new ExamResult { ExamId = currentExam.Id, StudentId = Guid.NewGuid(), Grade = "1" });
|
||||||
|
// Abwesende und leere Ergebnisse fließen bewusst nicht in den Schnitt ein.
|
||||||
|
results.Add(new ExamResult { ExamId = currentExam.Id, StudentId = Guid.NewGuid(), Absent = true, Grade = "6" });
|
||||||
|
|
||||||
|
var vm = NewVm(exams: exams, results: results, groups: groups);
|
||||||
|
|
||||||
|
vm.Initialize(groupId, "Testkurs");
|
||||||
|
|
||||||
|
Assert.True(vm.HasYearComparison);
|
||||||
|
Assert.Contains("Dieses Jahr: Ø 1,0 (1 Klausuren)", vm.YearComparisonLabel);
|
||||||
|
Assert.Contains("Vorjahr: Ø 3,0 (2 Klausuren)", vm.YearComparisonLabel);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Vorjahresvergleich_OhneEigeneKlausurenZeigtNurVorjahr()
|
||||||
|
{
|
||||||
|
var previousId = Guid.NewGuid();
|
||||||
|
var groupId = Guid.NewGuid();
|
||||||
|
var groups = new FakeGroups([
|
||||||
|
new LearningGroup { Id = groupId, GradingSystem = GradingSystem.Grades1To6, PreviousGroupId = previousId },
|
||||||
|
new LearningGroup { Id = previousId, GradingSystem = GradingSystem.Grades1To6 },
|
||||||
|
]);
|
||||||
|
var previousExam = new Exam { Id = Guid.NewGuid(), GroupId = previousId };
|
||||||
|
var exams = new FakeExams([previousExam]);
|
||||||
|
var results = new FakeResults();
|
||||||
|
results.Add(new ExamResult { ExamId = previousExam.Id, StudentId = Guid.NewGuid(), Grade = "3" });
|
||||||
|
|
||||||
|
var vm = NewVm(exams: exams, results: results, groups: groups);
|
||||||
|
|
||||||
|
vm.Initialize(groupId, "Testkurs");
|
||||||
|
|
||||||
|
Assert.True(vm.HasYearComparison);
|
||||||
|
Assert.Contains("noch keine Klausur", vm.YearComparisonLabel);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void Mitarbeit_OhneSitzungenZeigtHinweisOhneWarnung()
|
public void Mitarbeit_OhneSitzungenZeigtHinweisOhneWarnung()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -254,7 +254,8 @@ public sealed class HazardAssessmentWizardViewModelTests
|
|||||||
aiSettings.SetEnabled(true);
|
aiSettings.SetEnabled(true);
|
||||||
aiSettings.SetCredentialsAndToken("sebastian", "token-abc");
|
aiSettings.SetCredentialsAndToken("sebastian", "token-abc");
|
||||||
var ai = new AiPlanningService(new HttpClient(), new FakeLessons(), new FakeGroups([]),
|
var ai = new AiPlanningService(new HttpClient(), new FakeLessons(), new FakeGroups([]),
|
||||||
new FakeSubjects([]), new FakeCompetencyDomains(), new FakeAlternativeLessonPaths([]));
|
new FakeSubjects([]), new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions(), new FakeAlternativeLessonPaths([]),
|
||||||
|
TestSupport.BuildAppLogger());
|
||||||
var unit = new Unit { Title = "Redoxreaktionen" };
|
var unit = new Unit { Title = "Redoxreaktionen" };
|
||||||
var lesson = new Lesson { Topic = "Natrium in Wasser" };
|
var lesson = new Lesson { Topic = "Natrium in Wasser" };
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Desktop.Services;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.Tests;
|
||||||
|
|
||||||
|
public sealed class HomeworkOverdueServiceTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void Advance_Nach14Kalendertagen_NurOffeneNachreichungen()
|
||||||
|
{
|
||||||
|
var today = new DateOnly(2026, 9, 25);
|
||||||
|
var group = new LearningGroup { IsActive = true };
|
||||||
|
var archived = new LearningGroup { IsActive = false };
|
||||||
|
var dueSession = new ParticipationSession { GroupId = group.Id, Date = today.AddDays(-14) };
|
||||||
|
var recentSession = new ParticipationSession { GroupId = group.Id, Date = today.AddDays(-13) };
|
||||||
|
var archivedSession = new ParticipationSession { GroupId = archived.Id, Date = today.AddDays(-30) };
|
||||||
|
var open = new ParticipationEntry { SessionId = dueSession.Id, Homework = HomeworkStatus.MissingOpen };
|
||||||
|
var legacy = new ParticipationEntry { SessionId = dueSession.Id, HomeworkMissing = true };
|
||||||
|
var submitted = new ParticipationEntry { SessionId = dueSession.Id, Homework = HomeworkStatus.SubmittedLate };
|
||||||
|
var partial = new ParticipationEntry { SessionId = dueSession.Id, Homework = HomeworkStatus.PartiallyCompleted };
|
||||||
|
var recent = new ParticipationEntry { SessionId = recentSession.Id, Homework = HomeworkStatus.MissingOpen };
|
||||||
|
var oldArchived = new ParticipationEntry { SessionId = archivedSession.Id, Homework = HomeworkStatus.MissingOpen };
|
||||||
|
var entries = new FakeEntries();
|
||||||
|
foreach (var entry in new[] { open, legacy, submitted, partial, recent, oldArchived }) entries.Add(entry);
|
||||||
|
var service = new HomeworkOverdueService(new FakeGroups([group, archived]),
|
||||||
|
new FakeSessions([dueSession, recentSession, archivedSession]), entries);
|
||||||
|
|
||||||
|
Assert.Equal(2, service.Advance(today));
|
||||||
|
Assert.Equal(HomeworkStatus.MissingOverdue, open.Homework);
|
||||||
|
Assert.Equal(HomeworkStatus.MissingOverdue, legacy.Homework);
|
||||||
|
Assert.True(open.HomeworkMissing);
|
||||||
|
Assert.True(legacy.HomeworkMissing);
|
||||||
|
Assert.Equal(HomeworkStatus.SubmittedLate, submitted.Homework);
|
||||||
|
Assert.Equal(HomeworkStatus.PartiallyCompleted, partial.Homework);
|
||||||
|
Assert.Equal(HomeworkStatus.MissingOpen, recent.Homework);
|
||||||
|
Assert.Equal(HomeworkStatus.MissingOpen, oldArchived.Homework);
|
||||||
|
Assert.Equal(0, service.Advance(today));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Core.Services;
|
||||||
|
using LehrerApp.Desktop.ViewModels.Planning;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.Tests;
|
||||||
|
|
||||||
|
public sealed class LessonSchedulingServiceTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void UnitPicker_SchlaegtLaufendeEinheitVor_UndSpeichertNeuanlageNochNicht()
|
||||||
|
{
|
||||||
|
var groupId = Guid.NewGuid();
|
||||||
|
var planned = new Unit { GroupId = groupId, Title = "Später", Status = UnitStatus.Planned };
|
||||||
|
var active = new Unit { GroupId = groupId, Title = "Aktuell", Status = UnitStatus.Active };
|
||||||
|
var repo = new FakeUnits();
|
||||||
|
repo.Add(planned); repo.Add(active);
|
||||||
|
var vm = new TimetableUnitPickerViewModel(repo, groupId, "10c", new(2026, 9, 2), 3);
|
||||||
|
|
||||||
|
Assert.Equal(active.Id, vm.SelectedUnit?.Model.Id);
|
||||||
|
vm.NewUnitTitle = "Neue Reihe";
|
||||||
|
vm.SaveCommand.Execute(null);
|
||||||
|
|
||||||
|
Assert.True(vm.ResultIsNew);
|
||||||
|
Assert.Equal("Neue Reihe", vm.Result?.Title);
|
||||||
|
Assert.Null(repo.GetById(vm.Result!.Id));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Move_AendertDatumUndStunde_UndRuecktNurNichtDurchgefuehrteFolgestundenNach()
|
||||||
|
{
|
||||||
|
var unitId = Guid.NewGuid();
|
||||||
|
var groupId = Guid.NewGuid();
|
||||||
|
var moved = new Lesson { UnitId = unitId, GroupId = groupId, Date = new(2026, 9, 1), LessonNumber = 2 };
|
||||||
|
var draftFollowing = new Lesson { UnitId = unitId, GroupId = groupId, Date = new(2026, 9, 3), Status = LessonStatus.Draft };
|
||||||
|
var conducted = new Lesson { UnitId = unitId, GroupId = groupId, Date = new(2026, 9, 4), Status = LessonStatus.Conducted };
|
||||||
|
var repo = new FakeLessons();
|
||||||
|
repo.Add(moved); repo.Add(draftFollowing); repo.Add(conducted);
|
||||||
|
|
||||||
|
new LessonSchedulingService(repo).Move(moved, new(2026, 9, 8), 5, shiftFollowing: true);
|
||||||
|
|
||||||
|
Assert.Equal(new DateOnly(2026, 9, 8), moved.Date);
|
||||||
|
Assert.Equal(5, moved.LessonNumber);
|
||||||
|
Assert.Equal(new DateOnly(2026, 9, 10), draftFollowing.Date);
|
||||||
|
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()
|
||||||
|
{
|
||||||
|
var source = new Lesson
|
||||||
|
{
|
||||||
|
UnitId = Guid.NewGuid(), GroupId = Guid.NewGuid(), Date = new(2026, 9, 1),
|
||||||
|
LessonNumber = 3, Topic = "Fotosynthese", Homework = "Aufgabe 2",
|
||||||
|
Phases =
|
||||||
|
[
|
||||||
|
new LessonPhaseStep { Name = "Einstieg", DurationMinutes = 30 },
|
||||||
|
new LessonPhaseStep { Name = "Experiment", DurationMinutes = 30 },
|
||||||
|
new LessonPhaseStep { Name = "Sicherung", DurationMinutes = 20 },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
var repo = new FakeLessons();
|
||||||
|
repo.Add(source);
|
||||||
|
|
||||||
|
var continuation = new LessonSchedulingService(repo).SplitAndMoveSecondPart(source, 45,
|
||||||
|
new(2026, 9, 3), 6, new TimeOnly(12, 15));
|
||||||
|
|
||||||
|
Assert.Equal([30, 15], source.Phases.Select(p => p.DurationMinutes));
|
||||||
|
Assert.Equal([15, 20], continuation.Phases.Select(p => p.DurationMinutes));
|
||||||
|
Assert.Equal("Fotosynthese – Fortsetzung", continuation.Topic);
|
||||||
|
Assert.Null(source.Homework);
|
||||||
|
Assert.Equal("Aufgabe 2", continuation.Homework);
|
||||||
|
Assert.Equal(6, continuation.LessonNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Move_LehntBelegtenZielterminAb()
|
||||||
|
{
|
||||||
|
var groupId = Guid.NewGuid();
|
||||||
|
var source = new Lesson { GroupId = groupId, Date = new(2026, 9, 1), LessonNumber = 1 };
|
||||||
|
var occupied = new Lesson { GroupId = groupId, Date = new(2026, 9, 2), LessonNumber = 4 };
|
||||||
|
var repo = new FakeLessons();
|
||||||
|
repo.Add(source); repo.Add(occupied);
|
||||||
|
|
||||||
|
var error = Assert.Throws<InvalidOperationException>(() =>
|
||||||
|
new LessonSchedulingService(repo).Move(source, occupied.Date, 4, false));
|
||||||
|
|
||||||
|
Assert.Contains("bereits eine Planung", error.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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),
|
Date = new DateOnly(2026, 8, 19),
|
||||||
Comment = "Sitzplan",
|
Comment = "Sitzplan",
|
||||||
LessonId = Guid.NewGuid(),
|
LessonId = Guid.NewGuid(),
|
||||||
CompetencyCodes = ["K1"],
|
Competencies = [new CompetencyReference { ItemId = Guid.NewGuid(), Code = "K1", Description = "Kompetenz" }],
|
||||||
};
|
};
|
||||||
var vm = new AddSessionDialogViewModel(session)
|
var vm = new AddSessionDialogViewModel(session)
|
||||||
{
|
{
|
||||||
@@ -29,7 +29,7 @@ public sealed class ParticipationSessionEditingTests
|
|||||||
Assert.Equal(new DateOnly(2026, 8, 20), session.Date);
|
Assert.Equal(new DateOnly(2026, 8, 20), session.Date);
|
||||||
Assert.Equal("Elektrische Stromkreise", session.Comment);
|
Assert.Equal("Elektrische Stromkreise", session.Comment);
|
||||||
Assert.NotNull(session.LessonId);
|
Assert.NotNull(session.LessonId);
|
||||||
Assert.Equal(["K1"], session.CompetencyCodes);
|
Assert.Equal(["K1"], session.Competencies.Select(c => c.Code));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -45,7 +45,7 @@ public sealed class ParticipationSessionEditingTests
|
|||||||
var sessions = new FakeSessions([session]);
|
var sessions = new FakeSessions([session]);
|
||||||
var vm = new ParticipationTabViewModel(
|
var vm = new ParticipationTabViewModel(
|
||||||
sessions, new FakeEntries(), new FakeAspects(), new FakeStudents([]),
|
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 =>
|
vm.OnEditSession = existing =>
|
||||||
{
|
{
|
||||||
existing.Comment = "Nachbesprechung Elektrizität";
|
existing.Comment = "Nachbesprechung Elektrizität";
|
||||||
@@ -70,7 +70,7 @@ public sealed class ParticipationSessionEditingTests
|
|||||||
entries.Add(new ParticipationEntry { SessionId = session.Id, StudentId = Guid.NewGuid() });
|
entries.Add(new ParticipationEntry { SessionId = session.Id, StudentId = Guid.NewGuid() });
|
||||||
var vm = new ParticipationTabViewModel(
|
var vm = new ParticipationTabViewModel(
|
||||||
sessions, entries, new FakeAspects(), new FakeStudents([]),
|
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.Initialize(group.Id, group.SchoolYear);
|
||||||
vm.SelectedSession = vm.Sessions.Single(s => s.Id == session.Id);
|
vm.SelectedSession = vm.Sessions.Single(s => s.Id == session.Id);
|
||||||
|
|
||||||
@@ -87,6 +87,49 @@ public sealed class ParticipationSessionEditingTests
|
|||||||
Assert.Null(sessions.GetById(session.Id));
|
Assert.Null(sessions.GetById(session.Id));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Sitzung_MitBewertetenAspektenAberOhneKompetenzbewertung_ZeigtGeschaetztenWert()
|
||||||
|
{
|
||||||
|
var subjectId = Guid.NewGuid();
|
||||||
|
var group = new LearningGroup { Name = "8a", SchoolYear = "2026/27", SubjectId = subjectId, GradeLevel = 8 };
|
||||||
|
var student = new Student { FirstName = "Ada", LastName = "Lovelace" };
|
||||||
|
var item = new CompetencyItem { Code = "K1", Description = "Kompetenz" };
|
||||||
|
var session = new ParticipationSession
|
||||||
|
{
|
||||||
|
GroupId = group.Id, Date = new DateOnly(2026, 8, 19),
|
||||||
|
Competencies = [new CompetencyReference { ItemId = item.Id, Code = item.Code, Description = item.Description }],
|
||||||
|
};
|
||||||
|
var sessions = new FakeSessions([session]);
|
||||||
|
var entries = new FakeEntries();
|
||||||
|
entries.Add(new ParticipationEntry
|
||||||
|
{
|
||||||
|
SessionId = session.Id, StudentId = student.Id,
|
||||||
|
Ratings = [new AspectRating { Key = "quality", Value = 2 }],
|
||||||
|
});
|
||||||
|
var aspects = new FakeAspects();
|
||||||
|
aspects.Save(new ParticipationAspect
|
||||||
|
{
|
||||||
|
Key = "quality", Label = "Qualität", ValueType = AspectValueType.Scale5, IsActive = true,
|
||||||
|
});
|
||||||
|
var versions = new FakeCompetencyCatalogVersions();
|
||||||
|
var version = versions.GetOrCreateDefault(subjectId);
|
||||||
|
var domains = new FakeCompetencyDomains();
|
||||||
|
domains.Add(new CompetencyDomain
|
||||||
|
{
|
||||||
|
SubjectId = subjectId, GradeLevel = 8, VersionId = version.Id, Name = "Bereich", Items = [item],
|
||||||
|
});
|
||||||
|
var vm = new ParticipationTabViewModel(sessions, entries, aspects, new FakeStudents([student]),
|
||||||
|
new FakeMemberships([]), new FakeGroups([group]), domains, versions);
|
||||||
|
vm.Initialize(group.Id, group.SchoolYear);
|
||||||
|
|
||||||
|
vm.SelectedSession = vm.Sessions.Single(s => s.Id == session.Id);
|
||||||
|
|
||||||
|
var row = Assert.Single(vm.StudentRows);
|
||||||
|
var cell = Assert.Single(row.CompetencyCells);
|
||||||
|
Assert.True(cell.IsEstimated);
|
||||||
|
Assert.Equal(2, cell.Value); // einziger bewerteter Aspekt "quality" = 2, kein Tageshighlight
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task LoeschenBefehl_BrichtBeiAbgelehnterBestaetigungAb()
|
public async Task LoeschenBefehl_BrichtBeiAbgelehnterBestaetigungAb()
|
||||||
{
|
{
|
||||||
@@ -95,7 +138,7 @@ public sealed class ParticipationSessionEditingTests
|
|||||||
var sessions = new FakeSessions([session]);
|
var sessions = new FakeSessions([session]);
|
||||||
var vm = new ParticipationTabViewModel(
|
var vm = new ParticipationTabViewModel(
|
||||||
sessions, new FakeEntries(), new FakeAspects(), new FakeStudents([]),
|
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.Initialize(group.Id, group.SchoolYear);
|
||||||
vm.SelectedSession = vm.Sessions.Single(s => s.Id == session.Id);
|
vm.SelectedSession = vm.Sessions.Single(s => s.Id == session.Id);
|
||||||
vm.OnConfirmDeleteSession = (_, _) => Task.FromResult(false);
|
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",
|
Title = "Optik",
|
||||||
StartDate = new DateOnly(2026, 9, 1),
|
StartDate = new DateOnly(2026, 9, 1),
|
||||||
EndDate = new DateOnly(2026, 10, 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,
|
Status = UnitStatus.Active,
|
||||||
Notes = "Experimente",
|
Notes = "Experimente",
|
||||||
};
|
};
|
||||||
@@ -61,7 +65,11 @@ public sealed class PlanningExchangeServiceTests
|
|||||||
Assert.Equal(targetGroupId, result.Unit.GroupId);
|
Assert.Equal(targetGroupId, result.Unit.GroupId);
|
||||||
Assert.Equal("Optik", result.Unit.Title);
|
Assert.Equal("Optik", result.Unit.Title);
|
||||||
Assert.Equal(UnitStatus.Active, result.Unit.Status);
|
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);
|
var importedLesson = Assert.Single(result.Lessons);
|
||||||
Assert.NotEqual(sourceLesson.Id, importedLesson.Id);
|
Assert.NotEqual(sourceLesson.Id, importedLesson.Id);
|
||||||
Assert.Equal(result.Unit.Id, importedLesson.UnitId);
|
Assert.Equal(result.Unit.Id, importedLesson.UnitId);
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ public class PlanningTabViewModelTests
|
|||||||
var lessons = new FakeLessons();
|
var lessons = new FakeLessons();
|
||||||
|
|
||||||
var vm = new PlanningTabViewModel(units, lessons, groups, subjects, competencyDomains,
|
var vm = new PlanningTabViewModel(units, lessons, groups, subjects, competencyDomains,
|
||||||
TestSupport.BuildAiSettingsService(), new FakeSessions([]));
|
new FakeCompetencyCatalogVersions(), TestSupport.BuildAiSettingsService(), new FakeSessions([]));
|
||||||
vm.Initialize(groupId);
|
vm.Initialize(groupId);
|
||||||
|
|
||||||
return (vm, units, lessons, groupId);
|
return (vm, units, lessons, groupId);
|
||||||
@@ -45,6 +45,21 @@ public class PlanningTabViewModelTests
|
|||||||
Assert.Contains("2 / 3", summary.ProgressText);
|
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]
|
[Fact]
|
||||||
public async Task MoveLesson_MitNachrueckenVerschiebtNurGeplanteFolgestundenNachDemStichtag()
|
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
|
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]
|
[Fact]
|
||||||
public async Task CopyUnit_ErhaeltAbstaendeUndSetztGroupIdAufZielgruppe()
|
public async Task CopyUnit_ErhaeltAbstaendeUndSetztGroupIdAufZielgruppe()
|
||||||
{
|
{
|
||||||
@@ -238,7 +277,7 @@ public class PlanningTabViewModelTests
|
|||||||
var lessons = new FakeLessons();
|
var lessons = new FakeLessons();
|
||||||
var sessions = new FakeSessions([]);
|
var sessions = new FakeSessions([]);
|
||||||
var vm = new PlanningTabViewModel(units, lessons, groups, new FakeSubjects([]),
|
var vm = new PlanningTabViewModel(units, lessons, groups, new FakeSubjects([]),
|
||||||
new FakeCompetencyDomains(), TestSupport.BuildAiSettingsService(), sessions);
|
new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions(), TestSupport.BuildAiSettingsService(), sessions);
|
||||||
vm.Initialize(groupId);
|
vm.Initialize(groupId);
|
||||||
|
|
||||||
var unit = new Unit { GroupId = groupId, Title = "Optik" };
|
var unit = new Unit { GroupId = groupId, Title = "Optik" };
|
||||||
@@ -273,7 +312,7 @@ public class PlanningTabViewModelTests
|
|||||||
var lessons = new FakeLessons();
|
var lessons = new FakeLessons();
|
||||||
var sessions = new FakeSessions([]);
|
var sessions = new FakeSessions([]);
|
||||||
var vm = new PlanningTabViewModel(units, lessons, groups, new FakeSubjects([]),
|
var vm = new PlanningTabViewModel(units, lessons, groups, new FakeSubjects([]),
|
||||||
new FakeCompetencyDomains(), TestSupport.BuildAiSettingsService(), sessions);
|
new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions(), TestSupport.BuildAiSettingsService(), sessions);
|
||||||
vm.Initialize(groupId);
|
vm.Initialize(groupId);
|
||||||
|
|
||||||
var unit = new Unit { GroupId = groupId, Title = "Optik" };
|
var unit = new Unit { GroupId = groupId, Title = "Optik" };
|
||||||
@@ -294,4 +333,44 @@ public class PlanningTabViewModelTests
|
|||||||
Assert.Single(sessions.GetByGroup(groupId));
|
Assert.Single(sessions.GetByGroup(groupId));
|
||||||
Assert.Equal("Für diese Stunde existiert bereits eine Sitzung.", notified);
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -83,6 +83,67 @@ public sealed class QuickInputViewModelTests
|
|||||||
Assert.Equal(0.4, vm.CurrentStudentContentOpacity);
|
Assert.Equal(0.4, vm.CurrentStudentContentOpacity);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ClearRating_SetztVersehentlichGesetzteBewertungAufNichtBewertetZurueck()
|
||||||
|
{
|
||||||
|
var aspects = new List<AspectColumnDef>
|
||||||
|
{
|
||||||
|
new(new ParticipationAspect { Key = "quality", Label = "Qualität" }),
|
||||||
|
};
|
||||||
|
var rows = new List<ParticipationStudentRow>
|
||||||
|
{
|
||||||
|
new(Guid.NewGuid(), "Anna", new ParticipationEntry(), aspects, []),
|
||||||
|
};
|
||||||
|
var vm = new QuickInputViewModel(rows, aspects);
|
||||||
|
vm.SetRatingByNumber(4); // aus Versehen eine Note für Qualität vergeben
|
||||||
|
|
||||||
|
vm.ClearRating();
|
||||||
|
|
||||||
|
Assert.Null(vm.AspectRows[0].Value);
|
||||||
|
Assert.Null(rows[0].GetRating("quality"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void SetDayHighlight_SpeichertAufDerZeileUndAktualisiertDieAnzeige()
|
||||||
|
{
|
||||||
|
var aspects = new List<AspectColumnDef>
|
||||||
|
{
|
||||||
|
new(new ParticipationAspect { Key = "quality", Label = "Qualität" }),
|
||||||
|
};
|
||||||
|
var rows = new List<ParticipationStudentRow>
|
||||||
|
{
|
||||||
|
new(Guid.NewGuid(), "Anna", new ParticipationEntry(), aspects, []),
|
||||||
|
};
|
||||||
|
var vm = new QuickInputViewModel(rows, aspects);
|
||||||
|
|
||||||
|
vm.SetDayHighlight(DayHighlightKind.Standout);
|
||||||
|
|
||||||
|
Assert.Equal(DayHighlightKind.Standout, rows[0].DayHighlight);
|
||||||
|
Assert.Equal("👑", vm.CurrentStudentDayHighlightSymbol);
|
||||||
|
Assert.Equal("Spitzentag", vm.CurrentStudentDayHighlightLabel);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ZurueckZuVorherigemSchueler_ZeigtDessenTagesflaggeWiederAn()
|
||||||
|
{
|
||||||
|
var aspects = new List<AspectColumnDef>
|
||||||
|
{
|
||||||
|
new(new ParticipationAspect { Key = "quality", Label = "Qualität" }),
|
||||||
|
};
|
||||||
|
var rows = new List<ParticipationStudentRow>
|
||||||
|
{
|
||||||
|
new(Guid.NewGuid(), "Anna", new ParticipationEntry(), aspects, []),
|
||||||
|
new(Guid.NewGuid(), "Ben", new ParticipationEntry(), aspects, []),
|
||||||
|
};
|
||||||
|
var vm = new QuickInputViewModel(rows, aspects);
|
||||||
|
|
||||||
|
vm.SetDayHighlight(DayHighlightKind.Sleepy); // Anna
|
||||||
|
vm.NextStudent(); // zu Ben, keine Flagge
|
||||||
|
vm.PreviousStudent(); // zurück zu Anna
|
||||||
|
|
||||||
|
Assert.Equal(DayHighlightKind.Sleepy, vm.CurrentStudentDayHighlight);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void VorherigerAspekt_SpringtRueckwaertsMitUmlauf()
|
public void VorherigerAspekt_SpringtRueckwaertsMitUmlauf()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -78,4 +78,16 @@ public sealed class RatingCellTests
|
|||||||
var cell = new RatingCell(Guid.NewGuid(), "k", 2);
|
var cell = new RatingCell(Guid.NewGuid(), "k", 2);
|
||||||
Assert.Equal("++", cell.DisplayLabel);
|
Assert.Equal("++", cell.DisplayLabel);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void SetValue_AufGeschaetzterZelle_MarkiertSieAlsBestaetigt()
|
||||||
|
{
|
||||||
|
var cell = new RatingCell(Guid.NewGuid(), "k", 1, isEstimated: true);
|
||||||
|
Assert.True(cell.IsEstimated);
|
||||||
|
|
||||||
|
cell.SetValue(1); // bestätigt zufällig denselben Wert wie die Schätzung
|
||||||
|
|
||||||
|
Assert.False(cell.IsEstimated);
|
||||||
|
Assert.Equal(1, cell.Value);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -256,6 +256,30 @@ public sealed class SeatingPlanViewModelTests
|
|||||||
Assert.Single(sessions.GetByGroup(groupId));
|
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]
|
[Fact]
|
||||||
public void SelectOrCreateSessionForLesson_KeineSitzungVorhanden_LegtVerknuepfteAnUndWaehltSieAus()
|
public void SelectOrCreateSessionForLesson_KeineSitzungVorhanden_LegtVerknuepfteAnUndWaehltSieAus()
|
||||||
{
|
{
|
||||||
@@ -472,6 +496,7 @@ public sealed class SeatingPlanViewModelTests
|
|||||||
vm.SetRatingByNumber(5);
|
vm.SetRatingByNumber(5);
|
||||||
vm.ApplyAttendanceShortcut(1, clear: false);
|
vm.ApplyAttendanceShortcut(1, clear: false);
|
||||||
vm.ApplyHomeworkShortcut(7, clear: false);
|
vm.ApplyHomeworkShortcut(7, clear: false);
|
||||||
|
vm.ApplyDayHighlightShortcut(1, clear: false);
|
||||||
|
|
||||||
var session = Assert.Single(sessions.GetByGroup(groupId));
|
var session = Assert.Single(sessions.GetByGroup(groupId));
|
||||||
Assert.Equal(DateOnly.FromDateTime(DateTime.Today), session.Date);
|
Assert.Equal(DateOnly.FromDateTime(DateTime.Today), session.Date);
|
||||||
@@ -481,6 +506,56 @@ public sealed class SeatingPlanViewModelTests
|
|||||||
Assert.Equal(AttendanceStatus.Present, entry.Attendance);
|
Assert.Equal(AttendanceStatus.Present, entry.Attendance);
|
||||||
Assert.Equal(HomeworkStatus.MissingOpen, entry.Homework);
|
Assert.Equal(HomeworkStatus.MissingOpen, entry.Homework);
|
||||||
Assert.True(entry.HomeworkMissing);
|
Assert.True(entry.HomeworkMissing);
|
||||||
|
Assert.Equal(DayHighlightKind.Standout, entry.DayHighlight);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void SitzplatzBewertung_TagesflaggeKannWiederGeloeschtWerden()
|
||||||
|
{
|
||||||
|
var groupId = Guid.NewGuid();
|
||||||
|
var studentId = Guid.NewGuid();
|
||||||
|
var sessions = new FakeSessions([]);
|
||||||
|
var entries = new FakeEntries();
|
||||||
|
var vm = new SeatAssessmentViewModel(sessions, entries, new FakeAspects(),
|
||||||
|
groupId, studentId, "Beispiel, Anna", canEdit: true);
|
||||||
|
|
||||||
|
vm.ApplyDayHighlightShortcut(3, clear: false); // aus Versehen "Schlechter Tag" gesetzt
|
||||||
|
vm.ApplyDayHighlightShortcut(null, clear: true);
|
||||||
|
|
||||||
|
var session = Assert.Single(sessions.GetByGroup(groupId));
|
||||||
|
var entry = entries.GetBySessionAndStudent(session.Id, studentId)!;
|
||||||
|
Assert.Null(entry.DayHighlight);
|
||||||
|
Assert.Equal("Keine Markierung", vm.DayHighlightLabel);
|
||||||
|
Assert.All(vm.DayHighlightChoices, c => Assert.Equal(c.Kind is null, c.IsSelected));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void SitzplatzBewertung_SchlaegtQuantitaetAusStrichlisteVor()
|
||||||
|
{
|
||||||
|
var groupId = Guid.NewGuid();
|
||||||
|
var studentId = Guid.NewGuid();
|
||||||
|
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||||
|
var session = new ParticipationSession { GroupId = groupId, Date = today };
|
||||||
|
var sessions = new FakeSessions([session]);
|
||||||
|
var entries = new FakeEntries();
|
||||||
|
entries.Add(new ParticipationEntry { SessionId = session.Id, StudentId = studentId, RaisedHandCount = 3 });
|
||||||
|
|
||||||
|
var vm = new SeatAssessmentViewModel(sessions, entries, new FakeAspects(),
|
||||||
|
groupId, studentId, "Beispiel, Anna", canEdit: true);
|
||||||
|
|
||||||
|
var quantityRow = vm.AspectRows.Single(r => r.Key == "quantity");
|
||||||
|
Assert.True(quantityRow.HasSuggestion);
|
||||||
|
Assert.Equal(0, quantityRow.SuggestedValue); // 3 gemeldet -> "∼" laut ParticipationCountSuggestion
|
||||||
|
Assert.Contains("3× gemeldet", quantityRow.SuggestionLabel);
|
||||||
|
|
||||||
|
var qualityRow = vm.AspectRows.Single(r => r.Key == "quality");
|
||||||
|
Assert.False(qualityRow.HasSuggestion);
|
||||||
|
|
||||||
|
quantityRow.ApplySuggestionCommand.Execute(null);
|
||||||
|
|
||||||
|
Assert.Equal(0, quantityRow.Value);
|
||||||
|
var updatedEntry = entries.GetBySessionAndStudent(session.Id, studentId)!;
|
||||||
|
Assert.Equal(0, updatedEntry.Ratings.Single(r => r.Key == "quantity").Value);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -517,6 +592,60 @@ public sealed class SeatingPlanViewModelTests
|
|||||||
Assert.Null(vm.SelectedSession);
|
Assert.Null(vm.SelectedSession);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TallyRaisedHand_ErhoehtNurGemeldetZaehler()
|
||||||
|
{
|
||||||
|
var groupId = Guid.NewGuid();
|
||||||
|
var student = new Student { FirstName = "Anna", LastName = "A" };
|
||||||
|
var plan = new SeatingPlan
|
||||||
|
{
|
||||||
|
GroupId = groupId, Name = "Standard", Rows = 1, Columns = 1,
|
||||||
|
Assignments = [new SeatAssignment { StudentId = student.Id }],
|
||||||
|
};
|
||||||
|
var sessions = new FakeSessions([]);
|
||||||
|
var entries = new FakeEntries();
|
||||||
|
var vm = new SeatingPlanTabViewModel(new FakeSeatingPlans([plan]), new FakeStudents([student]),
|
||||||
|
new FakeMemberships([new GroupMembership { GroupId = groupId, StudentId = student.Id }]),
|
||||||
|
sessions, entries, new FakeAspects());
|
||||||
|
vm.Initialize(groupId, isReadOnly: false);
|
||||||
|
var seat = vm.Seats.Single();
|
||||||
|
|
||||||
|
seat.TallyRaisedHandCommand.Execute(null);
|
||||||
|
seat.TallyRaisedHandCommand.Execute(null);
|
||||||
|
|
||||||
|
Assert.Equal(2, seat.RaisedHandCount);
|
||||||
|
Assert.Equal(0, seat.CalledOnCount);
|
||||||
|
var session = Assert.Single(sessions.GetByGroup(groupId));
|
||||||
|
var entry = entries.GetBySessionAndStudent(session.Id, student.Id)!;
|
||||||
|
Assert.Equal(2, entry.RaisedHandCount);
|
||||||
|
Assert.Equal(0, entry.CalledOnCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TallyCalledOn_ErhoehtBeideZaehler()
|
||||||
|
{
|
||||||
|
var groupId = Guid.NewGuid();
|
||||||
|
var student = new Student { FirstName = "Anna", LastName = "A" };
|
||||||
|
var plan = new SeatingPlan
|
||||||
|
{
|
||||||
|
GroupId = groupId, Name = "Standard", Rows = 1, Columns = 1,
|
||||||
|
Assignments = [new SeatAssignment { StudentId = student.Id }],
|
||||||
|
};
|
||||||
|
var sessions = new FakeSessions([]);
|
||||||
|
var entries = new FakeEntries();
|
||||||
|
var vm = new SeatingPlanTabViewModel(new FakeSeatingPlans([plan]), new FakeStudents([student]),
|
||||||
|
new FakeMemberships([new GroupMembership { GroupId = groupId, StudentId = student.Id }]),
|
||||||
|
sessions, entries, new FakeAspects());
|
||||||
|
vm.Initialize(groupId, isReadOnly: false);
|
||||||
|
var seat = vm.Seats.Single();
|
||||||
|
|
||||||
|
seat.TallyRaisedHandCommand.Execute(null); // erste Meldung, nicht drangekommen
|
||||||
|
seat.TallyCalledOnCommand.Execute(null); // zweite Meldung, drangekommen
|
||||||
|
|
||||||
|
Assert.Equal(2, seat.RaisedHandCount);
|
||||||
|
Assert.Equal(1, seat.CalledOnCount);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task AssessStudent_LegtErstBeiTatsaechlicherBewertungEineSitzungAn()
|
public async Task AssessStudent_LegtErstBeiTatsaechlicherBewertungEineSitzungAn()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -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));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ using LehrerApp.Sync;
|
|||||||
using LehrerApp.Sync.Models;
|
using LehrerApp.Sync.Models;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using Xunit;
|
using Xunit;
|
||||||
|
using LehrerApp.Templating;
|
||||||
|
|
||||||
namespace LehrerApp.Desktop.Tests;
|
namespace LehrerApp.Desktop.Tests;
|
||||||
|
|
||||||
@@ -15,6 +16,7 @@ public sealed class SettingsViewModelTests
|
|||||||
private static SettingsViewModel BuildViewModel(FakeSchoolHolidays? holidays = null,
|
private static SettingsViewModel BuildViewModel(FakeSchoolHolidays? holidays = null,
|
||||||
FakeSupervisionDuties? supervisionDuties = null,
|
FakeSupervisionDuties? supervisionDuties = null,
|
||||||
FakeSubjects? subjects = null, FakeCompetencyDomains? competencyDomains = null,
|
FakeSubjects? subjects = null, FakeCompetencyDomains? competencyDomains = null,
|
||||||
|
FakeCompetencyCatalogVersions? competencyVersions = null,
|
||||||
EventQueue? eventQueue = null, SyncKeyStatus? syncKeyStatus = null,
|
EventQueue? eventQueue = null, SyncKeyStatus? syncKeyStatus = null,
|
||||||
SyncKeyRecoveryService? syncKeyRecovery = null, AppearanceSettingsService? appearance = null,
|
SyncKeyRecoveryService? syncKeyRecovery = null, AppearanceSettingsService? appearance = null,
|
||||||
TrashViewModel? trashTab = null)
|
TrashViewModel? trashTab = null)
|
||||||
@@ -26,14 +28,18 @@ public sealed class SettingsViewModelTests
|
|||||||
Directory.CreateDirectory(tempPath);
|
Directory.CreateDirectory(tempPath);
|
||||||
|
|
||||||
return new SettingsViewModel(
|
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 FakeSchemes(), new GradingService(), new BackupService(tempPath),
|
||||||
|
new BackupSettingsService(tempPath),
|
||||||
new DatabaseEncryptionService(), new AppLockService(tempPath),
|
new DatabaseEncryptionService(), new AppLockService(tempPath),
|
||||||
new LiteDbContext(new MemoryStream()), new PrivacySettingsService(tempPath),
|
new LiteDbContext(new MemoryStream()), new PrivacySettingsService(tempPath),
|
||||||
new FakeDocumentation(), new FakeStudents([]), new FakeShorthandCodes([]),
|
new FakeDocumentation(), new FakeStudents([]), new FakeShorthandCodes([]),
|
||||||
holidays ?? new FakeSchoolHolidays(), new SchoolCalendarSettingsService(tempPath),
|
holidays ?? new FakeSchoolHolidays(), new SchoolCalendarSettingsService(tempPath),
|
||||||
new PeriodScheduleService(tempPath), supervisionDuties ?? new FakeSupervisionDuties(),
|
new PeriodScheduleService(tempPath), supervisionDuties ?? new FakeSupervisionDuties(),
|
||||||
new LetterTemplateService(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.BuildWebUntisSettingsService(),
|
||||||
TestSupport.BuildAnnualPlanSettingsService(),
|
TestSupport.BuildAnnualPlanSettingsService(),
|
||||||
TestSupport.BuildSyncSettingsService(), TestSupport.BuildSyncAuthService(),
|
TestSupport.BuildSyncSettingsService(), TestSupport.BuildSyncAuthService(),
|
||||||
@@ -217,6 +223,25 @@ public sealed class SettingsViewModelTests
|
|||||||
Assert.Empty(queue.GetUnreviewed());
|
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]
|
[Fact]
|
||||||
public void AddSchoolHoliday_GueltigeEingabe_WirdGespeichertUndInListeAngezeigt()
|
public void AddSchoolHoliday_GueltigeEingabe_WirdGespeichertUndInListeAngezeigt()
|
||||||
{
|
{
|
||||||
@@ -312,13 +337,16 @@ public sealed class SettingsViewModelTests
|
|||||||
var calendarSettings = new SchoolCalendarSettingsService(tempPath);
|
var calendarSettings = new SchoolCalendarSettingsService(tempPath);
|
||||||
|
|
||||||
var vm = new SettingsViewModel(
|
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 FakeSchemes(), new GradingService(), new BackupService(tempPath),
|
||||||
|
new BackupSettingsService(tempPath),
|
||||||
new DatabaseEncryptionService(), new AppLockService(tempPath),
|
new DatabaseEncryptionService(), new AppLockService(tempPath),
|
||||||
new LiteDbContext(new MemoryStream()), new PrivacySettingsService(tempPath),
|
new LiteDbContext(new MemoryStream()), new PrivacySettingsService(tempPath),
|
||||||
new FakeDocumentation(), new FakeStudents([]), new FakeShorthandCodes([]),
|
new FakeDocumentation(), new FakeStudents([]), new FakeShorthandCodes([]),
|
||||||
new FakeSchoolHolidays(), calendarSettings, new PeriodScheduleService(tempPath),
|
new FakeSchoolHolidays(), calendarSettings, new PeriodScheduleService(tempPath),
|
||||||
new FakeSupervisionDuties(), new LetterTemplateService(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.BuildWebUntisSettingsService(),
|
||||||
TestSupport.BuildAnnualPlanSettingsService(),
|
TestSupport.BuildAnnualPlanSettingsService(),
|
||||||
TestSupport.BuildSyncSettingsService(), TestSupport.BuildSyncAuthService(), TestSupport.BuildEventQueue(),
|
TestSupport.BuildSyncSettingsService(), TestSupport.BuildSyncAuthService(), TestSupport.BuildEventQueue(),
|
||||||
@@ -339,13 +367,16 @@ public sealed class SettingsViewModelTests
|
|||||||
var periodSchedule = new PeriodScheduleService(tempPath);
|
var periodSchedule = new PeriodScheduleService(tempPath);
|
||||||
|
|
||||||
var vm = new SettingsViewModel(
|
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 FakeSchemes(), new GradingService(), new BackupService(tempPath),
|
||||||
|
new BackupSettingsService(tempPath),
|
||||||
new DatabaseEncryptionService(), new AppLockService(tempPath),
|
new DatabaseEncryptionService(), new AppLockService(tempPath),
|
||||||
new LiteDbContext(new MemoryStream()), new PrivacySettingsService(tempPath),
|
new LiteDbContext(new MemoryStream()), new PrivacySettingsService(tempPath),
|
||||||
new FakeDocumentation(), new FakeStudents([]), new FakeShorthandCodes([]),
|
new FakeDocumentation(), new FakeStudents([]), new FakeShorthandCodes([]),
|
||||||
new FakeSchoolHolidays(), new SchoolCalendarSettingsService(tempPath), periodSchedule,
|
new FakeSchoolHolidays(), new SchoolCalendarSettingsService(tempPath), periodSchedule,
|
||||||
new FakeSupervisionDuties(), new LetterTemplateService(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.BuildWebUntisSettingsService(),
|
||||||
TestSupport.BuildAnnualPlanSettingsService(),
|
TestSupport.BuildAnnualPlanSettingsService(),
|
||||||
TestSupport.BuildSyncSettingsService(), TestSupport.BuildSyncAuthService(), TestSupport.BuildEventQueue(),
|
TestSupport.BuildSyncSettingsService(), TestSupport.BuildSyncAuthService(), TestSupport.BuildEventQueue(),
|
||||||
@@ -370,13 +401,16 @@ public sealed class SettingsViewModelTests
|
|||||||
var periodSchedule = new PeriodScheduleService(tempPath);
|
var periodSchedule = new PeriodScheduleService(tempPath);
|
||||||
|
|
||||||
var vm = new SettingsViewModel(
|
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 FakeSchemes(), new GradingService(), new BackupService(tempPath),
|
||||||
|
new BackupSettingsService(tempPath),
|
||||||
new DatabaseEncryptionService(), new AppLockService(tempPath),
|
new DatabaseEncryptionService(), new AppLockService(tempPath),
|
||||||
new LiteDbContext(new MemoryStream()), new PrivacySettingsService(tempPath),
|
new LiteDbContext(new MemoryStream()), new PrivacySettingsService(tempPath),
|
||||||
new FakeDocumentation(), new FakeStudents([]), new FakeShorthandCodes([]),
|
new FakeDocumentation(), new FakeStudents([]), new FakeShorthandCodes([]),
|
||||||
new FakeSchoolHolidays(), new SchoolCalendarSettingsService(tempPath), periodSchedule,
|
new FakeSchoolHolidays(), new SchoolCalendarSettingsService(tempPath), periodSchedule,
|
||||||
new FakeSupervisionDuties(), new LetterTemplateService(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.BuildWebUntisSettingsService(),
|
||||||
TestSupport.BuildAnnualPlanSettingsService(),
|
TestSupport.BuildAnnualPlanSettingsService(),
|
||||||
TestSupport.BuildSyncSettingsService(), TestSupport.BuildSyncAuthService(), TestSupport.BuildEventQueue(),
|
TestSupport.BuildSyncSettingsService(), TestSupport.BuildSyncAuthService(), TestSupport.BuildEventQueue(),
|
||||||
@@ -457,25 +491,57 @@ public sealed class SettingsViewModelTests
|
|||||||
{
|
{
|
||||||
var subject = new Subject { Name = "Biologie", ShortName = "Bio" };
|
var subject = new Subject { Name = "Biologie", ShortName = "Bio" };
|
||||||
var repository = new FakeCompetencyDomains();
|
var repository = new FakeCompetencyDomains();
|
||||||
|
var versions = new FakeCompetencyCatalogVersions();
|
||||||
|
var version = versions.GetOrCreateDefault(subject.Id);
|
||||||
repository.Add(new CompetencyDomain
|
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
|
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.CatalogSubject = vm.Subjects.Single();
|
||||||
|
|
||||||
vm.Domains[1].MoveUpCommand.Execute(null);
|
vm.Domains[1].MoveUpCommand.Execute(null);
|
||||||
|
|
||||||
Assert.Equal(["Zweiter Bereich", "Erster Bereich"], vm.Domains.Select(x => x.Name));
|
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(["Zweiter Bereich", "Erster Bereich"], stored.Select(x => x.Name));
|
||||||
Assert.Equal([0, 1], stored.Select(x => x.SortOrder));
|
Assert.Equal([0, 1], stored.Select(x => x.SortOrder));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Kompetenzkatalog_Aktualisieren_ZeigtNachtraeglicheMcpAenderung()
|
||||||
|
{
|
||||||
|
var subject = new Subject { Name = "Naturwissenschaften", ShortName = "Nawi" };
|
||||||
|
var repository = new FakeCompetencyDomains();
|
||||||
|
var versions = new FakeCompetencyCatalogVersions();
|
||||||
|
var version = versions.GetOrCreateDefault(subject.Id);
|
||||||
|
var vm = BuildViewModel(subjects: new FakeSubjects([subject]), competencyDomains: repository,
|
||||||
|
competencyVersions: versions);
|
||||||
|
vm.CatalogSubject = vm.Subjects.Single();
|
||||||
|
|
||||||
|
Assert.True(vm.HasNoCatalogDomains);
|
||||||
|
|
||||||
|
repository.Add(new CompetencyDomain
|
||||||
|
{
|
||||||
|
SubjectId = subject.Id,
|
||||||
|
GradeLevel = 10,
|
||||||
|
VersionId = version.Id,
|
||||||
|
Name = "Erkenntnisgewinnung",
|
||||||
|
Items = [new CompetencyItem { Code = "EG1", Description = "Modelle verwenden" }],
|
||||||
|
});
|
||||||
|
|
||||||
|
vm.RefreshCompetencyCatalogCommand.Execute(null);
|
||||||
|
|
||||||
|
var domain = Assert.Single(vm.Domains);
|
||||||
|
Assert.Equal("Erkenntnisgewinnung", domain.Name);
|
||||||
|
Assert.False(vm.HasNoCatalogDomains);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void Kompetenzen_Umsortieren_PersistiertSortOrder()
|
public void Kompetenzen_Umsortieren_PersistiertSortOrder()
|
||||||
{
|
{
|
||||||
@@ -505,15 +571,19 @@ public sealed class SettingsViewModelTests
|
|||||||
{
|
{
|
||||||
var subject = new Subject { Name = "Biologie", ShortName = "Bio" };
|
var subject = new Subject { Name = "Biologie", ShortName = "Bio" };
|
||||||
var repository = new FakeCompetencyDomains();
|
var repository = new FakeCompetencyDomains();
|
||||||
|
var versions = new FakeCompetencyCatalogVersions();
|
||||||
|
var version = versions.GetOrCreateDefault(subject.Id);
|
||||||
repository.Add(new CompetencyDomain
|
repository.Add(new CompetencyDomain
|
||||||
{
|
{
|
||||||
SubjectId = subject.Id,
|
SubjectId = subject.Id,
|
||||||
GradeLevel = 10,
|
GradeLevel = 10,
|
||||||
|
VersionId = version.Id,
|
||||||
Name = "Erkenntnisgewinnung",
|
Name = "Erkenntnisgewinnung",
|
||||||
Code = "EG",
|
Code = "EG",
|
||||||
Items = [new CompetencyItem { Code = "EG1", Description = "Modelle verwenden" }],
|
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();
|
vm.CatalogSubject = vm.Subjects.Single();
|
||||||
|
|
||||||
var preview = vm.PrepareCatalogCopy(11);
|
var preview = vm.PrepareCatalogCopy(11);
|
||||||
@@ -524,9 +594,9 @@ public sealed class SettingsViewModelTests
|
|||||||
Assert.Equal(1, preview.NewCompetencies);
|
Assert.Equal(1, preview.NewCompetencies);
|
||||||
|
|
||||||
vm.ApplyCatalogImport(preview, CompetencyCatalogImportMode.Merge, new HashSet<string>());
|
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.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);
|
Assert.Equal("EG1", copied[0].Items.Single().Code);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -51,6 +51,18 @@ public class StudentListViewModelTests
|
|||||||
Assert.Equal("M", vm.Students.Single(s => s.Id == _ben.Id).AvatarLabel);
|
Assert.Equal("M", vm.Students.Single(s => s.Id == _ben.Id).AvatarLabel);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void SucheOhneTreffer_LiefertHilfreichenLeerzustand()
|
||||||
|
{
|
||||||
|
var vm = BuildViewModel();
|
||||||
|
|
||||||
|
vm.SearchText = "nicht vorhanden";
|
||||||
|
|
||||||
|
Assert.True(vm.HasNoStudents);
|
||||||
|
Assert.False(vm.HasStudents);
|
||||||
|
Assert.Contains("Suche", vm.EmptyListMessage);
|
||||||
|
}
|
||||||
|
|
||||||
private StudentListViewModel BuildViewModel() => new(
|
private StudentListViewModel BuildViewModel() => new(
|
||||||
new FakeStudents([_anna, _ben]),
|
new FakeStudents([_anna, _ben]),
|
||||||
new FakeGroups([_group]),
|
new FakeGroups([_group]),
|
||||||
|
|||||||
@@ -0,0 +1,146 @@
|
|||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Core.Services;
|
||||||
|
using LehrerApp.Desktop.ViewModels.Groups;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.Tests;
|
||||||
|
|
||||||
|
/// Tests für den Schüler-Leistungsüberblick (Nutzer-Feedback): Klausuren/Mitarbeit/Sonstige
|
||||||
|
/// im Überblick, berechnete Zeugnisnote, Zielnoten- und Was-wäre-wenn-Rechner sowie der
|
||||||
|
/// Bewerter-/Schülermodus-Unterschied (Kursdurchschnitt, Bearbeitbarkeit).
|
||||||
|
public sealed class StudentPerformanceOverviewViewModelTests
|
||||||
|
{
|
||||||
|
private static readonly Guid GroupId = Guid.NewGuid();
|
||||||
|
private static readonly Guid StudentId = Guid.NewGuid();
|
||||||
|
private static readonly Guid OtherStudentId = Guid.NewGuid();
|
||||||
|
|
||||||
|
private static StudentPerformanceOverviewViewModel BuildViewModel(
|
||||||
|
FakeExams? exams = null, FakeResults? results = null, FakeGrades? grades = null,
|
||||||
|
FakeSchemes? schemes = null, GradingSystem system = GradingSystem.Grades1To6)
|
||||||
|
{
|
||||||
|
var scheme = new GradingScheme { ExamsPercent = 50, ParticipationPercent = 40, OtherPercent = 10 };
|
||||||
|
var schemesRepo = schemes ?? new FakeSchemes();
|
||||||
|
if (schemes is null) schemesRepo.SetForGroup(GroupId, scheme);
|
||||||
|
|
||||||
|
return new StudentPerformanceOverviewViewModel(
|
||||||
|
grades ?? new FakeGrades(), exams ?? new FakeExams([]), results ?? new FakeResults(),
|
||||||
|
new FakeMemberships([]), schemesRepo, new GradingService(),
|
||||||
|
GroupId, StudentId, GroupType.Class, system, "Beispiel, Anna", "Testkurs", "2025/26");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ExamRows_ZeigtEigeneNoteUndKursdurchschnitt()
|
||||||
|
{
|
||||||
|
var exam = new Exam { Id = Guid.NewGuid(), GroupId = GroupId, Title = "K1", Date = new DateOnly(2025, 9, 10) };
|
||||||
|
var exams = new FakeExams([exam]);
|
||||||
|
var results = new FakeResults();
|
||||||
|
results.Add(new ExamResult { ExamId = exam.Id, StudentId = StudentId, Grade = "2" });
|
||||||
|
results.Add(new ExamResult { ExamId = exam.Id, StudentId = OtherStudentId, Grade = "4" });
|
||||||
|
|
||||||
|
var vm = BuildViewModel(exams, results);
|
||||||
|
|
||||||
|
var row = Assert.Single(vm.ExamRows);
|
||||||
|
Assert.Equal("2", row.OwnGradeDisplay);
|
||||||
|
Assert.Equal("3.0", row.ClassAverageDisplay);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ExamHistory_ZeigtEigenenVerlaufUndMarkiertNotenabfall()
|
||||||
|
{
|
||||||
|
var exam1 = new Exam { Id = Guid.NewGuid(), GroupId = GroupId, Title = "K1", Date = new DateOnly(2025, 9, 10) };
|
||||||
|
var exam2 = new Exam { Id = Guid.NewGuid(), GroupId = GroupId, Title = "K2", Date = new DateOnly(2025, 9, 24) };
|
||||||
|
var exams = new FakeExams([exam1, exam2]);
|
||||||
|
var results = new FakeResults();
|
||||||
|
results.Add(new ExamResult { ExamId = exam1.Id, StudentId = StudentId, Grade = "2" });
|
||||||
|
results.Add(new ExamResult { ExamId = exam2.Id, StudentId = StudentId, Grade = "5" }); // Abfall + mangelhaft
|
||||||
|
|
||||||
|
var vm = BuildViewModel(exams, results);
|
||||||
|
|
||||||
|
Assert.Equal(2, vm.ExamHistory.Points.Count);
|
||||||
|
Assert.False(vm.ExamHistory.Points[0].IsWarning);
|
||||||
|
Assert.True(vm.ExamHistory.Points[1].IsWarning);
|
||||||
|
Assert.Contains("Abfall", vm.ExamHistory.Points[1].WarningText);
|
||||||
|
Assert.Contains("Versetzungsgefährdung", vm.ExamHistory.Points[1].WarningText);
|
||||||
|
Assert.True(vm.ExamHistory.Points[1].BarHeight < vm.ExamHistory.Points[0].BarHeight);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void AktuelleZeugnisnote_KombiniertAlleDreiBereiche()
|
||||||
|
{
|
||||||
|
var exam = new Exam { Id = Guid.NewGuid(), GroupId = GroupId, Title = "K1", Date = new DateOnly(2025, 9, 10) };
|
||||||
|
var exams = new FakeExams([exam]);
|
||||||
|
var results = new FakeResults();
|
||||||
|
results.Add(new ExamResult { ExamId = exam.Id, StudentId = StudentId, Grade = "2" });
|
||||||
|
var grades = new FakeGrades();
|
||||||
|
grades.Add(new Grade { StudentId = StudentId, GroupId = GroupId, Category = GradeCategory.Participation,
|
||||||
|
Date = new DateOnly(2025, 9, 5), Value = "3" });
|
||||||
|
grades.Add(new Grade { StudentId = StudentId, GroupId = GroupId, Category = GradeCategory.Other,
|
||||||
|
Date = new DateOnly(2025, 9, 5), Value = "1" });
|
||||||
|
|
||||||
|
var vm = BuildViewModel(exams, results, grades);
|
||||||
|
|
||||||
|
// (2*50 + 3*40 + 1*10) / 100 = 2.3 -> kaufmännisch 2
|
||||||
|
Assert.Equal("Note 2", vm.CurrentReportGradeDisplay);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Zielnote_BerechnetNoetigenKlausurschnitt()
|
||||||
|
{
|
||||||
|
var grades = new FakeGrades();
|
||||||
|
grades.Add(new Grade { StudentId = StudentId, GroupId = GroupId, Category = GradeCategory.Participation,
|
||||||
|
Date = new DateOnly(2025, 9, 5), Value = "3" });
|
||||||
|
grades.Add(new Grade { StudentId = StudentId, GroupId = GroupId, Category = GradeCategory.Other,
|
||||||
|
Date = new DateOnly(2025, 9, 5), Value = "2" });
|
||||||
|
var vm = BuildViewModel(grades: grades);
|
||||||
|
|
||||||
|
vm.TargetGradeText = "2";
|
||||||
|
vm.TargetBucketName = "Klausuren";
|
||||||
|
|
||||||
|
// Ziel 2,0 = (x*50 + 3*40 + 2*10)/100 => 200 = 50x+120+20 => x = 1,2
|
||||||
|
Assert.Contains("1.2", vm.TargetResultDisplay);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void WasWaereWenn_ZeigtZeugnisnoteMitZusaetzlicherKlausurAn()
|
||||||
|
{
|
||||||
|
var exam = new Exam { Id = Guid.NewGuid(), GroupId = GroupId, Title = "K1", Date = new DateOnly(2025, 9, 10) };
|
||||||
|
var exams = new FakeExams([exam]);
|
||||||
|
var results = new FakeResults();
|
||||||
|
results.Add(new ExamResult { ExamId = exam.Id, StudentId = StudentId, Grade = "2" });
|
||||||
|
var grades = new FakeGrades();
|
||||||
|
grades.Add(new Grade { StudentId = StudentId, GroupId = GroupId, Category = GradeCategory.Participation,
|
||||||
|
Date = new DateOnly(2025, 9, 5), Value = "2" });
|
||||||
|
|
||||||
|
var vm = BuildViewModel(exams, results, grades);
|
||||||
|
|
||||||
|
vm.WhatIfExamGradeText = "6";
|
||||||
|
|
||||||
|
// Klausuren neu: (2+6)/2=4 (50%), Mitarbeit 2 (40%, Sonstige fehlt) -> (4*50+2*40)/90 = 3,11 -> kaufm. 3
|
||||||
|
Assert.Contains("3", vm.WhatIfResultDisplay);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void SaveCommand_AufMitarbeitszeile_SpeichertUndAktualisiertDurchschnitt()
|
||||||
|
{
|
||||||
|
var grades = new FakeGrades();
|
||||||
|
var grade = new Grade { StudentId = StudentId, GroupId = GroupId, Category = GradeCategory.Participation,
|
||||||
|
Date = new DateOnly(2025, 9, 5), Value = "3" };
|
||||||
|
grades.Add(grade);
|
||||||
|
var vm = BuildViewModel(grades: grades);
|
||||||
|
|
||||||
|
var row = Assert.Single(vm.ParticipationRows);
|
||||||
|
row.Value = "1";
|
||||||
|
row.SaveCommand.Execute(null);
|
||||||
|
|
||||||
|
Assert.Equal("1.0", vm.ParticipationAverageDisplay);
|
||||||
|
Assert.Equal("1", grades.GetByStudentAndGroup(StudentId, GroupId).Single().Value);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void OhneWerteImZeitraum_ZeigtHinweisStattZeugnisnote()
|
||||||
|
{
|
||||||
|
var vm = BuildViewModel();
|
||||||
|
|
||||||
|
Assert.Contains("Noch nicht berechenbar", vm.CurrentReportGradeDisplay);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
using System.Net;
|
using System.Net;
|
||||||
using System.Net.Http.Json;
|
using System.Net.Http.Json;
|
||||||
using LehrerApp.Data;
|
using LehrerApp.Data;
|
||||||
|
using LehrerApp.Desktop.Services;
|
||||||
using LehrerApp.Desktop.ViewModels;
|
using LehrerApp.Desktop.ViewModels;
|
||||||
using LehrerApp.Sync;
|
using LehrerApp.Sync;
|
||||||
using LehrerApp.Sync.Crypto;
|
using LehrerApp.Sync.Crypto;
|
||||||
@@ -80,6 +81,39 @@ public sealed class SyncStatusViewModelTests
|
|||||||
Assert.Contains("Bitte aktualisiere die LehrerApp", SyncStatusViewModel.IncompatibleVersionMessage);
|
Assert.Contains("Bitte aktualisiere die LehrerApp", SyncStatusViewModel.IncompatibleVersionMessage);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Regression: ein Sync-Ausfall (z.B. Server nicht erreichbar) war früher nur an einem
|
||||||
|
/// blassen "Offline"-Text in der Statuszeile erkennbar - ein Gerät konnte so stundenlang
|
||||||
|
/// unbemerkt nicht synchronisieren. NotificationService bekommt jetzt aktiv eine Meldung,
|
||||||
|
/// sobald der Status neu auf Offline/Error wechselt.
|
||||||
|
[Fact]
|
||||||
|
public async Task SyncOffline_MeldetSichAktivUeberNotificationService()
|
||||||
|
{
|
||||||
|
using var temp = new TempSyncEngine(new OfflineStubHandler());
|
||||||
|
var notifications = new NotificationService();
|
||||||
|
var vm = new SyncStatusViewModel(temp.Engine, notifications);
|
||||||
|
|
||||||
|
await temp.Engine.SyncNowAsync();
|
||||||
|
|
||||||
|
Assert.Equal("Offline", vm.StatusText);
|
||||||
|
Assert.Single(notifications.Toasts);
|
||||||
|
Assert.Equal(SyncStatusViewModel.OfflineMessage, notifications.Toasts[0].Message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ein erneuter automatischer Retry im selben Offline-Zustand darf keinen weiteren Toast
|
||||||
|
/// auslösen - sonst würde der Nutzer alle paar Minuten dieselbe Meldung sehen.
|
||||||
|
[Fact]
|
||||||
|
public async Task SyncOffline_WiederholterRetry_MeldetNurEinmal()
|
||||||
|
{
|
||||||
|
using var temp = new TempSyncEngine(new OfflineStubHandler());
|
||||||
|
var notifications = new NotificationService();
|
||||||
|
var vm = new SyncStatusViewModel(temp.Engine, notifications);
|
||||||
|
|
||||||
|
await temp.Engine.SyncNowAsync();
|
||||||
|
await temp.Engine.SyncNowAsync();
|
||||||
|
|
||||||
|
Assert.Single(notifications.Toasts);
|
||||||
|
}
|
||||||
|
|
||||||
private sealed class PullEventStubHandler : HttpMessageHandler
|
private sealed class PullEventStubHandler : HttpMessageHandler
|
||||||
{
|
{
|
||||||
protected override Task<HttpResponseMessage> SendAsync(
|
protected override Task<HttpResponseMessage> SendAsync(
|
||||||
@@ -113,6 +147,13 @@ public sealed class SyncStatusViewModelTests
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private sealed class OfflineStubHandler : HttpMessageHandler
|
||||||
|
{
|
||||||
|
protected override Task<HttpResponseMessage> SendAsync(
|
||||||
|
HttpRequestMessage request, CancellationToken cancellationToken) =>
|
||||||
|
Task.FromResult(new HttpResponseMessage(HttpStatusCode.Unauthorized));
|
||||||
|
}
|
||||||
|
|
||||||
private sealed class IncompatibleVersionStubHandler : HttpMessageHandler
|
private sealed class IncompatibleVersionStubHandler : HttpMessageHandler
|
||||||
{
|
{
|
||||||
protected override Task<HttpResponseMessage> SendAsync(
|
protected override Task<HttpResponseMessage> SendAsync(
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Desktop.ViewModels.Groups;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.Tests;
|
||||||
|
|
||||||
|
public sealed class TeachingModeOutstandingHomeworkViewModelTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void Refresh_ZeigtJungeOffeneNachreichungenUndFiltertAktuellAbwesende()
|
||||||
|
{
|
||||||
|
var date = new DateOnly(2026, 9, 25);
|
||||||
|
var group = new LearningGroup { Name = "10c Chemie" };
|
||||||
|
var amelia = new Student { FirstName = "Amelia", LastName = "Gerste" };
|
||||||
|
var ben = new Student { FirstName = "Ben", LastName = "Muster" };
|
||||||
|
var carl = new Student { FirstName = "Carl", LastName = "Beispiel" };
|
||||||
|
var oldMember = new Student { FirstName = "Dana", LastName = "Alt" };
|
||||||
|
var previous = new ParticipationSession { GroupId = group.Id, Date = date.AddDays(-5) };
|
||||||
|
var older = new ParticipationSession { GroupId = group.Id, Date = date.AddDays(-130) };
|
||||||
|
var current = new ParticipationSession { GroupId = group.Id, Date = date };
|
||||||
|
var memberships = new FakeMemberships([
|
||||||
|
new GroupMembership { StudentId = amelia.Id, GroupId = group.Id },
|
||||||
|
new GroupMembership { StudentId = ben.Id, GroupId = group.Id },
|
||||||
|
new GroupMembership { StudentId = carl.Id, GroupId = group.Id },
|
||||||
|
new GroupMembership { StudentId = oldMember.Id, GroupId = group.Id,
|
||||||
|
Period = MembershipPeriod.Custom, JoinedAt = date.AddDays(-30), LeftAt = date.AddDays(-1) },
|
||||||
|
]);
|
||||||
|
var entries = new FakeEntries();
|
||||||
|
entries.Add(new ParticipationEntry { SessionId = previous.Id, StudentId = amelia.Id,
|
||||||
|
Homework = HomeworkStatus.MissingOverdue });
|
||||||
|
var benEntry = new ParticipationEntry { SessionId = previous.Id, StudentId = ben.Id,
|
||||||
|
Homework = HomeworkStatus.MissingOpen };
|
||||||
|
entries.Add(benEntry);
|
||||||
|
entries.Add(new ParticipationEntry { SessionId = previous.Id, StudentId = carl.Id,
|
||||||
|
Homework = HomeworkStatus.SubmittedLate });
|
||||||
|
entries.Add(new ParticipationEntry { SessionId = previous.Id, StudentId = oldMember.Id,
|
||||||
|
Homework = HomeworkStatus.MissingOverdue });
|
||||||
|
entries.Add(new ParticipationEntry { SessionId = older.Id, StudentId = ben.Id,
|
||||||
|
Homework = HomeworkStatus.MissingOverdue });
|
||||||
|
entries.Add(new ParticipationEntry { SessionId = current.Id, StudentId = ben.Id,
|
||||||
|
Attendance = AttendanceStatus.Present });
|
||||||
|
entries.Add(new ParticipationEntry { SessionId = current.Id, StudentId = amelia.Id,
|
||||||
|
Attendance = AttendanceStatus.ExcusePending });
|
||||||
|
|
||||||
|
var vm = new TeachingModeOutstandingHomeworkViewModel(group.Id, date,
|
||||||
|
new FakeStudents([amelia, ben, carl, oldMember]), memberships,
|
||||||
|
new FakeSessions([previous, older, current]), entries);
|
||||||
|
vm.SetCurrentSessionId(current.Id);
|
||||||
|
vm.IsExpanded = true;
|
||||||
|
|
||||||
|
Assert.Equal(ben.FullName, Assert.Single(vm.Rows).StudentName);
|
||||||
|
Assert.Equal("Offene Nachreichungen (1)", vm.Header);
|
||||||
|
vm.IncludeAbsentStudents = true;
|
||||||
|
Assert.Equal(2, vm.Rows.Count);
|
||||||
|
Assert.Contains(vm.Rows, r => r.StudentName == amelia.FullName &&
|
||||||
|
r.Status == HomeworkStatus.MissingOverdue);
|
||||||
|
|
||||||
|
vm.IncludeAbsentStudents = false;
|
||||||
|
var currentAmelia = entries.GetBySessionAndStudent(current.Id, amelia.Id)!;
|
||||||
|
currentAmelia.Attendance = AttendanceStatus.Present;
|
||||||
|
entries.Save(currentAmelia);
|
||||||
|
vm.Refresh();
|
||||||
|
Assert.Equal(2, vm.Rows.Count);
|
||||||
|
|
||||||
|
benEntry.Homework = HomeworkStatus.SubmittedLate;
|
||||||
|
entries.Save(benEntry);
|
||||||
|
vm.Refresh();
|
||||||
|
Assert.Equal(amelia.FullName, Assert.Single(vm.Rows).StudentName);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -22,7 +22,7 @@ public sealed class TeachingModeViewModelTests
|
|||||||
FakeSessions? sessions = null) =>
|
FakeSessions? sessions = null) =>
|
||||||
new(sessions ?? new FakeSessions([]), new FakeEntries(), new FakeAspects(),
|
new(sessions ?? new FakeSessions([]), new FakeEntries(), new FakeAspects(),
|
||||||
new FakeStudents([]), new FakeMemberships([]), new FakeGroups([group]),
|
new FakeStudents([]), new FakeMemberships([]), new FakeGroups([group]),
|
||||||
new FakeCompetencyDomains());
|
new FakeCompetencyDomains(), new FakeCompetencyCatalogVersions());
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void Konstruktor_LaedtVerlaufsplanUndInitialisiertSitzplanFuerDieGruppe()
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -64,6 +64,44 @@ public sealed class TimetableViewModelTests
|
|||||||
Assert.Equal(6 + 10 * 6, vm.WeekItems.Count);
|
Assert.Equal(6 + 10 * 6, vm.WeekItems.Count);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Load_MarkiertDieAktuelleStundeAusDemHinterlegtenStundenraster()
|
||||||
|
{
|
||||||
|
var tempPath = Path.Combine(Path.GetTempPath(), $"lehrerapp-currentperiod-tests-{Guid.NewGuid():N}");
|
||||||
|
Directory.CreateDirectory(tempPath);
|
||||||
|
var schedule = new PeriodScheduleService(tempPath);
|
||||||
|
schedule.SetPeriods([
|
||||||
|
new PeriodTimeEntry { PeriodNumber = 2, Start = new TimeOnly(8, 0), End = new TimeOnly(8, 45) },
|
||||||
|
new PeriodTimeEntry { PeriodNumber = 3, Start = new TimeOnly(9, 0), End = new TimeOnly(9, 45) },
|
||||||
|
]);
|
||||||
|
var vm = BuildViewModel(new FakeTimetableSlots(), new FakeGroups([]), periodSchedule: schedule);
|
||||||
|
vm.Clock = () => new DateTime(2026, 9, 21, 9, 15, 0); // Montag, 3. Stunde
|
||||||
|
|
||||||
|
vm.Load();
|
||||||
|
|
||||||
|
var periodLabels = vm.WeekItems.Where(x => x.IsPeriodLabel).ToList();
|
||||||
|
Assert.True(periodLabels.Single(x => x.PeriodNumber == 3).IsCurrentPeriod);
|
||||||
|
Assert.DoesNotContain(periodLabels, x => x.PeriodNumber != 3 && x.IsCurrentPeriod);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Load_InAndererKalenderwoche_MarkiertKeineAktuelleStunde()
|
||||||
|
{
|
||||||
|
var tempPath = Path.Combine(Path.GetTempPath(), $"lehrerapp-currentperiod-tests-{Guid.NewGuid():N}");
|
||||||
|
Directory.CreateDirectory(tempPath);
|
||||||
|
var schedule = new PeriodScheduleService(tempPath);
|
||||||
|
schedule.SetPeriods([
|
||||||
|
new PeriodTimeEntry { PeriodNumber = 3, Start = new TimeOnly(9, 0), End = new TimeOnly(9, 45) },
|
||||||
|
]);
|
||||||
|
var vm = BuildViewModel(new FakeTimetableSlots(), new FakeGroups([]), periodSchedule: schedule);
|
||||||
|
vm.Clock = () => new DateTime(2026, 9, 21, 9, 15, 0);
|
||||||
|
vm.WeekOffset = 1;
|
||||||
|
|
||||||
|
vm.Load();
|
||||||
|
|
||||||
|
Assert.DoesNotContain(vm.WeekItems, x => x.IsCurrentPeriod);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void Load_ZeigtZugewieseneGruppeInDerPassendenZelle()
|
public void Load_ZeigtZugewieseneGruppeInDerPassendenZelle()
|
||||||
{
|
{
|
||||||
@@ -277,7 +315,23 @@ public sealed class TimetableViewModelTests
|
|||||||
|
|
||||||
Assert.Equal(group.Id, navigatedTo);
|
Assert.Equal(group.Id, navigatedTo);
|
||||||
Assert.False(viewerOpened);
|
Assert.False(viewerOpened);
|
||||||
Assert.Equal("Zur Lerngruppe", vm.TodayItems[0].OpenButtonLabel);
|
Assert.Equal("Stunde anlegen", vm.TodayItems[0].OpenButtonLabel);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task OpenTodayLesson_OhneLesson_StartetDirektanlageMitExaktemTermin()
|
||||||
|
{
|
||||||
|
var today = DateOnly.FromDateTime(DateTime.Today);
|
||||||
|
var group = new LearningGroup { Name = "Q1 Chemie" };
|
||||||
|
var slots = new FakeTimetableSlots();
|
||||||
|
slots.Add(new TimetableSlot { GroupId = group.Id, Weekday = today.DayOfWeek, PeriodNumber = 4 });
|
||||||
|
var vm = BuildViewModel(slots, new FakeGroups([group]));
|
||||||
|
TimetableLessonRequest? requested = null;
|
||||||
|
vm.OnCreateLesson = request => { requested = request; return Task.CompletedTask; };
|
||||||
|
|
||||||
|
await vm.OpenTodayLessonCommand.ExecuteAsync(vm.TodayItems[0]);
|
||||||
|
|
||||||
|
Assert.Equal(new TimetableLessonRequest(group.Id, today, 4), requested);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Unterrichtsmodus (14.x) ────────────────────────────────────────────────
|
// ── Unterrichtsmodus (14.x) ────────────────────────────────────────────────
|
||||||
@@ -696,6 +750,31 @@ public sealed class TimetableViewModelTests
|
|||||||
Assert.Equal("1", period2.BadgeText);
|
Assert.Equal("1", period2.BadgeText);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Load_Doppelstunde_ZeigtLessonThemaInBeidenKacheln_AuchOhnePhasenUndStundenraster()
|
||||||
|
{
|
||||||
|
var date = DateInCurrentWeek(DayOfWeek.Monday);
|
||||||
|
var group = new LearningGroup { Name = "10c" };
|
||||||
|
var slots = new FakeTimetableSlots();
|
||||||
|
slots.Add(new TimetableSlot { GroupId = group.Id, Weekday = date.DayOfWeek, PeriodNumber = 3 });
|
||||||
|
slots.Add(new TimetableSlot { GroupId = group.Id, Weekday = date.DayOfWeek, PeriodNumber = 4 });
|
||||||
|
var lesson = new Lesson
|
||||||
|
{
|
||||||
|
GroupId = group.Id, Date = date, LessonNumber = 3, Topic = "Werkstoffprüfung",
|
||||||
|
Phases = [],
|
||||||
|
};
|
||||||
|
var lessons = new FakeLessons();
|
||||||
|
lessons.Add(lesson);
|
||||||
|
|
||||||
|
var vm = BuildViewModel(slots, new FakeGroups([group]), lessons: lessons);
|
||||||
|
|
||||||
|
var first = vm.WeekItems.Single(c => c.IsSlotCell && c.Weekday == date.DayOfWeek && c.PeriodNumber == 3);
|
||||||
|
var second = vm.WeekItems.Single(c => c.IsSlotCell && c.Weekday == date.DayOfWeek && c.PeriodNumber == 4);
|
||||||
|
Assert.Equal("Werkstoffprüfung", first.Topic);
|
||||||
|
Assert.Equal("Werkstoffprüfung", second.Topic);
|
||||||
|
Assert.Equal(lesson.Id, second.Lesson?.Id);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void Load_KeineAnstehendenFerien_KeinBadge()
|
public void Load_KeineAnstehendenFerien_KeinBadge()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -25,4 +25,28 @@ public sealed class UnitDialogViewModelTests
|
|||||||
|
|
||||||
Assert.Equal("10c · kein Fach hinterlegt (siehe Lerngruppe)", vm.GroupSubjectDisplay);
|
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,84 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task ApplyUntisAbsenceStatus_ErheblichVerspaetet_IstZulaessigerZielstatus()
|
||||||
|
{
|
||||||
|
var tool = Build();
|
||||||
|
|
||||||
|
var result = await tool.ApplyUntisAbsenceStatus(
|
||||||
|
"nie-vergeben", nameof(AttendanceStatus.SignificantlyLate));
|
||||||
|
|
||||||
|
Assert.False(result.Applied);
|
||||||
|
Assert.Contains("row-id", result.Message); // Statusvalidierung wurde erfolgreich passiert
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,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));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Desktop.Services;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.Tests;
|
||||||
|
|
||||||
|
public sealed class UntisLessonAbsenceHelperTests
|
||||||
|
{
|
||||||
|
[Theory]
|
||||||
|
[InlineData(0, AttendanceStatus.Late)]
|
||||||
|
[InlineData(9, AttendanceStatus.Late)]
|
||||||
|
[InlineData(10, AttendanceStatus.SignificantlyLate)]
|
||||||
|
[InlineData(44, AttendanceStatus.SignificantlyLate)]
|
||||||
|
public void MapStatus_StaffeltVerspaetungAbZehnMinuten(
|
||||||
|
int absentMinutes, AttendanceStatus expected)
|
||||||
|
{
|
||||||
|
Assert.Equal(expected, UntisLessonAbsenceHelper.MapStatus(Absence(absentMinutes)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void MatchesUntisStatus_ErheblichVerspaetetAkzeptiertAllgemeinesUntisVerspaetet()
|
||||||
|
{
|
||||||
|
var matches = UntisLessonAbsenceHelper.MatchesUntisStatus(
|
||||||
|
AttendanceStatus.SignificantlyLate, AttendanceStatus.Late);
|
||||||
|
|
||||||
|
Assert.True(matches);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void MatchesUntisStatus_NachgereichteEntschuldigungBleibtAenderung()
|
||||||
|
{
|
||||||
|
var matches = UntisLessonAbsenceHelper.MatchesUntisStatus(
|
||||||
|
AttendanceStatus.SignificantlyLate, AttendanceStatus.Excused);
|
||||||
|
|
||||||
|
Assert.False(matches);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void MatchesUntisStatus_IstFuerVerspaetungsPraezisierungGerichtet()
|
||||||
|
{
|
||||||
|
var matches = UntisLessonAbsenceHelper.MatchesUntisStatus(
|
||||||
|
AttendanceStatus.Late, AttendanceStatus.SignificantlyLate);
|
||||||
|
|
||||||
|
Assert.False(matches);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(AttendanceStatus.Late)]
|
||||||
|
[InlineData(AttendanceStatus.SignificantlyLate)]
|
||||||
|
[InlineData(AttendanceStatus.ExcusePending)]
|
||||||
|
[InlineData(AttendanceStatus.Excused)]
|
||||||
|
[InlineData(AttendanceStatus.Unexcused)]
|
||||||
|
public void MatchesUntisStatus_GleicherStatusPasst(AttendanceStatus status)
|
||||||
|
{
|
||||||
|
Assert.True(UntisLessonAbsenceHelper.MatchesUntisStatus(status, status));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static UntisLessonAbsenceDto Absence(int absentMinutes) => new(
|
||||||
|
"Testschüler", 20260925, 1, 0, absentMinutes, 0, 800, 845,
|
||||||
|
"Verspätung", 1, false, null, true);
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
using LehrerApp.Desktop.ViewModels.ClassTeacher;
|
using LehrerApp.Desktop.ViewModels.ClassTeacher;
|
||||||
|
using LehrerApp.Core.Models;
|
||||||
using Xunit;
|
using Xunit;
|
||||||
|
|
||||||
namespace LehrerApp.Desktop.Tests;
|
namespace LehrerApp.Desktop.Tests;
|
||||||
@@ -9,6 +10,8 @@ public sealed class UntisNameMatchingTests
|
|||||||
[InlineData("Ben Schmidt", "Schmidt Ben")]
|
[InlineData("Ben Schmidt", "Schmidt Ben")]
|
||||||
[InlineData("Ada Müller", "MÜLLER ADA")]
|
[InlineData("Ada Müller", "MÜLLER ADA")]
|
||||||
[InlineData("Max Mustermann", "mustermann max")]
|
[InlineData("Max Mustermann", "mustermann max")]
|
||||||
|
[InlineData("Gerste, Amelia", "Gerste Amelia")]
|
||||||
|
[InlineData("Müller-Ada", "Ada Müller")]
|
||||||
public void NamesMatch_IstReihenfolgeUndGrossKleinschreibungUnabhaengig(string a, string b) =>
|
public void NamesMatch_IstReihenfolgeUndGrossKleinschreibungUnabhaengig(string a, string b) =>
|
||||||
Assert.True(UntisNameMatching.NamesMatch(a, b));
|
Assert.True(UntisNameMatching.NamesMatch(a, b));
|
||||||
|
|
||||||
@@ -18,4 +21,40 @@ public sealed class UntisNameMatchingTests
|
|||||||
[InlineData("Ben Schmidt", "")]
|
[InlineData("Ben Schmidt", "")]
|
||||||
public void NamesMatch_LehntUnterschiedlicheOderFehlendeNamenAb(string? a, string b) =>
|
public void NamesMatch_LehntUnterschiedlicheOderFehlendeNamenAb(string? a, string b) =>
|
||||||
Assert.False(UntisNameMatching.NamesMatch(a, b));
|
Assert.False(UntisNameMatching.NamesMatch(a, b));
|
||||||
|
|
||||||
|
// Regression: Student.FullName liefert "Nachname, Vorname" (mit Komma), während WebUntis
|
||||||
|
// denselben Namen je nach Bericht ohne Komma und in wechselnder Reihenfolge liefert.
|
||||||
|
[Fact]
|
||||||
|
public void NamesMatch_KommaGetrennterAnzeigename_PasstZumUntisNamenOhneKomma()
|
||||||
|
{
|
||||||
|
Assert.True(UntisNameMatching.NamesMatch("Gerste, Amelia", "Gerste Amelia"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void BuildClassNameIndex_VerwendetDieselbeInstanzWieDieAuswahlliste()
|
||||||
|
{
|
||||||
|
var candidate = new Student { FirstName = "Amelia", LastName = "Gerste" };
|
||||||
|
var repositoryCopy = new Student
|
||||||
|
{
|
||||||
|
Id = candidate.Id, FirstName = candidate.FirstName, LastName = candidate.LastName,
|
||||||
|
};
|
||||||
|
|
||||||
|
var index = UntisNameMatching.BuildClassNameIndex([candidate], [repositoryCopy]);
|
||||||
|
|
||||||
|
Assert.Same(candidate, index[UntisNameMatching.NameKey("Gerste Amelia")]);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void BuildClassNameIndex_GleicheNamenInVerschiedenenKlassenBleibenEindeutig()
|
||||||
|
{
|
||||||
|
var classStudent = new Student { FirstName = "Amelia", LastName = "Gerste" };
|
||||||
|
var otherStudent = new Student { FirstName = "Amelia", LastName = "Gerste" };
|
||||||
|
var candidates = new[] { classStudent, otherStudent };
|
||||||
|
|
||||||
|
Assert.Empty(UntisNameMatching.BuildNameIndex(candidates));
|
||||||
|
var index = UntisNameMatching.BuildClassNameIndex(candidates,
|
||||||
|
[new Student { Id = classStudent.Id, FirstName = "Amelia", LastName = "Gerste" }]);
|
||||||
|
|
||||||
|
Assert.Same(classStudent, index[UntisNameMatching.NameKey("Gerste Amelia")]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -61,7 +61,7 @@ public sealed class UntisSyncServiceTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ProcessIcsText_AbweichendesFach_SchreibtVertretungUndAktualisiertBeiWiederholung()
|
public void ProcessIcsText_AbweichendesFach_SchreibtVertretungUndUeberspringtUnveraenderteWiederholung()
|
||||||
{
|
{
|
||||||
var mappings = new FakeUntisSlotMappings();
|
var mappings = new FakeUntisSlotMappings();
|
||||||
mappings.Add(new UntisSlotMapping
|
mappings.Add(new UntisSlotMapping
|
||||||
@@ -81,7 +81,7 @@ public sealed class UntisSyncServiceTests
|
|||||||
// Eintrag erzeugen - Idempotenz über SubstitutionEntry.ExternalId.
|
// Eintrag erzeugen - Idempotenz über SubstitutionEntry.ExternalId.
|
||||||
var second = service.ProcessIcsText(BuildIcs("1", "20260817T075000", "NAT", "10c HED"));
|
var second = service.ProcessIcsText(BuildIcs("1", "20260817T075000", "NAT", "10c HED"));
|
||||||
|
|
||||||
Assert.Equal(1, second.SubstitutionCount);
|
Assert.Equal(0, second.SubstitutionCount);
|
||||||
Assert.Single(substitutions.GetAll());
|
Assert.Single(substitutions.GetAll());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -278,7 +278,7 @@ public sealed class UntisSyncServiceTests
|
|||||||
// Erneuter Poll mit demselben, weiterhin unverändert vorhandenen Termin darf keinen
|
// Erneuter Poll mit demselben, weiterhin unverändert vorhandenen Termin darf keinen
|
||||||
// zweiten Eintrag erzeugen (Idempotenz über ExternalId=Uid).
|
// zweiten Eintrag erzeugen (Idempotenz über ExternalId=Uid).
|
||||||
var second = service.ProcessIcsText(BuildIcs("v1", dtstart, null, "HED"));
|
var second = service.ProcessIcsText(BuildIcs("v1", dtstart, null, "HED"));
|
||||||
Assert.Equal(1, second.SubstitutionCount);
|
Assert.Equal(0, second.SubstitutionCount);
|
||||||
Assert.Single(substitutions.GetAll());
|
Assert.Single(substitutions.GetAll());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,167 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Text;
|
||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Core.Services;
|
||||||
|
using LehrerApp.Desktop.Services;
|
||||||
|
using LehrerApp.Desktop.ViewModels.Groups;
|
||||||
|
using LehrerApp.WebUntis;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.Tests;
|
||||||
|
|
||||||
|
public sealed class WebUntisHomeworkComparisonViewModelTests
|
||||||
|
{
|
||||||
|
[Theory]
|
||||||
|
[InlineData("Fehlende HA", "Buch vergessen", "Negativ", true)]
|
||||||
|
[InlineData("Sonstiges", "HA nicht dabei", "Negativ", false)]
|
||||||
|
[InlineData(null, "HA nicht dabei", "Negativ", true)]
|
||||||
|
[InlineData("Hausaufgaben fehlen", null, "Negativ", true)]
|
||||||
|
[InlineData("Verhalten", "Schüler war unruhig", "Negativ", false)]
|
||||||
|
[InlineData("Hausaufgaben", "HA gemacht", "Positiv", false)]
|
||||||
|
[InlineData("Sonstiges", "Schach gespielt", "Negativ", false)]
|
||||||
|
public void IsMissingHomeworkEntry_ErkenntAuchDasWebUntisKuerzel(
|
||||||
|
string? category, string? entryText, string group, bool expected)
|
||||||
|
{
|
||||||
|
var entry = new UntisClassRegisterEventDto("10c", 20260925, "Che", "Gerste Amelia",
|
||||||
|
category, group, entryText);
|
||||||
|
|
||||||
|
Assert.Equal(expected, WebUntisHomeworkComparisonViewModel.IsMissingHomeworkEntry(entry));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Load_ZeigtFehlendeHaAuchOhneHausaufgabeImFreitext()
|
||||||
|
{
|
||||||
|
const string report = "Klasse\tDatum\tFach\tName\tBenutzer\tEintragskategorie\tKategoriegruppe\tText\r\n" +
|
||||||
|
"10c\t25.09.26\tChe\tGerste Amelia\tlehrkraft\tFehlende HA\tNegativ\tChe: Buch vergessen\r\n" +
|
||||||
|
"10c\t25.09.26\tChe\tGerste Amelia\tlehrkraft\tHausaufgaben\tPositiv\tChe: alles erledigt\r\n";
|
||||||
|
var handler = new QueueHandler(
|
||||||
|
Json("{\"result\":{\"sessionId\":\"s\"}}"),
|
||||||
|
Json("{\"result\":[{\"id\":1,\"name\":\"2026/27\",\"startDate\":20260801,\"endDate\":20270731}]}"),
|
||||||
|
Json("{\"data\":{\"finished\":true,\"error\":false," +
|
||||||
|
"\"reportParams\":\"get=rpt.tmp&name=ClassregEventPerStudent&format=csv\"}}"),
|
||||||
|
new HttpResponseMessage(HttpStatusCode.OK)
|
||||||
|
{
|
||||||
|
Content = new ByteArrayContent(Encoding.UTF8.GetBytes(report)),
|
||||||
|
});
|
||||||
|
var settings = TestSupport.BuildWebUntisSettingsService();
|
||||||
|
var credentials = new WebUntisCredentials("schule", "arche.webuntis.com", "lehrkraft", "geheim");
|
||||||
|
settings.SetApiCredentials(credentials);
|
||||||
|
await using var untis = new WebUntisIntegrationService(new HttpClient(handler), settings);
|
||||||
|
await untis.ConnectAsync(credentials);
|
||||||
|
var vm = new WebUntisHomeworkComparisonViewModel(untis, new FakeStudents([]),
|
||||||
|
new FakeGroups([]), new FakeSubjects([]), new FakeMemberships([]),
|
||||||
|
new FakeSessions([]), new FakeEntries(), new SchoolYearService())
|
||||||
|
{
|
||||||
|
StartDate = new DateTimeOffset(2026, 9, 24, 12, 0, 0, TimeSpan.Zero),
|
||||||
|
EndDate = new DateTimeOffset(2026, 9, 26, 12, 0, 0, TimeSpan.Zero),
|
||||||
|
};
|
||||||
|
|
||||||
|
await vm.LoadCommand.ExecuteAsync(null);
|
||||||
|
|
||||||
|
Assert.Equal("Gerste Amelia", Assert.Single(vm.Rows).UntisStudentName);
|
||||||
|
Assert.Contains("1 passende Einträge von 2", vm.Status);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task LoadUndApply_TrenntBestehendenStatus_ZielstatusUndLokaleEintraege()
|
||||||
|
{
|
||||||
|
const string report = "Klasse\tDatum\tFach\tName\tBenutzer\tEintragskategorie\tKategoriegruppe\tText\r\n" +
|
||||||
|
"10c\t25.09.26\tChe\tGerste Amelia\tlehrkraft\tFehlende HA\tNegativ\tChe: nicht gemacht\r\n" +
|
||||||
|
"10c\t25.09.26\tChe\tMuster Ben\tlehrkraft\tFehlende HA\tNegativ\tChe: nicht gemacht\r\n";
|
||||||
|
var handler = new QueueHandler(
|
||||||
|
Json("{\"result\":{\"sessionId\":\"s\"}}"),
|
||||||
|
Json("{\"result\":[{\"id\":1,\"name\":\"2026/27\",\"startDate\":20260801,\"endDate\":20270731}]}"),
|
||||||
|
Json("{\"data\":{\"finished\":true,\"error\":false," +
|
||||||
|
"\"reportParams\":\"get=rpt.tmp&name=ClassregEventPerStudent&format=csv\"}}"),
|
||||||
|
new HttpResponseMessage(HttpStatusCode.OK)
|
||||||
|
{
|
||||||
|
Content = new ByteArrayContent(Encoding.UTF8.GetBytes(report)),
|
||||||
|
});
|
||||||
|
var settings = TestSupport.BuildWebUntisSettingsService();
|
||||||
|
var credentials = new WebUntisCredentials("schule", "arche.webuntis.com", "lehrkraft", "geheim");
|
||||||
|
settings.SetApiCredentials(credentials);
|
||||||
|
await using var untis = new WebUntisIntegrationService(new HttpClient(handler), settings);
|
||||||
|
await untis.ConnectAsync(credentials);
|
||||||
|
|
||||||
|
var date = new DateOnly(2026, 9, 25);
|
||||||
|
var schoolYear = new SchoolYearService();
|
||||||
|
var chemistry = new Subject { Name = "Chemie", ShortName = "Che" };
|
||||||
|
var biology = new Subject { Name = "Biologie", ShortName = "Bio" };
|
||||||
|
var classGroup = new LearningGroup { Name = "10c", Type = GroupType.Class,
|
||||||
|
SchoolYear = schoolYear.CurrentSchoolYear(date) };
|
||||||
|
var chemistryGroup = new LearningGroup { Name = "Chemie 10c", Type = GroupType.Course,
|
||||||
|
SubjectId = chemistry.Id, SchoolYear = classGroup.SchoolYear };
|
||||||
|
var biologyGroup = new LearningGroup { Name = "Biologie 10c", Type = GroupType.Course,
|
||||||
|
SubjectId = biology.Id, SchoolYear = classGroup.SchoolYear };
|
||||||
|
var amelia = new Student { FirstName = "Amelia", LastName = "Gerste" };
|
||||||
|
var ben = new Student { FirstName = "Ben", LastName = "Muster" };
|
||||||
|
var carl = new Student { FirstName = "Carl", LastName = "Beispiel" };
|
||||||
|
var chemistrySession = new ParticipationSession { GroupId = chemistryGroup.Id, Date = date };
|
||||||
|
var biologySession = new ParticipationSession { GroupId = biologyGroup.Id, Date = date };
|
||||||
|
var memberships = new FakeMemberships([
|
||||||
|
new GroupMembership { StudentId = amelia.Id, GroupId = chemistryGroup.Id },
|
||||||
|
new GroupMembership { StudentId = amelia.Id, GroupId = biologyGroup.Id },
|
||||||
|
new GroupMembership { StudentId = ben.Id, GroupId = chemistryGroup.Id },
|
||||||
|
new GroupMembership { StudentId = carl.Id, GroupId = chemistryGroup.Id },
|
||||||
|
]);
|
||||||
|
var participation = new FakeEntries();
|
||||||
|
participation.Add(new ParticipationEntry { SessionId = chemistrySession.Id, StudentId = amelia.Id,
|
||||||
|
Homework = HomeworkStatus.MissingOpen, HomeworkMissing = true });
|
||||||
|
participation.Add(new ParticipationEntry { SessionId = biologySession.Id, StudentId = amelia.Id,
|
||||||
|
Homework = HomeworkStatus.PartiallyCompleted, HomeworkMissing = true });
|
||||||
|
participation.Add(new ParticipationEntry { SessionId = chemistrySession.Id, StudentId = carl.Id,
|
||||||
|
Homework = HomeworkStatus.MissingOverdue, HomeworkMissing = true });
|
||||||
|
|
||||||
|
var vm = new WebUntisHomeworkComparisonViewModel(untis,
|
||||||
|
new FakeStudents([amelia, ben, carl]),
|
||||||
|
new FakeGroups([classGroup, chemistryGroup, biologyGroup]),
|
||||||
|
new FakeSubjects([chemistry, biology]), memberships,
|
||||||
|
new FakeSessions([chemistrySession, biologySession]), participation, schoolYear)
|
||||||
|
{
|
||||||
|
StartDate = new DateTimeOffset(2026, 9, 24, 12, 0, 0, TimeSpan.Zero),
|
||||||
|
EndDate = new DateTimeOffset(2026, 9, 26, 12, 0, 0, TimeSpan.Zero),
|
||||||
|
};
|
||||||
|
|
||||||
|
await vm.LoadCommand.ExecuteAsync(null);
|
||||||
|
|
||||||
|
var existing = Assert.Single(vm.Rows, r => r.AssignedStudent?.Id == amelia.Id);
|
||||||
|
Assert.False(existing.Selected);
|
||||||
|
Assert.Equal(HomeworkDisplay.Label(HomeworkStatus.MissingOpen), existing.LocalStatus);
|
||||||
|
Assert.Equal(HomeworkDisplay.Label(HomeworkStatus.MissingOpen), existing.SelectedStatusName);
|
||||||
|
var newRow = Assert.Single(vm.Rows, r => r.AssignedStudent?.Id == ben.Id);
|
||||||
|
Assert.True(newRow.Selected);
|
||||||
|
Assert.Equal("Noch kein Status erfasst", newRow.LocalStatus);
|
||||||
|
Assert.Equal(2, vm.LocalOnlyRows.Count);
|
||||||
|
Assert.Contains(vm.LocalOnlyRows, r => r.StudentName == amelia.FullName && r.GroupName == biologyGroup.Name);
|
||||||
|
Assert.Contains(vm.LocalOnlyRows, r => r.StudentName == carl.FullName && r.GroupName == chemistryGroup.Name);
|
||||||
|
|
||||||
|
newRow.AssignedStudent = carl;
|
||||||
|
Assert.Single(vm.LocalOnlyRows);
|
||||||
|
Assert.False(newRow.Selected);
|
||||||
|
newRow.AssignedStudent = ben;
|
||||||
|
Assert.Equal(2, vm.LocalOnlyRows.Count);
|
||||||
|
newRow.SelectedStatusName = HomeworkDisplay.Label(HomeworkStatus.SubmittedLate);
|
||||||
|
vm.ApplyCommand.Execute(null);
|
||||||
|
|
||||||
|
var saved = participation.GetBySessionAndStudent(chemistrySession.Id, ben.Id);
|
||||||
|
Assert.Equal(HomeworkStatus.SubmittedLate, saved?.Homework);
|
||||||
|
Assert.False(saved?.HomeworkMissing);
|
||||||
|
Assert.Equal(HomeworkDisplay.Label(HomeworkStatus.SubmittedLate), newRow.LocalStatus);
|
||||||
|
Assert.False(newRow.Selected);
|
||||||
|
Assert.Equal(HomeworkStatus.MissingOpen,
|
||||||
|
participation.GetBySessionAndStudent(chemistrySession.Id, amelia.Id)?.Homework);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static HttpResponseMessage Json(string json) => new(HttpStatusCode.OK)
|
||||||
|
{
|
||||||
|
Content = new StringContent(json, Encoding.UTF8, "application/json"),
|
||||||
|
};
|
||||||
|
|
||||||
|
private sealed class QueueHandler(params HttpResponseMessage[] responses) : HttpMessageHandler
|
||||||
|
{
|
||||||
|
private readonly Queue<HttpResponseMessage> _responses = new(responses);
|
||||||
|
|
||||||
|
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
|
||||||
|
CancellationToken cancellationToken) => Task.FromResult(_responses.Dequeue());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,208 @@
|
|||||||
|
using LehrerApp.Core.Interfaces;
|
||||||
|
using LehrerApp.Core.Models;
|
||||||
|
using LehrerApp.Core.Services;
|
||||||
|
using LehrerApp.Desktop.Services;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace LehrerApp.Desktop.Tests;
|
||||||
|
|
||||||
|
public sealed class WebUntisRestSyncProcessorTests
|
||||||
|
{
|
||||||
|
private static readonly DateOnly Monday = new(2026, 9, 28);
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Process_AusfallImDoppelblock_SchreibtBeideStundenUndIstIdempotent()
|
||||||
|
{
|
||||||
|
var group = new LearningGroup { Id = Guid.NewGuid(), Name = "8c" };
|
||||||
|
var mappings = new FakeUntisSlotMappings();
|
||||||
|
mappings.Add(new UntisSlotMapping
|
||||||
|
{
|
||||||
|
Weekday = DayOfWeek.Tuesday, StartTime = new TimeOnly(9, 40), Summary = "NAT",
|
||||||
|
ClassToken = "8c", Kind = SubstitutionKind.Lesson, GroupId = group.Id,
|
||||||
|
PeriodNumber = 3, CoveredPeriods = [3, 4], Confirmed = true,
|
||||||
|
});
|
||||||
|
var substitutions = new FakeSubstitutionEntries();
|
||||||
|
var processor = BuildProcessor(mappings, substitutions, new RecordingExams(), [group]);
|
||||||
|
var cancelled = Entry([100, 101], "2026-09-29T09:40", "2026-09-29T11:10",
|
||||||
|
"NORMAL_TEACHING_PERIOD", "CANCELLED", "NAT", "8c");
|
||||||
|
|
||||||
|
var first = processor.Process([cancelled], Monday, Monday.AddDays(13), Monday.AddDays(27));
|
||||||
|
var second = processor.Process([cancelled], Monday, Monday.AddDays(13), Monday.AddDays(27));
|
||||||
|
|
||||||
|
Assert.Equal(2, first.SubstitutionChanges);
|
||||||
|
Assert.Equal(0, second.SubstitutionChanges);
|
||||||
|
Assert.Equal([3, 4], substitutions.GetAll().Select(entry => entry.PeriodNumber).Order().ToArray());
|
||||||
|
Assert.All(substitutions.GetAll(), entry => Assert.Equal(SubstitutionKind.Cancelled, entry.Kind));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Process_Exam_LegtArbeitMitTitelAnUndEntferntSieNachVerschwinden()
|
||||||
|
{
|
||||||
|
var group = new LearningGroup { Id = Guid.NewGuid(), Name = "Mat_E" };
|
||||||
|
var mappings = new FakeUntisSlotMappings();
|
||||||
|
mappings.Add(new UntisSlotMapping
|
||||||
|
{
|
||||||
|
Weekday = DayOfWeek.Tuesday, StartTime = new TimeOnly(9, 40), Summary = "Mat_E",
|
||||||
|
ClassToken = "10a;10b;10c;Gastro", Kind = SubstitutionKind.Lesson, GroupId = group.Id,
|
||||||
|
PeriodNumber = 3, CoveredPeriods = [3, 4], Confirmed = true,
|
||||||
|
});
|
||||||
|
var exams = new RecordingExams();
|
||||||
|
var processor = BuildProcessor(mappings, new FakeSubstitutionEntries(), exams, [group]);
|
||||||
|
var exam = Entry([2002979, 2002982], "2026-09-29T09:40", "2026-09-29T11:10",
|
||||||
|
"EXAM", "REGULAR", "Mat_E", "10a", "Arbeit 1. Mathearbeit");
|
||||||
|
|
||||||
|
var imported = processor.Process([exam], Monday, Monday.AddDays(13), Monday.AddDays(27));
|
||||||
|
var unchanged = processor.Process([exam], Monday, Monday.AddDays(13), Monday.AddDays(27));
|
||||||
|
var removed = processor.Process([], Monday, Monday.AddDays(13), Monday.AddDays(27));
|
||||||
|
|
||||||
|
Assert.Equal(1, imported.ExamChanges);
|
||||||
|
Assert.Equal(0, unchanged.ExamChanges);
|
||||||
|
Assert.Equal(1, removed.ExamChanges);
|
||||||
|
Assert.Empty(exams.GetAll());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Process_DoppeltAngelegteArbeitDurchGeraeteSync_WirdAufEinenDatensatzReduziert()
|
||||||
|
{
|
||||||
|
var group = new LearningGroup { Id = Guid.NewGuid(), Name = "Mat_E" };
|
||||||
|
var mappings = new FakeUntisSlotMappings();
|
||||||
|
mappings.Add(new UntisSlotMapping
|
||||||
|
{
|
||||||
|
Weekday = DayOfWeek.Tuesday, StartTime = new TimeOnly(9, 40), Summary = "Mat_E",
|
||||||
|
ClassToken = "10a", Kind = SubstitutionKind.Lesson, GroupId = group.Id,
|
||||||
|
PeriodNumber = 3, CoveredPeriods = [3, 4], Confirmed = true,
|
||||||
|
});
|
||||||
|
var exam = Entry([2002979, 2002982], "2026-09-29T09:40", "2026-09-29T11:10",
|
||||||
|
"EXAM", "REGULAR", "Mat_E", "10a", "Arbeit 1. Mathearbeit");
|
||||||
|
var externalId = WebUntisRestSyncProcessor.ExamPrefix + "2002979-2002982";
|
||||||
|
// Zwei Geräte haben dieselbe WebUntis-Arbeit unabhängig voneinander (vor dem gegenseitigen
|
||||||
|
// Sync) mit derselben ExternalId, aber unterschiedlicher Id angelegt.
|
||||||
|
var olderDuplicate = new Exam
|
||||||
|
{
|
||||||
|
GroupId = group.Id, Date = new DateOnly(2026, 9, 29), Title = "Arbeit 1. Mathearbeit",
|
||||||
|
ExternalId = externalId, CreatedAt = new DateTime(2026, 9, 22, 8, 0, 0, DateTimeKind.Utc),
|
||||||
|
};
|
||||||
|
var newerDuplicate = new Exam
|
||||||
|
{
|
||||||
|
GroupId = group.Id, Date = new DateOnly(2026, 9, 29), Title = "Arbeit 1. Mathearbeit",
|
||||||
|
ExternalId = externalId, CreatedAt = new DateTime(2026, 9, 22, 9, 0, 0, DateTimeKind.Utc),
|
||||||
|
};
|
||||||
|
var exams = new RecordingExams([olderDuplicate, newerDuplicate]);
|
||||||
|
var processor = BuildProcessor(mappings, new FakeSubstitutionEntries(), exams, [group]);
|
||||||
|
|
||||||
|
var result = processor.Process([exam], Monday, Monday.AddDays(13), Monday.AddDays(27));
|
||||||
|
|
||||||
|
var remaining = Assert.Single(exams.GetAll());
|
||||||
|
Assert.Equal(olderDuplicate.Id, remaining.Id);
|
||||||
|
Assert.Equal(1, result.ExamChanges);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Process_DupliziertMitBereitsBenoteterKlausur_LoeschtNurDenNochPlanentenDatensatz()
|
||||||
|
{
|
||||||
|
var group = new LearningGroup { Id = Guid.NewGuid(), Name = "Mat_E" };
|
||||||
|
var mappings = new FakeUntisSlotMappings();
|
||||||
|
mappings.Add(new UntisSlotMapping
|
||||||
|
{
|
||||||
|
Weekday = DayOfWeek.Tuesday, StartTime = new TimeOnly(9, 40), Summary = "Mat_E",
|
||||||
|
ClassToken = "10a", Kind = SubstitutionKind.Lesson, GroupId = group.Id,
|
||||||
|
PeriodNumber = 3, CoveredPeriods = [3, 4], Confirmed = true,
|
||||||
|
});
|
||||||
|
var exam = Entry([2002979, 2002982], "2026-09-29T09:40", "2026-09-29T11:10",
|
||||||
|
"EXAM", "REGULAR", "Mat_E", "10a", "Arbeit 1. Mathearbeit");
|
||||||
|
var externalId = WebUntisRestSyncProcessor.ExamPrefix + "2002979-2002982";
|
||||||
|
var gradedDuplicate = new Exam
|
||||||
|
{
|
||||||
|
GroupId = group.Id, Date = new DateOnly(2026, 9, 29), Title = "Arbeit 1. Mathearbeit",
|
||||||
|
ExternalId = externalId, Status = ExamStatus.Graded,
|
||||||
|
};
|
||||||
|
var plannedDuplicate = new Exam
|
||||||
|
{
|
||||||
|
GroupId = group.Id, Date = new DateOnly(2026, 9, 29), Title = "Arbeit 1. Mathearbeit",
|
||||||
|
ExternalId = externalId,
|
||||||
|
};
|
||||||
|
var exams = new RecordingExams([gradedDuplicate, plannedDuplicate]);
|
||||||
|
var processor = BuildProcessor(mappings, new FakeSubstitutionEntries(), exams, [group]);
|
||||||
|
|
||||||
|
processor.Process([exam], Monday, Monday.AddDays(13), Monday.AddDays(27));
|
||||||
|
|
||||||
|
var remaining = Assert.Single(exams.GetAll());
|
||||||
|
Assert.Equal(gradedDuplicate.Id, remaining.Id);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Process_ManuelleArbeitAmSelbenTag_WirdNichtDupliziertOderGeloescht()
|
||||||
|
{
|
||||||
|
var group = new LearningGroup { Id = Guid.NewGuid(), Name = "Mat_E" };
|
||||||
|
var manual = new Exam { GroupId = group.Id, Date = new DateOnly(2026, 9, 29), Title = "1. Arbeit" };
|
||||||
|
var exams = new RecordingExams([manual]);
|
||||||
|
var mappings = new FakeUntisSlotMappings();
|
||||||
|
mappings.Add(new UntisSlotMapping
|
||||||
|
{
|
||||||
|
Weekday = DayOfWeek.Tuesday, StartTime = new TimeOnly(9, 40), Summary = "Mat_E",
|
||||||
|
ClassToken = "10a", GroupId = group.Id, PeriodNumber = 3, CoveredPeriods = [3, 4], Confirmed = true,
|
||||||
|
});
|
||||||
|
var processor = BuildProcessor(mappings, new FakeSubstitutionEntries(), exams, [group]);
|
||||||
|
|
||||||
|
processor.Process([Entry([1], "2026-09-29T09:40", "2026-09-29T11:10", "EXAM", "REGULAR",
|
||||||
|
"Mat_E", "10a", "Arbeit aus WebUntis")], Monday, Monday.AddDays(13), Monday.AddDays(27));
|
||||||
|
|
||||||
|
Assert.Same(manual, Assert.Single(exams.GetAll()));
|
||||||
|
Assert.Null(manual.ExternalId);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Process_UebernommeneRegulaereAufsicht_WirdAlsAenderungErfasst()
|
||||||
|
{
|
||||||
|
var duties = new FakeSupervisionDuties();
|
||||||
|
duties.Add(new SupervisionDuty { Weekday = DayOfWeek.Wednesday, AfterPeriod = 2, Location = "PH grün" });
|
||||||
|
var substitutions = new FakeSubstitutionEntries();
|
||||||
|
var processor = BuildProcessor(new FakeUntisSlotMappings(), substitutions, new RecordingExams(), [], duties);
|
||||||
|
var entry = new UntisTimetableGridEntryDto([17], new DateTime(2026, 9, 30, 9, 20, 0),
|
||||||
|
new DateTime(2026, 9, 30, 9, 40, 0), "BREAK_SUPERVISION", "CHANGED", "SUBSTITUTED",
|
||||||
|
null, null, null, null,
|
||||||
|
[new UntisGridResourceChangeDto(null,
|
||||||
|
new UntisGridResourceDto("TEACHER", "REMOVED", "HED", null, "HED"))]);
|
||||||
|
|
||||||
|
processor.Process([entry], Monday, Monday.AddDays(13), Monday.AddDays(27));
|
||||||
|
|
||||||
|
var change = Assert.Single(substitutions.GetAll());
|
||||||
|
Assert.Equal(SubstitutionKind.Supervision, change.Kind);
|
||||||
|
Assert.Equal(2, change.AfterPeriod);
|
||||||
|
Assert.Contains("übernommen", change.Description);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static WebUntisRestSyncProcessor BuildProcessor(FakeUntisSlotMappings mappings,
|
||||||
|
FakeSubstitutionEntries substitutions, IExamRepository exams, List<LearningGroup> groups,
|
||||||
|
FakeSupervisionDuties? supervisionDuties = null)
|
||||||
|
{
|
||||||
|
var path = Path.Combine(Path.GetTempPath(), $"lehrerapp-rest-sync-tests-{Guid.NewGuid():N}");
|
||||||
|
Directory.CreateDirectory(path);
|
||||||
|
var periods = new PeriodScheduleService(path);
|
||||||
|
periods.SetPeriods([
|
||||||
|
new PeriodTimeEntry { PeriodNumber = 2, Start = new TimeOnly(8, 35), End = new TimeOnly(9, 20) },
|
||||||
|
new PeriodTimeEntry { PeriodNumber = 3, Start = new TimeOnly(9, 40), End = new TimeOnly(10, 25) },
|
||||||
|
new PeriodTimeEntry { PeriodNumber = 4, Start = new TimeOnly(10, 25), End = new TimeOnly(11, 10) },
|
||||||
|
]);
|
||||||
|
return new WebUntisRestSyncProcessor(mappings, substitutions, exams, new FakeGroups(groups),
|
||||||
|
supervisionDuties ?? new FakeSupervisionDuties(), periods);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static UntisTimetableGridEntryDto Entry(IReadOnlyList<int> ids, string start, string end,
|
||||||
|
string type, string status, string subject, string className, string? lessonInfo = null) => new(
|
||||||
|
ids, DateTime.Parse(start), DateTime.Parse(end), type, status, null, null, null, lessonInfo, null,
|
||||||
|
[
|
||||||
|
new UntisGridResourceChangeDto(new UntisGridResourceDto("CLASS", "REGULAR", className, null, className), null),
|
||||||
|
new UntisGridResourceChangeDto(new UntisGridResourceDto("SUBJECT", "REGULAR", subject, null, subject), null),
|
||||||
|
]);
|
||||||
|
|
||||||
|
private sealed class RecordingExams(List<Exam>? initial = null) : IExamRepository
|
||||||
|
{
|
||||||
|
private readonly List<Exam> _all = initial ?? [];
|
||||||
|
public Exam? GetById(Guid id) => _all.FirstOrDefault(exam => exam.Id == id);
|
||||||
|
public List<Exam> GetAll() => _all.ToList();
|
||||||
|
public List<Exam> GetByGroup(Guid groupId) => _all.Where(exam => exam.GroupId == groupId).ToList();
|
||||||
|
public void Save(Exam exam) { _all.RemoveAll(item => item.Id == exam.Id); _all.Add(exam); }
|
||||||
|
public void Delete(Guid id) => _all.RemoveAll(exam => exam.Id == id);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -572,6 +572,51 @@ public sealed class TimeTrackingViewModelTests
|
|||||||
|
|
||||||
Assert.False(called);
|
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
|
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; }
|
||||||
|
}
|
||||||
@@ -7,6 +7,19 @@
|
|||||||
<ResourceDictionary.MergedDictionaries>
|
<ResourceDictionary.MergedDictionaries>
|
||||||
<ResourceInclude Source="avares://LehrerApp.Desktop/Styles/SemanticBrushes.axaml"/>
|
<ResourceInclude Source="avares://LehrerApp.Desktop/Styles/SemanticBrushes.axaml"/>
|
||||||
</ResourceDictionary.MergedDictionaries>
|
</ResourceDictionary.MergedDictionaries>
|
||||||
|
<!-- Plattformunabhängige Vektoricons für die Hauptnavigation (14.10). -->
|
||||||
|
<StreamGeometry x:Key="IconSearch">M10,2 A8,8 0 1 0 10,18 A8,8 0 1 0 10,2 M10,5 A5,5 0 1 1 10,15 A5,5 0 1 1 10,5 M15,14 L22,21 L20,23 L13,16 Z</StreamGeometry>
|
||||||
|
<StreamGeometry x:Key="IconDashboard">M3,3 H10 V10 H3 Z M14,3 H21 V7 H14 Z M14,11 H21 V21 H14 Z M3,14 H10 V21 H3 Z</StreamGeometry>
|
||||||
|
<StreamGeometry x:Key="IconGroups">M3,8 L12,3 L21,8 V10 H3 Z M5,11 H8 V18 H5 Z M10,11 H14 V18 H10 Z M16,11 H19 V18 H16 Z M3,20 H21 V22 H3 Z</StreamGeometry>
|
||||||
|
<StreamGeometry x:Key="IconStudents">M12,3 A4,4 0 1 0 12,11 A4,4 0 1 0 12,3 M4,21 C4,16 7,13 12,13 C17,13 20,16 20,21 Z</StreamGeometry>
|
||||||
|
<StreamGeometry x:Key="IconExams">M5,2 H15 L20,7 V22 H5 Z M7,5 V19 H18 V9 H13 V4 H7 Z M9,11 H16 V13 H9 Z M9,15 H16 V17 H9 Z</StreamGeometry>
|
||||||
|
<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>
|
</ResourceDictionary>
|
||||||
</Application.Resources>
|
</Application.Resources>
|
||||||
|
|
||||||
@@ -24,5 +37,17 @@
|
|||||||
<Setter Property="Opacity" Value="0.4"/>
|
<Setter Property="Opacity" Value="0.4"/>
|
||||||
<Setter Property="FontSize" Value="13"/>
|
<Setter Property="FontSize" Value="13"/>
|
||||||
</Style>
|
</Style>
|
||||||
|
<Style Selector="Button.touchTarget">
|
||||||
|
<Setter Property="MinWidth" Value="40"/>
|
||||||
|
<Setter Property="MinHeight" Value="40"/>
|
||||||
|
</Style>
|
||||||
|
<Style Selector="Button:focus-visible">
|
||||||
|
<Setter Property="BorderBrush" Value="{DynamicResource SystemAccentColor}"/>
|
||||||
|
<Setter Property="BorderThickness" Value="2"/>
|
||||||
|
</Style>
|
||||||
|
<Style Selector="TextBox:focus-visible, ComboBox:focus-visible">
|
||||||
|
<Setter Property="BorderBrush" Value="{DynamicResource SystemAccentColor}"/>
|
||||||
|
<Setter Property="BorderThickness" Value="2"/>
|
||||||
|
</Style>
|
||||||
</Application.Styles>
|
</Application.Styles>
|
||||||
</Application>
|
</Application>
|
||||||
+154
-20
@@ -1,8 +1,11 @@
|
|||||||
using Avalonia;
|
using Avalonia;
|
||||||
|
using Avalonia.Controls;
|
||||||
using Avalonia.Controls.ApplicationLifetimes;
|
using Avalonia.Controls.ApplicationLifetimes;
|
||||||
using Avalonia.Markup.Xaml;
|
using Avalonia.Markup.Xaml;
|
||||||
using Avalonia.Styling;
|
using Avalonia.Styling;
|
||||||
|
using Avalonia.Threading;
|
||||||
using LehrerApp.Core.Interfaces;
|
using LehrerApp.Core.Interfaces;
|
||||||
|
using LehrerApp.Core.Models;
|
||||||
using LehrerApp.Core.Services;
|
using LehrerApp.Core.Services;
|
||||||
using LehrerApp.Data;
|
using LehrerApp.Data;
|
||||||
using LehrerApp.Desktop.Services;
|
using LehrerApp.Desktop.Services;
|
||||||
@@ -23,6 +26,9 @@ public class App : Application
|
|||||||
public static IServiceProvider Services { get; private set; } = null!;
|
public static IServiceProvider Services { get; private set; } = null!;
|
||||||
private static ServiceProvider? _serviceProvider;
|
private static ServiceProvider? _serviceProvider;
|
||||||
private static bool _exitHandlerAttached;
|
private static bool _exitHandlerAttached;
|
||||||
|
private static Task _initialPolls = Task.CompletedTask;
|
||||||
|
private static readonly CancellationTokenSource StartupCancellation = new();
|
||||||
|
private static DispatcherTimer? _homeworkOverdueTimer;
|
||||||
|
|
||||||
public override void Initialize() => AvaloniaXamlLoader.Load(this);
|
public override void Initialize() => AvaloniaXamlLoader.Load(this);
|
||||||
|
|
||||||
@@ -36,6 +42,21 @@ public class App : Application
|
|||||||
ApplyTheme(new AppearanceSettingsService(AppBootstrapper.ResolveAppDataPath()).Load());
|
ApplyTheme(new AppearanceSettingsService(AppBootstrapper.ResolveAppDataPath()).Load());
|
||||||
|
|
||||||
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
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
|
// Verschlüsselte Datenbank (13.3.4): Passwort abfragen, bevor die Datenbank
|
||||||
// (und damit BuildServices, das sie öffnet) angefasst wird.
|
// (und damit BuildServices, das sie öffnet) angefasst wird.
|
||||||
@@ -44,34 +65,43 @@ public class App : Application
|
|||||||
var promptVm = new DbPasswordPromptViewModel(
|
var promptVm = new DbPasswordPromptViewModel(
|
||||||
new DatabaseEncryptionService(), AppBootstrapper.ResolveDbPath());
|
new DatabaseEncryptionService(), AppBootstrapper.ResolveDbPath());
|
||||||
var promptWindow = new DbPasswordPromptWindow { DataContext = promptVm };
|
var promptWindow = new DbPasswordPromptWindow { DataContext = promptVm };
|
||||||
promptVm.OnUnlocked = password =>
|
promptVm.OnUnlocked = async password =>
|
||||||
{
|
{
|
||||||
AppBootstrapper.DbPassword = password;
|
AppBootstrapper.DbPassword = password;
|
||||||
StartMainApp(desktop, showImmediately: true);
|
var unlockedSplash = new SplashWindow();
|
||||||
|
desktop.MainWindow = unlockedSplash;
|
||||||
|
unlockedSplash.Show();
|
||||||
promptWindow.Close();
|
promptWindow.Close();
|
||||||
|
await StartMainAppAsync(desktop, unlockedSplash);
|
||||||
};
|
};
|
||||||
desktop.MainWindow = promptWindow;
|
desktop.MainWindow = promptWindow;
|
||||||
}
|
promptWindow.Show();
|
||||||
else
|
splash.Close();
|
||||||
{
|
return;
|
||||||
StartMainApp(desktop, showImmediately: false);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
base.OnFrameworkInitializationCompleted();
|
await StartMainAppAsync(desktop, splash);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void StartMainApp(
|
private static async Task StartMainAppAsync(
|
||||||
IClassicDesktopStyleApplicationLifetime desktop, bool showImmediately)
|
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 = _serviceProvider;
|
||||||
Services.GetRequiredService<AppLogger>().Info("Anwendung gestartet.");
|
Services.GetRequiredService<AppLogger>().Info("Anwendung gestartet.");
|
||||||
GlobalExceptionHandler.AttachNotifications(Services.GetRequiredService<NotificationService>());
|
GlobalExceptionHandler.AttachNotifications(Services.GetRequiredService<NotificationService>());
|
||||||
// Papierkorb (14.3): Einträge älter als 30 Tage endgültig entfernen. Beim Start statt per
|
// 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
|
// Timer - reicht für ein Werkzeug, das ohnehin nur "Fehlklick eben rückgängig machen" sein
|
||||||
// soll, kein dauerhaftes Archiv.
|
// 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)));
|
||||||
|
await AdvanceHomeworkAsync();
|
||||||
|
|
||||||
if (!_exitHandlerAttached)
|
if (!_exitHandlerAttached)
|
||||||
{
|
{
|
||||||
@@ -79,23 +109,74 @@ public class App : Application
|
|||||||
_exitHandlerAttached = true;
|
_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>();
|
var mainVm = Services.GetRequiredService<MainWindowViewModel>();
|
||||||
WireCallbacks(mainVm);
|
WireCallbacks(mainVm);
|
||||||
|
|
||||||
// DI-Singletons werden erst beim ersten Auflösen erzeugt. Ohne dieses explizite
|
splash?.SetProgress(90, "Hauptfenster öffnen …");
|
||||||
// Auflösen entstand der Timer des optionalen WebUntis-Abgleichs erst, wenn die
|
await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.Background);
|
||||||
// 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();
|
|
||||||
|
|
||||||
var main = new MainWindow { DataContext = mainVm };
|
var main = new MainWindow { DataContext = mainVm };
|
||||||
main.EnableWindowSizePersistence(Services.GetRequiredService<WindowSettingsService>());
|
main.EnableWindowSizePersistence(Services.GetRequiredService<WindowSettingsService>());
|
||||||
if (Services.GetService<SyncEngine>() is { } syncEngine)
|
if (Services.GetService<SyncEngine>() is { } syncEngine)
|
||||||
main.EnableFinalSync(syncEngine);
|
main.EnableFinalSync(syncEngine);
|
||||||
desktop.MainWindow = main;
|
desktop.MainWindow = main;
|
||||||
if (showImmediately) main.Show();
|
main.Show();
|
||||||
|
StartHomeworkOverdueTimer();
|
||||||
|
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); }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task AdvanceHomeworkAsync()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var changed = await Task.Run(() => Services.GetRequiredService<HomeworkOverdueService>()
|
||||||
|
.Advance(DateOnly.FromDateTime(DateTime.Today)));
|
||||||
|
if (changed > 0) AppBootstrapper.Logger.Info($"{changed} offene Hausaufgaben als nicht nachgereicht markiert.");
|
||||||
|
}
|
||||||
|
catch (Exception ex) { AppBootstrapper.Logger.Error("Hausaufgaben-Fristprüfung fehlgeschlagen.", ex); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void StartHomeworkOverdueTimer()
|
||||||
|
{
|
||||||
|
var timer = new DispatcherTimer { Interval = TimeSpan.FromHours(1) };
|
||||||
|
timer.Tick += async (_, _) =>
|
||||||
|
{
|
||||||
|
timer.Stop();
|
||||||
|
await AdvanceHomeworkAsync();
|
||||||
|
if (_serviceProvider is not null) timer.Start();
|
||||||
|
};
|
||||||
|
_homeworkOverdueTimer = timer;
|
||||||
|
timer.Start();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Wechselt die Darstellung sofort, ohne Neustart (12.4) — Avalonia stylt den
|
/// <summary>Wechselt die Darstellung sofort, ohne Neustart (12.4) — Avalonia stylt den
|
||||||
@@ -111,11 +192,14 @@ public class App : Application
|
|||||||
|
|
||||||
private static void DisposeServices()
|
private static void DisposeServices()
|
||||||
{
|
{
|
||||||
|
_homeworkOverdueTimer?.Stop();
|
||||||
var serviceProvider = Interlocked.Exchange(ref _serviceProvider, null);
|
var serviceProvider = Interlocked.Exchange(ref _serviceProvider, null);
|
||||||
if (serviceProvider is null) return;
|
if (serviceProvider is null) return;
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
StartupCancellation.Cancel();
|
||||||
|
_initialPolls.GetAwaiter().GetResult();
|
||||||
serviceProvider.GetService<LiteDbContext>()?.Checkpoint();
|
serviceProvider.GetService<LiteDbContext>()?.Checkpoint();
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
@@ -153,6 +237,10 @@ public class App : Application
|
|||||||
dash.OnNavigateToLesson = id => main.NavigateToGroupDetail(id, 3); // Tab "Mitarbeit"
|
dash.OnNavigateToLesson = id => main.NavigateToGroupDetail(id, 3); // Tab "Mitarbeit"
|
||||||
dash.OnNavigateToExam = id => main.NavigateToGroupDetail(id, 4); // Tab "Klausuren"
|
dash.OnNavigateToExam = id => main.NavigateToGroupDetail(id, 4); // Tab "Klausuren"
|
||||||
dash.OnNavigateToUnplannedLesson = id => main.NavigateToGroupDetail(id, 6); // Tab "Planung"
|
dash.OnNavigateToUnplannedLesson = id => main.NavigateToGroupDetail(id, 6); // Tab "Planung"
|
||||||
|
dash.OnAddMissingTeachingTime = item => ShowMissingTeachingTimeDialog(item, dash);
|
||||||
|
|
||||||
|
var examsOverview = Services.GetRequiredService<ViewModels.Exams.ExamsOverviewViewModel>();
|
||||||
|
examsOverview.OnNavigateToGroups = () => main.NavigateToCommand.Execute(NavItem.Groups);
|
||||||
|
|
||||||
// Globale Suche/Schnellerfassung (14.2): Navigation bleibt im MainWindow-VM, die
|
// Globale Suche/Schnellerfassung (14.2): Navigation bleibt im MainWindow-VM, die
|
||||||
// vorhandenen Dialog-Helfer übernehmen Eingabe und Validierung.
|
// vorhandenen Dialog-Helfer übernehmen Eingabe und Validierung.
|
||||||
@@ -170,6 +258,7 @@ public class App : Application
|
|||||||
};
|
};
|
||||||
search.OnQuickAddTask = startAsReminder => ShowQuickTaskDialog(startAsReminder, dash);
|
search.OnQuickAddTask = startAsReminder => ShowQuickTaskDialog(startAsReminder, dash);
|
||||||
search.OnQuickAddStudent = ShowAddStudentDialog;
|
search.OnQuickAddStudent = ShowAddStudentDialog;
|
||||||
|
search.OnQuickAddGroupDocumentation = () => ShowQuickGroupDocumentationDialog(dash);
|
||||||
|
|
||||||
// StudentList → StudentDetail + Anlegen
|
// StudentList → StudentDetail + Anlegen
|
||||||
var sl = Services.GetRequiredService<StudentListViewModel>();
|
var sl = Services.GetRequiredService<StudentListViewModel>();
|
||||||
@@ -203,4 +292,49 @@ public class App : Application
|
|||||||
dashboard.RefreshCommand.Execute(null);
|
dashboard.RefreshCommand.Execute(null);
|
||||||
Services.GetRequiredService<WorkTaskListViewModel>().Load();
|
Services.GetRequiredService<WorkTaskListViewModel>().Load();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static async Task ShowMissingTeachingTimeDialog(MissingTeachingTimeItem item, DashboardViewModel dashboard)
|
||||||
|
{
|
||||||
|
if (Application.Current?.ApplicationLifetime is not IClassicDesktopStyleApplicationLifetime
|
||||||
|
{ MainWindow: { } owner }) return;
|
||||||
|
|
||||||
|
var tasks = Services.GetRequiredService<IWorkTaskRepository>()
|
||||||
|
.GetAll().Where(t => t.Status != WorkTaskStatus.Done).ToList();
|
||||||
|
var vm = new AddTimeEntryDialogViewModel(tasks)
|
||||||
|
{
|
||||||
|
DateText = item.Date.ToString("dd.MM.yyyy"),
|
||||||
|
SelectedCategory = "Unterricht",
|
||||||
|
StartTimeText = item.WindowStart.ToString("HH:mm"),
|
||||||
|
EndTimeText = item.WindowEnd.ToString("HH:mm"),
|
||||||
|
};
|
||||||
|
var dialog = new AddTimeEntryDialog { DataContext = vm };
|
||||||
|
await dialog.ShowDialog<bool>(owner);
|
||||||
|
if (vm.Result is null) return;
|
||||||
|
|
||||||
|
Services.GetRequiredService<ITimeEntryRepository>().Save(vm.Result);
|
||||||
|
dashboard.RefreshCommand.Execute(null);
|
||||||
|
Services.GetRequiredService<TimeTrackingViewModel>().Load();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task ShowQuickGroupDocumentationDialog(DashboardViewModel dashboard)
|
||||||
|
{
|
||||||
|
if (Application.Current?.ApplicationLifetime is not IClassicDesktopStyleApplicationLifetime
|
||||||
|
{ MainWindow: { } owner }) return;
|
||||||
|
|
||||||
|
var subjects = Services.GetRequiredService<ISubjectRepository>().GetAll()
|
||||||
|
.ToDictionary(s => s.Id);
|
||||||
|
var options = Services.GetRequiredService<IGroupRepository>().GetAll()
|
||||||
|
.Where(g => g.IsActive)
|
||||||
|
.OrderBy(g => g.Name)
|
||||||
|
.Select(g => new GroupDocumentationOption(g.Id,
|
||||||
|
g.SubjectId is { } subjectId && subjects.TryGetValue(subjectId, out var subject)
|
||||||
|
? $"{g.Name} · {(string.IsNullOrWhiteSpace(subject.ShortName) ? subject.Name : subject.ShortName)}"
|
||||||
|
: g.Name));
|
||||||
|
var vm = new GroupDocumentationQuickViewModel(options);
|
||||||
|
var dialog = new Views.Students.GroupDocumentationQuickDialog { DataContext = vm };
|
||||||
|
if (!await dialog.ShowDialog<bool>(owner) || vm.Result is null) return;
|
||||||
|
|
||||||
|
Services.GetRequiredService<IDocumentationRepository>().Save(vm.Result);
|
||||||
|
dashboard.RefreshCommand.Execute(null);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -4,6 +4,8 @@ using LehrerApp.Core.Services;
|
|||||||
using LehrerApp.Data;
|
using LehrerApp.Data;
|
||||||
using LehrerApp.Data.Repositories;
|
using LehrerApp.Data.Repositories;
|
||||||
using LehrerApp.Desktop.Services;
|
using LehrerApp.Desktop.Services;
|
||||||
|
using LehrerApp.Desktop.Services.Mcp;
|
||||||
|
using LehrerApp.Desktop.Services.Mcp.Tools;
|
||||||
using LehrerApp.Desktop.ViewModels;
|
using LehrerApp.Desktop.ViewModels;
|
||||||
using LehrerApp.Desktop.ViewModels.ClassTeacher;
|
using LehrerApp.Desktop.ViewModels.ClassTeacher;
|
||||||
using LehrerApp.Desktop.ViewModels.Exams;
|
using LehrerApp.Desktop.ViewModels.Exams;
|
||||||
@@ -16,6 +18,7 @@ using LehrerApp.Sync;
|
|||||||
using LehrerApp.Sync.Crypto;
|
using LehrerApp.Sync.Crypto;
|
||||||
using LehrerApp.Sync.Models;
|
using LehrerApp.Sync.Models;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using LehrerApp.Templating;
|
||||||
|
|
||||||
namespace LehrerApp.Desktop;
|
namespace LehrerApp.Desktop;
|
||||||
|
|
||||||
@@ -98,7 +101,7 @@ public static class AppBootstrapper
|
|||||||
Environment.Exit(0);
|
Environment.Exit(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static ServiceProvider BuildServices()
|
public static ServiceProvider BuildServices(Action<int, string>? reportProgress = null)
|
||||||
{
|
{
|
||||||
var services = new ServiceCollection();
|
var services = new ServiceCollection();
|
||||||
|
|
||||||
@@ -117,13 +120,25 @@ public static class AppBootstrapper
|
|||||||
services.AddSingleton<NotificationService>();
|
services.AddSingleton<NotificationService>();
|
||||||
services.AddSingleton<ExportService>();
|
services.AddSingleton<ExportService>();
|
||||||
services.AddSingleton<PdfExportService>();
|
services.AddSingleton<PdfExportService>();
|
||||||
|
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) ───────────────────────────────────────────
|
// ── Datensicherheit (13.3) ───────────────────────────────────────────
|
||||||
// Backup läuft vor dem Öffnen der Datenbank, rein dateibasiert (unabhängig von
|
// Backup läuft vor dem Öffnen der Datenbank, rein dateibasiert (unabhängig von
|
||||||
// Verschlüsselung) — reine Datei-Kopie, kein offener LiteDB-Handle nötig.
|
// Verschlüsselung) — reine Datei-Kopie, kein offener LiteDB-Handle nötig.
|
||||||
var backup = new BackupService(appData);
|
var backupSettings = new BackupSettingsService(appData);
|
||||||
backup.CreateBackup(DbPath);
|
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))
|
||||||
|
Logger.Warn($"Automatisches Backup {backupPath} lässt sich nicht öffnen/lesen — möglicherweise beschädigt.");
|
||||||
services.AddSingleton(backup);
|
services.AddSingleton(backup);
|
||||||
|
services.AddSingleton(backupSettings);
|
||||||
services.AddSingleton(_ => new AppLockService(appData));
|
services.AddSingleton(_ => new AppLockService(appData));
|
||||||
services.AddSingleton<DatabaseEncryptionService>();
|
services.AddSingleton<DatabaseEncryptionService>();
|
||||||
services.AddSingleton(_ => new PrivacySettingsService(appData));
|
services.AddSingleton(_ => new PrivacySettingsService(appData));
|
||||||
@@ -152,6 +167,7 @@ public static class AppBootstrapper
|
|||||||
services.AddSingleton<IUnitRepository, UnitRepository>();
|
services.AddSingleton<IUnitRepository, UnitRepository>();
|
||||||
services.AddSingleton<ILessonRepository, LessonRepository>();
|
services.AddSingleton<ILessonRepository, LessonRepository>();
|
||||||
services.AddSingleton<IDocumentationRepository, DocumentationRepository>();
|
services.AddSingleton<IDocumentationRepository, DocumentationRepository>();
|
||||||
|
services.AddSingleton<IVorgangRepository, VorgangRepository>();
|
||||||
services.AddSingleton<IWorkTaskRepository, WorkTaskRepository>();
|
services.AddSingleton<IWorkTaskRepository, WorkTaskRepository>();
|
||||||
services.AddSingleton<ITimeEntryRepository, TimeEntryRepository>();
|
services.AddSingleton<ITimeEntryRepository, TimeEntryRepository>();
|
||||||
services.AddSingleton<IParticipationSessionRepository, ParticipationSessionRepository>();
|
services.AddSingleton<IParticipationSessionRepository, ParticipationSessionRepository>();
|
||||||
@@ -160,6 +176,7 @@ public static class AppBootstrapper
|
|||||||
services.AddSingleton<IParticipationSectionRepository, ParticipationSectionRepository>();
|
services.AddSingleton<IParticipationSectionRepository, ParticipationSectionRepository>();
|
||||||
services.AddSingleton<ISubjectRepository, SubjectRepository>();
|
services.AddSingleton<ISubjectRepository, SubjectRepository>();
|
||||||
services.AddSingleton<ICompetencyDomainRepository, CompetencyDomainRepository>();
|
services.AddSingleton<ICompetencyDomainRepository, CompetencyDomainRepository>();
|
||||||
|
services.AddSingleton<ICompetencyCatalogVersionRepository, CompetencyCatalogVersionRepository>();
|
||||||
services.AddSingleton<IShorthandCodeRepository, ShorthandCodeRepository>();
|
services.AddSingleton<IShorthandCodeRepository, ShorthandCodeRepository>();
|
||||||
services.AddSingleton<IAlternativeLessonPathRepository, AlternativeLessonPathRepository>();
|
services.AddSingleton<IAlternativeLessonPathRepository, AlternativeLessonPathRepository>();
|
||||||
services.AddSingleton<IAttachmentStorage, LiteAttachmentStorage>();
|
services.AddSingleton<IAttachmentStorage, LiteAttachmentStorage>();
|
||||||
@@ -174,34 +191,61 @@ public static class AppBootstrapper
|
|||||||
services.AddSingleton<IUntisClassRegisterCacheRepository, UntisClassRegisterCacheRepository>();
|
services.AddSingleton<IUntisClassRegisterCacheRepository, UntisClassRegisterCacheRepository>();
|
||||||
services.AddSingleton<IUntisCacheFetchStateRepository, UntisCacheFetchStateRepository>();
|
services.AddSingleton<IUntisCacheFetchStateRepository, UntisCacheFetchStateRepository>();
|
||||||
services.AddSingleton<IUntisStudentRosterCacheRepository, UntisStudentRosterCacheRepository>();
|
services.AddSingleton<IUntisStudentRosterCacheRepository, UntisStudentRosterCacheRepository>();
|
||||||
|
services.AddSingleton<IUntisHubJobStateRepository, UntisHubJobStateRepository>();
|
||||||
|
|
||||||
// ── Services ──────────────────────────────────────────────────────────
|
// ── Services ──────────────────────────────────────────────────────────
|
||||||
services.AddSingleton<GradingService>();
|
services.AddSingleton<GradingService>();
|
||||||
services.AddSingleton<CompetencyAnalysisService>();
|
services.AddSingleton<CompetencyAnalysisService>();
|
||||||
services.AddSingleton<SchoolYearService>();
|
services.AddSingleton<SchoolYearService>();
|
||||||
|
services.AddSingleton<HomeworkOverdueService>();
|
||||||
services.AddSingleton<GroupRolloverService>();
|
services.AddSingleton<GroupRolloverService>();
|
||||||
services.AddSingleton<PublicHolidayService>();
|
services.AddSingleton<PublicHolidayService>();
|
||||||
services.AddSingleton(_ => new SchoolCalendarSettingsService(appData));
|
services.AddSingleton(_ => new SchoolCalendarSettingsService(appData));
|
||||||
services.AddSingleton(_ => new PeriodScheduleService(appData));
|
services.AddSingleton(_ => new PeriodScheduleService(appData));
|
||||||
services.AddSingleton(_ => new WorkloadSettingsService(appData));
|
services.AddSingleton(_ => new WorkloadSettingsService(appData));
|
||||||
services.AddSingleton(_ => new DashboardSettingsService(appData));
|
services.AddSingleton(_ => new DashboardSettingsService(appData));
|
||||||
|
services.AddSingleton(_ => new PatternScoreSettingsService(appData));
|
||||||
services.AddSingleton(_ => new WindowSettingsService(appData));
|
services.AddSingleton(_ => new WindowSettingsService(appData));
|
||||||
services.AddSingleton(_ => new AppearanceSettingsService(appData));
|
services.AddSingleton(_ => new AppearanceSettingsService(appData));
|
||||||
services.AddSingleton(_ => new LetterTemplateService(appData));
|
|
||||||
services.AddSingleton<PlanningExchangeService>();
|
services.AddSingleton<PlanningExchangeService>();
|
||||||
|
|
||||||
// ── KI-Unterstützung (4.5.9, optional – nur wenn in den Einstellungen aktiviert) ──────
|
// ── KI-Unterstützung (4.5.9, optional – nur wenn in den Einstellungen aktiviert) ──────
|
||||||
services.AddSingleton(_ => new AiSettingsService(appData));
|
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>();
|
services.AddSingleton<AiPlanningService>();
|
||||||
|
|
||||||
// ── WebUntis-iCal-Abgleich (optional – nur wenn URL hinterlegt und aktiviert) ─────────
|
// ── 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-Stundenplan-Abgleich (REST bei API-Zugang, sonst optionaler iCal-Fallback) ─
|
||||||
var untisSettings = new WebUntisSettingsService(appData);
|
var untisSettings = new WebUntisSettingsService(appData);
|
||||||
services.AddSingleton(untisSettings);
|
services.AddSingleton(untisSettings);
|
||||||
services.AddSingleton<UntisMatchingService>();
|
services.AddSingleton<UntisMatchingService>();
|
||||||
services.AddSingleton<UntisDiffService>();
|
services.AddSingleton<UntisDiffService>();
|
||||||
if (untisSettings.Enabled && !string.IsNullOrEmpty(untisSettings.GetIcalUrl()))
|
services.AddSingleton(sp => new WebUntisIntegrationService(new HttpClient(), untisSettings));
|
||||||
{
|
services.AddSingleton<WebUntisRestSyncProcessor>();
|
||||||
services.AddSingleton(sp => new UntisSyncService(
|
services.AddSingleton(sp => new UntisSyncService(
|
||||||
new HttpClient(), untisSettings,
|
new HttpClient(), untisSettings,
|
||||||
sp.GetRequiredService<IUntisSnapshotRepository>(), sp.GetRequiredService<IUntisSlotMappingRepository>(),
|
sp.GetRequiredService<IUntisSnapshotRepository>(), sp.GetRequiredService<IUntisSlotMappingRepository>(),
|
||||||
@@ -210,8 +254,8 @@ public static class AppBootstrapper
|
|||||||
sp.GetRequiredService<ISchoolHolidayRepository>(), sp.GetRequiredService<PublicHolidayService>(),
|
sp.GetRequiredService<ISchoolHolidayRepository>(), sp.GetRequiredService<PublicHolidayService>(),
|
||||||
sp.GetRequiredService<SchoolCalendarSettingsService>(), sp.GetRequiredService<PeriodScheduleService>(),
|
sp.GetRequiredService<SchoolCalendarSettingsService>(), sp.GetRequiredService<PeriodScheduleService>(),
|
||||||
sp.GetRequiredService<UntisMatchingService>(), sp.GetRequiredService<UntisDiffService>(),
|
sp.GetRequiredService<UntisMatchingService>(), sp.GetRequiredService<UntisDiffService>(),
|
||||||
sp.GetRequiredService<AppLogger>()));
|
sp.GetRequiredService<AppLogger>(), sp.GetRequiredService<WebUntisIntegrationService>(),
|
||||||
}
|
sp.GetRequiredService<WebUntisRestSyncProcessor>()));
|
||||||
|
|
||||||
// ── Schulweiter Jahresplan (informativer ClassyPlan-iCal, kein Stundenplan-Abgleich) ──
|
// ── Schulweiter Jahresplan (informativer ClassyPlan-iCal, kein Stundenplan-Abgleich) ──
|
||||||
var annualPlanSettings = new AnnualPlanSettingsService(appData);
|
var annualPlanSettings = new AnnualPlanSettingsService(appData);
|
||||||
@@ -229,8 +273,8 @@ public static class AppBootstrapper
|
|||||||
services.AddSingleton(syncSettings);
|
services.AddSingleton(syncSettings);
|
||||||
services.AddSingleton(_ => new SyncAuthService(new HttpClient()));
|
services.AddSingleton(_ => new SyncAuthService(new HttpClient()));
|
||||||
services.AddSingleton(sp => new SchoolWeatherService(new HttpClient(), syncSettings));
|
services.AddSingleton(sp => new SchoolWeatherService(new HttpClient(), syncSettings));
|
||||||
services.AddSingleton(sp => new WebUntisIntegrationService(new HttpClient(), untisSettings));
|
|
||||||
services.AddSingleton<UntisReportCacheService>();
|
services.AddSingleton<UntisReportCacheService>();
|
||||||
|
services.AddSingleton<UntisHubService>();
|
||||||
// War dieses Gerät schon eingeloggt, aber sync.key fehlt(e), wurde gerade eben (unten)
|
// War dieses Gerät schon eingeloggt, aber sync.key fehlt(e), wurde gerade eben (unten)
|
||||||
// stillschweigend ein neuer, unabhängiger Schlüssel erzeugt - bisher unter dem ALTEN
|
// 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.
|
// Schlüssel synchronisierte Server-Daten sind für dieses Gerät dann nicht mehr lesbar.
|
||||||
@@ -306,6 +350,7 @@ public static class AppBootstrapper
|
|||||||
services.AddSingleton<WorkloadEvaluationViewModel>();
|
services.AddSingleton<WorkloadEvaluationViewModel>();
|
||||||
services.AddSingleton<WorkloadViewModel>();
|
services.AddSingleton<WorkloadViewModel>();
|
||||||
services.AddSingleton<ClassTeacherDetailsViewModel>();
|
services.AddSingleton<ClassTeacherDetailsViewModel>();
|
||||||
|
services.AddSingleton<ClassTeacherCasesViewModel>();
|
||||||
services.AddSingleton<ClassTeacherOverviewViewModel>();
|
services.AddSingleton<ClassTeacherOverviewViewModel>();
|
||||||
services.AddSingleton<ExamsOverviewViewModel>();
|
services.AddSingleton<ExamsOverviewViewModel>();
|
||||||
|
|
||||||
@@ -323,13 +368,19 @@ public static class AppBootstrapper
|
|||||||
services.AddTransient<TrashViewModel>();
|
services.AddTransient<TrashViewModel>();
|
||||||
services.AddTransient<SettingsViewModel>();
|
services.AddTransient<SettingsViewModel>();
|
||||||
|
|
||||||
|
reportProgress?.Invoke(40, "Datenbank öffnen und aktualisieren …");
|
||||||
var provider = services.BuildServiceProvider();
|
var provider = services.BuildServiceProvider();
|
||||||
|
provider.GetRequiredService<LiteDbContext>();
|
||||||
|
|
||||||
// Sync-agnostischer Hook auf LiteDbContext (siehe LiteDbContext.OnChange) wird erst hier,
|
// Sync-agnostischer Hook auf LiteDbContext (siehe LiteDbContext.OnChange) wird erst hier,
|
||||||
// außerhalb der Repository-Registrierung, mit der tatsächlichen Sync-Logik verbunden.
|
// außerhalb der Repository-Registrierung, mit der tatsächlichen Sync-Logik verbunden.
|
||||||
if (!string.IsNullOrEmpty(serverUrl))
|
if (!string.IsNullOrEmpty(serverUrl))
|
||||||
provider.GetRequiredService<LiteDbContext>().OnChange =
|
{
|
||||||
provider.GetRequiredService<SyncEventPublisher>().Publish;
|
var context = provider.GetRequiredService<LiteDbContext>();
|
||||||
|
var publisher = provider.GetRequiredService<SyncEventPublisher>();
|
||||||
|
context.OnChange = publisher.Publish;
|
||||||
|
publisher.BackfillCompetencyCatalog(context);
|
||||||
|
}
|
||||||
|
|
||||||
return provider;
|
return provider;
|
||||||
}
|
}
|
||||||
|
|||||||
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;
|
||||||
|
}
|
||||||
@@ -10,6 +10,7 @@
|
|||||||
<ProjectReference Include="..\LehrerApp.Data\LehrerApp.Data.csproj" />
|
<ProjectReference Include="..\LehrerApp.Data\LehrerApp.Data.csproj" />
|
||||||
<ProjectReference Include="..\LehrerApp.Sync\LehrerApp.Sync.csproj" />
|
<ProjectReference Include="..\LehrerApp.Sync\LehrerApp.Sync.csproj" />
|
||||||
<ProjectReference Include="..\LehrerApp.WebUntis\LehrerApp.WebUntis.csproj" />
|
<ProjectReference Include="..\LehrerApp.WebUntis\LehrerApp.WebUntis.csproj" />
|
||||||
|
<ProjectReference Include="..\LehrerApp.Templating\LehrerApp.Templating.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Avalonia" />
|
<PackageReference Include="Avalonia" />
|
||||||
@@ -20,6 +21,7 @@
|
|||||||
<PackageReference Include="CommunityToolkit.Mvvm" />
|
<PackageReference Include="CommunityToolkit.Mvvm" />
|
||||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
|
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
|
||||||
<PackageReference Include="QuestPDF" />
|
<PackageReference Include="QuestPDF" />
|
||||||
|
<PackageReference Include="ModelContextProtocol.Core" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<AvaloniaResource Include="Assets\**" />
|
<AvaloniaResource Include="Assets\**" />
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using Avalonia;
|
using Avalonia;
|
||||||
|
using LehrerApp.Core.Mcp;
|
||||||
using LehrerApp.Desktop.Services;
|
using LehrerApp.Desktop.Services;
|
||||||
|
|
||||||
namespace LehrerApp.Desktop;
|
namespace LehrerApp.Desktop;
|
||||||
@@ -8,6 +9,10 @@ class Program
|
|||||||
[STAThread]
|
[STAThread]
|
||||||
public static void Main(string[] args)
|
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();
|
var logger = AppBootstrapper.EnsureLogger();
|
||||||
GlobalExceptionHandler.Install(logger);
|
GlobalExceptionHandler.Install(logger);
|
||||||
|
|
||||||
|
|||||||
Loaded 100 of 375 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user